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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
"""Checks of the task add-user-testing against the planner app's state, exported by REA from a desktop application capture.

It reads the app's data/get through the computer, takes the typed views of its files and evaluates each check: no
model, no code from the task. A failure to reach the app raises, so the run fails rather than scoring the agent.
"""
import json
import math
import re

from agentenv_protocol import client as protocol
from agentenv_protocol.types import RPC_PATH

APP = "planner"
CHECKS = [
    {"id": "user-testing", "kind": "value_equals", "file": "Documents/website-launch.planner", "pointer": "/root/children/[name=tasks]/children/[name=task][@name=User testing]/attributes/name", "value": "User testing"},
    {"id": "requirements-kept", "kind": "value_equals", "file": "Documents/website-launch.planner", "pointer": "/root/children/[name=tasks]/children/[name=task][@name=Requirements]/attributes/name", "value": "Requirements"},
    {"id": "design-kept", "kind": "value_equals", "file": "Documents/website-launch.planner", "pointer": "/root/children/[name=tasks]/children/[name=task][@name=Design]/attributes/name", "value": "Design"},
    {"id": "development-kept", "kind": "value_equals", "file": "Documents/website-launch.planner", "pointer": "/root/children/[name=tasks]/children/[name=task][@name=Development]/attributes/work", "value": "144000"},
    {"id": "launch-kept", "kind": "value_equals", "file": "Documents/website-launch.planner", "pointer": "/root/children/[name=tasks]/children/[name=task][@name=Launch]/attributes/name", "value": "Launch"},
]

MISSING = object()
INDEX = re.compile(r"0|[1-9][0-9]*")
VIEW_FORMATS = ("text", "json", "keyfile", "xml")
NUMERAL = re.compile(r"[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?")
WHITESPACE_RUN = re.compile(r"[ \t\r\n]+")


def _shown(value) -> str:
    text = json.dumps(value, ensure_ascii=False, separators=(",", ":"))
    return text if len(text) <= 200 else text[:200] + "…"


def _same(actual, expected) -> bool:
    """JSON equality: numbers by value but never a boolean for a number, objects by their keys, arrays in order."""
    if isinstance(expected, list):
        return (isinstance(actual, list) and len(actual) == len(expected)
                and all(_same(item, wanted) for item, wanted in zip(actual, expected)))
    if isinstance(expected, dict):
        return (isinstance(actual, dict) and len(actual) == len(expected)
                and all(key in actual and _same(actual[key], value) for key, value in expected.items()))
    if isinstance(expected, bool) or isinstance(actual, bool):
        return isinstance(expected, bool) and isinstance(actual, bool) and actual == expected
    if isinstance(expected, (int, float)):
        return isinstance(actual, (int, float)) and actual == expected
    return type(actual) is type(expected) and actual == expected


def _bracketed(token: str) -> bool:
    return len(token) >= 2 and token.startswith("[") and token.endswith("]")


def _selector(token: str):
    """A selector's conditions, [KEY=VALUE] or [@KEY=VALUE] one or more times, or None when the token is not one."""
    if not _bracketed(token):
        return None
    conditions = []
    for part in token[1:-1].split("]["):
        key, equals, value = part.partition("=")
        name = key[1:] if key.startswith("@") else key
        if not equals or not name:
            return None
        conditions.append((key.startswith("@"), name, value))
    return conditions


def _selects(member, conditions) -> bool:
    """Whether an array member meets every condition; selectors compare strings only."""
    if not isinstance(member, dict):
        return False
    for attribute, key, value in conditions:
        fields = member.get("attributes") if attribute else member
        if not isinstance(fields, dict) or not isinstance(fields.get(key), str) or fields[key] != value:
            return False
    return True


