REA computer-use environment, v0.1.0
Browse files- README.md +111 -0
- bundle/README.md +48 -0
- bundle/artifacts/fix-customer-email-check/verify.py +492 -0
- bundle/envs/sqlitebrowser/SKILL.md +10 -0
- bundle/envs/sqlitebrowser/env.toml +4 -0
- bundle/envs/sqlitebrowser/seed/.config/sqlitebrowser/sqlitebrowser.conf +3 -0
- bundle/envs/sqlitebrowser/seed/Documents/contacts.db +0 -0
- bundle/envs/sqlitebrowser/sqlitebrowser_app.py +854 -0
- bundle/evals/sqlitebrowser.toml +1 -0
- bundle/tasks/fix-customer-email.json +9 -0
- bundle/tasks/smoke.json +7 -0
- media/hero.gif +3 -0
- media/solve-1.mp4 +3 -0
- media/solve-2.mp4 +3 -0
- media/solve-3.mp4 +3 -0
- media/witness.mp4 +3 -0
- results.json +123 -0
README.md
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: apache-2.0
|
| 3 |
+
pretty_name: DB Browser for SQLite 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 |
+
- database
|
| 14 |
+
- sqlite
|
| 15 |
+
- data-editing
|
| 16 |
+
- from-request
|
| 17 |
+
---
|
| 18 |
+
|
| 19 |
+
# DB Browser for SQLite: a computer-use environment built from a one-line request
|
| 20 |
+
|
| 21 |
+

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