Skip to content

Commit 4591cfd

Browse files
committed
Extract page presence readings
Move claim, viewed-state, neighboring-leaf, and presence-fingerprint readings out of browser state projection. Point HTTP, agent state, and tests directly at the new presence owner.
1 parent fdb8b0a commit 4591cfd

7 files changed

Lines changed: 192 additions & 182 deletions

File tree

‎plugins/leaf/skills/leaf/scripts/CLAUDE.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,8 @@ The main owners are:
2121
- `service`: page claims, serialized transactions, and leases;
2222
- `server` and `hosting`: server address and lifetime state, and the HTTP process;
2323
- `session` and `hooks`: wait delivery and host lifecycle;
24-
- `served_state` and `http`: browser-facing state readings and HTTP transport;
24+
- `presence`: page, claim, and neighboring-leaf presence readings;
25+
- `served_state` and `http`: browser-facing state projection and HTTP transport;
2526
- `registry/`: registry storage plus shared, layer-wide, widget, and state
2627
vocabulary contracts;
2728
- `layer`: package discovery, composition, and commands;

‎plugins/leaf/skills/leaf/scripts/leaf/agent_state.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
version_descriptors,
2121
)
2222
from .passages import enclosing_of, page_passages
23+
from .presence import presence
2324
from .projection import (
2425
StateProjection,
2526
canonical_updates,
@@ -29,7 +30,6 @@
2930
)
3031
from .registry import described, require_registry
3132
from .revisioning import activate_source
32-
from .served_state import presence
3333
from .server import running_server
3434
from .service import PageTransaction, unacknowledged
3535
from .thread_context import thread_digest

‎plugins/leaf/skills/leaf/scripts/leaf/http.py‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
from pathlib import Path
1010
from urllib.parse import parse_qs, urlsplit
1111

