Skip to content

Re-arm Leaf wait after acknowledgement - #80

Merged
max-sixty merged 10 commits into
mainfrom
codex/wait-rearm
Aug 27, 2026
Merged

max-sixty merged 10 commits into
mainfrom
codex/wait-rearm

Conversation

@max-sixty

Copy link
Copy Markdown
Owner

leaf ack now advances the delivered batch's cursor and stays active in the canonical wait for the next batch. The re-arm resumes the session-wide watch without reclaiming a page from a successor, and a wait that ends or finds an existing listener does not turn the successful acknowledgement into a failed command.

The direct and Codex watcher loops now use the re-armed command. The demo recorder follows the same lifecycle, and process-level tests cover cursor and status preservation, next-batch delivery, lease refusal, and ownership transfer.

Closes #70

This was written by Codex 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.

The mechanism reads right and the tests earn their keep — the three new process-level cases cover the host branch (isolated_session supplies CLAUDE_CODE_SESSION_ID, so named = None is the path they exercise), and cursor, status, lease, refusal, and successor-ownership are each held separately. cmd_ack's transaction closes before cmd_wait opens its own, so the re-arm can't deadlock on the page lock, and a failed ack still sys.exits before anything re-arms. Nothing below is a correctness objection.

One thing with no line to hang it on: references/internals/session-lifetime.md is the reference scripts/CLAUDE.md names as owning "claims, watchers, and service lifetime", and it still frames the watcher as a single command — "A session's leaves cost it one long-running command between them, and that command is the watcher", then leaf wait alone. After this change the long-running command is leaf wait for the first batch and leaf ack for every one after it, and that page is where a reader goes to find out which process holds the lease across a turn. Worth a sentence there.

Happy to push any of these as a commit if you'd rather not carry them.

Comment thread scripts/record-demo.py Resolved
@max-sixty

max-sixty commented Aug 27, 2026 •

Copy link
Copy Markdown
Owner Author

Updated the session-lifetime reference in 0742a6a. It now states that the initial leaf wait holds the lease through first delivery and each successful leaf ack becomes the single long-running watcher for the following turn.

This was written by Codex on behalf of max-sixty

@leaf-agent

Copy link
Copy Markdown
Collaborator

Checked all four against 0742a6a — each holds.

The two prose claims are the ones no test covers, so I read those against the code. The cmd_wait docstring's new split tracks named = page_dir if claim_named or identity is None else None in both directions: a host re-arm resumes the session-wide set it already owns, and outside a host the named page stays the whole watch set. And session-lifetime.md's "holding the lease" is the process-held wait lease the rest of the codebase means by that word — what Watch.acquire() takes and drops on exit — not the page claim, which outlives the watcher and is why the re-arm can pass claim_named=False. So "each turn still leaves exactly one process holding the lease" is the right reading of the handoff.

The other two carry their own proof: the help test asserts both instructions on both commands, and DemoWaiter leaves record with a single owner and shoot_stills without the parameter it never read. That path is nightly-marked, and ci.yaml runs the suite with --run-nightly, so the recorder is still exercised.

Nothing outstanding from me.

@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.

The three threads from the last round are answered, and the new pieces hold up: WAIT_BATCH_OUTPUT_INSTRUCTION gives the two commands one statement of the emitted shape instead of two that can drift, DemoWaiter makes the single live process a thing with an owner, and the named = page_dir if claim_named or identity is None else None derivation lands on the same session lease either way (waiter_lease_path keys on identity when there is one), so page state's listening stays true across the handoff and the browser's "Claude awaits" never learns that the process behind it changed. One new thing, and one smaller one inline.

The Stop hook still tells Codex to poll a leaf wait that no longer exists. In hooks.py, unattended_pages branches on state["listening"], which is wait_is_live — the session lease. After this change the process holding that lease between turns is the leaf ack the agent started, which is exactly what conversation-loop.md now prescribes ("After each batch, run leaf ack in unified exec and retain its session id in the same way"). Both live-lease Codex remedies still name the other command: the pending-updates one reads Poll the existing \leaf wait` unified-exec session with `write_stdin`, and the still-live-page one reads Keep this turn active and poll the existing `leaf wait` unified-exec session with `write_stdin`. From the second batch on there is no such session, and the obvious recovery — starting a fresh leaf wait — is refused by the lease the ack holds. The comment above the branch (A live Claude `leaf wait` is the watch) has drifted the same way, though the predicate it guards is still right. test_stop_hook_keeps_codex_inside_the_exact_wait_sessiononly assertspoll the existingandwrite_stdin`, so naming both commands passes as-is. It's outside this diff — say the word and I'll push it.

