Skip to content

Keep each record shape in its own file, and let any shape hold what it arbitrates - #7157

Merged
max-sixty merged 11 commits into
mainfrom
agent-a221b9209833519e9
Nov 25, 2026
Merged

max-sixty merged 11 commits into
mainfrom
agent-a221b9209833519e9

Conversation

@max-sixty

@max-sixty max-sixty commented Nov 25, 2026 •

Copy link
Copy Markdown
Owner

Each state.Record shape now lives in a file named with its since (drafts.json is kept at [email protected]), and a Leaf reads and replaces only its own shapes' files. This takes out #7061's Record.kept, read_any and the build's kept-key checks: root AGENTS.md "Stage" forbids fallback reads, and in the last five weeks the records #7114 would carry across changed shape only during the drafts store's first two days.

A record that arbitrates between Leaves (a page's claim with its session's lifecycle, a page's service, a grant, the Codex adapter's) holds while a file of any shape of it stands, without being read, and a session's end, leaf server stop, a grant's withdrawal and a takeover of the page end it at every shape. Who holds a page is one reading, service.page_holder, which every reader deciding whether it may act on a page asks, and a rolled-back takeover puts back what it removed. The cost: after a SESSION shape change, which comes with a protocol bump, a page whose session ended under the older Leaf stays held for the newer one until an agent takes it over with leaf server start, which every refusal of a held page names; the takeover leaves one owner. layer.json stays one file, and renewal keeps its packages. page check names a drafts store of another shape, the user's unsent words, and says to point the user at it rather than read it.

Max chose this over #7114 on his Leaf page; it supersedes #7114.

At a shape change, against main: drafts, connection grants, the sign-in key and the server address are gone from the page as on main, their files kept; file grants, which main carries across, are gone too; a claim-shape change leaves the page held until the agent runs leaf server start. Session records, delivery envelopes and the layer behave as on main.

Net lines: production code +83, comments and docstrings +57, tests +96, prose +22, baseline data −7.

Tests: tests/model/test_record_shapes.py (a page held at another shape, a session-less wait stopping there, a takeover leaving one owner and its rollback restoring the other holder, a withdrawal at every shape, the page check note) and a stop beside another shape's server in test_server_lifetime.py; the model and process files that touch records pass on Python 3.14 and 3.12. CI also runs the journey and browser tests this branch edits; the four server-row journeys in test_interact_server and test_render_controls fail on main at 118f31f too, since #7061 refuses to serve a held page for no session. Edited but not run locally: tests/journeys (test_activity, test_claims, test_codex_adapter, test_hook_registration, test_interact_document, test_interact_layer, test_interact_server, test_native_watch, test_render_controls, test_session_lifecycle, test_site), tests/browser (drafts/test_shared_drafts, startup/test_projected_data, projection/test_code_review) and dev/tests/journeys (test_render_export, test_interact_preview).

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

…or the agent

