Repository navigation
Declare the served state in a JSON Schema and generate its types - #3185
Merged
Merged
Conversation
`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
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]>
leaf-agent
approved these changes
Oct 19, 2026
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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
GET /api/stateis 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.jsondeclares the full state answer (also embedded in thePOST /api/eventanswer and in leaf.page's published state) and the/api/viewanswer (ViewAnswer). Objects are closed wherever Python's output is closed, so a new field has to be declared. Event records are referenced asleaf:eventandleaf:event/<kind>rather than copied, and a projection entry'sspecis referenced asleaf:verb, which resolves to the newschema.VERB_SCHEMA, the single schema for one x-state verb.STATE_SCHEMAmaps each verb to it. The comments inserved_state/andworkflows.pythat 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_readingvalidates every fold, including each recordserved_records.pyhands the Node tests, andtest_every_state_answer_holds_the_served_state_schemavalidates real/api/state, event and/api/viewanswers over HTTP, before the first revision and after.Generated types and the protocol check
build/browser/contract-types.mjs(renamed fromevent-types.mjs) writescontract.d.ts(renamed fromevent-contract.d.ts). It generatesServedState,ServedVerband one type per schema definition beside the event types, readingVERB_SCHEMAthroughuv run pythonasbuild/vendor.mjsalready does. The browser'sAuthoritativeStateand wire types now come from it, as doesdomain.ts's served message. The Worker reads the event answer as{ state: ServedState }; its existingcatchstill rejects a malformed answer.protocol.test.tsnow 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. ItsLostcheck 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.tscarries the served state forward, andlayer-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:
agentinstead of sendingagent: null, which contradicted the kernel record'sagent(a non-empty string). Every reader checks the author first./api/viewanswers{browser}withoutworkflows. Its only reader,version.js, reads.views. The browser reading no longer buildsactivityandworkflowsonly forread_served_pageto pop them out;page.pytakes both from the work reading, which deletesproject_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 missingnow,working_grace_ms,data,source_error, the presence fields,preview,publication,leafandrelease, and treated item answer and end references as full events.