Skip to content

Commit 7892125

Browse files
committed
Name agent page state readings
1 parent be1c853 commit 7892125

1 file changed

Lines changed: 179 additions & 104 deletions

File tree

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

Lines changed: 179 additions & 104 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import json
44
from pathlib import Path
5+
from typing import NamedTuple, Protocol
56

67
from .data import measurement_lag_entries, page_data_binding_inventory, read_data
78
from .events import (
@@ -19,6 +20,7 @@
1920
)
2021
from .passages import enclosing_of, page_passages
2122
from .projection import (
23+
StateProjection,
2224
canonical_updates,
2325
decisions,
2426
page_asks,
@@ -61,55 +63,59 @@ def cmd_page_state(page_dir: Path) -> None:
6163
_write_page_state(page_dir, page.events, activation.error)
6264

6365

64-
def _write_page_state(
65-
page_dir: Path, events: list, source_error: str | None = None
66-
) -> None:
67-
"""Where the page stands, as one JSON object — the agent-side twin of the
68-
browser's /api/state, folded rather than raw. /api/state ships the log and
69-
lets the runtime replay it; a session picking a page up owes the same
70-
reading, and doing it in-head over `leaf events` is how a standing decision
71-
gets missed. So this prints the readings the runtime derives, from the same
72-
constructions it derives them with: the active revision's elements, the
73-
projection of the user's standing state and the reports standing on the agent
74-
channel, where the record lags either (`record_lag_entries`), authored
75-
measurements whose live source has run again (`measurement_lag_entries`), the
76-
open asks on the page and in threads (the banner's own count), each comment
77-
thread's exchange,
78-
and presence beside what answers for it. Computed on demand from the log,
79-
revision, registry, and source store — no derived reading is stored, so there
80-
is no second copy of the truth to reconcile.
66+
class _DocumentParser(Protocol):
67+
by_id: dict
68+
title: str
69+
lf_elements: list[dict]
8170

82-
Every markup-derived reading is of the latest valid revision, because that
83-
is the page the live root shows and the user acts on. An invalid source save
84-
appears only as `source_error` while that revision remains active."""
85-
registry = require_registry(page_dir)
86-
versions = version_descriptors(page_dir, events)
71+
72+
class _DocumentReading(NamedTuple):
73+
html: str
74+
parser: _DocumentParser
75+
projection: StateProjection
76+
spoken: dict
77+
78+
79+
def _active_revision(page_dir: Path, events: list) -> tuple[int | None, dict | None]:
80+
# Every markup-derived reading is of the latest valid revision, because that
81+
# is the page the live root shows and the user acts on.
8782
try:
88-
revision = latest_revision(page_dir)
89-
active = active_descriptor(page_dir, events)
83+
return latest_revision(page_dir), active_descriptor(page_dir, events)
9084
except SystemExit:
91-
revision, active = None, None
92-
pres = presence(page_dir, events)
93-
claims = pres.pop("claims")
94-
# The active page's readings, up front and through the one construction
95-
# (page_projection) every consumer of declared state reads, so the threads
96-
# settle against the same page the projection was built over rather than no page.
97-
parser, projection, spk = None, None, {}
98-
if revision is not None:
99-
html = revision_path(page_dir, revision).read_text(encoding="utf-8")
100-
projection, parser, spk = page_projection(html, events, registry, revision)
101-
threads = build_threads(events, enclosing_of(spk))
102-
stored_data = read_data(page_dir)
103-
state = {
85+
return None, None
86+
87+
88+
def _read_active_document(
89+
page_dir: Path, events: list, registry: dict, revision: int | None
90+
) -> _DocumentReading | None:
91+
if revision is None:
92+
return None
93+
html = revision_path(page_dir, revision).read_text(encoding="utf-8")
94+
projection, parser, spoken = page_projection(html, events, registry, revision)
95+
return _DocumentReading(html, parser, projection, spoken)
96+
97+
98+
def _base_state(
99+
page_dir: Path,
100+
events: list,
101+
source_error: str | None,
102+
versions: list,
103+
active: dict | None,
104+
presence_reading: dict,
105+
threads: dict,
106+
stored_data: dict,
107+
registry: dict,
108+
) -> dict:
109+
return {
104110
"page": str(page_dir),
105111
"title": "",
106112
"active": active,
107113
"versions": versions,
108114
"source_error": source_error,
109-
**pres,
115+
**presence_reading,
110116
# The watcher's number where `pending` is the reader's: everything a
111117
# wait would still print, workers' reports included.
112-
"unacked": len(unacknowledged(events, pres["cursor"])),
118+
"unacked": len(unacknowledged(events, presence_reading["cursor"])),
113119
"server": running_server(page_dir),
114120
"elements": [],
115121
"state": [],
@@ -124,79 +130,87 @@ def _write_page_state(
124130
# letting it answer one.
125131
# A reaction nobody has replied to opened no conversation: it is
126132
# paint on the page, and stands under `reactions` below.
127-
"threads": [thread_digest(t) for t in threads.values() if not bare_reaction(t)],
133+
"threads": [
134+
thread_digest(thread)
135+
for thread in threads.values()
136+
if not bare_reaction(thread)
137+
],
128138
# Every reaction still standing — the agent-side reading of the marks
129139
# the page paints, each explained (`means`) off this page's vocabulary.
130140
# On the page (`anchor`, or none for the page whole) while its thread is
131141
# unresolved; in a thread (`parent`) while that thread is open.
132142
"reactions": [
133143
described(
134144
{
135-
"id": m["id"],
136-
"token": m["token"],
137-
"anchor": m.get("anchor"),
138-
"about": m.get("about"),
139-
"parent": m.get("parent"),
145+
"id": message["id"],
146+
"token": message["token"],
147+
"anchor": message.get("anchor"),
148+
"about": message.get("about"),
149+
"parent": message.get("parent"),
140150
"thread": root,
141-
"revision": m.get("revision"),
142-
"seq": m["seq"],
151+
"revision": message.get("revision"),
152+
"seq": message["seq"],
143153
},
144154
registry,
145155
)
146-
for root, t in threads.items()
147-
if not t["resolved"]
148-
for m in t["msgs"]
149-
if is_reaction(m)
156+
for root, thread in threads.items()
157+
if not thread["resolved"]
158+
for message in thread["msgs"]
159+
if is_reaction(message)
150160
],
151161
"lag": [],
152162
}
153-
if revision is not None:
154-
byid = parser.by_id
155-
state["title"] = parser.title.strip()
156-
state["elements"] = [
157-
{
158-
"tag": r["tag"],
159-
"id": r["attrs"].get("id"),
160-
"line": r["line"],
161-
"thread": None,
162-
}
163-
for r in parser.lf_elements
164-
]
165-
state["state"] = [
166-
standing_entry(coordinate, e)
167-
for coordinate, (e, _) in projection.actions.items()
168-
]
169-
# An ask standing in a slot the log has retired — a group inside the lf-new
170-
# of a rejected suggestion — left the page with the slot, so it is nobody's
171-
# to answer; the passage reading already knows which ids a decision dropped.
172-
passages = page_passages(
173-
html, registry, decisions(projection.actions, registry)
174-
)
175-
state["asks"] = page_asks(
176-
parser,
177-
projection,
178-
byid,
179-
spk,
180-
registry,
181-
set(passages.retired) | set(passages.gone),
182-
# A session picking the page up wants the reader's list, so a request
183-
# whose own seat conversation is with this agent is not on it: the next
184-
# word there is owed by the agent, and the stop hook says so.
185-
seats_with_agent(threads),
186-
)
187-
state["lag"] = record_lag_entries(projection, byid, spk, registry)
188-
state["measurement_lag"] = measurement_lag_entries(
189-
parser.lf_elements, registry, stored_data
190-
)
191-
state["asks"] += thread_asks(
192-
events, registry, {rid for rid, t in threads.items() if t["resolved"]}
163+
164+
165+
def _apply_document_state(
166+
state: dict,
167+
document: _DocumentReading,
168+
threads: dict,
169+
stored_data: dict,
170+
registry: dict,
171+
) -> None:
172+
parser = document.parser
173+
projection = document.projection
174+
byid = parser.by_id
175+
state["title"] = parser.title.strip()
176+
state["elements"] = [
177+
{
178+
"tag": record["tag"],
179+
"id": record["attrs"].get("id"),
180+
"line": record["line"],
181+
"thread": None,
182+
}
183+
for record in parser.lf_elements
184+
]
185+
state["state"] = [
186+
standing_entry(coordinate, event)
187+
for coordinate, (event, _) in projection.actions.items()
188+
]
189+
# An ask standing in a slot the log has retired — a group inside the lf-new
190+
# of a rejected suggestion — left the page with the slot, so it is nobody's
191+
# to answer; the passage reading already knows which ids a decision dropped.
192+
passages = page_passages(
193+
document.html, registry, decisions(projection.actions, registry)
193194
)
194-
state["updates"] = canonical_updates(
195+
state["asks"] = page_asks(
196+
parser,
195197
projection,
196-
claims,
197-
threads,
198-
events,
198+
byid,
199+
document.spoken,
200+
registry,
201+
set(passages.retired) | set(passages.gone),
202+
# A session picking the page up wants the reader's list, so a request
203+
# whose own seat conversation is with this agent is not on it: the next
204+
# word there is owed by the agent, and the stop hook says so.
205+
seats_with_agent(threads),
206+
)
207+
state["lag"] = record_lag_entries(projection, byid, document.spoken, registry)
208+
state["measurement_lag"] = measurement_lag_entries(
209+
parser.lf_elements, registry, stored_data
199210
)
211+
212+
213+
def _apply_thread_state(state: dict, events: list, registry: dict) -> None:
200214
# The panel's own document, listed and projected the way the version's is, and
201215
# for the same reason: a widget an agent sent is a widget, and the reader
202216
# answering one is answering the page. The projection above is of the published
@@ -212,17 +226,78 @@ def _write_page_state(
212226
thread_actions, thread_byid, thread_of = thread_state(events, registry)
213227
state["elements"] += [
214228
{
215-
"tag": rec["tag"],
216-
"id": wid,
217-
"line": rec["line"],
218-
"thread": thread_of[wid],
229+
"tag": record["tag"],
230+
"id": widget,
231+
"line": record["line"],
232+
"thread": thread_of[widget],
219233
}
220-
for wid, rec in thread_byid.items()
234+
for widget, record in thread_byid.items()
221235
]
222-
state["elements"].sort(key=lambda e: (e["thread"] or "", e["line"]))
236+
state["elements"].sort(
237+
key=lambda element: (element["thread"] or "", element["line"])
238+
)
223239
state["state"] += [
224-
standing_entry(coordinate, e, thread_of[coordinate[0]])
225-
for coordinate, (e, _) in thread_actions.actions.items()
240+
standing_entry(coordinate, event, thread_of[coordinate[0]])
241+
for coordinate, (event, _) in thread_actions.actions.items()
226242
]
227-
state["state"].sort(key=lambda s: (s["widget"], s["unit"], s["facet"]))
243+
state["state"].sort(
244+
key=lambda reading: (reading["widget"], reading["unit"], reading["facet"])
245+
)
246+
247+
248+
def _write_page_state(
249+
page_dir: Path, events: list, source_error: str | None = None
250+
) -> None:
251+
"""Where the page stands, as one JSON object — the agent-side twin of the
252+
browser's /api/state, folded rather than raw. /api/state ships the log and
253+
lets the runtime replay it; a session picking a page up owes the same
254+
reading, and doing it in-head over `leaf events` is how a standing decision
255+
gets missed. So this prints the readings the runtime derives, from the same
256+
constructions it derives them with: the active revision's elements, the
257+
projection of the user's standing state and the reports standing on the agent
258+
channel, where the record lags either (`record_lag_entries`), authored
259+
measurements whose live source has run again (`measurement_lag_entries`), the
260+
open asks on the page and in threads (the banner's own count), each comment
261+
thread's exchange,
262+
and presence beside what answers for it. Computed on demand from the log,
263+
revision, registry, and source store — no derived reading is stored, so there
264+
is no second copy of the truth to reconcile.
265+
266+
Every markup-derived reading is of the latest valid revision, because that
267+
is the page the live root shows and the user acts on. An invalid source save
268+
appears only as `source_error` while that revision remains active."""
269+
registry = require_registry(page_dir)
270+
versions = version_descriptors(page_dir, events)
271+
revision, active = _active_revision(page_dir, events)
272+
presence_reading = presence(page_dir, events)
273+
claims = presence_reading.pop("claims")
274+
document = _read_active_document(page_dir, events, registry, revision)
275+
spoken = document.spoken if document is not None else {}
276+
threads = build_threads(events, enclosing_of(spoken))
277+
stored_data = read_data(page_dir)
278+
state = _base_state(
279+
page_dir,
280+
events,
281+
source_error,
282+
versions,
283+
active,
284+
presence_reading,
285+
threads,
286+
stored_data,
287+
registry,
288+
)
289+
if document is not None:
290+
_apply_document_state(state, document, threads, stored_data, registry)
291+
state["asks"] += thread_asks(
292+
events,
293+
registry,
294+
{root for root, thread in threads.items() if thread["resolved"]},
295+
)
296+
state["updates"] = canonical_updates(
297+
document.projection if document is not None else None,
298+
claims,
299+
threads,
300+
events,
301+
)
302+
_apply_thread_state(state, events, registry)
228303
print(json.dumps(state, indent=2, ensure_ascii=False))

0 commit comments

Comments
 (0)