Skip to content

Declare the served state in a JSON Schema and generate its types - #3185

Merged
max-sixty merged 6 commits into
mainfrom
data-structures
Oct 19, 2026
Merged

max-sixty merged 6 commits into
mainfrom
data-structures

Conversation

@max-sixty

Copy link
Copy Markdown
Owner

GET /api/state is Leaf's largest contract between versions: a page's vendored runtime reads it from every later Leaf that serves the page, and leaf.page's Worker reads the same state from the container's event answer. Until now nothing declared it. Python built it from dict literals, the browser hand-typed part of it, and the Worker hand-typed the slice it reads. This change declares it in one JSON Schema beside its producer and generates every reader's types from that schema.

The schema

skills/leaf/scripts/leaf/served_state/state.schema.json declares the full state answer (also embedded in the POST /api/event answer and in leaf.page's published state) and the /api/view answer (ViewAnswer). Objects are closed wherever Python's output is closed, so a new field has to be declared. Event records are referenced as leaf:event and leaf:event/<kind> rather than copied, and a projection entry's spec is referenced as leaf:verb, which resolves to the new schema.VERB_SCHEMA, the single schema for one x-state verb. STATE_SCHEMA maps each verb to it. The comments in served_state/ and workflows.py that explained fields are now the schema's descriptions.

Nothing validates on the serving path, since only Leaf writes this channel. Tests validate real output instead: model_folds.served_reading validates every fold, including each record served_records.py hands the Node tests, and test_every_state_answer_holds_the_served_state_schema validates real /api/state, event and /api/view answers over HTTP, before the first revision and after.

Generated types and the protocol check

build/browser/contract-types.mjs (renamed from event-types.mjs) writes contract.d.ts (renamed from event-contract.d.ts). It generates ServedState, ServedVerb and one type per schema definition beside the event types, reading VERB_SCHEMA through uv run python as build/vendor.mjs already does. The browser's AuthoritativeState and wire types now come from it, as does domain.ts's served message. The Worker reads the event answer as { state: ServedState }; its existing catch still rejects a malformed answer.

protocol.test.ts now also fails a change an older vendored runtime would break on: a served field dropped at any depth, or a value widened beyond what the vendored type accepts. Its Lost check remembers each pair of vendored and current record types it compares, so recursive types such as plan steps terminate without a depth bound. protocol-contract.d.ts carries the served state forward, and layer-registry.md, "Page protocol", says the check covers it.

Wire changes

Both run at the same protocol, because no reader distinguishes the old shape from the new, in this tree or in the runtime vendored at the merge base:

  • A served message or resolution by anyone but the agent omits agent instead of sending agent: null, which contradicted the kernel record's agent (a non-empty string). Every reader checks the author first.
  • /api/view answers {browser} without workflows. Its only reader, version.js, reads .views. The browser reading no longer builds activity and workflows only for read_served_page to pop them out; page.py takes both from the work reading, which deletes project_activity.

Declaring the state also corrected the browser's hand-written type: it had fields Python never sends (workflow quiet, dropped, answer kind "turn"), was missing now, working_grace_ms, data, source_error, the presence fields, preview, publication, leaf and release, and treated item answer and end references as full events.

This was written by Claude Code on behalf of max-sixty

max-sixty and others added 5 commits October 19, 2026 15:57
`GET /api/state` (and the state a POST /api/event answer carries, and
leaf.page's published state) had no declaration: Python built it from dict
literals, the browser hand-typed part of it, and the Worker hand-typed the
slice it reads. `served_state/state.schema.json` now declares it, closed
wherever the producer's output is closed, referring to the kernel's event
records as `leaf:event` and `leaf:event/<kind>` rather than copying them.
The field explanations that lived in comments in `served_state/page.py`,
`browser.py`, `wire.py`, `document.py`, `thread.py` and `workflows.py`
moved into the schema's descriptions.

The build generates `ServedState` from it beside the event types
(`build/browser/contract-types.mjs`, renamed from `event-types.mjs`, writing
`contract.d.ts`, renamed from `event-contract.d.ts`). The browser's
`AuthoritativeState` and wire types now select from it, and the Worker reads
the event answer through it instead of `LeafStateAnswer`, without the
fallbacks the type rules out. `protocol.test.ts` now also fails a change
that stops serving a field, at any depth, or widens a value a page's older
runtime reads, and `protocol-contract.d.ts` carries the served state forward.

Behavior changes:
- A served thread message or resolution by anyone but the agent no longer
  carries `agent: null`, which contradicted its kernel record's `agent`
  (a non-empty string); it carries no `agent`. Every browser reader checks
  the author first.
- The model fold's unclaimed presence now carries `live_turn`, `turn_opened`
  and `turn_takes_input`, as the real presence reading does.

Tests holding the shape: `model_folds.served_reading` validates every fold
(and so every `served_records.py` record the Node tests read), and
`test_every_state_answer_holds_the_served_state_schema` validates real
`/api/state` and event answers over HTTP, before the first revision and
after, with a neighbor and a claim.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Review of the served-state schema found places where it accepted output the
producer never writes, a protocol check that passed silently past a depth,
and a served answer it didn't declare.

- A projection entry's `spec` is now the x-state verb it was admitted under
  (`Verb`): its unit, record, creates, writer, text and detail, with a record
  or a detail required, as `schema.STATE_SCHEMA` admits them. Only `detail`,
  a widget's own JSON Schema, stays open.
- An entry's coordinate requires its three parts.
- `preview.input`, a data source's `run`, a reply's `settles` and a history
  row's `about` and `holds` declare what their producers write, the last two
  by reference to the comment record.
- `/api/view` now answers `{browser}` with exactly the browser reading the
  state carries (`ViewAnswer`). The browser reading no longer carries
  `activity` and `workflows` for `read_served_page` and `page_browser_view`
  to pop: the state takes both from the page's work reading directly, and
  the view, whose only reader folds `views`, no longer sends `workflows`.
  `version.js` reads the answer by its generated type.
- `protocol.test.ts` walks each record of the vendored contract once instead
  of stopping after sixteen levels, so a field dropped at any depth fails,
  and holds the `/api/view` answer as it holds the state. The generated
  contract exports a type per schema definition, which the browser now
  imports by name.

Tests: `test_every_state_answer_holds_the_served_state_schema` also
validates a real `/api/view` answer; the model folds validate as before.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
# Conflicts:
#	skills/leaf/kernel/kernel.json
A served projection entry's `spec` is the x-state verb its event was admitted
under. The served schema restated that shape as `Verb`, which had already
drifted from the layer schema: it took an agent verb without a record, a body
record with `creates`, and an empty unit, all of which admission refuses.
`Verb` is gone. The layer schema's verb is now its own constant,
`schema.VERB_SCHEMA`, which `STATE_SCHEMA` maps each verb to; the served
schema refers to it as `leaf:verb`, the tests compose it in as they do the
event records, and the browser build asks Python for it to generate
`ServedVerb`, so `check:browser` fails while the committed type lags it. It
stays in Python rather than moving to JSON because it is built from the name
patterns (`HTML_NAME`, `WIDGET_NAME`) the rest of the layer schema shares.

`protocol.test.ts`'s `Lost` stopped a walk once a vendored record recurred,
even where the current record differed at that edge, so a field dropped from
a recursive record's children passed. It now remembers each vendored and
current pair it compared and stops only when that pair recurs.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
leaf-agent
leaf-agent previously approved these changes Oct 19, 2026
Main's #3184 served each item record once under page protocol 10, so the
served-state schema follows it: a view serves `items`, one list of records;
its `document` and `thread` lose their item collections; a widget or approval
queue row names its item by `id` with no record or title; a thread loses
`user_prompt`. The protocol baseline restarts at 10 from the current contract.
The kernel and browser runtime bundle are rebuilt.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@max-sixty
max-sixty merged commit 11930a3 into main Oct 19, 2026
3 checks passed
@max-sixty
max-sixty deleted the data-structures branch October 19, 2026 23:50
max-sixty added a commit that referenced this pull request Oct 20, 2026
…ssion files (#3202)

Leaf keeps about twenty JSON records outside a page's log and document.
Three carried a `format` and a schema; the rest were dict literals
written at scattered sites and read with key-presence checks, `.get(...)
or {}` chains or raw indexing, each reader deciding for itself what an
unreadable record means. This change gives every record one form, and
stops the state home growing by a file pair for every session of every
harness Leaf is installed in.

## The primitive

`state.Record(kind, schema)` is the one form of every such record. Each
kind is declared once, with its JSON Schema, beside the module that owns
it, and that module's functions are its only writers. `write` stamps
`format` (`leaf-<kind>/<protocol>`) and replaces the file atomically.
`read` returns the record less its `format`, or None for a record this
Leaf does not read: a missing file, one at another protocol or with no
format, or one lacking a field its schema requires at any declared
depth, conditional `allOf`/`if`/`then` clauses included, as a record
another checkout wrote before a field was added. A file that is not JSON
raises, naming it. `state.py` owns the primitive because the SessionEnd
entry runs it on system Python 3.9.

Nothing validates a record whole while Leaf runs, since only Leaf writes
them and the hooks that read the lifecycle and claims must not load the
schema engine (`test_hook_registration` and `test_codex_adapter` hold
that). The suite checks every record a test writes against its schema
instead (`tests/conftest.py`, `declared_records`), as #3185 does for the
served state.

## Records cut over

- Page directory: `status.json` (`service.STATUS`), `cursor.json`
(`event_log.CURSOR`), `viewed.json` (`presence.VIEWED`), `service.json`
(`server.SERVICE`, written only through `server.write_service`),
`preview.json` (`server.PREVIEW`, whose shape is the served state's
`preview`), `data.json` and `data/<source>.json` (`data.CONTRACTS`,
`data.PUBLICATION`, written only through `data.write_data`),
`files.json` (`file_bindings.BINDINGS`), `user-views.json`
(`user_views.USER_VIEWS`).
- State home: claims (`service.CLAIM`, written only by `publish_claim`),
session lifecycles (`state.SESSION`), reconnect notices
(`reconnect.NOTICES`, now an object), neighbor rows (`server_rows.ROW`),
delivery envelopes (`delivery.DELIVERY`), Codex task records
(`codex.RECORD`), the Codex adapter's lease contents
(`codex_adapter.ADAPTER`), the bridge's address and registrations
(`bridge.ADDRESS`, `bridge.REGISTRATION`), and leaf.page's publication
fingerprints (`leaf_website.storage.PUBLISHED`).
- Left out: `access.json`, whose one field never changes meaning; a
format would rotate the machine's key, signing every open tab out, at
each protocol bump. Claude Code's own job records are not Leaf's. Two
dev tools read records raw on purpose: `leaf_dev/arms.py` runs inside
another payload's interpreter, which may predate `Record`, and
`usability_eval.py` copies files verbatim as judging evidence.

Deleted: `registry.kernel.record_format`, `SESSION_FIELDS`,
`CLAIM_IDENTITY`, `readable_claim` (now `claim_reading`),
`readable_delivery`, `SERVICE_KEYS`/`LIFETIMES`, the read-time
jsonschema checks of Codex task records, neighbor rows and user views,
and `retire_if_gone`'s shape checks. `status.json` always carries its
`stream` with `activity`, `reply` and `reply_reservations`, so its
readers index it. `samples.py` writes a child page's data through
`data.write_data` and its starting history through the new
`event_log.start_log`, which `page init` also uses, and writes no
status. Its events were already admitted against the child's view, and a
copied thread keeps its parent's ids, so `append_admitted` would admit
them twice.

## Session files

The SessionEnd hook used to write a lifecycle record and a lock for
every session of every harness Leaf is installed in, used or not: 4,647
of 4,961 lifecycle files on one machine. A session that left no file now
ends without one. At its end, its lifecycle, session lock and reconnect
notices stay, since a failed takeover can restore a claim naming it: the
page shows that session's turn from the lifecycle, and its resumed hooks
read the notices. A session holding no claim loses every other file no
process holds a lock on, so a running watch keeps its lease; one holding
a claim loses only the observations that end with it.
`session-lifetime.md`, "A session's files", owns the rule.

## Behavior changes

- A record another Leaf wrote reads as absent wherever it is read,
including a Codex task record or envelope of the current format that
lacks a required field. A wrong-typed value is no longer rejected on
read.
- A malformed `files.json` reads as no bindings rather than refusing.
- `leaf status` prints the declaration without the stream.
- A delivery this Leaf does not read is refused as "written by another
Leaf".
- Records on disk from before this change read as absent once, as at a
protocol bump; the next claim or serve writes them again.

## Size

Against main the branch adds 858 and deletes 582 product lines (+276),
and adds 499 and deletes 327 test lines. Of the product lines, about 200
are the new schema declarations, which replace shapes that were
implicit, about 60 are the session-file retirement, and about 100 are
the primitive with its docstring; the code it replaced shrank. The
cutover replaces a dozen ad hoc read checks with one.

## Tests

`test_a_session_keeps_its_files_only_while_something_can_read_them`
holds the retirement. The drift tests in `test_claims`,
`test_concurrent_deliveries`, `test_user_views`,
`test_session_lifecycle` and `process/test_interact_server` hold
absent-on-drift, and
`test_the_registered_session_end_releases_shared_claims_without_an_environment`
holds the system-Python SessionEnd. Fixtures write records through
`interact_support.write_record` and `write_row`; a test of an earlier
Leaf's record writes it raw.

> _This was written by Claude Code on behalf of max-sixty_

---------

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants