earakely-scale commited on
Commit
fbbbd86
·
verified ·
1 Parent(s): 211af69

REA computer-use environment, v0.1.0

Browse files
README.md ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ pretty_name: gLabels computer-use environment from a one-line request (REA)
4
+ tags:
5
+ - computer-use
6
+ - cua
7
+ - gui-agent
8
+ - rl-environment
9
+ - agentenv
10
+ - desktop
11
+ - linux
12
+ - rea
13
+ - labels
14
+ - label-design
15
+ - printing
16
+ - from-request
17
+ ---
18
+
19
+ # gLabels: a computer-use environment built from a one-line request
20
+
21
+ ![An agent solving the task in gLabels](media/hero.gif)
22
+
23
+ **The real gLabels 3.4 label designer running on an Ubuntu 24.04 desktop, as an [agentenv](https://pypi.org/project/agentenv-framework/) computer environment. An agent completes the task only through screenshots, mouse and keyboard, and a verifier grades the saved files with no model.**
24
+
25
+ Claude Code built this environment from a one-line request in about 30 minutes, with only REA's build skill and MCP tools; [How it was made](#how-it-was-made) has the request and the steps. gLabels opens a one-label document, `Documents/address-label.glabels`, at launch: an Avery 5160 address label for Marisol Penhalow, 418 Juniper Court, Bellmont, OR 97215. The agent has to correct the name to Marisol Penhallow and save. It sees only the screen and acts only with the mouse and keyboard.
26
+
27
+ ## Watch
28
+
29
+ - Agent runs (Claude Code with Claude Sonnet 5.5): [run 1](media/solve-1.mp4), [run 2](media/solve-2.mp4), [run 3](media/solve-3.mp4)
30
+ - Witness, which proves the task can be done through the computer: [witness.mp4](media/witness.mp4)
31
+
32
+ Each video is the computer's own screen recording at 10 frames per second.
33
+
34
+ ## The task
35
+
36
+ > The name on my address label in Documents/address-label.glabels is misspelled. It should read Marisol Penhallow. Fix the name in gLabels and save the label.
37
+
38
+ `bundle/artifacts/fix-label-name-check/verify.py` reads the app's files through the computer's `data/get` view and passes only if every check holds:
39
+
40
+ | Check | Kind | File |
41
+ | --- | --- | --- |
42
+ | `check-1` | `text_equals` | `Documents/address-label.glabels` |
43
+
44
+ A `.glabels` file is gzip-compressed XML, and REA reads the XML inside. The check reads the whole text of the label's text object, the `Span` inside `Object-text`, where gLabels writes each line break as an empty `NL` element, so the lines run together: it must equal "Marisol Penhallow418 Juniper CourtBellmont, OR 97215" exactly, which proves the name is fixed and the address untouched. It is the one check REA's draft suggested, kept exactly as written.
45
+
46
+ ## Results
47
+
48
+ 3 of 3 runs passed, about $0.68 per run.
49
+
50
+ | Run | Outcome | Turns | Cost | Video |
51
+ | --- | --- | --- | --- | --- |
52
+ | 1 | passed | 10 | $0.98 | [video](media/solve-1.mp4) |
53
+ | 2 | passed | 10 | $0.46 | [video](media/solve-2.mp4) |
54
+ | 3 | passed | 17 | $0.59 | [video](media/solve-3.mp4) |
55
+
56
+ ## Run it
57
+
58
+ You need Docker. `agentenv-framework` builds the computer: Ubuntu 24.04 with the app installed from Ubuntu's archive (`glabels` 3.4.1, with `librsvg2-common`).
59
+
60
+ ```bash
61
+ pip install agentenv-framework==0.9.1431
62
+ hf download earakely-scale/gLabelsFromRequestComputerEnv-REA --repo-type dataset --local-dir glabels-request
63
+ agent-env run glabels-request/bundle --task fix-label-name --agent claude-code --model <model>
64
+ ```
65
+
66
+ The agent needs a model provider configured for agentenv. `--task smoke` only boots the computer, with no agent. `bundle/README.md` describes the bundle in detail.
67
+
68
+ ## How it was made
69
+
70
+ Claude Code built this environment from a one-line request, given only [REA](https://github.com/morluto/rea)'s build skill and REA's MCP tools:
71
+
72
+ > Build me a gLabels environment where the agent fixes the name on a small address label and saves it.
73
+
74
+ It asked only the skill's upfront questions, wrote no app-specific scripts, and finished in about 30 minutes.
75
+
76
+ gLabels 3.4.1 crashed the first time its Text tool was clicked in a fresh profile; Claude Code set a default font and captured again, and the seed keeps that setting among its dconf keys. The environment was named `glabels` at export, because the build computer's own default name, taken from the desktop entry `glabels-3.0`, came out as "0". The steps were REA's usual ones:
77
+
78
+ 1. **Capture.** REA launched gLabels on a Linux desktop and recorded its package, windows and opened files while the edit was made. It also recorded the app's state folders before and after.
79
+ 2. **Export.** REA turned the capture into an agentenv `computer_app`. It installs the app, seeds the starting files, starts the app, and waits for its main window. It also serves typed views of the app's files for verifiers.
80
+ 3. **Task.** The task's checks were validated against the capture: they fail on the starting state and pass on the captured end state.
81
+ 4. **Witness.** In a fresh computer, the edit was made through computer actions alone, and the checks were read at four stages. They held on the first try:
82
+
83
+ | Stage | Checks |
84
+ | --- | --- |
85
+ | `seed` | fail, as expected: the name reads Marisol Penhalow |
86
+ | `after_edit` | pass |
87
+ | `near_miss` | fail, as expected: the name was cut to "Marisol Penhallo" |
88
+ | `after_reset` | fail, as expected: `data/reset` restored the seed |
89
+
90
+ The agent runs came after the build: Claude Code with Claude Sonnet 5.5 (`--model anthropic/claude-sonnet-5-5 --no-emulate`, on an amd64 host) solved the task 3 times, each run recorded.
91
+
92
+ ## What's inside
93
+
94
+ ```
95
+ bundle/ the agentenv bundle: envs/ (app module, seed files), tasks/, artifacts/ (verifier), evals/
96
+ media/ witness and agent-run recordings (MP4) with short GIF previews
97
+ results.json the runs above, with each check's result
98
+ ```
99
+
100
+ ## Limits
101
+
102
+ - The check reads the label's one text object, name and address together, and needs it exact: any change to the address lines fails, and so does a fix made by adding a second text object.
103
+ - gLabels keeps its settings in dconf keys, which the computer loads once when the app first starts; `data/reset` restores the label but not those settings.
104
+ - The bundle installs `librsvg2-common`, the SVG image loader gLabels' icons need, beside the app as an extra package.
105
+ - The computer installs whatever `glabels` Ubuntu 24.04's archive holds at build time (3.4.1 for these runs); it is not pinned.
106
+ - Three runs is a small sample: the solve rate shows the task is solvable, not how hard it is.
107
+
108
+ ## Licences
109
+
110
+ The bundle code, the task and the synthetic seed files are Apache-2.0. gLabels itself is not included: the computer installs it from Ubuntu's archive (`glabels` 3.4.1, with `librsvg2-common`) at build time, under its own licence (GPL-3.0-or-later).
bundle/README.md ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # gLabels Label Designer 3 computer app
2
+
3
+ Exported by REA's `export-desktop-application` from a capture of the `glabels` package
4
+ (capture Evidence `ev_92a1ee88a892a24749a52e7954d21e09e8086fbf72c122cc198ac3d6f65be773`). It was checked against agentenv-framework
5
+ 0.9.1431.
6
+
7
+ - `envs/glabels/` is a computer app on the `ubuntu-24.04` base with the `reference` driver, for
8
+ `amd64` and `arm64`. It installs `glabels` from the distribution archive, launches `sh -c cd "$HOME" 2>/dev/null; exec 'glabels-3' "$HOME"/'Documents/address-label.glabels'` at boot and is ready
9
+ when a window of class `Glabels-3` appears.
10
+ - Installed beside the app because the export was asked for them with `--extra-package`, as a build computer asks
11
+ for the packages its request named: `librsvg2-common`.
12
+ - At launch the app opens `~/Documents/address-label.glabels`, the seed's one document.
13
+ - Owned paths: `~/Documents`.
14
+ `data/get` returns their files and a typed JSON view of each; `data/reset` restores the seed.
15
+ - Seed: 1 file(s) made for the task, as saved at checkpoint `seed`, and the application's dconf keys.
16
+ Text files and dconf keys spell the capture host's name as `localhost`, `user@host` as `user@localhost`
17
+ and the home as `/home/user`, which the computer respells to its own at boot.
18
+ Rewritten: `envs/glabels/seed/Documents/address-label.glabels`.
19
+ - `tasks/smoke.json` deploys the app.
20
+
21
+ Run the task with `agent-env run <this folder>`, or only the deploy with `--task smoke`.
22
+
23
+ The seed was made for this task, not taken from a user's own data; read `envs/glabels/seed/` before publishing the bundle.
24
+ dconf keys are compiled into the user's dconf database, with `dconf-cli`, once when the app first starts; `data/reset` does not restore them.
25
+
26
+ ## Task `fix-label-name`
27
+
28
+ `tasks/fix-label-name.json` deploys the app, has the agent work through the computer from the prompt below, and grades
29
+ the outcome with `artifacts/fix-label-name-check/verify.py`, which reads the app's `data/get` views and needs
30
+ no model. It grades once the app's files have held for 3 s, so a save the app makes on its own within that
31
+ time of the agent stopping counts; each result's `settled` is false when they were still changing 15 s after the
32
+ first read. `evals/glabels.toml` names it, so a run of the bundle runs it.
33
+
34
+ > The name on my address label in Documents/address-label.glabels is misspelled. It should read Marisol Penhallow. Fix the name in gLabels and save the label.
35
+
36
+ Checks, each of which must pass:
37
+
38
+ - `check-1`: `{"kind":"text_equals","file":"Documents/address-label.glabels","pointer":"/root/children/[name=Objects]/children/[name=Object-text]/children/[name=Span]","value":"Marisol Penhallow418 Juniper CourtBellmont, OR 97215"}`
39
+
40
+ REA kept the task because its checks fail on the seed (`check-1`) and all
41
+ pass on the captured end state.
42
+
43
+ To measure a solve rate, run the task k times (3 by default) with the agent and model to measure, and count the runs
44
+ whose summary line says `passed`; a run that says `failed` did not finish and is run again rather than counted:
45
+
46
+ agent-env run <this folder> --task fix-label-name --agent claude-code --model MODEL
bundle/artifacts/fix-label-name-check/verify.py ADDED
@@ -0,0 +1,559 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Checks of the task fix-label-name against the glabels app's state, exported by REA from a desktop application capture.
2
+
3
+ It reads the app's data/get through the computer, takes the typed views of its files and evaluates each check: no
4
+ model, no code from the task. It grades once the app's files settle, since an app can save a few seconds after the
5
+ last change: each result's settled says whether they had held for SETTLE_WINDOW_S, or had not by SETTLE_BOUND_S and
6
+ the last completed read was graded, and read_cut whether a read still running at SETTLE_BOUND_S was cut. A failure to
7
+ reach the app raises, so the run fails rather than scoring the agent.
8
+ """
9
+ import asyncio
10
+ import hashlib
11
+ import json
12
+ import math
13
+ import re
14
+ import time
15
+
16
+ from agentenv_protocol import client as protocol
17
+ from agentenv_protocol.types import RPC_PATH
18
+
19
+ APP = "glabels"
20
+ CHECKS = [
21
+ {"id": "check-1", "kind": "text_equals", "file": "Documents/address-label.glabels", "pointer": "/root/children/[name=Objects]/children/[name=Object-text]/children/[name=Span]", "value": "Marisol Penhallow418 Juniper CourtBellmont, OR 97215"},
22
+ ]
23
+ #: The app's data/get is read this often until its files settle.
24
+ SETTLE_INTERVAL_S = 0.5
25
+ #: How long each file's bytes must hold, from the read that returned them, before the views are graded.
26
+ SETTLE_WINDOW_S = 3.0
27
+ #: After the first read began: no read starts then or later, one still running is cut, and the last completed read is
28
+ #: graded though the files are still changing.
29
+ SETTLE_BOUND_S = 15.0
30
+ #: Where a data/get file part names its path in the home.
31
+ DATA_OBJECTS = "urn:agentenv:data-objects/v1"
32
+
33
+ MISSING = object()
34
+ INDEX = re.compile(r"0|[1-9][0-9]*")
35
+ VIEW_FORMATS = ("text", "json", "keyfile", "xml")
36
+ NUMERAL = re.compile(r"[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?")
37
+ WHITESPACE_RUN = re.compile(r"[ \t\r\n]+")
38
+
39
+
40
+ def _shown(value) -> str:
41
+ text = json.dumps(value, ensure_ascii=False, separators=(",", ":"))
42
+ return text if len(text) <= 200 else text[:200] + "…"
43
+
44
+
45
+ def _same(actual, expected) -> bool:
46
+ """JSON equality: numbers by value but never a boolean for a number, objects by their keys, arrays in order."""
47
+ if isinstance(expected, list):
48
+ return (isinstance(actual, list) and len(actual) == len(expected)
49
+ and all(_same(item, wanted) for item, wanted in zip(actual, expected)))
50
+ if isinstance(expected, dict):
51
+ return (isinstance(actual, dict) and len(actual) == len(expected)
52
+ and all(key in actual and _same(actual[key], value) for key, value in expected.items()))
53
+ if isinstance(expected, bool) or isinstance(actual, bool):
54
+ return isinstance(expected, bool) and isinstance(actual, bool) and actual == expected
55
+ if isinstance(expected, (int, float)):
56
+ return isinstance(actual, (int, float)) and actual == expected
57
+ return type(actual) is type(expected) and actual == expected
58
+
59
+
60
+ def _is_element(value) -> bool:
61
+ return (isinstance(value, dict) and isinstance(value.get("name"), str) and isinstance(value.get("attributes"), dict)
62
+ and isinstance(value.get("children"), list))
63
+
64
+
65
+ def _element_text(element, attribute=None) -> str:
66
+ """An element's text as XPath's string() reads it from what the view keeps: every text node among its children
67
+ and its descendants', in document order. With attribute, the values of that attribute on it and its descendants
68
+ instead, in document order, and no text node."""
69
+ parts, pending = [], [element]
70
+ while pending:
71
+ node = pending.pop()
72
+ if isinstance(node, str):
73
+ if attribute is None:
74
+ parts.append(node)
75
+ elif _is_element(node):
76
+ if attribute is not None and isinstance(node["attributes"].get(attribute), str):
77
+ parts.append(node["attributes"][attribute])
78
+ pending.extend(reversed(node["children"]))
79
+ return "".join(parts)
80
+
81
+
82
+ def _bracketed(token: str) -> bool:
83
+ return len(token) >= 2 and token.startswith("[") and token.endswith("]")
84
+
85
+
86
+ def _selector(token: str):
87
+ """A selector's conditions, [KEY=VALUE], [@KEY=VALUE] or [>KEY=VALUE] one or more times, or None when the token
88
+ is not one."""
89
+ if not _bracketed(token):
90
+ return None
91
+ conditions = []
92
+ for part in token[1:-1].split("]["):
93
+ key, equals, value = part.partition("=")
94
+ prefix = key[:1] if key[:1] in ("@", ">") else ""
95
+ name = key[len(prefix):]
96
+ if not equals or not name:
97
+ return None
98
+ conditions.append((prefix, name, value))
99
+ return conditions
100
+
101
+
102
+ def _has_child_text(member, key: str, value: str) -> bool:
103
+ """Whether an element has a child element named key whose text, its whitespace collapsed, is value."""
104
+ return _is_element(member) and any(
105
+ _is_element(child) and child["name"] == key and _collapse_whitespace(_element_text(child)) == value
106
+ for child in member["children"])
107
+
108
+
109
+ def _selects(member, conditions) -> bool:
110
+ """Whether an array member meets every condition; selectors compare strings only."""
111
+ if not isinstance(member, dict):
112
+ return False
113
+ for prefix, key, value in conditions:
114
+ if prefix == ">":
115
+ if not _has_child_text(member, key, value):
116
+ return False
117
+ continue
118
+ fields = member.get("attributes") if prefix == "@" else member
119
+ if not isinstance(fields, dict) or not isinstance(fields.get(key), str) or fields[key] != value:
120
+ return False
121
+ return True
122
+
123
+
124
+ def _step(items: list, token: str, last: bool):
125
+ """One step into an array, by index or by a selector that must match one member, or none when it is the last."""
126
+ if INDEX.fullmatch(token):
127
+ return ("member", items[int(token)]) if int(token) < len(items) else ("none", None)
128
+ conditions = _selector(token)
129
+ if conditions is None:
130
+ return ("unresolved", f"{token} is not a selector of the form [KEY=VALUE]") if _bracketed(token) else (
131
+ "none", None)
132
+ matched = [item for item in items if _selects(item, conditions)]
133
+ if len(matched) == 1:
134
+ return "member", matched[0]
135
+ if len(matched) > 1:
136
+ return "unresolved", f"{token} matches {len(matched)} members, not one"
137
+ return ("none" if last else "unresolved"), f"{token} matches no member"
138
+
139
+
140
+ def _locate(view, pointer: str):
141
+ """Where a pointer leads: ("value", value), ("none", why or None) or ("unresolved", problem), with the pointers
142
+ to the arrays a selector searched on the way."""
143
+ current, searched = view, []
144
+ segments = pointer[1:].split("/")
145
+ for position, segment in enumerate(segments):
146
+ token = segment.replace("~1", "/").replace("~0", "~")
147
+ if isinstance(current, list):
148
+ if not INDEX.fullmatch(token) and _selector(token) is not None:
149
+ searched.append("".join("/" + part for part in segments[:position]))
150
+ kind, found = _step(current, token, position == len(segments) - 1)
151
+ if kind != "member":
152
+ return kind, found, searched
153
+ current = found
154
+ elif isinstance(current, dict) and token in current:
155
+ current = current[token]
156
+ else:
157
+ return "none", None, searched
158
+ return "value", current, searched
159
+
160
+
161
+ def _number(value):
162
+ """A number, or a numeral string read as one; None for anything else, a boolean, or a numeral past the doubles."""
163
+ if isinstance(value, bool):
164
+ return None
165
+ if isinstance(value, (int, float)):
166
+ return value
167
+ if not isinstance(value, str) or not NUMERAL.fullmatch(value):
168
+ return None
169
+ number = float(value)
170
+ return number if math.isfinite(number) else None
171
+
172
+
173
+ def _entry_leaves_out(entry) -> bool:
174
+ return isinstance(entry, dict) and (isinstance(entry.get("view_error"), str) or (
175
+ entry.get("format") in ("text", "xml") and isinstance(entry.get("view"), dict)
176
+ and entry["view"].get("truncated") is True))
177
+
178
+
179
+ def _viewless_entry(view, pointer: str):
180
+ """The name of the entry whose view a pointer goes into when it has none, so its null is no JSON value, and
181
+ why: binary, unread, or of a format without a view; None when it has one."""
182
+ parts = pointer[1:].split("/")
183
+ if len(parts) < 3 or parts[0] != "entries" or parts[2] != "view":
184
+ return None
185
+ kind, item, _ = _locate(view, "/entries/" + parts[1])
186
+ if kind != "value" or not isinstance(item, dict):
187
+ return None
188
+ if isinstance(item.get("view_error"), str):
189
+ reason = f"has no view: {item['view_error']}"
190
+ elif item.get("format") == "binary":
191
+ reason = "is binary and has no view"
192
+ elif item.get("format") not in VIEW_FORMATS:
193
+ reason = "has no view"
194
+ else:
195
+ return None
196
+ return (item["name"] if isinstance(item.get("name"), str) else ""), reason
197
+
198
+
199
+ def _array_leaves_out(form, view, array: str) -> bool:
200
+ """Whether an array a selector searched may lack members: in a zip the listing or its entry's view, else the
201
+ view's own truncation."""
202
+ if form != "zip":
203
+ return _truncated(form, view)
204
+ if array == "/entries":
205
+ return isinstance(view, dict) and view.get("truncated") is True
206
+ return _zip_leaves_out(view, array)
207
+
208
+
209
+ def _zip_leaves_out(view, pointer: str) -> bool:
210
+ """Whether a zip view leaves out what a pointer reaches: for a pointer into one listed entry, only that entry."""
211
+ if not isinstance(view, dict):
212
+ return False
213
+ parts = pointer[1:].split("/")
214
+ if parts[0] == "entries" and len(parts) > 1:
215
+ kind, entry, _ = _locate(view, "/entries/" + parts[1])
216
+ return _entry_leaves_out(entry) if kind == "value" else view.get("truncated") is True
217
+ entries = view.get("entries") if isinstance(view.get("entries"), list) else []
218
+ return view.get("truncated") is True or any(_entry_leaves_out(entry) for entry in entries)
219
+
220
+
221
+ def _truncated(form, view) -> bool:
222
+ if not isinstance(view, dict):
223
+ return False
224
+ if form in ("text", "xml"):
225
+ return view.get("truncated") is True
226
+ if form != "sqlite":
227
+ return False
228
+ tables = view.get("tables")
229
+ return view.get("tables_truncated") is True or any(
230
+ isinstance(table, dict) and (table.get("truncated") is True or isinstance(table.get("error"), str))
231
+ for table in (tables.values() if isinstance(tables, dict) else []))
232
+
233
+
234
+ def _view_of(check, entry, form):
235
+ """The view, whether it is truncated, and why the check cannot read it; an absent file reads as empty."""
236
+ if entry is None:
237
+ return None, False, None
238
+ if isinstance(entry.get("error"), str):
239
+ return None, False, f"{check['file']} has no view: {entry['error']}"
240
+ if entry.get("format") in (None, "binary"):
241
+ return None, False, f"{check['file']} is binary and has no view"
242
+ if form is not None and entry.get("format") != form:
243
+ return None, False, f"{check['file']} is read as {entry.get('format')}, not {form}"
244
+ return entry.get("view"), _truncated(entry.get("format"), entry.get("view")), None
245
+
246
+
247
+ def _undecided(check):
248
+ return False, f"the view of {check['file']} is truncated, so what it leaves out is unknown"
249
+
250
+
251
+ def _compared(check, n: int, what: str):
252
+ operator = next(key for key in ("equals", "at_least", "at_most") if check.get(key) is not None)
253
+ expected = check[operator]
254
+ met = n == expected if operator == "equals" else n >= expected if operator == "at_least" else n <= expected
255
+ return met, f"{n} {what}, expected {operator.replace('_', ' ')} {expected}"
256
+
257
+
258
+ def _lines(check, entry):
259
+ view, truncated, problem = _view_of(check, entry, "text")
260
+ if problem is not None:
261
+ return False, problem
262
+ lines = view.get("lines") if isinstance(view, dict) and isinstance(view.get("lines"), list) else []
263
+ lines = [line for line in lines if isinstance(line, str)]
264
+ file = check["file"]
265
+ if check["kind"] == "lines_present":
266
+ missing = next((line for line in check["lines"] if line not in lines), None)
267
+ return (True, f"{file} has the line(s) {_shown(check['lines'])}") if missing is None else (
268
+ False, f"{file} has no line {_shown(missing)}")
269
+ if truncated:
270
+ return _undecided(check)
271
+ if check["kind"] == "lines_absent":
272
+ found = next((line for line in check["lines"] if line in lines), None)
273
+ return (True, f"{file} has none of the lines {_shown(check['lines'])}") if found is None else (
274
+ False, f"{file} still has the line {_shown(found)}")
275
+ if check.get("contains") is not None:
276
+ n = sum(1 for line in lines if check["contains"] in line)
277
+ return _compared(check, n, f"line(s) of {file} contain {_shown(check['contains'])}")
278
+ n = sum(1 for line in lines if line == check["exact"])
279
+ return _compared(check, n, f"line(s) of {file} match {_shown(check['exact'])}")
280
+
281
+
282
+ def _near(at: str, found, expected, tolerance):
283
+ """A value compared within a tolerance: numbers, and numeral strings, by their difference."""
284
+ number = _number(found)
285
+ within = f"within {_shown(tolerance)} of {_shown(expected)}"
286
+ if number is None:
287
+ return False, f"{at} is {_shown(found)}, not a number"
288
+ if abs(number - expected) <= tolerance:
289
+ return True, f"{at} is {_shown(found)}, {within}"
290
+ return False, f"{at} is {_shown(found)}, not {within}"
291
+
292
+
293
+ def _value(check, entry):
294
+ view, truncated, problem = _view_of(check, entry, None)
295
+ if problem is not None:
296
+ return False, problem
297
+ kind, found, searched = ("none", None, []) if entry is None else _locate(view, check["pointer"])
298
+ at = f"{check['file']} at {check['pointer']}"
299
+ viewless = _viewless_entry(view, check["pointer"]) if entry is not None and entry.get("format") == "zip" else None
300
+ if viewless is not None:
301
+ return False, f"{check['file']} entry {viewless[0]} {viewless[1]}"
302
+ # A selector tells one member from several only in an array the view holds whole.
303
+ if any(_array_leaves_out(entry.get("format"), view, array) for array in searched):
304
+ return _undecided(check)
305
+ if kind == "unresolved":
306
+ return False, f"{at}: {found}"
307
+ if entry is not None and entry.get("format") == "zip":
308
+ truncated = _zip_leaves_out(view, check["pointer"])
309
+ if check["kind"] == "value_equals" and isinstance(check["value"], (dict, list)) and truncated:
310
+ return _undecided(check)
311
+ if check["kind"] == "value_equals":
312
+ if kind == "none":
313
+ return False, f"{at} has no value" if found is None else f"{at}: {found}"
314
+ expected = check["value"]
315
+ if check.get("tolerance") is not None and isinstance(expected, (int, float)) and not isinstance(expected, bool):
316
+ return _near(at, found, expected, check["tolerance"])
317
+ if _same(found, check["value"]):
318
+ return True, f"{at} is {_shown(check['value'])}"
319
+ return False, f"{at} is {_shown(found)}, not {_shown(check['value'])}"
320
+ if truncated:
321
+ return _undecided(check)
322
+ return (True, f"{at} has no value") if kind == "none" else (False, f"{at} is {_shown(found)}")
323
+
324
+
325
+ def _collapse_whitespace(text: str) -> str:
326
+ """Each run of XML whitespace (space, tab, CR, LF) made one space, none at either end, as normalize-space()."""
327
+ return WHITESPACE_RUN.sub(" ", text).strip(" ")
328
+
329
+
330
+ def _text_at(view, pointer: str) -> bool:
331
+ """Whether a string a pointer reaches is text of the document: a member of an element's children (a text node)
332
+ or attributes (an attribute's value), rather than an element's name or a field of the DOCTYPE."""
333
+ segments = pointer.split("/")
334
+ if len(segments) < 3 or segments[-2] not in ("children", "attributes"):
335
+ return False
336
+ kind, owner, _ = _locate(view, "/".join(segments[:-2]))
337
+ return kind == "value" and _is_element(owner)
338
+
339
+
340
+ def _not_xml_entry(check, view):
341
+ """Why a text check's pointer into an archive goes into no XML entry's view, or None when it does or names an
342
+ entry not listed."""
343
+ parts = check["pointer"].split("/")
344
+ if len(parts) < 4 or parts[3] != "view":
345
+ return f"{check['file']} at {check['pointer']} does not point into an entry's view"
346
+ if parts[1] != "entries":
347
+ return None
348
+ kind, item, _ = _locate(view, "/entries/" + parts[2])
349
+ if kind != "value" or not isinstance(item, dict) or item.get("format") == "xml":
350
+ return None
351
+ # An entry without a view failed before this, so its format is one with a view.
352
+ name, form = (value if isinstance(value, str) else "" for value in (item.get("name"), item.get("format")))
353
+ return f"{check['file']} entry {name} is read as {form}, not xml"
354
+
355
+
356
+ def _whole_text(check, entry):
357
+ """An element's whole text, or a text node's, compared with the value or searched for it."""
358
+ view, truncated, problem = _view_of(check, entry, None)
359
+ if problem is not None:
360
+ return False, problem
361
+ at = f"{check['file']} at {check['pointer']}"
362
+ if entry is None:
363
+ return False, f"{at} has no value"
364
+ form = entry.get("format")
365
+ if form not in ("xml", "zip"):
366
+ return False, f"{check['file']} is read as {form}, not xml"
367
+ kind, found, searched = _locate(view, check["pointer"])
368
+ viewless = _viewless_entry(view, check["pointer"]) if form == "zip" else None
369
+ if viewless is not None:
370
+ return False, f"{check['file']} entry {viewless[0]} {viewless[1]}"
371
+ if any(_array_leaves_out(form, view, array) for array in searched):
372
+ return _undecided(check)
373
+ problem = _not_xml_entry(check, view) if form == "zip" else None
374
+ if problem is not None:
375
+ return False, problem
376
+ if kind == "unresolved":
377
+ return False, f"{at}: {found}"
378
+ if kind == "none":
379
+ return False, f"{at} has no value" if found is None else f"{at}: {found}"
380
+ # Only an element has attributes of its own and of its descendants to join.
381
+ attribute = check.get("text_attribute")
382
+ if not ((attribute is None and _text_at(view, check["pointer"])) if isinstance(found, str) else _is_element(found)):
383
+ what = "an element, a text node or an attribute value" if attribute is None else "an element"
384
+ return False, f"{at} is {_shown(found)}, not {what}"
385
+ # A text node is whole. An element's text in a cut view may lack what the cut dropped from its middle.
386
+ if form == "zip":
387
+ truncated = _zip_leaves_out(view, check["pointer"])
388
+ if not isinstance(found, str) and truncated:
389
+ return _undecided(check)
390
+ return _compared_text(check, at, _element_text(found, attribute))
391
+
392
+
393
+ def _compared_text(check, at: str, found: str):
394
+ """A text found at a pointer compared with the check's value or searched for it, both collapsed when it asks."""
395
+ collapse = check.get("normalize_whitespace") is True
396
+ text = _collapse_whitespace(found) if collapse else found
397
+ value = _collapse_whitespace(check["value"]) if collapse else check["value"]
398
+ attribute = check.get("text_attribute")
399
+ read = "" if attribute is None else f" in its {attribute} values"
400
+ how = read + (" with whitespace collapsed" if collapse else "")
401
+ if check["kind"] == "text_equals":
402
+ if text == value:
403
+ return True, f"{at} has the text {_shown(value)}{how}"
404
+ return False, f"{at} has the text {_shown(text)}{how}, not {_shown(value)}"
405
+ if value in text:
406
+ return True, f"{at} has text containing {_shown(value)}{how}"
407
+ return False, f"{at} has the text {_shown(text)}{how}, without {_shown(value)}"
408
+
409
+
410
+ def _members(check, entry):
411
+ """How many members of the array at a pointer, or of those a selector matches, compared with the expected
412
+ number."""
413
+ matching, pointer = check.get("matching"), check["pointer"]
414
+ view, truncated, problem = _view_of(check, entry, None)
415
+ if problem is not None:
416
+ return False, problem
417
+ form = None if entry is None else entry.get("format")
418
+ # The empty pointer names the whole view, as a JSON file whose top level is an array.
419
+ kind, found, searched = (("none", None, []) if entry is None else ("value", view, []) if pointer == ""
420
+ else _locate(view, pointer))
421
+ at = check["file"] if pointer == "" else f"{check['file']} at {pointer}"
422
+ viewless = _viewless_entry(view, pointer) if form == "zip" else None
423
+ if viewless is not None:
424
+ return False, f"{check['file']} entry {viewless[0]} {viewless[1]}"
425
+ if any(_array_leaves_out(form, view, array) for array in searched):
426
+ return _undecided(check)
427
+ if kind == "unresolved":
428
+ return False, f"{at}: {found}"
429
+ if kind == "none":
430
+ return False, f"{at} has no value" if found is None else f"{at}: {found}"
431
+ if not isinstance(found, list):
432
+ return False, f"{at} is {_shown(found)}, not an array"
433
+ # A count is decided only on an array the view holds whole.
434
+ if _array_leaves_out(form, view, pointer):
435
+ return _undecided(check)
436
+ # The parser refuses a matching that is no selector.
437
+ conditions = None if matching is None else _selector(matching)
438
+ n = len(found) if matching is None else sum(1 for item in found if conditions and _selects(item, conditions))
439
+ return _compared(check, n, f"member(s) of {at}" + ("" if matching is None else f" matching {matching}"))
440
+
441
+
442
+ def _rows(check, entry):
443
+ view, _, problem = _view_of(check, entry, "sqlite")
444
+ if problem is not None:
445
+ return False, problem
446
+ view = view if isinstance(view, dict) else {}
447
+ tables = view.get("tables") if isinstance(view.get("tables"), dict) else {}
448
+ table = tables[check["table"]] if check["table"] in tables else MISSING
449
+ name = f"{check['file']} table {check['table']}"
450
+ if table is MISSING and view.get("tables_truncated") is True:
451
+ return _undecided(check)
452
+ table = table if isinstance(table, dict) else {}
453
+ if isinstance(table.get("error"), str):
454
+ return False, f"{name} could not be read: {table['error']}"
455
+ columns = table.get("columns") if isinstance(table.get("columns"), list) else []
456
+ rows = table.get("rows") if isinstance(table.get("rows"), list) else []
457
+ where = check.get("where") or {}
458
+
459
+ def matches(row) -> bool:
460
+ return isinstance(row, list) and all(
461
+ column in columns and columns.index(column) < len(row) and _same(row[columns.index(column)], value)
462
+ for column, value in where.items())
463
+
464
+ n = sum(1 for row in rows if matches(row))
465
+ if check["kind"] == "row_present":
466
+ return (n > 0, f"{name} has a row with {_shown(where)}" if n > 0 else f"{name} has no row with {_shown(where)}")
467
+ if table.get("truncated") is True:
468
+ return _undecided(check)
469
+ if check["kind"] == "row_absent":
470
+ return (True, f"{name} has no row with {_shown(where)}") if n == 0 else (
471
+ False, f"{name} has {n} row(s) with {_shown(where)}")
472
+ return _compared(check, n, f"row(s) of {name}" + (f" with {_shown(where)}" if "where" in check else ""))
473
+
474
+
475
+ def _verdict(check, entry):
476
+ kind = check["kind"]
477
+ if kind == "file_present":
478
+ return (entry is not None, f"{check['file']} exists" if entry is not None else f"{check['file']} does not exist")
479
+ if kind == "file_absent":
480
+ return (entry is None, f"{check['file']} does not exist" if entry is None else f"{check['file']} exists")
481
+ if kind in ("lines_present", "lines_absent", "line_count"):
482
+ return _lines(check, entry)
483
+ if kind in ("value_equals", "value_absent"):
484
+ return _value(check, entry)
485
+ if kind in ("text_equals", "text_contains"):
486
+ return _whole_text(check, entry)
487
+ if kind == "member_count":
488
+ return _members(check, entry)
489
+ return _rows(check, entry)
490
+
491
+
492
+ def evaluate(checks: list, views: dict) -> list:
493
+ """One result per check against the views data/get returned, by home path."""
494
+ results = []
495
+ for check in checks:
496
+ passed, description = _verdict(check, views.get(check["file"]))
497
+ results.append({"id": check["id"], "result": passed, "description": description})
498
+ return results
499
+
500
+
501
+ def _files(answer) -> list:
502
+ """Each file data/get returned, by its home path or its place among the parts, with the SHA-256 of its bytes as
503
+ sent: what changes when the app saves."""
504
+ files = []
505
+ for index, part in enumerate(answer.parts):
506
+ if part.kind != "file":
507
+ continue
508
+ marker = (getattr(part, "metadata", None) or {}).get(DATA_OBJECTS)
509
+ path = marker.get("path") if isinstance(marker, dict) else None
510
+ content = getattr(part.file, "bytes", None) or getattr(part.file, "uri", None) or ""
511
+ files.append((path if isinstance(path, str) else f"#{index}", hashlib.sha256(content.encode()).hexdigest()))
512
+ return sorted(files)
513
+
514
+
515
+ async def _read(url):
516
+ answer = await protocol.get_data(url, timeout=120)
517
+ states = [part.data["state"] for part in answer.parts
518
+ if part.kind == "data" and isinstance(part.data.get("state"), dict)]
519
+ if not states:
520
+ raise RuntimeError(f"the {APP} app's data/get returned no state views")
521
+ return states[0], _files(answer)
522
+
523
+
524
+ async def _settled_views(url):
525
+ """The app's views once each file's bytes have held for SETTLE_WINDOW_S, counted from the read that returned them,
526
+ read every SETTLE_INTERVAL_S; else the last completed read's. No read starts SETTLE_BOUND_S or more after the first
527
+ began, and one still running then is cut. Also whether the files had held, and whether a read was cut."""
528
+ start = time.monotonic()
529
+ # The first read is the one a grade needs, so only its own timeout bounds it.
530
+ views, files = await _read(url)
531
+ # Offsets from the first read's start: when the last completed read began, and when a read first returned the
532
+ # bytes it holds.
533
+ began, since = 0.0, time.monotonic() - start
534
+ while began - since < SETTLE_WINDOW_S:
535
+ # Reads come an interval apart, and the one that can settle the files as soon as the window allows.
536
+ at = max(min(began + SETTLE_INTERVAL_S, since + SETTLE_WINDOW_S), time.monotonic() - start)
537
+ if at >= SETTLE_BOUND_S:
538
+ return views, False, False
539
+ await asyncio.sleep(max(0.0, at - (time.monotonic() - start)))
540
+ at = max(at, time.monotonic() - start)
541
+ if at >= SETTLE_BOUND_S:
542
+ return views, False, False
543
+ try:
544
+ latest_views, latest = await asyncio.wait_for(_read(url), SETTLE_BOUND_S - at)
545
+ except asyncio.TimeoutError:
546
+ return views, False, True
547
+ began, views = at, latest_views
548
+ if latest != files:
549
+ since, files = time.monotonic() - start, latest
550
+ return views, True, False
551
+
552
+
553
+ async def verify(mcp_url, env_url):
554
+ card = await protocol.get_card(env_url)
555
+ child = protocol.find_child(card, APP)
556
+ if child is None:
557
+ raise RuntimeError(f"the computer at {env_url} lists no app named {APP}")
558
+ views, settled, read_cut = await _settled_views(env_url + (child.get("url") or RPC_PATH).removesuffix(RPC_PATH))
559
+ return [{**result, "settled": settled, "read_cut": read_cut} for result in evaluate(CHECKS, views)]
bundle/envs/glabels/SKILL.md ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ description: Use gLabels Label Designer 3 on this Linux desktop; its window has class Glabels-3.
3
+ ---
4
+
5
+ # gLabels Label Designer 3
6
+
7
+ gLabels Label Designer 3 is open on the desktop at boot. Its window's class is `Glabels-3`.
8
+
9
+ Its files live under `~/Documents`. Work through the application's own
10
+ window and dialogs; the result is read from those files.
bundle/envs/glabels/env.toml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ type = "computer_app"
2
+ module = "glabels_app.py:Glabels"
3
+ computer = "ubuntu-24.04"
4
+ driver = "reference"
bundle/envs/glabels/glabels_app.py ADDED
@@ -0,0 +1,903 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """gLabels Label Designer 3 as an agentenv computer app, exported by REA from a desktop application capture.
2
+
3
+ Package: glabels (captured at 3.4.1-4build3). Capture Evidence: ev_92a1ee88a892a24749a52e7954d21e09e8086fbf72c122cc198ac3d6f65be773.
4
+ The seed was made for the task, as saved at checkpoint seed.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import contextlib
10
+ import copy
11
+ import hashlib
12
+ import io
13
+ import json
14
+ import math
15
+ import os
16
+ import re
17
+ import sqlite3
18
+ import struct
19
+ import subprocess
20
+ import sys
21
+ import tempfile
22
+ import zipfile
23
+ import zlib
24
+ from pathlib import Path
25
+ from xml.parsers import expat
26
+
27
+ from agentenv_protocol import add_data, get_data, reset_data
28
+ from agentenv_protocol.computer import AptSource, ComputerAppEnvironment, Download, Launch, Packages, Ready, RunScript, computer_app, linux, ready_check
29
+ from agentenv_protocol.computer.app_data import INITIAL, add, get, in_thread, keep_initial, reset
30
+ from agentenv_protocol.types import DataPart
31
+
32
+ HERE = Path(__file__).resolve().parent
33
+ SEED_HOME = "/home/user"
34
+ PATHS = ["Documents"]
35
+ DCONF = "[apps/glabels-3/history]\nrecent-templates=['Avery 5160']\n\n[apps/glabels-3/objects]\ndefault-fill-color=uint32 16711935\ndefault-font-family='Serif'\ndefault-font-italic-flag=false\ndefault-font-size=12.0\ndefault-font-weight='Regular'\ndefault-line-color=uint32 255\ndefault-line-width=1.0\ndefault-text-alignment='Left'\ndefault-text-color=uint32 255\ndefault-text-line-spacing=1.0\n\n[apps/glabels-3/ui]\ngrid-visible=false\n"
36
+ TEXT_SEEDS = frozenset([])
37
+ WINDOW_CLASS = "Glabels-3"
38
+
39
+ XML_SUFFIXES = (".xml", ".xbel", ".plist", ".svg", ".ui")
40
+ GROUP_HEADER = re.compile(r"^\[([^\]]+)\]$")
41
+ LINE_BREAK = re.compile(r"\r?\n")
42
+ SQLITE_HEADER = b"SQLite format 3\x00"
43
+ GVDB_HEADER = b"GVariant"
44
+ ZIP_HEADER = b"PK\x03\x04"
45
+ GZIP_HEADER = b"\x1f\x8b\x08"
46
+ XML_SPACE = "xml:space"
47
+ MAX_VIEW_BYTES = 64 * 1024 * 1024
48
+ MAX_SAFE_INTEGER = 2**53 - 1
49
+ MAX_TABLES = 64
50
+ MAX_ROWS = 500
51
+ MAX_LINES = 5000
52
+ MAX_XML_NODES = 5000
53
+ MAX_XML_DEPTH = 64
54
+ SQLITE_BUSY_S = 0.25
55
+ MAX_PARSED_BYTES = 4 * 1024 * 1024
56
+ PARSED_TOO_LARGE = "larger than the 4 MiB limit for JSON and key file views"
57
+ MAX_JSON_VIEW_DEPTH = 500
58
+ JSON_TOO_DEEP = f"nested deeper than the {MAX_JSON_VIEW_DEPTH} levels a JSON view keeps"
59
+ #: A JSON token after any whitespace, by group: an opening, a closing, a comma, a colon, a string's quote, or a number
60
+ #: or literal. Strings are read by json's scanner, since a pattern repeating per escape holds memory for each.
61
+ JSON_TOKEN = re.compile(r'[ \t\n\r]*(?:([\[{])|([\]}])|(,)|(:)|(")|(-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?'
62
+ r"|true|false|null))")
63
+ JSON_SPACE = re.compile(r"[ \t\n\r]*")
64
+
65
+
66
+ def _respelled(text: str, home: Path) -> str:
67
+ """The seed's home path respelled to this computer's home, only where a whole path segment ends after it."""
68
+ return re.sub(re.escape(SEED_HOME) + r"(?![\w.@+~-])", lambda _: str(home), text)
69
+
70
+
71
+ def _respelled_utf16(data: bytes, home: Path) -> bytes:
72
+ """A UTF-16 text file with a byte-order mark respelled like a text seed, its mark kept; any other bytes as given."""
73
+ for mark, codec in ((b"\xff\xfe", "utf-16-le"), (b"\xfe\xff", "utf-16-be")):
74
+ if data.startswith(mark):
75
+ try:
76
+ text = data[len(mark):].decode(codec)
77
+ except UnicodeDecodeError:
78
+ return data
79
+ return mark + _respelled(text, home).encode(codec) if SEED_HOME in text else data
80
+ return data
81
+
82
+
83
+ #: What marks a window as not yet the app's own: skipping the taskbar, as splash screens and dialogs do, or a splash type.
84
+ SPLASH_MARKS = ("_NET_WM_STATE_SKIP_TASKBAR", "_NET_WM_WINDOW_TYPE_SPLASH")
85
+
86
+
87
+ def _taskbar_window(window_class: str) -> bool:
88
+ """Whether a top-level window of the given class that the taskbar lists is shown; a splash screen or a dialog
89
+ skips the taskbar."""
90
+ def xprop(*args: str) -> str:
91
+ done = subprocess.run(["xprop", *args], capture_output=True, text=True)
92
+ return done.stdout if done.returncode == 0 else ""
93
+
94
+ for window in re.findall(r"0x[0-9a-f]+", xprop("-root", "_NET_CLIENT_LIST").partition("#")[2]):
95
+ props = xprop("-id", window, "WM_CLASS", "_NET_WM_STATE", "_NET_WM_WINDOW_TYPE")
96
+ classes = re.findall(r'"((?:[^"\\]|\\.)*)"', props.partition("WM_CLASS")[2].split("\n", 1)[0])
97
+ if window_class in classes and not any(mark in props for mark in SPLASH_MARKS):
98
+ return True
99
+ return False
100
+
101
+
102
+ def _seed_home(home: Path) -> None:
103
+ """Copy the captured files into this computer's home; text files, UTF-16 ones too, have the seed's home path
104
+ respelled."""
105
+ seed = HERE / "seed"
106
+ for source in sorted(seed.rglob("*")) if seed.is_dir() else []:
107
+ if not source.is_file():
108
+ continue
109
+ relative = source.relative_to(seed).as_posix()
110
+ target = home / relative
111
+ target.parent.mkdir(parents=True, exist_ok=True)
112
+ data = source.read_bytes()
113
+ if relative in TEXT_SEEDS:
114
+ data = _respelled(data.decode("utf-8"), home).encode("utf-8")
115
+ else:
116
+ data = _respelled_utf16(data, home)
117
+ target.write_bytes(data)
118
+
119
+
120
+ def _dconf(arguments: list, environment: dict) -> str:
121
+ return subprocess.run(["dconf", *arguments], env={**os.environ, **environment}, capture_output=True, text=True,
122
+ check=True).stdout
123
+
124
+
125
+ def _load_dconf(home: Path) -> None:
126
+ """Compile the captured dconf keys into the user database without D-Bus, which is not up yet. Keys already there
127
+ stay unless captured: dconf compile reads the key files in name order and a later file wins. A failure is
128
+ reported and the app starts without them."""
129
+ if not DCONF:
130
+ return
131
+ database = home / ".config" / "dconf" / "user"
132
+ try:
133
+ database.parent.mkdir(parents=True, exist_ok=True)
134
+ with tempfile.TemporaryDirectory(dir=database.parent) as scratch:
135
+ keyfiles = Path(scratch, "keyfiles")
136
+ keyfiles.mkdir()
137
+ if database.is_file():
138
+ profile = Path(scratch, "profile")
139
+ profile.write_text(f"file-db:{database}\n")
140
+ existing = _dconf(["dump", "/"], {"DCONF_PROFILE": str(profile)})
141
+ (keyfiles / "00-existing").write_text(existing)
142
+ (keyfiles / "01-captured").write_text(_respelled(DCONF, home))
143
+ _dconf(["compile", str(Path(scratch, "user")), str(keyfiles)], {})
144
+ os.replace(Path(scratch, "user"), database)
145
+ except (OSError, subprocess.CalledProcessError) as error:
146
+ detail = (getattr(error, "stderr", None) or "").strip().splitlines()
147
+ print(f"warning: the captured dconf settings were not loaded: {detail[-1] if detail else error}",
148
+ file=sys.stderr)
149
+
150
+
151
+ def _sqlite_text(data: bytes):
152
+ text = data.decode("utf-8", "replace")
153
+ return {"text": text, "bytes_hex": data.hex()} if "�" in text else text
154
+
155
+
156
+ def _cell(value):
157
+ if isinstance(value, bytes):
158
+ return {"blob_hex": value.hex()}
159
+ if isinstance(value, int) and abs(value) > MAX_SAFE_INTEGER:
160
+ return {"integer": str(value)}
161
+ # JSON has no infinities or negative zero; REA's SQLite reader spells them as strings.
162
+ if isinstance(value, float) and (math.isinf(value) or (value == 0 and math.copysign(1, value) < 0)):
163
+ return "Infinity" if value == math.inf else "-Infinity" if value == -math.inf else "-0"
164
+ return value
165
+
166
+
167
+ def _table(db, name: str, primary_key: list) -> dict:
168
+ quoted = '"' + name.replace('"', '""') + '"'
169
+ cursor = db.execute(f"select * from main.{quoted} not indexed limit {MAX_ROWS + 1}")
170
+ rows = [[_cell(value) for value in row] for row in cursor]
171
+ return {"columns": [column[0] for column in cursor.description], "primary_key": primary_key,
172
+ "rows": rows[:MAX_ROWS], "truncated": len(rows) > MAX_ROWS}
173
+
174
+
175
+ def _sqlite(path: Path) -> dict:
176
+ """The database's ordinary tables, in schema order, up to REA's table and row limits."""
177
+ with contextlib.closing(sqlite3.connect(path.resolve().as_uri() + "?mode=ro", uri=True, timeout=SQLITE_BUSY_S)) as db:
178
+ kinds = dict(db.execute("select name, type from pragma_table_list where schema = 'main'"))
179
+ names = [name for (name,) in db.execute("select name from sqlite_schema where type = 'table'")
180
+ if kinds.get(name) == "table"]
181
+ keys = {name: [key for (key,) in db.execute(
182
+ "select name from pragma_table_info(?, 'main') where pk > 0 order by pk", (name,))]
183
+ for name in names[:MAX_TABLES]}
184
+ db.text_factory = _sqlite_text
185
+ tables = {name: _table(db, name, keys[name]) for name in names[:MAX_TABLES]}
186
+ cut = len(names) > MAX_TABLES
187
+ return {"format": "sqlite", "view": {"tables": tables, "tables_truncated": cut},
188
+ "truncated": cut or any(table["truncated"] for table in tables.values())}
189
+
190
+
191
+ def _text(text: str) -> dict:
192
+ lines = LINE_BREAK.split(text)
193
+ if lines[-1] == "":
194
+ lines.pop()
195
+ view = {"lines": lines[:MAX_LINES], "line_count": len(lines), "truncated": len(lines) > MAX_LINES}
196
+ return {"format": "text", "view": view, "truncated": view["truncated"]}
197
+
198
+
199
+ def _keyfile_line(raw: str) -> tuple:
200
+ """A key file line as REA reads it: skip (blank or comment), group, entry or other."""
201
+ line = raw.strip()
202
+ if not line or line[0] in "#;":
203
+ return ("skip",)
204
+ header = GROUP_HEADER.match(line)
205
+ if header:
206
+ return ("group", header.group(1))
207
+ key, equals, value = line.partition("=")
208
+ return ("entry", key.strip(), value.strip()) if equals and key else ("other",)
209
+
210
+
211
+ def _each_line(text: str):
212
+ """Each line of text as REA splits them, one at a time."""
213
+ start = 0
214
+ for line_break in LINE_BREAK.finditer(text):
215
+ yield text[start:line_break.start()]
216
+ start = line_break.end()
217
+ yield text[start:]
218
+
219
+
220
+ def _is_keyfile(text: str) -> bool:
221
+ """REA's rule: at least one group, and nothing a key file view would drop. Lines are read one at a time, stopping
222
+ at the first it would drop."""
223
+ group = False
224
+ for line in _each_line(text):
225
+ kind = _keyfile_line(line)[0]
226
+ if kind == "other":
227
+ return False
228
+ group = group or kind == "group"
229
+ return group
230
+
231
+
232
+ def _keyfile(text: str) -> dict:
233
+ groups, group = {}, ""
234
+ for line in map(_keyfile_line, LINE_BREAK.split(text)):
235
+ if line[0] == "group":
236
+ group = line[1]
237
+ groups.setdefault(group, {})
238
+ elif line[0] == "entry":
239
+ groups.setdefault(group, {})[line[1]] = line[2]
240
+ return groups
241
+
242
+
243
+ #: XML's whitespace, which alone can be formatting between elements; Unicode's wider set is text.
244
+ XML_WHITESPACE = " \t\r\n"
245
+ PREDEFINED_ENTITIES = ("amp", "lt", "gt", "apos", "quot")
246
+ ENTITY_REFERENCE = re.compile(r"&([^#;][^;]*);")
247
+
248
+
249
+ def _expat(namespaces: bool, doctype=None):
250
+ """An expat parser that reads a DOCTYPE as REA does: one with an internal subset, which could declare entities,
251
+ is refused, the DTD it names is never read, and a reference to an entity other than XML's five is refused where
252
+ expat would skip it. With namespaces it also enforces their rules, as REA's parser does, and without them it
253
+ reports names as the document spells them. doctype, when given, receives the declared name and identifiers."""
254
+ parser = expat.ParserCreate(namespace_separator=" " if namespaces else None)
255
+ parser.SetParamEntityParsing(expat.XML_PARAM_ENTITY_PARSING_NEVER)
256
+
257
+ def declared(name: str, system_id, public_id, internal_subset: bool) -> None:
258
+ if internal_subset:
259
+ raise ValueError("the document's DOCTYPE has an internal subset")
260
+ if doctype is not None:
261
+ doctype({"name": name, "public_id": public_id, "system_id": system_id})
262
+
263
+ def undeclared(name: str, _parameter: bool) -> None:
264
+ raise ValueError(f"the document refers to the undeclared entity {name}")
265
+
266
+ def external(*_) -> None:
267
+ raise ValueError("the document refers to an external entity")
268
+
269
+ parser.StartDoctypeDeclHandler = declared
270
+ parser.SkippedEntityHandler = undeclared
271
+ parser.ExternalEntityRefHandler = external
272
+ return parser
273
+
274
+
275
+ def _check_tag(markup: str) -> None:
276
+ """expat leaves an undeclared entity out of an attribute value without a word when a DOCTYPE names a DTD; REA's
277
+ parser refuses it. With text taken by its own handler, a start tag is the only markup expat passes here that
278
+ starts with < and a name, and it passes it whole."""
279
+ if markup[:1] == "<" and markup[1:2] not in ("!", "?", "/"):
280
+ for name in ENTITY_REFERENCE.findall(markup):
281
+ if name not in PREDEFINED_ENTITIES:
282
+ raise ValueError(f"the document refers to the undeclared entity {name}")
283
+
284
+
285
+ def _ignore_text(_text: str) -> None:
286
+ pass
287
+
288
+
289
+ class _XmlReader:
290
+ """REA's XML view built as expat reads: names as spelled, declarations as attributes, text split where REA's DOM
291
+ splits it (an empty CDATA section joins the text around it), and each node counted against REA's limits."""
292
+
293
+ def __init__(self) -> None:
294
+ self.remaining, self.truncated, self.root, self.doctype = MAX_XML_NODES, False, None, None
295
+ #: Per open element: its view or None when left out, whether xml:space="preserve" applies inside it, whether
296
+ #: it holds an element, and whether it holds text other than whitespace: whitespace-only text is formatting
297
+ #: only in an element that holds elements and no such text.
298
+ self.open = []
299
+ self.text, self.cdata = [], None
300
+
301
+ def read(self, text: str) -> None:
302
+ parser = _expat(False, self._doctype)
303
+ parser.buffer_text = True
304
+ parser.StartElementHandler, parser.EndElementHandler = self._start, self._end
305
+ parser.CharacterDataHandler = self._data
306
+ parser.StartCdataSectionHandler, parser.EndCdataSectionHandler = self._cdata_start, self._cdata_end
307
+ parser.CommentHandler = parser.ProcessingInstructionHandler = self._other
308
+ parser.Parse(text, True)
309
+
310
+ def _doctype(self, declared: dict) -> None:
311
+ self.doctype = declared
312
+
313
+ def _admit(self) -> bool:
314
+ """Whether the next node inside a kept element is kept, within the node and depth limits; one past them
315
+ marks the view truncated."""
316
+ if self.open and self.open[-1][0] is None:
317
+ return False
318
+ if self.remaining <= 0 or len(self.open) > MAX_XML_DEPTH:
319
+ self.truncated = True
320
+ return False
321
+ self.remaining -= 1
322
+ return True
323
+
324
+ def _text_node(self, text: str) -> None:
325
+ if self.open and text.strip(XML_WHITESPACE):
326
+ self.open[-1][3] = True
327
+ if self._admit():
328
+ self.open[-1][0]["children"].append(text)
329
+
330
+ def _flush(self) -> None:
331
+ if self.text:
332
+ text, self.text = "".join(self.text), []
333
+ self._text_node(text)
334
+
335
+ def _data(self, text: str) -> None:
336
+ (self.text if self.cdata is None else self.cdata).append(text)
337
+
338
+ def _cdata_start(self) -> None:
339
+ self.cdata = []
340
+
341
+ def _cdata_end(self) -> None:
342
+ text, self.cdata = "".join(self.cdata), None
343
+ if text:
344
+ self._flush()
345
+ self._text_node(text)
346
+
347
+ def _other(self, *_) -> None:
348
+ """A comment or processing instruction, counted like any node and never kept."""
349
+ self._flush()
350
+ if self.open:
351
+ self._admit()
352
+
353
+ def _start(self, name: str, attributes: dict) -> None:
354
+ self._flush()
355
+ parent = self.open[-1] if self.open else [None, False, False, False]
356
+ parent[2] = True
357
+ view = {"name": name, "attributes": attributes, "children": []} if self._admit() else None
358
+ if view is not None and parent[0] is not None:
359
+ parent[0]["children"].append(view)
360
+ space = attributes.get(XML_SPACE)
361
+ self.open.append([view, space == "preserve" if space else parent[1], False, False])
362
+
363
+ def _end(self, _name: str) -> None:
364
+ self._flush()
365
+ view, preserve, holds_element, holds_text = self.open.pop()
366
+ if view is not None and holds_element and not holds_text and not preserve:
367
+ view["children"] = [child for child in view["children"]
368
+ if not isinstance(child, str) or child.strip(XML_WHITESPACE)]
369
+ if not self.open:
370
+ self.root = view
371
+
372
+
373
+ def _xml_view(text: str):
374
+ """REA's XML view, or None for a document REA's parser refuses: a pass with namespaces checks the document as REA's
375
+ parser does, then a pass without them reads names as spelled, as REA's view keeps them, and the DOCTYPE."""
376
+ reader = _XmlReader()
377
+ try:
378
+ check = _expat(True)
379
+ check.CharacterDataHandler, check.DefaultHandler = _ignore_text, _check_tag
380
+ check.Parse(text, True)
381
+ reader.read(text)
382
+ except (expat.ExpatError, ValueError):
383
+ return None
384
+ view = {"root": reader.root, "truncated": reader.truncated}
385
+ return view if reader.doctype is None else {"doctype": reader.doctype, **view}
386
+
387
+
388
+ def _not_json(constant: str):
389
+ raise ValueError(f"{constant} is not JSON")
390
+
391
+
392
+ class _Inexact(Exception):
393
+ """A JSON number that REA's state view refuses, since reading it would change it."""
394
+
395
+
396
+ def _digits(text: str) -> str:
397
+ return re.split(r"[eE]", text.lstrip("-"))[0].replace(".", "").strip("0") or "0"
398
+
399
+
400
+ def _js_string(value: float) -> str:
401
+ """How JavaScript's String() writes a finite double: an integer below 1e21 in full, any other in shortest form."""
402
+ return str(int(value)) if value.is_integer() and abs(value) < 1e21 else repr(value)
403
+
404
+
405
+ def _safe_number(text: str) -> bool:
406
+ """lossless-json's isSafeNumber: an integer spelling within 2^53, or a float spelling that keeps its digits."""
407
+ if re.fullmatch(r"-?[0-9]+", text):
408
+ return len(text.lstrip("-")) <= 16 and abs(int(text)) <= MAX_SAFE_INTEGER
409
+ value = float(text)
410
+ if not math.isfinite(value):
411
+ return False
412
+ written = _js_string(value)
413
+ return written == text or _digits(written) == _digits(text)
414
+
415
+
416
+ def _exact_number(text: str):
417
+ """A JSON number read only when reading it changes nothing, as REA's state view rules: its spelling and its
418
+ written-back form both safe, and not -0."""
419
+ value = float(text)
420
+ if (not _safe_number(text) or not math.isfinite(value) or not _safe_number(_js_string(value))
421
+ or (value == 0 and math.copysign(1, value) < 0)):
422
+ raise _Inexact(text)
423
+ return int(text) if re.fullmatch(r"-?[0-9]+", text) else value
424
+
425
+
426
+ _INEXACT = object()
427
+ _LEVEL_END = object()
428
+
429
+
430
+ def _number_or_mark(spelling: str):
431
+ """A JSON number read exactly, or a mark for one REA's state view refuses."""
432
+ try:
433
+ return _exact_number(spelling)
434
+ except _Inexact:
435
+ return _INEXACT
436
+
437
+
438
+ def _holds_inexact(value) -> bool:
439
+ """Whether a parsed JSON value still holds a marked number once duplicate keys kept their last value; one
440
+ iterator per nesting level, so no child list is copied."""
441
+ levels = [iter((value,))]
442
+ while levels:
443
+ item = next(levels[-1], _LEVEL_END)
444
+ if item is _LEVEL_END:
445
+ levels.pop()
446
+ elif item is _INEXACT:
447
+ return True
448
+ elif isinstance(item, dict):
449
+ levels.append(iter(item.values()))
450
+ elif isinstance(item, list):
451
+ levels.append(iter(item))
452
+ return False
453
+
454
+
455
+ def _deeper_than(root, limit: int) -> bool:
456
+ """Whether a parsed JSON value nests deeper than a limit, as REA checks it: a value's depth is the number of
457
+ iterators open above it, one per nesting level, so no child list is copied."""
458
+ levels = [iter((root,))]
459
+ while levels:
460
+ item = next(levels[-1], _LEVEL_END)
461
+ if item is _LEVEL_END:
462
+ levels.pop()
463
+ elif len(levels) - 1 > limit:
464
+ return True
465
+ elif isinstance(item, dict):
466
+ levels.append(iter(item.values()))
467
+ elif isinstance(item, list):
468
+ levels.append(iter(item))
469
+ return False
470
+
471
+
472
+ def _is_json(text: str) -> bool:
473
+ """Whether text is one JSON value as REA's state view reads it, checked a token at a time without building it or
474
+ recursing: it holds a byte per open container and one string at a time, so text too deep for Python's parser or
475
+ too large to parse into a view is still told apart from other text."""
476
+ containers, expect, empty, at = bytearray(), "value", False, 0
477
+ while True:
478
+ token = JSON_TOKEN.match(text, at)
479
+ if token is None:
480
+ break
481
+ kind, at = token.lastindex, token.end()
482
+ if kind == 5:
483
+ try:
484
+ at = json.decoder.scanstring(text, at)[1]
485
+ except ValueError:
486
+ return False
487
+ if kind == 1 and expect == "value":
488
+ containers.append(ord(text[at - 1]))
489
+ expect, empty = ("value" if text[at - 1] == "[" else "key"), True
490
+ # A closing bracket's code is its opening's plus two.
491
+ elif kind == 2 and (expect == "after" or empty) and containers and containers[-1] == ord(text[at - 1]) - 2:
492
+ containers.pop()
493
+ expect, empty = "after", False
494
+ elif kind == 3 and expect == "after" and containers:
495
+ expect = "value" if containers[-1] == ord("[") else "key"
496
+ elif kind == 4 and expect == "colon":
497
+ expect = "value"
498
+ elif kind >= 5 and (expect == "value" or (kind == 5 and expect == "key")):
499
+ expect, empty = ("colon" if expect == "key" else "after"), False
500
+ else:
501
+ return False
502
+ return expect == "after" and not containers and JSON_SPACE.fullmatch(text, at) is not None
503
+
504
+
505
+ def _json_view(text: str, size: int):
506
+ """A JSON text's format and view, or why it has none, as REA reads it; None when it is not JSON. Text over the
507
+ parsed-view limit, or nested past Python's recursion limit, is told apart without building its value."""
508
+ if size > MAX_PARSED_BYTES:
509
+ return {"format": "json", "view": None, "error": PARSED_TOO_LARGE} if _is_json(text) else None
510
+ # The whole text must parse, and duplicate keys settle, before an inexact number makes it JSON with an error.
511
+ try:
512
+ view = json.loads(text, parse_constant=_not_json, parse_float=_number_or_mark, parse_int=_number_or_mark)
513
+ except RecursionError:
514
+ # Nesting too deep for Python to parse is far deeper than REA's view keeps, once the rest of it is JSON too.
515
+ return {"format": "json", "view": None, "error": JSON_TOO_DEEP} if _is_json(text) else None
516
+ except ValueError:
517
+ return None
518
+ if _holds_inexact(view):
519
+ return {"format": "json", "view": None,
520
+ "error": "a number in it cannot be read exactly, such as an integer above 2^53"}
521
+ if _deeper_than(view, MAX_JSON_VIEW_DEPTH):
522
+ return {"format": "json", "view": None, "error": JSON_TOO_DEEP}
523
+ return {"format": "json", "view": view, "truncated": False}
524
+
525
+
526
+ def _text_view(name: str, text: str, size: int) -> dict:
527
+ """The format REA's state view detects for decoded text of size bytes, and its view; a JSON or key file over the
528
+ parsed-view limit is refused before its value is built."""
529
+ trimmed = re.sub(r"^[\s]+", "", text)
530
+ if name.endswith(".json") or trimmed[:1] in ("[", "{"):
531
+ view = _json_view(text, size)
532
+ if view is not None:
533
+ return view
534
+ lowered = name.lower()
535
+ # Text that opens with an element is XML if it parses, whatever the file is called, as a Freeplane map.
536
+ if lowered.endswith(XML_SUFFIXES) or trimmed.startswith("<?xml") or re.match(r"<[A-Za-z_:]", trimmed):
537
+ view = _xml_view(text)
538
+ return _text(text) if view is None else {"format": "xml", "view": view, "truncated": view["truncated"]}
539
+ if _is_keyfile(text):
540
+ if size > MAX_PARSED_BYTES:
541
+ return {"format": "keyfile", "view": None, "error": PARSED_TOO_LARGE}
542
+ return {"format": "keyfile", "view": {"groups": _keyfile(text)}, "truncated": False}
543
+ return _text(text)
544
+
545
+
546
+ def _bytes_view(name: str, data: bytes) -> dict:
547
+ """The view of a document that is no database or archive: its text's, or none when it is binary."""
548
+ try:
549
+ text = data.decode("utf-8-sig") if b"\x00" not in data[:8192] else None
550
+ except UnicodeDecodeError:
551
+ text = None
552
+ if text is None:
553
+ return {"format": "binary", "view": None, "truncated": False}
554
+ return _text_view(name, text, len(data))
555
+
556
+
557
+ def _view(path: Path) -> dict:
558
+ """A typed JSON view of one file in the shapes of REA's state view; truncated says the view is partial."""
559
+ too_large = {"format": None, "view": None, "error": "larger than 64 MiB, the most the view reads"}
560
+ if path.stat().st_size > MAX_VIEW_BYTES:
561
+ return too_large
562
+ with path.open("rb") as file:
563
+ data = file.read(8192)
564
+ whole = data.startswith(GZIP_HEADER) or (not data.startswith(SQLITE_HEADER) and b"\x00" not in data)
565
+ data += file.read(MAX_VIEW_BYTES + 1 - len(data)) if whole else b""
566
+ if data.startswith(SQLITE_HEADER):
567
+ return _sqlite(path)
568
+ if data.startswith(ZIP_HEADER):
569
+ with path.open("rb") as file:
570
+ return _zip(file, os.fstat(file.fileno()).st_size)
571
+ if len(data) > MAX_VIEW_BYTES:
572
+ return too_large
573
+ if data.startswith(GZIP_HEADER):
574
+ return _gzip(path.name, data)
575
+ return _bytes_view(path.name, data)
576
+
577
+
578
+ def _views(home: Path, paths: list) -> dict:
579
+ """A view of every file under the app's paths, keyed by its home-relative path."""
580
+ files = {}
581
+ for owned in paths:
582
+ root = home / owned
583
+ candidates = [root] if root.is_file() else sorted(root.rglob("*")) if root.is_dir() else []
584
+ for path in candidates:
585
+ if path.is_file() and not path.is_symlink():
586
+ key = path.relative_to(home).as_posix()
587
+ try:
588
+ files[key] = _view(path)
589
+ except (OSError, ValueError, sqlite3.Error, RecursionError) as error:
590
+ files[key] = {"format": None, "view": None, "error": str(error)}
591
+ return files
592
+
593
+ MAX_ZIP_ENTRIES = 1000
594
+ MAX_ZIP_ENTRY_BYTES = 16 * 1024 * 1024
595
+ MAX_ZIP_BYTES = 64 * 1024 * 1024
596
+ MAX_ZIP_RATIO = 100
597
+ ZIP_READ_CHUNK = 64 * 1024
598
+ #: Small, since the end of each gzip member copies what is left of the piece it was read from.
599
+ GZIP_READ_CHUNK = 4 * 1024
600
+ ZIP_END = b"PK\x05\x06"
601
+ ZIP_CENTRAL = b"PK\x01\x02"
602
+ ZIP64_LOCATOR = b"PK\x06\x07"
603
+ ZIP64_END = b"PK\x06\x06"
604
+ #: Formats an archive entry may have whose reader needs a tool, a worker or another archive opened.
605
+ NOT_READ_INSIDE = ((SQLITE_HEADER, "sqlite", "a SQLite database"), (GVDB_HEADER, "dconf", "a dconf database"),
606
+ (ZIP_HEADER, "zip", "an archive"))
607
+
608
+
609
+ def _entry_view(name: str, data: bytes) -> dict:
610
+ """An archive entry's format and view by the rules a file's follow; a database or an archive inside is not
611
+ read."""
612
+ for header, form, inside in NOT_READ_INSIDE:
613
+ if data.startswith(header):
614
+ return {"format": form, "view": None, "error": f"{inside} inside an archive is not read"}
615
+ return _bytes_view(name, data)
616
+
617
+
618
+ def _zip_refusal(info, spent: int):
619
+ """Why an entry is not read, checked in REA's order, or None; spent is the archive's bytes read so far."""
620
+ if info.flag_bits & 0x1:
621
+ return "encrypted, so it is not read"
622
+ if info.compress_type not in (zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED):
623
+ return f"compressed with method {info.compress_type}, which the view does not read"
624
+ if info.file_size > MAX_ZIP_ENTRY_BYTES:
625
+ return "larger than the 16 MiB an entry's view reads"
626
+ if info.file_size > MAX_ZIP_RATIO * info.compress_size:
627
+ return f"expands more than {MAX_ZIP_RATIO} times, so it is not read"
628
+ if spent + info.file_size > MAX_ZIP_BYTES:
629
+ return "past the 64 MiB read from one archive"
630
+ return None
631
+
632
+
633
+ def _entry_bytes(archive, info):
634
+ """An entry's uncompressed bytes, or None when they fail its CRC-32 or are not exactly its declared size. Reading
635
+ stops one byte past that size, which data past a short declared size fills, and asks for a bounded chunk at a
636
+ time, which bounds what the decompressor expands per call, so a forged small size holds no more than that."""
637
+ probe = copy.copy(info)
638
+ probe.file_size = info.file_size + 1
639
+ data = bytearray()
640
+ try:
641
+ with archive.open(probe) as member:
642
+ while len(data) <= info.file_size:
643
+ chunk = member.read(min(probe.file_size - len(data), ZIP_READ_CHUNK))
644
+ if not chunk:
645
+ break
646
+ data += chunk
647
+ except (zipfile.BadZipFile, zlib.error, EOFError, OSError, ValueError):
648
+ return None
649
+ return data if len(data) == info.file_size else None
650
+
651
+
652
+ def _zip_entry(archive, info, refusal):
653
+ """One entry of a zip view: its name, size and digest, and its own format and view, or why it was not read."""
654
+ entry = {"name": info.filename, "size": info.file_size, "sha256": None, "format": None, "view": None,
655
+ "view_error": refusal}
656
+ if refusal is not None:
657
+ return entry
658
+ data = _entry_bytes(archive, info)
659
+ if data is None:
660
+ return {**entry, "view_error": "its compressed data is damaged"}
661
+ view = _entry_view(info.filename, data)
662
+ return {**entry, "sha256": hashlib.sha256(data).hexdigest(), "format": view["format"],
663
+ "view": view.get("view"), "view_error": view.get("error")}
664
+
665
+
666
+ def _zip_end(file, size: int):
667
+ """Where an archive's central directory ends, how long it is and the offset it declares, from the last end
668
+ record whose comment reaches the end of the file and, when a Zip64 locator precedes it whatever that record
669
+ holds, the Zip64 one just before the locator; None without an end record, or when sentinels defer to a
670
+ Zip64 record that is missing."""
671
+ window = min(size, 22 + 0xFFFF)
672
+ file.seek(size - window)
673
+ tail = file.read(window)
674
+ at = tail.rfind(ZIP_END, 0, len(tail) - 18)
675
+ while at >= 0 and at + 22 + int.from_bytes(tail[at + 20:at + 22], "little") != len(tail):
676
+ at = tail.rfind(ZIP_END, 0, at + 3)
677
+ if at < 0:
678
+ return None
679
+ total, length, offset = struct.unpack_from("<HII", tail, at + 10)
680
+ end = size - window + at
681
+ record = end - 20 - 56
682
+ if record < 0:
683
+ return end, length, offset
684
+ file.seek(end - 20)
685
+ if file.read(4) != ZIP64_LOCATOR:
686
+ return end, length, offset
687
+ file.seek(record)
688
+ zip64 = file.read(56)
689
+ if len(zip64) == 56 and zip64[:4] == ZIP64_END:
690
+ length, offset = struct.unpack_from("<QQ", zip64, 40)
691
+ return record, length, offset
692
+ if total == 0xFFFF or 0xFFFFFFFF in (length, offset):
693
+ return None
694
+ return end, length, offset
695
+
696
+
697
+ def _zip_unicode_path(raw: bytes, flags: int, extra: bytes):
698
+ """An Info-ZIP Unicode Path when zip.js uses it: version 1, no UTF-8 flag, and the CRC-32 of the stored name."""
699
+ at = 0
700
+ while at + 4 <= len(extra):
701
+ kind, length = struct.unpack_from("<HH", extra, at)
702
+ if kind == 0x7075:
703
+ data = extra[at + 4:at + 4 + length]
704
+ usable = (length >= 5 and len(data) == length and data[0] == 1 and not flags & 0x800
705
+ and int.from_bytes(data[1:5], "little") == zlib.crc32(raw))
706
+ return data[5:] if usable else None
707
+ at += 4 + length
708
+ return None
709
+
710
+
711
+ def _zip_ends_in_slash(raw: bytes, flags: int, extra: bytes):
712
+ """Whether an entry's name, as REA decodes it, ends in a slash; None when it must be UTF-8 and is not."""
713
+ utf8 = _zip_unicode_path(raw, flags, extra)
714
+ if utf8 is None and flags & 0x800:
715
+ utf8 = raw
716
+ if utf8 is None:
717
+ return raw.endswith(b"/")
718
+ try:
719
+ return utf8.decode("utf-8").endswith("/")
720
+ except UnicodeDecodeError:
721
+ return None
722
+
723
+
724
+ def _zip_directory(file, size: int, keep: int):
725
+ """An archive's central directory read a record at a time, keeping the first file entries' records, as many as keep allows, and
726
+ counting the rest, as REA reads it: (start, declared offset, records, count), or None when it cannot be read.
727
+ Directories are told apart as zip.js tells them: a final slash, a Unix directory mode, or the MS-DOS attribute."""
728
+ located = _zip_end(file, size)
729
+ if located is None:
730
+ return None
731
+ end, length, declared = located
732
+ start = end - length
733
+ if start < 0:
734
+ return None
735
+ file.seek(start)
736
+ records, count, at = [], 0, start
737
+ while at < end:
738
+ fixed = file.read(46)
739
+ if at + 46 > end or len(fixed) < 46 or fixed[:4] != ZIP_CENTRAL:
740
+ return None
741
+ made_by, flags = struct.unpack_from("<H2xH", fixed, 4)
742
+ name_length, extra_length, comment_length = struct.unpack_from("<HHH", fixed, 28)
743
+ external = struct.unpack_from("<I", fixed, 38)[0]
744
+ rest = file.read(name_length + extra_length + comment_length)
745
+ at += 46 + name_length + extra_length + comment_length
746
+ if len(rest) < name_length + extra_length + comment_length or at > end:
747
+ return None
748
+ slash = _zip_ends_in_slash(rest[:name_length], flags, rest[name_length:name_length + extra_length])
749
+ if slash is None:
750
+ return None
751
+ if not (slash or (external >> 16) & 0o170000 == 0o040000 or (made_by >> 8 == 0 and external & 0x10)):
752
+ count += 1
753
+ if len(records) < keep:
754
+ records.append(fixed + rest)
755
+ return start, declared, records, count
756
+
757
+
758
+ class _BoundedArchive(io.RawIOBase):
759
+ """An archive as zipfile reads it: its entries in place, then a directory of the kept records alone and end
760
+ records for them, so zipfile parses no more records than the view lists."""
761
+
762
+ def __init__(self, file, start: int, tail: bytes) -> None:
763
+ super().__init__()
764
+ self._file, self._start, self._tail, self._at = file, start, tail, 0
765
+
766
+ def readable(self) -> bool:
767
+ return True
768
+
769
+ def seekable(self) -> bool:
770
+ return True
771
+
772
+ def tell(self) -> int:
773
+ return self._at
774
+
775
+ def seek(self, offset: int, whence: int = 0) -> int:
776
+ self._at = offset + (0, self._at, self._start + len(self._tail))[whence]
777
+ return self._at
778
+
779
+ def readinto(self, buffer) -> int:
780
+ view = memoryview(buffer)
781
+ if self._at < self._start:
782
+ self._file.seek(self._at)
783
+ count = self._file.readinto(view[:self._start - self._at])
784
+ else:
785
+ chunk = self._tail[self._at - self._start:self._at - self._start + len(view)]
786
+ count = len(chunk)
787
+ view[:count] = chunk
788
+ self._at += count
789
+ return count
790
+
791
+
792
+ def _zip(file, size: int) -> dict:
793
+ """A zip archive's file entries in archive order, up to REA's entry, size, ratio and archive limits; nothing is
794
+ extracted to disk, no archive inside is opened, and zipfile is shown only the directory records listed."""
795
+ entries, spent = [], 0
796
+ try:
797
+ directory = _zip_directory(file, size, MAX_ZIP_ENTRIES)
798
+ if directory is None:
799
+ raise zipfile.BadZipFile("no readable central directory")
800
+ start, declared, records, count = directory
801
+ kept = b"".join(records)
802
+ offset = declared if declared <= 0xFFFFFFFF else start
803
+ # zipfile follows a Zip64 locator signature wherever one sits before the end record, and the kept records
804
+ # may end in those bytes, so a real Zip64 end record and locator for them come first.
805
+ tail = (kept
806
+ + struct.pack("<4sQ2H2I4Q", ZIP64_END, 44, 45, 45, 0, 0, len(records), len(records), len(kept), offset)
807
+ + struct.pack("<4sIQI", ZIP64_LOCATOR, 0, offset + len(kept), 1)
808
+ + struct.pack("<4s4H2IH", ZIP_END, 0, 0, len(records), len(records), len(kept), offset, 0))
809
+ with zipfile.ZipFile(_BoundedArchive(file, start, tail)) as archive:
810
+ for info in archive.infolist():
811
+ refusal = _zip_refusal(info, spent)
812
+ spent += info.file_size if refusal is None else 0
813
+ entries.append(_zip_entry(archive, info, refusal))
814
+ except (zipfile.BadZipFile, zlib.error, EOFError, NotImplementedError, OSError, ValueError, struct.error):
815
+ return {"format": "zip", "view": None, "error": "not a readable zip archive"}
816
+ view = {"entries": entries, "entry_count": count, "truncated": count > len(entries)}
817
+ return {"format": "zip", "view": view, "truncated": view["truncated"]}
818
+
819
+
820
+ def _gunzip(data: bytes, limit: int):
821
+ """A gzip stream's document, its members joined as REA joins them, or None once it passes limit bytes, where
822
+ decompressing stops: data after a member that starts with a zero byte is padding and ends the stream. It is read
823
+ a piece at a time, so a member's end carries over only the rest of its piece. Raises zlib.error or EOFError when
824
+ the stream is damaged or cut short."""
825
+ document, member, rest, at = bytearray(), zlib.decompressobj(16 + zlib.MAX_WBITS), b"", 0
826
+ while True:
827
+ if not rest:
828
+ if at >= len(data):
829
+ raise EOFError("the gzip stream is cut short")
830
+ rest, at = data[at:at + GZIP_READ_CHUNK], at + GZIP_READ_CHUNK
831
+ document += member.decompress(rest, limit + 1 - len(document))
832
+ if len(document) > limit:
833
+ return None
834
+ if not member.eof:
835
+ rest = member.unconsumed_tail
836
+ continue
837
+ rest = member.unused_data
838
+ if not rest and at < len(data):
839
+ rest, at = data[at:at + GZIP_READ_CHUNK], at + GZIP_READ_CHUNK
840
+ if not rest or rest[0] == 0:
841
+ return bytes(document)
842
+ member = zlib.decompressobj(16 + zlib.MAX_WBITS)
843
+
844
+
845
+ def _gzip(name: str, data: bytes) -> dict:
846
+ """A gzip file's view: its document's, decompressed within an archive entry's size and ratio limits and read by
847
+ the rules a file's follow; a database inside is not read."""
848
+ compressed = {"format": None, "compression": "gzip", "view": None}
849
+ try:
850
+ document = _gunzip(data, min(MAX_ZIP_ENTRY_BYTES, MAX_ZIP_RATIO * len(data)))
851
+ except (zlib.error, EOFError):
852
+ return {**compressed, "error": "not a readable gzip stream"}
853
+ if document is None:
854
+ return {**compressed, "error": f"expands more than {MAX_ZIP_RATIO} times, so it is not read"
855
+ if MAX_ZIP_RATIO * len(data) < MAX_ZIP_ENTRY_BYTES
856
+ else "larger than the 16 MiB a compressed document's view reads"}
857
+ for header, form, inside in NOT_READ_INSIDE:
858
+ if form != "zip" and document.startswith(header):
859
+ return {**compressed, "format": form, "error": f"{inside} inside a gzip file is not read"}
860
+ view = _zip(io.BytesIO(document), len(document)) if document.startswith(ZIP_HEADER) else _bytes_view(name, document)
861
+ return {**view, "compression": "gzip"}
862
+
863
+
864
+ @computer_app(supports=[{"os": {"type": "linux", "display": ["x11"]}, "arch": ["amd64", "arm64"]}])
865
+ @linux(
866
+ packages=Packages(apt=["glabels", "librsvg2-common", "dconf-cli"]),
867
+ launch=Launch(at="boot", command=["sh", "-c", "cd \"$HOME\" 2>/dev/null; exec 'glabels-3' \"$HOME\"/'Documents/address-label.glabels'"], window={"class": "Glabels-3"}, ready=Ready(window=True)),
868
+ paths=PATHS,
869
+ skill="SKILL.md",
870
+ )
871
+ class Glabels(ComputerAppEnvironment):
872
+ """gLabels Label Designer 3, launched at boot with the captured state in its home.
873
+
874
+ Declaring data hooks switches off agentenv's default data plane, so these call its helpers: the seed is kept as
875
+ the initial state, reset restores it, add writes files under PATHS, and get returns those files plus a typed JSON
876
+ view of each.
877
+ """
878
+
879
+ def __init__(self) -> None:
880
+ super().__init__()
881
+ if not INITIAL.exists():
882
+ _seed_home(Path.home())
883
+ _load_dconf(Path.home())
884
+ keep_initial(self.paths)
885
+
886
+ @add_data
887
+ async def add_files(self, parts: list) -> None:
888
+ await add(parts, self.paths)
889
+
890
+ @get_data
891
+ async def get_files(self, write_namespace=None) -> list:
892
+ files = await get(self.paths, write_namespace)
893
+ views = await in_thread(_views, Path.home(), self.paths)
894
+ return [*files, DataPart(data={"state": views})]
895
+
896
+ @reset_data
897
+ async def reset_files(self) -> None:
898
+ await reset(self.paths)
899
+
900
+ @ready_check
901
+ def main_window_shown(self) -> bool:
902
+ """A window of the app's class that the taskbar lists is shown, not only a splash screen or a dialog."""
903
+ return _taskbar_window(WINDOW_CLASS)
bundle/envs/glabels/seed/Documents/address-label.glabels ADDED
Binary file (530 Bytes). View file
 
bundle/evals/glabels.toml ADDED
@@ -0,0 +1 @@
 
 
1
+ tasks = ["fix-label-name"]
bundle/tasks/fix-label-name.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {"id":"env","type":"deploy_env","env_id":"glabels"},
3
+ {"id":"agent","type":"deploy_agent","env_ids":["glabels"]},
4
+ {"id":"skills","type":"add_skills","env_ids":["glabels"]},
5
+ {"id":"record","type":"start_computer_recording","env_id":"glabels","name":"agent","depends_on":["env"]},
6
+ {"id":"task","type":"prompt_agent","depends_on":["skills","record"],"prompt":"The name on my address label in Documents/address-label.glabels is misspelled. It should read Marisol Penhallow. Fix the name in gLabels and save the label."},
7
+ {"id":"check","type":"env_outcome_verifier","env_id":"glabels","file_artifact_id":"fix-label-name-check","verifier_id":"fix-label-name","depends_on":["task"]},
8
+ {"id":"end","type":"end_computer_recording","name":"agent","depends_on":["task"]}
9
+ ]
bundle/tasks/smoke.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "id": "env",
4
+ "type": "deploy_env",
5
+ "env_id": "glabels"
6
+ }
7
+ ]
media/hero.gif ADDED