def _step(items: list, token: str, last: bool):
    """One step into an array, by index or by a selector that must match one member, or none when it is the last."""
    if INDEX.fullmatch(token):
        return ("member", items[int(token)]) if int(token) < len(items) else ("none", None)
    conditions = _selector(token)
    if conditions is None:
        return ("unresolved", f"{token} is not a selector of the form [KEY=VALUE]") if _bracketed(token) else (
            "none", None)
    matched = [item for item in items if _selects(item, conditions)]
    if len(matched) == 1:
        return "member", matched[0]
    if len(matched) > 1:
        return "unresolved", f"{token} matches {len(matched)} members, not one"
    return ("none" if last else "unresolved"), f"{token} matches no member"


def _locate(view, pointer: str):
    """Where a pointer leads: ("value", value), ("none", why or None) or ("unresolved", problem), with the pointers
    to the arrays a selector searched on the way."""
    current, searched = view, []
    segments = pointer[1:].split("/")
    for position, segment in enumerate(segments):
        token = segment.replace("~1", "/").replace("~0", "~")
        if isinstance(current, list):
            if not INDEX.fullmatch(token) and _selector(token) is not None:
                searched.append("".join("/" + part for part in segments[:position]))
            kind, found = _step(current, token, position == len(segments) - 1)
            if kind != "member":
                return kind, found, searched
            current = found
        elif isinstance(current, dict) and token in current:
            current = current[token]
        else:
            return "none", None, searched
    return "value", current, searched


def _number(value):
    """A number, or a numeral string read as one; None for anything else, a boolean, or a numeral past the doubles."""
    if isinstance(value, bool):
        return None
    if isinstance(value, (int, float)):
        return value
    if not isinstance(value, str) or not NUMERAL.fullmatch(value):
        return None
    number = float(value)
    return number if math.isfinite(number) else None


def _entry_leaves_out(entry) -> bool:
    return isinstance(entry, dict) and (isinstance(entry.get("view_error"), str) or (
        entry.get("format") in ("text", "xml") and isinstance(entry.get("view"), dict)
        and entry["view"].get("truncated") is True))


def _viewless_entry(view, pointer: str):
    """The name of the entry whose view a pointer goes into when it has none, so its null is no JSON value, and
    why: binary, unread, or of a format without a view; None when it has one."""
    parts = pointer[1:].split("/")
    if len(parts) < 3 or parts[0] != "entries" or parts[2] != "view":
        return None
    kind, item, _ = _locate(view, "/entries/" + parts[1])
    if kind != "value" or not isinstance(item, dict):
        return None
    if isinstance(item.get("view_error"), str):
        reason = f"has no view: {item['view_error']}"
    elif item.get("format") == "binary":
        reason = "is binary and has no view"
    elif item.get("format") not in VIEW_FORMATS:
        reason = "has no view"
    else:
        return None
    return (item["name"] if isinstance(item.get("name"), str) else ""), reason


def _array_leaves_out(form, view, array: str) -> bool:
    """Whether an array a selector searched may lack members: in a zip the listing or its entry's view, else the
    view's own truncation."""
    if form != "zip":
        return _truncated(form, view)
    if array == "/entries":
        return isinstance(view, dict) and view.get("truncated") is True
    return _zip_leaves_out(view, array)


def _zip_leaves_out(view, pointer: str) -> bool:
    """Whether a zip view leaves out what a pointer reaches: for a pointer into one listed entry, only that entry."""
    if not isinstance(view, dict):
        return False
    parts = pointer[1:].split("/")
    if parts[0] == "entries" and len(parts) > 1:
        kind, entry, _ = _locate(view, "/entries/" + parts[1])
        return _entry_leaves_out(entry) if kind == "value" else view.get("truncated") is True
    entries = view.get("entries") if isinstance(view.get("entries"), list) else []
    return view.get("truncated") is True or any(_entry_leaves_out(entry) for entry in entries)


def _truncated(form, view) -> bool:
    if not isinstance(view, dict):
        return False
    if form in ("text", "xml"):
        return view.get("truncated") is True
    if form != "sqlite":
        return False
    tables = view.get("tables")
    return view.get("tables_truncated") is True or any(
        isinstance(table, dict) and (table.get("truncated") is True or isinstance(table.get("error"), str))
        for table in (tables.values() if isinstance(tables, dict) else []))