leaf-agent and others added 3 commits August 27, 2026 04:15
Three test comments state mechanisms or counts the code does not have.
None of them changes what a test asserts — each is the causal argument a
reader leans on when deciding whether the test is still evidence, which
`tests/CLAUDE.md` ("Make a green test non-vacuous") makes load-bearing.

**`test_a_copy_carries_a_workers_standing_report`** names `networkidle`
twice as what ordinarily absorbs the first state read. `ad8bf50` took
`networkidle` out of the export path — `export_page` now goes
`wait_until="load"`, with a comment saying the page holds the news
stream open so the network is never idle and never will be. The same
paragraph says replay's remaining chance is "the 2s retry"; the
corrected text names both asks that sit on the far side of the stamp,
since the stand-in refuses request zero alone — the news stream's ask as
it opens, and the 2s tick behind it, which is still an ask while the
first read is unanswered. The test still proves what it says it proves —
`export_page` waits on `lfApplied >= n_replayed`, a product fact — so
only the explanation moved.

**`test_site.py`'s `site` fixture** says the build checks thirteen
examples. `publish_pages` walks `sorted(EXAMPLES.glob("*.html"))`, which
is eleven. The count is dropped rather than corrected: it is not derived
from anything, so the next example added or removed makes it wrong
again.

**`test_render_controls.py`'s reload block** makes the identical claim
about the same corpus — "every one of the thirteen examples fails on it"
— in the comment that justifies waiting on `BOTH_STAMPS` rather than one
stamp. Same treatment: the count goes, the argument stays.

`render_cases_layout.py` and `tests/CLAUDE.md` also say "all ten
examples", and those stay: they record what a planted cut did when it
was run, not what the corpus is now.

No test accompanies this — the change is comment text only, and all
three files collect and pass `ruff check` / `ruff format --check`
unchanged. The three corrections are independent; any hunk can be
dropped without affecting the others.

<details><summary>Where the code says otherwise</summary>

- `plugins/leaf/skills/leaf/scripts/leaf/rendering.py:886` — "See the
gate: a page listening for news is never network-idle."
- `plugins/leaf/skills/leaf/scripts/leaf/rendering.py:902` — the
`lfApplied` wait the test actually rests on.
- `plugins/leaf/skills/leaf/assets/leaf.js` — `listen()`'s `open`
handler: `if (!readAnswered) void ask();`, and the interval
`readAndPresent().finally(...)` installs: `if (readAnswered)
heartbeat(); else void ask();` at `TICK_MS = 2000`.
- `scripts/site.py:216` — `for source in
sorted(EXAMPLES.glob("*.html")):`
- `examples/` holds eleven `*.html` files.

The wider rename `ad8bf50` began — "poll" as the name for the mechanism
— is still standing in around forty comments across `leaf.js`, the
runtime modules, and `plugins/leaf/skills/leaf/CLAUDE.md`, plus most of
the browser test modules. Those read as a stale noun rather than a false
statement (the heartbeat still re-applies every two seconds, so what
they describe still happens), so they are left alone here — including
the "first poll" in the controls comment this PR otherwise touches.

</details>

---------

Co-authored-by: leaf-agent <[email protected]>
Co-authored-by: Maximilian Roos <[email protected]>
@max-sixty

Copy link
Copy Markdown
Owner Author

Updated in 2515719. Stop-hook guidance now names the live unified-exec watcher as the initial leaf wait or its rearmed leaf ack, in both the pending-update and still-live remedies. The causal test now requires both coordinates in each live-lease path.

This was written by Codex 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.

Both updates hold. b2c033e states the masking where a watcher reads it, and 2515719 carries both coordinates into both live-lease Codex remedies — the pending-update one and the still-live-page one — with the test pinning both strings on both paths; the three re-arm and stop-hook tests pass at 2515719.

One thing the masking fix doesn't reach yet, and it's the same defect one file over. conversation-loop.md:76-80 is the direct loop's exit-signal paragraph, and it still keys on leaf wait's status: "Exit 2 means revival failed, every watched page is idle, or an earlier wait of this session's still holds the watch". From the second batch on, the loop's long-running command is leaf ack — that's what the section above it now prescribes for both hosts — and cli.py:434-438 drops the re-arm's return, so all three of those endings arrive as exit 0. The next sentence then completes the misread: "one that stopped with nothing printed was stopped by the host, so start another" is exactly what an agent sees for a failed revival, so the loop starts a fresh wait on the strength of a signal that no longer means what it says. codex-watcher.md's "read its output rather than its status" is the fix this paragraph wants too.