Git LFS Details

  • SHA256: 0879be1dd69c130f9510a25874f59a58e0d7f76267d881bb3a2d41902ee7d9e2
  • Pointer size: 131 Bytes
  • Size of remote file: 344 kB
media/solve-1.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3958ee4f7f274ad87a9b0b55604d6e6cf72739e1565377995e80b7914728c114
3
+ size 1861240
media/solve-2.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e518cd4d90ddad0658233776e10854aba82f64edf589b5964616955526e0e24c
3
+ size 1662319
media/solve-3.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8436f647579839e1bb398c13f77ab1f35e45ef51eecbcd98b9ff3b559eedccc7
3
+ size 2534726
media/witness.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:84fe96334728fddb0ba51f7d2b49073023914abfef0fc0413e72c6e22cc8b010
3
+ size 10685370
results.json ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "environment": "gLabels",
3
+ "app_version": "gLabels 3.4 label designer",
4
+ "task": "fix-label-name",
5
+ "prompt": "The name on my address label in Documents/address-label.glabels is misspelled. It should read Marisol Penhallow. Fix the name in gLabels and save the label.",
6
+ "agent": "claude-code",
7
+ "model": "claude-sonnet-5-5",
8
+ "agentenv_framework": "0.9.1431",
9
+ "witness": "checks failed on the seed, passed after an edit made through computer actions, failed on a near miss (\"Marisol Penhallo\") and failed again after data/reset, in a fresh computer; held on the first try",
10
+ "runs": [
11
+ {
12
+ "run": 1,
13
+ "verdict": "passed",
14
+ "turns": 10,
15
+ "usd": 0.98,
16
+ "checks": {
17
+ "fix-label-name": {
18
+ "score": 1.0,
19
+ "results": [
20
+ {
21
+ "id": "check-1",
22
+ "result": true,
23
+ "description": "Documents/address-label.glabels at /root/children/[name=Objects]/children/[name=Object-text]/children/[name=Span] has the text \"Marisol Penhallow418 Juniper CourtBellmont, OR 97215\"",
24
+ "settled": true,
25
+ "read_cut": false
26
+ }
27
+ ]
28
+ }
29
+ }
30
+ },
31
+ {
32
+ "run": 2,
33
+ "verdict": "passed",
34
+ "turns": 10,
35
+ "usd": 0.46,
36
+ "checks": {
37
+ "fix-label-name": {
38
+ "score": 1.0,
39
+ "results": [
40
+ {
41
+ "id": "check-1",
42
+ "result": true,
43
+ "description": "Documents/address-label.glabels at /root/children/[name=Objects]/children/[name=Object-text]/children/[name=Span] has the text \"Marisol Penhallow418 Juniper CourtBellmont, OR 97215\"",
44
+ "settled": true,
45
+ "read_cut": false
46
+ }
47
+ ]
48
+ }
49
+ }
50
+ },
51
+ {
52
+ "run": 3,
53
+ "verdict": "passed",
54
+ "turns": 17,
55
+ "usd": 0.59,
56
+ "checks": {
57
+ "fix-label-name": {
58
+ "score": 1.0,
59
+ "results": [
60
+ {
61
+ "id": "check-1",
62
+ "result": true,
63
+ "description": "Documents/address-label.glabels at /root/children/[name=Objects]/children/[name=Object-text]/children/[name=Span] has the text \"Marisol Penhallow418 Juniper CourtBellmont, OR 97215\"",
64
+ "settled": true,
65
+ "read_cut": false
66
+ }
67
+ ]
68
+ }
69
+ }
70
+ }
71
+ ]
72
+ }