12+
from . import presence as presence_model
1213
from . import served_state
1314
from .event_endpoint import EventEndpoint, event_rejection
1415
from .event_log import read_events
@@ -154,11 +155,11 @@ def page_state(self, view_revision: int | None = None) -> dict:
154155
# reaches neighbouring pages without creating another authorization path.
155156
# Scan neighbours after releasing this page's lease: they are independent
156157
# snapshots, and one slow neighbour must not block this page's writers.
157-
state["others"] = served_state.other_leaves(self.page_dir)
158+
state["others"] = presence_model.other_leaves(self.page_dir)
158159
state["reading"] = (
159160
reading
160161
+ "."
161-
+ served_state.presence_fingerprint(
162+
+ presence_model.presence_fingerprint(
162163
state["listening"], state["session_alive"], state["others"]
163164
)
164165
)
@@ -190,7 +191,7 @@ def page_browser_view(self, view_revision: int, through_seq: int) -> dict:
190191
events,
191192
view_revision,
192193
active,
193-
served_state.presence(self.page_dir, events)["claims"],
194+
presence_model.presence(self.page_dir, events)["claims"],
194195
source_overrides,
195196
include_active_view=False,
196197
)
@@ -275,7 +276,7 @@ def _news(self):
275276
# the next look would leave the tab holding a reading this stream
276277
# never disagreed with, and never spoke again.
277278
if files != files_said or now - looked >= PRESENCE_S:
278-
presence = served_state.presence_reading(self.page_dir)
279+
presence = presence_model.presence_reading(self.page_dir)
279280
looked = now
280281
reading = f"{files}.{presence}"
281282
# Before the word goes out, so a listener that has heard the first
Lines changed: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,167 @@
1+
"""Page and neighboring-leaf presence readings."""
2+
3+
import hashlib
4+
import json
5+
from pathlib import Path
6+
7+
from .event_log import read_cursor, read_events
8+
from .files import latest_revision, list_revisions, read_json
9+
from .host import state_home
10+
from .server import running_server
11+
from .service import (
12+
claim_is_active,
13+
claim_records,
14+
claim_update_sources,
15+
page_claim,
16+
unacknowledged,
17+
wait_is_live,
18+
)
19+
from .structure import parse_revision
20+
21+
22+
def other_leaves(page_dir: Path) -> list:
23+
"""The machine's other live leaves, for the banner's panel: each page
24+
whose server is up, as a title, its handover URL, and the same presence
25+
facts the page ships about itself — so a row there and the banner above it
26+
are the one judgment reading the one shape.
27+
28+
Candidates are the conventional pages/ home and every claim record, which
29+
is what finds a page served from a session's scratch directory. Released
30+
and dead claims stay useful here as provenance. Liveness is the held
31+
server.lock lease, the same answer `running_server` gives everything else,
32+
and the URL is the one in durable service state, key included. The title is the
33+
active revision's — the document that page's own root URL answers with —
34+
read the way `transcript` reads it.
35+
36+
The whole scan runs on every /api/state; what it reads of each neighbour is
37+
kept per file, so a state read costs the scan and the presence reads rather than a
38+
parse of every live neighbour's page (`parse_version`)."""
39+
candidates = []
40+
pages = state_home() / "pages"
41+
if pages.is_dir():
42+
candidates += (d for d in pages.iterdir() if d.is_dir())
43+
candidates += (Path(claim["page"]) for claim in claim_records())
44+
others = []
45+
seen = {page_dir.resolve()}
46+
for candidate in candidates:
47+
candidate = candidate.resolve()
48+
if candidate in seen or not candidate.is_dir():
49+
continue
50+
seen.add(candidate)
51+
# A neighbour's fault stays its own. This is the one read of state some
52+
# other page owns: a directory deleted mid-scan (stale pages are deleted
53+
# and made again) or a log a disk fault corrupted would otherwise 500
54+
# every open page's state read on the machine, blaming the page that asked.
55+
try:
56+
info = running_server(candidate)
57+
if not info:
58+
continue
59+
events = read_events(candidate)
60+
if not list_revisions(candidate):
61+
continue
62+
revision = latest_revision(candidate)
63+
parser = parse_revision(candidate, revision)
64+
present = presence(candidate, events)
65+
except Exception: # noqa: BLE001, S112 - whatever shape its fault takes
66+
continue
67+
others.append(
68+
{
69+
"title": parser.title.strip() or candidate.name,
70+
"url": info["url"],
71+
**present,
72+
}
73+
)
74+
return sorted(others, key=lambda entry: entry["title"].lower())
75+
76+
77+
def presence(page_dir: Path, events: list) -> dict:
78+
"""What a seat showing this page says about it: the agent's claim, everything
79+
the directory holds that can answer for it, and where that agent is working.
80+
One gatherer for every such seat — `full_state` spreads it into the page's own
81+
state answer, and `other_leaves` attaches it to each entry — so the runtime's one
82+
claim-against-proof judgment reads the same fields whichever page it judges,
83+
and the tray's account of a neighbour is the account this page gives of
84+
itself."""
85+
# A file that isn't there stands in as its whole record, so every read below
86+
# indexes rather than asking twice whether the field arrived.
87+
stored_status = read_json(page_dir / "status.json") or {
88+
"state": "idle",
89+
"detail": "",
90+
"ts": None,
91+
}
92+
status = {key: value for key, value in stored_status.items() if key != "work"}
93+
claim = page_claim(page_dir)
94+
active = claim if claim_is_active(claim) else None
95+
# What the wait owner has acknowledged after the complete batch reached its
96+
# next durable consumer. An action past this seq has not reached that point,
97+
# which lets the runtime carry it forward onto versions written without it.
98+
cursor = read_cursor(page_dir)
99+
return {
100+
"status": status,
101+
"claims": claim_update_sources(stored_status, events),
102+
"listening": wait_is_live(page_dir, active),
103+
"cursor": cursor,
104+
# The reader's number, not the watcher's: their own messages the agent
105+
# hasn't taken in. Reports ride the same cursor but are the agent's debt,
106+
# so the banner never tells a reader that a worker's news is waiting on them.
107+
"pending": sum(
108+
1 for e in unacknowledged(events, cursor) if e["author"] == "user"
109+
),
110+
"agent": claim.get("agent", "Claude") if claim else "Claude",
111+
# The claimant's host program, for behavior that keys on it — the display
112+
# name above is anyone's to choose, so nothing may dispatch on it.
113+
"host": claim.get("host") if claim else None,
114+
# None when nothing claimed the page — interact.py run outside an agent host.
115+
"session_alive": active is not None if claim else None,
116+
# Which session the turn-closed evidence belongs to. Thread updates carry
117+
# their posting session too, so a delegate is not declared abandoned merely
118+
# because the orchestrator's turn ended under it.
119+
"claim_session": claim.get("id") if claim else None,
120+
# When the claiming session's last turn ended, or None while none has.
121+
# A `working` claim older than this is one that no turn and no delegate
122+
# renewed across the boundary — the same judgment the runtime's grace
123+
# makes, available at the moment it becomes true instead of a quarter of
124+
# an hour after it. Read with .get like the rest of the claim's fields,
125+
# since a record written before this existed is still a valid claim.
126+
"turn_closed": claim.get("turn_closed") if claim else None,
127+
# When a browser last held the page open (the server bumps viewed.json,
128+
# throttled, while a tab's news stream stands), or None for a page nobody
129+
# has ever opened — which used to be indistinguishable from one the user
130+
# studied and left.
131+
"viewed": (read_json(page_dir / "viewed.json") or {"t": None})["t"],
132+
# Where the claimant is working (claim_page), for the tray's hover: what
133+
# tells one leaf from another is the work behind it, and neither the title
134+
# nor the page directory says which that is. It outlives the session that
135+
# wrote it, as every other fact in this record does — a page the tray
136+
# calls unheld came out of somewhere, and that is still where it came from.
137+
# None for a page nothing ever claimed, which is the honest nothing.
138+
"session_cwd": claim.get("cwd") if claim else None,
139+
}
140+
141+
142+
def presence_fingerprint(listening: bool, session_alive, others: list) -> str:
143+
"""The half of a reading that file stamps cannot supply, from the facts a state
144+
already carries: the lease, the claimant's life, and the neighbours as the tray
145+
shows them. A neighbour's `viewed` is left out, since it moves every half minute
146+
that tab stays open and changes nothing this page shows."""
147+
facts = (
148+
listening,
149+
session_alive,
150+
[{k: v for k, v in other.items() if k != "viewed"} for other in others],
151+
)
152+
return hashlib.sha256(
153+
json.dumps(facts, sort_keys=True, default=str).encode()
154+
).hexdigest()[:8]
155+
156+
157+
def presence_reading(page_dir: Path) -> str:
158+
"""`presence_fingerprint` read fresh, for a stream between states. The three facts
159+
are read the way `presence` and `full_state` read them, so the stream and the
160+
state it prompts name the same reading."""
161+
claim = page_claim(page_dir)
162+
active = claim if claim_is_active(claim) else None
163+
return presence_fingerprint(
164+
wait_is_live(page_dir, active),
165+
active is not None if claim else None,
166+
other_leaves(page_dir),
167+
)

0 commit comments

Comments
 (0)