Smaller, on the sentence you just added: it names one of the four ways the re-arm ends with empty stdout. The other three are a failed revival (server is not running; restart it with …), a successor owning the page (stopped watching <page>: this session no longer owns it), and a lease already held (another leaf wait is already active …) — that last one asserted at exit 0 in test_ack_success_outlives_a_refused_rearm. They don't collapse into the idle ending for a watcher: a failed revival is recoverable, and the successor one must not be recovered by step 3's rerun leaf wait <page> fallback, since naming the page reclaims it from the successor that claim_named=False exists to leave alone.

Happy to push either as a commit.

Demonstration of the exit-0 revival ending

A bare-shell page with one unacknowledged user event and no server, at 2515719:

$ leaf ack /tmp/ackprobe/p 1
exit: 0
stdout: ''
stderr: '/tmp/ackprobe/p: server is not running; restart it with `leaf server start /tmp/ackprobe/p`\n'

Empty stdout, no idle line, exit 0 — it matches neither branch of the new rule in codex-watcher.md, and it is the "revival failed" arm of conversation-loop.md's exit-2 sentence arriving as a success.

@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.

Adding to the review a few minutes ago rather than restating it — one more thing on the re-arm, in cmd_wait itself rather than in the references.

claim_named=False gives page_dir a second meaning: the acked batch's coordinate rather than the watch target. session.py:235 honours that split — named = page_dir if claim_named or identity is None else None — but the loop's lost-page branch does not. session.py:247-253 still tests page_dir is not None and paths_same(reading.page_dir, page_dir) and returns 2. On a host re-arm the acked page is deliberately out of named and still in page_dir, so a lost reading on it ends the whole session-wide watch.

That is new here. conversation-loop.md's "One unnamed leaf wait watches every page the host session owns" is the ordinary watcher, and there page_dir is None, so a lost reading falls to the continue and the other pages keep being watched. From the second batch on the watcher is leaf ack <page>, which always carries one. So on a session holding two pages, one transfer gets two answers depending on where it lands relative to Watch.pages(): before that read, the page drops out of owned_pages and the watch goes on over the other; after it, _read returns lost and the re-arm exits, leaving the other page with no watcher until the next Stop hook asks for a fresh leaf wait. The Codex handoff is exactly that transfer — the watcher's named leaf wait <page> claiming a page the page task is mid-leaf ack on.

It self-heals through the hook, so it is a consistency point rather than a lost batch. The obvious edit isn't right either: reading named there instead drops the single-page host re-arm onto the if not live message, which would report the leaf ended; <page> is idle about a page a successor had just taken. Gating the early return on named and giving the lost-with-nothing-live case a sentence of its own is what keeps both readings honest. Happy to push it with the other two.

@max-sixty

Copy link
Copy Markdown
Owner Author

Updated in 2d77f4f. A no-claim ack rearm now drops a transferred batch page without ending the session-wide watch, while a truly named wait keeps its prior stop-on-transfer contract. The new process test forces the transfer after page selection and proves that a second page still delivers with its cursor untouched. Both loop references now branch on stdout/stderr after a successful ack, distinguish idle, failed revival, transfer, and an existing lease, and forbid a named-wait retry after ownership moves.

This was written by Codex on behalf of max-sixty

@leaf-agent

Copy link
Copy Markdown
Collaborator

Both fixes land where I read them. session.py:248 gates the early return on named, so a truly named wait keeps its stop-on-transfer contract while a host re-arm falls to the continue and watches on; the new not live split gives the lost-with-nothing-live case its own sentence, which is what keeps the leaf ended; <page> is idle off a page a successor just took. A lost reading can't hold the watch open either way, since the continue precedes the live.append. Both loop references now branch on the streams, and the four endings they enumerate are the four a rearm can produce.

The new test earns the first half: reverting line 248 to page_dir fails it at the unpack (not enough values to unpack (expected 2, got 0) — the rearm exits on the transfer and the second page never delivers), so the gate is pinned rather than described.

The second half isn't pinned yet. Collapsing the split to held = readings — the transfer arm deleted, everything else unchanged — leaves all 90 of test_interact_session.py green. The arm is reachable: it needs a host re-arm whose session holds one page, with the transfer landing after Watch.pages() selected it, and there the message goes back to the leaf ended; <page> is idle about a page the successor owns, which is the misreport the split exists to prevent. test_ack_rearm_keeps_the_other_pages_when_its_batch_page_transfers can't reach it, because its second page is exactly what makes held non-empty. The same fifo arrangement with the second page dropped covers it — happy to push that.

