earakely-scale commited on
Commit
c2f89ec
·
verified ·
1 Parent(s): ae866fd

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: Xournal++ 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
+ - notes
14
+ - handwriting
15
+ - pdf-annotation
16
+ - from-request
17
+ ---
18
+
19
+ # Xournal++: a computer-use environment built from a one-line request
20
+
21
+ ![An agent solving the task in Xournal++](media/hero.gif)
22
+
23
+ **The real Xournal++ 1.2 handwriting notebook 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 18 minutes, with only REA's build skill and MCP tools; [How it was made](#how-it-was-made) has the request and the steps. Xournal++ opens a one-page notebook, `Documents/biology-notes.xopp`, at launch: a lined page with three typed notes, Cell Biology - Week 3, Mitochondria make ATP and Ribosomes build proteins. The agent has to add a text note that says "Quiz on Friday: bring a calculator" 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
+ > In Xournal++, add a text note that says "Quiz on Friday: bring a calculator" to the Cell Biology notebook page in Documents/biology-notes.xopp, and save it.
37
+
38
+ `bundle/artifacts/add-quiz-note-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
+ | `note-text` | `text_contains` | `Documents/biology-notes.xopp` |
43
+ | `one-new-note` | `member_count` | `Documents/biology-notes.xopp` |
44
+ | `notes-kept` | `text_contains` | `Documents/biology-notes.xopp` |
45
+
46
+ An `.xopp` file is gzip-compressed XML, and REA reads the XML inside. Each typed note is a `text` element in the page's layer. The checks read the layer: its text must contain "Quiz on Friday: bring a calculator" and, with the notes' text run together, still contain the three original notes in order, and the layer must hold exactly four text notes (`member_count`), so the new text has to be a note of its own rather than added to an existing one. REA's draft suggested a check on the page's preview image, which Xournal++ redraws on every save, and one on the layer's whole text; Claude Code discarded the first, split the second into the new-note and kept-notes checks, and added the count.
47
+
48
+ ## Results
49
+
50
+ 3 of 3 runs passed, about $0.56 per run.
51
+
52
+ | Run | Outcome | Turns | Cost | Video |
53
+ | --- | --- | --- | --- | --- |
54
+ | 1 | passed | 10 | $0.72 | [video](media/solve-1.mp4) |
55
+ | 2 | passed | 10 | $0.49 | [video](media/solve-2.mp4) |
56
+ | 3 | passed | 9 | $0.46 | [video](media/solve-3.mp4) |
57
+
58
+ ## Run it
59
+
60
+ You need Docker. `agentenv-framework` builds the computer: Ubuntu 24.04 with the app installed from Ubuntu's archive (`xournalpp` 1.2.2, with `librsvg2-common`).
61
+
62
+ ```bash
63
+ pip install agentenv-framework==0.9.1431
64
+ hf download earakely-scale/XournalppFromRequestComputerEnv-REA --repo-type dataset --local-dir xournalpp-request
65
+ agent-env run xournalpp-request/bundle --task add-quiz-note --agent claude-code --model <model>
66
+ ```
67
+
68
+ 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.
69
+
70
+ ## How it was made
71
+
72
+ 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:
73
+
74
+ > Build me a Xournal++ environment where the agent adds a text note to a small notebook page and saves it.
75
+
76
+ It asked only the skill's upfront questions, wrote no app-specific scripts, and finished in about 18 minutes. The steps were REA's usual ones:
77
+
78
+ 1. **Capture.** REA launched Xournal++ 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 note was added 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 layer holds three notes, none of them the quiz note |
86
+ | `after_edit` | pass |
87
+ | `near_miss` | fail, as expected: the note was changed to "Quiz on Friday: bring a calculater" |
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 checks expect the notebook to keep one page with one layer: a note added on a new page or in a new layer makes their pointers match two and fail.
103
+ - The note must contain the sentence exactly as written, though words around it still pass; where it sits on the page is not checked.
104
+ - The bundle installs `librsvg2-common`, the SVG image loader Xournal++'s icons need, beside the app as an extra package. The build asked for it up front.
105
+ - The computer installs whatever `xournalpp` Ubuntu 24.04's archive holds at build time (1.2.2 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. Xournal++ itself is not included: the computer installs it from Ubuntu's archive (`xournalpp` 1.2.2, with `librsvg2-common`) at build time, under its own licence (GPL-2.0-or-later).
bundle/README.md ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Xournal++ computer app
2
+
3
+ Exported by REA's `export-desktop-application` from a capture of the `xournalpp` package
4
+ (capture Evidence `ev_ae6b6473d4c3536078503ae95cc6b6ff3e22d29881d18f518b21b338a9e6142b`). It was checked against agentenv-framework
5
+ 0.9.1431.
6
+
7
+ - `envs/xournalpp/` is a computer app on the `ubuntu-24.04` base with the `reference` driver, for
8
+ `amd64` and `arm64`. It installs `xournalpp` from the distribution archive, launches `sh -c cd "$HOME" 2>/dev/null; exec 'xournalpp' "$HOME"/'Documents/biology-notes.xopp'` at boot and is ready
9
+ when a window of class `Com.github.xournalpp.xournalpp` 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/biology-notes.xopp`, the seed's one document.
13
+ - Owned paths: `~/.config/xournalpp`, `~/Documents`.
14
+ `data/get` returns their files and a typed JSON view of each; `data/reset` restores the seed.
15
+ - Seed: 3 file(s) made for the task, as saved at checkpoint `seed`.
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/xournalpp/seed/Documents/biology-notes.xopp`.
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/xournalpp/seed/` before publishing the bundle.
24
+
25
+ ## Task `add-quiz-note`
26
+
27
+ `tasks/add-quiz-note.json` deploys the app, has the agent work through the computer from the prompt below, and grades
28
+ the outcome with `artifacts/add-quiz-note-check/verify.py`, which reads the app's `data/get` views and needs
29
+ 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
30
+ time of the agent stopping counts; each result's `settled` is false when they were still changing 15 s after the
31
+ first read. `evals/xournalpp.toml` names it, so a run of the bundle runs it.
32
+
33
+ > In Xournal++, add a text note that says "Quiz on Friday: bring a calculator" to the Cell Biology notebook page in Documents/biology-notes.xopp, and save it.
34
+
35
+ Checks, each of which must pass:
36
+
37
+ - `note-text`: `{"kind":"text_contains","file":"Documents/biology-notes.xopp","pointer":"/root/children/[name=page]/children/[name=layer]","value":"Quiz on Friday: bring a calculator"}`
38
+ - `one-new-note`: `{"kind":"member_count","file":"Documents/biology-notes.xopp","pointer":"/root/children/[name=page]/children/[name=layer]/children","matching":"[name=text]","equals":4}`
39
+ - `notes-kept`: `{"kind":"text_contains","file":"Documents/biology-notes.xopp","pointer":"/root/children/[name=page]/children/[name=layer]","value":"Cell Biology - Week 3Mitochondria make ATPRibosomes build proteins"}`
40
+
41
+ REA kept the task because its checks fail on the seed (`note-text`, `one-new-note`) and all
42
+ pass on the captured end state.
43
+
44
+ To measure a solve rate, run the task k times (3 by default) with the agent and model to measure, and count the runs
45
+ whose summary line says `passed`; a run that says `failed` did not finish and is run again rather than counted:
46
+
47
+ agent-env run <this folder> --task add-quiz-note --agent claude-code --model MODEL
bundle/artifacts/add-quiz-note-check/verify.py ADDED
@@ -0,0 +1,561 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Checks of the task add-quiz-note against the xournalpp 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 = "xournalpp"
20
+ CHECKS = [
21
+ {"id": "note-text", "kind": "text_contains", "file": "Documents/biology-notes.xopp", "pointer": "/root/children/[name=page]/children/[name=layer]", "value": "Quiz on Friday: bring a calculator"},
22
+ {"id": "one-new-note", "kind": "member_count", "file": "Documents/biology-notes.xopp", "pointer": "/root/children/[name=page]/children/[name=layer]/children", "matching": "[name=text]", "equals": 4},
23
+ {"id": "notes-kept", "kind": "text_contains", "file": "Documents/biology-notes.xopp", "pointer": "/root/children/[name=page]/children/[name=layer]", "value": "Cell Biology - Week 3Mitochondria make ATPRibosomes build proteins"},
24
+ ]
25
+ #: The app's data/get is read this often until its files settle.
26
+ SETTLE_INTERVAL_S = 0.5
27
+ #: How long each file's bytes must hold, from the read that returned them, before the views are graded.
28
+ SETTLE_WINDOW_S = 3.0
29
+ #: After the first read began: no read starts then or later, one still running is cut, and the last completed read is
30
+ #: graded though the files are still changing.
31
+ SETTLE_BOUND_S = 15.0
32
+ #: Where a data/get file part names its path in the home.
33
+ DATA_OBJECTS = "urn:agentenv:data-objects/v1"
34
+
35
+ MISSING = object()
36
+ INDEX = re.compile(r"0|[1-9][0-9]*")
37
+ VIEW_FORMATS = ("text", "json", "keyfile", "xml")
38
+ NUMERAL = re.compile(r"[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?")
39
+ WHITESPACE_RUN = re.compile(r"[ \t\r\n]+")
40
+
41
+
42
+ def _shown(value) -> str:
43
+ text = json.dumps(value, ensure_ascii=False, separators=(",", ":"))
44
+ return text if len(text) <= 200 else text[:200] + "…"
45
+
46
+
47
+ def _same(actual, expected) -> bool:
48
+ """JSON equality: numbers by value but never a boolean for a number, objects by their keys, arrays in order."""
49
+ if isinstance(expected, list):
50
+ return (isinstance(actual, list) and len(actual) == len(expected)
51
+ and all(_same(item, wanted) for item, wanted in zip(actual, expected)))
52
+ if isinstance(expected, dict):
53
+ return (isinstance(actual, dict) and len(actual) == len(expected)
54
+ and all(key in actual and _same(actual[key], value) for key, value in expected.items()))
55
+ if isinstance(expected, bool) or isinstance(actual, bool):
56
+ return isinstance(expected, bool) and isinstance(actual, bool) and actual == expected
57
+ if isinstance(expected, (int, float)):
58
+ return isinstance(actual, (int, float)) and actual == expected
59
+ return type(actual) is type(expected) and actual == expected
60
+
61
+
62
+ def _is_element(value) -> bool:
63
+ return (isinstance(value, dict) and isinstance(value.get("name"), str) and isinstance(value.get("attributes"), dict)
64
+ and isinstance(value.get("children"), list))
65
+
66
+
67
+ def _element_text(element, attribute=None) -> str:
68
+ """An element's text as XPath's string() reads it from what the view keeps: every text node among its children
69
+ and its descendants', in document order. With attribute, the values of that attribute on it and its descendants
70
+ instead, in document order, and no text node."""
71
+ parts, pending = [], [element]
72
+ while pending:
73
+ node = pending.pop()
74
+ if isinstance(node, str):
75
+ if attribute is None:
76
+ parts.append(node)
77
+ elif _is_element(node):
78
+ if attribute is not None and isinstance(node["attributes"].get(attribute), str):
79
+ parts.append(node["attributes"][attribute])
80
+ pending.extend(reversed(node["children"]))
81
+ return "".join(parts)
82
+
83
+
84
+ def _bracketed(token: str) -> bool:
85
+ return len(token) >= 2 and token.startswith("[") and token.endswith("]")
86
+
87
+
88
+ def _selector(token: str):
89
+ """A selector's conditions, [KEY=VALUE], [@KEY=VALUE] or [>KEY=VALUE] one or more times, or None when the token
90
+ is not one."""
91
+ if not _bracketed(token):
92
+ return None
93
+ conditions = []
94
+ for part in token[1:-1].split("]["):
95
+ key, equals, value = part.partition("=")
96
+ prefix = key[:1] if key[:1] in ("@", ">") else ""
97
+ name = key[len(prefix):]
98
+ if not equals or not name:
99
+ return None
100
+ conditions.append((prefix, name, value))
101
+ return conditions
102
+
103
+
104
+ def _has_child_text(member, key: str, value: str) -> bool:
105
+ """Whether an element has a child element named key whose text, its whitespace collapsed, is value."""
106
+ return _is_element(member) and any(
107
+ _is_element(child) and child["name"] == key and _collapse_whitespace(_element_text(child)) == value
108
+ for child in member["children"])
109
+
110
+
111
+ def _selects(member, conditions) -> bool:
112
+ """Whether an array member meets every condition; selectors compare strings only."""
113
+ if not isinstance(member, dict):
114
+ return False
115
+ for prefix, key, value in conditions:
116
+ if prefix == ">":
117
+ if not _has_child_text(member, key, value):
118
+ return False
119
+ continue
120
+ fields = member.get("attributes") if prefix == "@" else member
121
+ if not isinstance(fields, dict) or not isinstance(fields.get(key), str) or fields[key] != value:
122
+ return False
123
+ return True
124
+
125
+
126
+ def _step(items: list, token: str, last: bool):
127
+ """One step into an array, by index or by a selector that must match one member, or none when it is the last."""
128
+ if INDEX.fullmatch(token):
129
+ return ("member", items[int(token)]) if int(token) < len(items) else ("none", None)
130
+ conditions = _selector(token)
131
+ if conditions is None:
132
+ return ("unresolved", f"{token} is not a selector of the form [KEY=VALUE]") if _bracketed(token) else (
133
+ "none", None)
134
+ matched = [item for item in items if _selects(item, conditions)]
135
+ if len(matched) == 1:
136
+ return "member", matched[0]
137
+ if len(matched) > 1:
138
+ return "unresolved", f"{token} matches {len(matched)} members, not one"
139
+ return ("none" if last else "unresolved"), f"{token} matches no member"
140
+
141
+
142
+ def _locate(view, pointer: str):
143
+ """Where a pointer leads: ("value", value), ("none", why or None) or ("unresolved", problem), with the pointers
144
+ to the arrays a selector searched on the way."""
145
+ current, searched = view, []
146
+ segments = pointer[1:].split("/")
147
+ for position, segment in enumerate(segments):
148
+ token = segment.replace("~1", "/").replace("~0", "~")
149
+ if isinstance(current, list):
150
+ if not INDEX.fullmatch(token) and _selector(token) is not None:
151
+ searched.append("".join("/" + part for part in segments[:position]))
152
+ kind, found = _step(current, token, position == len(segments) - 1)
153
+ if kind != "member":
154
+ return kind, found, searched
155
+ current = found
156
+ elif isinstance(current, dict) and token in current:
157
+ current = current[token]
158
+ else:
159
+ return "none", None, searched
160
+ return "value", current, searched
161
+
162
+
163
+ def _number(value):
164
+ """A number, or a numeral string read as one; None for anything else, a boolean, or a numeral past the doubles."""
165
+ if isinstance(value, bool):
166
+ return None
167
+ if isinstance(value, (int, float)):
168
+ return value
169
+ if not isinstance(value, str) or not NUMERAL.fullmatch(value):
170
+ return None
171
+ number = float(value)
172
+ return number if math.isfinite(number) else None
173
+
174
+
175
+ def _entry_leaves_out(entry) -> bool:
176
+ return isinstance(entry, dict) and (isinstance(entry.get("view_error"), str) or (
177
+ entry.get("format") in ("text", "xml") and isinstance(entry.get("view"), dict)
178
+ and entry["view"].get("truncated") is True))
179
+
180
+
181
+ def _viewless_entry(view, pointer: str):
182
+ """The name of the entry whose view a pointer goes into when it has none, so its null is no JSON value, and
183
+ why: binary, unread, or of a format without a view; None when it has one."""
184
+ parts = pointer[1:].split("/")
185
+ if len(parts) < 3 or parts[0] != "entries" or parts[2] != "view":
186
+ return None
187
+ kind, item, _ = _locate(view, "/entries/" + parts[1])
188
+ if kind != "value" or not isinstance(item, dict):
189
+ return None
190
+ if isinstance(item.get("view_error"), str):
191
+ reason = f"has no view: {item['view_error']}"
192
+ elif item.get("format") == "binary":
193
+ reason = "is binary and has no view"
194
+ elif item.get("format") not in VIEW_FORMATS:
195
+ reason = "has no view"
196
+ else:
197
+ return None
198
+ return (item["name"] if isinstance(item.get("name"), str) else ""), reason
199
+
200
+
201
+ def _array_leaves_out(form, view, array: str) -> bool:
202
+ """Whether an array a selector searched may lack members: in a zip the listing or its entry's view, else the
203
+ view's own truncation."""
204
+ if form != "zip":
205
+ return _truncated(form, view)
206
+ if array == "/entries":
207
+ return isinstance(view, dict) and view.get("truncated") is True
208
+ return _zip_leaves_out(view, array)
209
+
210
+
211
+ def _zip_leaves_out(view, pointer: str) -> bool:
212
+ """Whether a zip view leaves out what a pointer reaches: for a pointer into one listed entry, only that entry."""
213
+ if not isinstance(view, dict):
214
+ return False
215
+ parts = pointer[1:].split("/")
216
+ if parts[0] == "entries" and len(parts) > 1:
217
+ kind, entry, _ = _locate(view, "/entries/" + parts[1])
218
+ return _entry_leaves_out(entry) if kind == "value" else view.get("truncated") is True
219
+ entries = view.get("entries") if isinstance(view.get("entries"), list) else []
220
+ return view.get("truncated") is True or any(_entry_leaves_out(entry) for entry in entries)
221
+
222
+
223
+ def _truncated(form, view) -> bool:
224
+ if not isinstance(view, dict):
225
+ return False
226
+ if form in ("text", "xml"):
227
+ return view.get("truncated") is True
228
+ if form != "sqlite":
229
+ return False
230
+ tables = view.get("tables")
231
+ return view.get("tables_truncated") is True or any(
232
+ isinstance(table, dict) and (table.get("truncated") is True or isinstance(table.get("error"), str))
233
+ for table in (tables.values() if isinstance(tables, dict) else []))
234
+
235
+
236
+ def _view_of(check, entry, form):
237
+ """The view, whether it is truncated, and why the check cannot read it; an absent file reads as empty."""
238
+ if entry is None:
239
+ return None, False, None
240
+ if isinstance(entry.get("error"), str):
241
+ return None, False, f"{check['file']} has no view: {entry['error']}"
242
+ if entry.get("format") in (None, "binary"):
243
+ return None, False, f"{check['file']} is binary and has no view"
244
+ if form is not None and entry.get("format") != form:
245
+ return None, False, f"{check['file']} is read as {entry.get('format')}, not {form}"
246
+ return entry.get("view"), _truncated(entry.get("format"), entry.get("view")), None
247
+
248
+
249
+ def _undecided(check):
250
+ return False, f"the view of {check['file']} is truncated, so what it leaves out is unknown"
251
+
252
+
253
+ def _compared(check, n: int, what: str):
254
+ operator = next(key for key in ("equals", "at_least", "at_most") if check.get(key) is not None)
255
+ expected = check[operator]
256
+ met = n == expected if operator == "equals" else n >= expected if operator == "at_least" else n <= expected
257
+ return met, f"{n} {what}, expected {operator.replace('_', ' ')} {expected}"
258
+
259
+
260
+ def _lines(check, entry):
261
+ view, truncated, problem = _view_of(check, entry, "text")
262
+ if problem is not None:
263
+ return False, problem
264
+ lines = view.get("lines") if isinstance(view, dict) and isinstance(view.get("lines"), list) else []
265
+ lines = [line for line in lines if isinstance(line, str)]
266
+ file = check["file"]
267
+ if check["kind"] == "lines_present":
268
+ missing = next((line for line in check["lines"] if line not in lines), None)
269
+ return (True, f"{file} has the line(s) {_shown(check['lines'])}") if missing is None else (
270
+ False, f"{file} has no line {_shown(missing)}")
271
+ if truncated:
272
+ return _undecided(check)
273
+ if check["kind"] == "lines_absent":
274
+ found = next((line for line in check["lines"] if line in lines), None)
275
+ return (True, f"{file} has none of the lines {_shown(check['lines'])}") if found is None else (
276
+ False, f"{file} still has the line {_shown(found)}")
277
+ if check.get("contains") is not None:
278
+ n = sum(1 for line in lines if check["contains"] in line)
279
+ return _compared(check, n, f"line(s) of {file} contain {_shown(check['contains'])}")
280
+ n = sum(1 for line in lines if line == check["exact"])
281
+ return _compared(check, n, f"line(s) of {file} match {_shown(check['exact'])}")
282
+
283
+
284
+ def _near(at: str, found, expected, tolerance):
285
+ """A value compared within a tolerance: numbers, and numeral strings, by their difference."""
286
+ number = _number(found)
287
+ within = f"within {_shown(tolerance)} of {_shown(expected)}"
288
+ if number is None:
289
+ return False, f"{at} is {_shown(found)}, not a number"
290
+ if abs(number - expected) <= tolerance:
291
+ return True, f"{at} is {_shown(found)}, {within}"
292
+ return False, f"{at} is {_shown(found)}, not {within}"
293
+
294
+
295
+ def _value(check, entry):
296
+ view, truncated, problem = _view_of(check, entry, None)
297
+ if problem is not None:
298
+ return False, problem
299
+ kind, found, searched = ("none", None, []) if entry is None else _locate(view, check["pointer"])
300
+ at = f"{check['file']} at {check['pointer']}"
301
+ viewless = _viewless_entry(view, check["pointer"]) if entry is not None and entry.get("format") == "zip" else None
302
+ if viewless is not None:
303
+ return False, f"{check['file']} entry {viewless[0]} {viewless[1]}"
304
+ # A selector tells one member from several only in an array the view holds whole.
305
+ if any(_array_leaves_out(entry.get("format"), view, array) for array in searched):
306
+ return _undecided(check)
307
+ if kind == "unresolved":
308
+ return False, f"{at}: {found}"
309
+ if entry is not None and entry.get("format") == "zip":
310
+ truncated = _zip_leaves_out(view, check["pointer"])
311
+ if check["kind"] == "value_equals" and isinstance(check["value"], (dict, list)) and truncated:
312
+ return _undecided(check)
313
+ if check["kind"] == "value_equals":
314
+ if kind == "none":
315
+ return False, f"{at} has no value" if found is None else f"{at}: {found}"
316
+ expected = check["value"]
317
+ if check.get("tolerance") is not None and isinstance(expected, (int, float)) and not isinstance(expected, bool):
318
+ return _near(at, found, expected, check["tolerance"])
319
+ if _same(found, check["value"]):
320
+ return True, f"{at} is {_shown(check['value'])}"
321
+ return False, f"{at} is {_shown(found)}, not {_shown(check['value'])}"
322
+ if truncated:
323
+ return _undecided(check)
324
+ return (True, f"{at} has no value") if kind == "none" else (False, f"{at} is {_shown(found)}")
325
+
326
+
327
+ def _collapse_whitespace(text: str) -> str:
328
+ """Each run of XML whitespace (space, tab, CR, LF) made one space, none at either end, as normalize-space()."""
329
+ return WHITESPACE_RUN.sub(" ", text).strip(" ")
330
+
331
+
332
+ def _text_at(view, pointer: str) -> bool:
333
+ """Whether a string a pointer reaches is text of the document: a member of an element's children (a text node)
334
+ or attributes (an attribute's value), rather than an element's name or a field of the DOCTYPE."""
335
+ segments = pointer.split("/")
336
+ if len(segments) < 3 or segments[-2] not in ("children", "attributes"):
337
+ return False
338
+ kind, owner, _ = _locate(view, "/".join(segments[:-2]))
339
+ return kind == "value" and _is_element(owner)
340
+
341
+
342
+ def _not_xml_entry(check, view):
343
+ """Why a text check's pointer into an archive goes into no XML entry's view, or None when it does or names an
344
+ entry not listed."""
345
+ parts = check["pointer"].split("/")
346
+ if len(parts) < 4 or parts[3] != "view":
347
+ return f"{check['file']} at {check['pointer']} does not point into an entry's view"
348
+ if parts[1] != "entries":
349
+ return None
350
+ kind, item, _ = _locate(view, "/entries/" + parts[2])
351
+ if kind != "value" or not isinstance(item, dict) or item.get("format") == "xml":
352
+ return None
353
+ # An entry without a view failed before this, so its format is one with a view.
354
+ name, form = (value if isinstance(value, str) else "" for value in (item.get("name"), item.get("format")))
355
+ return f"{check['file']} entry {name} is read as {form}, not xml"
356
+
357
+
358
+ def _whole_text(check, entry):
359
+ """An element's whole text, or a text node's, compared with the value or searched for it."""
360
+ view, truncated, problem = _view_of(check, entry, None)
361
+ if problem is not None:
362
+ return False, problem
363
+ at = f"{check['file']} at {check['pointer']}"
364
+ if entry is None:
365
+ return False, f"{at} has no value"
366
+ form = entry.get("format")
367
+ if form not in ("xml", "zip"):
368
+ return False, f"{check['file']} is read as {form}, not xml"
369
+ kind, found, searched = _locate(view, check["pointer"])
370
+ viewless = _viewless_entry(view, check["pointer"]) if form == "zip" else None
371
+ if viewless is not None:
372
+ return False, f"{check['file']} entry {viewless[0]} {viewless[1]}"
373
+ if any(_array_leaves_out(form, view, array) for array in searched):
374
+ return _undecided(check)
375
+ problem = _not_xml_entry(check, view) if form == "zip" else None
376
+ if problem is not None:
377
+ return False, problem
378
+ if kind == "unresolved":
379
+ return False, f"{at}: {found}"
380
+ if kind == "none":
381
+ return False, f"{at} has no value" if found is None else f"{at}: {found}"
382
+ # Only an element has attributes of its own and of its descendants to join.
383
+ attribute = check.get("text_attribute")
384
+ if not ((attribute is None and _text_at(view, check["pointer"])) if isinstance(found, str) else _is_element(found)):
385
+ what = "an element, a text node or an attribute value" if attribute is None else "an element"
386
+ return False, f"{at} is {_shown(found)}, not {what}"
387
+ # A text node is whole. An element's text in a cut view may lack what the cut dropped from its middle.
388
+ if form == "zip":
389
+ truncated = _zip_leaves_out(view, check["pointer"])
390
+ if not isinstance(found, str) and truncated:
391
+ return _undecided(check)
392
+ return _compared_text(check, at, _element_text(found, attribute))
393
+
394
+
395
+ def _compared_text(check, at: str, found: str):
396
+ """A text found at a pointer compared with the check's value or searched for it, both collapsed when it asks."""
397
+ collapse = check.get("normalize_whitespace") is True
398
+ text = _collapse_whitespace(found) if collapse else found
399
+ value = _collapse_whitespace(check["value"]) if collapse else check["value"]
400
+ attribute = check.get("text_attribute")
401
+ read = "" if attribute is None else f" in its {attribute} values"
402
+ how = read + (" with whitespace collapsed" if collapse else "")
403
+ if check["kind"] == "text_equals":
404
+ if text == value:
405
+ return True, f"{at} has the text {_shown(value)}{how}"
406
+ return False, f"{at} has the text {_shown(text)}{how}, not {_shown(value)}"
407
+ if value in text:
408
+ return True, f"{at} has text containing {_shown(value)}{how}"
409
+ return False, f"{at} has the text {_shown(text)}{how}, without {_shown(value)}"
410
+
411
+
412
+ def _members(check, entry):
413
+ """How many members of the array at a pointer, or of those a selector matches, compared with the expected
414
+ number."""
415
+ matching, pointer = check.get("matching"), check["pointer"]
416
+ view, truncated, problem = _view_of(check, entry, None)
417
+ if problem is not None:
418
+ return False, problem
419
+ form = None if entry is None else entry.get("format")
420
+ # The empty pointer names the whole view, as a JSON file whose top level is an array.
421
+ kind, found, searched = (("none", None, []) if entry is None else ("value", view, []) if pointer == ""
422
+ else _locate(view, pointer))
423
+ at = check["file"] if pointer == "" else f"{check['file']} at {pointer}"
424
+ viewless = _viewless_entry(view, pointer) if form == "zip" else None
425
+ if viewless is not None:
426
+ return False, f"{check['file']} entry {viewless[0]} {viewless[1]}"
427
+ if any(_array_leaves_out(form, view, array) for array in searched):
428
+ return _undecided(check)
429
+ if kind == "unresolved":
430
+ return False, f"{at}: {found}"
431
+ if kind == "none":
432
+ return False, f"{at} has no value" if found is None else f"{at}: {found}"
433
+ if not isinstance(found, list):
434
+ return False, f"{at} is {_shown(found)}, not an array"
435
+ # A count is decided only on an array the view holds whole.
436
+ if _array_leaves_out(form, view, pointer):
437
+ return _undecided(check)
438
+ # The parser refuses a matching that is no selector.
439
+ conditions = None if matching is None else _selector(matching)
440
+ n = len(found) if matching is None else sum(1 for item in found if conditions and _selects(item, conditions))
441
+ return _compared(check, n, f"member(s) of {at}" + ("" if matching is None else f" matching {matching}"))
442
+
443
+
444
+ def _rows(check, entry):
445
+ view, _, problem = _view_of(check, entry, "sqlite")
446
+ if problem is not None:
447
+ return False, problem
448
+ view = view if isinstance(view, dict) else {}
449
+ tables = view.get("tables") if isinstance(view.get("tables"), dict) else {}
450
+ table = tables[check["table"]] if check["table"] in tables else MISSING
451
+ name = f"{check['file']} table {check['table']}"
452
+ if table is MISSING and view.get("tables_truncated") is True:
453
+ return _undecided(check)
454
+ table = table if isinstance(table, dict) else {}
455
+ if isinstance(table.get("error"), str):
456
+ return False, f"{name} could not be read: {table['error']}"
457
+ columns = table.get("columns") if isinstance(table.get("columns"), list) else []
458
+ rows = table.get("rows") if isinstance(table.get("rows"), list) else []
459
+ where = check.get("where") or {}
460
+
461
+ def matches(row) -> bool:
462
+ return isinstance(row, list) and all(
463
+ column in columns and columns.index(column) < len(row) and _same(row[columns.index(column)], value)
464
+ for column, value in where.items())
465
+
466
+ n = sum(1 for row in rows if matches(row))
467
+ if check["kind"] == "row_present":
468
+ return (n > 0, f"{name} has a row with {_shown(where)}" if n > 0 else f"{name} has no row with {_shown(where)}")
469
+ if table.get("truncated") is True:
470
+ return _undecided(check)
471
+ if check["kind"] == "row_absent":
472
+ return (True, f"{name} has no row with {_shown(where)}") if n == 0 else (
473
+ False, f"{name} has {n} row(s) with {_shown(where)}")
474
+ return _compared(check, n, f"row(s) of {name}" + (f" with {_shown(where)}" if "where" in check else ""))
475
+
476
+
477
+ def _verdict(check, entry):
478
+ kind = check["kind"]
479
+ if kind == "file_present":
480
+ return (entry is not None, f"{check['file']} exists" if entry is not None else f"{check['file']} does not exist")
481
+ if kind == "file_absent":
482
+ return (entry is None, f"{check['file']} does not exist" if entry is None else f"{check['file']} exists")
483
+ if kind in ("lines_present", "lines_absent", "line_count"):
484
+ return _lines(check, entry)
485
+ if kind in ("value_equals", "value_absent"):
486
+ return _value(check, entry)
487
+ if kind in ("text_equals", "text_contains"):
488
+ return _whole_text(check, entry)
489
+ if kind == "member_count":
490
+ return _members(check, entry)
491
+ return _rows(check, entry)
492
+
493
+
494
+ def evaluate(checks: list, views: dict) -> list:
495
+ """One result per check against the views data/get returned, by home path."""
496
+ results = []
497
+ for check in checks:
498
+ passed, description = _verdict(check, views.get(check["file"]))
499
+ results.append({"id": check["id"], "result": passed, "description": description})
500
+ return results
501
+
502
+
503
+ def _files(answer) -> list:
504
+ """Each file data/get returned, by its home path or its place among the parts, with the SHA-256 of its bytes as
505
+ sent: what changes when the app saves."""
506
+ files = []
507
+ for index, part in enumerate(answer.parts):
508
+ if part.kind != "file":
509
+ continue
510
+ marker = (getattr(part, "metadata", None) or {}).get(DATA_OBJECTS)
511
+ path = marker.get("path") if isinstance(marker, dict) else None
512
+ content = getattr(part.file, "bytes", None) or getattr(part.file, "uri", None) or ""
513
+ files.append((path if isinstance(path, str) else f"#{index}", hashlib.sha256(content.encode()).hexdigest()))
514
+ return sorted(files)
515
+
516
+
517
+ async def _read(url):
518
+ answer = await protocol.get_data(url, timeout=120)
519
+ states = [part.data["state"] for part in answer.parts
520
+ if part.kind == "data" and isinstance(part.data.get("state"), dict)]
521
+ if not states:
522
+ raise RuntimeError(f"the {APP} app's data/get returned no state views")
523
+ return states[0], _files(answer)
524
+
525
+
526
+ async def _settled_views(url):
527
+ """The app's views once each file's bytes have held for SETTLE_WINDOW_S, counted from the read that returned them,
528
+ read every SETTLE_INTERVAL_S; else the last completed read's. No read starts SETTLE_BOUND_S or more after the first
529
+ began, and one still running then is cut. Also whether the files had held, and whether a read was cut."""
530
+ start = time.monotonic()
531
+ # The first read is the one a grade needs, so only its own timeout bounds it.
532
+ views, files = await _read(url)
533
+ # Offsets from the first read's start: when the last completed read began, and when a read first returned the
534
+ # bytes it holds.
535
+ began, since = 0.0, time.monotonic() - start
536
+ while began - since < SETTLE_WINDOW_S:
537
+ # Reads come an interval apart, and the one that can settle the files as soon as the window allows.
538
+ at = max(min(began + SETTLE_INTERVAL_S, since + SETTLE_WINDOW_S), time.monotonic() - start)
539
+ if at >= SETTLE_BOUND_S:
540
+ return views, False, False
541
+ await asyncio.sleep(max(0.0, at - (time.monotonic() - start)))
542
+ at = max(at, time.monotonic() - start)
543
+ if at >= SETTLE_BOUND_S:
544
+ return views, False, False
545
+ try:
546
+ latest_views, latest = await asyncio.wait_for(_read(url), SETTLE_BOUND_S - at)
547
+ except asyncio.TimeoutError:
548
+ return views, False, True
549
+ began, views = at, latest_views
550
+ if latest != files:
551
+ since, files = time.monotonic() - start, latest
552
+ return views, True, False
553
+
554
+
555
+ async def verify(mcp_url, env_url):
556
+ card = await protocol.get_card(env_url)
557
+ child = protocol.find_child(card, APP)
558
+ if child is None:
559
+ raise RuntimeError(f"the computer at {env_url} lists no app named {APP}")
560
+ views, settled, read_cut = await _settled_views(env_url + (child.get("url") or RPC_PATH).removesuffix(RPC_PATH))
561
+ return [{**result, "settled": settled, "read_cut": read_cut} for result in evaluate(CHECKS, views)]
bundle/envs/xournalpp/SKILL.md ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ description: Use Xournal++ on this Linux desktop; its window has class Com.github.xournalpp.xournalpp.
3
+ ---
4
+
5
+ # Xournal++
6
+
7
+ Xournal++ is open on the desktop at boot. Its window's class is `Com.github.xournalpp.xournalpp`.
8
+
9
+ Its files live under `~/.config/xournalpp`, `~/Documents`. Work through the application's own
10
+ window and dialogs; the result is read from those files.
bundle/envs/xournalpp/env.toml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ type = "computer_app"
2
+ module = "xournalpp_app.py:Xournalpp"
3
+ computer = "ubuntu-24.04"
4
+ driver = "reference"
bundle/envs/xournalpp/seed/.config/xournalpp/palette.gpl ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GIMP Palette
2
+ Name: Xournal Default Palette
3
+ #
4
+ 0 0 0 Black
5
+ 0 128 0 Green
6
+ 0 192 255 Light Blue
7
+ 0 255 0 Light Green
8
+ 51 51 204 Blue
9
+ 128 128 128 Gray
10
+ 255 0 0 Red
11
+ 255 0 255 Magenta
12
+ 255 128 0 Orange
13
+ 255 255 0 Yellow
14
+ 255 255 255 White
bundle/envs/xournalpp/seed/.config/xournalpp/settings.xml ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <!--The Xournal++ settings file. Do not edit this file! Most settings are available in the Settings dialog, the others are commented in this file, but handle with care!-->
3
+ <settings>
4
+ <property name="pressureSensitivity" value="true"/>
5
+ <property name="minimumPressure" value="0.05"/>
6
+ <property name="pressureMultiplier" value="1"/>
7
+ <property name="zoomGesturesEnabled" value="true"/>
8
+ <property name="selectedToolbar" value="Portrait"/>
9
+ <property name="lastSavePath" value="/home/user/Documents"/>
10
+ <property name="lastOpenPath" value=""/>
11
+ <property name="lastImagePath" value=""/>
12
+ <property name="edgePanSpeed" value="20"/>
13
+ <property name="edgePanMaxMult" value="5"/>
14
+ <property name="zoomStep" value="10"/>
15
+ <property name="zoomStepScroll" value="2"/>
16
+ <property name="displayDpi" value="72"/>
17
+ <property name="mainWndWidth" value="800"/>
18
+ <property name="mainWndHeight" value="600"/>
19
+ <property name="maximized" value="false"/>
20
+ <property name="showToolbar" value="true"/>
21
+ <property name="showSidebar" value="true"/>
22
+ <property name="sidebarWidth" value="150"/>
23
+ <property name="sidebarNumberingStyle" value="1"/>
24
+ <property name="sidebarOnRight" value="false"/>
25
+ <property name="scrollbarOnLeft" value="false"/>
26
+ <property name="menubarVisible" value="true"/>
27
+ <property name="filepathShownInTitlebar" value="false"/>
28
+ <property name="numColumns" value="1"/>
29
+ <property name="numRows" value="1"/>
30
+ <property name="viewFixedRows" value="false"/>
31
+ <property name="showPairedPages" value="false"/>
32
+ <property name="layoutVertical" value="false"/>
33
+ <property name="layoutRightToLeft" value="false"/>
34
+ <property name="layoutBottomToTop" value="false"/>
35
+ <property name="numPairsOffset" value="1"/>
36
+ <!--The icon theme, allowed values are "disabled", "onDrawOfLastPage", and "onScrollOfLastPage"-->
37
+ <property name="emptyLastPageAppend" value="disabled"/>
38
+ <property name="presentationMode" value="false"/>
39
+ <!--Which GUI elements are shown in default view mode, separated by a colon (,)-->
40
+ <property name="defaultViewModeAttributes" value="showMenubar,showToolbar,showSidebar"/>
41
+ <!--Which GUI elements are shown in fullscreen view mode, separated by a colon (,)-->
42
+ <property name="fullscreenViewModeAttributes" value="goFullscren,showToolbar,showSidebar"/>
43
+ <!--Which GUI elements are shown in presentation view mode, separated by a colon (,)-->
44
+ <property name="presentationViewModeAttributes" value="goFullscren,showToolbar"/>
45
+ <!--The cursor icon used with a stylus, allowed values are "none", "dot", "big", "arrow"-->
46
+ <property name="stylusCursorType" value="dot"/>
47
+ <!--The eraser cursor visibility used with a stylus, allowed values are "never", "always", "hover", "touch"-->
48
+ <property name="eraserVisibility" value="always"/>
49
+ <!--The icon theme, allowed values are "iconsColor", "iconsLucide"-->
50
+ <property name="iconTheme" value="iconsColor"/>
51
+ <property name="highlightPosition" value="false"/>
52
+ <property name="cursorHighlightColor" value="2164260608"/>
53
+ <property name="cursorHighlightBorderColor" value="2147483903"/>
54
+ <property name="cursorHighlightRadius" value="30"/>
55
+ <property name="cursorHighlightBorderWidth" value="0"/>
56
+ <property name="darkTheme" value="false"/>
57
+ <property name="useStockIcons" value="false"/>
58
+ <property name="disableScrollbarFadeout" value="false"/>
59
+ <property name="disableAudio" value="false"/>
60
+ <!--Hides scroolbars in the main window, allowed values: "none", "horizontal", "vertical", "both"-->
61
+ <property name="scrollbarHideType" value="none"/>
62
+ <property name="autoloadMostRecent" value="false"/>
63
+ <property name="autoloadPdfXoj" value="true"/>
64
+ <property name="defaultSaveName" value="%F-Note-%H-%M"/>
65
+ <property name="defaultPdfExportName" value="%{name}_annotated"/>
66
+ <property name="autosaveEnabled" value="true"/>
67
+ <property name="autosaveTimeout" value="3"/>
68
+ <property name="addHorizontalSpace" value="false"/>
69
+ <property name="addHorizontalSpaceAmount" value="150"/>
70
+ <property name="addVerticalSpace" value="false"/>
71
+ <property name="addVerticalSpaceAmount" value="150"/>
72
+ <property name="drawDirModsEnabled" value="false"/>
73
+ <property name="drawDirModsRadius" value="50"/>
74
+ <property name="snapRotation" value="true"/>
75
+ <property name="snapRotationTolerance" value="0.3"/>
76
+ <property name="snapGrid" value="true"/>
77
+ <property name="snapGridTolerance" value="0.5"/>
78
+ <property name="snapGridSize" value="14.17"/>
79
+ <property name="strokeRecognizerMinSize" value="40"/>
80
+ <property name="touchDrawing" value="false"/>
81
+ <property name="gtkTouchInertialScrolling" value="true"/>
82
+ <property name="pressureGuessing" value="false"/>
83
+ <property name="selectionBorderColor" value="4294901760"/>
84
+ <property name="backgroundColor" value="4292664021"/>
85
+ <property name="selectionMarkerColor" value="4285702095"/>
86
+ <property name="touchZoomStartThreshold" value="0"/>
87
+ <property name="pageRerenderThreshold" value="5"/>
88
+ <!--The count of rendered PDF pages which will be cached.-->
89
+ <property name="pdfPageCacheSize" value="10"/>
90
+ <property name="preloadPagesBefore" value="3"/>
91
+ <property name="preloadPagesAfter" value="5"/>
92
+ <property name="eagerPageCleanup" value="true"/>
93
+ <!--Config for new pages-->
94
+ <property name="pageTemplate" value="xoj/template&#10;copyLastPageSettings=true&#10;size=595.275591x841.889764&#10;backgroundType=lined&#10;backgroundColor=#ffffff&#10;"/>
95
+ <property name="sizeUnit" value=""/>
96
+ <property name="audioFolder" value=""/>
97
+ <property name="audioInputDevice" value="-1"/>
98
+ <property name="audioOutputDevice" value="-1"/>
99
+ <property name="audioSampleRate" value="44100"/>
100
+ <property name="audioGain" value="1"/>
101
+ <property name="defaultSeekTime" value="5"/>
102
+ <property name="pluginEnabled" value=""/>
103
+ <property name="pluginDisabled" value=""/>
104
+ <property name="strokeFilterIgnoreTime" value="150"/>
105
+ <property name="strokeFilterIgnoreLength" value="1"/>
106
+ <property name="strokeFilterSuccessiveTime" value="500"/>
107
+ <property name="strokeFilterEnabled" value="false"/>
108
+ <property name="doActionOnStrokeFiltered" value="false"/>
109
+ <property name="trySelectOnStrokeFiltered" value="false"/>
110
+ <property name="snapRecognizedShapesEnabled" value="false"/>
111
+ <property name="restoreLineWidthEnabled" value="false"/>
112
+ <property name="numIgnoredStylusEvents" value="0"/>
113
+ <property name="inputSystemTPCButton" value="false"/>
114
+ <property name="inputSystemDrawOutsideWindow" value="true"/>
115
+ <property name="preferredLocale" value=""/>
116
+ <property name="stabilizerAveragingMethod" value="0"/>
117
+ <property name="stabilizerPreprocessor" value="0"/>
118
+ <property name="stabilizerBuffersize" value="20"/>
119
+ <property name="stabilizerSigma" value="0.5"/>
120
+ <property name="stabilizerDeadzoneRadius" value="1.3"/>
121
+ <property name="stabilizerDrag" value="0.4"/>
122
+ <property name="stabilizerMass" value="5"/>
123
+ <property name="stabilizerCuspDetection" value="true"/>
124
+ <property name="stabilizerFinalizeStroke" value="true"/>
125
+ <property name="latexSettings.autoCheckDependencies" value="true"/>
126
+ <property name="latexSettings.defaultText" value="x^2"/>
127
+ <property name="latexSettings.globalTemplatePath" value="/usr/share/xournalpp/resources/default_template.tex"/>
128
+ <property name="latexSettings.genCmd" value="pdflatex -halt-on-error -interaction=nonstopmode '{}'"/>
129
+ <property name="latexSettings.sourceViewThemeId" value=""/>
130
+ <property name="latexSettings.editorFont" value="Monospace 12"/>
131
+ <property name="latexSettings.useCustomEditorFont" value="false"/>
132
+ <property name="latexSettings.editorWordWrap" value="true"/>
133
+ <property name="latexSettings.sourceViewAutoIndent" value="true"/>
134
+ <property name="latexSettings.sourceViewSyntaxHighlight" value="true"/>
135
+ <property name="latexSettings.sourceViewShowLineNumbers" value="false"/>
136
+ <property name="font" font="Sans" size="12"/>
137
+ <data name="buttonConfig">
138
+ <data name="default">
139
+ <attribute name="color" type="hex" value="ff000000"/>
140
+ <attribute name="drawingType" type="string" value="default"/>
141
+ <attribute name="size" type="string" value="thin"/>
142
+ <attribute name="tool" type="string" value="pen"/>
143
+ </data>
144
+ <data name="eraser">
145
+ <attribute name="eraserMode" type="string" value="none"/>
146
+ <attribute name="size" type="string" value="none"/>
147
+ <attribute name="tool" type="string" value="eraser"/>
148
+ </data>
149
+ <data name="middle">
150
+ <attribute name="tool" type="string" value="hand"/>
151
+ </data>
152
+ <data name="right">
153
+ <attribute name="tool" type="string" value="none"/>
154
+ </data>
155
+ <data name="stylus">
156
+ <attribute name="tool" type="string" value="none"/>
157
+ </data>
158
+ <data name="stylus2">
159
+ <attribute name="tool" type="string" value="none"/>
160
+ </data>
161
+ <data name="touch">
162
+ <attribute name="device" type="string" value=""/>
163
+ <attribute name="disableDrawing" type="boolean" value="false"/>
164
+ <attribute name="tool" type="string" value="none"/>
165
+ </data>
166
+ </data>
167
+ <data name="deviceClasses">
168
+ <data name="Virtual core XTEST pointer">
169
+ <attribute name="deviceClass" type="int" value="1"/>
170
+ <attribute name="deviceSource" type="int" value="0"/>
171
+ </data>
172
+ </data>
173
+ <data name="tools"/>
174
+ <data name="touch"/>
175
+ </settings>
bundle/envs/xournalpp/seed/Documents/biology-notes.xopp ADDED
Binary file (1.13 kB). View file
 
bundle/envs/xournalpp/xournalpp_app.py ADDED
@@ -0,0 +1,903 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Xournal++ as an agentenv computer app, exported by REA from a desktop application capture.
2
+
3
+ Package: xournalpp (captured at 1.2.2-2build3). Capture Evidence: ev_ae6b6473d4c3536078503ae95cc6b6ff3e22d29881d18f518b21b338a9e6142b.
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 = [".config/xournalpp", "Documents"]
35
+ DCONF = ""
36
+ TEXT_SEEDS = frozenset([".config/xournalpp/palette.gpl", ".config/xournalpp/settings.xml"])
37
+ WINDOW_CLASS = "Com.github.xournalpp.xournalpp"
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=["xournalpp", "librsvg2-common"]),
867
+ launch=Launch(at="boot", command=["sh", "-c", "cd \"$HOME\" 2>/dev/null; exec 'xournalpp' \"$HOME\"/'Documents/biology-notes.xopp'"], window={"class": "Com.github.xournalpp.xournalpp"}, ready=Ready(window=True)),
868
+ paths=PATHS,
869
+ skill="SKILL.md",
870
+ )
871
+ class Xournalpp(ComputerAppEnvironment):
872
+ """Xournal++, 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/evals/xournalpp.toml ADDED
@@ -0,0 +1 @@
 
 
1
+ tasks = ["add-quiz-note"]
bundle/tasks/add-quiz-note.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {"id":"env","type":"deploy_env","env_id":"xournalpp"},
3
+ {"id":"agent","type":"deploy_agent","env_ids":["xournalpp"]},
4
+ {"id":"skills","type":"add_skills","env_ids":["xournalpp"]},
5
+ {"id":"record","type":"start_computer_recording","env_id":"xournalpp","name":"agent","depends_on":["env"]},
6
+ {"id":"task","type":"prompt_agent","depends_on":["skills","record"],"prompt":"In Xournal++, add a text note that says \"Quiz on Friday: bring a calculator\" to the Cell Biology notebook page in Documents/biology-notes.xopp, and save it."},
7
+ {"id":"check","type":"env_outcome_verifier","env_id":"xournalpp","file_artifact_id":"add-quiz-note-check","verifier_id":"add-quiz-note","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": "xournalpp"
6
+ }
7
+ ]
media/hero.gif ADDED

Git LFS Details

  • SHA256: 6bd1df112bfb70a7723a07849a5ec3261e1189509d30d09deb22da08bb96daee
  • Pointer size: 131 Bytes
  • Size of remote file: 714 kB
media/solve-1.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:159ee7014c62ca5fe49cf5027de3d7414fb5f91c22ced4bfa0f04eeaa7add3d5
3
+ size 2382757
media/solve-2.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4460bed990df2014b8d942d095851de56cbe26aa2a80be0fa1773d12cd39203f
3
+ size 2382149
media/solve-3.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3331ac1c03d87fac3d72294aa9dfe05e08d57da82e344bddea1f8165208d4fdb
3
+ size 1876868
media/witness.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6003bc17d16256d6798f65a194241332fad3b54138e373ec46094b654c1aa68b
3
+ size 14409741
results.json ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "environment": "Xournal++",
3
+ "app_version": "Xournal++ 1.2 handwriting notebook",
4
+ "task": "add-quiz-note",
5
+ "prompt": "In Xournal++, add a text note that says \"Quiz on Friday: bring a calculator\" to the Cell Biology notebook page in Documents/biology-notes.xopp, and save it.",
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 a note was added through computer actions, failed on a near miss (\"bring a calculater\") 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.72,
16
+ "checks": {
17
+ "add-quiz-note": {
18
+ "score": 1.0,
19
+ "results": [
20
+ {
21
+ "id": "note-text",
22
+ "result": true,
23
+ "description": "Documents/biology-notes.xopp at /root/children/[name=page]/children/[name=layer] has text containing \"Quiz on Friday: bring a calculator\"",
24
+ "settled": true,
25
+ "read_cut": false
26
+ },
27
+ {
28
+ "id": "one-new-note",
29
+ "result": true,
30
+ "description": "4 member(s) of Documents/biology-notes.xopp at /root/children/[name=page]/children/[name=layer]/children matching [name=text], expected equals 4",
31
+ "settled": true,
32
+ "read_cut": false
33
+ },
34
+ {
35
+ "id": "notes-kept",
36
+ "result": true,
37
+ "description": "Documents/biology-notes.xopp at /root/children/[name=page]/children/[name=layer] has text containing \"Cell Biology - Week 3Mitochondria make ATPRibosomes build proteins\"",
38
+ "settled": true,
39
+ "read_cut": false
40
+ }
41
+ ]
42
+ }
43
+ }
44
+ },
45
+ {
46
+ "run": 2,
47
+ "verdict": "passed",
48
+ "turns": 10,
49
+ "usd": 0.49,
50
+ "checks": {
51
+ "add-quiz-note": {
52
+ "score": 1.0,
53
+ "results": [
54
+ {
55
+ "id": "note-text",
56
+ "result": true,
57
+ "description": "Documents/biology-notes.xopp at /root/children/[name=page]/children/[name=layer] has text containing \"Quiz on Friday: bring a calculator\"",
58
+ "settled": true,
59
+ "read_cut": false
60
+ },
61
+ {
62
+ "id": "one-new-note",
63
+ "result": true,
64
+ "description": "4 member(s) of Documents/biology-notes.xopp at /root/children/[name=page]/children/[name=layer]/children matching [name=text], expected equals 4",
65
+ "settled": true,
66
+ "read_cut": false
67
+ },
68
+ {
69
+ "id": "notes-kept",
70
+ "result": true,
71
+ "description": "Documents/biology-notes.xopp at /root/children/[name=page]/children/[name=layer] has text containing \"Cell Biology - Week 3Mitochondria make ATPRibosomes build proteins\"",
72
+ "settled": true,
73
+ "read_cut": false
74
+ }
75
+ ]
76
+ }
77
+ }
78
+ },
79
+ {
80
+ "run": 3,
81
+ "verdict": "passed",
82
+ "turns": 9,
83
+ "usd": 0.46,
84
+ "checks": {
85
+ "add-quiz-note": {
86
+ "score": 1.0,
87
+ "results": [
88
+ {
89
+ "id": "note-text",
90
+ "result": true,
91
+ "description": "Documents/biology-notes.xopp at /root/children/[name=page]/children/[name=layer] has text containing \"Quiz on Friday: bring a calculator\"",
92
+ "settled": true,
93
+ "read_cut": false
94
+ },
95
+ {
96
+ "id": "one-new-note",
97
+ "result": true,
98
+ "description": "4 member(s) of Documents/biology-notes.xopp at /root/children/[name=page]/children/[name=layer]/children matching [name=text], expected equals 4",
99
+ "settled": true,
100
+ "read_cut": false
101
+ },
102
+ {
103
+ "id": "notes-kept",
104
+ "result": true,
105
+ "description": "Documents/biology-notes.xopp at /root/children/[name=page]/children/[name=layer] has text containing \"Cell Biology - Week 3Mitochondria make ATPRibosomes build proteins\"",
106
+ "settled": true,
107
+ "read_cut": false
108
+ }
109
+ ]
110
+ }
111
+ }
112
+ }
113
+ ]
114
+ }