Skip to content

Commit c4b7444

Browse files
committed
Extract Python event contracts
Move browser and CLI event validation plus shared thread-state readings out of authored-markup validation into a direct event-contract owner.
1 parent 03ae447 commit c4b7444

8 files changed

Lines changed: 304 additions & 287 deletions

File tree

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,8 @@ The main owners are:
1010
- `page`: vendored page guidance and vocabulary catalog;
1111
- `agent_state`: the agent-facing folded page-state reading;
1212
- `event_log`: append-only JSONL storage, locking, and attempt identity;
13-
- `event_endpoint`: browser-event admission, retry coordination, and append;
13+
- `event_endpoint` and `event_contracts`: browser-event admission, retry
14+
coordination and append, and shared browser/CLI event contracts;
1415
- `events` and `projection`: standing event and durable state folds;
1516
- `thread_context` and `conversation`: thread identity, frozen markup, bounded
1617
delivery context, and conversation writes;

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
from .asks import page_asks, thread_asks
88
from .data import measurement_lag_entries, page_data_binding_inventory, read_data
9+
from .event_contracts import thread_state
910
from .events import (
1011
bare_reaction,
1112
build_threads,
@@ -32,7 +33,6 @@
3233
from .server import running_server
3334
from .service import PageTransaction, unacknowledged
3435
from .thread_context import thread_digest
35-
from .validation import thread_state
3636

3737

3838
def standing_entry(coordinate, e: dict, thread: str | None = None) -> dict:

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

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
from pathlib import Path
66

77
from leaf.asks import page_awaiting_values
8+
from leaf.event_contracts import report_contract_error
89
from leaf.event_log import append_event
910
from leaf.files import (
1011
latest_published,
@@ -26,11 +27,7 @@
2627
from leaf.service import PageTransaction, contract_writer
2728
from leaf.structure import parse_revision
2829
from leaf.thread_context import thread_roots
29-
from leaf.validation import (
30-
check_markup,
31-
read_text_arg,
32-
report_contract_error,
33-
)
30+
from leaf.validation import check_markup, read_text_arg
3431

3532

3633
def _thread_root(events: list, to: str) -> tuple[str, dict | None]:
Lines changed: 272 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,272 @@
1+
"""Browser and CLI event contracts against page and thread state."""
2+
3+
from pathlib import Path
4+
5+
from leaf.asks import (
6+
asking,
7+
page_awaiting_values,
8+
projected_action_holders,
9+
quoted_in,
10+
thread_ask_projection,
11+
)
12+
from leaf.events import build_threads
13+
from leaf.files import revision_path
14+
from leaf.passages import enclosing_ids, spoken
15+
from leaf.projection import page_projection, state_projection
16+
from leaf.registry import json_validator, visual_parts
17+
from leaf.structure import parse_revision
18+
from leaf.thread_context import thread_roots, thread_structure, thread_widgets
19+
20+
21+
def thread_universe(events: list, registry: dict):
22+
"""Every widget the log's frozen markup holds, read as one document.
23+
24+
id → record and id → spoken words, which is the panel's answer to a version's
25+
`parser.by_id`/`spoken` pair, plus the thread each widget was sent in. A
26+
version's element universe is one file; the panel's is every fragment the log
27+
carries, and the two are separate documents that happen to share a page."""
28+
structure = thread_structure(events)
29+
byid, spk = {}, {}
30+
for e in events:
31+
if markup := e.get("markup"):
32+
byid.update(structure.fragments[e["id"]].by_id)
33+
spk.update(spoken(markup, registry))
34+
return byid, spk, thread_widgets(structure, thread_roots(events))
35+
36+
37+
def thread_state(events: list, registry: dict):
38+
"""What the reader's gestures leave standing on the widgets an agent sent.
39+
40+
Thread markup is frozen in its event: no version window bounds it and no
41+
retraction floor reaches it, so every action on it reads the whole
42+
conversation window. Both doors that must answer for such a widget read it
43+
here — the action gate, deciding whether a fresh press is allowed, and
44+
`page state`, telling a session picking the page up what the reader has
45+
already settled — so a decision made in the panel cannot stand at one door
46+
and be missing at the other."""
47+
byid, spk, thread_of = thread_universe(events, registry)
48+
projection = state_projection(events, byid, spk, registry, None, floors={})
49+
return projection, byid, thread_of
50+
51+
52+
def detail_error(schema: dict, detail: dict):
53+
"""The first schema complaint about an event's detail payload, or None —
54+
ordered so which one speaks doesn't depend on validator iteration order."""
55+
error = min(json_validator(schema).iter_errors(detail), key=str, default=None)
56+
return error.message if error else None
57+
58+
59+
def event_record_error(contract: dict, event: dict, browser: bool = False):
60+
"""The first complaint from one event kind's stored-record contract."""
61+
schema = contract["record"]
62+
instance = event
63+
if browser:
64+
# Supply the fields the server and reader add so the full record schema
65+
# can validate the unstamped request beside its browser assertions.
66+
schema = {"allOf": [schema, contract["browser"]]}
67+
instance = {
68+
**event,
69+
"id": "browser",
70+
"ts": "browser",
71+
"author": "page" if event.get("kind") == "error" else "user",
72+
"seq": 1,
73+
}
74+
return detail_error(schema, instance)
75+
76+
77+
def declared_event_error(
78+
event: dict, tag: str, registry: dict, kind: str, channel: str
79+
):
80+
"""Why a known widget's verb or detail violates one declared channel."""
81+
entry = registry.get(tag)
82+
if entry is None:
83+
return (
84+
f"registry no longer declares <{tag}> for {kind} widget {event['widget']!r}"
85+
)
86+
declared = entry.get(channel, {})
87+
spec = declared.get(event["action"])
88+
if spec is None:
89+
return f"<{tag}> does not declare {kind} verb {event['action']!r}" + (
90+
f"; it declares {sorted(declared)}" if kind == "report" and declared else ""
91+
)
92+
if message := detail_error(spec["detail"], event["detail"]):
93+
return f"<{tag}> {kind} {event['action']!r} detail is invalid: {message}"
94+
return None
95+
96+
97+
def declared_action_error(
98+
event: dict, page_by_id: dict, thread_by_id: dict, registry: dict
99+
):
100+
"""Why a stored action violates its sending widget's durable declaration."""
101+
# Page widgets come from the action's own immutable revision. Thread widgets
102+
# inhabit the panel's other live document. Either record answers both which
103+
# tag sent the action and whether it stands inside an exhibit.
104+
rec = page_by_id.get(event["widget"]) or thread_by_id.get(event["widget"])
105+
if rec is None:
106+
return (
107+
f"unknown action widget {event['widget']!r} in revision "
108+
f"r{event['revision']} "
109+
"or agent-authored thread markup"
110+
)
111+
tag = rec["tag"]
112+
if error := declared_event_error(event, tag, registry, "action", "x-state"):
113+
return error
114+
# The exhibit rule at the door, not only in the shipped runtime's
115+
# sendAction: an exhibited widget is a mention, and the log outranks the
116+
# document — an action taken here would replay as a decision the reader
117+
# made on quoted material. Any sender the key admits reaches this door.
118+
if quoted_in(rec, registry):
119+
return (
120+
f"<{tag}> {event['widget']!r} stands inside an exhibit (x-exhibit); "
121+
"quoted material takes no input"
122+
)
123+
return None
124+
125+
126+
def held_comment_error(event: dict, page_by_id: dict, registry: dict):
127+
"""Why one comment cannot hold the exact command goal it names."""
128+
target = event.get("holds")
129+
if not target:
130+
return None
131+
rec = page_by_id.get(target)
132+
conversation = (
133+
(registry.get(rec["tag"]) or {}).get("x-conversation") if rec else None
134+
)
135+
if (
136+
rec is None
137+
or not conversation
138+
or not conversation.get("hold")
139+
or not asking(rec["attrs"], conversation.get("when"))
140+
or event.get("anchor") != {"section": target}
141+
):
142+
return (
143+
"comment holds must name its exact-section anchor on a matching "
144+
"x-conversation hold target"
145+
)
146+
return None
147+
148+
149+
def version_response_comment_error(event: dict, page_by_id: dict, registry: dict):
150+
"""Why a comment cannot require the authored response it names."""
151+
response = event.get("response")
152+
if not response:
153+
return None
154+
anchor = event.get("anchor")
155+
target = anchor.get("section") if isinstance(anchor, dict) else None
156+
rec = page_by_id.get(target)
157+
conversation = (
158+
(registry.get(rec["tag"]) or {}).get("x-conversation") if rec else None
159+
)
160+
if (
161+
rec is None
162+
or not conversation
163+
or conversation.get("response") != response
164+
or not asking(rec["attrs"], conversation.get("when"))
165+
or anchor != {"section": target}
166+
):
167+
return (
168+
"comment response must match its exact-section x-conversation "
169+
"response target"
170+
)
171+
return None
172+
173+
174+
def visual_anchor_error(event: dict, page_by_id: dict, registry: dict):
175+
"""Why a semantic visual coordinate is not authored on its section."""
176+
anchor = event.get("anchor") or {}
177+
visual = anchor.get("visual")
178+
if not visual:
179+
return None
180+
if anchor.get("quote") or anchor.get("datum"):
181+
return (
182+
f"visual anchor {visual!r} names a box rather than a passage, "
183+
"so it cannot also carry a quote or a datum"
184+
)
185+
section = anchor["section"]
186+
available = visual_parts(page_by_id.get(section) or {}, registry)
187+
if visual not in available:
188+
return (
189+
f"visual anchor {visual!r} is not declared on section {section!r}; "
190+
f"known: {list(available)}"
191+
)
192+
return None
193+
194+
195+
def action_contract_error(page_dir: Path, event: dict, events: list, registry: dict):
196+
"""Why a fresh action violates its declaration or current applicability.
197+
198+
Eligibility is derived inside the append transaction from the action's
199+
authored document and the standing log. A browser evaluates the same
200+
declaration for honest controls, but its possibly stale reading never
201+
authorizes this boundary.
202+
"""
203+
revision = event["revision"]
204+
page = parse_revision(page_dir, revision)
205+
# One reading of the panel's document for the whole door: the id universe the
206+
# declaration is looked up in and the projection the requirement is judged
207+
# against are the same frozen fragments, and parsing them twice was two
208+
# readings that could only ever agree.
209+
thread_projection, thread_by_id, _threads = thread_state(events, registry)
210+
if error := declared_action_error(event, page.by_id, thread_by_id, registry):
211+
return error
212+
page_rec = page.by_id.get(event["widget"])
213+
rec = page_rec or thread_by_id[event["widget"]]
214+
tag = rec["tag"]
215+
spec = registry[tag]["x-state"][event["action"]]
216+
requirement = spec.get("requires")
217+
if not requirement:
218+
return None
219+
220+
if page_rec:
221+
html = revision_path(page_dir, revision).read_text(encoding="utf-8")
222+
projection, parser, spk = page_projection(html, events, registry, revision)
223+
byid = parser.by_id
224+
current = parser.by_id[event["widget"]]
225+
# This door asks whether the request is answered, not whether it is the
226+
# reader's to deal with: a conversation standing in the widget's seat
227+
# takes it off their list without answering it, and refusing their pick
228+
# over their own remark would refuse them the answer they were asked for.
229+
awaiting_values = page_awaiting_values(html, parser, projection, spk, registry)
230+
else:
231+
# Thread markup is frozen in the log: it has no version retraction floor
232+
# and its actions read the whole conversation window.
233+
projection, byid = thread_projection, thread_by_id
234+
current = byid[event["widget"]]
235+
page_html = revision_path(page_dir, revision).read_text(encoding="utf-8")
236+
threads = build_threads(events, enclosing_ids(page_html))
237+
settled = {root for root, value in threads.items() if value["resolved"]}
238+
_, awaiting_values = thread_ask_projection(events, registry, settled)
239+
240+
holders = projected_action_holders(projection, byid, registry)
241+
target = (
242+
current
243+
if requirement["target"] == "self"
244+
else holders.get(current["attrs"]["id"], current["holder"])
245+
)
246+
target_id = target["attrs"]["id"]
247+
awaiting = awaiting_values.get(target_id, False)
248+
if awaiting != requirement["awaiting"]:
249+
return (
250+
f"<{tag}> {event['widget']!r} action {event['action']!r} is "
251+
f"unavailable: {requirement['target']} {target_id!r} is "
252+
f"{'still ' if awaiting else 'no longer '}awaiting the reader"
253+
)
254+
return None
255+
256+
257+
def report_contract_error(event: dict, page_by_id: dict, registry: dict):
258+
"""Why a structurally complete report violates its widget's declaration —
259+
the CLI door's mirror of the POST door's action_contract_error. Page markup
260+
only, never a reply's: a report has to be answerable, and thread markup is
261+
frozen in the log, so no version could ever absorb or overrule one made
262+
there."""
263+
rec = page_by_id.get(event["widget"])
264+
tag = rec["tag"] if rec else None
265+
if tag is None:
266+
return (
267+
f"unknown report widget {event['widget']!r} in revision "
268+
f"r{event['revision']} — "
269+
"reports name page widgets only; thread markup is frozen, so no "
270+
"version could ever answer a report made there"
271+
)
272+
return declared_event_error(event, tag, registry, "report", "x-report")

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

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,13 @@
44
from collections.abc import Callable
55
from pathlib import Path
66

7+
from .event_contracts import (
8+
action_contract_error,
9+
event_record_error,
10+
held_comment_error,
11+
version_response_comment_error,
12+
visual_anchor_error,
13+
)
714
from .event_log import (
815
AttemptConflict,
916
AttemptExecution,
@@ -17,13 +24,6 @@
1724
from .schema import MESSAGE_KINDS
1825
from .service import PageTransaction
1926
from .structure import parse_revision, revision_review_mode
20-
from .validation import (
21-
action_contract_error,
22-
event_record_error,
23-
held_comment_error,
24-
version_response_comment_error,
25-
visual_anchor_error,
26-
)
2727

2828
EventAnswer = tuple[int, dict]
2929
StateReader = Callable[[], dict]

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
from pathlib import Path
1010
from urllib.parse import urljoin, urlsplit
1111

12+
from leaf.event_contracts import thread_universe
1213
from leaf.event_log import flocked, now_iso, read_events
1314
from leaf.files import revision_label, version_name, version_num
1415
from leaf.hosting import LeafHTTPServer
@@ -24,7 +25,6 @@
2425
wait_for_probe,
2526
)
2627
from leaf.service import transition_lock
27-
from leaf.validation import thread_universe
2828

2929
# ---------- check --render: the browser half of the gate ----------
3030

0 commit comments

Comments
 (0)