def _view_of(check, entry, form):
    """The view, whether it is truncated, and why the check cannot read it; an absent file reads as empty."""
    if entry is None:
        return None, False, None
    if isinstance(entry.get("error"), str):
        return None, False, f"{check['file']} has no view: {entry['error']}"
    if entry.get("format") in (None, "binary"):
        return None, False, f"{check['file']} is binary and has no view"
    if form is not None and entry.get("format") != form:
        return None, False, f"{check['file']} is read as {entry.get('format')}, not {form}"
    return entry.get("view"), _truncated(entry.get("format"), entry.get("view")), None


def _undecided(check):
    return False, f"the view of {check['file']} is truncated, so what it leaves out is unknown"


def _compared(check, n: int, what: str):
    operator = next(key for key in ("equals", "at_least", "at_most") if check.get(key) is not None)
    expected = check[operator]
    met = n == expected if operator == "equals" else n >= expected if operator == "at_least" else n <= expected
    return met, f"{n} {what}, expected {operator.replace('_', ' ')} {expected}"


def _lines(check, entry):
    view, truncated, problem = _view_of(check, entry, "text")
    if problem is not None:
        return False, problem
    lines = view.get("lines") if isinstance(view, dict) and isinstance(view.get("lines"), list) else []
    lines = [line for line in lines if isinstance(line, str)]
    file = check["file"]
    if check["kind"] == "lines_present":
        missing = next((line for line in check["lines"] if line not in lines), None)
        return (True, f"{file} has the line(s) {_shown(check['lines'])}") if missing is None else (
            False, f"{file} has no line {_shown(missing)}")
    if truncated:
        return _undecided(check)
    if check["kind"] == "lines_absent":
        found = next((line for line in check["lines"] if line in lines), None)
        return (True, f"{file} has none of the lines {_shown(check['lines'])}") if found is None else (
            False, f"{file} still has the line {_shown(found)}")
    if check.get("contains") is not None:
        n = sum(1 for line in lines if check["contains"] in line)
        return _compared(check, n, f"line(s) of {file} contain {_shown(check['contains'])}")
    n = sum(1 for line in lines if line == check["exact"])
    return _compared(check, n, f"line(s) of {file} match {_shown(check['exact'])}")


def _near(at: str, found, expected, tolerance):
    """A value compared within a tolerance: numbers, and numeral strings, by their difference."""
    number = _number(found)
    within = f"within {_shown(tolerance)} of {_shown(expected)}"
    if number is None:
        return False, f"{at} is {_shown(found)}, not a number"
    if abs(number - expected) <= tolerance:
        return True, f"{at} is {_shown(found)}, {within}"
    return False, f"{at} is {_shown(found)}, not {within}"


def _value(check, entry):
    view, truncated, problem = _view_of(check, entry, None)
    if problem is not None:
        return False, problem
    kind, found, searched = ("none", None, []) if entry is None else _locate(view, check["pointer"])
    at = f"{check['file']} at {check['pointer']}"
    viewless = _viewless_entry(view, check["pointer"]) if entry is not None and entry.get("format") == "zip" else None
    if viewless is not None:
        return False, f"{check['file']} entry {viewless[0]} {viewless[1]}"
    # A selector tells one member from several only in an array the view holds whole.
    if any(_array_leaves_out(entry.get("format"), view, array) for array in searched):
        return _undecided(check)
    if kind == "unresolved":
        return False, f"{at}: {found}"
    if entry is not None and entry.get("format") == "zip":
        truncated = _zip_leaves_out(view, check["pointer"])
    if check["kind"] == "value_equals" and isinstance(check["value"], (dict, list)) and truncated:
        return _undecided(check)
    if check["kind"] == "value_equals":
        if kind == "none":
            return False, f"{at} has no value" if found is None else f"{at}: {found}"
        expected = check["value"]
        if check.get("tolerance") is not None and isinstance(expected, (int, float)) and not isinstance(expected, bool):
            return _near(at, found, expected, check["tolerance"])
        if _same(found, check["value"]):
            return True, f"{at} is {_shown(check['value'])}"
        return False, f"{at} is {_shown(found)}, not {_shown(check['value'])}"
    if truncated:
        return _undecided(check)
    return (True, f"{at} has no value") if kind == "none" else (False, f"{at} is {_shown(found)}")