An alternative to reading records across shapes (#7061's `Record.kept` and
`read_any`, and #7114's extension of them), built so the maintainer can compare
the two. Max: "We could just avoid deleting anything and then the agent can
clear it up."

**The primitive.** `state.Record.file` names each shape's file with its `since`
before the suffix (`drafts.json` is kept at `[email protected]`). `read`, `write`,
`remove` and `glob` go through it, so a Leaf reads, replaces and removes only
its own shapes' files, and a Leaf of another shape finds its record as it left
it, even with both running. Chosen over setting another shape's record aside
before a write, which ping-pongs when two Leaves run at once (an installed copy
and an update, or two worktrees) and overwrites the earlier set-aside copy.

**What goes.** `Record.kept`, `read_any`, `_keep`, `since_of`, the build's
kept-key checks and baseline entries, and their tests and prose. An unknown
lifetime kind still reads as live, since the bridge's registrations don't
declare their lifetime's keys. The Codex adapter's record moves beside its
lease rather than into it, and `PREVIEW` moves to `service.py`, below the hooks
that ask whether a page is a preview.

**What stays across shapes.** The layer record keeps one file, since its
`format` is the page's protocol, and renewal still carries its `packages`. A
session's end retires its files of every shape, and a stop removes another
shape's service record, which is what stops that Leaf's server.

**How the agent learns.** `page check` (and the first reply on a revision)
names the page directory's records of other shapes, and `leaf page list` the
state home's (`state.leftover_records`), by pattern, format, count and newest
write, reading only each file's `format`. The serving-pages reference says to
remove them once no session runs the earlier Leaf, and to point the user at a
drafts file rather than read it.

**Readers by name.** Page readings, the website's page records and the site
build classify a page directory's files by the name readers give them
(`state.record_name`).

**What the user loses against main.** An update that changes the claim's
shape leaves the session holding none of its pages under the new Leaf until the
agent runs `leaf server start`, and nothing tells it but `leaf page list`. Main
keeps the claim live across that change. The other kinds behave as on main,
except that the earlier Leaf's file stays untouched and is named to the agent,
and the sign-in key no longer churns when two Leaves read it.

**Tests.** Tests of cross-shape reading go; tests that simulated another
Leaf's record by rewriting `format` in place now put it at another shape's
file and assert this Leaf leaves it byte-for-byte. New: `test_record_shapes`.

**Protocol.** No record's shape changes and no `since` moves; the file names
change, so records an earlier Leaf wrote at the old names read as absent once
(Stage: old records are disposable).

> _This was written by Claude Code on behalf of max-sixty_
…and score the leftover guidance

The two refusals a shape change meets now say what is true:

- `leaf delivery read` of an envelope another Leaf version froze names that
  envelope's format, not the reader's own, and says to read and acknowledge the
  page's next delivery.
- `leaf server start` on a page whose server another version started no longer
  says "re-run", which can never work: it names `leaf server stop` then `start`,
  and the new address that brings.

`state.leftover_records` groups by directory and format, and names a group by
one pattern only where the pattern matches those files and no other, in place
of a regex over hex keys. Its module walk moves to `state.declared_records`,
which `leaf_dev.declared_records` now calls rather than repeating: without it,
`page check` misses drafts and user views, and `page list` misses grants,
deliveries and every Codex record.

`evals/update-leaves-other-version-records` scores the `other-version-records`
finding and the serving-pages paragraph: Claude Code, 3 runs on each of this
tree and the merge base, passed all 3 rubrics (drafts left unread and pointed
at, the page taken again, the rest removed once no older Leaf runs) on both
arms. Every run opened `serving-pages.md`; the finding's own words carry the
behaviour.

> _This was written by Claude Code on behalf of max-sixty_
# Conflicts:
#	build/browser/protocol-baseline.json
> _This was written by Claude Code on behalf of max-sixty_

@leaf-agent leaf-agent left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On Python 3.12 and 3.13, which requires-python = ">=3.12" admits, sessions never end. session_file(session_id, "") returns <key>., and before 3.14 Path("<key>.").stem keeps the trailing dot. So _session_paths globs <key>.[.@]*, which matches none of the session's files (<key>@56.lifecycle, <key>.wait, …). end_session and end_harness_instance then return at not _session_paths(session_id) without writing ended, and _retire removes nothing. A claim keeps reading as active after its session ends. tests/model/test_claims.py::test_a_claim_records_where_the_session_is_working passes on the merge base and fails on this head under 3.12 at assert presence_model.presence(page_dir, [])["session_alive"] is False. With the suggestion below it passes, and so do the 191 tests in the record, claim, session-lifecycle, drafts, stop-guard, server-lifetime and hooks model files.

Comment thread src/leaf/state.py Resolved
…hat a stop or withdrawal ends at every shape

Review of #7157 found four defects in the per-shape records, fixed here by one
rule `state.Record` now states: a record that arbitrates between the Leaves on
the machine (a claim with its session's lifecycle, a page's service, a grant,
the Codex adapter's) holds while a file of any shape of it stands, without
being read, and the acts that end one end it at every shape.

- A page whose claim or session lifecycle is at another shape reads as held
  (`service.held_at_another_shape`): a terminal's `page init`, another
  session's Leaf and a session-less `leaf wait` no longer take it or its input.
  A session that dies without ending stays holding its pages until a session
  takes them, as main documents for a newer Leaf's session.
- `leaf server stop` removes the service records of every shape on every pass,
  so a stop beside this shape's own stale record no longer waits forever on a
  server of another shape.
- Withdrawing a file or connection grant removes the grants records of other
  shapes whole, since this Leaf can't read which grants they hold.
- Another shape's Codex adapter reads as running with its transport unknown.
- SessionEnd and session retirement glob the session's files by its key, since
  `Path("<key>.").stem` keeps the dot below Python 3.14, which left every
  session's files in place on the system Python the SessionEnd hook runs.

`leaf page list` no longer scans the state home for other shapes: it cost every
call a walk of all of Leaf's modules and a parse of every record, and
state-home records are disposable. `page check` names the page directory's
records of other shapes through `Record.others`, with the drafts clause only
where a drafts record is among them; the eval case, rescored on Claude Code,
passed 3 of 3 on this tree and on the merge base. The website publishes only
this shape's grants and data files.

Tests: `test_record_shapes` covers a page held at another shape (lifecycle and
claim) and a withdrawal at every shape; `test_server_lifetime` covers a stop
beside another shape's server. Focused model and process tests pass on Python
3.14 and 3.12.

> _This was written by Claude Code on behalf of max-sixty_
# Conflicts:
#	src/leaf/harness.py
#	tests/model/test_hooks.py
@max-sixty max-sixty changed the title Keep each record shape in a file of its own, and leave other shapes for the agent Keep each record shape in its own file, and let any shape hold what it arbitrates Nov 25, 2026
leaf-agent
leaf-agent previously approved these changes Nov 25, 2026
…ts another version left

A second review of #7157 ran two cross-Leaf cases the hold rule got wrong:

- This shape's claim naming a session that ended hid a claim of another shape
  naming a live one, so this Leaf would re-initialize the page or hand a
  session-less `leaf wait` its input. `held_at_another_shape` now checks
  another shape's claim whenever this shape's claim isn't active.
- A takeover left the other shape's claim standing, so two sessions owned the
  page and both received its input. `publish_claim` now removes the claim's
  other shapes under the claims lock, as a stop and a withdrawal do.

Max's call through the coordinator: no shape-free "ended" marker for a session
that ended under the older Leaf. Its pages stay held for the newer Leaf until an
agent's session takes each over, and each refusal of a held page names that
takeover; `delivery ack`'s now does too.

`page check` names only a drafts store of another shape, the user's unsent
words, in place of a hand-kept list of seven page records; the rest are
disposable. The `serving-pages.md` paragraph goes: in both scorings, base and
head passed 3 of 3 with the finding's own words in the prompt, so it added
nothing, and the eval case goes with it, since without the finding in its prompt
it tests nothing. `delivery read` takes another shape's `since` from
`state.record_since`, the one reading of a shaped name beside `record_name`.

> _This was written by Claude Code on behalf of max-sixty_
leaf-agent
leaf-agent previously approved these changes Nov 25, 2026
… to what it removed

A third review of #7157 found two more cases where a reader missed the rule that
a claim of another shape holds the page, so who holds a page is now one
primitive, `service.page_holder`: this shape's live claim, a holder at another
shape named in words, or no one. Every reader that decides whether it may act
on a page someone else holds asks it: `held_elsewhere` (and through it
`refuse_held` and renewal), `may_receive`, `PageTransaction.watch_state` and a
session server's retirement. `PageTransaction.active_claim` stays the reading
of a reader acting for the claim's own session.

- A wait acting for no session now stops at a page held at another shape, as at
  one held at this shape, naming the holder and the takeover, rather than
  handing out a batch it can't acknowledge and handing it out again next time.
- A takeover's transition (`ClaimTransition`) carries the bytes of the claims
  of other shapes `publish_claim` removed, which a rollback writes back unread,
  so a Codex start whose offer fails leaves the other Leaf's session its page.
- The refusals of a held page name the takeover as run from an agent session.

> _This was written by Claude Code on behalf of max-sixty_
leaf-agent
leaf-agent previously approved these changes Nov 25, 2026
…for a Codex record at its own shape

CI on 18af799 ran two tests this branch edited without running:

- A data source's publication file a hand edit leaves as `{}` made
  `Record.read` raise, so `/api/state` answered 500, where main reads it
  as no publication and the widget recovers. `Record.read` again reads an
  object at its file without this shape's `format` as none.
- The Codex journey waited for a history record named with the delivery
  envelope's `since` rather than the Codex record's.

Four other journey failures in that run (the server row tests in
test_interact_server and test_render_controls) also fail on main at
118f31f: they serve a page a live session holds for no session, which
#7061's refusal turns away.

> _This was written by Claude Code on behalf of max-sixty_
@max-sixty
max-sixty merged commit d0bd795 into main Nov 25, 2026
5 of 6 checks passed
@max-sixty
max-sixty deleted the agent-a221b9209833519e9 branch November 25, 2026 23:50
max-sixty added a commit that referenced this pull request Nov 25, 2026
#7157 changed the claim code and `PageTransaction` that this branch moves
out of `service`. Each change goes to its home under the split:

- `service` keeps `publish_claim` (which now returns the bytes of the
  claims of other shapes it removes), `page_holder`, `may_receive`'s new
  page argument, `held_elsewhere`'s holder words, `refuse_held`,
  `claim_records` and `PREVIEW`, which #7157 moved here from `server` so
  the hooks can ask whether a page carries a preview.
- `transaction` takes `ClaimTransition`, the rollback record of a claim's
  publication, with `PageTransaction.holder`, `publishing_claim`,
  `restore_claim` (which writes back the displaced claims), `watch_state`
  and `note_messaged` as #7157 left them, and `take_page_claim` and
  `restore_page_claim` returning and taking a `ClaimTransition`.

`page-storage.md` names `service.PREVIEW`. Tests and dev code that #7157
changed follow the moved names. The import-linter allowances go from
main's 40 to 35.
max-sixty added a commit that referenced this pull request Nov 26, 2026
The move is generated, so rather than resolve the service split's new merge of main
(#7157) by hand, this records the split's head as a parent and reruns the codemod on its
tree. #7157 moved `PREVIEW`, with its read of the served-state schema, from `server` to
`service`, so the path patch follows it to `base/service.py`.
max-sixty added a commit that referenced this pull request Nov 26, 2026
#7158)

This PR splits the page transaction out of `service`. `service` was
doing two jobs that sit at different heights in `src/leaf`'s import
order. Low-level readers such as `page_inputs`, the sandbox bridge,
`codex_state` and `activity` need its page claims. Its `PageTransaction`
needs `event_log`, `interaction_log`, `harness`, `activity`,
`event_contracts` and `revisioning`. The order therefore put `service`
below the event log, and import-linter allowed six backward imports from
it. After the split, the count drops from 40 to 35.

- **New module, `transaction`.** It takes `PageTransaction` and the
claim changes made through one (`take_page_claim`, `claim_page`,
`restore_page_claim`, and `ClaimTransition`, the record a failed claim's
rollback restores from). It also takes `owned_pages`, `commit_provider`
and the acknowledgement cursor (`acknowledged`, `unacknowledged`,
`requires_agent_attention`). In the order it stands just above
`activity`.
- **What `service` keeps.** The page claims with `page_holder`,
`session_lives`, the stream record (`STREAM`) and `PREVIEW`.
- **Log helpers made public.** The transaction holds the log's lease,
which serializes claim changes, the stream, the commit provider's
publish and appends. So the three `event_log` helpers it calls are the
log's interface for whoever holds that lease, and they lose their
underscores: `end_last_line`, `append_event_unlocked` and
`matching_attempt`.
- **`set_status` moves to `session`.** `PageTransaction.set_status`
becomes `session.set_status(page, state)`, since a declaration is
appended through admission, which takes the transaction. The transaction
keeps `clear_stream()` for `idle`.
- **`delivery_turn` reads through `presence`.**
`codex_state.delivery_turn` now calls `presence.session_turn_running`,
so `codex_state` doesn't import the transaction above it.
- **One allowance added.** `transaction -> revisioning` closes a real
cycle. A transaction finishes an interrupted publication before
admitting a reader, and finishing one appends through admission under
that same transaction. The `transaction.py` header says so.

Most of the 116 files only change an import from `service` to
`transaction`. The substance is in `transaction.py`, `service.py`,
`session.py`, `presence.py`, `codex_state.py` and `event_log.py`. The
cold hooks import the same modules as before, plus `transaction`, and
`import leaf.hooks` takes the same time within noise.

Checks: pre-commit passes, ty and import-linter included. The focused
model and process tests for claims, activity, receipts, session
lifecycle, delivery, hooks, the Codex adapter and App Server, the Stop
guard, forks, the interact contract and the website server pass. Main,
with #7157, is merged in, and #7157's changes to the moved code are
ported to `transaction.py`.

> _This was written by Claude Code on behalf of max-sixty_
max-sixty added a commit that referenced this pull request Nov 26, 2026
`src/leaf`'s modules move into eight layer packages, each holding one
concern: `commands`, `pages`, `serving`, `agents`, `records`, `log`,
`source` and `base`, top to bottom. Each package's `__init__.py` says
what it holds. import-linter's contract names the packages in place of a
flat order of modules: a module may import its own package and the
packages below it, and 13 imports that point up across packages are
allowed by name.

Those 13 are 7 of the flat order's 35 allowances and 6 imports that
pointed down in the flat order but point up between the packages their
modules now sit in, such as `base.leases` importing the kernel's
protocol from `source.registry.kernel`. Each of the 6 is a module placed
by its concern at the cost of one allowance; cutting them is follow-up
work, as the splits before this did. Of the other 28 old allowances, 21
fall inside one package, where the contract no longer checks direction,
and 7 now point down.

The maintainer chose packages over naming the layers in the config or
keeping the flat order. Before the move I tested the packages two ways
beyond the import graph:

- A reader given only each package's line and each module's docstring
put 78 of the 107 modules in the package this PR puts them in. Moving 27
of the other 29 to the reader's package would add between one and
thirteen backward imports.
- Over the 526 commits on `main` since 1 October, 20% of the co-change
between modules falls inside a package, against 13% for random packages
of the same sizes (p < 0.0001). Packages drawn from co-change would hold
65% but leave 127 backward imports, since Leaf's changes cut across
layers: the median PR touches two of these packages.

A script generates the diff. ruff's TID252 fix makes `src/leaf`'s
relative imports absolute. The script then moves each module with `git
mv`, and in every tracked text file it rewrites the module's dotted name
(in imports, strings and comments), `from leaf import <module>`, and its
path. It also deepens the relative paths in moved files that climb to
the repository's top. Everything else is renames and rewritten import
lines, so review these:

- `.config/importlinter.ini`, `src/AGENTS.md` and `base/harness.py`'s
header;
- the eight `src/leaf/*/__init__.py` headers;
- the paths code computes from a moved module's file: `base/state.py`,
`agents/codex_tool.py`, `base/service.py`, `records/activity.py`,
`base/rows.py` and `pages/packages.py`, with `dev/leaf_dev/docs.py`,
`.config/knip.js`, `tests/process/test_bridge.py`,
`tests/model/test_interact_layer.py` and
`tests/model/interact_contract/test_layer_contract.py`.

The branch is regenerated on `main`, which now holds #7157 and #7158,
rather than merged with it: its last commit takes `main` as a parent and
reruns the script on `main`'s tree. Each Python PR still open when this
lands needs `main` merged in, and its new imports of moved modules
renamed. The Python that `leaf-dev`'s evals run inside an arm's own
checkout, such as its cleanup, imports modules by their new paths, so an
arm pinned to a revision before this move can't run it.

Tests: pre-commit (ruff, ty, import-linter, vulture, knip), `pnpm run
check`, an import of every module, and 2,533 tests that read `src/leaf`
by path or import most of it, run locally.

> _This was written by Claude Code on behalf of max-sixty_
max-sixty added a commit that referenced this pull request Nov 26, 2026
…7199)

`main` fails five journeys in `tests/journeys/test_codex_adapter.py`
since #7157, which stores each record shape in a file of its own
(`<id>@<since>.json`). These tests still read and wrote Codex delivery
records at their bare paths: the two restarts read None where they edit
a record in place, and the two receipt recoveries find no queued record.
They now go through `codex_model.RECORD.read` and `RECORD.write`, which
name the shape's file and supply its `format`. Test-only; no behaviour
changes.

I merged #7157 on the maintainer's go-ahead, and this repairs what it
left failing. The five tests pass locally.

> _This was written by Claude Code on behalf of max-sixty_
max-sixty added a commit that referenced this pull request Nov 26, 2026
)

Four journeys fail on `main` since #7061, which refuses a server start
that takes no claim on a page another live session holds
(`service.refuse_held`). Each recorded a live claim on a neighbour page
and then started its server for no session, so it raised `StartRefused`
at setup. #7061's CI missed it because `--changed-since` adds a
later-tier test only when the test's own function changes, and #7061
changed none of these four; #7157 edits lines inside them, so its run
selected them and they failed.

Each test now starts, revives or restarts the server with the harness
the claim names (`harness.claim_harness`), as the holding session's own
Leaf does in use and as the `live_leaf` fixture already does. No
assertion changed, and the refusal stays as it is. A scan of
`tests/journeys`, `tests/smoke`, `tests/browser` and `dev/tests` for
other tests that write a live claim and then start, restart or re-init
the page for another session found no others; browser tests serve
through `TemporaryPageServer`, which the refusal doesn't reach.

Tests: the four failed locally on `main` with the refusal and pass with
this change.

> _This was written by Claude Code on behalf of max-sixty_
max-sixty added a commit that referenced this pull request Nov 26, 2026
…n at (#7198)

leaf.page's session object kept one drafts store per page, keyed by the
page's root alone, and a container's restore wrote whatever store it
received as its own `drafts@<since>.json`. `DRAFTS.since` moves without
a protocol bump whenever the drafts record changes shape at a later
protocol (`src/leaf/layer-registry.md`, "Page protocol"), and the
session object is keyed only by protocol and store format, so the first
release after such a change would read the previous release's stores as
its own shape and could lose or misread a visitor's unsent words.

**Reproduced on main.** A scratch probe on the process tier's page-store
double wrote a draft at `leaf-drafts/51`, then restored the page with
`DRAFTS.since` set to 57 (the current protocol, so no bump). The store
came back as `[email protected]` stamped `leaf-drafts/57`, and
`read_drafts` served it as the new shape. The new Worker test below
fails against main's `storage.ts` for the same reason: a release at
another drafts format receives the earlier format's store in its restore
snapshot.

**The change.** The site manifest now carries the release's
`DRAFTS.format` as `drafts_format`, and the `leaf_drafts` table is keyed
by root and format. A release reads and replaces only the stores at its
own format, as a local Leaf reads only its own shape's file since #7157.
After a shape change a page starts with no saved drafts (an open tab
still saves the words it holds once the visitor acts, as after a
protocol bump), and a release back at the earlier shape, such as a
rollback, finds that store as it was left. Nothing reads another shape's
store, and no store is migrated. The container code is unchanged: every
page-store request and every saved response the session object serves
comes from or for the manifest's release.

The table change moves `STORE_FORMAT` to 2. As a protocol bump does,
that starts every visitor on the published page at the deploy that lands
this.

Net lines: production code +6, comments +11, tests +43, prose +1.

**Verified.**
- `worker/test/storage.test.ts`, "reads and replaces only the drafts
stores written at its own drafts shape": a store saved at one format is
neither restored nor a reason to turn a save away at another, and is
restored again at its own. Fails against main's `storage.ts`.
- `pnpm run check` passes.
- `tests/process/website_server/test_saved_records.py` and
`dev/tests/process/test_website_server.py` pass.
- Edited but not run locally: `tests/journeys/test_site.py`, which now
asserts the built manifest's `drafts_format`.

> _This was written by Claude Code on behalf of max-sixty_
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