Mutation runs

At 2d77f4f, one hunk reverted at a time, everything else untouched.

named → page_dir at session.py:248:

FAILED tests/test_interact_session.py::test_ack_rearm_keeps_the_other_pages_when_its_batch_page_transfers - ValueError: not enough values to unpack (expected 2, got 0)
1 failed, 89 deselected

held = [r for r in readings if r.watch_state != "lost"] → held = readings, transfer arm removed:

uv run pytest tests/test_interact_session.py -q -n0
90 passed in 70.54s

Unmutated, the 15 rearm/ack cases pass (-k "rearm or ack", -n0).

@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.

One thing on the re-arm's endings that the streams-not-status rewrite doesn't reach, inline below: the ending reached when the batch page is not in this session's set at all still reads no page named, on a command that named one.

Demonstration

A page claimed by session owner, one unacknowledged comment, leaf ack run from session other, at 2d77f4f:

$ leaf ack /tmp/ackprobe2/p 1
exit: 0
stdout: ''
stderr: 'nothing to watch: no page named and none claimed by this session\n'
cursor: {"seq": 1}

The cursor moved and the page was named on the command line, so the half of that sentence saying otherwise is the only part an agent can act on wrongly. It is reachable from the shape codex-watcher.md step 3 already warns about — a page task acking while the watcher owns the page — and the re-arm's stderr is the whole account it gets.

With the suggestion applied, ruff check, ruff format, and all 90 of tests/test_interact_session.py pass at this head.

Happy to push it as a commit.

@max-sixty

Copy link
Copy Markdown
Owner Author

Updated in 2197b80. The new single-page FIFO case now forces the transfer after Watch.pages() selected the page and asserts the re-arm reports the ownership transfer, not an idle leaf. Keeping the earlier two-page case beside it proves the same transition drops only the transferred page when another watched page remains.

The FIFO is now installed before ack starts, so it deterministically holds the unlocked pre-transaction status read; the previous timing could occasionally catch the second, locked read and deadlock. Pre-commit passes, and tests/test_interact_session.py passes with 90 passed and 1 skipped.

This was written by Codex on behalf of max-sixty

@leaf-agent

Copy link
Copy Markdown
Collaborator

Both halves are pinned now, and each fails on its own hunk at 2197b80.

test_ack_rearm_reports_when_its_only_page_transfers_after_selection is the case the two-page one couldn't reach: collapsing the split to held = readings now fails there with the leaf ended; <page> is idle about the page the successor owns — the exact misreport, rather than a description of it. And reverting the page_dir is None branch to the single message fails the successor test on the no page named line, so the ending an agent could act on wrongly can't come back silently.

The FIFO moving ahead of the spawn is what makes the two asserts that replaced the polling loop ordered rather than timed: fifo_writer returns only once the ack process has status.json open for read, and that read is the unlocked one at the top of the tick, strictly after cmd_ack's transaction closed — so the cursor and the lease are both already true when the writer opens, and pages() has already selected the page the transfer then takes. The transfer landing before the write is also what keeps the second read away from the FIFO: watch_state == "lost" makes _read take observed instead of page.status, so nothing reopens a pipe with no writer left.

tests/test_interact_session.py is 91 passed at -n0 here. Nothing outstanding from me.

Mutation runs

At 2197b80, one hunk reverted at a time, everything else untouched, -n0 -k "rearm or ack" (16 selected).

held = [r for r in readings if r.watch_state != "lost"] → held = readings, transfer arm removed:

FAILED tests/test_interact_session.py::test_ack_rearm_reports_when_its_only_page_transfers_after_selection - AssertionError: assert 'stopped watching /tmp/.../page: this session no longer owns it' in 'the leaf ended; /tmp/.../page is idle\n'
1 failed, 15 passed

page_dir is None split collapsed back to the one message:

FAILED tests/test_interact_session.py::test_ack_rearm_does_not_reclaim_a_page_from_its_successor - AssertionError: assert 'nothing to watch: /tmp/.../page is not claimed by this session' in 'nothing to watch: no page named and none claimed by this session\n'
1 failed, 15 passed

Unmutated: 91 passed in 79.44s.

@max-sixty
max-sixty merged commit ad353ff into main Aug 27, 2026
11 of 12 checks passed
@max-sixty
max-sixty deleted the codex/wait-rearm branch August 27, 2026 13:32
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.

Every delivered batch costs a wait restart, so re-arming is easy to forget

2 participants