def _is_element(value) -> bool:
    return (isinstance(value, dict) and isinstance(value.get("name"), str) and isinstance(value.get("attributes"), dict)
            and isinstance(value.get("children"), list))


def _element_text(element) -> str:
    """An element's text as XPath's string() reads it from what the view keeps: every text node among its children
    and its descendants', in document order."""
    parts, pending = [], [element]
    while pending:
        node = pending.pop()
        if isinstance(node, str):
            parts.append(node)
        elif _is_element(node):
            pending.extend(reversed(node["children"]))
    return "".join(parts)


def _collapse_whitespace(text: str) -> str:
    """Each run of XML whitespace (space, tab, CR, LF) made one space, none at either end, as normalize-space()."""
    return WHITESPACE_RUN.sub(" ", text).strip(" ")


def _text_at(view, pointer: str) -> bool:
    """Whether a string a pointer reaches is text of the document: a member of an element's children (a text node)
    or attributes (an attribute's value), rather than an element's name or a field of the DOCTYPE."""
    segments = pointer.split("/")
    if len(segments) < 3 or segments[-2] not in ("children", "attributes"):
        return False
    kind, owner, _ = _locate(view, "/".join(segments[:-2]))
    return kind == "value" and _is_element(owner)


def _not_xml_entry(check, view):
    """Why a text check's pointer into an archive goes into no XML entry's view, or None when it does or names an
    entry not listed."""
    parts = check["pointer"].split("/")
    if len(parts) < 4 or parts[3] != "view":
        return f"{check['file']} at {check['pointer']} does not point into an entry's view"
    if parts[1] != "entries":
        return None
    kind, item, _ = _locate(view, "/entries/" + parts[2])
    if kind != "value" or not isinstance(item, dict) or item.get("format") == "xml":
        return None
    # An entry without a view failed before this, so its format is one with a view.
    name, form = (value if isinstance(value, str) else "" for value in (item.get("name"), item.get("format")))
    return f"{check['file']} entry {name} is read as {form}, not xml"


def _whole_text(check, entry):
    """An element's whole text, or a text node's, compared with the value or searched for it."""
    view, truncated, problem = _view_of(check, entry, None)
    if problem is not None:
        return False, problem
    at = f"{check['file']} at {check['pointer']}"
    if entry is None:
        return False, f"{at} has no value"
    form = entry.get("format")
    if form not in ("xml", "zip"):
        return False, f"{check['file']} is read as {form}, not xml"
    kind, found, searched = _locate(view, check["pointer"])
    viewless = _viewless_entry(view, check["pointer"]) if form == "zip" else None
    if viewless is not None:
        return False, f"{check['file']} entry {viewless[0]} {viewless[1]}"
    if any(_array_leaves_out(form, view, array) for array in searched):
        return _undecided(check)
    problem = _not_xml_entry(check, view) if form == "zip" else None
    if problem is not None:
        return False, problem
    if kind == "unresolved":
        return False, f"{at}: {found}"
    if kind == "none":
        return False, f"{at} has no value" if found is None else f"{at}: {found}"
    if not (_text_at(view, check["pointer"]) if isinstance(found, str) else _is_element(found)):
        return False, f"{at} is {_shown(found)}, not an element, a text node or an attribute value"
    # A text node is whole. An element's text in a cut view may lack what the cut dropped from its middle.
    if form == "zip":
        truncated = _zip_leaves_out(view, check["pointer"])
    if not isinstance(found, str) and truncated:
        return _undecided(check)
    return _compared_text(check, at, _element_text(found))


