<!-- https://charter.gedw99.workers.dev/docs/ -->

# charter

Go apps on Cloudflare Workers, one way: pages, an API from a contract, a live feed behind both, languages and search engines, in one Worker.

## What charter is

A Go library and one command. It drives the tools that own each job and adds what they lack:

| Job | Tool |
|---|---|
| The Worker: run it, ship it, its bindings | [wrangler](https://developers.cloudflare.com/workers/wrangler/) |
| Go on Workers | [workers-go](https://github.com/syumai/workers-go) |
| Components and the dev loop | [gsx](https://gsxhq.github.io) and [gsxui](https://ui.gsxhq.dev) |
| Pages and their routes | [structpages](https://jackielii.github.io/structpages/) |
| The browser's files | [Vite](https://vite.dev) |
| SDKs | [Fern](https://buildwithfern.com) |

A charter app runs on Cloudflare and nowhere else. Locally that is `wrangler dev`, the same runtime; remotely it is Cloudflare.

## See it running

[The example](https://charter-example.ubuntusoftware.net) is one app that uses all of charter: its notes are the live feed, people sign in with a passkey and have roles, and each thing Cloudflare gives a Worker does one job in it, on a page of its own. Its source is [`example/`](https://github.com/joeblew999/charter/tree/main/example) in charter's repository, and it is what `charter create` copies.

This site is a charter app too: [`site/`](https://github.com/joeblew999/charter/tree/main/site), a front page and these docs, which are Markdown files in its `docs/` folder. The pages that show them are charter's own, the same ones [your app's docs](11-docs.md) get.

## Where to go

The docs follow what a developer does, in order: start an app, write it beside `charter dev`, prove it with `charter check` and `charter test`, ship it with `charter deploy` and watch it with `charter run`. Each page opens with the commands that matter for it, what is checked before the app runs, and what is not.

**Start**

- [Getting started](01-getting-started.md): a new app in three commands.
- [The commands, and what each one proves](02-commands.md): the whole day, command by command. Read this one first.
- [An app's layout](03-layout.md): what goes where, and what charter finds by itself.

**Write**

- [Pages](04-pages.md), [the API](05-api.md), [the live feed](06-live.md), [the database](07-database.md).
- [Signing in, and who may do what](14-sign-in.md): one caller and one rule for pages and API; passkeys.
- [Languages and search engines](08-languages.md).
- [Screens and themes](13-screens-and-themes.md): what charter gives every app's interface, in the app's own look.
- [Docs](11-docs.md): your app's own, from Markdown and from the app itself.

**Prove**

- [Tests](09-tests.md): what to test, what not to, and how.

**Ship and watch**

- [Deploying](10-deploy.md), [the admin screen](15-admin.md), [watching a deployed Worker](16-watching.md).

**Later**

- [Upgrading](17-upgrading.md): what each release changed in how an app is written, what to write instead, and what tells you.

**With an agent**

- [For your coding agent](12-agents.md): the Claude Code plugins, and what a language model reads.

## What an app made with charter looks like

These pages explain charter. For what an app has, look at the example, whose reference pages nobody wrote: charter writes them from the app itself.

- [Its API](https://charter-example.ubuntusoftware.net/docs/reference-api), from its contract.
- [Its database](https://charter-example.ubuntusoftware.net/docs/reference-database), from its schema and queries.
- [What its Worker is bound to](https://charter-example.ubuntusoftware.net/docs/reference-bindings), from `wrangler.jsonc`.

<!-- https://charter.gedw99.workers.dev/docs/getting-started -->

# Getting started

You need [mise](https://mise.jdx.dev), once. It brings everything else, at the versions each app pins.

```sh
brew install mise      # once. Linux: curl https://mise.run | sh   Windows: winget install jdx.mise
mise exec go@latest -- go run github.com/joeblew999/charter/cmd/charter@latest create my-app
cd my-app
go tool charter dev
```

Put `mise activate` in your shell's profile, once ([mise's guide](https://mise.jdx.dev/getting-started.html)): then in an app's folder `go` and `node` are the app's.

`create` copies [the example](https://github.com/joeblew999/charter/tree/main/example) under your name, gives it the tools charter is built with (its own `mise.toml`), installs what it pins and writes its specs.

## Working on it

`dev` runs the app on the real runtime: workers-go on wrangler dev, with the bindings of `wrangler.jsonc`. The first time, it makes the local database and fills it with the app's [seed](07-database.md). Leave it running and run everything else beside it.

| You save | What happens | On the page after about |
|---|---|---|
| A `.gsx` or `.go` file | gsx regenerates, the Wasm is built, the running Worker takes it | 1.5 s |
| A catalog (`locales/*.toml`) | the messages are compiled and handed to the running Worker: no Wasm is built | 1.3 s |
| A page of the docs (`docs/*.md`) | the same: the pages are data beside the Wasm | 1.3 s |
| `db/schema.sql` | the local database follows, its migration and the queries' Go are written | 2 s |
| `wrangler.jsonc` | wrangler reloads the Worker | 0.6 s |
| A file of `web/`, CSS | Vite replaces it in the open page | at once |

The Worker is started once and never restarted: each build is handed to it. A mistake, in any of these files, shows in the browser in gsx's overlay, and the last page that worked stays up. Cmd-D (Ctrl-D) opens gsx's dev panel, with the Worker's log.

`go tool charter env` says where the loop is running and where its log is, for a second terminal or a coding agent.

`go tool charter install` puts gsx's language server where your editor's gsx extension finds it. The app's `.vscode/` recommends the extension and formats a gsx file when it is saved.

## Before a push

```sh
go tool charter check
go tool charter test
```

`check` says everything that can be said without running the app: formatting, go vet and structpages' linter (for the machine and for the Worker's build), the API's contract, the database's schema, the languages, and charter's screens. `check --fix` writes what it can. `check --json` is the same as one JSON document, each part with what it said, for a script or a coding agent. `test` runs the Worker on wrangler dev and asks it: the pages in a real browser, the API through its own SDK, and the search-engine audit.

## Shipping it

```sh
go tool charter deploy
go tool charter test --deployed
```

The first deploy makes the database, the KV namespace, the bucket and the queue that `wrangler.jsonc` names. The same tests then ask the deployed Worker.

## Tools

| For | Tool | Pinned by | Brought by |
|---|---|---|---|
| Everything below | mise | | you, once |
| Building | Go | `mise.toml` | mise |
| Vite and wrangler | Node | `mise.toml` | mise |
| Secrets | fnox | `mise.toml` | mise |
| Vite, wrangler, gsx's plugin | npm packages | `package-lock.json` | `charter install` |
| Containers | Kiri | | charter, the first time `charter pack` generates SDKs |
| Skills for your coding agent | Claude Code plugins for charter, gsx, gsxui and structpages | | `charter install` |

`mise.toml` is the app's, and so is `mise.lock`, which says what each download must be: commit both. Every machine and CI then build with the same Go and the same Node.

```toml
[tools]
go = "1.27.4"
node = "26.13.1"
"github:jdx/fnox" = "1.50.0"
```

`go tool charter check` holds the app to it:

- **What runs is what is pinned.** A shell whose PATH mise has not set for this folder runs another Go or Node, and what it builds is not what CI builds: check fails and says what runs and what is pinned. An interactive shell with `mise activate` follows the folder by itself. A shell that does not run its hook (an editor's task, an agent's) gets it with `eval "$(mise hook-env)"`.
- **At least what charter was tested with.** An app pins no less than charter's own `mise.toml`. After `go tool charter upgrade`, `check --fix` raises the app's pins and installs them; it never lowers one. What a release changed in how an app is written is on [the upgrading page](17-upgrading.md).

go.mod's `go` line is something else: the oldest Go the module may be built with. Leave it where it is until you need something newer.

In CI, [mise's action](https://github.com/jdx/mise-action) installs the tools from `mise.lock` (charter's own workflows use it through `.github/actions/tools`). [Renovate](https://docs.renovatebot.com/modules/manager/mise/) reads `mise.toml` and `mise.lock` and keeps them current; Dependabot does not read them.

The first command that talks to Cloudflare says, in three steps, how to put your token and account id into fnox, once. `go tool charter env` says whether they are there.

## Every command

The commands are [Vite+](https://viteplus.dev/guide/)'s verbs. [The commands, and what each one proves](02-commands.md) goes through them in the order you meet them: what each does, what it checks of your code, and what it leaves for the next one. `go tool charter` lists them, and `go tool charter run` lists the tasks that are no verb: `intl:translate`, `seo:audit`, `db:status`, `ui:list` and the rest.

<!-- https://charter.gedw99.workers.dev/docs/commands -->

# The commands, and what each one proves

You build a charter app by running a handful of commands while you, or your coding agent, add code. This page goes through them in the order you meet them, and says for each one what it does and what it proves about your code.

That second part is the reason for the stack. Each tool in it was picked because it lets a mistake be found by a machine before a reader finds it: gsx turns templates into Go, structpages turns routes into Go types, sqlc checks SQL against the schema, Huma writes the API's spec from Go types, Fern writes clients from that spec. charter's job is to run them at the right moment so you never have to remember to.

Not everything is checked by a compiler. Where it is not, this page says so, and says what catches the mistake instead.

## What is checked, and when you find out

| What you write | Written once, in | Who checks it | You find a mistake |
|---|---|---|---|
| A page or a component | a `.gsx` file | gsx writes Go from it; the Go compiler checks every value, prop and call | on save, under `dev` |
| A link, an element's id, a swap's target | the page tree (Go structs) | structpages: `url`, `id`, `target` take a page's type, never a string; structpages-lint checks each against the tree | on save for a type that is gone; in `check` for the rest |
| A table | `db/schema.sql` | charter writes the migration from it | on save, under `dev` |
| A statement on the database | `db/queries.sql` | sqlc checks its columns and types against the schema; charter writes it as a Go function | on save, under `dev` |
| Who may do what | a scope, declared once as a Go value (`var Write = charter.NewScope("write")`) | the compiler: a page's `Needs`, an operation's `Security` and `caller.May` take the value, never a word | on save, under `dev` |
| A binding, a variable, a secret's name | `wrangler.jsonc` (a secret's name: `.dev.vars.example`, `fnox.toml`) | charter writes each as a Go value of its kind (`env.DB`, `env.KV`, `env.APP_NAME`); the compiler refuses one that is not declared, or of another kind | on save, under `dev` |
| The API | Go types (`api/contract.go`) | Huma writes the OpenAPI spec from the types; `check` compares it with the committed one | in `check` |
| A client of the API, in any language | nothing: it is generated | Fern writes it from the spec; it is proven by calling the Worker | in `test` and `pack --prove` |
| Text, in every language | `locales/*.toml` | charter writes each message as a Go name, so a page that uses one that is gone does not compile | on save; `check` for a language that is incomplete |
| A live feed | `live.Feed[Note]` | the Go compiler: a feed is of one type, for pages, API and SDK | on save |

The same holds for what Cloudflare gives the Worker. Take a bucket out of `wrangler.jsonc` and every line that used it stops compiling, because `env.BUCKET` is gone. Hand a KV namespace to something that takes a database and it does not compile either.

So one change, a column renamed in `db/schema.sql`, is followed through by machines: the migration is written, every query that used the column fails, the Go that used the row no longer compiles, the API's spec changes and `check` says the committed one is stale, and the generated clients change with it.

## What no compiler checks

These are strings or behaviour, and a wrong one compiles. Each is found by `charter test`, which runs the app on a real Worker, and not before.

| What | Why it is not checked | What finds a mistake |
|---|---|---|
| That a binding is there on the deployed Worker, and a secret has a value | The name is checked; what Cloudflare has under it is not Go's to know | `deploy` makes what `wrangler.jsonc` names; `charter run resources` and `charter run secrets` say what the Worker has; `test --deployed` |
| That a role grants what you meant it to | A scope is checked; whether a moderator should have it is your decision | `test`, signed in as each role |
| What a page's `Props` asks for | structpages hands it over by its type when the page is asked for | `test`: the page answers with an error |
| A link in a page of the docs, or in any page's text | It is text. A link in a template is from the page tree and checked by `check`; one written in Markdown is not | `test`: the audit follows every link to the site itself and fails on one that leads nowhere |
| An htmx attribute written by hand: `hx-swap="innerMorph"` | It is text for htmx. What charter gives for the hard cases (`live.Follows()`, `app.Body()`) is Go | `test`, in a real browser |
| JavaScript: `web/`, and the glue that runs Go | charter has no TypeScript. It is kept small and free of logic | `test`, in a real browser and on the Worker |
| Go calling Cloudflare inside charter's `cloud` package | Go on Workers calls JavaScript by name | charter's own tests, on a Worker |
| Three statements of the admin screen | They ask a database what tables it has, which is no table of a schema | charter's own tests |

If you can express something as a Go type or a query, do: it moves from this table to the one above.

## `create`

```sh
mise exec go@latest -- go run github.com/joeblew999/charter/cmd/charter@latest create my-app
```

Copies [the example](https://github.com/joeblew999/charter/tree/main/example), the one app that uses all of charter, under your name. It pins the tools in the app's own `mise.toml`, installs them and writes the specs.

**What it proves:** nothing yet, but what it gives you passes `check` and `test` as it stands. You start from an app in which every layer above is already wired, and change it.

## `dev`

```sh
go tool charter dev
```

The loop you work in. It runs the app on the real runtime (workers-go on `wrangler dev`, with the bindings of `wrangler.jsonc`) and stays running; every other command works beside it.

Each save runs the generator that owns the file, then the Go compiler:

| You save | What is written for you | What is then checked |
|---|---|---|
| A `.gsx` file | its Go | the compiler: every value and prop in the template |
| A `.go` file | | the compiler |
| `db/schema.sql` | the migration, and the local database follows | every query, again, against the new schema |
| `db/queries.sql` | `db/queries.gen.go`: a function and a row type for each query | sqlc: columns and types; then the compiler, on every caller |
| `locales/*.toml` | the messages as Go names | the compiler, on every page that uses one |
| The API's spec, `db/*.sql`, `wrangler.jsonc` | the docs' pages of the API, the database and what the Worker is bound to ([what charter writes](11-docs.md#what-you-write-and-what-charter-writes)) | nothing to check: they are read from the source |
| `wrangler.jsonc`, `.dev.vars.example`, `fnox.toml` | `env/env.built.go`: each binding, variable and secret's name as a typed value | the compiler, on every line that uses one |

A mistake shows in the browser in gsx's overlay within a second or two, and the last page that worked stays up.

**What it proves:** that the app compiles, with its templates, queries and messages. That is most type mistakes, at the moment you make them.

**What it does not:** it runs no linter and no tests, and it does not compare the API's spec. A link to a page that was removed can still be there. That is `check`.

## `add`

```sh
go tool charter add screen:sign-in
go tool charter add ui:dialog
go tool charter add locale:de
go tool charter add d1:DB
```

Brings something more into the app: a screen of charter's, a gsxui component, a language, a Cloudflare resource with its binding, a Go module or an npm package.

**What it proves:** what it adds arrives in the checked form. A screen is a `.gsx` file in your app, built from your own components, so it is compiled as your pages are. `screen:sign-in` writes its tables into your `db/schema.sql`, and from then on `check` holds your schema to the statements charter runs on them. `d1:DB` writes the binding into `wrangler.jsonc`, and with that `env.DB` exists for your Go to use.

## `check`

```sh
go tool charter check          # says
go tool charter check --fix    # writes what can be written
```

Everything that can be said without running the app. It starts nothing, so it is safe beside `dev`. Run it before a push; CI runs it too.

| Part | What it checks |
|---|---|
| `tools` | Go, Node and fnox are the versions `mise.toml` pins, so what you build is what CI builds |
| `generate` | the messages, the components' Go and the browser's files are written again, so everything after reads what is true now |
| `fmt` | Go and gsx files are formatted |
| `lint` | `go vet`, twice: for your machine and for the Worker's build. Then structpages-lint: every link, id and target against the page tree, and any internal address written as a string |
| `statements` | no statement on the database is written in Go: each is a query in `db/queries.sql`, checked by sqlc ([the database](07-database.md#every-statement-is-checked)). And your schema still has the sign-in screen's tables as charter uses them |
| `bindings` | no binding, variable or secret is named as text (`kv.NewNamespace("KV")`, `cloudflare.Getenv("X")`): each is its value in `env`, which only exists for what is declared |
| `scopes` | a scope is made only where it is declared, as a package's variable: never from a word where it is used |
| `contract` | the committed OpenAPI and AsyncAPI specs and the queries' Go are what the code gives now, and each rate limit the contract declares is bound |
| `languages` | every language is complete, plural forms are right, no message is unused |
| `screens` | charter's screens that you have not changed are charter's current ones |

**What it proves:** the whole first table on this page, for the whole app at once, and that nothing generated is stale. `dev` checks what you touched; `check` checks everything, including what a change somewhere else broke.

**What it does not:** it never runs your code. Everything in "What no compiler checks" is still open after a green `check`.

`check --json` gives the same as one JSON document, each part with what it said, for a script or a coding agent.

## `test`

```sh
go tool charter test
go tool charter test --deployed
```

Runs `go test` for plain logic, then starts the Worker on `wrangler dev` with a new database filled by [the seed](07-database.md#seeding), and tests it from outside: the pages in a real browser, the API through its own generated SDK, and the site as a search engine reads it, which includes following every link to the site itself.

**What it proves:** what types cannot. That the bindings answer, that a signed-in member may do what a member may and no more, that a page asks for what it is given, that a list updates in a second tab, that the JavaScript and Go meet. And it proves the generated clients against a running Worker, not only that they compile.

The tests use the types too: a test names a page by its type and an element by its id from the tree, never by an address or a selector, so a renamed page fails the test at compile time and not by timing out.

It also fails when a Go runtime of the Worker ended itself while the tests ran (Go's own `fatal error:`). The Worker starts another and every request is still answered, so nothing else would say. What Cloudflare refuses while a Worker starts, a local Worker allows: that shows only in `test --deployed`, which is why you run it after a deploy.

**What it does not:** what only shows at scale or far away: memory under many readers, a first hit on another continent. Those are [`run load` and `run cold`](16-watching.md), before a release.

`--deployed` runs the same tests against the deployed Worker, and leaves it as it found it.

## `deploy`

```sh
go tool charter deploy
```

Applies the migrations that have not run, then deploys with wrangler. The first time, it makes the database, the KV namespace, the bucket and the queue that `wrangler.jsonc` names, and writes their ids there.

**What it proves:** that the deployed database has the schema the deployed code was checked against. The migrations are the ones written from `db/schema.sql`, and they are applied before the code that needs them. It stops rather than guess when a bucket or a queue was renamed, since that would make a new, empty one.

**What it does not:** that the app works there. Run `test --deployed` after it. A deploy does not wait on tests or on health; it says how the Worker did in the day before.

## `pack`

```sh
go tool charter pack --prove
```

What others consume: SDKs written by Fern from the API's spec.

**What it proves:** that a client in each language, written from the same contract the Worker serves, calls the running Worker and gets what the types say. The spec comes from your Go types, so a client is typed all the way from your table: `db/schema.sql` gives the row, the row is what the API serves, the spec says so, and the SDK's type is that.

## `run`

```sh
go tool charter run            # lists the tasks
go tool charter run db:seed
go tool charter run health
```

Everything that is no verb: tasks for languages (`intl:`), search engines (`seo:`), the database (`db:`), components (`ui:`), people, secrets, and watching a deployed Worker.

**What they prove** is about the running system, which no type describes: [`health`](16-watching.md) says how requests ended on Cloudflare, `load` what happens under many readers, `cold` what a first reader waits. They take seconds or minutes, so none is part of `check`, `test` or `deploy`.

## The rest

| Command | For |
|---|---|
| `install` | everything the app pins, and gsx's language server for your editor |
| `fmt`, `lint` | the parts of `check`, alone |
| `build`, `preview` | what `dev` and `deploy` build, by hand |
| `exec` | one of the app's tools as it pins it: `charter exec wrangler …` |
| `update`, `outdated`, `upgrade` | the pins, and charter itself |
| `staged` | `check` for what is staged, as a pre-commit hook |
| `env` | what this machine has of what an app needs, and where `dev` is running |

`go tool charter <command> -h` says a command's flags.

<!-- https://charter.gedw99.workers.dev/docs/layout -->

# An app's layout

charter finds everything by where it is. There is nothing to configure for any of this.

```
pages/         the page tree and its components
pages/screens/ charter's screens: the docs' pages, the languages, the theme switch
api/           contract.go: the API
db/            schema.sql, queries.sql; the migrations charter writes from them
env/           what the Worker is bound to, as Go: written by charter from wrangler.jsonc, never by hand
seed.go        what a new database starts with, and what the tests know is there
fnox.toml      the deployed Worker's secrets: their names and who keeps them, never a value
docs/          the app's docs, as Markdown
locales/       <language>.toml: the languages are the files here
web/  public/  what the browser loads
ui/            gsxui's components
test/          tests of the pages and of the API
sdk/go/        the app's own Go client
wrangler.jsonc the Worker and its bindings, without ids
charter.toml   only url, and what Fern should generate
main.go
```

## What the Worker is bound to

A binding is declared once, in `wrangler.jsonc`. charter writes each as a Go value in the app's `env` package, under the name it has there, with the type of its kind:

| Declared in `wrangler.jsonc` as | In Go | What you do with it |
|---|---|---|
| `d1_databases`: `DB` | `env.DB` | `env.DB.Open()`: the database, for [the queries](07-database.md#queries) |
| `kv_namespaces`: `KV` | `env.KV` | `env.KV.Open()`: workers-go's `*kv.Namespace` |
| `r2_buckets`: `BUCKET` | `env.BUCKET` | `env.BUCKET.Open()`: workers-go's `*r2.Bucket` |
| `queues.producers`: `QUEUE` | `env.QUEUE` | `env.QUEUE.Open()`: workers-go's `*queues.Producer` |
| `durable_objects.bindings`: `HUB` | `env.HUB` | `live.Feed[Note]{Binding: env.HUB, …}` |
| `ratelimits`: `WRITE_LIMIT` | `env.WRITE_LIMIT` | `env.WRITE_LIMIT.Allow(key)`; `api.Limit{Binding: env.WRITE_LIMIT}`. It carries the calls and the seconds `wrangler.jsonc` says, so they are said once |
| `send_email`: `MAIL` | `env.MAIL` | `env.MAIL.Send(from, to, raw)` |
| `vars`: `APP_NAME` | `env.APP_NAME` | `env.APP_NAME.Value()` |
| a secret named in `.dev.vars.example` or `fnox.toml` | `env.ADMIN_TOKEN` | `env.ADMIN_TOKEN.Value()`; `api.Token{Secret: env.ADMIN_TOKEN}` |

Why it is this way: a name written as text (`kv.NewNamespace("KV")`) compiles whatever it says, and fails on a Worker when nothing is bound there or something of another kind is. A value cannot be wrong like that:

- **What is not declared does not exist.** Take a bucket out of `wrangler.jsonc` and every line that used `env.BUCKET` stops compiling.
- **A kind is a type.** `api.D1Accounts(env.KV)` does not compile: it takes a database.
- **No value can be written by hand.** `api.D1Accounts("DB")` does not compile either.

The file is `env/env.built.go`. `dev` writes it again when `wrangler.jsonc`, `.dev.vars.example` or `fnox.toml` is saved, and `build`, `check` and `test` write it too; it is not committed. `charter check` fails an app that names a binding the old way, with the file and the line.

A binding's name must be one Go can have, starting with a capital letter (`DB`, `WRITE_LIMIT`), since it is its name in Go too. What workers-go gives that has no name of the Worker's (the Cache API, `fetch`, Cron Triggers) is used as workers-go's docs say.

What this does not tell you: whether the deployed Worker has the thing. `charter deploy` makes what `wrangler.jsonc` names; `charter run resources` and `charter run secrets` say what is there.

## main.go

```go file=../example/main.go#main
func main() {
	// What the Worker does that is no request: a queue's consumer, a Cron Trigger's task, email (package built).
	built.Background()
	(&app.App{
		Name:  "charter-example",
		Dist:  dist,
		Pages: pages.Mount,
		// The app's own docs (docs/*.md), shown by charter's docs pages, which the tree mounts at /docs.
		Docs: &app.Docs{
			Name:    "charter-example",
			Summary: "charter's example: notes that are live on every open page, an API from a contract, and a card for everything Cloudflare gives a Worker.",
			Pages:   docs.Pages,
			Repo:    "https://github.com/joeblew999/charter",
			Dir:     "example",
			Agents:  "A coding agent working on this app uses the Claude Code plugins of the marketplace joeblew999/charter: charter, gsx, gsxui and structpages. The app's .claude/settings.json enables them.",
		},
		// Who may do what, for the pages as for the API (api.Auth): a page or a group says what it needs with a Needs
		// method, and whoever is not signed in is sent to the sign-in screen.
		Auth:   api.Auth,
		SignIn: screens.SignInPage{},
		// The app's own lines on the admin screen's overview: asked when that page is.
		Facts: []app.Fact{
			{Label: locales.FactsNotes, Value: func(ctx context.Context) (any, error) {
				report, err := api.Report(ctx)
				return report.Notes, err
			}},
			{Label: locales.FactsWriters, Value: func(ctx context.Context) (any, error) {
				report, err := api.Report(ctx)
				return report.Authors, err
			}},
		},
		Args: []any{api.Auth},
		// What a page asks for by type, made from the request: the notes' store (D1), and who is asking.
		RequestArgs: []any{api.OpenStore, api.Auth.Caller},
		API:         api.Handler(api.Env{Var: charter.Var}),
	}).Run()
}
```

That one value is the pages, the API, the docs, Vite's files, a URL per language, `robots.txt`, the sitemap and `/llms.txt`.

## What is generated

Two kinds, told apart by name.

| Kind | Files | In git |
|---|---|---|
| Built from your sources each time | `*.x.go`, `*.built.go`, `.charter/`, `build/`, `dist/` | no |
| Read from the repository by something | `*.gen.go`, `db/migrations/`, `fern/`, `sdk/go/` | yes, and `check` holds each to its source |

`dev`, `build` and `check` write the first kind, so a fresh clone needs only `go tool charter check`. `check --fix` writes the second.

## What is never in git

`.dev.vars`, the local secrets wrangler dev reads. charter makes it from `.dev.vars.example`.

<!-- https://charter.gedw99.workers.dev/docs/pages -->

# Pages

Pages are a [structpages](https://jackielii.github.io/structpages/) tree, rendered with [gsx](https://gsxhq.github.io) and built from [gsxui](https://ui.gsxhq.dev) components. The tree is the one source of routes, links, element ids and the sitemap.

## With the commands

| When | Command | What it does for your pages |
|---|---|---|
| You save a `.gsx` or `.go` file | `dev`, running | gsx writes the template's Go, the compiler checks it, and the page in your browser is the new one in about 1.5 s |
| You need a component | `add ui:dialog` | gsxui's component, copied into `ui/`, where it is yours |
| Before a push | `check` | structpages-lint holds every link, id and target to the tree; `go vet` runs for your machine and for the Worker's build |
| Before a push | `test` | the pages in a real browser on a real Worker, and every link followed |

**Checked before the app runs:** every value a template shows and every prop it passes (a template is Go); every link, element id and swap target (each takes a page's type, never a string); what a page needs of its caller (a scope is a value); every text it shows (a message is a Go name).

**Not checked until it runs:** that a page's `Props` is handed what it asks for (structpages matches it by type when the page is asked for); an htmx attribute written by hand; anything that happens in the browser. `test` is what finds these.

## The tree

Every route is a field, with its route in the field's tag.

```go file=../example/pages/pages.go#Pages
// Pages is the tree.
type Pages struct {
	home  Home         `route:"GET /{$} Home"`
	built Built        `route:"/built Built"`
	docs  screens.Docs `route:"/docs Docs"`
	// gsxui's theme editor, in the app: a reader chooses, and the app has it from then on.
	theme screens.Theme `route:"/theme Theme"`

	// The app's own people: signing in with a passkey, and what is someone's own (charter's sign-in screen).
	signIn  screens.SignIn  `route:"/sign-in SignIn"`
	account screens.Account `route:"/account Account"`

	// What an admin sees of the system (charter's admin screen): the app at a glance, its bindings, its database.
	admin screens.Admin `route:"/admin Admin"`

	// The time zone and clock dialog's form, and where it is sent.
	preferences screens.Preferences `route:"/preferences Preferences"`

	// What the pages call: routes, not pages.
	post   PostNote   `route:"POST /notes PostNote"`
	remove RemoveNote `route:"POST /notes/{note}/remove RemoveNote"`
}
```

## A page declares what it needs

A page is a type with a `Page` component, and `Props` for its data. `Props` names what it needs as parameters, and structpages hands each over by its type.

```go file=../example/pages/pages.go#Home.Props
// Props loads what the request wants, as structpages has it. A row's button asks for that row alone (its target is
// Home's Item, with the note's id as its key): then one note is read, and structpages renders Item with it. The
// list asks for itself when its stream says the notes changed (its target is Home's List): then the newest notes
// are read, and structpages renders List with them, for this reader. Anything else is the page. Each component
// takes its share of the results by their types.
func (p Home) Props(r *http.Request, store api.Store, caller charter.Caller, target structpages.RenderTarget) (HomeProps, []api.Note, charter.Caller, api.Note, Open, Removable, Kept, error) {
	if target.Is(p.Item) {
		id, err := strconv.ParseInt(structpages.KeyOf(target), 10, 64)
		if err != nil {
			return HomeProps{}, nil, caller, api.Note{}, false, false, false, app.NotFound("no such note")
		}
		note, err := store.Get(r.Context(), id)
		if err != nil {
			return HomeProps{}, nil, caller, api.Note{}, false, false, false, app.NotFound("no such note")
		}
		return HomeProps{}, nil, caller, note, r.URL.Query().Get("open") != "", Removable(api.MayRemove(caller, note)), false, nil
	}
	notes, err := store.Before(r.Context(), math.MaxInt64, shown)
	if err != nil {
		return HomeProps{}, nil, caller, api.Note{}, false, false, false, err
	}
	if target.Is(p.List) {
		return HomeProps{}, notes, caller, api.Note{}, false, false, false, nil
	}
	props := HomeProps{Notes: notes, MayWrite: caller.May(PostNote{}.Needs()...), Caller: caller}
	// One read of KV, for every reader: what it is for.
	if props.Notice, err = built.NoticeNow(r.Context()); err != nil {
		return HomeProps{}, nil, caller, api.Note{}, false, false, false, err
	}
	return props, notes, caller, api.Note{}, false, false, false, nil
}
```

The store comes from `main.go`: `RequestArgs: []any{api.OpenStore}`, a function from the request to the value. No page opens a database or reads a binding itself, so a test hands a page a store of its own. The target is what the request wants: the whole page, or one part of it.

## A region that changes by itself

A part of a page that htmx replaces is a component of that page. Its id and its target come from the tree, so the three places that must agree cannot drift apart.

```gsx file=../example/pages/home.gsx#Home.Form
// Form is the form, a region of the page that changes by itself: PostNote answers with it, and htmx puts it in place
// of the one sent (its target is this component, by the tree), empty, or with what was typed, marked as refused.
component (p Home) Form(body string, refused bool) {
	<form
		id={Home.Form |> id}
		class="flex flex-wrap gap-2"
		hx-post={PostNote{} |> url}
		hx-target={Home.Form |> target}
		hx-swap="outerHTML"
	>
		<ui.Input
			name="body"
			class="flex-1"
			value={body}
			maxlength={strconv.Itoa(maxBody)}
			required
			autofocus
			autocomplete="off"
			dir="auto"
			placeholder={locales.HomePlaceholder}
			aria-label={locales.HomeLabel}
			{ if refused {
				aria-invalid="true"
			} }
		/>
		<ui.Button type="submit">{ locales.HomePost }</ui.Button>
	</form>
}
```

One of many (a row, a card) has a key: `id={Home.Item |> key(id)}`, and its own button targets `{Home.Item |> keytarget(id)}`. `Props` then asks whether that row is what is wanted, reads which from `structpages.KeyOf`, and loads that note alone, as above.

## The page being shown

`structpages.Within(ctx, Bindings{})` says whether the page being shown is that page or one under it: how the example's header marks its links.

## A fragment opened as a page

A route with `Props` and no `Page` is a fragment: markup for part of a page, such as a dialog's form. Its address opened in a browser would be that markup alone, so charter sends such a request to the page the fragment is part of (structpages' own convention), before its `Props` runs. Only an htmx request for part of a page gets the fragment.

## What a page calls

A type with `ServeHTTP` that returns an error. It answers with a component, and never writes an error or a redirect itself.

```go file=../example/pages/pages.go#PostNote.ServeHTTP
func (PostNote) ServeHTTP(w http.ResponseWriter, r *http.Request, store api.Store, caller charter.Caller) error {
	body := strings.TrimSpace(r.PostFormValue("body"))
	if body == "" || len(body) > maxBody || strings.Contains(body, api.END) {
		// htmx 4 swaps a 422 too: the form comes back with what was typed.
		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		w.WriteHeader(http.StatusUnprocessableEntity)
		return structpages.RenderComponent(Home{}.Form(body, true))
	}
	if _, err := api.Post(r.Context(), store, caller, body); err != nil {
		return err
	}
	return structpages.RenderComponent(Home{}.Form("", false))
}
```

| To say | Return |
|---|---|
| It is not there | `app.NotFound("no such note")` |
| Another status | `app.Status(http.StatusForbidden, "…")` |
| Go somewhere else | `app.Redirect{To: url}`: `HX-Location` for htmx, a 303 otherwise |
| It broke | the error: a 500, logged, with nothing of it shown |

## Links

A link or a form's target comes from the tree, never from a path written as a string.

```gsx
<ui.Button variant={current(ctx, Built{})} size="sm" href={BuiltIndex{} |> url}>
hx-post={PostNote{} |> url}
hx-post={RemoveNote{} |> url(map[string]any{"note": note.ID})}
```

Those are three lines of the example: a link to a page, a form's target, and one with a value in its address.

`url` is structpages' own `URLFor`. charter mounts the tree once for each language, each told its prefix, so every address it gives is in the reader's language by itself: a page, a form's target, a stream. structpages' linter runs inside `charter check`, for the machine and for the Worker's build, and fails on a link to a page that is not there, a missing parameter, or a path written as a string.

## A link shows the next page with no page load

```gsx
<body data-layout={string(mode)} class={bodyClass} { app.Body()... }>
```

`app.Body()` on the layout's `<body>` is all of it. A link to another page of the app, and a form, then keeps the document: htmx asks for the next page and puts its body in place of this one's (boost). The scripts, the stylesheet and the theme stay; everything in the body is the next page's, as if it had loaded, so nothing a reader opened on one page (a menu, a dialog) is left open over the next. The page's title comes with it, a list that follows a feed opens its stream as it arrives, and Back shows the page that was there. With htmx's preload extension (`web/main.js`: `hx-preload.js`) the request starts when the link is pressed, before the click is done.

What is asked for on a press is asked for before the reader has decided, so a `GET` must change nothing. One that does (a link that declines an offer, or chooses a language) is not boosted.

What stays a page load, and how each says so:

| What | How |
|---|---|
| A page whose script runs as its document loads (the sign-in screens, the theme editor) | Its type has `FullLoad() bool`: a link to it from anywhere is a page load, with nothing on the link |
| A link whose following changes something, or the document itself (another language: `<html lang>` changes) | `hx-boost="false"` on the link, or `hx-boost:inherited="false"` on what holds several (the language list has it) |
| A link whose answer is no page: a download, JSON, a text file | Nothing: charter sends the reader there as a page load |
| A link to another site, one with `download`, one to a place on the same page | Nothing: htmx does not boost them |

## Which pages search engines get

The tree's GET pages without parameters are in the sitemap, in every language. The pages of the docs are too.

## A page that is the same for every reader

A page that shows every reader the same thing says so on its type, and Cloudflare keeps it:

```go
func (DocsIndex) Shared() bool { return true }
```

Cloudflare's [cache for the Worker](https://developers.cloudflare.com/workers/cache/) is asked before the Worker runs. A page it has is answered from the nearest of Cloudflare's places with no Worker started and no Go, so a reader's first hit, which otherwise waits for both, is as quick as any other. It is on in `wrangler.jsonc`:

```jsonc
  "cache": { "enabled": true },
```

charter decides, as each answer goes, whether it may be kept, and only all of this makes it so:

| | |
|---|---|
| The page | Its type says `Shared`, and it answered 200 to a GET for a page. A part of a page is never kept |
| The request | Brought no cookie and no `Authorization`. A reader who has chosen a style or a language, or signed in, is answered by the Worker |
| The answer | Gives no cookie, and read no database |

Everything else the Worker answers says `private`: the API, a page that is not shared, an error, a stream. That matters, since with its cache on Cloudflare keeps an answer that says nothing for two hours.

- **There is one copy of a page for every reader who brings no cookie**, however they ask: a page load, a link followed in the app, a crawler, any browser in any language. Cloudflare keeps a copy for each value of the request headers an answer names (`Vary`), compared as written, so a shared page names only `Cookie` and `Authorization` (a reader with either is answered by the Worker), `HX-Target` (htmx asking for a part of the page is not given the page) and `X-Forwarded-Proto` (a request over http is sent to https).
- **It is not drawn from the browser's languages.** In an app with several, a shared page offers another language only to a reader who has chosen one; every reader has the language list.
- **A deploy starts an empty cache**, so what is kept is never of older code, and that is checked on every deploy. Every answer says the build that drew it (`X-Charter-Build`), a kept one too. `charter deploy` asks for every page of the sitemap, which fills the cache of the data centre the deploy reaches, until each is answered by the build it deployed: a new version takes some seconds to reach every data centre, and until then the one before it answers there, from its own cache. A page still of another build after a minute fails the deploy. `charter test --deployed` asks the same of a kept page.
- **Each of Cloudflare's data centres fills its own cache, so behind it is one copy for all of them.** Where a data centre has no copy, the request reaches the Worker in front ([two Workers](10-deploy.md#two-workers)), which answers from KV, under the build's name: the Go is not loaded. Asked on 2026-11-28 from one place, requests that missed the cache were answered from KV in 68 to 190 ms at the nearest data centre and 139 to 587 ms at the next (the first read of a page in a place is KV's slowest); before, the Go Worker drew each in 1.2 to 1.5 s. Such an answer says `X-Charter-Kept: kv`.
- **A copy is kept a day**, and for a week after that it is still given at once while the Worker draws a new one behind it.
- **A shared page shows nothing it read for the request**: no row of a database, no time in the reader's zone, nothing of who asks. The docs, the theme editor and this site's front page are shared; the example's front page reads its database and is not.
- **It gives no cookie**, so the language of the last page viewed is not remembered from a shared page. A language the reader chose is.
- **A reader with a cookie is answered by the Worker**, as before there was a cache. charter gives a reader none until they choose something (a style, a language, a time zone), sign in, read a page in another language than the first, or read a page that reads the database (its bookmark, for five minutes). A cookie your own script sets for every reader takes every reader out of the cache.

Not checked before the app runs: that a page which says `Shared` really is the same for everyone. `charter test` asks each of charter's own; a test of yours asks yours.

## The head

```gsx
<html { app.HTML(ctx)... }>
	<head>
		<app.Head title={title} description={description}/>
	</head>
```

`app.Head` writes the title and description, the canonical address, every language's alternate, Open Graph, and the scripts Vite built.

Under `charter dev` Vite gives the stylesheet by script, so that a change to it shows without a reload, and a script comes after the page's markup: `app.Head` hides the page until it is styled, as gsxui's own site does, so it is never seen bare. What is built for a deploy links its stylesheet in the head, which a browser waits for by itself.

What Vite built is kept by a browser for good. Each file has its contents in its name (`assets/main-uiJkX3bL.css`), so `charter build` writes the rule for it into the built files' `_headers`: `Cache-Control: public, max-age=31536000, immutable` for `/assets/*`. Cloudflare serves a Worker's static assets to be [asked about on every page](https://developers.cloudflare.com/workers/static-assets/headers/#default-headers) unless told otherwise, and then the font's answer comes after the text is shown in another one: the page is seen to change. An app's own `public/_headers` is kept beside the rule, and one that says what `/assets/*` gets is left as it is.

<!-- https://charter.gedw99.workers.dev/docs/api -->

# The API

The API is written once, as a contract in Go (`api/contract.go`). Its OpenAPI and AsyncAPI documents, its MCP tools and its SDKs come from that.

## With the commands

| When | Command | What it does for your API |
|---|---|---|
| You change `api/contract.go` | `dev`, running | it compiles, and the running Worker serves the operation |
| Before a push | `check --fix` | writes `fern/openapi.json` and `fern/asyncapi.json` from the Go types; `check` fails while the committed ones are behind |
| Before a push | `test` | the API called through its own generated Go SDK, on a real Worker |
| Before a release | `pack --prove` | a client in each language, written by Fern from the spec, proven by calling the Worker |
| Nothing | | the docs' page of the API is written from the spec: [the example's](https://charter-example.ubuntusoftware.net/docs/reference-api) |

**Checked before the app runs:** what an operation takes and answers (Huma writes the spec from the Go types, never the other way); the scopes it needs (values); its limit, whose binding, calls and seconds are `wrangler.jsonc`'s, said once.

**Not checked until it runs:** what a handler does with a request. And nothing checks that a change is safe for clients already out there: the API's row is the table's row, so a column you rename is a field renamed for every client. `check` shows the spec changed; whether that is acceptable is yours to decide.

## An operation

```go
{Method: http.MethodPost, Path: "/api/notes", OperationID: "createNote", Register: func(api huma.API) {
	huma.Register(api, huma.Operation{
		OperationID: "createNote", Method: http.MethodPost, Path: "/api/notes",
		Summary:  "Create a note", Tags: []string{"notes"},
		Security: charter.Needs(Write),
	}, env.create)
}},
```

`charter check --fix` writes `fern/openapi.json` and `fern/asyncapi.json` from the contract; `charter check` fails when they are behind it.

This site has no API of its own. The example's is live: [every operation of it, written from its contract](https://charter-example.ubuntusoftware.net/docs/reference-api), [its OpenAPI document](https://charter-example.ubuntusoftware.net/api/openapi.json), and [its notes](https://charter-example.ubuntusoftware.net/api/notes).

An app's docs get that page without anyone writing it: [what charter writes](11-docs.md#what-you-write-and-what-charter-writes).

## Who may call

Reading is public. Writing needs a scope, which a bearer token, Cloudflare Access or an OpenID Connect issuer gives. An unset secret trusts no one.

## Limits

An operation says how often one caller may call it. The Worker's Rate Limiting binding enforces it, and `charter check` holds `wrangler.jsonc` to the contract.

## SDKs

```sh
go tool charter pack -prove
```

Fern generates a client for each language `charter.toml` names. Each is proved in its own language, and then against the Worker itself: the program in `test/sdk/<language>/` is refused and let through as the contract says ([who may do what](14-sign-in.md)). It all runs in containers, so nothing of Rust or Python is on your machine. The Go client is committed in `sdk/go` (`charter pack -publish`), and this site's own tests use it as the client.

## MCP

Every operation is also an MCP tool, at `/api/mcp`.

<!-- https://charter.gedw99.workers.dev/docs/live -->

# The live feed

A feed is declared once and serves everything that shows it.

```go file=../example/api/handlers.go#Notes
// Notes is the feed of notes, declared once: the table is the log, the Durable Object HUB wakes whoever follows.
// The page's live list, the API's stream and its WebSocket channel are all this.
var Notes = live.Feed[Note]{Binding: env.HUB, Name: "notes", Log: func() (live.Log[Note], error) { return open() }}
```

The log, a D1 table, is the truth. The hub, a Durable Object, only wakes whoever follows. So no item is lost or sent twice, across reconnects and deploys alike.

A change that is no new item is said too, so that every open page shows it:

```go
if err := store.Remove(ctx, id); err != nil {
	return err
}
Notes.Changed(ctx)
```

## With the commands

| When | Command | What it does for a feed |
|---|---|---|
| You declare a feed | `dev`, running | it compiles: a `live.Feed[Note]` is of one type, for the page, the API and the SDK |
| Before a push | `test` | a note written in one browser tab appears in another, and one taken away goes from both |
| Before a release | `run load --deployed` | many readers' streams held open at once, and whether Cloudflare ended any request |

**Checked before the app runs:** the item's type everywhere the feed goes; the hub it wakes (`env.HUB`, a Durable Object namespace: any other kind of binding does not compile).

**Not checked until it runs:** that an item arrives, once, in order, across a reconnect and a deploy. That is the two-tab test and the stream's tests. What many open pages cost in memory shows only on Cloudflare: `run load`.

## Writing

```go file=../example/api/handlers.go#Post
// Post writes a note to the store, as whoever is asking, and wakes every follower: what the API's createNote and
// the page's form both do.
func Post(ctx context.Context, store Store, by charter.Caller, body string) (Note, error) {
	note, err := store.Create(ctx, body, by.Subject, by.Name())
	if err != nil {
		return Note{}, err
	}
	Notes.Publish(ctx, note)
	if OnPost != nil {
		OnPost(ctx, note)
	}
	return note, nil
}
```

## Three ways out, one feed

| For | Call | What it sends |
|---|---|---|
| An open page | `Notes.Stream()` and `live.Follows()` | "what you show has changed": the page asks for that part of itself again, as that reader sees it |
| An SDK client | `Notes.Events(ctx, setHeader, w, positions, seconds, end)` | each item as JSON over server-sent events |
| A WebSocket | `Notes.Lines(ctx, setHeader, w, positions)` | each item as a line of JSON |

Write a note on [the example's home page](https://charter-example.ubuntusoftware.net/) in one tab and it appears in another; take it away and it goes from both. Create one through the SDK and it appears there too.

## A page's stream holds no Go

A Go runtime takes 13 MB or more of a Worker's [128 MB](https://developers.cloudflare.com/workers/platform/limits/#memory) for as long as it serves a request, and a stream is a request that lasts minutes. Served by Go, a handful of open pages took a Worker over its memory, and Cloudflare ended it with every request it was answering (a 503 for each; `exceededMemory` in its analytics).

So a page's stream is the hub's, a small Durable Object in JavaScript, and it says one thing: what you show has changed. The part of the page that shows the feed then asks for itself again, and what comes takes the place of what it had.

```gsx
<div { api.Notes.Stream()... }>
	<ul
		id={Home.List |> id}
		hx-get={Home{} |> url}
		hx-target={Home.List |> target}
		{ live.Follows()... }
	>
		<p.List notes={props.Notes} reader={props.Caller}/>
	</ul>
</div>
```

`Stream` is the stream, on an element around the list. `Follows` is everything that makes the list keep itself current. What is left in the markup is what is the page's own, from the tree as every other id and address is: the list's id, the page it asks for, and itself as the target.

There is no route for it: the list is a component of its page, so the request is for the page with the list as its target, and structpages renders the list alone (`target.Is(p.List)` in the page's `Props`). It is a short, ordinary request: Go renders the rows for that reader, in their language, with the buttons they may use.

Why it is told that something changed, and never what:

- **Added, taken away or altered, it is one thing.** The page shows what the log has, so nothing is shown twice or left behind.
- **Changes that come together end right.** The last request is the one that counts: however many arrive at once, the page ends as the log is.
- **What the reader was doing stays, when the page says so.** What comes is the list as the Worker has it, which knows nothing of what a reader did to a row since: a row they opened would be shut by it. So a row of a list that is asked for again is marked to be kept (`hx-preserve`, which the example's `List` gives each `Item`): htmx leaves the row the page has as it is, and puts in only the rows that are new. A row asked for by itself, by its own button, is not marked: it is the answer.
- **It reads what is newest.** The request says so (the header `X-D1-Newest`), so it is answered by the database's primary: a copy that is behind would show the page as it was before the change it was just told of ([reads near the reader](07-database.md#reads-near-the-reader)).

The stream is on an element of its own, around the list: htmx opens a stream on that element's trigger, and what is replaced is inside it, so the stream stays open across every change.

Nothing is lost when a stream breaks, which every one does when the Worker is deployed: the hub restarts and holds nothing. A page says when it was rendered, and a stream that connects again says when it was last told; the hub answers "changed" at once when something changed since, or when it started since and cannot know.

The API's streams hold no Go either. `Events` (an SDK client's stream) and `Lines` (a WebSocket channel) write what the log has after the position their caller gave, say where they stopped, and are done; the hub writes the rest, as Go would have: an event for each item and the terminator at the end, or a line for each. Your handler gives them the answer's `SetHeader`, which is how they say it:

```go
Notes.Events(hc.Context(), hc.SetHeader, hc.BodyWriter(), []string{in.After, in.LastEventID}, int(in.Seconds), END)
```

Twenty SDK clients watching for a quarter of a minute hold no Go runtime between them.

## Resuming

An API stream's events each have the item's position in the log as their id: an SDK client passes `after`, or its last event's id, and is sent what came after. A page's stream has the time as its id: a browser sends the last one when it connects again, and is told at once if anything changed since. The log is the truth, so nothing in between is lost.

<!-- https://charter.gedw99.workers.dev/docs/database -->

# The database

`db/schema.sql` is the one place a table is written down.

```sql file=../example/db/schema.sql
-- The database, as it is now: the one place a table is written down. charter writes everything else from it: the
-- migrations (db/migrations, for whatever changes here), and with the queries of queries.sql the typed Go
-- (queries.gen.go). A column's comment says what the API shows of it: its row is also what the contract serves.

CREATE TABLE notes (
  id INTEGER PRIMARY KEY AUTOINCREMENT,                 -- example: 42
  body TEXT NOT NULL,                                   -- example: Buy milk
  author_id TEXT NOT NULL DEFAULT '',                   -- example: 4f1c9a0e7b2d4c6f8a1b3c5d7e9f0a1b; doc: Who wrote it: their id, empty for a program with one of the Worker's own tokens
  author TEXT NOT NULL DEFAULT '',                      -- example: Ada; doc: What they call themselves
  created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP    -- example: 2026-10-01 12:00:00
);

-- What happened, as the app records it: a note written (the queue's consumer writes the row, a moment after the
-- note), and once a day how many there were (the Cron Trigger's task). The activity page follows this table live.
CREATE TABLE activity (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  kind TEXT NOT NULL,
  note_id INTEGER NOT NULL DEFAULT 0,
  author TEXT NOT NULL DEFAULT '',
  notes INTEGER NOT NULL DEFAULT 0,
  created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);

-- A file someone attached: where it is in the bucket (R2 keeps the file, this table what is known of it), and the
-- note it goes with, 0 for none.
CREATE TABLE attachments (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  object TEXT NOT NULL,
  name TEXT NOT NULL,
  type TEXT NOT NULL,
  size INTEGER NOT NULL,
  note_id INTEGER NOT NULL DEFAULT 0,
  author_id TEXT NOT NULL,
  author TEXT NOT NULL,
  created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);

-- The app's own users (charter's sign-in screen, package api): who signed up, the passkeys they sign in with, the
-- sessions and tokens they hold (never the token: its SHA-256), and sign-ins that were started.
CREATE TABLE users (
  id TEXT PRIMARY KEY,
  name TEXT NOT NULL,
  role TEXT NOT NULL, -- was: scopes
  created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
  email TEXT
);

CREATE TABLE passkeys (
  id TEXT PRIMARY KEY,
  user_id TEXT NOT NULL REFERENCES users (id),
  credential TEXT NOT NULL,
  created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
  name TEXT NOT NULL DEFAULT '',
  used_at TEXT
);

CREATE TABLE tokens (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  hash TEXT NOT NULL UNIQUE,
  user_id TEXT NOT NULL REFERENCES users (id),
  kind TEXT NOT NULL,
  name TEXT NOT NULL DEFAULT '',
  scopes TEXT NOT NULL,
  expires_at TEXT,
  created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE ceremonies (
  id TEXT PRIMARY KEY,
  data TEXT NOT NULL,
  expires_at TEXT NOT NULL
);
```

What the example's database has, every table, column and statement, is [a page of its docs](https://charter-example.ubuntusoftware.net/docs/reference-database) that charter writes from this file. Your app gets the same.

## With the commands

| When | Command | What it does for your database |
|---|---|---|
| You save `db/schema.sql` | `dev`, running | writes the migration, brings the local database to it keeping its rows, and checks every query again |
| You save `db/queries.sql` | `dev`, running | sqlc checks each statement against the schema; charter writes it as a Go function in `db/queries.gen.go` |
| Before a push | `check` | fails while the schema is ahead of the migrations, where a statement is written in Go, and where the sign-in screen's tables no longer fit |
| Before a push | `check --fix` | writes the migration (`--drop` for one that loses data) |
| You ship | `deploy` | applies the migrations that have not run, before the code that needs them |
| By hand | `run db:status`, `db:seed`, `db:reset`, `db:execute`, `db:export` | the local database, or the deployed one with `--deployed` |
| Nothing | | the docs' page of the database is written from these two files: [the example's](https://charter-example.ubuntusoftware.net/docs/reference-database) |

**Checked before the app runs:** every column a statement names and its type; the arguments and rows of its Go function; the API's row, which is the same type; that the migrations are what the schema says.

**Not checked until it runs:** what a statement means. A `WHERE` on the wrong column compiles, and so does a query that reads every row. What a deployed database holds is not known to any check.

## Changing it

Edit the schema and save. Nobody writes a migration.

| When | What happens |
|---|---|
| `charter dev` is running | the local database gets exactly the difference, and keeps its rows |
| `charter check --fix` | the migration for the change is written to `db/migrations` |
| `charter check` | fails while the schema is ahead of the migrations |
| `charter deploy` | applies it |

A column added at the end becomes `ALTER TABLE … ADD COLUMN`. Anything else about a table makes the table again and copies its rows. A renamed column says what it was:

```sql
role TEXT NOT NULL, -- was: scopes
```

A change that would lose data is refused until you ask for it: `charter check --fix --drop`.

## Queries

`db/queries.sql` holds the queries. charter writes each as a typed Go function in `db/queries.gen.go`.

```sql
-- name: CreateNote :one
INSERT INTO notes (body, author_id, author) VALUES (?, ?, ?) RETURNING *;
```

Select whole rows, and a new column needs no change here.

### Every statement is checked

sqlc works out each query against `db/schema.sql`: a column that is not there, an argument or a result of the wrong type, fails `charter check`, and the Go that calls the function with the wrong types does not compile. So what is checked is every statement, as long as every statement is a query. `charter check` holds an app to that (its part `statements`):

- **No statement is written in Go.** A call that hands the database SQL as text (`cloud.Query`, `cloud.One`, `cloud.Exec`, `cloud.ExecRows`, `cloud.Stmt`, a `cloud.Statement{…}` written out) outside `db/queries.gen.go` fails the check, with the file and the line. Those functions are what the generated code is made of, not something to call.
- **Several statements in one transaction** are `cloud.Batch` of the `…Stmt` function charter writes beside each query that returns no rows:

  ```go
  forget := make([]cloud.Statement, len(gone))
  for i, note := range gone {
  	forget[i] = db.ForgetNoteStmt(note.ID)
  }
  return cloud.Batch(s.db, forget...)
  ```

- **Nothing reaches D1 around charter.** workers-go's `database/sql` driver (`workers-go/cloudflare/d1`) is checked by nothing and is in no request's session, so its reads are the primary's and its writes give no bookmark ([reads near the reader](#reads-near-the-reader)). Importing it fails the check.

charter holds itself to the same. The statements of its sign-in (the tables `users`, `passkeys`, `tokens`, `ceremonies`) are a `queries.sql` of its own, written as Go by the same generator, and a test fails charter if any statement in its library is written in Go. An app owns its copy of those tables, in its own `db/schema.sql`, and may add to them; `charter check` runs charter's statements against the app's schema, so a column of theirs that was dropped, renamed or retyped is said there:

```
✗ statements: db/schema.sql no longer has the tables of the sign-in screen (users, passkeys, tokens, ceremonies) as charter reads and writes them:
  queries.sql:8:30: column "role" does not exist
```

What is not checked this way, and cannot be: the admin screen asks a database what tables it has and how many rows each holds, which is SQLite's own catalogue and no table of a schema; and inside `cloud`, Go calls Cloudflare's D1 by name, which only running on a Worker proves, as the tests do.

## One definition

A column's comment becomes its tag in Go, so the row is also what the API serves.

```go file=../example/api/contract.go#Note
// Note is a note as the API shows it: the table's row, as db/schema.sql has it (db.NotesRow, whose examples are the
// schema's comments). A note is written down once, in the schema.
type Note struct{ db.NotesRow }
```

## Seeding

A seed is what a new checkout's database starts with. In charter it is also what the tests know is there: one set of values, written once, in the app's own types.

```go file=../example/api/fixtures.go#Seeded
// Seeded is what a new checkout's database starts with, and what a test knows is there: a few people, one of each
// role, and notes they wrote. It is written down once, as values of the app's own types. The seed fills the local
// database with it (go tool charter run db:seed; charter dev, on a database it has just made; charter test, on the
// one it makes), and a test of a page fills its own store with the same call, so both show the same notes by the
// same people.
//
// Each person has a token, so that a developer, a test or an agent can be the admin, the moderator or the member
// at once: Authorization: Bearer ch_seed_grace. The seed is built only for seeding and runs only on this machine.
// A deployed database filled by it (go tool charter run db:seed --deployed) has the people and their notes, and
// none of the tokens: their values are written here, for anyone to read.
var Seeded = struct {
	Ada, Grace, Lin SeededPerson
	Notes           []SeededNote
}{
	Ada:   SeededPerson{charter.Person{ID: "seed-ada", Name: "Ada", Role: "admin"}, "ch_seed_ada"},
	Grace: SeededPerson{charter.Person{ID: "seed-grace", Name: "Grace", Role: "moderator"}, "ch_seed_grace"},
	Lin:   SeededPerson{charter.Person{ID: "seed-lin", Name: "Lin", Role: "member"}, "ch_seed_lin"},
}
```

It fills a store the way the app itself writes, through the app's own functions, so a seeded note is a note the app would have made: with its writer, and announced to whoever follows.

```go file=../example/api/fixtures.go#Seed
// Seed fills a store with Seeded, the way the app itself writes: each note through Post, by its writer, as the
// page's form and the API's createNote write one. accounts is where the people are kept (the Worker's database);
// a test of a page, which is handed its caller, passes nil.
func Seed(ctx context.Context, store Store, accounts charter.Accounts) error {
	if accounts != nil {
		for _, p := range []SeededPerson{Seeded.Ada, Seeded.Grace, Seeded.Lin} {
			if err := charter.SeedPerson(ctx, accounts, p.Person, p.Token); err != nil {
				return err
			}
		}
	}
	for _, n := range Seeded.Notes {
		if _, err := Post(ctx, store, n.By.Caller(), n.Body); err != nil {
			return err
		}
	}
	return nil
}
```

`seed.go`, at the app's top, tells charter about it. It is built only for seeding:

```go file=../example/seed.go#init
// The seed: what fills the local database (go tool charter run db:seed; charter dev and charter test, on a database
// they have just made). What it fills it with is api.Seeded, written with the app's own types and through its own
// functions; this file only says so to charter. It is built only for seeding (the build tag), in a Worker started
// on this machine: a Worker that is deployed has none of it.
func init() {
	app.Seed(env.DB, func(ctx context.Context, conn cloud.DB) error {
		// What the app does with each note written, it does for a seeded one: here at once, where a request would
		// leave it to the queue, so the activity page has the seed's notes on it when the seed is done.
		queued := api.OnPost
		api.OnPost = func(ctx context.Context, note api.Note) {
			built.Record(ctx, conn, built.NoteWritten, note.ID, note.Author, 0)
		}
		defer func() { api.OnPost = queued }()
		return api.Seed(ctx, api.StoreOn(conn), charter.AccountsOn(conn))
	})
}
```

```sh
go tool charter run db:seed
```

| When | What happens |
|---|---|
| `charter run db:seed` | The local database is made again (its tables gone, the migrations run) and filled |
| `charter dev`, the first time | The database it has just made is filled; one that is there is yours, and is left alone |
| `charter test` | The Worker under test starts on a database of its own, filled the same way |
| A test of a page, as plain Go | Calls `api.Seed` on its own store: the same people and notes, in memory |
| `charter run db:seed --deployed my-worker` | Every row of the deployed database is deleted, and the seed's put there |

So a page test, a browser test and your own screen show the same notes by the same people.

Each seeded person has a token (`ch_seed_ada`, `ch_seed_grace`, `ch_seed_lin`), so you, a test or a coding agent can be the admin, the moderator or the member at once, with no one to sign up first:

```sh
curl -H "Authorization: Bearer ch_seed_grace" -X DELETE http://localhost:5173/api/notes/1
```

What keeps this safe:

- **The seed never ships.** It is built only when charter seeds, and `charter deploy` builds without it whatever the environment says. A deployed Worker never has the seed in it, and a deployed database never has a seeded token.
- **Nothing is dropped for a seed that does not build.** It is compiled first, and `check` compiles it on every push.
- **The local database, unless you say otherwise twice.** `db:seed` alone fills the local one and refuses a flag it does not know. The deployed one needs `--deployed` and then the Worker's name ([below](#a-deployed-database)).
- **It runs where the app's database code always runs:** in a Worker charter starts here, on the real binding. Beside a running `charter dev` it works in place, with no restart.

`db/seed.sql` works too, for plain SQL, in place of `seed.go`.

### A deployed database

A demo, or a staging environment, shows the seed's data too. The same seed fills it:

```sh
go tool charter run db:seed --deployed             # what the deployed database has, table by table; changes nothing
go tool charter run db:seed --deployed my-worker   # every row deleted, then the seed's rows
```

It deletes everything, so it is asked for twice: the second time with the Worker's name. The tables stay as the migrations made them, and the deployed Worker keeps answering.

The seed still runs on your machine: a Worker started here, built with the seed, whose database binding is the deployed database. The deployed Worker never has the seed in it. What is safe only locally stays out: `api.SeedPerson` keeps the person and no token, because a token whose value is in your code is no secret. `app.SeedIsDeployed(ctx)` tells your own seed the same.

## Reads near the reader

A D1 database takes its writes in one place, its primary, and can keep a copy in each of [its regions](https://developers.cloudflare.com/d1/best-practices/read-replication/). A read answered by the copy nearest the reader spares them the trip to the primary. A copy may be a moment behind, so two things have to hold, and charter holds them for every app, with no line of the app's:

- **The statements of one request agree with each other.** They share one [session](https://developers.cloudflare.com/d1/worker-api/d1-database/#withsession), so a later one never sees less than an earlier one did.
- **A reader sees their own writes, and never the database earlier than they have seen it.** The answer to a request that read or changed the database gives a bookmark, the point the database was at as that request saw it, and the reader's next request brings it back: its reads are at least that new. So what someone wrote is there on the next page, and so is what they were shown: a note that arrived in a live list is not gone a moment later because another copy answered. A browser carries it in a cookie (`d1`, for five minutes, not readable by scripts), so it survives the redirect after a form; a program carries it in a header (`X-D1-Bookmark`), which it sends back as it was given.

`go tool charter deploy` turns the copies on for every database the Worker is bound to (D1's read replication, which wrangler has no setting for): a new app has them from its first deploy, an older one from its next. It costs nothing more: D1 bills the rows a statement reads and writes, with copies or without.

Where a request's reads start:

| The request | Its reads start |
|---|---|
| Says who it is (a session, a token), or signs someone in | At the primary. A session or a token that was just taken away, or a role that just changed, is never accepted by a copy that is behind. The rest of the request reads from there on, so it sees whatever its caller wrote before, bookmark or none |
| Calls the API and brings no bookmark | At the primary: a program that writes and then reads sees what it wrote, though its client knows nothing of bookmarks. One that sends back the `X-D1-Bookmark` it was given reads near itself |
| Is a part of a page asking for itself because its feed said something changed (`live.Follows`), or sends `X-D1-Newest` | At the primary: a copy that is behind would show the page as it was before the change |
| Brings a bookmark | At least where the bookmark says |
| Anything else | At the nearest copy |
| No request at all: a Cron Trigger, a queue's batch, an email, work left for after the answer | At the primary, each statement |

What to know:

- **A request is given a bookmark only when it saw something new.** One that ran no statement is given nothing, and so is one whose reader already holds where the database is: a page that touches no database sets no cookie.
- **A read that must be the newest says so:** `cloud.Newest()` before it. It is the one line an app may need, after a write that someone else made and this reader was told of some other way.
- **The bookmark is given as the answer's headers go.** A statement that runs after that (in a stream, or in work left for after the answer) is not in it.
- **What is brought as a bookmark and is none costs nothing.** One that is malformed starts nothing; one D1 does not know is given up for the primary.
- **Nothing reads D1 another way.** workers-go's own `database/sql` driver knows no session: what went through it would be answered by the primary and give no bookmark. `charter check` fails an app that imports it.

Who answered is said to a request that asks which runtime answered, as `charter run cold` does:

```sh
curl -sD - -o /dev/null -H 'x-go-runtime: ?' https://my-app.example.com/ | grep -i x-d1-served
```

```
x-d1-served: DB WEUR replica, DB WEUR replica
```

Which copy answers, or whether the primary does, is D1's choice, and nothing a Worker does changes it. Cloudflare says a copy is [active or inactive by the traffic it gets](https://developers.cloudflare.com/changelog/post/2025-04-10-d1-read-replication-beta/), and that reads are sent by its own measure of what is fastest. What was seen of the example (primary in APAC), a page with one read, asked with `go tool charter run cold`:

| When | Reads by a new instance of the Worker | Reads by a running one |
|---|---|---|
| The day the copies were turned on, minutes after a deploy, from 123 countries | 20 of 110 at a copy | 11 of 12 at a copy |
| Later that day, the database an hour unused, from 4 countries | 4 of 8 at a copy | |
| Minutes after that, from 12 countries | 18 of 23 at a copy | 9 of 9 at a copy |

So a copy that has had no reads for a while is not there for the first of them, and the primary answers until it is. A new instance of the Worker reads a copy as a running one does: Los Angeles read the copy in WNAM on a new instance three times in three. An app with readers in a region has that region's copy; an app nobody is using has the primary, and its first readers the trip to it.

## By hand

`go tool charter run db:status`, `db:execute "…"`, `db:export`: each for the local database, or the deployed one with `--deployed`. `db:reset` makes the local database again, and only that one; `db:seed` does too, and fills a deployed one only as [above](#a-deployed-database).

<!-- https://charter.gedw99.workers.dev/docs/sign-in -->

# Signing in, and who may do what

An app has one answer to "who is asking, and may they?", for its pages and for its API alike.

## With the commands

| When | Command | What it does |
|---|---|---|
| You want people to sign in | `add screen:sign-in` | the sign-in, account and people pages, and their tables in `db/schema.sql` |
| The first admin | `run people:invite admin` | a link that makes whoever signs up through it an admin, once, within the hour |
| To see who there is | `run people` | everyone who signed up, and what each is |
| Someone has no device left to sign in with | `run people:device <name>` | a link: the device that opens it makes a passkey for their account, once, within the hour |
| Before a push | `check` | a scope is made only where it is declared; your schema still has the sign-in's tables as charter uses them; the role new people get is one of your roles |
| Before a push | `test` | signing up and in with a passkey in a real browser, as each role, on the pages and through the API |

**Checked before the app runs:** every scope a page, an operation or a rule names (a scope is a value: a misspelt one does not compile); the tables charter's sign-in reads and writes, column by column.

**Not checked until it runs:** that a role grants what you meant it to, which is your decision and what the tests of each role are for. A role's name is still a word (`"moderator"`): only the one new people get is checked, when the app starts.

## One caller

```go file=../example/api/handlers.go#Auth
// Auth is that, for the whole app: the API's operations are checked by it (API), and so are the pages (main.go
// gives it to app.App). So a page that needs Write and the operation that needs Write ask the same thing of
// the same caller.
var Auth = charter.NewAuth(cloud.Var, Trusted...)
```

`api.Auth` works out who a request comes from, whatever it carries:

| The request has | The caller is |
|---|---|
| The session cookie of someone who signed in on a page | That person |
| `Authorization: Bearer` with a token that person made | That person, with the token's scopes |
| `Authorization: Bearer` with one of the Worker's secrets | A program, with that secret's scopes |
| Cloudflare Access's token, or an OpenID Connect issuer's | Whoever those vouch for |

The API's operations are checked by it, and so are the pages: `main.go` gives the same `Auth` to both.

## Saying what is needed

What someone may do is a scope. Each is declared once, as a value, where the app says who may do what:

```go file=../example/api/handlers.go#Read
// What someone may do: each scope is declared here, once, and named everywhere else (a page's Needs, an
// operation's Security, Caller.May). A scope is a value, not a word, so one that is misspelt does not compile.
// charter.Admin is charter's own: whoever has it says who is what, and sees the admin screen.
var (
	Read     = charter.NewScope("read")
	Write    = charter.NewScope("write")
	Moderate = charter.NewScope("moderate")
)
```

An operation says what it needs in the contract. A page, or a group of pages, says it with a method. Both name the same value:

```go
// api/contract.go
Security: charter.Needs(Write),

// pages/pages.go
func (PostNote) Needs() []charter.Scope { return []charter.Scope{api.Write} }
```

A scope is a value and not a word so that it cannot be written as one. `Needs: "wrtie"` would compile, name a scope no role grants, and shut everyone out of the page with nothing to say why. As it is, a scope that is not declared is a name that does not exist, and the compiler says so. `charter check` fails an app that makes one anywhere but in its declaration (its part `scopes`).

`charter.Admin` is charter's own scope: whoever has it says who is what and sees the admin screen. Your roles grant it to whom they will.

`Needs` on a group of the tree covers every route under it. A group that returns `nil` needs someone signed in, whoever they are.

| The caller | An operation answers | A page answers |
|---|---|---|
| Is nobody | 401 | Sent to the sign-in page, then back to where they were going |
| May not | 403 | 403 |
| May | The result | The page |

A page that shows something of the caller declares them, as it declares the store:

```go file=../example/pages/pages.go#Home.Props
// Props loads what the request wants, as structpages has it. A row's button asks for that row alone (its target is
// Home's Item, with the note's id as its key): then one note is read, and structpages renders Item with it. The
// list asks for itself when its stream says the notes changed (its target is Home's List): then the newest notes
// are read, and structpages renders List with them, for this reader. Anything else is the page. Each component
// takes its share of the results by their types.
func (p Home) Props(r *http.Request, store api.Store, caller charter.Caller, target structpages.RenderTarget) (HomeProps, []api.Note, charter.Caller, api.Note, Open, Removable, Kept, error) {
	if target.Is(p.Item) {
		id, err := strconv.ParseInt(structpages.KeyOf(target), 10, 64)
		if err != nil {
			return HomeProps{}, nil, caller, api.Note{}, false, false, false, app.NotFound("no such note")
		}
		note, err := store.Get(r.Context(), id)
		if err != nil {
			return HomeProps{}, nil, caller, api.Note{}, false, false, false, app.NotFound("no such note")
		}
		return HomeProps{}, nil, caller, note, r.URL.Query().Get("open") != "", Removable(api.MayRemove(caller, note)), false, nil
	}
	notes, err := store.Before(r.Context(), math.MaxInt64, shown)
	if err != nil {
		return HomeProps{}, nil, caller, api.Note{}, false, false, false, err
	}
	if target.Is(p.List) {
		return HomeProps{}, notes, caller, api.Note{}, false, false, false, nil
	}
	props := HomeProps{Notes: notes, MayWrite: caller.May(PostNote{}.Needs()...), Caller: caller}
	// One read of KV, for every reader: what it is for.
	if props.Notice, err = built.NoticeNow(r.Context()); err != nil {
		return HomeProps{}, nil, caller, api.Note{}, false, false, false, err
	}
	return props, notes, caller, api.Note{}, false, false, false, nil
}
```

In a component, `caller.May(api.Write)` decides what to show: the form, or the way to sign in. Hiding a button protects nothing; the check on the route does.

## Roles

What people may be is said once, as names and what each may do. A person has one role; someone who signs up gets the first you name.

```go file=../example/api/handlers.go#Roles
// Roles are what the app's people may be, and what each may do. Someone who signs up is a member. A moderator
// may also take anyone's note away; an admin may also say who is what.
var Roles = map[string][]charter.Scope{
	"member":    {Read, Write},
	"moderator": {Read, Write, Moderate},
	"admin":     {Read, Write, Moderate, charter.Admin},
}
```

The role someone who signs up gets (`Role: "member"`) must be one of these: an app whose `Role` is none of its `Roles` does not start, which `charter check` finds as it writes the specs.

A role changes for everyone who has it when you change it here, and a person's changes at their next request: in the session they have open, and for the tokens they made before.

A rule that is about more than a scope is a function, asked by the page and by the API alike:

```go file=../example/api/handlers.go#MayRemove
// MayRemove is the rule for taking a note away, said once: whoever wrote it may, and so may whoever may moderate.
// The page asks it to show the button, the page's route and the API's deleteNote ask it before they act.
func MayRemove(who charter.Caller, note Note) bool {
	return who.May(Moderate) || (who.SignedIn() && who.Subject != "" && who.Subject == note.AuthorID)
}
```

In the example a note says who wrote it. Its writer may take it away, and so may a moderator: the page shows the button to exactly those, and the page's route and the API's `deleteNote` ask the same function before they act.

Who is what is an admin's to say: on the people page (from their account), and through the API (`listPeople`, `setRole`), so the generated clients and the command-line client can do it too.

### The first admin, and inviting people

Nobody is an admin until someone is invited to be. An invitation is a link: whoever signs up through it, once, within the hour, is what it says.

```sh
go tool charter run people:invite admin              # under charter dev
go tool charter run people:invite admin --deployed   # on the deployed Worker
go tool charter run people                           # who signed up, and what each is
```

Open the link, give a display name, and your device makes the passkey: you are signed in as an admin. The link's page says what the invitation is to, and one that was used or is too old says so. Someone who has an account already, and is signed in, gets a button there instead: "Accept the invitation". From then on you invite others on the people page ("Invite someone"), to any role, or change the role of someone who signed up already. Under a new invitation's link is a Share button: the device's own share sheet on a phone, the clipboard elsewhere.

On the people page an admin also takes a person away (the bin on their row, asked first): what your app keeps of theirs goes as it does when they delete their own account (`Leaving`). An admin's own row has no bin; their account is theirs to delete, on their account page.

An invitation is kept as a started sign-in is, by the SHA-256 of its code, so the database has nothing that invites anyone. A program does the same with `auth.Invite(r, role)`.

## Signing in

People sign in with a passkey: the device keeps the key and asks its owner (a finger, a face, a PIN). There is no password anywhere.

```sh
go tool charter add screen:sign-in
```

That brings the sign-in page, the account page, the people page and their routes, built from your app's gsxui components, and writes four tables into `db/schema.sql`: users, their passkeys, their tokens, and what was started and not finished (a sign-in, an invitation, a device link, a confirmation).

```go
// pages/pages.go
signIn  screens.SignIn  `route:"/sign-in SignIn"`
account screens.Account `route:"/account Account"`

// main.go
Auth:        api.Auth,
SignIn:      screens.SignInPage{},
Args:        []any{api.Auth},
RequestArgs: []any{api.OpenStore, api.Auth.Caller},
```

`<screens.AccountLink/>` in a header says who is signed in, or leads to signing in.

The name someone gives when they make an account is a display name: it is shown to everyone, beside what they write. The field says so, and an email address is refused there, by the browser and by the Worker.

Someone signed in has a session: a token the app issued, kept by their browser as a cookie that scripts cannot read. On their account page they make tokens for their programs, each with a name; a token is shown once, and the database keeps only its SHA-256. A program sends one as `Authorization: Bearer`, and is that person.

At the foot of the account page someone can delete their account: asked twice, the second time with what goes. Their passkeys, sessions and tokens go with it, and so does what your app keeps of theirs, which you say once:

```go
charter.People{Name: "Notes", Accounts: charter.D1Accounts(env.DB), Roles: Roles, Role: "member", Leaving: Leaving, Mail: env.MAIL},
```

The example takes away the notes they wrote, what the activity page recorded of those, and the files they attached. Only the person can do this, signed in on the page: a program with one of their tokens cannot.

A passkey belongs to a host name. Under `charter dev` that is `localhost`; an IP address has none.

### Another device

A passkey stays with the device that made it, or with the devices of one maker: Apple's keychain takes it to that person's other Apple devices, Google's to their Android phones and their Chrome, and one a Windows computer made is usually that computer's alone. So someone who signed up on a Windows computer has nothing to sign in with on their iPhone, and an account that could only ever have the passkey it was made with would be an account for one device.

An account has as many passkeys as it has been given devices, and there is a way to the next one from wherever someone is:

| Where they are | What they do | What happens |
|---|---|---|
| Signed in on one device, wanting another | "Another device" on their account page makes a link; they open it on the other device (Share hands it to the phone's own share sheet) | That device makes a passkey of its own for the account, and is signed in |
| At a computer that is not theirs, phone in hand | Sign in, and choose the phone in the browser's own dialog (a QR code) | Signed in with the phone's passkey; nothing is kept on the computer |
| With no device left, having given an address | "No device to sign in with?" on the sign-in page, and their address | The same link, sent to that address |
| With no device left, and no address | An admin presses the key on their row of the people page, or you run `people:device` | The same link, made for them: it is shown once, to hand to them |

The account page lists the account's passkeys, each with the browser and the system that made it ("Chrome, Windows"), the day it was made and the day it last signed in. One on a device that is gone is taken away there. The last one stays: without it there is no signing in, and an account is deleted as a whole.

```sh
go tool charter run people:device Ada              # under charter dev
go tool charter run people:device Ada --deployed   # on the deployed Worker
```

A device link is kept as an invitation is: by the SHA-256 of its code, once, for an hour. Whoever opens it is signed in as that person, so it is shown once, to whoever asked for it, and an admin who makes one for someone else can be them: that is what a way back in is, and why only whoever may manage people has it. A device that already holds a passkey of the account says so and makes no second.

### An address to get back in by

Someone may give an email address on their account page ("A way back in"). It is for one thing: with no device left, the link is sent there. It is no name to sign in with, the sign-in page never asks for it first, and it is shown to no one, an admin included.

| What | How |
|---|---|
| The address is theirs | A confirmation goes to it, and it is kept once its link is opened. An address mistyped would otherwise be a stranger's way in |
| Nobody learns whose address is known | The sign-in page answers the same for an address someone gave and for one nobody did |
| Nobody fills an inbox from here | One confirmation and one way back in go to an address in five minutes |
| The message is in their language | It is written by the sign-in screen, from the app's catalogs, in the language of the page that sent it |

The app sends it through its `send_email` binding, which you hand to its people: `Mail: env.MAIL`, in the line above that says what the app's people are. It writes from `sign-in@` the name it is served under, so this is there once the app is on [a domain of its own](10-deploy.md#your-own-domain), which `charter deploy` has Cloudflare send mail for. Under `workers.dev` an app has no address to write from: the account page has no such panel, and the sign-in page says to ask whoever runs the app.

In a test, what the app sent is read where wrangler dev keeps it: `apptest.Mailed(t, address)` is the link in the newest message to an address. The example's `TestAnAddressGetsSomeoneBackIn` goes the whole way: an address given and confirmed, a link asked for from a browser that has never been there, and the old passkey taken away.

## Testing it

| Test | How it has a caller |
|---|---|
| A page's logic (`pages/pages_test.go`) | The test hands the page a caller, as it hands it a store |
| A page in a browser | `page.SignUp(path, "Ada")`: Chrome's own virtual authenticator makes the passkey, in a fraction of a second |
| The API | A bearer token: one of the Worker's secrets |

The example holds both sides to one rule in `test/page_signin_test.go`: nobody is refused by the page's form and by the API's `createNote`; someone signed in is let through by both, and so is the token they made. A member may not remove another's note, on the page or through the API; made a moderator, they may, through both, at once.

## The clients

Every client Fern generates is run against the Worker itself (`go tool charter pack -prove`), by the program in `test/sdk/<language>/`: a token nobody issued is refused, a token that may only read may not write, a token that may write does, and what it wrote is read back. Go, Python, TypeScript and the command-line client each prove it in their own language.

## What is left to you

- **Someone with no device, no address and no admin to ask.** There is nothing of theirs left to know them by. Say so where people sign up, if your app's people would not think to give an address.
- **More than one role each, groups, teams.** A person has one role. Anything richer is your app's own tables and its own rule, written as `MayRemove` is.

<!-- https://charter.gedw99.workers.dev/docs/languages -->

# Languages and search engines

## With the commands

| When | Command | What it does for your languages |
|---|---|---|
| You want a language | `add locale:de` | its catalog, `locales/de.toml` |
| You save a catalog | `dev`, running | the messages are written as Go names and the open page has the new text in about 1.3 s |
| You want it translated | `run intl:status`, `intl:translate`, `intl:todo` | what is missing or stale in each language, and a translation of it |
| Before a push | `check` | every language complete, plural forms right, no message unused |
| Before a push | `test` | the audit: each page's language, its links to its other languages, the sitemap |

**Checked before the app runs:** that a message a page shows exists and is given its arguments (it is a Go name); that every language has every message, with the plural forms that language has.

**Not checked by anything:** whether a translation says the right thing. A message whose source changed is marked stale until someone confirms or retranslates it (`run intl:confirm`).

## Languages

The languages are the catalogs in `locales/`: `en.toml` is the source, and each other file is a translation.

```sh
go tool charter add locale:de
go tool charter run intl:translate
```

Every page has a URL per language (`/built/`, `/de/built/`). Text in a page is a message from the catalog, never a literal:

```gsx
<ui.Button variant="link" class="px-0" href={screens.SignInPage{} |> url}>{ locales.BuiltSignIn }</ui.Button>
```

Numbers, dates and ages go through the runtime's Intl, in the reader's language and time zone:

```gsx
<span class="text-xs text-muted-foreground">{ note.Created() |> since }</span>
{ note.Created() |> date("dateStyle", "full", "timeStyle", "long") }
<dd>{ f.Timezone |> zone }</dd>
```

An age ("3 minutes ago"), a full date and time, and a time zone by its name, as the example's pages write them. `number` takes Intl's own options the same way.

`charter check` fails while a language is incomplete. A right-to-left language is laid out right to left; `check --fix` rewrites gsxui's components for it once.

These docs are the exception: they are written in English.

## Search engines

charter serves `robots.txt`, a sitemap in every language, the canonical address and every alternate in each page's head, and `noindex` on whatever is no page.

```sh
go tool charter run seo:audit
```

The audit reads the live site as a search engine does and fails on anything that would keep a page out of the index or look wrong in a result. It also follows every link a page has to the site itself, from the docs' pages as from any other, and fails on one that leads nowhere: an address that answers 404, or a `#part` the page it names does not have. `charter test` runs it on every push.

## Agents

[`/llms.txt`](/llms.txt) lists the site's pages and these docs for a language model, as [llmstxt.org](https://llmstxt.org) lays it out.

<!-- https://charter.gedw99.workers.dev/docs/screens-and-themes -->

# Screens and themes

## With the commands

| When | Command | What it does |
|---|---|---|
| You want a screen | `add screen:sign-in`, `screen:docs`, `screen:admin`, … | copies it into `pages/screens/`, with the gsxui components it is made of |
| You want a component | `add ui:dialog`; `run ui:list` | gsxui's component, in `ui/` |
| You want another look | `run ui:theme --style lyra`, `run ui:theme <preset>` | another of gsxui's 8 styles, or a style and theme from its editor: `gsxui apply` |
| Readers choose a theme | `add screen:theme` | gsxui's own theme editor, in the app, with the app as its preview: style, mode, base color, theme, chart color, menu accent, radius, fonts |
| Before a push | `check` | fails when charter's screens have moved on and your unchanged copies have not; `--fix` brings them up to date |

**Checked before the app runs:** a screen is a `.gsx` file of your app, so it is compiled against your own components and your own messages, as your pages are.

**Not checked:** a screen you have changed is yours. charter no longer updates it and says so, and `add screen:<name> -diff` shows how it differs. How anything looks is seen in a browser.

## The interface is gsxui's

Every visual piece is a [gsxui](https://ui.gsxhq.dev) component, copied into the app's `ui/` folder, where it is the app's own.

```sh
go tool charter run ui:list        # what there is
go tool charter add ui:dialog      # one more (gsxui add; -diff and -overwrite pass through)
```

## Screens

What every app needs and nobody should write twice is a screen: gsx that charter copies into `pages/screens`, the way gsxui copies a component. A screen is built from the app's own gsxui components, so it has the app's look, and its text comes translated.

```sh
go tool charter add screen:docs screen:theme-toggle
```

| Screen | What it is | In the page tree |
|---|---|---|
| `docs` | The docs' pages, from `docs/*.md` | `docs screens.Docs` at `/docs` |
| `theme-toggle` | `<screens.ThemeToggle/>`: light and dark | |
| `theme` | `screens.Theme`: gsxui's theme editor, and `<screens.ThemeLink/>`, the way to it | |
| `language-list` | `<screens.LanguageList/>`: the page in every language | |
| `language-offer` | `<screens.LanguageOffer/>`: the page offered in the reader's own language | |
| `preferences` | `<screens.PreferencesDialog/>`: time zone and clock | `preferences screens.Preferences` at `/preferences` |
| `admin` | [The admin screen](15-admin.md): the app at a glance, its bindings, its databases; `<screens.AdminLink/>` | `screens.Admin` at `/admin` |
| `sign-in` | [Signing in](14-sign-in.md) with a passkey, the account page, `<screens.AccountLink/>` | `screens.SignIn` at `/sign-in`, `screens.Account` at `/account` |

A copy you have not changed follows charter: `check` says when charter writes it differently, and `check --fix` brings it up to date. A copy you changed is yours, and is left alone (`go tool charter add screen:docs -diff` shows the difference, `-overwrite` takes charter's).

A screen's text follows the same way, message by message and in every language: one you have as charter wrote it takes charter's new wording, and one you worded yourself keeps yours. `locales/intl.sum` records which is which (its `file text:…` lines), so you never mark anything.

## The layout

```sh
go tool charter add screen:layout
```

One document is around every page of an app: `screens.Layout`. Every page has the same header (the app's name, the ways to its pages, its tools) and the same footer, charter's screens too: the docs, the theme editor, signing in, the account, the admin's pages. The app says them once, as it starts:

```go
	screens.Around.Links, screens.Around.Tools, screens.Around.Footer = Links(), Tools(), Footer()
```

A page then names its mode and says what it is. It writes no `<!DOCTYPE html>`, no header, no width, no heading of the first level and no way back: the app's name in the header is the way to the front page, on every page. This is the admin's pages' whole frame:

```gsx
	<Layout mode={LayoutPage} title={title |> text} description={about |> text} heading={title |> text} about={about |> text} tabs={<AdminTabs here={here}/>}>
```

`heading` and `about` are what the page is and a line about it, shown the same way above every page. `tabs` are the pages it is one of.

### What a page is made of

A page puts these together and writes none of them out itself. They are in the layout screen, so every page of the app and every screen of charter's looks the same, and a change to one is a change everywhere:

| Part | What it is | Made of |
|---|---|---|
| `<screens.Panel title={…} about={…}>` | one thing on a page, with what it is and a line about it | gsxui's `Card` |
| `<screens.Rows>`, `<screens.Row>` | a list, and a line of it: what it is, then what it is now or what is done with it | a list |
| `<screens.None>` | what a list says when there is nothing in it | |
| `<screens.Once label={…} value={…}>` | something shown this once (a token, an invitation's link) | |
| `<screens.Tabs tabs={…}>` | the way between the pages a page is one of, the one shown marked | gsxui's `Button` |
| `screens.Failed` | the page an error is (not there, not allowed, went wrong): a page of the app like any other | the layout |

What moves in the layout is gsxui's own components, as `gsxui add` brings and updates them: its `Sidebar`, which is a drawer on a phone by itself, and its `Sheet` for what else has no room there.

| Mode | For | What it is |
|---|---|---|
| `LayoutMarketing` | a front page | as wide as the header |
| `LayoutPage` | a page of the app: a list, a form, signing in, the admin's pages | one column at a width that reads, the same on every one |
| `LayoutDocs` | a page to read | gsxui's `Sidebar` with the pages, the page beside it, its sections at the other side |
| `LayoutWorkspace` | the theme editor | the whole window under the header, no footer |

| What | On a wide window | On a phone |
|---|---|---|
| The app's name | at the start of the header | the same |
| `Around.Links` | in the header | in a drawer, from the header's menu button; on a page of docs, at the top of the list of pages |
| `Around.Tools` | in the header | in the header |
| `Around.Footer` | under the page | under the page |
| A docs page's `navigation` | in the `Sidebar`, which its button or Cmd-B folds away | the `Sidebar` slides in over the page |
| A docs page's `contents` | at the other side, staying in view | under "On this page" at the top of the page |

The links are shown in two places, so nothing in them has an id.

What is checked: `check` fails a page that writes a document of its own. A browser test opens each page at a phone's, a tablet's, a laptop's and a desk's width and fails one that is wider than its window, has something in its header cut off, or shows a menu before it is opened (`page.Wide(390)`, `page.Fits()`).

What is not: how a page looks at a width. And inside its part of the layout a page still places its own elements, with Tailwind's classes.

## Themes

The look is gsxui's, all of it, and so is the way to change it: [gsxui's theme editor](https://ui.gsxhq.dev/theme). charter adds no colour, no setting and no control of its own. What the editor makes is a preset:

| Part of a preset | gsxui has | Changed |
|---|---|---|
| Style: how the components are drawn | 8: Vega, Nova, Maia, Lyra, Mira, Luma, Sera, Rhea | by a reader, and while developing |
| Mode | Light, Dark | by a reader, or their system |
| Base color | 7 | by a reader, and while developing |
| Theme | the base color's own, and 17 accents | by a reader, and while developing |
| Chart color | 18 | by a reader, and while developing |
| Menu accent | Subtle, Bold | by a reader, and while developing |
| Radius | None, Small, Medium, Large | by a reader, and while developing |
| Body font, Heading font | 6 each | by a reader, and while developing |

A preset has a share code (`gsxui:p1:4nI`), which is how it is kept, sent and applied.

### The editor, in your app

```sh
go tool charter add screen:theme
```

`screens.Theme`, mounted at `/theme`, is gsxui's own editor: the same controls, under the same names, as on gsxui's site. Beside them, where gsxui's site shows its gallery, is your app's own front page, changing as a reader chooses. `<screens.ThemeLink/>` in a header is the way there; the docs' pages have it.

What a reader chooses:

- **is kept by their browser**, and every page of the app has it from then on, before its first paint, in the light and in the dark, in the style they chose;
- **is in the page's address** (`/theme?preset=gsxui:p1:ZJC4`): send the address and whoever opens it has the same, in this app or in another made with charter, and in gsxui's own editor;
- **is undone** by "The app's own theme".

Everything in it is gsxui's own code: its markup and its catalogue of choices, rendered by gsxui's own Go, and its three scripts. `charter check --fix` writes them into the app, as gsxui writes its components there (`pages/screens/theme-editor.gen.html`, `web/gsxui-site/`), and again when the app's preset or its gsxui changes; `charter check` fails while they are behind. A page of the app shown in the editor is its preview by gsxui's own preview protocol.

Why it is written into the app and not compiled into it: gsxui's editor is 25 MiB as Go in a Worker, and its preview of every component in every style 40, of the [64 a Worker may have](16-watching.md#cloudflares-limits). Rendered once on your machine it is a file of half a megabyte.

### A style

A style is the one part of a preset that is not CSS. gsxui has it in each component's own markup: a button in Lyra has other classes than a button in Nova, and a card other elements. So the app has its components in every one of gsxui's styles, and the Worker answers each reader in theirs:

| Where | What | Written by |
|---|---|---|
| `ui/` | the components in the app's own style | `gsxui add`, `gsxui apply`: yours to change |
| `ui/styles/<style>/` | the same components in each of the other seven | `charter check --fix`, by running gsxui's own `apply` in a copy of the app |
| `ui/styles/` | a package named `ui` with every component, each rendering the reader's style of it | `charter check --fix` |

A page takes its components from the third, where it would take them from `ui`:

```go
	ui "github.com/joeblew999/charter/site/ui/styles"
```

`<ui.Button>` in a page is then the reader's style of the button. `check` fails a page that imports `ui` itself, which would be the app's own style whatever was chosen.

The editor tells the Worker the style in a cookie (`gsxui-style`), since the Worker needs it to write the markup; the rest of a preset stays in the browser. Choosing a style in the editor asks for the previewed page again, and it comes back in that style.

What this costs, and what it does not do:

- **Size.** Seven more styles of the example's 19 components are 3 MiB of its Worker (measured: 28.1 MiB with one style, 31.2 with eight, of the [64 a Worker may have](16-watching.md#cloudflares-limits)).
- **A component you change in `ui/` is changed in the app's own style only.** The other seven are gsxui's, written again whenever gsxui or the app's components change. A reader who chose another style sees gsxui's.
- **A component that takes a type of its own package** (a chart's `ChartConfig`, a calendar's locale) is the app's own style whatever is chosen: another package's component cannot be handed it.
- **`charter add ui:<name>`, not `gsxui add` alone**, once a page uses the component: charter has `ui/styles` declare it first, then writes it in every style.

### While developing

```sh
go tool charter run ui:theme                            # what the app has, and what there is
go tool charter run ui:theme --style lyra               # another of gsxui's styles, keeping the colours
go tool charter run ui:theme 'gsxui:p1:ZJC4'            # a whole preset: a share code from the editor
go tool charter run ui:theme my-preset.json --only theme
```

Each is `gsxui apply`. It writes `gsxui.preset.json` and `web/gsxui/theme.css`, and for another style every component in `ui/` again in that style; charter then writes `ui/styles` again, which is every style but the app's own. That is the app's own theme: what every reader has who has chosen nothing. The pages follow at once under `charter dev`.

So the docs and the example have one theme by having one preset: apply the same share code to each.

### Light and dark

`app.Head` decides which before the first paint: what the reader chose, else what their system asks for. `<screens.ThemeToggle/>` switches, and any element with `data-theme-toggle` does. It is as gsxui's own site does it. In the editor, Mode shows the preview in the other; a reader's own light or dark stays the toggle's.

### What is checked, and what is not

A browser test drives the editor in the app: it chooses a theme, a radius and a font with gsxui's own controls, sees the preview change, finds the choice on another page in the light and in the dark, hands the address to a second browser, chooses another style and finds the app's pages drawn in it, and goes back to the app's own. The share code charter makes for `--style` is in gsxui's format, which a test holds to gsxui's own source.

Not checked by anything: how a preset looks, and how each page of yours looks in each of the eight styles: the test tells Lyra from Nova by one button. That a colour has enough contrast on another is gsxui's work, and seen in a browser. The editor is in English, as gsxui wrote it. And the two buttons with which gsxui's editor chooses between its own two preview pages are not shown: here the preview is your app's front page.

<!-- https://charter.gedw99.workers.dev/docs/docs -->

# Docs

An app's docs are Markdown files in its `docs/` folder. charter shows them, lists them for search engines, and gives them to language models as Markdown.

```
docs/
  index.md               /docs/
  01-getting-started.md  /docs/getting-started
  02-how-it-works.md     /docs/how-it-works
```

A page's first heading is its title and its first paragraph its description. The number in a file's name is its place in the list, and is not in its address. A link to another page is written to its file (`[the start](index.md)`), so it works on GitHub too.

## With the commands

| When | Command | What it does for your docs |
|---|---|---|
| You want docs | `add screen:docs` | the pages that show them, in your app's own components |
| You save `docs/*.md` | `dev`, running | the page is rebuilt and shown in about 1.3 s; no Go is compiled |
| You save the API's spec, `db/*.sql` or `wrangler.jsonc` | `dev`, running | the pages charter writes of the app follow |
| Before a push | `check` | a code sample taken from a file is what the file says (`--fix` writes it again) |
| Before a push | `test` | every link a page has to the app is followed, and one that leads nowhere fails |

**Checked:** code that names its file; links; and the pages charter writes, which are read from the source and cannot differ from it.

**Not checked by anything:** what a page says in words. When the code a paragraph describes changes, nothing can tell. So keep prose for what does not change with every commit (what the app is for, why it is built as it is), and take facts from files: a sample by its file's name, a table or an operation from the page charter writes.

## Groups, and the order

The front page, `docs/index.md`, says both, where a reader finds them too. A line that is only bold names a group, and the pages the list under it links to are in it, in that order:

```
**Start**

- [Getting started](01-getting-started.md): a new app in three commands.
- [An app's layout](03-layout.md)

**Write**

- [Pages](04-pages.md), [the API](05-api.md)
```

The list at the side of every page is then those groups, and "next" at the foot of a page is the next one listed. There is nothing else to keep: no file of settings, and no second list. A page the front page lists in no group comes after them, and what charter writes of the app is the group Reference. A front page with no such lines groups nothing, and the pages are in the order of their files' numbers.

## What you write, and what charter writes

You write what only you know: what the app is for, and how to use it.

What the app *has* is already written down once, in the files that make it. charter reads those and writes a page of the docs for each, after yours:

| Page | Address | Written from | Says |
|---|---|---|---|
| The API | `/docs/reference-api` | `fern/openapi.json`, the contract `charter check` holds to your Go types | every operation, who may call it and how often, what it takes and answers, every type |
| The database | `/docs/reference-database` | `db/schema.sql`, `db/queries.sql` | every table and column, every statement the app runs |
| What the Worker is bound to | `/docs/reference-bindings` | `wrangler.jsonc`, `.dev.vars.example`, `fnox.toml` | each database, bucket, queue and variable, and the names of the secrets |

A page is there when its source is: an app with no API has no API page. Nobody keeps them in step, because there is nothing to keep: rename a column and the database's page has the new name at the next save. They are pages like any other: listed, searched, given to language models as Markdown, and their "edit" link goes to the file they are written from. Link to one by its address: `[the API](reference-api)`.

[The example's](https://github.com/joeblew999/charter/tree/main/example) are live: [its API](https://charter-example.ubuntusoftware.net/docs/reference-api), [its database](https://charter-example.ubuntusoftware.net/docs/reference-database), [what it is bound to](https://charter-example.ubuntusoftware.net/docs/reference-bindings).

charter's own site has none of the first two, and says so: it has no API and no database. Its pages explain how charter works; for what an app made with it looks like, they point at the example.

## Links are checked

`charter test` follows every link a page of the docs has to the app itself, as it does for every other page, and fails on one that leads nowhere: an address that answers 404, or a `#part` the page it names does not have. A link to another page's file (`03-pages.md`) or to a written page's address is such a link.

## Showing them

```go
// main.go
Docs: &app.Docs{
	Name:    "charter-example",
	Pages:   docs.Pages,
	Repo:    "https://github.com/joeblew999/charter",
	Dir:     "example",
},

// pages/pages.go
docs  screens.Docs `route:"/docs Docs"`
```

That is the example's: its name, the pages charter build wrote from `docs/`, and where its repository is, for the links to a page's own file. `Summary` is a line about the app. The route is the docs screen's (`go tool charter add screen:docs`).

Everything around a page is a gsxui component, so it has your app's theme and gsxui's own behaviour, and none of it is charter's own markup. The page itself is the one thing that is not: it is the HTML charter build makes of your Markdown, styled to match.

The pages are one of [charter's screens](13-screens-and-themes.md): the list at the side, the page, its sections, the theme switch, a link to the repository and one to the page's own file on GitHub. They are built from your app's own gsxui components, so they have its look. This site's docs are shown by the same screen.

How a page of Markdown looks is gsxui's too, as gsxui's own docs are, and nothing of it is charter's:

| Part of a page | Looks as it does by |
|---|---|
| Headings, paragraphs, links, code | gsxui's own stylesheet for its site's docs, which `check --fix` writes from gsxui into `web/gsxui-site/site.css`. A page is marked `data-doc`, as gsxui's doc pages are |
| A table | gsxui's `Table` component, in the reader's style |
| A list, a sample's caption | the classes gsxui's own doc pages give them |
| The colours of code | gsxui's stylesheet. charter marks each word by what it is under the names gsxui's site uses; a test fails when gsxui stops colouring one |

So when gsxui changes how its docs look, yours follow with the next `check --fix`.

## What comes with them

| Address | What it is |
|---|---|
| `/docs/<page>` | The page, in the sitemap, with a title and a description of its own |
| `/docs/<page>.md` | The same page as Markdown |
| `/llms.txt` | The app in a few lines, and every page of the docs as a link to its Markdown |
| `/llms-full.txt` | Every page, as one Markdown document |

While `charter dev` runs, saving a Markdown file reloads the page.

## What the pages have

- The list of pages at the side, in groups: gsxui's `Sidebar` (the [layout screen](13-screens-and-themes.md#the-layout)). Its button, or Cmd-B (Ctrl-B), folds it away; on a phone it slides in over the page.
- Where the page is among the others, at the top, which stays as the page is read: gsxui's `Breadcrumb`.
- The page's own sections at the other side, and on a narrow window under "On this page", which comes down from the top and goes when a section is chosen (a `Sheet`).
- A table too wide for a phone scrolls sideways in its place, its columns at a width that reads.
- At the foot of each page, the page before it and the page after it, each a gsxui `Item`: the docs read from one end to the other.
- Search by the titles of pages and their sections. Cmd-K (Ctrl-K) opens it.
- Code marked up by what each word is, in the colours gsxui's own site gives code, light and dark.
- The theme switch, the repository, and "edit this page".

## Code taken from a real file

A sample that names a file is that file's code, and `check` keeps it so:

> Open the sample's fence with the language and the file: three backticks, then `go file=../example/pages/pages.go#Home.Props`.

`file` is a path from the app's folder. After `#` is one declaration by its name: a type, a function, a method as `Type.Method`, a gsx component. Without `#` it is the whole file. `go tool charter check --fix` writes the code into the Markdown, so it reads on GitHub too; `check` fails when the two differ. Most samples of these docs are the example's own code, taken this way.

<!-- https://charter.gedw99.workers.dev/docs/tests -->

# Tests

Tests are of the pages and of the API. Two kinds: a page as plain Go, in a fraction of a second, and the whole app on a real Worker.

## A page, as plain Go

A page declares what it needs, so a test hands it its own. No Worker, no database, no browser.

```go file=../example/pages/pages_test.go#TestHomeProps
// The home page's data is the newest notes first.
func TestHomeProps(t *testing.T) {
	store := &notes{}
	store.Create(context.Background(), "first", "u1", "Ada")
	store.Create(context.Background(), "second", "u1", "Ada")
	props, _, _, _, _, _, _, err := Home{}.Props(httptest.NewRequest("GET", "/", nil), store, writer, page{})
	if err != nil || len(props.Notes) != 2 || props.Notes[0].Body != "second" {
		t.Fatalf("%+v %v", props, err)
	}
}
```

These live beside the pages (`pages/pages_test.go`) and run with `go test`, which `charter test` does first.

## The whole app, on a real Worker

```sh
go tool charter test             # the Worker on wrangler dev
go tool charter test --deployed  # the deployed one: the same tests, and the audit
```

The local Worker starts on a database of its own, made new, filled by the app's [seed](07-database.md#seeding) and thrown away: a test can count on the seed's people and notes, and changes nothing you have. The deployed Worker's database is real, which is why a test leaves it as it found it ([below](#a-test-leaves-the-worker-as-it-found-it)), and why a test that needs the seed's tokens runs only locally (`apptest.Local()`): a deployed database never has them.

## A page, in a real browser

```go file=../example/test/page_home_test.go#TestANoteShowsOnEveryOpenPage
// A note typed into one open page shows at once in another: the form, the feed, htmx's SSE swap.
func TestANoteShowsOnEveryOpenPage(t *testing.T) {
	t.Parallel()
	writer := apptest.Browser(t)
	reader := writer.Tab()
	// Writing is for whoever is signed in; reading is anyone's.
	writer.SignUp(at(screens.SignInPage{}), "Writer")
	writer.Open("/")
	reader.Open("/")
	body := "typed at " + time.Now().Format(time.RFC3339Nano)
	writer.Type(el(pages.Home.Form)+` input[name=body]`, body)
	writer.Click(el(pages.Home.Form) + ` button[type=submit]`)
	reader.WaitText(el(pages.Home.List), body)
	writer.WaitText(el(pages.Home.List), body)
	if left := writer.Attr(el(pages.Home.Form)+` input[name=body]`, "value"); left != "" {
		t.Errorf("the form still holds %q after posting", left)
	}
}
```

`apptest.Browser` is Chrome on the Worker under test, so htmx, the feed and the scripts Vite built are part of what is tested. `el` asks the app's own tree for a component's selector (`test/tree_test.go`): a renamed component breaks the test when it is compiled, not when a selector quietly matches nothing.

A browser is Chrome, and it is what the time goes on: of the example's suite, the tests that open one take nine tenths of it, about a second each, and the forty that do not take a few hundredths. So:

- **A test that opens a browser says `t.Parallel()`** as its first line. They then run beside each other, and the suite takes a third of the time (the example's: 29 s to 11 s on a local Worker, 85 s to 22 s on the deployed one).
- **A test finds its own rows.** Others write while it runs, so "the first row of the list" is not its note. It asks the tree for the row by the note's id (`row(note.ID)` in `test/tree_test.go`), and never counts what is on a page.
- **A test waits for the thing, not for a while.** `WaitText` and its like ask until it is there. A `time.Sleep` that is long enough on your machine is too short on a deployed Worker that is starting.

## What to test, and what not to

A test is for what running the app shows and nothing else does.

| Do not test | Because |
|---|---|
| That a link, an id or a target reaches its page | the tree and structpages-lint say so when the app is compiled and checked, and `charter test` follows every link |
| That a statement names real columns, with the right types | sqlc checks it against the schema |
| That a binding, a variable or a scope exists | it is a Go value: one that is not there does not compile |
| That the API's spec matches the code | `charter check` compares them |
| What charter's own screens do (the docs' pages, their search, their menu) | charter tests them once, on its own site |

| Do test | Because |
|---|---|
| Who may do what, signed in as each role, on the page and through the API | whether a moderator should have a scope is your decision, and only a request shows it |
| What a binding does: a file kept and given back, a queue's message consumed, an email sent | the name is checked; what Cloudflare does with it is not |
| What a reader sees happen: a list that follows a feed in a second tab, a form refused in place, a menu that opens | it is behaviour in a browser |
| The API through its generated SDK | a client is proven by calling the Worker, never only by compiling |

## The API, through its own SDK

```go
note, err := as.Notes.Create(t.Context(), &notes.CreateNotesRequest{Body: body})
```

The client is the one in `sdk/go`, generated from the contract: the same one another repository would import.

## Where a test runs

| Folder | Runs against |
|---|---|
| `test/` | both |
| `test/dev/` | a local Worker only |
| `test/deployed/` | a deployed one only |

A test that only one can answer asks `apptest.Local()`.

## A test leaves the Worker as it found it

The same tests ask the deployed Worker, whose database is real. So a test takes away what it makes:

- **People.** `page.SignUp` deletes the account again when the test is done, on the account page's own form, and with it what the app keeps of that person. A test that signs up by hand calls `page.Leave(path)`.
- **Rows.** A test that writes through the API takes the row away in `t.Cleanup` (the example's `write` helper).

`page.JS(expression)` evaluates in the page, for what a test cannot do as a reader does: the example stands in for the device's share sheet with it, and checks what the Share button hands over.

The example holds itself to this in `test/main_test.go`: a local Worker starts with the seed, and when the tests are done it must have the seed's people and notes and no more, or the run fails and names what was left.

## Secrets a test needs

A test that must be someone asks for a secret of the Worker by name: `apptest.Secret(t, "ADMIN_TOKEN")`. Locally that is the throwaway value in `.dev.vars`. For the deployed Worker, `go tool charter test --deployed` hands the tests each secret fnox has for it (see [deploying](10-deploy.md)); a test whose secret is missing is skipped, and charter says which.

## What else `charter test` does

The standard test of an API with a contract, and the search-engine audit.

<!-- https://charter.gedw99.workers.dev/docs/deploy -->

# Deploying

```sh
go tool charter deploy
```

That is the D1 migrations, then `wrangler deploy` twice: a deployed app is two Workers.

## Two Workers

| | Name | What it is |
|---|---|---|
| The Go Worker | `<name>-go` | The app as `wrangler.jsonc` has it: every binding, its cron, its queue, its secrets. It has no address of its own |
| The Worker in front | `<name>` | A few KB of JavaScript at the app's address, with the browser's files. It answers a page that is the same for every reader from KV and hands everything else to the Go Worker |

You write one `wrangler.jsonc`, which is what `charter dev` runs, as one Worker. `charter deploy` writes the two configurations from it each time (`wrangler.go.built.json`, `wrangler.front.built.json`, not kept in git).

Why two: a Worker that is not running where a request arrives is loaded there first, and that takes as long as it is large. Measured on 2026-11-28, a one-line answer from an 18 MiB Worker took 210 to 630 ms where it was not running and 25 ms where it was, whether or not Go was started. The Worker in front is small enough to be running anywhere in a few milliseconds, and KV is one copy for every data centre ([a shared page](04-pages.md#a-page-that-is-the-same-for-every-reader)).

- **Health, logs and secrets are the Go Worker's**: that is where the app runs. `run health`, `run logs`, `run secrets` and `run secrets:put` mean it.
- **An app deployed as one Worker becomes two on its next deploy.** The Worker of the app's name hands its queue and cron to the Go Worker and becomes the one in front. A secret that fnox does not have cannot be moved (Cloudflare never gives one back): deploy names it, and it has to be put again.
- **Each of an app's requests comes through the Worker in front**, which gives them to fewer instances of the Go Worker than Cloudflare spreads readers over. The Go Worker keeps what its runtimes hold under a budget that follows the size of the build ([watching](16-watching.md)).

## With the commands

| When | Command | What it does |
|---|---|---|
| You ship | `deploy` | applies the migrations, then deploys the Go Worker and the Worker in front with wrangler; the first time it makes what `wrangler.jsonc` names and writes the ids there |
| After it | `test --deployed` | the same tests, asked of the deployed Worker, which they leave as they found it |
| A secret | `run secrets`, `run secrets:put NAME` | what is declared and what the Worker has; one kept by fnox and put on the Worker |
| To see what is there | `run resources` | the database, KV namespace, bucket and queue the deployed Worker is bound to |
| To take it away | `run delete` | the Worker and its secrets; its data only when you say so |

**Checked before it is deployed:** everything `check` says of the code; that the deployed database gets the schema that code was checked against, before the code; that a resource is the one it was (its id), so a renamed bucket stops the deploy and does not make an empty one.

**Not checked by a deploy:** that the app works there, and that each secret it names has a value on the Worker. `test --deployed` and `run secrets` say. A deploy waits on neither: it tells you how the Worker did in the day before.

## The plan

A charter app is for Workers Paid ($5 a month). Workers Free allows [10 ms of CPU time a request](https://developers.cloudflare.com/workers/platform/limits/#cpu-time), and a Go Worker takes that or more for many of its requests. What Cloudflare allows a Worker and what it charges, each with a link to Cloudflare's own page, is in [Cloudflare's limits](16-watching.md#cloudflares-limits).

## Nothing of your account in the repository

`wrangler.jsonc` names its database, KV namespace, bucket and queue without ids. wrangler makes them on the first deploy and finds them by name after.

```jsonc
"d1_databases": [{ "binding": "DB", "database_name": "my-app", "migrations_dir": "db/migrations" }],
"kv_namespaces": [{ "binding": "KV" }],
```

## Credentials

charter runs wrangler under fnox, which mise installs (`mise.toml`). The token comes from your keychain or password manager, never from a file. In CI the two variables are the environment's.

## Secrets

The Worker's secrets are named in `.dev.vars.example`, each with a throwaway value for `charter dev`. Their real values are fnox's to keep, declared in the app's own `fnox.toml`, which you commit:

```toml
[secrets]
ADMIN_TOKEN = { provider = "keychain", value = "CHARTER_MY_APP_ADMIN_TOKEN", if_missing = "ignore" }
```

That is a name and where its value is kept, never the value. The provider is yours to choose: the keychain, a password manager, an encrypted file ([fnox's providers](https://fnox.jdx.dev)). So each app has its own secrets, and nothing of an app's is in your global config.

```sh
go tool charter run secrets                            # which the app names, and which fnox has
go tool charter run secrets:put ADMIN_TOKEN --random   # a new random value: kept by fnox, put on the deployed Worker
echo "$address" | go tool charter run secrets:put MAIL_TO   # a value of your own, piped in
```

A value is never printed and never on a command line. charter does not write one into `fnox.toml`: with no provider to keep it, it stops and says how to add one. `go tool charter test --deployed` hands the tests the secrets fnox has.

An environment of `wrangler.jsonc` is a profile of `fnox.toml`, with the same names and its own values:

```sh
go tool charter run secrets staging
go tool charter run secrets:put staging ADMIN_TOKEN --random
```

Someone who clones the app has the file and not the values. charter tells them which are missing; nothing else stops.

## Resources

The Worker's database, KV namespace, bucket and queue are named in `wrangler.jsonc`, and the first deploy makes them. What a resource *is* is its id (a database, a KV namespace) or its name (a bucket and a queue, which Cloudflare knows by name and cannot rename).

charter deploy writes the ids into `wrangler.jsonc` after it has made them, and you commit that:

```jsonc
"d1_databases": [{ "binding": "DB", "database_name": "my-app", "database_id": "c26412c3-…" }],
"kv_namespaces": [{ "binding": "KV", "id": "a20e27f8…" }],
```

From then on the Worker is bound to exactly that database and that namespace, whatever the Worker or the resource is later called. Rename the database in the file and it is the same database, with its rows.

A bucket's or a queue's name is different: a changed name is a new, empty one, and the old one is left behind with what it holds. charter deploy stops and says so; `go tool charter deploy --new-resources` goes ahead on purpose.

```sh
go tool charter run resources    # what the file names, and what the deployed Worker is bound to
```

The ids are no secrets. They do tie the repository to the account it deploys to; `charter create` starts a new app without them.

## Taking an app away

```sh
go tool charter run delete                         # what there is: the Worker, its secrets, its data. Changes nothing
go tool charter run delete my-worker               # all of it
go tool charter run delete my-worker --keep-data   # the Worker and its secrets; its data stays
```

It deletes, so it is asked for twice: the second time with the Worker's name. Deleting the app deletes all of it (both Workers, and the pages the one in front kept), and `wrangler.jsonc` no longer names the ids of what is gone, so the next deploy makes its own.

With `--keep-data` the database, namespace, bucket and queue stay, and the file still names them: `go tool charter deploy` brings the same app back with the same data, and with its secrets from fnox, which deploy puts on a Worker that lacks them.

Cloudflare never gives a secret back. So while the Worker has a secret that fnox does not, delete stops and names it.

## Your own domain

A new app is at `<name>.<account>.workers.dev`, which Cloudflare gives it for nothing and which is enough to build with. An app people sign in to belongs on a domain of its own, on a zone of your account. It is said once, in `wrangler.jsonc`, as wrangler has it:

```jsonc
"routes": [{ "pattern": "charter-example.ubuntusoftware.net", "custom_domain": true }],
```

From that line `charter deploy` does the rest:

| What | Who does it |
|---|---|
| The DNS record and the certificate for that name | Cloudflare, as wrangler deploys the Worker in front there |
| `charter.toml`'s `url` is that address | deploy writes it: the specs, the tests and every command with `--deployed` ask it |
| Cloudflare sends mail for that name, when the Worker has a `send_email` binding | deploy asks Cloudflare (Email Sending, on the Workers Paid plan), which adds the records |
| The app writes to its people from `sign-in@` that name | charter, for a way back in and for confirming an address ([another device](14-sign-in.md#another-device)) |

An app made with `charter create` has the line written out and commented, with a name to change.

Choose the domain before people sign up. A passkey belongs to the host name it was made under: people who made theirs at `workers.dev` cannot use them at the domain the app moves to later, and deploy says so when it sees an app with the sign-in screen and no domain, and again as the address changes. Whoever signed up before the move gets back in by a link (`run people:device`).

Under `charter dev` the address is `localhost`, passkeys work there, and mail is not sent: wrangler keeps each message as a file under `.wrangler/` and says where, which is where a test reads it (`apptest.Mailed`).

## Email

A Worker sends email through its `send_email` binding. To an address verified on your account it sends as it is. To anyone, the domain it sends from is onboarded once (Cloudflare Email Sending, on the Workers Paid plan). For the app's own domain, deploy does that. For another:

```sh
go tool charter run mail                           # the domains that send, in the account
go tool charter run mail:enable mail.example.com   # onboard one, and show its records
```

Cloudflare adds the records that let it send for that domain. A subdomain keeps them apart from the domain's own mail.

## After a deploy

```sh
go tool charter test --deployed
go tool charter run seo:audit
go tool charter run logs
```

## Environments

An environment of `wrangler.jsonc` is deployed with `go tool charter deploy staging` and tested with `go tool charter test --env staging`. charter keeps its address in `charter.toml`.

## Everything Cloudflare gives a Worker

workers-go's own packages work as its docs say (the example's package `built` uses each for one job, with a page that shows it): KV, R2, Queues, D1, Cron Triggers, the Cache API, Durable Objects, sockets and fetch. charter adds what it lacks: D1 as typed rows, rate limits and email. [The example's pages for what it is built with](https://charter-example.ubuntusoftware.net/built/) use each one, each on a page of its own, with a test for each.

<!-- https://charter.gedw99.workers.dev/docs/admin -->

# The admin screen

What an admin sees of the system: the app at a glance, what the Worker is bound to, and what its databases hold. It is one of charter's [screens](13-screens-and-themes.md), for an app that has [people who sign in](14-sign-in.md).

```sh
go tool charter add screen:admin
```

```go
admin screens.Admin `route:"/admin Admin"`
```

```gsx
<screens.AdminLink/>
```

The link goes in your header. It is there for whoever may open the pages, and for no one else. The pages need the scope that manages people (`admin`): nobody is sent to sign in, and someone signed in without it gets a 403, by the same rule as every other page.

## The pages

| Page | Shows |
|---|---|
| Overview | The app's name; the charter and Go versions it was built with, and its own commit; how many people there are of each role; the invitations that still wait, each with a button that cancels it; the app's own facts |
| People | The [people page](14-sign-in.md#the-first-admin-and-inviting-people): roles, invitations, removing a person |
| System | Each binding the Worker has, and what kind it is; its variables and secrets, by name, with whether each is set |
| Database | Each database's tables with how many rows they have, and the migrations that ran |

Each page asks only for what it shows. Nothing here changes anything, but an invitation that is cancelled.

**It is what the Worker really has.** The bindings are read from the Worker's own environment as it runs, not from `wrangler.jsonc`: what is listed is what is bound. A database, a KV namespace and a bucket have a Check button, which asks one small thing (a `SELECT 1`, a key that is not there) and says whether it answered and how fast. It asks when you press it, never when the page loads.

**A value is never shown.** A variable and a secret are listed by name, with "set" or "not set". An invitation is listed by what it is to and when it ends, never by its code, which is the invitation.

## The app's own facts

What an admin wants to know of your app goes on the overview, as lines you name:

```go
(&app.App{
	Facts: []app.Fact{
		{Label: locales.FactsNotes, Value: func(ctx context.Context) (any, error) {
			report, err := api.Report(ctx)
			return report.Notes, err
		}},
	},
}).Run()
```

Each is asked when the page is. A number is written as the reader's language writes one, a `time.Time` as a date, anything else as it prints.

## From a program

The pages are functions of `api.Auth`, which check the caller as the pages do: `auth.Overview(r)`, `auth.System(r)`, `auth.Probe(r, binding)`, `auth.Databases(r)`, `auth.CancelInvitation(r, id)`. Their answers are plain values with JSON names, so an operation of your contract can give a program the same thing a page gives a person.

## What it does not do

- **Logs and errors.** A Worker keeps none itself: `go tool charter run logs` follows them live.
- **Anything on Cloudflare.** Deleting a resource and changing a secret are commands ([deploying](10-deploy.md)), each asked twice.

<!-- https://charter.gedw99.workers.dev/docs/watching -->

# Watching a deployed Worker

A deployed Worker fails in ways nothing on your machine shows. Cloudflare ends one that takes more than [128 MB of memory](https://developers.cloudflare.com/workers/platform/limits/#memory), or [too much CPU time](https://developers.cloudflare.com/workers/platform/limits/#cpu-time), and every request it was answering gets a 503 ([all of Cloudflare's limits](#cloudflares-limits)): no code of the app runs, no test of its logic fails, and `charter dev` has no such limits. charter looks where that is recorded, so that you do not have to.

## Is it well?

```sh
go tool charter run health               # the last 24 hours
go tool charter run health --since 7d    # another span: 30m, 6h, 7d
go tool charter run health staging       # an environment
```

```
charter-example, the last 7 days: 10,571 requests
✗ 123 (1.2%) ended because the Worker went over its 128 MB of memory: every request it was answering then got a 503. …
· 1,281 readers left before their answer was done (a stream that was closed: usual)
· CPU time: half under 12 ms, 99% under 192 ms
```

It is Cloudflare's own count of how each request ended. A request the Worker answered is well there whatever it answered; what this finds is the requests it never got to answer. It ends with an error when there are any, so a pipeline can run it.

Nobody has to remember to ask. It is asked where it costs no time:

| When | What is asked |
|---|---|
| `go tool charter deploy` | How the version that is going did the last day, before the new one goes out |
| `go tool charter test --deployed` | First, how the Worker did the last hour. At the end, what Cloudflare has counted of the run so far: a request it ended fails the run, though every test passed |
| Once a day | The last day, for every app, by a scheduled workflow (`.github/workflows/health.yml`): a day that was not well fails it, and GitHub tells you |

Cloudflare takes up to a minute to count a burst of requests. A test run does not wait for that: it asks once, at once, and what is counted later is seen by the next deploy, the next test and the daily check. What goes wrong under real use does so over hours, which is why the daily check is where it is watched for, and why no deploy waits on any of this.

## Three numbers

Go on Workers lives within three limits, and an app drifts towards each a little at a time. charter says each where it is known anyway, keeps the last ones (`.charter/times.json`), and remarks when one has grown or is near its limit:

| Number | Its limit | Said by |
|---|---|---|
| The size of what is deployed, uncompressed | [64 MiB](https://developers.cloudflare.com/workers/platform/limits/#worker-size), on every plan | `charter build` |
| The CPU time the Worker takes to start | [1 second](https://developers.cloudflare.com/workers/platform/limits/#worker-startup-time) | `charter deploy`, from what wrangler reports |
| The memory one Go runtime holds | [128 MB](https://developers.cloudflare.com/workers/platform/limits/#memory) for all of them | `charter test`, from what the Worker says |

```
✓ build/: 27.25 MiB of the 64.00 MiB a Worker may be, uncompressed
· a Go runtime holds about 20 MB: 4 fit in the 80 MB the Worker gives them, so it answers that many at once in one instance
```

What the Worker gives its runtimes is what is left of its 128 MB after its compiled code, which takes about twice the build's size: 80 MB at most, less for a large build. Measured on 2026-11-28 with 40 requests at once, three times: a 31 MiB build ended requests over memory with 80 MB for its runtimes and answered every one with 56; an 18 MiB one answered every one with 80. A request that finds no room waits for a runtime to finish. When one is started over the budget anyway, the Worker says so in its logs (`go tool charter run logs --since 1h --find "over the budget"`).

The size is all of `build/`: the Wasm, and the JavaScript wrangler bundles from the rest, which is what `wrangler deploy --dry-run` calls the Total Upload. Cloudflare counts it as it is: "There is no compressed size limit. Only the uncompressed bundle size counts", the same on the free plan as on the paid one ([Cloudflare's limits](https://developers.cloudflare.com/workers/platform/limits/#worker-size)). The build fails above it, or above `[build] limit` in `charter.toml` when an app sets one lower. What a larger Worker costs is time to start, which is the second number.

A number is remarked on when it is past 80% of its limit, or above what is usual here by more than it varies by itself: 10% for the size, which is the same for the same code; 50% for the start-up, which varies from deploy to deploy; 30% for a runtime's memory, which grows with what it has served.

They are the numbers that say when a limit is coming, and the ones to measure a change of compiler or of design against.

## Cloudflare's limits

What Cloudflare allows a Worker, and what it charges, as its own pages said on 2026-11-27. They change: the links are the authority.

| Limit | Workers Free | Workers Paid | Cloudflare's page |
|---|---|---|---|
| The Worker's size, uncompressed. There is no limit on its compressed size | 64 MiB | 64 MiB | [Worker size](https://developers.cloudflare.com/workers/platform/limits/#worker-size) |
| CPU time to start (the module's top level) | 1 second | 1 second | [Worker startup time](https://developers.cloudflare.com/workers/platform/limits/#worker-startup-time) |
| Memory, for each isolate, shared by every request it is answering | 128 MB | 128 MB | [Memory](https://developers.cloudflare.com/workers/platform/limits/#memory) |
| CPU time for each request | 10 ms | 30 s by default, up to 5 minutes | [CPU time](https://developers.cloudflare.com/workers/platform/limits/#cpu-time) |
| Requests | 100,000 a day | no limit | [Daily requests](https://developers.cloudflare.com/workers/platform/limits/#daily-requests) |

What Workers Paid charges, beyond its $5 a month:

| What is counted | Included each month | Then | Cloudflare's page |
|---|---|---|---|
| Requests to the Worker (requests for static assets are free) | 10 million | $0.30 a million | [Workers pricing](https://developers.cloudflare.com/workers/platform/pricing/#workers) |
| CPU time while the Worker runs: not time spent waiting for D1, a fetch or KV, and not its start-up | 30 million ms | $0.02 a million ms | [Workers pricing](https://developers.cloudflare.com/workers/platform/pricing/#workers) |
| A Durable Object's time while it is active, counted at 128 MB whatever it holds | 400,000 GB-s | $12.50 a million GB-s | [Durable Objects pricing](https://developers.cloudflare.com/durable-objects/platform/pricing/#compute-billing) |
| Requests to a Durable Object | 1 million | $0.15 a million | [Durable Objects pricing](https://developers.cloudflare.com/durable-objects/platform/pricing/#compute-billing) |

That a Worker's start-up is not billed is said on [Dynamic Workers' pricing](https://developers.cloudflare.com/dynamic-workers/pricing/#cpu-time), where it is the difference.

What that means for a charter app, from the example over the 30 days to 2026-11-27:

- **It is for Workers Paid.** A Go Worker takes more than Free's 10 ms of CPU for many of its requests: the example's median is 10 ms, its 99th percentile 166 ms.
- **Size is not near its limit.** The example is 27.25 MiB of the 64. What size costs is time to start, which is not billed: it is the reader who waits for it.
- **Memory is the limit a Go Worker meets first.** A runtime holds 13 MB or more of the isolate's 128 MB ([below](#memory)). While a Go runtime held each page's stream, the example had 123 requests ended over it, on 2026-11-26 and 27; since the hub has held the streams (bdf9572), it has had none.
- **CPU time is what it pays for.** The example took 20 ms a request: 0.42 million ms for its 20,930 requests, well inside the 30 million included. Past what is included, 20 ms a request is $0.40 a million requests, beside the $0.30 for the requests themselves.
- **The hub is billed by time.** A page's stream held open keeps the hub's Durable Object active, which is counted at 128 MB a second. The example's hub was active for 1,406 seconds: 180 GB-s of the 400,000 included.

`go tool charter run health` says the CPU time and how requests ended. What the account has used this month, for every Worker on it, is on the Cloudflare dashboard's billing page.

## Under load

What a Go Worker does wrong under load it does only on Cloudflare, and only when requests come together. Before a release, or when something about what the Worker holds has changed:

```sh
go tool charter run load --deployed                          # 20 at once for 10 seconds, 10 streams held open
go tool charter run load --deployed -at 50 -for 30s -streams 40
go tool charter run load                                     # wrangler dev: how fast, with none of Cloudflare's limits
```

```
https://charter-example.ubuntusoftware.net: 30 pages asked 20 at once for 10s, with 10 streams held open
3,326 requests, 330 a second: half answered within 37ms, 99% within 503ms
✓ every request was answered
charter-example, while it was loaded: 3,222 requests
✓ every one was answered: none went over its memory or CPU time, none threw
```

It only reads: the pages of the sitemap, and the streams they open. It waits until Cloudflare has counted what it sent, so what it says is of all of it; that takes about a minute, and is why it is no part of a deploy.

## A first hit

Where no instance of the Worker is running, a reader waits for one to start. For an app without constant traffic everywhere, most readers in most places are that first hit, and one machine never shows it: its second request finds the instance its first one started.

```sh
go tool charter run cold                        # the deployed Worker's front page, from 30 places
go tool charter run cold -path /docs/ -from 50
go tool charter run cold -in DE,US               # one probe in each of these countries: four of Globalping's tests
go tool charter run cold staging                # an environment
```

```
charter-example, GET /docs/ from 30 places (Globalping), the time from the connection to the first byte:
· the first request: 29 met a new instance (half under 628 ms, 90% under 979 ms); 1 met a running one (half under 520 ms, 90% under 520 ms)
· again from each: 23 met a new instance (half under 501 ms, 90% under 635 ms); 7 met a running one (half under 54 ms, 90% under 131 ms)
```

The places are the probes of [Globalping](https://globalping.io), a public service: it is told the Worker's address and the page, and nothing else. Each asks once, then again. The same is then said for each continent, both rounds together: what a page waits for that is far from some of its readers, a database's primary above all, shows there and in no single number. Last, who answered the page's statements on D1, where the Worker says: the primary, or a copy near the reader, for new instances and for running ones apart ([reads near the reader](07-database.md#reads-near-the-reader)). Which answers were a first hit is counted, not guessed: the Worker says which runtime answered (the header `x-go-runtime`), and one that started as the instance did is a first hit. The time is from the connection made to the first byte, so it is what the Worker and Cloudflare take, without the reader's distance to Cloudflare. Without an account Globalping gives an address 250 probes an hour; this takes two for each place.

### Every data centre, by country

```sh
go tool charter run cold -everywhere
```

Cloudflare runs a Worker in the data centre a request arrives at, and which one that is depends on the network the request comes from, not on a place on a map: two probes a city apart can reach different ones. So it is found by asking. One probe in every country Globalping has probes in asks for the page, once, and the answer's `cf-ray` header ends with the code of the data centre that answered. What each probe reached is kept as the map, in `.charter/colos.json`: the probe's country, city and network, the data centre, whether a new instance answered, how long it took, and who answered the page's statements on D1.

It says how many of [the data centres Cloudflare lists](https://www.cloudflarestatus.com) were reached, then each one, with the countries that reached it and what a reader there waited. It costs one of Globalping's tests for each country, about 120 of the 250 an address has in an hour; with `GLOBALPING_TOKEN` set to a Globalping account's token, the tests are that account's.

What it found on 2026-11-27, from 30 places each:

| | A first hit, half under | A running instance, half under |
|---|---|---|
| `site/`, `/docs/`: 14.4 MiB, starts in 103 ms of CPU | 433 ms | 55 ms |
| The example, `/docs/`: 27.3 MiB, starts in 142 to 224 ms | 628 ms | 54 ms |
| The example, `/`, which reads D1 | 810 ms | 266 to 313 ms |

- **A page that is the same for every reader has a first hit once at each data centre, not once for each instance.** Cloudflare keeps it and answers before the Worker runs ([a shared page](04-pages.md#a-page-that-is-the-same-for-every-reader)). Asked from one place on 2026-11-28, a page of these docs took 508 to 1,424 ms the first time and 44 to 133 ms from the cache; a request with a session was not given the kept page. A data centre that has not been asked for the page has no copy: there the Worker in front answers from KV, without the Go (139 to 587 ms, asked the same day, where the Go Worker took 1.4 s). The rows above are of pages that were not kept.
- **A second request is still a first hit, two times in three.** Cloudflare runs a Worker on many machines at a location, and each starts its own instance. So what counts is less how long an instance is kept than how many of them a reader's requests meet.
- **Of a first hit, charter's part is the smaller.** The request itself took at most 87 ms and the module's start-up 142 to 224 ms of CPU, by Cloudflare's own counts; the rest is Cloudflare making the instance, before any code of the app runs.
- **The runtime that starts with the Worker is the one that answers.** charter starts Go as the Worker's module loads and has it answer the warm-up's pages, so a first request finds it ready. Two things there end a Go runtime: Cloudflare refuses a timer while a module loads ("Disallowed operation called within global scope"), and its clock reads zero, at which Go's collector ends the program. So Go's collector is off until the runtime is given its first request, and its clock is kept off zero until then. When the runtime does not last anyway, the Worker says so to whoever asks which runtime answered (`x-go-runtime: …; start-up failed while the module loaded: …`), starts another for each first request, and answers: only that header shows it. The example and the site each have a test that reads it, which is for `charter test --deployed`: a local Worker allows while its module loads what Cloudflare refuses.
- **A smaller Worker that starts sooner has a shorter first hit**: `site/` is half the example's size and 0.2 s sooner.
- **A page that reads D1 waits for it**, 0.2 s and more, on a running instance too.

It is for after a change to what the Worker loads or does as it starts. It is no part of a deploy.

## What happened?

Workers Logs keep what the Worker printed and how each request ended, for a week. They are on in `wrangler.jsonc`:

```jsonc
"observability": { "enabled": true },
```

```sh
go tool charter run logs                              # live, until Ctrl-C
go tool charter run logs --since 1h                   # what was kept
go tool charter run logs --since 1h --errors          # only what went wrong
go tool charter run logs --since 1d --find 8f3a1b2c   # one request, by its reference
```

`--errors` is a line printed as an error, a request Cloudflare ended, or one answered with a 5xx. A reader who closed a stream is not one.

## A failure has a reference

When a page or a handler returns an error the app does not know how to answer, the reader is told "Something went wrong" and a reference, and never what went wrong inside. The app logs one line of JSON for it, which Workers Logs keeps field by field:

```json
{"level":"error","message":"the app could not answer a request","method":"POST","path":"/notes","route":"POST /notes","status":500,"error":"…","reference":"8f3a1b2c3d4e5f60-SIN"}
```

The reference is Cloudflare's own id of the request, and is also the answer's `X-Request-Id`. Someone who says "it said reference 8f3a…" has named that very request: `--find` brings its line.

The line says what was asked and what went wrong. It never has what was sent: no body, no query, no header, nobody's name.

## Memory

A Go runtime holds 13 MB or more for as long as it serves a request, of the [128 MB](https://developers.cloudflare.com/workers/platform/limits/#memory) an isolate has for every request it is answering. So two things are built in:

- **Nothing long holds one.** A page's stream is held by the hub, in JavaScript ([live feeds](06-live.md)).
- **The runtimes share a budget.** The Worker counts what all its Go runtimes hold and keeps the sum under it; a request that would take it over waits a moment for one to finish.

The [admin screen](15-admin.md)'s system page says how many Go runtimes this instance has alive, what they hold, and what they may. A request with the header `x-go-runtime` is told the same in the answer's.

## What charter leaves to Cloudflare

- **Sending logs elsewhere** (a log store of your own): `wrangler.jsonc`'s `observability` and Logpush.
- **Being told** when something is wrong: a notification on the Worker's error rate, in the Cloudflare dashboard.
- **Lowering what is kept**, for a busy app: `"observability": { "enabled": true, "head_sampling_rate": 0.1 }`.

<!-- https://charter.gedw99.workers.dev/docs/upgrading -->

# Upgrading

```sh
go tool charter upgrade
```

That moves the app to charter's latest, the library and the command together, and runs the new `check --fix`: what charter writes for an app (its screens, its generated files, its tool versions) follows by itself.

What you wrote does not, when a release changes how something is written. This page lists those changes, newest first: what it was, what it is now, and what tells you. In every case below something does: the compiler or `charter check` names the file and the line. Nothing here fails silently on a Worker.

charter is before 1.0: a release may change how an app is written, and says so here. This page starts at 0.63; it does not cover what changed before that.

## 0.82

An app with the sign-in screen adds three columns to `db/schema.sql`; `go tool charter check` names them until it has, and `check --fix` writes the migration.

- **Three columns.** In `users`: `email TEXT`. In `passkeys`: `name TEXT NOT NULL DEFAULT ''` and `used_at TEXT`. They are what the account page's list of passkeys and the address to get back in by are kept in ([another device](14-sign-in.md#another-device)).
- **A way back in by email**, for an app that hands its people a mailer: `Mail: env.MAIL` in its `charter.People`, with a `send_email` binding in `wrangler.jsonc`. Without it nothing changes.
- **An app's own domain is said once**, as a custom domain among `wrangler.jsonc`'s `routes`: deploy makes it `charter.toml`'s `url` and has Cloudflare send mail for it ([your own domain](10-deploy.md#your-own-domain)). An app at `workers.dev` works as before, and deploy says what that costs an app people sign in to.
- **Moving an app to a domain signs everyone out for good.** A passkey belongs to the host name it was made under. Each person gets back in by a link: `go tool charter run people:device <name> --deployed`.
- **The account page lists the account's passkeys**, and one is taken away there.

## 0.81

Nothing of yours has to change. `go tool charter check --fix` brings the sign-in screen's new parts.

- **An account comes to another device.** A passkey stays with the device that made it, or with that maker's devices, and an account had only the one it was made with. "Another device" on the account page makes a link that the other device opens to make a passkey of its own; an admin makes one on the people page for someone with no device left, and so does `run people:device <name>` ([another device](14-sign-in.md#another-device)). No table changes.

## 0.80

Nothing of yours has to change. The next `go tool charter deploy` makes the app two Workers.

- **A deployed app is two Workers**: the Go Worker (`<name>-go`, the app) and a small one in front at the app's address, which answers a page that is the same for every reader from KV ([two Workers](10-deploy.md#two-workers)). A reader in a data centre with no copy is answered without the Go being loaded.
- **The first deploy moves the app's queue, cron and secrets to the Go Worker.** A secret fnox does not have cannot be moved: deploy names it, and you put it again (`run secrets:put`).
- **What the Go runtimes may hold follows the size of the build**, and a request that finds no room waits. A large app that ended requests over memory under load no longer does.
- **Health, logs and secrets are the Go Worker's**: in Cloudflare's dashboard the app's own logs are under `<name>-go`.

## 0.79

Nothing of yours has to change.

- **A shared page is one copy for every reader with no cookie.** It named eleven request headers it was drawn from, and Cloudflare kept a copy for each set of their values: a browser in another language, a page load and a link each got their own, drawn by the Worker. It names four now (`Vary: HX-Target, Cookie, Authorization, X-Forwarded-Proto`).
- **A shared page does not read the browser's languages**, so it offers another language only to a reader who has chosen one.
- **A reader with any cookie is answered by the Worker.** A copy was kept for each style and language cookie; there is one copy of a page now.
- **Every answer says its build** (`X-Charter-Build`), and `charter deploy` fails when a page is answered by an older one: a deploy is seen to have emptied the cache.
- **A first page in the first language gives no `locale` cookie.** No cookie says the same.

## 0.78

Nothing of yours has to change. One line in `wrangler.jsonc` turns on what is new, and `charter create` writes it for a new app.

- **Cloudflare keeps the pages that are the same for every reader**, and answers with them before the Worker runs: add `"cache": { "enabled": true }` to `wrangler.jsonc`. The docs and the theme editor are kept from then on. A page of yours is when its type has `Shared() bool` ([a shared page](04-pages.md#a-page-that-is-the-same-for-every-reader)).
- **Every answer says who may keep it.** What says nothing is `private` now, the API too. An answer of yours that sets its own `Cache-Control` keeps it.
- **A shared page gives no cookie**: the language of the last page viewed is no longer remembered from the docs. A language the reader chose still is.
- **The browser no longer tells the server its time zone** (the `browser_tz` cookie is gone). A time is drawn in the zone the reader chose, else in Cloudflare's guess from where they connect, and their browser puts it right in the page as before. `intl.Decision` has no `BrowserZone`.
- **An app with one language no longer varies by the browser's languages** (`Vary: Accept-Language`): there is none to offer.

## 0.77

Your pages change where they wrote out what is now said once.

- **A page's heading is the layout's**: `<screens.Layout … heading={…} about={…}>`. A page has no `<h1>` of its own, and no card whose title is the page's.
- **What a page is made of is in the layout screen**: `screens.Panel` (a titled card), `screens.Rows` and `screens.Row` (a list and its lines), `screens.None`, `screens.Once`, `screens.Tabs`. charter's screens are made of them; yours can be, in place of a `ui.Card` with its header and content written out and a `<li>` with its classes.
- **An error is a page of the app**, in its layout, for a reader who asked for a page; a program still gets its words.
- **The account asks before it is deleted in gsxui's `Dialog`**, where it had the browser's own disclosure; the people's page has the admin's tabs.

## 0.76

Two lines of yours change: what is around your pages is said once.

- **Every page has the same header and footer.** The app says them once, and no page or screen passes its own:

  | Was | Is |
  |---|---|
  | `<screens.Layout mode={…} title={…} description={…} brand={…} links={…} tools={…} footer={…}>` on each page | `screens.Around.Links, screens.Around.Tools, screens.Around.Footer = Links(), Tools(), Footer()` in a `func init()`, once, and `<screens.Layout mode={…} title={…} description={…}>` on each page |

  The compiler names each page that still passes them.
- **`LayoutPage`** is a page of the app at one width, the same for all: your lists and forms, and charter's sign-in, account and admin pages. `LayoutMarketing` is a front page.
- **No screen has a way back of its own** (the account's, the admin's): the app's name in the header is the way to the front page everywhere. The docs' link to the repository is at the foot of a page, beside "Edit this page".

## 0.75

Nothing to change in an app's code, unless it took 0.74.

- **The layout is of gsxui's components**: its `Sidebar` for a page of docs (a drawer on a phone) and its `Sheet` for the header's links on a phone and for "On this page". 0.74 had copied the shell of gsxui's own website instead, which on a phone had the pages in a small popover and no "On this page"; that is gone. `check --fix` writes the screens again.
- **A page of the docs is put in place by a link again**, with no page load.

## 0.74

A page of yours that writes its own `<!DOCTYPE html>` moves into the layout.

- **One document around every page: the `layout` screen**, with three modes (a centred page, a page of docs, a workspace). `check --fix` adds it and moves charter's screens onto it. Your own pages move by hand, and `check` names each that has not:

  | Was | Is |
  |---|---|
  | `<!DOCTYPE html>`, `<html>`, `<head>`, `<body>`, a `<header>` and a `<main>` with widths of your own | `<screens.Layout mode={screens.LayoutMarketing} title={…} description={…} brand={<screens.LayoutBrand/>} links={…} tools={…} footer={…}>` around the page |

  `links` are the ways to your pages: in the header where there is room, in a drawer where there is not, so nothing in them has an id. `tools` are what the header always has.
- **`apptest`'s `Page` has `Wide(width)` and `Fits()`**: a test that no page is wider than its window, at a phone's width and a desk's.

## 0.73

Nothing to change in an app's code.

- **A docs page looks as gsxui's own docs do**, by gsxui's own stylesheet for them (`web/gsxui-site/site.css`, which `check --fix` writes and adds to `web/main.js`) and gsxui's `Table`, which `check --fix` adds. charter's own styling of a page is gone. Commit what `check --fix` writes.
- **`app.Doc` has `Sections`** where it had `HTML`: a page's parts under each heading, a table as its head and rows. Only a docs screen you changed yourself reads it; `check` says which.

## 0.72

One line to change in each page that uses gsxui's components.

- **A reader chooses a style too.** The app has its components in every one of gsxui's eight styles: `check --fix` writes the other seven into `ui/styles/<style>/` with gsxui's own `apply`, and `ui/styles` itself, a package named `ui` that renders the reader's. Commit all of it. In each `.gsx` of yours that imports the components, take them from there:

  | Was | Is |
  |---|---|
  | `"example.com/app/ui"` | `ui "example.com/app/ui/styles"` |

  `check` names each file that still has the first. charter's screens are changed by `check --fix`. Nothing else in a page changes: `<ui.Button>` stays `<ui.Button>`.
- **`charter add ui:<name>`** writes a new component in every style. `gsxui add` alone fails once a page uses the component.
- **A page's answer varies by cookie** (`Vary: Cookie`): the style is in one.

## 0.71

Nothing to change in an app's code, unless it took 0.70's theme picker.

- **gsxui's theme editor is a screen** (`theme`), and the docs screen brings it. `check --fix` adds it, writes gsxui's editor into the app (`pages/screens/theme-editor.gen.html`, `pages/screens/theme_editor.gen.go`, `web/gsxui-site/`), adds two npm packages gsxui's scripts import (`css-tree`, `jsonc-parser`) and a line to `web/main.js`. Mount it, and commit all of it:

  | In | Add |
  |---|---|
  | the page tree | ``theme screens.Theme `route:"/theme Theme"` `` |
  | a header | `<screens.ThemeLink/>` beside `<screens.ThemeToggle/>` |

- **0.70's `theme-picker` screen is gone**, with `web/gsxui/themes.css`: it was one of the editor's eight parts. In an app that has them, delete `pages/screens/theme-picker.gsx` and `web/gsxui/themes.css`, take `import "./gsxui/themes.css";` out of `web/main.js` and `screens.theme_own` out of the catalogs, and write `<screens.ThemeLink/>` where `<screens.ThemePicker/>` was. The compiler and `check` name each.
- **`charter run ui:theme --style <name>`** switches to another of gsxui's eight styles and keeps the app's colours, radius and fonts.

## 0.69

Nothing to change in an app's code. The docs screen is made of gsxui's `Sidebar`, `Breadcrumb`, `Sheet` and `Item`, which `check --fix` adds to `ui/` as it brings the screen up to date.

- **A message is gone.** An app whose docs screen was brought up to date by 0.68 has `screens.docs_menu` in its catalogs, which nothing uses now: `check` says so, and the line is to be taken out of each `locales/*.toml`.
- **A docs screen you changed** is yours and is left as it is: `go tool charter add screen:docs -diff` shows what charter's is now.
- **The groups and the order of the docs are their front page's** (since 0.68): a line of `docs/index.md` that is only bold names a group, and the list under it its pages ([groups, and the order](11-docs.md#groups-and-the-order)). With no such lines the pages are in their files' order, as before.

## 0.65

Nothing to change in an app's code. Three things behave differently.

- **A page reached by a link is a new page.** Its body takes the place of the one before, where 0.61 to 0.64 morphed it in and left a menu or a dialog that was open still open over the next page. If you relied on something in the body staying across a link (a value typed into a field outside a form, an element you changed with a script), it no longer does: it is as if the page had loaded.
- **`charter test` follows every link** a page has to the app, and fails on one that leads nowhere. A link in your docs to a page you removed is now an error.
- **Three pages are added to your docs**, written from the app: `/docs/reference-api`, `/docs/reference-database` and `/docs/reference-bindings` ([what charter writes](11-docs.md#what-you-write-and-what-charter-writes)). A file of yours in `docs/` that would be at one of those addresses stops the build, which says which: give it another name.

Worth doing while you are here, though nothing requires it: a test that opens a browser can say `t.Parallel()`, which took the example's suite to a third of its time. A test that takes "the first row" for its own, or counts what is on a page, then fails; [tests](09-tests.md) says what to do instead.

## 0.64

Two things an app names are no longer text. Both changes are mechanical: the compiler stops at each line, and the table says what to write.

### A binding, a variable, a secret's name

Each is a value in the package `env`, which charter writes from `wrangler.jsonc`, `.dev.vars.example` and `fnox.toml` ([what the Worker is bound to](03-layout.md#what-the-worker-is-bound-to)). Import it as `"<your module>/env"`.

| It was | It is |
|---|---|
| `cloud.Open("DB")` | `env.DB.Open()` |
| `kv.NewNamespace("KV")` | `env.KV.Open()` |
| `r2.NewBucket("BUCKET")` | `env.BUCKET.Open()` |
| `queues.NewProducer("QUEUE")` | `env.QUEUE.Open()` |
| `cloud.Allow("WRITE_LIMIT", key)` | `env.WRITE_LIMIT.Allow(key)` |
| `cloud.SendEmail("MAIL", from, to, raw)` | `env.MAIL.Send(from, to, raw)` |
| `cloud.Var("APP_NAME")`, `cloudflare.Getenv("APP_NAME")` | `env.APP_NAME.Value()` |
| `live.Feed[Note]{Binding: "HUB", …}` | `live.Feed[Note]{Binding: env.HUB, …}` |
| `charter.Limit{Binding: "WRITE_LIMIT", Limit: 100, Period: 60}` | `charter.Limit{Binding: env.WRITE_LIMIT}`: the calls and the seconds are `wrangler.jsonc`'s |
| a constant of your own that repeats a limit (`LimitCalls = 100`) | `env.WRITE_LIMIT.Calls()`, `env.WRITE_LIMIT.Seconds()` |
| `charter.Token{Secret: "ADMIN_TOKEN", …}` | `charter.Token{Secret: env.ADMIN_TOKEN, …}` |
| `charter.D1Accounts("DB")` | `charter.D1Accounts(env.DB)` |
| `app.Seed("DB", …)` | `app.Seed(env.DB, …)` |
| `apptest.Secret(t, "WRITE_TOKEN")`, in a test | `apptest.Secret(t, env.WRITE_TOKEN)` |

Who tells you: the compiler, for everything of charter's (`undefined: cloud.Open`, or "cannot use "DB" as cloud.Database"). `charter check`, in its part `bindings`, for workers-go's own (`kv.NewNamespace`, `cloudflare.Getenv`), which still compile.

Two things this may turn up, as it did in charter's own example:

- **A name your code reads that is declared nowhere.** `env.MAIL_UNLIMITED` does not exist until `MAIL_UNLIMITED` is in `wrangler.jsonc`'s `vars` (empty is fine), or among the secrets.
- **A binding's name that is no name in Go** (`my-db`, `db`). It must start with a capital letter, then letters, digits and `_`: rename it in `wrangler.jsonc`.

### A scope

A scope is a value, declared once and named everywhere else ([saying what is needed](14-sign-in.md#saying-what-is-needed)).

| It was | It is |
|---|---|
| nothing: a scope was the word wherever it was used | `var Write = charter.NewScope("write")`, once, beside your roles |
| `map[string][]string{"member": {"read", "write"}}` | `map[string][]charter.Scope{"member": {Read, Write}}` |
| the scope `"admin"` | `charter.Admin`, which is charter's own |
| `func (PostNote) Needs() []string { return []string{"write"} }` | `func (PostNote) Needs() []charter.Scope { return []charter.Scope{api.Write} }` |
| `charter.Needs("write")` | `charter.Needs(Write)` |
| `caller.May("moderate")` | `caller.May(api.Moderate)` |
| `charter.Token{…, Scopes: []string{"read"}}` | `charter.Token{…, Scopes: []charter.Scope{Read}}` |
| `charter.Access{People: []string{"read"}, …}` | `charter.Access{People: []charter.Scope{Read}, …}` |
| `charter.Caller{…, Scopes: []string{"read", "write"}}`, in a test | `charter.Caller{…, Scopes: []charter.Scope{api.Read, api.Write}}`, or a role's: `Scopes: api.Roles["member"]` |
| `charter.People{…, Manage: "admin"}` | leave `Manage` out: it is `charter.Admin` |
| `Allow(r *http.Request, needs ...string)`, on an Auth of your own for a test | `Allow(r *http.Request, needs ...charter.Scope)` |

The list above is every kind of change charter's own example needed, taken from its history. Who tells you: the compiler, at every one ("cannot use "write" as Scope"). `charter check`, in its part `scopes`, where a scope is made with `NewScope` anywhere but its declaration.

One thing this may turn up: an app whose `People` has a `Role` that is none of its `Roles` no longer starts, and `charter check` fails as it writes the specs, with the role and the roles there are.

### Screens

A copy of the sign-in or the admin screen that you have not changed is brought up to date by `check --fix`. One you changed is yours: it will not compile until its `Needs` methods return `[]api.Scope` (`api.Admin` for the people and the admin pages), and where it shows a caller's scopes, `scope.String()`.

## 0.63

**No statement on the database is written in Go.**

| It was | It is |
|---|---|
| `cloud.Query[Row](db, "SELECT …", id)`, and `cloud.One`, `cloud.Exec`, `cloud.ExecRows` by hand | a query in `db/queries.sql` (`-- name: Something :one`), and the function `check --fix` writes for it: `db.Something(conn, id)` |
| `cloud.Batch(db, cloud.Stmt("DELETE …", id), …)` | `cloud.Batch(conn, db.ForgetNoteStmt(id), …)`: each query that returns no rows has a `…Stmt` function |
| `cloud.SQL("DB")`, workers-go's `database/sql` driver | a query, as above. `cloud.SQL` is gone: what went through it read the primary always and gave its reader no bookmark |

Who tells you: `charter check`, in its part `statements`, with the file and the line. The compiler, for `cloud.SQL`.

One thing this may turn up: a statement that never matched your schema. sqlc checks each query's columns and types against `db/schema.sql`, which nothing did for a statement written in Go.

`check` now also holds your `db/schema.sql` to the statements charter's sign-in runs on its tables (`users`, `passkeys`, `tokens`, `ceremonies`): you may add columns to them, and a column of theirs that you dropped, renamed or retyped is said, with the statement that needs it.

## When `upgrade` stops

`charter upgrade` ends with the new `check --fix`. When your code no longer compiles against the new release, that is where it stops, with the compiler's lines. Work through them with the tables above, then:

```sh
go tool charter check --fix
go tool charter test
```

<!-- https://charter.gedw99.workers.dev/docs/agents -->

# For your coding agent

charter is made to be worked on by a coding agent as much as by a person. An agent gets two things: skills, which are the rules to work by, and these docs as Markdown, which are the reference.

## The plugins

charter's repository is a [Claude Code plugin marketplace](https://code.claude.com/docs/en/plugin-marketplaces). It lists four plugins, each a skill kept by the owner of the tool it is about:

| Plugin | What it teaches | Kept in |
|---|---|---|
| `charter` | Where everything in a charter app goes, and which command follows which change | [joeblew999/charter](https://github.com/joeblew999/charter/tree/main/skills) |
| `gsx` | Writing gsx components | [gsxhq/gsx](https://github.com/gsxhq/gsx) |
| `gsxui` | Building the interface from gsxui's components | [gsxhq/gsxui](https://github.com/gsxhq/gsxui) |
| `structpages` | The page tree: routes, Props, regions, links | [jackielii/structpages](https://github.com/jackielii/structpages) |

## In an app made with charter

There is nothing to do. The app's `.claude/settings.json` names the marketplace and enables the four plugins, so Claude Code offers them to everyone who opens the repository, and keeps them current as their owners change them.

```sh
go tool charter install   # installs them too
```

## Anywhere else

In Claude Code:

```
/plugin marketplace add joeblew999/charter
/plugin install charter@charter
/plugin install gsx@charter
/plugin install gsxui@charter
/plugin install structpages@charter
```

## One set of commands

The skills of gsx, gsxui and structpages are written for any app. A charter app runs those tools through charter, so charter's skill says what each of their instructions is here:

| Their skill says | In a charter app |
|---|---|
| `gsx generate`, `gsx dev`, `gsx fmt` | Nothing to run: `charter dev` is gsx dev, and `check --fix` generates and formats |
| `gsxui add`, `gsxui list`, `gsxui apply` | `charter add ui:<name>`, `charter run ui:list`, `charter run ui:theme` |
| Run `structpages-lint` | `charter check` runs it |
| Mount the tree with an error handler and a target selector | `app.App` does |

Their tools are the app's own Go tools too (`go tool gsx info`), at the versions `go.mod` pins.

## What an agent can ask

- `go tool charter env`: is `charter dev` running here, at which address, and where is its log.
- `go tool charter check --json`: whether the code is right, as one JSON document: each part (formatting, lint, the contract, the languages) with what it said. No command asks a question.
- The page itself, at the address `env` gives: a save is on it in about two seconds.

## What a language model reads

Any agent, with or without the plugins, can read these docs as Markdown:

| Address | What it is |
|---|---|
| [`/llms.txt`](../llms.txt) | charter in a few lines, the plugins to work with, and every page as a link to its Markdown |
| [`/llms-full.txt`](../llms-full.txt) | Every page, as one document |
| `/docs/<page>.md` | One page |

The skill is short on purpose: the rules, and which command follows which change. For how something works it points here. So the two never say different things: the docs are written once, as the Markdown of [`site/docs/`](https://github.com/joeblew999/charter/tree/main/site/docs).

[Your own app's docs](11-docs.md) get the same three addresses.

<!-- https://charter.gedw99.workers.dev/docs/reference-bindings -->

# What the Worker is bound to

Everything Cloudflare gives this Worker by name: its databases, buckets and queues, its variables, and the names of its secrets.

*Written by charter from `wrangler.jsonc`, `.dev.vars.example` and `fnox.toml`: it is what the app has now, and changes when that does.*

Each is a value in the app's Go under the same name (`env.DB`, `env.APP_NAME`), so one that is not here cannot be used. A secret's value is never in the repository, and never here.

| | In Go |
|---|---|
| Variables (wrangler.jsonc's vars): Value is what one holds. | `env.APP_NAME` |

