# Teaspoon Server Design

This document describes the implemented single-revision HTTP server and its
read-only status page. Language rules are specified in [spec.md](spec.md);
durability and external-call guarantees are detailed in
[API Server Semantics](api_server_semantics.md).

## 1. Runtime Boundary

One `Server` owns the program, state, request store and external-call recovery.
One HTTP handler serves API discovery, execution, inspection, and the status
page. The base runtime has no separate product host or workspace lifecycle.

Agents and applications use HTTP JSON. Source editing, conversations, deployment,
authentication and authorization policy belong outside the language runtime. The default listen
address is loopback; exposing the service to other users requires a trusted
gateway or equivalent access controls. The status page and API diagnostics can
contain application data and are not a separate authorization boundary.

An optional `--access-service http://127.0.0.1:PORT` HTTP admission hook asks a
trusted private service before dispatch or UUID-cache lookup. The service may
reject/handle the request, admit the base handler, or select another loopback
business runtime. Credentials and forwarding headers are not passed into that
runtime. Authority failure is a 503, never anonymous fallback. This option is
part of the persisted serve configuration used by managed migration. Without
it, existing serving and replay behavior is unchanged. The hosted TSP IDE uses
this hook for one shared multi-user instance; see
[Email Onboarding](../apps/tspide/docs/onboarding.md). Credentials stay outside
TSP journals, and the account's ordinary business UUID semantics stay unchanged.

The trusted decision may specify string `Arguments`, a `KeyScope`, and
`RedactErrors`. Arguments replace client query/JSON values before API decoding;
JSON numbers retain their exact representation. A valid nonzero UUID is mapped
deterministically into the scope before cache lookup; invalid/missing keys remain
subject to ordinary runtime admission. Redaction preserves HTTP status and a
minimal error envelope, excluding stacks/global snapshots and raw runtime error
messages; explicit `business`/`APIError` values remain visible. These are trusted
admission controls, not headers a client may grant itself. The IDE injects a
nonsecret account ID as `actor`, performs ownership checks in TSP, and denies
public access to global/status inspection. Native authentication and private
resource management remain in `tspideio`.

## 2. Source Shape

A server program is still one Teaspoon source file at runtime. Complete fragments
may be concatenated in a fixed order before launch; `namespace` groups ordinary
helpers and APIs without imports or a module loader. A qualified API
`auth.session` has HTTP path `/api/auth/session` and schema path
`/apis/auth/session/schema`; its advertised and journaled name stays
`auth.session`. Ordinary namespace helpers are not HTTP endpoints.

Top-level mutable state comes from top-level `let` definitions.

```text
let tasks = []

start() {
  tasks = ["buy milk"]
}

readonly api list_tasks() {
  return ok(tasks)
}

api add_task(title: text) {
  tasks = tasks + [title]
  return ok()
}
```

Top-level forms in server mode:

```text
let name = literal
start() { ... }
helper_name(params) { ... }
readonly api name(param: type, ...) { ... }
api name(param: type, ...) { ... }
deprecated api name(param: type, ...) { ... }
deprecated readonly api name(param: type, ...) { ... }
namespace name { helper(params) { ... } }
transient GET "/path"(param: type, ...) { ... }
```

Rules:

- `start()` is retained and required.
- `start()` initializes base state.
- Top-level `let` values are the application state.
- Ordinary functions are internal helpers.
- `readonly api` and `api` functions are exposed externally.
- Exposed API parameters must declare types.
- Ordinary helper function parameters remain untyped.
- API functions are not callable from Teaspoon code.
- `start()` cannot call API functions.
- API functions cannot call other API functions.
- Shared logic should live in helper functions.
- `deprecated` is an independent API admission modifier, written before `api`
  or `readonly api`. It is not allowed on `start()` or ordinary helpers.
  Deprecated bodies retain all existing parameter, return and readonly rules.
  New requests are refused; historical execution and matching completed retries
  remain available. See [Revision Compatibility](revision_compatibility.md#4-approach-two-replay-only-deprecated-apis).

Example:

```text
add_task_impl(title) {
  tasks = tasks + [title]
}

api add_task(title: text) {
  add_task_impl(title)
  return ok()
}

api add_default_task() {
  add_task_impl("buy milk")
  return ok()
}
```

This keeps the transaction boundary at the external API entry point.

## 3. Startup

Server startup for one revision:

1. Parse source.
2. Check source.
3. Initialize top-level `let` values from literals.
4. Lock and open the SQLite request database for the selected revision.
5. Verify the program fingerprint and let SQLite recover committed transactions.
6. Run `start()`.
7. Replay successful mutations, consuming saved external results without new calls.
8. Recover any pending parent request using its saved child UUIDs and outcomes.
9. Open the HTTP listener only after startup and recovery succeed.

If parsing, checking, `start()`, or recovery fails, the CLI reports the diagnostic
and exits; it does not open a failed-host HTTP shell.
If the database cannot be opened, verified, or locked, `start()` is not run.

`start()` is the base state. The change log is the replayed mutation history on
top of that base state.

## 4. API Kinds

### 4.1 `readonly api`

`readonly api` exposes a read-only operation.

Rules:

- Every normal path must return `ok(value)` or `error(problem)`.
- Payload-free `ok()` is not allowed for read-only APIs.
- Cannot assign top-level state.
- Cannot call API functions.
- May call helper functions.
- If the call chain started from a `readonly api`, helper functions also cannot
  assign top-level state.
- Stores the final response, but never adds a replayable mutation.

The checker should catch simple top-level writes statically. The runtime must
also enforce the rule dynamically for the whole call chain.

### 4.2 `api`

`api` exposes a state-changing operation.

Rules:

- May assign top-level state.
- May call helper functions.
- Cannot call API functions.
- Every normal path must return `ok(value)`, `ok()`, or `error(problem)`.
- For explicit payload-free success, `return ok()`, the host returns a system result:

```json
{ "ok": true }
```

Every `api` call is transactional.

## 5. Transaction Semantics

`api` is the Teaspoon equivalent of PFBase `@rpcpost`.

For every external `api` call:

1. Create a snapshot of the current revision state.
2. Execute the API body.
3. Build the structured result.
4. Store the operation and its final response in one SQLite transaction.
5. Commit with `synchronous=FULL` (WAL on disk).
6. Publish the in-memory state and response only after the database commit succeeds.

Rollback rules:

- If API execution fails, restore the snapshot.
- If the API returns `error(problem)`, restore the snapshot and return a business
  error with the explicit payload. Store this final error, but no replayable mutation.
- If result serialization fails, restore the snapshot.
- If persistence fails, restore the snapshot and pause API execution. Return
  HTTP 503, `phase: "storage"`, `StorageUnavailable`, not a confirmed business
  error or success. Restart/recovery must resolve the original request key.
- Failed API calls are not replayed after restart.

Read-only responses are also persisted so retries can return the original
snapshot. TSP execution is serialized; no SQLite write transaction stays open
while the API body runs. This is local durability, not a distributed transaction.

## 6. State Model

The first server version deliberately keeps the language value model narrow:

- `number`
- `text`
- `list of number`
- `list of text`
- `empty list`

API parameter source syntax writes list types in Standard ML order:
`number list` and `text list`. This is new source-level type syntax. It maps
to the existing runtime/output kind wording `list of number` and
`list of text`.

There are no records/objects in the Teaspoon language yet. Applications can
still be built with parallel lists when needed. This is less ergonomic, but it
lets the product flow prove itself before expanding the language.

The status page renders global names and structured value envelopes. Lists use
one item per line. It displays the current API summary and recent HTTP API
response summaries, not a persisted runtime log.

## 7. External Parameter Model

Exposed API parameters declare types with a small Standard ML-style type
annotation syntax.

Examples:

```text
api add_task(title: text) {
  tasks = tasks + [title]
  return ok()
}

api add_score(name: text, score: number) {
  names = names + [name]
  scores = scores + [score]
  return ok()
}

api add_scores(scores: number list) {
  all_scores = all_scores + scores
  return ok()
}
```

Rules:

- Only `readonly api` and `api` parameters use typed parameters in v1.
- Ordinary function parameters remain untyped.
- Parameter syntax is `name: type`.
- Supported API parameter types are `text`, `number`, `text list`, and
  `number list`.
- `empty list` is a value, not a declared parameter type.
- Return types are not declared in v1.
- Future return types, if added, should follow the same style:
  `readonly api list_tasks(): text list`.

Not supported in v1:

- Standard ML type variables, such as `'a`
- function types, such as `number -> text`
- tuple types, such as `text * number`
- record types
- nested list types
- user-defined type names

External clients pass one JSON object whose keys are API parameter names.

Example:

```json
{
  "title": "buy milk"
}
```

The host converts each JSON argument to a Teaspoon value.

Decode rules are driven by the declared API parameter type:

- `text`: JSON string
- `number`: JSON number written in Teaspoon decimal syntax, or exact number
  wrapper
- `text list`: JSON array of strings, or exact `list of text` wrapper
- `number list`: JSON array of numbers written in Teaspoon decimal syntax, or
  exact `list of number` wrapper
- empty JSON array: accepted for `text list` and `number list`

Rejected in v1:

- missing parameters
- extra parameters
- values that do not match the declared parameter type
- JSON boolean
- JSON null
- JSON object, except for explicit Teaspoon value wrappers
- JSON numbers using exponent notation, such as `1e3`
- nested arrays
- arrays mixing strings and numbers outside an explicit wrapper

### 7.1 Exact Numbers

JSON number handling is not enough for Teaspoon's exact rational number model,
because some hosts parse JSON numbers through floating-point values.

Simple JSON numbers are accepted for convenience only when their JSON number
text is also valid Teaspoon decimal number text: integers or decimals without
exponent notation. Transport decoders must preserve JSON number text, for
example with Go's `json.Decoder.UseNumber`, before calling Teaspoon's argument
decoder. Exact clients should use an explicit wrapper:

```json
{
  "amount": {
    "kind": "number",
    "value": "1/3"
  }
}
```

Supported wrappers:

```json
{ "kind": "text", "value": "hello" }
{ "kind": "number", "value": "1/3" }
{ "kind": "list of text", "items": ["a", "b"] }
{ "kind": "list of number", "items": ["1/3", "2"] }
{ "kind": "empty list", "items": [] }
```

Number wrapper values use Teaspoon number text, including integers, decimals,
and reduced fractions.

The wrapper object is a transport shape only. It does not add objects to the
Teaspoon language.

### 7.2 Boundary Checking

API argument type mistakes are detected before the API body starts.

Example:

```text
api add_score(score: number) {
  total = total + score
  return ok()
}
```

If the caller passes text for `score`, the call fails with a structured
`DecodeError` and does not start executing.

Runtime kind errors are still possible inside the API body, for example when
the program combines existing state values incorrectly. Those failures use the
normal structured Teaspoon runtime errors and roll back transactional APIs.

## 8. Return Model

APIs explicitly return `ok(value)` or `error(problem)`. Transactional APIs may
also return `ok()` for payload-free success. Read-only success must carry a value.
API early return is allowed inside `if`, `else`, `for`, and `match` blocks; all
normally terminating paths must return an outcome. A loop alone cannot establish
exhaustive return because it may execute zero times. Ordinary functions retain
their existing final `return value` rule.

`return error(problem)` rolls back local business state. It is a normal API
outcome, not a raised language exception. The host reports `ok: false`,
`phase: "business"`, and an `error` diagnostic with code `APIError` and an extra
`value` field holding the payload's usual `kind`/`display`/`items` representation.
Its message is the payload display, or a generic message for empty text. It does
not include live globals or a call stack. HTTP returns 422 with the structured envelope. Runtime failures remain `phase: "runtime"`.

`ok(value)` and `error(problem)` are result constructors. Their payloads are
ordinary number, text, or list values, not nested outcomes. Local outcome values
can be passed to helper functions and inspected using `match`; they cannot be
compared or stored in lists. `match` requires exactly one `ok(value)` (or `ok()`)
and one `error(problem)` block, without `=>`. Bindings are read-only and local
to the selected branch. `ok()` as a pattern ignores a success payload; binding
a value from payload-free success is a runtime error. Matching or constructing
an error value alone never rolls back state. Only returning it explicitly as
the enclosing API's `error(...)` outcome does so.

Both payloads must be finite, acyclic and JSON-serializable. Current flat lists
contain only scalars and TSP has no references, so source cannot create cycles;
the runtime also validates payloads before encoding responses.

This is a breaking source migration: change API `return value` to
`return ok(value)` and add `return ok()` to formerly no-return transactional
APIs. Do not wrap ordinary function returns. Both constructors are built-in names
and cannot be redefined. Parameter schemas and successful wire payloads are
unchanged. SQLite now stores final success/error responses and replays the
original response for an identical request key, instead of rejecting all
duplicates. The broader target is recorded separately in
[API Server Semantics](api_server_semantics.md).

Host response envelope:

```json
{
  "ok": true,
  "revision": "rev_0001",
  "api": "list_tasks",
  "result": {
    "kind": "list of text",
    "display": "[\"buy milk\"]",
    "items": [
      {
        "kind": "text",
        "display": "buy milk"
      }
    ]
  }
}
```

For `api` returning `ok()`:

```json
{
  "ok": true,
  "revision": "rev_0001",
  "api": "add_task",
  "result": {
    "ok": true
  }
}
```

The inner `{ "ok": true }` is a host result object, not a Teaspoon value.

## 9. Error Model

Stored and direct Go API failures use a minimal diagnostic, wrapped in an API
envelope. Runtime/decode descriptions are fixed by error code. No global values,
stack, locals/parameters, source snippets or suggestions are copied into either
stored error column. For example:

```json
{
  "ok": false,
  "revision": "rev_0001",
  "api": "add_score",
  "phase": "runtime",
  "error": {
    "code": "KindError",
    "message": "This value kind does not support that operation.",
    "location": {
      "file": "main.tsp",
      "line": 8,
      "column": 11
    }
  }
}
```

HTTP errors further omit location and return a fixed `Request failed.` message
for runtime/decode failures, with or without authentication. Explicit business
errors retain their message and structured payload. Cached historical failures
are projected to the same safe output without rewriting old rows. See
[API diagnostics](output_contract.md#server-api-diagnostics) for rationale,
compatibility and the distinction from local CLI debugging.

Common phases:

- `decode`: external parameters could not be converted to Teaspoon values
- `idempotency`: conflicting reuse or invalid idempotency key
- `business`: explicit `error(problem)` outcome and local rollback
- `check`: revision failed validation
- `startup`: `start()` failed
- `runtime`: API execution failed
- `storage`: database outcome unconfirmed; API execution paused (HTTP 503)
- `replay`: startup replay failed

## 10. Change Log

Each revision uses `<log-dir>/<revision>.sqlite`, with WAL and
`synchronous=FULL`. A lifetime `.sqlite.lock` file lock prevents two runtimes
from maintaining divergent in-memory states over one database. SQLite's short
write transactions alone are not sufficient for that ownership guarantee.

One append-only `requests` row contains the sequence number, namespaced request
key, API name, canonical JSON arguments, mutation marker, original result and
diagnostic, and timestamp. Successful transactional calls alone have the
mutation marker. Read-only calls and final failures are stored but not executed
again during recovery. Recovery runs `start()`, replays mutations in sequence,
and checks that every replayed result matches the stored result.

Metadata binds the database to a fingerprint of the parsed program (including
source locations) and the persistence schema version. Changed code must not
silently reuse an old revision database. Existing `<revision>.jsonl` files are
rejected with a migration diagnostic and left untouched; automatic legacy
import is not implemented. Back up legacy data instead of deleting it to make
startup succeed. With no log directory, the store is in-memory only.

If storage cannot confirm a write, the server pauses all API execution, including
reads. `GET /health` returns 503 with `paused: true`; inspection of globals
remains available. A storage failure is an indeterminate infrastructure response,
not a persisted final error. Programs using `await service.api(...)` also journal
their pending request, outbound UUIDs, HTTP method/URL/body and confirmed results. Committed
replay never re-reads dependencies. Interrupted parents reuse saved results or
retry missing replies under their original UUIDs. See the
[external-call contract](api_server_semantics.md#101-implemented-external-calls).
Remote transactional calls use POST and may return payload-free `ok()`; a readonly
caller cannot invoke them. Local rollback never undoes a downstream commit.

## 11. Idempotency

Trusted in-process calls may carry `APICallOptions.Identity`, containing user
and optional session IDs, never credentials. `current_user()` matches
`authenticated(user)` or `anonymous`. The admission journal saves the identity
atomically with pending intent; completion cannot replace it. Replay and the
offline compatibility checker use that recorded identity. Missing legacy
identity is not guessed, and unresolved requests requiring it cannot resume
external calls without it.

Keys supplied with a user identity are scoped to that user, not to a browser
session. An anonymous request cannot retrieve an authenticated user's receipt,
even if it supplies the derived cache key. No session-token authentication or
revocation policy is implied by this in-process API: those must run before
cached responses are returned. The bare HTTP handler currently supplies
anonymous identity; it does not interpret client identity headers.

Local-only programs accept an optional `Idempotency-Key`, for read-only as well
as transactional APIs. Programs containing external calls require a nonzero UUID
key for new transactional admissions; readonly keys remain optional. Same
revision, same key, same API and canonical JSON arguments return the stored final
success or error, without executing again.
Canonicalization sorts object keys but does not equate distinct number tokens
or alternate argument wrappers. Reusing a key with different API/arguments
returns an idempotency conflict without replacing the original record.

Recognized UUID keys compare by UUID value, not spelling: letter case, compact
hex, braces and `urn:uuid:` forms resolve to one identity. New records use the
lowercase hyphenated form. Non-UUID legacy keys remain case-sensitive strings.
On opening a database, the runtime indexes legacy spellings without renaming
request keys, admission times or outbound parent references. If multiple stored
keys identify one UUID (including pending requests), startup and compatibility
checking refuse that ambiguous history; preserve it for explicit repair rather
than picking a result or executing again. This check does not undo historical
duplicate mutations. Cached legacy outcomes remain retrievable, even for a key
that no longer qualifies for a new admission, such as a formerly accepted zero
UUID.

Without a key, each call receives a fresh internal UUID and is a distinct request;
network retries cannot be deduplicated. The UUID requirement is currently scoped
to transactional entry points in programs with external calls. Syntactically invalid transport requests that never reach API dispatch,
invalid keys and unserializable Go arguments are rejected before persistence.

Results are stored durably only when a log directory is configured. Retention
and cleanup are not implemented: deleting request records destroys retry safety.

## 12. HTTP API

`tsprun` and `tspideio` accept the same input-limit flags, in positive decimal
bytes: `--max-header-bytes` defaults to `1048576` (1 MiB), and
`--max-body-bytes` defaults to `8388608` (8 MiB). The first bounds the request
line and headers; the second bounds API JSON bodies. For example, append
`--max-header-bytes 2097152 --max-body-bytes 16777216` to a launch command.
Managed runtime migrations retain these settings. Smaller authentication
protocol limits still apply, and response-size limits are independent.

GET query percent-encoding can expand parameters, so matching numeric limits
does not guarantee that every forwarded request fits. A Go HTTP parser can
reject a long query with 431 before API dispatch. For external calls, the
runtime records this as a terminal `error` under the external service admission
compatibility contract described in [API Server Semantics](api_server_semantics.md).
Services and proxies must preserve admission for historical requests that can
still be retried; lowering a limit incompatibly is outside that guarantee.

HTTP JSON is the public API for agents, applications, and debugging.
Clients discover parameter schemas through `/apis` and `/apis/{name}/schema`.
Operation identity is the HTTP `Idempotency-Key`, not a business parameter.
Clients must retain the same key for retries and use a new key for a new operation.

Current local command:

```text
teaspoon serve main.tsp --addr 127.0.0.1:8080 --revision rev_dev --log-dir .teaspoon/logs
```

Current first implementation serves one selected revision per process.

The same command serves the read-only page at `/` and the aggregate view at
`/view`. Options are `--addr` (default `127.0.0.1:8080`), `--revision`
(default `working`), `--log-dir` (default `.teaspoon/logs`), and optional
`--services`. The CLI closes the listener and server when serving returns.
SQLite ownership is also released if listen or serve fails.

Current smoke example:

```text
let total = 1

readonly api get_total() {
  return ok(total)
}

api add(amount: number) {
  total = total + amount
  return ok(total)
}

start() {
  total = total + 1
}
```

For an automatically selected local port, pass `127.0.0.1:0`. The command prints
the actual URL after the listener is bound:

```text
teaspoon serve main.tsp --addr 127.0.0.1:0 --revision rev_smoke --log-dir .teaspoon/logs
Serving Teaspoon on http://127.0.0.1:54321
```

Use the printed URL for HTTP calls:

```bash
base=http://127.0.0.1:54321

curl "$base/health"
curl "$base/state/globals"
curl "$base/apis"
curl "$base/apis/add/schema"

curl "$base/api/get_total"
curl -X POST "$base/api/add" \
  -H 'Content-Type: application/json' \
  -d '{"amount":3}'
curl "$base/state/globals"
```

In this example, `start()` changes `total` from `1` to `2`; the readonly
`GET /api/get_total` returns `2`; the transactional `POST /api/add` commits the
new state and returns `5`; the final `GET /state/globals` also shows `total` as
`5`.

Active revision routes:

```text
GET  /
GET  /view
GET  /health
GET  /state/globals
GET  /apis
GET  /apis/{name}/schema
GET  /api/list_tasks
POST /api/add_task
```

Programs may also declare exact-path transient GET pages. These render a private
committed-state snapshot without request logging, UUID semantics, external calls
or state writes; transitive helper effects are checked. They may override `/`,
but not the other runtime paths above or their subpaths, and are not added to
`/apis` or explicit-revision routes. See [Transient HTTP Pages](spec.md#transient-http-pages)
for return values, errors and execution limits. The TSP-written IDE uses this
facility for its [integrated book/diff pages](source_views.md#integrated-tsp-pages).

Explicit revision routes:

```text
GET  /revisions/{revision}/state/globals
GET  /revisions/{revision}/apis
GET  /revisions/{revision}/apis/{name}/schema
GET  /revisions/{revision}/api/list_tasks
POST /revisions/{revision}/api/add_task
```

Rules:

- `readonly api` maps to `GET`.
- `api` maps to `POST`.
- Calling a `readonly api` with `POST` is a method error.
- Calling an `api` with `GET` is a method error.
- Deprecated APIs retain their GET/POST method and remain in discovery, with
  `"deprecated": true` on their declaration in `/apis`, `/apis/{name}/schema`
  and the `/view` API summary. Active declarations omit this field.
  For otherwise valid requests, completed identity matching occurs first.
  A new deprecated request returns HTTP `410`, `ok: false`,
  `phase: "admission"` and `error.code: "APIDeprecated"`, before parameter
  decoding or execution. Transport JSON/query/method and UUID errors retain
  their existing precedence. Reusing a completed key with different API/args
  is still an idempotency conflict, not a deprecation response.
- `GET /state/globals` returns every top-level state value using structured
  Teaspoon value JSON.
- `GET /apis` and `GET /apis/{name}/schema` are generated from `.tsp` source.
- `GET` accepts text, decimal numbers and repeated query values for lists;
  exact number wrappers are not supported in query parameters.
- `POST` JSON accepts ordinary values and exact value wrappers, decoded with
  JSON number preservation (`UseNumber`).
- Both API kinds accept `Idempotency-Key`; new transactional admissions in programs
  with external calls require a nonzero UUID. Other calls without a key are not
  retry-safe. Completed legacy retries follow the rules in section 11.
- Calling APIs after server close returns `phase: "server"` with
  `ServerClosed`; state remains readable for UI display.

## 13. Status View

`GET /view` returns `200` with `ServerStateView` directly, without an `ok`
wrapper. It is a snapshot of the same Server used by API requests, taken under
the server mutex; there is no second readiness or lifecycle state machine.

Fields:

- `revision`: `id`, `status` (`ready`, `paused`, or `closed`), optional diagnostic.
- `ready`: true only when API execution is available.
- `globals`: name-sorted `{name, value}` entries, using value `kind/display/items`.
- `apis`: name-sorted `{name, kind, params}` summaries; params contain `name/type`
  in declaration order. Full input schemas remain at `/apis`.
- `activity`: up to 20 current-process HTTP API response summaries, oldest first.
- `last_api_call`: optional summary derived from the final activity entry.
- `diagnostic`: optional top-level diagnostic while paused.

A paused view has `ready: false`, empty `globals/apis/activity`, and a
`StorageUnavailable` diagnostic at both levels. A closed view has the same empty
arrays, status `closed`, and no diagnostic or last call. The internal nil
receiver returns an empty revision and empty arrays with `ready: false`; the
CLI never creates a handler with a nil Server.

The lower-level `/state/globals` endpoint still exposes the stored state during
pause or after close. `/health` reports `paused` and `closed` flags and returns
503 while paused; a closed, non-paused server retains its existing 200 health
response. Neither health nor state inspection authorizes API execution after close.

Activity records only responses dispatched to known APIs with the correct HTTP
method, including transport decode failures and exact retries. Metadata, unknown
routes/APIs, method errors, and revision mismatch do not record activity.
Both direct and revision-pinned API routes use the same recording path. Direct
Go calls and startup replay do not add entries.

Each entry has `kind: "api_call"`, `api`, `api_kind`, `ok`, and HTTP `status`.
Success includes the public `result`; failure includes `phase` and only
diagnostic `code/message`. There are no request args, request bodies, UUIDs,
stack frames, globals or locals copied into activity. Public result values and
diagnostic messages may themselves contain application data: this is a field
whitelist, not content redaction. Returned views are detached copies.

Activity is not persisted, is not replayed, and is not an execution audit log.
Concurrent responses are ordered by when their summaries are recorded; a state
snapshot can be newer than its last recorded response summary. `last_api_call`
is derived, never independently written.

Unless the program declares its own transient `/`, `GET /` serves static HTML/JS
that fetches only `/view` on page load. Refresh
the browser to see changes. It renders values through DOM text content, not
HTML from API data. There are no action controls, chat, source editor or embedded
agent runtime. Both inspection routes accept only GET; other methods get
405 with `Allow: GET`.

## 14. Revisions and Migration

Each process runs one fixed source revision. A revision identifies an immutable
program and its SQLite history. Source changes, named versions, deployment and
migration belong outside this runtime; it does not implement traffic splitting,
draft revisions, a source editor, or hot replacement.

The configured revision is used without appending a version suffix. Existing
workspace-era databases can be reopened by explicitly using their complete
revision (such as `working_v1`) and unchanged source. No database is renamed
or discarded during this transition. Changing source under existing history is
rejected. A different revision starts from its own initialization and history;
there is no automatic state migration.

The former `product serve` command and `/product/*` and `/use/*` routes are
removed, not compatibility aliases. Clients now use `serve`, `/view`, `/apis`,
`/api/{name}`, and `/revisions/{revision}/api/{name}`. Runtime source replacement,
MCP transports and built-in chat are also removed; earlier implementations
remain in git history.

External service bindings and child requests can contain old URLs. Completed
child outcomes replay offline regardless of today's configured service address;
new calls use that current address. An unconfirmed child still requires its
recorded endpoint and UUID. Preserve that route when upgrading a dependency
whose previous URL used `/use`; HTTP redirects are not accepted. A changed
configured endpoint leaves such recovery paused, without forwarding the old
UUID or credentials. Do not rewrite the journal or delete data to bypass this.
See [external-call recovery](api_server_semantics.md) for the exact boundary.

## 15. API Server Restrictions

In server mode:

- `ask` is not allowed.
- `say` is not an API output mechanism and does not accumulate runtime events.
- API output comes from explicit `return ok(...)` or `return error(...)`.
- `readonly api` cannot write top-level state.
- Local API functions cannot be called internally; use ordinary helpers.
- `await service.api(...)` is allowed only during API execution, not startup.

The CLI `run` mode keeps its `say` and `ask` behavior. External conversational
clients can discover schemas and invoke HTTP APIs; the server itself owns no
conversation, agent connection, or programming workspace.