def _compared_text(check, at: str, found: str):
    """A text found at a pointer compared with the check's value or searched for it, both collapsed when it asks."""
    collapse = check.get("normalize_whitespace") is True
    text = _collapse_whitespace(found) if collapse else found
    value = _collapse_whitespace(check["value"]) if collapse else check["value"]
    how = " with whitespace collapsed" if collapse else ""
    if check["kind"] == "text_equals":
        if text == value:
            return True, f"{at} has the text {_shown(value)}{how}"
        return False, f"{at} has the text {_shown(text)}{how}, not {_shown(value)}"
    if value in text:
        return True, f"{at} has text containing {_shown(value)}{how}"
    return False, f"{at} has the text {_shown(text)}{how}, without {_shown(value)}"


def _rows(check, entry):
    view, _, problem = _view_of(check, entry, "sqlite")
    if problem is not None:
        return False, problem
    view = view if isinstance(view, dict) else {}
    tables = view.get("tables") if isinstance(view.get("tables"), dict) else {}
    table = tables[check["table"]] if check["table"] in tables else MISSING
    name = f"{check['file']} table {check['table']}"
    if table is MISSING and view.get("tables_truncated") is True:
        return _undecided(check)
    table = table if isinstance(table, dict) else {}
    if isinstance(table.get("error"), str):
        return False, f"{name} could not be read: {table['error']}"
    columns = table.get("columns") if isinstance(table.get("columns"), list) else []
    rows = table.get("rows") if isinstance(table.get("rows"), list) else []
    where = check.get("where") or {}

    def matches(row) -> bool:
        return isinstance(row, list) and all(
            column in columns and columns.index(column) < len(row) and _same(row[columns.index(column)], value)
            for column, value in where.items())

    n = sum(1 for row in rows if matches(row))
    if check["kind"] == "row_present":
        return (n > 0, f"{name} has a row with {_shown(where)}" if n > 0 else f"{name} has no row with {_shown(where)}")
    if table.get("truncated") is True:
        return _undecided(check)
    if check["kind"] == "row_absent":
        return (True, f"{name} has no row with {_shown(where)}") if n == 0 else (
            False, f"{name} has {n} row(s) with {_shown(where)}")
    return _compared(check, n, f"row(s) of {name}" + (f" with {_shown(where)}" if "where" in check else ""))


def _verdict(check, entry):
    kind = check["kind"]
    if kind == "file_present":
        return (entry is not None, f"{check['file']} exists" if entry is not None else f"{check['file']} does not exist")
    if kind == "file_absent":
        return (entry is None, f"{check['file']} does not exist" if entry is None else f"{check['file']} exists")
    if kind in ("lines_present", "lines_absent", "line_count"):
        return _lines(check, entry)
    if kind in ("value_equals", "value_absent"):
        return _value(check, entry)
    if kind in ("text_equals", "text_contains"):
        return _whole_text(check, entry)
    return _rows(check, entry)


def evaluate(checks: list, views: dict) -> list:
    """One result per check against the views data/get returned, by home path."""
    results = []
    for check in checks:
        passed, description = _verdict(check, views.get(check["file"]))
        results.append({"id": check["id"], "result": passed, "description": description})
    return results


async def verify(mcp_url, env_url):
    card = await protocol.get_card(env_url)
    child = protocol.find_child(card, APP)
    if child is None:
        raise RuntimeError(f"the computer at {env_url} lists no app named {APP}")
    answer = await protocol.get_data(env_url + (child.get("url") or RPC_PATH).removesuffix(RPC_PATH), timeout=120)
    states = [part.data["state"] for part in answer.parts
              if part.kind == "data" and isinstance(part.data.get("state"), dict)]
    if not states:
        raise RuntimeError(f"the {APP} app's data/get returned no state views")
    return evaluate(CHECKS, states[0])