Skip to content

Commit d79a08b

Browse files
committed
Extract authored anchor capture
Keep document text and containment readings in passages, and move quote matching, visual lookup, and stored anchor context into anchor_capture. Callers now import the owner that turns an authored request into an anchor record.
1 parent ae66e73 commit d79a08b

7 files changed

Lines changed: 205 additions & 197 deletions

File tree

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,8 @@ The main owners are:
3333
- `vendoring`: page initialization, layer transitions, and atomic installation;
3434
- `schema`, `structure`, `styles`, and `validation/`: authored-page gates, the
3535
complete source reading, and the `version check` command;
36-
- `passages`: the file-side text reading and anchor capture;
36+
- `passages` and `anchor_capture`: the file-side text reading and authored
37+
anchor construction;
3738
- `render_checks`, `render_gate/`, and `exporting`: browser probes, validation,
3839
and standalone export;
3940
- `data` and `data_contracts`: typed snapshot storage, commands, bindings, and
Lines changed: 195 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,195 @@
1+
"""Capture authored anchor requests against the file-side passage reading."""
2+
3+
from .passages import collapse, page_passages, section_span
4+
from .registry import visual_parts
5+
from .structure import parse_structure
6+
7+
# How much of the surrounding text an anchor stores to tell two identical passages
8+
# apart. The browser's capture states the same number and a test holds the two equal,
9+
# so this side cannot come to store a neighbourhood the browser would never have
10+
# written. The quote itself is stored whole, however long the passage: it is the extent
11+
# the page marks, and a cap on it was a comment quietly made on less than was quoted
12+
# (see selectionAnchor, wherever the capture lives).
13+
CONTEXT = 24
14+
15+
16+
def enclosing_section(owner: list, lo: int, hi: int):
17+
"""The innermost id enclosing every character of [lo, hi) — the runtime's
18+
`closest("[id]")` on the passage's common ancestor."""
19+
first, last = owner[lo], owner[hi - 1]
20+
shared = 0
21+
while shared < min(len(first), len(last)) and first[shared] == last[shared]:
22+
shared += 1
23+
return first[shared - 1] if shared else None
24+
25+
26+
def occurrences(text: str, quote: str, lo: int, hi: int, fences=frozenset()) -> list:
27+
"""Where `quote` sits in text[lo:hi], as absolute indices. A match that runs across a
28+
fence is not one: the page has words there that this text doesn't."""
29+
found = []
30+
at = text.find(quote, lo, hi)
31+
while at != -1:
32+
if not any(at < f < at + len(quote) for f in fences):
33+
found.append(at)
34+
at = text.find(quote, at + len(quote), hi)
35+
return found
36+
37+
38+
def capture_anchor(
39+
html: str,
40+
registry,
41+
quote: str,
42+
section: str,
43+
decided=None,
44+
rewrites=None,
45+
part: str | None = None,
46+
) -> dict:
47+
"""The anchor a quote makes, written the way a selection's is. Raises ValueError with
48+
what to do about it — a quote the file doesn't hold, or holds twice, is a question
49+
with an answer, and asking now beats posting a comment that lands nowhere.
50+
51+
`decided` and `rewrites` make this the reading the user is looking at rather
52+
than the version as authored: a slot their decision retired is off the page, and a
53+
body their edit rewrote holds their words — so an anchor is met here the way it
54+
would land there, instead of detaching in front of them."""
55+
if part and not section:
56+
raise ValueError("--part needs --section to name its visual")
57+
if part and quote:
58+
raise ValueError("--part names a visual box; use it without --quote")
59+
text, owner, fences, retired, rewritten, gone, shown, enclosing = page_passages(
60+
html, registry, decided, rewrites
61+
)
62+
if section:
63+
# Against the structure, not the text: an element anchor is the one a click makes
64+
# on a diagram or an image, and those hold no text to look for.
65+
if section not in enclosing:
66+
raise ValueError(f"no element id {section!r} in this version")
67+
if section in retired:
68+
sid = retired[section]
69+
raise ValueError(
70+
f"§ {section} left the page when the user chose to {decided[sid]} "
71+
f"§ {sid} — a decision retires the slot its outcome names, and an anchor "
72+
"on it would reach nobody. Anchor on the settled text instead."
73+
)
74+
if section in gone:
75+
raise ValueError(
76+
f"§ {section} settled to nothing when the user chose to {gone[section]} "
77+
"it — the decision removed everything it held from the page, and an anchor "
78+
"on it would reach nobody. Anchor on the surrounding text instead."
79+
)
80+
if part:
81+
record = parse_structure(html).by_id.get(section)
82+
available = visual_parts(record or {}, registry)
83+
if not available:
84+
raise ValueError(
85+
f"§ {section} declares no commentable visual parts in this version"
86+
)
87+
if part not in available:
88+
raise ValueError(
89+
f"§ {section} has no visual part {part!r}; known: {list(available)}"
90+
)
91+
return {"section": section, "visual": part}
92+
if not quote:
93+
return {"section": section}
94+
95+
wanted = collapse(quote)
96+
lo_bound, hi_bound = 0, len(text)
97+
if section:
98+
span = section_span(owner, section)
99+
if span is None:
100+
raise ValueError(
101+
f"§ {section} holds no quotable text — a widget's data body is its source, "
102+
"not its words. Drop --quote to anchor on the element itself."
103+
)
104+
lo_bound, hi_bound = span
105+
where = "the page" if not section else f"§ {section}"
106+
hits = occurrences(text, wanted, lo_bound, hi_bound, fences)
107+
if not hits:
108+
if occurrences(text, wanted, lo_bound, hi_bound):
109+
raise ValueError(
110+
f"{wanted!r} runs across a widget's parts, and a widget writes words of "
111+
"its own between them — a column's heading, a milestone's chips, a "
112+
"diagram in place of its source. Quote within one part, or --section the "
113+
"widget to point at the whole of it."
114+
)
115+
was = _removed_by(html, registry, wanted, section, decided or {}, rewritten)
116+
if was:
117+
raise ValueError(f"{where} said {wanted!r} until {was}")
118+
holder = next((el for el, words in shown.items() if wanted in words), None)
119+
if holder:
120+
raise ValueError(
121+
f"{wanted!r} is in § {holder}'s data body, which is the widget's source "
122+
"and not its words — the page shows whatever its module made of that, "
123+
"and this reading holds nothing there to anchor on. Point at the element "
124+
f"instead: --section {holder}."
125+
)
126+
raise ValueError(
127+
f"{where} doesn't say {wanted!r} — quote it as the version file holds it. A "
128+
"widget's data body is the widget's source, not its words (a diagram's body "
129+
"is a picture by the time it is read), so --section the element instead."
130+
)
131+
if len(hits) > 1:
132+
around = [
133+
f" - …{text[max(lo_bound, at - 30) : at + len(wanted) + 30]}…"
134+
for at in hits[:4]
135+
]
136+
if len(hits) > len(around):
137+
around.append(f" - …and {len(hits) - len(around)} more")
138+
raise ValueError(
139+
f"{where} says {wanted!r} {len(hits)} times, so this quote names no one "
140+
"passage. Extend it, or scope it with --section:\n" + "\n".join(around)
141+
)
142+
143+
lo = hits[0]
144+
hi = lo + len(wanted)
145+
section = section or enclosing_section(owner, lo, hi)
146+
# The neighbours come from the whole reading, as the browser's do — the section
147+
# filters where the search may land, never what surrounds a passage — so a passage
148+
# closing its section still stores a full suffix. Each side reaches only to the
149+
# nearest fence, because past one the page holds words this doesn't: context the
150+
# runtime can never confirm leaves every copy equally unconfirmed, which is where
151+
# an anchor carrying none starts anyway.
152+
# Both are trimmed before they are cut, since the runtime reads its side back through
153+
# the same collapse, which trims — a stored space no occurrence produces fails at the
154+
# first comparison.
155+
prefix = text[max([0] + [f for f in fences if f <= lo]) : lo].strip()[-CONTEXT:]
156+
suffix = text[hi : min([len(text)] + [f for f in fences if f >= hi])].strip()[
157+
:CONTEXT
158+
]
159+
return {
160+
"section": section,
161+
"quote": wanted,
162+
**({"prefix": prefix} if prefix else {}),
163+
**({"suffix": suffix} if suffix else {}),
164+
}
165+
166+
167+
def _removed_by(html, registry, wanted: str, section: str, decided, rewritten):
168+
"""What took `wanted` off the user's page, when the version as authored still
169+
holds it: the decision that retired the slot it sat in, or the edit that rewrote
170+
the element saying it. Naming that act beats telling the writer the page never
171+
said it."""
172+
if not (decided or rewritten):
173+
return None
174+
p = page_passages(html, registry)
175+
lo, hi = 0, len(p.text)
176+
if section:
177+
span = section_span(p.owner, section)
178+
if span is None:
179+
return None
180+
lo, hi = span
181+
for at in occurrences(p.text, wanted, lo, hi, p.fences):
182+
for ids in p.owner[at : at + len(wanted)]:
183+
sid = next((wid for wid in ids if wid in decided), None)
184+
if sid:
185+
return (
186+
f"the user chose to {decided[sid]} § {sid} — that decision "
187+
"retired these words from the page. Quote it as it now stands."
188+
)
189+
wid = next((wid for wid in ids if wid in rewritten), None)
190+
if wid:
191+
return (
192+
f"the user rewrote § {wid} — their {rewritten[wid]} replaced "
193+
"these words. Quote the text as they left it."
194+
)
195+
return None

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import sys
55
from pathlib import Path
66

7+
from leaf.anchor_capture import capture_anchor
78
from leaf.asks import page_awaiting_values
89
from leaf.event_contracts import report_contract_error
910
from leaf.event_log import append_event
@@ -15,7 +16,6 @@
1516
)
1617
from leaf.host import message_identity
1718
from leaf.leases import contract_writer
18-
from leaf.passages import capture_anchor
1919
from leaf.projection import (
2020
decisions,
2121
markup_facet,

0 commit comments

Comments
 (0)