REA computer-use environment, v0.1.0
Browse files- README.md +111 -0
- bundle/README.md +45 -0
- bundle/artifacts/record-grocery-expense-check/verify.py +445 -0
- bundle/envs/homebank/SKILL.md +10 -0
- bundle/envs/homebank/env.toml +4 -0
- bundle/envs/homebank/homebank_app.py +790 -0
- bundle/envs/homebank/seed/Documents/household.xhb +144 -0
- bundle/evals/homebank.toml +1 -0
- bundle/tasks/record-grocery-expense.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/witness.mp4 +3 -0
- results.json +98 -0
README.md
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: apache-2.0
|
| 3 |
+
pretty_name: HomeBank 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 |
+
- personal-finance
|
| 14 |
+
- accounting
|
| 15 |
+
- budget
|
| 16 |
+
- from-request
|
| 17 |
+
---
|
| 18 |
+
|
| 19 |
+
# HomeBank: a computer-use environment built from a one-line request
|
| 20 |
+
|
| 21 |
+

|
| 22 |
+
|
| 23 |
+
**The real HomeBank 5.7 personal finance manager 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 36 minutes, with only REA's build skill and MCP tools; [How it was made](#how-it-was-made) has the request and the steps. HomeBank opens a synthetic household's accounts, `Documents/household.xhb`, at launch: a checking and a savings account, six payees and five October transactions. The agent has to record a $64.18 grocery expense at Fresh Market in the checking account, dated November 4, 2026, with the category Groceries and the memo "Weekly groceries", and save. It sees only the screen and acts only with the mouse and keyboard.
|
| 26 |
+
|
| 27 |
+
## Watch
|
| 28 |
+
|
| 29 |
+
- Agent runs (Claude Code with Claude Sonnet 5.5): [run 1](media/solve-1.mp4), [run 2](media/solve-2.mp4)
|
| 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 HomeBank, record a new grocery expense in the Everyday Checking account of Documents/household.xhb: $64.18 paid to Fresh Market on November 4, 2026, category Groceries, memo "Weekly groceries". Then save the file.
|
| 37 |
+
|
| 38 |
+
`bundle/artifacts/record-grocery-expense-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 |
+
| `amount` | `value_equals` | `Documents/household.xhb` |
|
| 43 |
+
| `account` | `value_equals` | `Documents/household.xhb` |
|
| 44 |
+
| `date` | `value_equals` | `Documents/household.xhb` |
|
| 45 |
+
| `payee` | `value_equals` | `Documents/household.xhb` |
|
| 46 |
+
| `category` | `value_equals` | `Documents/household.xhb` |
|
| 47 |
+
| `rent-untouched` | `value_equals` | `Documents/household.xhb` |
|
| 48 |
+
|
| 49 |
+
An `.xhb` file is XML with one `ope` element per transaction. The checks find the new transaction by its memo (`wording`), never by position, and check each field: the amount is -64.18 (within 0.001, as HomeBank writes -64.180000000000007), the account is Everyday Checking (key 1, not Savings), the date is 739924 (HomeBank's day number for 2026-11-04), the payee is the existing Fresh Market (key 1) and the category is Groceries (key 44). A sixth check keeps the October rent unchanged. Entering the expense twice, or under a new misspelled payee, fails. REA's draft offered only a check that a transaction exists; Claude Code wrote the field checks, and took Groceries' key from REA's one export refusal, which named the value the captured file held.
|
| 50 |
+
|
| 51 |
+
## Results
|
| 52 |
+
|
| 53 |
+
2 of 2 runs passed, about $1.62 per run.
|
| 54 |
+
|
| 55 |
+
| Run | Outcome | Turns | Cost | Video |
|
| 56 |
+
| --- | --- | --- | --- | --- |
|
| 57 |
+
| 1 | passed | 38 | $1.78 | [video](media/solve-1.mp4) |
|
| 58 |
+
| 2 | passed | 43 | $1.47 | [video](media/solve-2.mp4) |
|
| 59 |
+
|
| 60 |
+
## Run it
|
| 61 |
+
|
| 62 |
+
You need Docker. `agentenv-framework` builds the computer: Ubuntu 24.04 with the app installed from Ubuntu's archive (`homebank` 5.7.4).
|
| 63 |
+
|
| 64 |
+
```bash
|
| 65 |
+
pip install agentenv-framework==0.9.1431
|
| 66 |
+
hf download earakely-scale/HomeBankFromRequestComputerEnv-REA --repo-type dataset --local-dir homebank-request
|
| 67 |
+
agent-env run homebank-request/bundle --task record-grocery-expense --agent claude-code --model <model>
|
| 68 |
+
```
|
| 69 |
+
|
| 70 |
+
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.
|
| 71 |
+
|
| 72 |
+
## How it was made
|
| 73 |
+
|
| 74 |
+
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:
|
| 75 |
+
|
| 76 |
+
> Build me a HomeBank environment where the agent records a new grocery expense in a checking account and saves the file.
|
| 77 |
+
|
| 78 |
+
It asked only the skill's upfront questions, wrote no app-specific scripts, and finished in about 36 minutes. The steps were REA's usual ones:
|
| 79 |
+
|
| 80 |
+
1. **Capture.** REA launched HomeBank 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.
|
| 81 |
+
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.
|
| 82 |
+
3. **Task.** The task's checks were validated against the capture: they fail on the starting state and pass on the captured end state.
|
| 83 |
+
4. **Witness.** In a fresh computer, the expense was recorded through computer actions alone, and the checks were read at four stages. They held on the first try:
|
| 84 |
+
|
| 85 |
+
| Stage | Checks |
|
| 86 |
+
| --- | --- |
|
| 87 |
+
| `seed` | fail, as expected: no transaction has the memo "Weekly groceries" |
|
| 88 |
+
| `after_edit` | pass |
|
| 89 |
+
| `near_miss` | fail, as expected: the amount was changed to $64.81 |
|
| 90 |
+
| `after_reset` | fail, as expected: `data/reset` restored the seed |
|
| 91 |
+
|
| 92 |
+
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 twice, each run recorded.
|
| 93 |
+
|
| 94 |
+
## What's inside
|
| 95 |
+
|
| 96 |
+
```
|
| 97 |
+
bundle/ the agentenv bundle: envs/ (app module, seed files), tasks/, artifacts/ (verifier), evals/
|
| 98 |
+
media/ witness and agent-run recordings (MP4) with short GIF previews
|
| 99 |
+
results.json the runs above, with each check's result
|
| 100 |
+
```
|
| 101 |
+
|
| 102 |
+
## Limits
|
| 103 |
+
|
| 104 |
+
- Only two runs: the third was skipped to keep the solve spend under its $4 budget. Two runs show the task is solvable, not how hard it is.
|
| 105 |
+
- Recording the expense takes many steps in HomeBank's transaction dialog: the runs took 38 and 43 turns.
|
| 106 |
+
- The checks find the transaction by its memo, so a transaction recorded with a different memo is not found and every field check fails.
|
| 107 |
+
- The computer installs whatever `homebank` Ubuntu 24.04's archive holds at build time (5.7.4 for these runs); it is not pinned.
|
| 108 |
+
|
| 109 |
+
## Licences
|
| 110 |
+
|
| 111 |
+
The bundle code, the task and the synthetic seed files are Apache-2.0. HomeBank itself is not included: the computer installs it from Ubuntu's archive (`homebank` 5.7.4) at build time, under its own licence (GPL-2.0-or-later).
|
bundle/README.md
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# HomeBank computer app
|
| 2 |
+
|
| 3 |
+
Exported by REA's `export-desktop-application` from a capture of the `homebank` package
|
| 4 |
+
(capture Evidence `ev_e0dde61fc1c0be8aca9878658fdcc47d16f2e4a2ce40157e9b881b37c76bb082`). It was checked against agentenv-framework
|
| 5 |
+
0.9.1431.
|
| 6 |
+
|
| 7 |
+
- `envs/homebank/` is a computer app on the `ubuntu-24.04` base with the `reference` driver, for
|
| 8 |
+
`amd64` and `arm64`. It installs `homebank` from the distribution archive, launches `sh -c cd "$HOME" 2>/dev/null; exec 'homebank' "$HOME"/'Documents/household.xhb'` at boot and is ready
|
| 9 |
+
when a window of class `Homebank` appears.
|
| 10 |
+
- At launch the app opens `~/Documents/household.xhb`, the seed's one document.
|
| 11 |
+
- Owned paths: `~/.config/homebank`, `~/Documents`.
|
| 12 |
+
`data/get` returns their files and a typed JSON view of each; `data/reset` restores the seed.
|
| 13 |
+
- Seed: 1 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 |
+
- `tasks/smoke.json` deploys the app.
|
| 17 |
+
|
| 18 |
+
Run the task with `agent-env run <this folder>`, or only the deploy with `--task smoke`.
|
| 19 |
+
|
| 20 |
+
The seed was made for this task, not taken from a user's own data; read `envs/homebank/seed/` before publishing the bundle.
|
| 21 |
+
|
| 22 |
+
## Task `record-grocery-expense`
|
| 23 |
+
|
| 24 |
+
`tasks/record-grocery-expense.json` deploys the app, has the agent work through the computer from the prompt below, and grades
|
| 25 |
+
the outcome with `artifacts/record-grocery-expense-check/verify.py`, which reads the app's `data/get` views and needs
|
| 26 |
+
no model. `evals/homebank.toml` names it, so a run of the bundle runs it.
|
| 27 |
+
|
| 28 |
+
> In HomeBank, record a new grocery expense in the Everyday Checking account of Documents/household.xhb: $64.18 paid to Fresh Market on November 4, 2026, category Groceries, memo "Weekly groceries". Then save the file.
|
| 29 |
+
|
| 30 |
+
Checks, each of which must pass:
|
| 31 |
+
|
| 32 |
+
- `amount`: `{"kind":"value_equals","file":"Documents/household.xhb","pointer":"/root/children/[name=ope][@wording=Weekly groceries]/attributes/amount","value":-64.18,"tolerance":0.001}`
|
| 33 |
+
- `account`: `{"kind":"value_equals","file":"Documents/household.xhb","pointer":"/root/children/[name=ope][@wording=Weekly groceries]/attributes/account","value":"1"}`
|
| 34 |
+
- `date`: `{"kind":"value_equals","file":"Documents/household.xhb","pointer":"/root/children/[name=ope][@wording=Weekly groceries]/attributes/date","value":"739924"}`
|
| 35 |
+
- `payee`: `{"kind":"value_equals","file":"Documents/household.xhb","pointer":"/root/children/[name=ope][@wording=Weekly groceries]/attributes/payee","value":"1"}`
|
| 36 |
+
- `category`: `{"kind":"value_equals","file":"Documents/household.xhb","pointer":"/root/children/[name=ope][@wording=Weekly groceries]/attributes/category","value":"44"}`
|
| 37 |
+
- `rent-untouched`: `{"kind":"value_equals","file":"Documents/household.xhb","pointer":"/root/children/[name=ope][@wording=October rent]/attributes/amount","value":-1450,"tolerance":0.001}`
|
| 38 |
+
|
| 39 |
+
REA kept the task because its checks fail on the seed (`amount`, `account`, `date`, `payee`, `category`) and all
|
| 40 |
+
pass on the captured end state.
|
| 41 |
+
|
| 42 |
+
To measure a solve rate, run the task k times (3 by default) with the agent and model to measure, and count the runs
|
| 43 |
+
whose summary line says `passed`; a run that says `failed` did not finish and is run again rather than counted:
|
| 44 |
+
|
| 45 |
+
agent-env run <this folder> --task record-grocery-expense --agent claude-code --model MODEL
|
bundle/artifacts/record-grocery-expense-check/verify.py
ADDED
|
@@ -0,0 +1,445 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Checks of the task record-grocery-expense against the homebank 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. A failure to reach the app raises, so the run fails rather than scoring the agent.
|
| 5 |
+
"""
|
| 6 |
+
import json
|
| 7 |
+
import math
|
| 8 |
+
import re
|
| 9 |
+
|
| 10 |
+
from agentenv_protocol import client as protocol
|
| 11 |
+
from agentenv_protocol.types import RPC_PATH
|
| 12 |
+
|
| 13 |
+
APP = "homebank"
|
| 14 |
+
CHECKS = [
|
| 15 |
+
{"id": "amount", "kind": "value_equals", "file": "Documents/household.xhb", "pointer": "/root/children/[name=ope][@wording=Weekly groceries]/attributes/amount", "value": -64.18, "tolerance": 0.001},
|
| 16 |
+
{"id": "account", "kind": "value_equals", "file": "Documents/household.xhb", "pointer": "/root/children/[name=ope][@wording=Weekly groceries]/attributes/account", "value": "1"},
|
| 17 |
+
{"id": "date", "kind": "value_equals", "file": "Documents/household.xhb", "pointer": "/root/children/[name=ope][@wording=Weekly groceries]/attributes/date", "value": "739924"},
|
| 18 |
+
{"id": "payee", "kind": "value_equals", "file": "Documents/household.xhb", "pointer": "/root/children/[name=ope][@wording=Weekly groceries]/attributes/payee", "value": "1"},
|
| 19 |
+
{"id": "category", "kind": "value_equals", "file": "Documents/household.xhb", "pointer": "/root/children/[name=ope][@wording=Weekly groceries]/attributes/category", "value": "44"},
|
| 20 |
+
{"id": "rent-untouched", "kind": "value_equals", "file": "Documents/household.xhb", "pointer": "/root/children/[name=ope][@wording=October rent]/attributes/amount", "value": -1450, "tolerance": 0.001},
|
| 21 |
+
]
|
| 22 |
+
|
| 23 |
+
MISSING = object()
|
| 24 |
+
INDEX = re.compile(r"0|[1-9][0-9]*")
|
| 25 |
+
VIEW_FORMATS = ("text", "json", "keyfile", "xml")
|
| 26 |
+
NUMERAL = re.compile(r"[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?")
|
| 27 |
+
WHITESPACE_RUN = re.compile(r"[ \t\r\n]+")
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _shown(value) -> str:
|
| 31 |
+
text = json.dumps(value, ensure_ascii=False, separators=(",", ":"))
|
| 32 |
+
return text if len(text) <= 200 else text[:200] + "…"
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _same(actual, expected) -> bool:
|
| 36 |
+
"""JSON equality: numbers by value but never a boolean for a number, objects by their keys, arrays in order."""
|
| 37 |
+
if isinstance(expected, list):
|
| 38 |
+
return (isinstance(actual, list) and len(actual) == len(expected)
|
| 39 |
+
and all(_same(item, wanted) for item, wanted in zip(actual, expected)))
|
| 40 |
+
if isinstance(expected, dict):
|
| 41 |
+
return (isinstance(actual, dict) and len(actual) == len(expected)
|
| 42 |
+
and all(key in actual and _same(actual[key], value) for key, value in expected.items()))
|
| 43 |
+
if isinstance(expected, bool) or isinstance(actual, bool):
|
| 44 |
+
return isinstance(expected, bool) and isinstance(actual, bool) and actual == expected
|
| 45 |
+
if isinstance(expected, (int, float)):
|
| 46 |
+
return isinstance(actual, (int, float)) and actual == expected
|
| 47 |
+
return type(actual) is type(expected) and actual == expected
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _bracketed(token: str) -> bool:
|
| 51 |
+
return len(token) >= 2 and token.startswith("[") and token.endswith("]")
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def _selector(token: str):
|
| 55 |
+
"""A selector's conditions, [KEY=VALUE] or [@KEY=VALUE] one or more times, or None when the token is not one."""
|
| 56 |
+
if not _bracketed(token):
|
| 57 |
+
return None
|
| 58 |
+
conditions = []
|
| 59 |
+
for part in token[1:-1].split("]["):
|
| 60 |
+
key, equals, value = part.partition("=")
|
| 61 |
+
name = key[1:] if key.startswith("@") else key
|
| 62 |
+
if not equals or not name:
|
| 63 |
+
return None
|
| 64 |
+
conditions.append((key.startswith("@"), name, value))
|
| 65 |
+
return conditions
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def _selects(member, conditions) -> bool:
|
| 69 |
+
"""Whether an array member meets every condition; selectors compare strings only."""
|
| 70 |
+
if not isinstance(member, dict):
|
| 71 |
+
return False
|
| 72 |
+
for attribute, key, value in conditions:
|
| 73 |
+
fields = member.get("attributes") if attribute else member
|
| 74 |
+
if not isinstance(fields, dict) or not isinstance(fields.get(key), str) or fields[key] != value:
|
| 75 |
+
return False
|
| 76 |
+
return True
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _step(items: list, token: str, last: bool):
|
| 80 |
+
"""One step into an array, by index or by a selector that must match one member, or none when it is the last."""
|
| 81 |
+
if INDEX.fullmatch(token):
|
| 82 |
+
return ("member", items[int(token)]) if int(token) < len(items) else ("none", None)
|
| 83 |
+
conditions = _selector(token)
|
| 84 |
+
if conditions is None:
|
| 85 |
+
return ("unresolved", f"{token} is not a selector of the form [KEY=VALUE]") if _bracketed(token) else (
|
| 86 |
+
"none", None)
|
| 87 |
+
matched = [item for item in items if _selects(item, conditions)]
|
| 88 |
+
if len(matched) == 1:
|
| 89 |
+
return "member", matched[0]
|
| 90 |
+
if len(matched) > 1:
|
| 91 |
+
return "unresolved", f"{token} matches {len(matched)} members, not one"
|
| 92 |
+
return ("none" if last else "unresolved"), f"{token} matches no member"
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def _locate(view, pointer: str):
|
| 96 |
+
"""Where a pointer leads: ("value", value), ("none", why or None) or ("unresolved", problem), with the pointers
|
| 97 |
+
to the arrays a selector searched on the way."""
|
| 98 |
+
current, searched = view, []
|
| 99 |
+
segments = pointer[1:].split("/")
|
| 100 |
+
for position, segment in enumerate(segments):
|
| 101 |
+
token = segment.replace("~1", "/").replace("~0", "~")
|
| 102 |
+
if isinstance(current, list):
|
| 103 |
+
if not INDEX.fullmatch(token) and _selector(token) is not None:
|
| 104 |
+
searched.append("".join("/" + part for part in segments[:position]))
|
| 105 |
+
kind, found = _step(current, token, position == len(segments) - 1)
|
| 106 |
+
if kind != "member":
|
| 107 |
+
return kind, found, searched
|
| 108 |
+
current = found
|
| 109 |
+
elif isinstance(current, dict) and token in current:
|
| 110 |
+
current = current[token]
|
| 111 |
+
else:
|
| 112 |
+
return "none", None, searched
|
| 113 |
+
return "value", current, searched
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def _number(value):
|
| 117 |
+
"""A number, or a numeral string read as one; None for anything else, a boolean, or a numeral past the doubles."""
|
| 118 |
+
if isinstance(value, bool):
|
| 119 |
+
return None
|
| 120 |
+
if isinstance(value, (int, float)):
|
| 121 |
+
return value
|
| 122 |
+
if not isinstance(value, str) or not NUMERAL.fullmatch(value):
|
| 123 |
+
return None
|
| 124 |
+
number = float(value)
|
| 125 |
+
return number if math.isfinite(number) else None
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def _entry_leaves_out(entry) -> bool:
|
| 129 |
+
return isinstance(entry, dict) and (isinstance(entry.get("view_error"), str) or (
|
| 130 |
+
entry.get("format") in ("text", "xml") and isinstance(entry.get("view"), dict)
|
| 131 |
+
and entry["view"].get("truncated") is True))
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def _viewless_entry(view, pointer: str):
|
| 135 |
+
"""The name of the entry whose view a pointer goes into when it has none, so its null is no JSON value, and
|
| 136 |
+
why: binary, unread, or of a format without a view; None when it has one."""
|
| 137 |
+
parts = pointer[1:].split("/")
|
| 138 |
+
if len(parts) < 3 or parts[0] != "entries" or parts[2] != "view":
|
| 139 |
+
return None
|
| 140 |
+
kind, item, _ = _locate(view, "/entries/" + parts[1])
|
| 141 |
+
if kind != "value" or not isinstance(item, dict):
|
| 142 |
+
return None
|
| 143 |
+
if isinstance(item.get("view_error"), str):
|
| 144 |
+
reason = f"has no view: {item['view_error']}"
|
| 145 |
+
elif item.get("format") == "binary":
|
| 146 |
+
reason = "is binary and has no view"
|
| 147 |
+
elif item.get("format") not in VIEW_FORMATS:
|
| 148 |
+
reason = "has no view"
|
| 149 |
+
else:
|
| 150 |
+
return None
|
| 151 |
+
return (item["name"] if isinstance(item.get("name"), str) else ""), reason
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def _array_leaves_out(form, view, array: str) -> bool:
|
| 155 |
+
"""Whether an array a selector searched may lack members: in a zip the listing or its entry's view, else the
|
| 156 |
+
view's own truncation."""
|
| 157 |
+
if form != "zip":
|
| 158 |
+
return _truncated(form, view)
|
| 159 |
+
if array == "/entries":
|
| 160 |
+
return isinstance(view, dict) and view.get("truncated") is True
|
| 161 |
+
return _zip_leaves_out(view, array)
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def _zip_leaves_out(view, pointer: str) -> bool:
|
| 165 |
+
"""Whether a zip view leaves out what a pointer reaches: for a pointer into one listed entry, only that entry."""
|
| 166 |
+
if not isinstance(view, dict):
|
| 167 |
+
return False
|
| 168 |
+
parts = pointer[1:].split("/")
|
| 169 |
+
if parts[0] == "entries" and len(parts) > 1:
|
| 170 |
+
kind, entry, _ = _locate(view, "/entries/" + parts[1])
|
| 171 |
+
return _entry_leaves_out(entry) if kind == "value" else view.get("truncated") is True
|
| 172 |
+
entries = view.get("entries") if isinstance(view.get("entries"), list) else []
|
| 173 |
+
return view.get("truncated") is True or any(_entry_leaves_out(entry) for entry in entries)
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def _truncated(form, view) -> bool:
|
| 177 |
+
if not isinstance(view, dict):
|
| 178 |
+
return False
|
| 179 |
+
if form in ("text", "xml"):
|
| 180 |
+
return view.get("truncated") is True
|
| 181 |
+
if form != "sqlite":
|
| 182 |
+
return False
|
| 183 |
+
tables = view.get("tables")
|
| 184 |
+
return view.get("tables_truncated") is True or any(
|
| 185 |
+
isinstance(table, dict) and (table.get("truncated") is True or isinstance(table.get("error"), str))
|
| 186 |
+
for table in (tables.values() if isinstance(tables, dict) else []))
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def _view_of(check, entry, form):
|
| 190 |
+
"""The view, whether it is truncated, and why the check cannot read it; an absent file reads as empty."""
|
| 191 |
+
if entry is None:
|
| 192 |
+
return None, False, None
|
| 193 |
+
if isinstance(entry.get("error"), str):
|
| 194 |
+
return None, False, f"{check['file']} has no view: {entry['error']}"
|
| 195 |
+
if entry.get("format") in (None, "binary"):
|
| 196 |
+
return None, False, f"{check['file']} is binary and has no view"
|
| 197 |
+
if form is not None and entry.get("format") != form:
|
| 198 |
+
return None, False, f"{check['file']} is read as {entry.get('format')}, not {form}"
|
| 199 |
+
return entry.get("view"), _truncated(entry.get("format"), entry.get("view")), None
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def _undecided(check):
|
| 203 |
+
return False, f"the view of {check['file']} is truncated, so what it leaves out is unknown"
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def _compared(check, n: int, what: str):
|
| 207 |
+
operator = next(key for key in ("equals", "at_least", "at_most") if check.get(key) is not None)
|
| 208 |
+
expected = check[operator]
|
| 209 |
+
met = n == expected if operator == "equals" else n >= expected if operator == "at_least" else n <= expected
|
| 210 |
+
return met, f"{n} {what}, expected {operator.replace('_', ' ')} {expected}"
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def _lines(check, entry):
|
| 214 |
+
view, truncated, problem = _view_of(check, entry, "text")
|
| 215 |
+
if problem is not None:
|
| 216 |
+
return False, problem
|
| 217 |
+
lines = view.get("lines") if isinstance(view, dict) and isinstance(view.get("lines"), list) else []
|
| 218 |
+
lines = [line for line in lines if isinstance(line, str)]
|
| 219 |
+
file = check["file"]
|
| 220 |
+
if check["kind"] == "lines_present":
|
| 221 |
+
missing = next((line for line in check["lines"] if line not in lines), None)
|
| 222 |
+
return (True, f"{file} has the line(s) {_shown(check['lines'])}") if missing is None else (
|
| 223 |
+
False, f"{file} has no line {_shown(missing)}")
|
| 224 |
+
if truncated:
|
| 225 |
+
return _undecided(check)
|
| 226 |
+
if check["kind"] == "lines_absent":
|
| 227 |
+
found = next((line for line in check["lines"] if line in lines), None)
|
| 228 |
+
return (True, f"{file} has none of the lines {_shown(check['lines'])}") if found is None else (
|
| 229 |
+
False, f"{file} still has the line {_shown(found)}")
|
| 230 |
+
if check.get("contains") is not None:
|
| 231 |
+
n = sum(1 for line in lines if check["contains"] in line)
|
| 232 |
+
return _compared(check, n, f"line(s) of {file} contain {_shown(check['contains'])}")
|
| 233 |
+
n = sum(1 for line in lines if line == check["exact"])
|
| 234 |
+
return _compared(check, n, f"line(s) of {file} match {_shown(check['exact'])}")
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def _near(at: str, found, expected, tolerance):
|
| 238 |
+
"""A value compared within a tolerance: numbers, and numeral strings, by their difference."""
|
| 239 |
+
number = _number(found)
|
| 240 |
+
within = f"within {_shown(tolerance)} of {_shown(expected)}"
|
| 241 |
+
if number is None:
|
| 242 |
+
return False, f"{at} is {_shown(found)}, not a number"
|
| 243 |
+
if abs(number - expected) <= tolerance:
|
| 244 |
+
return True, f"{at} is {_shown(found)}, {within}"
|
| 245 |
+
return False, f"{at} is {_shown(found)}, not {within}"
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def _value(check, entry):
|
| 249 |
+
view, truncated, problem = _view_of(check, entry, None)
|
| 250 |
+
if problem is not None:
|
| 251 |
+
return False, problem
|
| 252 |
+
kind, found, searched = ("none", None, []) if entry is None else _locate(view, check["pointer"])
|
| 253 |
+
at = f"{check['file']} at {check['pointer']}"
|
| 254 |
+
viewless = _viewless_entry(view, check["pointer"]) if entry is not None and entry.get("format") == "zip" else None
|
| 255 |
+
if viewless is not None:
|
| 256 |
+
return False, f"{check['file']} entry {viewless[0]} {viewless[1]}"
|
| 257 |
+
# A selector tells one member from several only in an array the view holds whole.
|
| 258 |
+
if any(_array_leaves_out(entry.get("format"), view, array) for array in searched):
|
| 259 |
+
return _undecided(check)
|
| 260 |
+
if kind == "unresolved":
|
| 261 |
+
return False, f"{at}: {found}"
|
| 262 |
+
if entry is not None and entry.get("format") == "zip":
|
| 263 |
+
truncated = _zip_leaves_out(view, check["pointer"])
|
| 264 |
+
if check["kind"] == "value_equals" and isinstance(check["value"], (dict, list)) and truncated:
|
| 265 |
+
return _undecided(check)
|
| 266 |
+
if check["kind"] == "value_equals":
|
| 267 |
+
if kind == "none":
|
| 268 |
+
return False, f"{at} has no value" if found is None else f"{at}: {found}"
|
| 269 |
+
expected = check["value"]
|
| 270 |
+
if check.get("tolerance") is not None and isinstance(expected, (int, float)) and not isinstance(expected, bool):
|
| 271 |
+
return _near(at, found, expected, check["tolerance"])
|
| 272 |
+
if _same(found, check["value"]):
|
| 273 |
+
return True, f"{at} is {_shown(check['value'])}"
|
| 274 |
+
return False, f"{at} is {_shown(found)}, not {_shown(check['value'])}"
|
| 275 |
+
if truncated:
|
| 276 |
+
return _undecided(check)
|
| 277 |
+
return (True, f"{at} has no value") if kind == "none" else (False, f"{at} is {_shown(found)}")
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
def _is_element(value) -> bool:
|
| 281 |
+
return (isinstance(value, dict) and isinstance(value.get("name"), str) and isinstance(value.get("attributes"), dict)
|
| 282 |
+
and isinstance(value.get("children"), list))
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
def _element_text(element) -> str:
|
| 286 |
+
"""An element's text as XPath's string() reads it from what the view keeps: every text node among its children
|
| 287 |
+
and its descendants', in document order."""
|
| 288 |
+
parts, pending = [], [element]
|
| 289 |
+
while pending:
|
| 290 |
+
node = pending.pop()
|
| 291 |
+
if isinstance(node, str):
|
| 292 |
+
parts.append(node)
|
| 293 |
+
elif _is_element(node):
|
| 294 |
+
pending.extend(reversed(node["children"]))
|
| 295 |
+
return "".join(parts)
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
def _collapse_whitespace(text: str) -> str:
|
| 299 |
+
"""Each run of XML whitespace (space, tab, CR, LF) made one space, none at either end, as normalize-space()."""
|
| 300 |
+
return WHITESPACE_RUN.sub(" ", text).strip(" ")
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
def _text_at(view, pointer: str) -> bool:
|
| 304 |
+
"""Whether a string a pointer reaches is text of the document: a member of an element's children (a text node)
|
| 305 |
+
or attributes (an attribute's value), rather than an element's name or a field of the DOCTYPE."""
|
| 306 |
+
segments = pointer.split("/")
|
| 307 |
+
if len(segments) < 3 or segments[-2] not in ("children", "attributes"):
|
| 308 |
+
return False
|
| 309 |
+
kind, owner, _ = _locate(view, "/".join(segments[:-2]))
|
| 310 |
+
return kind == "value" and _is_element(owner)
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
def _not_xml_entry(check, view):
|
| 314 |
+
"""Why a text check's pointer into an archive goes into no XML entry's view, or None when it does or names an
|
| 315 |
+
entry not listed."""
|
| 316 |
+
parts = check["pointer"].split("/")
|
| 317 |
+
if len(parts) < 4 or parts[3] != "view":
|
| 318 |
+
return f"{check['file']} at {check['pointer']} does not point into an entry's view"
|
| 319 |
+
if parts[1] != "entries":
|
| 320 |
+
return None
|
| 321 |
+
kind, item, _ = _locate(view, "/entries/" + parts[2])
|
| 322 |
+
if kind != "value" or not isinstance(item, dict) or item.get("format") == "xml":
|
| 323 |
+
return None
|
| 324 |
+
# An entry without a view failed before this, so its format is one with a view.
|
| 325 |
+
name, form = (value if isinstance(value, str) else "" for value in (item.get("name"), item.get("format")))
|
| 326 |
+
return f"{check['file']} entry {name} is read as {form}, not xml"
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
def _whole_text(check, entry):
|
| 330 |
+
"""An element's whole text, or a text node's, compared with the value or searched for it."""
|
| 331 |
+
view, truncated, problem = _view_of(check, entry, None)
|
| 332 |
+
if problem is not None:
|
| 333 |
+
return False, problem
|
| 334 |
+
at = f"{check['file']} at {check['pointer']}"
|
| 335 |
+
if entry is None:
|
| 336 |
+
return False, f"{at} has no value"
|
| 337 |
+
form = entry.get("format")
|
| 338 |
+
if form not in ("xml", "zip"):
|
| 339 |
+
return False, f"{check['file']} is read as {form}, not xml"
|
| 340 |
+
kind, found, searched = _locate(view, check["pointer"])
|
| 341 |
+
viewless = _viewless_entry(view, check["pointer"]) if form == "zip" else None
|
| 342 |
+
if viewless is not None:
|
| 343 |
+
return False, f"{check['file']} entry {viewless[0]} {viewless[1]}"
|
| 344 |
+
if any(_array_leaves_out(form, view, array) for array in searched):
|
| 345 |
+
return _undecided(check)
|
| 346 |
+
problem = _not_xml_entry(check, view) if form == "zip" else None
|
| 347 |
+
if problem is not None:
|
| 348 |
+
return False, problem
|
| 349 |
+
if kind == "unresolved":
|
| 350 |
+
return False, f"{at}: {found}"
|
| 351 |
+
if kind == "none":
|
| 352 |
+
return False, f"{at} has no value" if found is None else f"{at}: {found}"
|
| 353 |
+
if not (_text_at(view, check["pointer"]) if isinstance(found, str) else _is_element(found)):
|
| 354 |
+
return False, f"{at} is {_shown(found)}, not an element, a text node or an attribute value"
|
| 355 |
+
# A text node is whole; an element's text is whole only if its view left nothing out.
|
| 356 |
+
if form == "zip":
|
| 357 |
+
truncated = _zip_leaves_out(view, check["pointer"])
|
| 358 |
+
if not isinstance(found, str) and truncated:
|
| 359 |
+
return _undecided(check)
|
| 360 |
+
return _compared_text(check, at, _element_text(found))
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
def _compared_text(check, at: str, found: str):
|
| 364 |
+
"""A text found at a pointer compared with the check's value or searched for it, both collapsed when it asks."""
|
| 365 |
+
collapse = check.get("normalize_whitespace") is True
|
| 366 |
+
text = _collapse_whitespace(found) if collapse else found
|
| 367 |
+
value = _collapse_whitespace(check["value"]) if collapse else check["value"]
|
| 368 |
+
how = " with whitespace collapsed" if collapse else ""
|
| 369 |
+
if check["kind"] == "text_equals":
|
| 370 |
+
if text == value:
|
| 371 |
+
return True, f"{at} has the text {_shown(value)}{how}"
|
| 372 |
+
return False, f"{at} has the text {_shown(text)}{how}, not {_shown(value)}"
|
| 373 |
+
if value in text:
|
| 374 |
+
return True, f"{at} has text containing {_shown(value)}{how}"
|
| 375 |
+
return False, f"{at} has the text {_shown(text)}{how}, without {_shown(value)}"
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
def _rows(check, entry):
|
| 379 |
+
view, _, problem = _view_of(check, entry, "sqlite")
|
| 380 |
+
if problem is not None:
|
| 381 |
+
return False, problem
|
| 382 |
+
view = view if isinstance(view, dict) else {}
|
| 383 |
+
tables = view.get("tables") if isinstance(view.get("tables"), dict) else {}
|
| 384 |
+
table = tables[check["table"]] if check["table"] in tables else MISSING
|
| 385 |
+
name = f"{check['file']} table {check['table']}"
|
| 386 |
+
if table is MISSING and view.get("tables_truncated") is True:
|
| 387 |
+
return _undecided(check)
|
| 388 |
+
table = table if isinstance(table, dict) else {}
|
| 389 |
+
if isinstance(table.get("error"), str):
|
| 390 |
+
return False, f"{name} could not be read: {table['error']}"
|
| 391 |
+
columns = table.get("columns") if isinstance(table.get("columns"), list) else []
|
| 392 |
+
rows = table.get("rows") if isinstance(table.get("rows"), list) else []
|
| 393 |
+
where = check.get("where") or {}
|
| 394 |
+
|
| 395 |
+
def matches(row) -> bool:
|
| 396 |
+
return isinstance(row, list) and all(
|
| 397 |
+
column in columns and columns.index(column) < len(row) and _same(row[columns.index(column)], value)
|
| 398 |
+
for column, value in where.items())
|
| 399 |
+
|
| 400 |
+
n = sum(1 for row in rows if matches(row))
|
| 401 |
+
if check["kind"] == "row_present":
|
| 402 |
+
return (n > 0, f"{name} has a row with {_shown(where)}" if n > 0 else f"{name} has no row with {_shown(where)}")
|
| 403 |
+
if table.get("truncated") is True:
|
| 404 |
+
return _undecided(check)
|
| 405 |
+
if check["kind"] == "row_absent":
|
| 406 |
+
return (True, f"{name} has no row with {_shown(where)}") if n == 0 else (
|
| 407 |
+
False, f"{name} has {n} row(s) with {_shown(where)}")
|
| 408 |
+
return _compared(check, n, f"row(s) of {name}" + (f" with {_shown(where)}" if "where" in check else ""))
|
| 409 |
+
|
| 410 |
+
|
| 411 |
+
def _verdict(check, entry):
|
| 412 |
+
kind = check["kind"]
|
| 413 |
+
if kind == "file_present":
|
| 414 |
+
return (entry is not None, f"{check['file']} exists" if entry is not None else f"{check['file']} does not exist")
|
| 415 |
+
if kind == "file_absent":
|
| 416 |
+
return (entry is None, f"{check['file']} does not exist" if entry is None else f"{check['file']} exists")
|
| 417 |
+
if kind in ("lines_present", "lines_absent", "line_count"):
|
| 418 |
+
return _lines(check, entry)
|
| 419 |
+
if kind in ("value_equals", "value_absent"):
|
| 420 |
+
return _value(check, entry)
|
| 421 |
+
if kind in ("text_equals", "text_contains"):
|
| 422 |
+
return _whole_text(check, entry)
|
| 423 |
+
return _rows(check, entry)
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
def evaluate(checks: list, views: dict) -> list:
|
| 427 |
+
"""One result per check against the views data/get returned, by home path."""
|
| 428 |
+
results = []
|
| 429 |
+
for check in checks:
|
| 430 |
+
passed, description = _verdict(check, views.get(check["file"]))
|
| 431 |
+
results.append({"id": check["id"], "result": passed, "description": description})
|
| 432 |
+
return results
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
async def verify(mcp_url, env_url):
|
| 436 |
+
card = await protocol.get_card(env_url)
|
| 437 |
+
child = protocol.find_child(card, APP)
|
| 438 |
+
if child is None:
|
| 439 |
+
raise RuntimeError(f"the computer at {env_url} lists no app named {APP}")
|
| 440 |
+
answer = await protocol.get_data(env_url + (child.get("url") or RPC_PATH).removesuffix(RPC_PATH), timeout=120)
|
| 441 |
+
states = [part.data["state"] for part in answer.parts
|
| 442 |
+
if part.kind == "data" and isinstance(part.data.get("state"), dict)]
|
| 443 |
+
if not states:
|
| 444 |
+
raise RuntimeError(f"the {APP} app's data/get returned no state views")
|
| 445 |
+
return evaluate(CHECKS, states[0])
|
bundle/envs/homebank/SKILL.md
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
description: Use HomeBank on this Linux desktop; its window has class Homebank.
|
| 3 |
+
---
|
| 4 |
+
|
| 5 |
+
# HomeBank
|
| 6 |
+
|
| 7 |
+
HomeBank is open on the desktop at boot. Its window's class is `Homebank`.
|
| 8 |
+
|
| 9 |
+
Its files live under `~/.config/homebank`, `~/Documents`. Work through the application's own
|
| 10 |
+
window and dialogs; the result is read from those files.
|
bundle/envs/homebank/env.toml
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
type = "computer_app"
|
| 2 |
+
module = "homebank_app.py:Homebank"
|
| 3 |
+
computer = "ubuntu-24.04"
|
| 4 |
+
driver = "reference"
|
bundle/envs/homebank/homebank_app.py
ADDED
|
@@ -0,0 +1,790 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""HomeBank as an agentenv computer app, exported by REA from a desktop application capture.
|
| 2 |
+
|
| 3 |
+
Package: homebank (captured at 5.7.4-1build4). Capture Evidence: ev_e0dde61fc1c0be8aca9878658fdcc47d16f2e4a2ce40157e9b881b37c76bb082.
|
| 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/homebank", "Documents"]
|
| 35 |
+
DCONF = ""
|
| 36 |
+
TEXT_SEEDS = frozenset(["Documents/household.xhb"])
|
| 37 |
+
WINDOW_CLASS = "Homebank"
|
| 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 |
+
MAX_JSON_VIEW_DEPTH = 500
|
| 56 |
+
JSON_TOO_DEEP = f"nested deeper than the {MAX_JSON_VIEW_DEPTH} levels a JSON view keeps"
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def _respelled(text: str, home: Path) -> str:
|
| 60 |
+
"""The seed's home path respelled to this computer's home, only where a whole path segment ends after it."""
|
| 61 |
+
return re.sub(re.escape(SEED_HOME) + r"(?![\w.@+~-])", lambda _: str(home), text)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _respelled_utf16(data: bytes, home: Path) -> bytes:
|
| 65 |
+
"""A UTF-16 text file with a byte-order mark respelled like a text seed, its mark kept; any other bytes as given."""
|
| 66 |
+
for mark, codec in ((b"\xff\xfe", "utf-16-le"), (b"\xfe\xff", "utf-16-be")):
|
| 67 |
+
if data.startswith(mark):
|
| 68 |
+
try:
|
| 69 |
+
text = data[len(mark):].decode(codec)
|
| 70 |
+
except UnicodeDecodeError:
|
| 71 |
+
return data
|
| 72 |
+
return mark + _respelled(text, home).encode(codec) if SEED_HOME in text else data
|
| 73 |
+
return data
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
#: What marks a window as not yet the app's own: skipping the taskbar, as splash screens and dialogs do, or a splash type.
|
| 77 |
+
SPLASH_MARKS = ("_NET_WM_STATE_SKIP_TASKBAR", "_NET_WM_WINDOW_TYPE_SPLASH")
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def _taskbar_window(window_class: str) -> bool:
|
| 81 |
+
"""Whether a top-level window of the given class that the taskbar lists is shown; a splash screen or a dialog
|
| 82 |
+
skips the taskbar."""
|
| 83 |
+
def xprop(*args: str) -> str:
|
| 84 |
+
done = subprocess.run(["xprop", *args], capture_output=True, text=True)
|
| 85 |
+
return done.stdout if done.returncode == 0 else ""
|
| 86 |
+
|
| 87 |
+
for window in re.findall(r"0x[0-9a-f]+", xprop("-root", "_NET_CLIENT_LIST").partition("#")[2]):
|
| 88 |
+
props = xprop("-id", window, "WM_CLASS", "_NET_WM_STATE", "_NET_WM_WINDOW_TYPE")
|
| 89 |
+
classes = re.findall(r'"((?:[^"\\]|\\.)*)"', props.partition("WM_CLASS")[2].split("\n", 1)[0])
|
| 90 |
+
if window_class in classes and not any(mark in props for mark in SPLASH_MARKS):
|
| 91 |
+
return True
|
| 92 |
+
return False
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def _seed_home(home: Path) -> None:
|
| 96 |
+
"""Copy the captured files into this computer's home; text files, UTF-16 ones too, have the seed's home path
|
| 97 |
+
respelled."""
|
| 98 |
+
seed = HERE / "seed"
|
| 99 |
+
for source in sorted(seed.rglob("*")) if seed.is_dir() else []:
|
| 100 |
+
if not source.is_file():
|
| 101 |
+
continue
|
| 102 |
+
relative = source.relative_to(seed).as_posix()
|
| 103 |
+
target = home / relative
|
| 104 |
+
target.parent.mkdir(parents=True, exist_ok=True)
|
| 105 |
+
data = source.read_bytes()
|
| 106 |
+
if relative in TEXT_SEEDS:
|
| 107 |
+
data = _respelled(data.decode("utf-8"), home).encode("utf-8")
|
| 108 |
+
else:
|
| 109 |
+
data = _respelled_utf16(data, home)
|
| 110 |
+
target.write_bytes(data)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def _dconf(arguments: list, environment: dict) -> str:
|
| 114 |
+
return subprocess.run(["dconf", *arguments], env={**os.environ, **environment}, capture_output=True, text=True,
|
| 115 |
+
check=True).stdout
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def _load_dconf(home: Path) -> None:
|
| 119 |
+
"""Compile the captured dconf keys into the user database without D-Bus, which is not up yet. Keys already there
|
| 120 |
+
stay unless captured: dconf compile reads the key files in name order and a later file wins. A failure is
|
| 121 |
+
reported and the app starts without them."""
|
| 122 |
+
if not DCONF:
|
| 123 |
+
return
|
| 124 |
+
database = home / ".config" / "dconf" / "user"
|
| 125 |
+
try:
|
| 126 |
+
database.parent.mkdir(parents=True, exist_ok=True)
|
| 127 |
+
with tempfile.TemporaryDirectory(dir=database.parent) as scratch:
|
| 128 |
+
keyfiles = Path(scratch, "keyfiles")
|
| 129 |
+
keyfiles.mkdir()
|
| 130 |
+
if database.is_file():
|
| 131 |
+
profile = Path(scratch, "profile")
|
| 132 |
+
profile.write_text(f"file-db:{database}\n")
|
| 133 |
+
existing = _dconf(["dump", "/"], {"DCONF_PROFILE": str(profile)})
|
| 134 |
+
(keyfiles / "00-existing").write_text(existing)
|
| 135 |
+
(keyfiles / "01-captured").write_text(_respelled(DCONF, home))
|
| 136 |
+
_dconf(["compile", str(Path(scratch, "user")), str(keyfiles)], {})
|
| 137 |
+
os.replace(Path(scratch, "user"), database)
|
| 138 |
+
except (OSError, subprocess.CalledProcessError) as error:
|
| 139 |
+
detail = (getattr(error, "stderr", None) or "").strip().splitlines()
|
| 140 |
+
print(f"warning: the captured dconf settings were not loaded: {detail[-1] if detail else error}",
|
| 141 |
+
file=sys.stderr)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def _sqlite_text(data: bytes):
|
| 145 |
+
text = data.decode("utf-8", "replace")
|
| 146 |
+
return {"text": text, "bytes_hex": data.hex()} if "�" in text else text
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def _cell(value):
|
| 150 |
+
if isinstance(value, bytes):
|
| 151 |
+
return {"blob_hex": value.hex()}
|
| 152 |
+
if isinstance(value, int) and abs(value) > MAX_SAFE_INTEGER:
|
| 153 |
+
return {"integer": str(value)}
|
| 154 |
+
# JSON has no infinities or negative zero; REA's SQLite reader spells them as strings.
|
| 155 |
+
if isinstance(value, float) and (math.isinf(value) or (value == 0 and math.copysign(1, value) < 0)):
|
| 156 |
+
return "Infinity" if value == math.inf else "-Infinity" if value == -math.inf else "-0"
|
| 157 |
+
return value
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def _table(db, name: str, primary_key: list) -> dict:
|
| 161 |
+
quoted = '"' + name.replace('"', '""') + '"'
|
| 162 |
+
cursor = db.execute(f"select * from main.{quoted} not indexed limit {MAX_ROWS + 1}")
|
| 163 |
+
rows = [[_cell(value) for value in row] for row in cursor]
|
| 164 |
+
return {"columns": [column[0] for column in cursor.description], "primary_key": primary_key,
|
| 165 |
+
"rows": rows[:MAX_ROWS], "truncated": len(rows) > MAX_ROWS}
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def _sqlite(path: Path) -> dict:
|
| 169 |
+
"""The database's ordinary tables, in schema order, up to REA's table and row limits."""
|
| 170 |
+
with contextlib.closing(sqlite3.connect(path.resolve().as_uri() + "?mode=ro", uri=True, timeout=SQLITE_BUSY_S)) as db:
|
| 171 |
+
kinds = dict(db.execute("select name, type from pragma_table_list where schema = 'main'"))
|
| 172 |
+
names = [name for (name,) in db.execute("select name from sqlite_schema where type = 'table'")
|
| 173 |
+
if kinds.get(name) == "table"]
|
| 174 |
+
keys = {name: [key for (key,) in db.execute(
|
| 175 |
+
"select name from pragma_table_info(?, 'main') where pk > 0 order by pk", (name,))]
|
| 176 |
+
for name in names[:MAX_TABLES]}
|
| 177 |
+
db.text_factory = _sqlite_text
|
| 178 |
+
tables = {name: _table(db, name, keys[name]) for name in names[:MAX_TABLES]}
|
| 179 |
+
cut = len(names) > MAX_TABLES
|
| 180 |
+
return {"format": "sqlite", "view": {"tables": tables, "tables_truncated": cut},
|
| 181 |
+
"truncated": cut or any(table["truncated"] for table in tables.values())}
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def _text(text: str) -> dict:
|
| 185 |
+
lines = LINE_BREAK.split(text)
|
| 186 |
+
if lines[-1] == "":
|
| 187 |
+
lines.pop()
|
| 188 |
+
view = {"lines": lines[:MAX_LINES], "line_count": len(lines), "truncated": len(lines) > MAX_LINES}
|
| 189 |
+
return {"format": "text", "view": view, "truncated": view["truncated"]}
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def _keyfile_line(raw: str) -> tuple:
|
| 193 |
+
"""A key file line as REA reads it: skip (blank or comment), group, entry or other."""
|
| 194 |
+
line = raw.strip()
|
| 195 |
+
if not line or line[0] in "#;":
|
| 196 |
+
return ("skip",)
|
| 197 |
+
header = GROUP_HEADER.match(line)
|
| 198 |
+
if header:
|
| 199 |
+
return ("group", header.group(1))
|
| 200 |
+
key, equals, value = line.partition("=")
|
| 201 |
+
return ("entry", key.strip(), value.strip()) if equals and key else ("other",)
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def _is_keyfile(text: str) -> bool:
|
| 205 |
+
"""REA's rule: at least one group, and nothing a key file view would drop."""
|
| 206 |
+
kinds = {_keyfile_line(line)[0] for line in LINE_BREAK.split(text)}
|
| 207 |
+
return "group" in kinds and "other" not in kinds
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def _keyfile(text: str) -> dict:
|
| 211 |
+
groups, group = {}, ""
|
| 212 |
+
for line in map(_keyfile_line, LINE_BREAK.split(text)):
|
| 213 |
+
if line[0] == "group":
|
| 214 |
+
group = line[1]
|
| 215 |
+
groups.setdefault(group, {})
|
| 216 |
+
elif line[0] == "entry":
|
| 217 |
+
groups.setdefault(group, {})[line[1]] = line[2]
|
| 218 |
+
return groups
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
#: XML's whitespace, which alone can be formatting between elements; Unicode's wider set is text.
|
| 222 |
+
XML_WHITESPACE = " \t\r\n"
|
| 223 |
+
PREDEFINED_ENTITIES = ("amp", "lt", "gt", "apos", "quot")
|
| 224 |
+
ENTITY_REFERENCE = re.compile(r"&([^#;][^;]*);")
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def _expat(namespaces: bool, doctype=None):
|
| 228 |
+
"""An expat parser that reads a DOCTYPE as REA does: one with an internal subset, which could declare entities,
|
| 229 |
+
is refused, the DTD it names is never read, and a reference to an entity other than XML's five is refused where
|
| 230 |
+
expat would skip it. With namespaces it also enforces their rules, as REA's parser does, and without them it
|
| 231 |
+
reports names as the document spells them. doctype, when given, receives the declared name and identifiers."""
|
| 232 |
+
parser = expat.ParserCreate(namespace_separator=" " if namespaces else None)
|
| 233 |
+
parser.SetParamEntityParsing(expat.XML_PARAM_ENTITY_PARSING_NEVER)
|
| 234 |
+
|
| 235 |
+
def declared(name: str, system_id, public_id, internal_subset: bool) -> None:
|
| 236 |
+
if internal_subset:
|
| 237 |
+
raise ValueError("the document's DOCTYPE has an internal subset")
|
| 238 |
+
if doctype is not None:
|
| 239 |
+
doctype({"name": name, "public_id": public_id, "system_id": system_id})
|
| 240 |
+
|
| 241 |
+
def undeclared(name: str, _parameter: bool) -> None:
|
| 242 |
+
raise ValueError(f"the document refers to the undeclared entity {name}")
|
| 243 |
+
|
| 244 |
+
def external(*_) -> None:
|
| 245 |
+
raise ValueError("the document refers to an external entity")
|
| 246 |
+
|
| 247 |
+
parser.StartDoctypeDeclHandler = declared
|
| 248 |
+
parser.SkippedEntityHandler = undeclared
|
| 249 |
+
parser.ExternalEntityRefHandler = external
|
| 250 |
+
return parser
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def _check_tag(markup: str) -> None:
|
| 254 |
+
"""expat leaves an undeclared entity out of an attribute value without a word when a DOCTYPE names a DTD; REA's
|
| 255 |
+
parser refuses it. With text taken by its own handler, a start tag is the only markup expat passes here that
|
| 256 |
+
starts with < and a name, and it passes it whole."""
|
| 257 |
+
if markup[:1] == "<" and markup[1:2] not in ("!", "?", "/"):
|
| 258 |
+
for name in ENTITY_REFERENCE.findall(markup):
|
| 259 |
+
if name not in PREDEFINED_ENTITIES:
|
| 260 |
+
raise ValueError(f"the document refers to the undeclared entity {name}")
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
def _ignore_text(_text: str) -> None:
|
| 264 |
+
pass
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
class _XmlReader:
|
| 268 |
+
"""REA's XML view built as expat reads: names as spelled, declarations as attributes, text split where REA's DOM
|
| 269 |
+
splits it (an empty CDATA section joins the text around it), and each node counted against REA's limits."""
|
| 270 |
+
|
| 271 |
+
def __init__(self) -> None:
|
| 272 |
+
self.remaining, self.truncated, self.root, self.doctype = MAX_XML_NODES, False, None, None
|
| 273 |
+
#: Per open element: its view or None when left out, whether xml:space="preserve" applies inside it, whether
|
| 274 |
+
#: it holds an element, and whether it holds text other than whitespace: whitespace-only text is formatting
|
| 275 |
+
#: only in an element that holds elements and no such text.
|
| 276 |
+
self.open = []
|
| 277 |
+
self.text, self.cdata = [], None
|
| 278 |
+
|
| 279 |
+
def read(self, text: str) -> None:
|
| 280 |
+
parser = _expat(False, self._doctype)
|
| 281 |
+
parser.buffer_text = True
|
| 282 |
+
parser.StartElementHandler, parser.EndElementHandler = self._start, self._end
|
| 283 |
+
parser.CharacterDataHandler = self._data
|
| 284 |
+
parser.StartCdataSectionHandler, parser.EndCdataSectionHandler = self._cdata_start, self._cdata_end
|
| 285 |
+
parser.CommentHandler = parser.ProcessingInstructionHandler = self._other
|
| 286 |
+
parser.Parse(text, True)
|
| 287 |
+
|
| 288 |
+
def _doctype(self, declared: dict) -> None:
|
| 289 |
+
self.doctype = declared
|
| 290 |
+
|
| 291 |
+
def _admit(self) -> bool:
|
| 292 |
+
"""Whether the next node inside a kept element is kept, within the node and depth limits; one past them
|
| 293 |
+
marks the view truncated."""
|
| 294 |
+
if self.open and self.open[-1][0] is None:
|
| 295 |
+
return False
|
| 296 |
+
if self.remaining <= 0 or len(self.open) > MAX_XML_DEPTH:
|
| 297 |
+
self.truncated = True
|
| 298 |
+
return False
|
| 299 |
+
self.remaining -= 1
|
| 300 |
+
return True
|
| 301 |
+
|
| 302 |
+
def _text_node(self, text: str) -> None:
|
| 303 |
+
if self.open and text.strip(XML_WHITESPACE):
|
| 304 |
+
self.open[-1][3] = True
|
| 305 |
+
if self._admit():
|
| 306 |
+
self.open[-1][0]["children"].append(text)
|
| 307 |
+
|
| 308 |
+
def _flush(self) -> None:
|
| 309 |
+
if self.text:
|
| 310 |
+
text, self.text = "".join(self.text), []
|
| 311 |
+
self._text_node(text)
|
| 312 |
+
|
| 313 |
+
def _data(self, text: str) -> None:
|
| 314 |
+
(self.text if self.cdata is None else self.cdata).append(text)
|
| 315 |
+
|
| 316 |
+
def _cdata_start(self) -> None:
|
| 317 |
+
self.cdata = []
|
| 318 |
+
|
| 319 |
+
def _cdata_end(self) -> None:
|
| 320 |
+
text, self.cdata = "".join(self.cdata), None
|
| 321 |
+
if text:
|
| 322 |
+
self._flush()
|
| 323 |
+
self._text_node(text)
|
| 324 |
+
|
| 325 |
+
def _other(self, *_) -> None:
|
| 326 |
+
"""A comment or processing instruction, counted like any node and never kept."""
|
| 327 |
+
self._flush()
|
| 328 |
+
if self.open:
|
| 329 |
+
self._admit()
|
| 330 |
+
|
| 331 |
+
def _start(self, name: str, attributes: dict) -> None:
|
| 332 |
+
self._flush()
|
| 333 |
+
parent = self.open[-1] if self.open else [None, False, False, False]
|
| 334 |
+
parent[2] = True
|
| 335 |
+
view = {"name": name, "attributes": attributes, "children": []} if self._admit() else None
|
| 336 |
+
if view is not None and parent[0] is not None:
|
| 337 |
+
parent[0]["children"].append(view)
|
| 338 |
+
space = attributes.get(XML_SPACE)
|
| 339 |
+
self.open.append([view, space == "preserve" if space else parent[1], False, False])
|
| 340 |
+
|
| 341 |
+
def _end(self, _name: str) -> None:
|
| 342 |
+
self._flush()
|
| 343 |
+
view, preserve, holds_element, holds_text = self.open.pop()
|
| 344 |
+
if view is not None and holds_element and not holds_text and not preserve:
|
| 345 |
+
view["children"] = [child for child in view["children"]
|
| 346 |
+
if not isinstance(child, str) or child.strip(XML_WHITESPACE)]
|
| 347 |
+
if not self.open:
|
| 348 |
+
self.root = view
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
def _xml_view(text: str):
|
| 352 |
+
"""REA's XML view, or None for a document REA's parser refuses: a pass with namespaces checks the document as REA's
|
| 353 |
+
parser does, then a pass without them reads names as spelled, as REA's view keeps them, and the DOCTYPE."""
|
| 354 |
+
reader = _XmlReader()
|
| 355 |
+
try:
|
| 356 |
+
check = _expat(True)
|
| 357 |
+
check.CharacterDataHandler, check.DefaultHandler = _ignore_text, _check_tag
|
| 358 |
+
check.Parse(text, True)
|
| 359 |
+
reader.read(text)
|
| 360 |
+
except (expat.ExpatError, ValueError):
|
| 361 |
+
return None
|
| 362 |
+
view = {"root": reader.root, "truncated": reader.truncated}
|
| 363 |
+
return view if reader.doctype is None else {"doctype": reader.doctype, **view}
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
def _not_json(constant: str):
|
| 367 |
+
raise ValueError(f"{constant} is not JSON")
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
class _Inexact(Exception):
|
| 371 |
+
"""A JSON number that REA's state view refuses, since reading it would change it."""
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
def _digits(text: str) -> str:
|
| 375 |
+
return re.split(r"[eE]", text.lstrip("-"))[0].replace(".", "").strip("0") or "0"
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
def _js_string(value: float) -> str:
|
| 379 |
+
"""How JavaScript's String() writes a finite double: an integer below 1e21 in full, any other in shortest form."""
|
| 380 |
+
return str(int(value)) if value.is_integer() and abs(value) < 1e21 else repr(value)
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
def _safe_number(text: str) -> bool:
|
| 384 |
+
"""lossless-json's isSafeNumber: an integer spelling within 2^53, or a float spelling that keeps its digits."""
|
| 385 |
+
if re.fullmatch(r"-?[0-9]+", text):
|
| 386 |
+
return len(text.lstrip("-")) <= 16 and abs(int(text)) <= MAX_SAFE_INTEGER
|
| 387 |
+
value = float(text)
|
| 388 |
+
if not math.isfinite(value):
|
| 389 |
+
return False
|
| 390 |
+
written = _js_string(value)
|
| 391 |
+
return written == text or _digits(written) == _digits(text)
|
| 392 |
+
|
| 393 |
+
|
| 394 |
+
def _exact_number(text: str):
|
| 395 |
+
"""A JSON number read only when reading it changes nothing, as REA's state view rules: its spelling and its
|
| 396 |
+
written-back form both safe, and not -0."""
|
| 397 |
+
value = float(text)
|
| 398 |
+
if (not _safe_number(text) or not math.isfinite(value) or not _safe_number(_js_string(value))
|
| 399 |
+
or (value == 0 and math.copysign(1, value) < 0)):
|
| 400 |
+
raise _Inexact(text)
|
| 401 |
+
return int(text) if re.fullmatch(r"-?[0-9]+", text) else value
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
_INEXACT = object()
|
| 405 |
+
_LEVEL_END = object()
|
| 406 |
+
|
| 407 |
+
|
| 408 |
+
def _number_or_mark(spelling: str):
|
| 409 |
+
"""A JSON number read exactly, or a mark for one REA's state view refuses."""
|
| 410 |
+
try:
|
| 411 |
+
return _exact_number(spelling)
|
| 412 |
+
except _Inexact:
|
| 413 |
+
return _INEXACT
|
| 414 |
+
|
| 415 |
+
|
| 416 |
+
def _holds_inexact(value) -> bool:
|
| 417 |
+
"""Whether a parsed JSON value still holds a marked number once duplicate keys kept their last value; one
|
| 418 |
+
iterator per nesting level, so no child list is copied."""
|
| 419 |
+
levels = [iter((value,))]
|
| 420 |
+
while levels:
|
| 421 |
+
item = next(levels[-1], _LEVEL_END)
|
| 422 |
+
if item is _LEVEL_END:
|
| 423 |
+
levels.pop()
|
| 424 |
+
elif item is _INEXACT:
|
| 425 |
+
return True
|
| 426 |
+
elif isinstance(item, dict):
|
| 427 |
+
levels.append(iter(item.values()))
|
| 428 |
+
elif isinstance(item, list):
|
| 429 |
+
levels.append(iter(item))
|
| 430 |
+
return False
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
def _deeper_than(root, limit: int) -> bool:
|
| 434 |
+
"""Whether a parsed JSON value nests deeper than a limit, as REA checks it: a value's depth is the number of
|
| 435 |
+
iterators open above it, one per nesting level, so no child list is copied."""
|
| 436 |
+
levels = [iter((root,))]
|
| 437 |
+
while levels:
|
| 438 |
+
item = next(levels[-1], _LEVEL_END)
|
| 439 |
+
if item is _LEVEL_END:
|
| 440 |
+
levels.pop()
|
| 441 |
+
elif len(levels) - 1 > limit:
|
| 442 |
+
return True
|
| 443 |
+
elif isinstance(item, dict):
|
| 444 |
+
levels.append(iter(item.values()))
|
| 445 |
+
elif isinstance(item, list):
|
| 446 |
+
levels.append(iter(item))
|
| 447 |
+
return False
|
| 448 |
+
|
| 449 |
+
|
| 450 |
+
def _text_view(name: str, text: str) -> dict:
|
| 451 |
+
"""The format REA's state view detects for decoded text, and its view."""
|
| 452 |
+
trimmed = re.sub(r"^[\s]+", "", text)
|
| 453 |
+
if name.endswith(".json") or trimmed[:1] in ("[", "{"):
|
| 454 |
+
# The whole text must parse, and duplicate keys settle, before an inexact number makes it JSON with an error.
|
| 455 |
+
try:
|
| 456 |
+
view = json.loads(text, parse_constant=_not_json, parse_float=_number_or_mark, parse_int=_number_or_mark)
|
| 457 |
+
except RecursionError:
|
| 458 |
+
# Nesting too deep for Python to parse is far deeper than REA's view keeps.
|
| 459 |
+
return {"format": "json", "view": None, "error": JSON_TOO_DEEP}
|
| 460 |
+
except ValueError:
|
| 461 |
+
pass
|
| 462 |
+
else:
|
| 463 |
+
if _holds_inexact(view):
|
| 464 |
+
return {"format": "json", "view": None,
|
| 465 |
+
"error": "a number in it cannot be read exactly, such as an integer above 2^53"}
|
| 466 |
+
if _deeper_than(view, MAX_JSON_VIEW_DEPTH):
|
| 467 |
+
return {"format": "json", "view": None, "error": JSON_TOO_DEEP}
|
| 468 |
+
return {"format": "json", "view": view, "truncated": False}
|
| 469 |
+
lowered = name.lower()
|
| 470 |
+
if lowered.endswith(XML_SUFFIXES) or trimmed.startswith("<?xml"):
|
| 471 |
+
view = _xml_view(text)
|
| 472 |
+
return _text(text) if view is None else {"format": "xml", "view": view, "truncated": view["truncated"]}
|
| 473 |
+
if _is_keyfile(text):
|
| 474 |
+
return {"format": "keyfile", "view": {"groups": _keyfile(text)}, "truncated": False}
|
| 475 |
+
return _text(text)
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
def _view(path: Path) -> dict:
|
| 479 |
+
"""A typed JSON view of one file in the shapes of REA's state view; truncated says the view is partial."""
|
| 480 |
+
too_large = {"format": None, "view": None, "error": "larger than 64 MiB, the most the view reads"}
|
| 481 |
+
if path.stat().st_size > MAX_VIEW_BYTES:
|
| 482 |
+
return too_large
|
| 483 |
+
with path.open("rb") as file:
|
| 484 |
+
data = file.read(8192)
|
| 485 |
+
whole = not data.startswith(SQLITE_HEADER) and b"\x00" not in data
|
| 486 |
+
data += file.read(MAX_VIEW_BYTES + 1 - len(data)) if whole else b""
|
| 487 |
+
if data.startswith(SQLITE_HEADER):
|
| 488 |
+
return _sqlite(path)
|
| 489 |
+
if data.startswith(ZIP_HEADER):
|
| 490 |
+
return _zip(path)
|
| 491 |
+
if len(data) > MAX_VIEW_BYTES:
|
| 492 |
+
return too_large
|
| 493 |
+
try:
|
| 494 |
+
text = data.decode("utf-8-sig") if whole else None
|
| 495 |
+
except UnicodeDecodeError:
|
| 496 |
+
text = None
|
| 497 |
+
return {"format": "binary", "view": None, "truncated": False} if text is None else _text_view(path.name, text)
|
| 498 |
+
|
| 499 |
+
|
| 500 |
+
def _views(home: Path, paths: list) -> dict:
|
| 501 |
+
"""A view of every file under the app's paths, keyed by its home-relative path."""
|
| 502 |
+
files = {}
|
| 503 |
+
for owned in paths:
|
| 504 |
+
root = home / owned
|
| 505 |
+
candidates = [root] if root.is_file() else sorted(root.rglob("*")) if root.is_dir() else []
|
| 506 |
+
for path in candidates:
|
| 507 |
+
if path.is_file() and not path.is_symlink():
|
| 508 |
+
key = path.relative_to(home).as_posix()
|
| 509 |
+
try:
|
| 510 |
+
files[key] = _view(path)
|
| 511 |
+
except (OSError, ValueError, sqlite3.Error, RecursionError) as error:
|
| 512 |
+
files[key] = {"format": None, "view": None, "error": str(error)}
|
| 513 |
+
return files
|
| 514 |
+
|
| 515 |
+
MAX_ZIP_ENTRIES = 1000
|
| 516 |
+
MAX_ZIP_ENTRY_BYTES = 16 * 1024 * 1024
|
| 517 |
+
MAX_ZIP_BYTES = 64 * 1024 * 1024
|
| 518 |
+
MAX_ZIP_RATIO = 100
|
| 519 |
+
ZIP_READ_CHUNK = 64 * 1024
|
| 520 |
+
ZIP_END = b"PK\x05\x06"
|
| 521 |
+
ZIP_CENTRAL = b"PK\x01\x02"
|
| 522 |
+
ZIP64_LOCATOR = b"PK\x06\x07"
|
| 523 |
+
ZIP64_END = b"PK\x06\x06"
|
| 524 |
+
#: Formats an archive entry may have whose reader needs a tool, a worker or another archive opened.
|
| 525 |
+
NOT_READ_INSIDE = ((SQLITE_HEADER, "sqlite", "a SQLite database"), (GVDB_HEADER, "dconf", "a dconf database"),
|
| 526 |
+
(ZIP_HEADER, "zip", "an archive"))
|
| 527 |
+
|
| 528 |
+
|
| 529 |
+
def _entry_view(name: str, data: bytes) -> dict:
|
| 530 |
+
"""An archive entry's format and view by the rules a file's follow; a database or an archive inside is not
|
| 531 |
+
read."""
|
| 532 |
+
for header, form, inside in NOT_READ_INSIDE:
|
| 533 |
+
if data.startswith(header):
|
| 534 |
+
return {"format": form, "view": None, "error": f"{inside} inside an archive is not read"}
|
| 535 |
+
try:
|
| 536 |
+
text = data.decode("utf-8-sig") if b"\x00" not in data[:8192] else None
|
| 537 |
+
except UnicodeDecodeError:
|
| 538 |
+
text = None
|
| 539 |
+
if text is None:
|
| 540 |
+
return {"format": "binary", "view": None}
|
| 541 |
+
view = _text_view(name, text)
|
| 542 |
+
if view["format"] in ("json", "keyfile") and len(data) > MAX_PARSED_BYTES:
|
| 543 |
+
return {"format": view["format"], "view": None,
|
| 544 |
+
"error": "larger than the 4 MiB limit for JSON and key file views"}
|
| 545 |
+
return view
|
| 546 |
+
|
| 547 |
+
|
| 548 |
+
def _zip_refusal(info, spent: int):
|
| 549 |
+
"""Why an entry is not read, checked in REA's order, or None; spent is the archive's bytes read so far."""
|
| 550 |
+
if info.flag_bits & 0x1:
|
| 551 |
+
return "encrypted, so it is not read"
|
| 552 |
+
if info.compress_type not in (zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED):
|
| 553 |
+
return f"compressed with method {info.compress_type}, which the view does not read"
|
| 554 |
+
if info.file_size > MAX_ZIP_ENTRY_BYTES:
|
| 555 |
+
return "larger than the 16 MiB an entry's view reads"
|
| 556 |
+
if info.file_size > MAX_ZIP_RATIO * info.compress_size:
|
| 557 |
+
return f"expands more than {MAX_ZIP_RATIO} times, so it is not read"
|
| 558 |
+
if spent + info.file_size > MAX_ZIP_BYTES:
|
| 559 |
+
return "past the 64 MiB read from one archive"
|
| 560 |
+
return None
|
| 561 |
+
|
| 562 |
+
|
| 563 |
+
def _entry_bytes(archive, info):
|
| 564 |
+
"""An entry's uncompressed bytes, or None when they fail its CRC-32 or are not exactly its declared size. Reading
|
| 565 |
+
stops one byte past that size, which data past a short declared size fills, and asks for a bounded chunk at a
|
| 566 |
+
time, which bounds what the decompressor expands per call, so a forged small size holds no more than that."""
|
| 567 |
+
probe = copy.copy(info)
|
| 568 |
+
probe.file_size = info.file_size + 1
|
| 569 |
+
data = bytearray()
|
| 570 |
+
try:
|
| 571 |
+
with archive.open(probe) as member:
|
| 572 |
+
while len(data) <= info.file_size:
|
| 573 |
+
chunk = member.read(min(probe.file_size - len(data), ZIP_READ_CHUNK))
|
| 574 |
+
if not chunk:
|
| 575 |
+
break
|
| 576 |
+
data += chunk
|
| 577 |
+
except (zipfile.BadZipFile, zlib.error, EOFError, OSError, ValueError):
|
| 578 |
+
return None
|
| 579 |
+
return data if len(data) == info.file_size else None
|
| 580 |
+
|
| 581 |
+
|
| 582 |
+
def _zip_entry(archive, info, refusal):
|
| 583 |
+
"""One entry of a zip view: its name, size and digest, and its own format and view, or why it was not read."""
|
| 584 |
+
entry = {"name": info.filename, "size": info.file_size, "sha256": None, "format": None, "view": None,
|
| 585 |
+
"view_error": refusal}
|
| 586 |
+
if refusal is not None:
|
| 587 |
+
return entry
|
| 588 |
+
data = _entry_bytes(archive, info)
|
| 589 |
+
if data is None:
|
| 590 |
+
return {**entry, "view_error": "its compressed data is damaged"}
|
| 591 |
+
view = _entry_view(info.filename, data)
|
| 592 |
+
return {**entry, "sha256": hashlib.sha256(data).hexdigest(), "format": view["format"],
|
| 593 |
+
"view": view.get("view"), "view_error": view.get("error")}
|
| 594 |
+
|
| 595 |
+
|
| 596 |
+
def _zip_end(file, size: int):
|
| 597 |
+
"""Where an archive's central directory ends, how long it is and the offset it declares, from the last end
|
| 598 |
+
record whose comment reaches the end of the file and, when a Zip64 locator precedes it whatever that record
|
| 599 |
+
holds, the Zip64 one just before the locator; None without an end record, or when sentinels defer to a
|
| 600 |
+
Zip64 record that is missing."""
|
| 601 |
+
window = min(size, 22 + 0xFFFF)
|
| 602 |
+
file.seek(size - window)
|
| 603 |
+
tail = file.read(window)
|
| 604 |
+
at = tail.rfind(ZIP_END, 0, len(tail) - 18)
|
| 605 |
+
while at >= 0 and at + 22 + int.from_bytes(tail[at + 20:at + 22], "little") != len(tail):
|
| 606 |
+
at = tail.rfind(ZIP_END, 0, at + 3)
|
| 607 |
+
if at < 0:
|
| 608 |
+
return None
|
| 609 |
+
total, length, offset = struct.unpack_from("<HII", tail, at + 10)
|
| 610 |
+
end = size - window + at
|
| 611 |
+
record = end - 20 - 56
|
| 612 |
+
if record < 0:
|
| 613 |
+
return end, length, offset
|
| 614 |
+
file.seek(end - 20)
|
| 615 |
+
if file.read(4) != ZIP64_LOCATOR:
|
| 616 |
+
return end, length, offset
|
| 617 |
+
file.seek(record)
|
| 618 |
+
zip64 = file.read(56)
|
| 619 |
+
if len(zip64) == 56 and zip64[:4] == ZIP64_END:
|
| 620 |
+
length, offset = struct.unpack_from("<QQ", zip64, 40)
|
| 621 |
+
return record, length, offset
|
| 622 |
+
if total == 0xFFFF or 0xFFFFFFFF in (length, offset):
|
| 623 |
+
return None
|
| 624 |
+
return end, length, offset
|
| 625 |
+
|
| 626 |
+
|
| 627 |
+
def _zip_unicode_path(raw: bytes, flags: int, extra: bytes):
|
| 628 |
+
"""An Info-ZIP Unicode Path when zip.js uses it: version 1, no UTF-8 flag, and the CRC-32 of the stored name."""
|
| 629 |
+
at = 0
|
| 630 |
+
while at + 4 <= len(extra):
|
| 631 |
+
kind, length = struct.unpack_from("<HH", extra, at)
|
| 632 |
+
if kind == 0x7075:
|
| 633 |
+
data = extra[at + 4:at + 4 + length]
|
| 634 |
+
usable = (length >= 5 and len(data) == length and data[0] == 1 and not flags & 0x800
|
| 635 |
+
and int.from_bytes(data[1:5], "little") == zlib.crc32(raw))
|
| 636 |
+
return data[5:] if usable else None
|
| 637 |
+
at += 4 + length
|
| 638 |
+
return None
|
| 639 |
+
|
| 640 |
+
|
| 641 |
+
def _zip_ends_in_slash(raw: bytes, flags: int, extra: bytes):
|
| 642 |
+
"""Whether an entry's name, as REA decodes it, ends in a slash; None when it must be UTF-8 and is not."""
|
| 643 |
+
utf8 = _zip_unicode_path(raw, flags, extra)
|
| 644 |
+
if utf8 is None and flags & 0x800:
|
| 645 |
+
utf8 = raw
|
| 646 |
+
if utf8 is None:
|
| 647 |
+
return raw.endswith(b"/")
|
| 648 |
+
try:
|
| 649 |
+
return utf8.decode("utf-8").endswith("/")
|
| 650 |
+
except UnicodeDecodeError:
|
| 651 |
+
return None
|
| 652 |
+
|
| 653 |
+
|
| 654 |
+
def _zip_directory(file, size: int, keep: int):
|
| 655 |
+
"""An archive's central directory read a record at a time, keeping the first file entries' records, as many as keep allows, and
|
| 656 |
+
counting the rest, as REA reads it: (start, declared offset, records, count), or None when it cannot be read.
|
| 657 |
+
Directories are told apart as zip.js tells them: a final slash, a Unix directory mode, or the MS-DOS attribute."""
|
| 658 |
+
located = _zip_end(file, size)
|
| 659 |
+
if located is None:
|
| 660 |
+
return None
|
| 661 |
+
end, length, declared = located
|
| 662 |
+
start = end - length
|
| 663 |
+
if start < 0:
|
| 664 |
+
return None
|
| 665 |
+
file.seek(start)
|
| 666 |
+
records, count, at = [], 0, start
|
| 667 |
+
while at < end:
|
| 668 |
+
fixed = file.read(46)
|
| 669 |
+
if at + 46 > end or len(fixed) < 46 or fixed[:4] != ZIP_CENTRAL:
|
| 670 |
+
return None
|
| 671 |
+
made_by, flags = struct.unpack_from("<H2xH", fixed, 4)
|
| 672 |
+
name_length, extra_length, comment_length = struct.unpack_from("<HHH", fixed, 28)
|
| 673 |
+
external = struct.unpack_from("<I", fixed, 38)[0]
|
| 674 |
+
rest = file.read(name_length + extra_length + comment_length)
|
| 675 |
+
at += 46 + name_length + extra_length + comment_length
|
| 676 |
+
if len(rest) < name_length + extra_length + comment_length or at > end:
|
| 677 |
+
return None
|
| 678 |
+
slash = _zip_ends_in_slash(rest[:name_length], flags, rest[name_length:name_length + extra_length])
|
| 679 |
+
if slash is None:
|
| 680 |
+
return None
|
| 681 |
+
if not (slash or (external >> 16) & 0o170000 == 0o040000 or (made_by >> 8 == 0 and external & 0x10)):
|
| 682 |
+
count += 1
|
| 683 |
+
if len(records) < keep:
|
| 684 |
+
records.append(fixed + rest)
|
| 685 |
+
return start, declared, records, count
|
| 686 |
+
|
| 687 |
+
|
| 688 |
+
class _BoundedArchive(io.RawIOBase):
|
| 689 |
+
"""An archive as zipfile reads it: its entries in place, then a directory of the kept records alone and end
|
| 690 |
+
records for them, so zipfile parses no more records than the view lists."""
|
| 691 |
+
|
| 692 |
+
def __init__(self, file, start: int, tail: bytes) -> None:
|
| 693 |
+
super().__init__()
|
| 694 |
+
self._file, self._start, self._tail, self._at = file, start, tail, 0
|
| 695 |
+
|
| 696 |
+
def readable(self) -> bool:
|
| 697 |
+
return True
|
| 698 |
+
|
| 699 |
+
def seekable(self) -> bool:
|
| 700 |
+
return True
|
| 701 |
+
|
| 702 |
+
def tell(self) -> int:
|
| 703 |
+
return self._at
|
| 704 |
+
|
| 705 |
+
def seek(self, offset: int, whence: int = 0) -> int:
|
| 706 |
+
self._at = offset + (0, self._at, self._start + len(self._tail))[whence]
|
| 707 |
+
return self._at
|
| 708 |
+
|
| 709 |
+
def readinto(self, buffer) -> int:
|
| 710 |
+
view = memoryview(buffer)
|
| 711 |
+
if self._at < self._start:
|
| 712 |
+
self._file.seek(self._at)
|
| 713 |
+
count = self._file.readinto(view[:self._start - self._at])
|
| 714 |
+
else:
|
| 715 |
+
chunk = self._tail[self._at - self._start:self._at - self._start + len(view)]
|
| 716 |
+
count = len(chunk)
|
| 717 |
+
view[:count] = chunk
|
| 718 |
+
self._at += count
|
| 719 |
+
return count
|
| 720 |
+
|
| 721 |
+
|
| 722 |
+
def _zip(path: Path) -> dict:
|
| 723 |
+
"""A zip archive's file entries in archive order, up to REA's entry, size, ratio and archive limits; nothing is
|
| 724 |
+
extracted to disk, no archive inside is opened, and zipfile is shown only the directory records listed."""
|
| 725 |
+
entries, spent = [], 0
|
| 726 |
+
try:
|
| 727 |
+
with path.open("rb") as file:
|
| 728 |
+
directory = _zip_directory(file, os.fstat(file.fileno()).st_size, MAX_ZIP_ENTRIES)
|
| 729 |
+
if directory is None:
|
| 730 |
+
raise zipfile.BadZipFile("no readable central directory")
|
| 731 |
+
start, declared, records, count = directory
|
| 732 |
+
kept = b"".join(records)
|
| 733 |
+
offset = declared if declared <= 0xFFFFFFFF else start
|
| 734 |
+
# zipfile follows a Zip64 locator signature wherever one sits before the end record, and the kept records
|
| 735 |
+
# may end in those bytes, so a real Zip64 end record and locator for them come first.
|
| 736 |
+
tail = (kept
|
| 737 |
+
+ struct.pack("<4sQ2H2I4Q", ZIP64_END, 44, 45, 45, 0, 0, len(records), len(records), len(kept), offset)
|
| 738 |
+
+ struct.pack("<4sIQI", ZIP64_LOCATOR, 0, offset + len(kept), 1)
|
| 739 |
+
+ struct.pack("<4s4H2IH", ZIP_END, 0, 0, len(records), len(records), len(kept), offset, 0))
|
| 740 |
+
with zipfile.ZipFile(_BoundedArchive(file, start, tail)) as archive:
|
| 741 |
+
for info in archive.infolist():
|
| 742 |
+
refusal = _zip_refusal(info, spent)
|
| 743 |
+
spent += info.file_size if refusal is None else 0
|
| 744 |
+
entries.append(_zip_entry(archive, info, refusal))
|
| 745 |
+
except (zipfile.BadZipFile, zlib.error, EOFError, NotImplementedError, OSError, ValueError, struct.error):
|
| 746 |
+
return {"format": "zip", "view": None, "error": "not a readable zip archive"}
|
| 747 |
+
view = {"entries": entries, "entry_count": count, "truncated": count > len(entries)}
|
| 748 |
+
return {"format": "zip", "view": view, "truncated": view["truncated"]}
|
| 749 |
+
|
| 750 |
+
|
| 751 |
+
@computer_app(supports=[{"os": {"type": "linux", "display": ["x11"]}, "arch": ["amd64", "arm64"]}])
|
| 752 |
+
@linux(
|
| 753 |
+
packages=Packages(apt=["homebank"]),
|
| 754 |
+
launch=Launch(at="boot", command=["sh", "-c", "cd \"$HOME\" 2>/dev/null; exec 'homebank' \"$HOME\"/'Documents/household.xhb'"], window={"class": "Homebank"}, ready=Ready(window=True)),
|
| 755 |
+
paths=PATHS,
|
| 756 |
+
skill="SKILL.md",
|
| 757 |
+
)
|
| 758 |
+
class Homebank(ComputerAppEnvironment):
|
| 759 |
+
"""HomeBank, launched at boot with the captured state in its home.
|
| 760 |
+
|
| 761 |
+
Declaring data hooks switches off agentenv's default data plane, so these call its helpers: the seed is kept as
|
| 762 |
+
the initial state, reset restores it, add writes files under PATHS, and get returns those files plus a typed JSON
|
| 763 |
+
view of each.
|
| 764 |
+
"""
|
| 765 |
+
|
| 766 |
+
def __init__(self) -> None:
|
| 767 |
+
super().__init__()
|
| 768 |
+
if not INITIAL.exists():
|
| 769 |
+
_seed_home(Path.home())
|
| 770 |
+
_load_dconf(Path.home())
|
| 771 |
+
keep_initial(self.paths)
|
| 772 |
+
|
| 773 |
+
@add_data
|
| 774 |
+
async def add_files(self, parts: list) -> None:
|
| 775 |
+
await add(parts, self.paths)
|
| 776 |
+
|
| 777 |
+
@get_data
|
| 778 |
+
async def get_files(self, write_namespace=None) -> list:
|
| 779 |
+
files = await get(self.paths, write_namespace)
|
| 780 |
+
views = await in_thread(_views, Path.home(), self.paths)
|
| 781 |
+
return [*files, DataPart(data={"state": views})]
|
| 782 |
+
|
| 783 |
+
@reset_data
|
| 784 |
+
async def reset_files(self) -> None:
|
| 785 |
+
await reset(self.paths)
|
| 786 |
+
|
| 787 |
+
@ready_check
|
| 788 |
+
def main_window_shown(self) -> bool:
|
| 789 |
+
"""A window of the app's class that the taskbar lists is shown, not only a splash screen or a dialog."""
|
| 790 |
+
return _taskbar_window(WINDOW_CLASS)
|
bundle/envs/homebank/seed/Documents/household.xhb
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<?xml version="1.0"?>
|
| 2 |
+
<homebank v="1.3999999999999999" d="050704">
|
| 3 |
+
<properties title="Rivera Household" curr="1" auto_smode="0" auto_weekday="1" auto_nbmonths="1"/>
|
| 4 |
+
<cur key="1" flags="0" iso="USD" name="US Dollar" symb="$" syprf="1" dchar="." gchar="," frac="2" rate="0" mdate="0"/>
|
| 5 |
+
<account key="1" pos="1" type="6" curr="1" name="Everyday Checking" bankname="Lakeside Credit Union" initial="2450" minimum="0" maximum="0"/>
|
| 6 |
+
<account key="2" pos="2" type="7" curr="1" name="Rainy Day Savings" bankname="Lakeside Credit Union" initial="6200" minimum="0" maximum="0"/>
|
| 7 |
+
<pay key="1" name="Fresh Market"/>
|
| 8 |
+
<pay key="2" name="Maple Grove Apartments"/>
|
| 9 |
+
<pay key="3" name="Northside Power Co"/>
|
| 10 |
+
<pay key="4" name="Corner Pantry Grocers"/>
|
| 11 |
+
<pay key="5" name="Brightwave Internet"/>
|
| 12 |
+
<pay key="6" name="Acme Robotics Payroll"/>
|
| 13 |
+
<cat key="1" name="Alimony"/>
|
| 14 |
+
<cat key="2" name="Automobile"/>
|
| 15 |
+
<cat key="5" parent="2" flags="1" name="Maintenance"/>
|
| 16 |
+
<cat key="4" parent="2" flags="1" name="Gasoline"/>
|
| 17 |
+
<cat key="3" parent="2" flags="1" name="Car Payment"/>
|
| 18 |
+
<cat key="6" name="Bank Charges"/>
|
| 19 |
+
<cat key="8" parent="6" flags="1" name="Service charge"/>
|
| 20 |
+
<cat key="7" parent="6" flags="1" name="Interest Paid"/>
|
| 21 |
+
<cat key="9" name="Bills"/>
|
| 22 |
+
<cat key="22" parent="9" flags="1" name="Other Loan Payment"/>
|
| 23 |
+
<cat key="21" parent="9" flags="1" name="On-line/Internet Service"/>
|
| 24 |
+
<cat key="20" parent="9" flags="1" name="Newspaper"/>
|
| 25 |
+
<cat key="19" parent="9" flags="1" name="Natural Gas/Oil"/>
|
| 26 |
+
<cat key="18" parent="9" flags="1" name="Mortgage Payment"/>
|
| 27 |
+
<cat key="17" parent="9" flags="1" name="Membership Fees"/>
|
| 28 |
+
<cat key="16" parent="9" flags="1" name="Home-owner's Dues"/>
|
| 29 |
+
<cat key="15" parent="9" flags="1" name="Health Club"/>
|
| 30 |
+
<cat key="14" parent="9" flags="1" name="Garbage & Recycle"/>
|
| 31 |
+
<cat key="13" parent="9" flags="1" name="Electricity"/>
|
| 32 |
+
<cat key="12" parent="9" flags="1" name="Cellular"/>
|
| 33 |
+
<cat key="11" parent="9" flags="1" name="Cell Phone"/>
|
| 34 |
+
<cat key="10" parent="9" flags="1" name="Cable/Satellite Television"/>
|
| 35 |
+
<cat key="26" parent="9" flags="1" name="Water & Sewer"/>
|
| 36 |
+
<cat key="25" parent="9" flags="1" name="Telephone"/>
|
| 37 |
+
<cat key="24" parent="9" flags="1" name="Student Loan Payment"/>
|
| 38 |
+
<cat key="23" parent="9" flags="1" name="Rent"/>
|
| 39 |
+
<cat key="27" name="Cash Withdrawal"/>
|
| 40 |
+
<cat key="28" name="Charitable Donations"/>
|
| 41 |
+
<cat key="29" name="Childcare"/>
|
| 42 |
+
<cat key="30" name="Children/Toys"/>
|
| 43 |
+
<cat key="32" parent="30" flags="1" name="Daycare"/>
|
| 44 |
+
<cat key="31" parent="30" flags="1" name="Child Support"/>
|
| 45 |
+
<cat key="33" name="Clothing"/>
|
| 46 |
+
<cat key="34" name="Credit Card Payments/Transfers"/>
|
| 47 |
+
<cat key="35" name="Dining Out"/>
|
| 48 |
+
<cat key="36" name="Education"/>
|
| 49 |
+
<cat key="39" parent="36" flags="1" name="Tuition"/>
|
| 50 |
+
<cat key="38" parent="36" flags="1" name="Fees"/>
|
| 51 |
+
<cat key="37" parent="36" flags="1" name="Books"/>
|
| 52 |
+
<cat key="40" name="Entertainment"/>
|
| 53 |
+
<cat key="41" name="Fees"/>
|
| 54 |
+
<cat key="42" name="Food"/>
|
| 55 |
+
<cat key="43" name="Gifts"/>
|
| 56 |
+
<cat key="44" name="Groceries"/>
|
| 57 |
+
<cat key="45" name="Health-care"/>
|
| 58 |
+
<cat key="50" parent="45" flags="1" name="Prescriptions"/>
|
| 59 |
+
<cat key="49" parent="45" flags="1" name="Physician"/>
|
| 60 |
+
<cat key="48" parent="45" flags="1" name="Hospital"/>
|
| 61 |
+
<cat key="47" parent="45" flags="1" name="Eye-care"/>
|
| 62 |
+
<cat key="46" parent="45" flags="1" name="Dental"/>
|
| 63 |
+
<cat key="51" name="Hobbies/Leisure"/>
|
| 64 |
+
<cat key="59" parent="51" flags="1" name="Toys & Games"/>
|
| 65 |
+
<cat key="58" parent="51" flags="1" name="Tapes & CDs"/>
|
| 66 |
+
<cat key="57" parent="51" flags="1" name="Sporting Goods"/>
|
| 67 |
+
<cat key="56" parent="51" flags="1" name="Sporting Events"/>
|
| 68 |
+
<cat key="55" parent="51" flags="1" name="Movies & Video Rentals"/>
|
| 69 |
+
<cat key="54" parent="51" flags="1" name="Entertaining"/>
|
| 70 |
+
<cat key="53" parent="51" flags="1" name="Cultural Events"/>
|
| 71 |
+
<cat key="52" parent="51" flags="1" name="Books & Magazines"/>
|
| 72 |
+
<cat key="60" name="Home Improvement"/>
|
| 73 |
+
<cat key="61" name="Household"/>
|
| 74 |
+
<cat key="64" parent="61" flags="1" name="Yard Service"/>
|
| 75 |
+
<cat key="63" parent="61" flags="1" name="House Cleaning"/>
|
| 76 |
+
<cat key="62" parent="61" flags="1" name="Furnishing"/>
|
| 77 |
+
<cat key="65" name="Insurance"/>
|
| 78 |
+
<cat key="68" parent="65" flags="1" name="Home-owner's/Renter's"/>
|
| 79 |
+
<cat key="67" parent="65" flags="1" name="Health"/>
|
| 80 |
+
<cat key="66" parent="65" flags="1" name="Automobile"/>
|
| 81 |
+
<cat key="69" parent="65" flags="1" name="Life"/>
|
| 82 |
+
<cat key="70" name="Job Expense"/>
|
| 83 |
+
<cat key="72" parent="70" flags="1" name="Reimbursed"/>
|
| 84 |
+
<cat key="71" parent="70" flags="1" name="Non-Reimbursed"/>
|
| 85 |
+
<cat key="73" name="Loan"/>
|
| 86 |
+
<cat key="76" parent="73" flags="1" name="Student Loan Interest"/>
|
| 87 |
+
<cat key="75" parent="73" flags="1" name="Mortgage Interest"/>
|
| 88 |
+
<cat key="74" parent="73" flags="1" name="Loan Interest"/>
|
| 89 |
+
<cat key="77" name="Miscellaneous"/>
|
| 90 |
+
<cat key="78" name="Mortgage/Rent"/>
|
| 91 |
+
<cat key="79" name="Personal Care"/>
|
| 92 |
+
<cat key="80" name="Pet Care"/>
|
| 93 |
+
<cat key="83" parent="80" flags="1" name="Veterinarian"/>
|
| 94 |
+
<cat key="82" parent="80" flags="1" name="Supplies"/>
|
| 95 |
+
<cat key="81" parent="80" flags="1" name="Food"/>
|
| 96 |
+
<cat key="84" name="Phone/Wireless"/>
|
| 97 |
+
<cat key="85" name="Services/Memberships"/>
|
| 98 |
+
<cat key="86" name="Taxes"/>
|
| 99 |
+
<cat key="91" parent="86" flags="1" name="Other Taxes"/>
|
| 100 |
+
<cat key="90" parent="86" flags="1" name="Medicare tax"/>
|
| 101 |
+
<cat key="89" parent="86" flags="1" name="Local Income Tax"/>
|
| 102 |
+
<cat key="88" parent="86" flags="1" name="Federal Income Tax-Previous Year"/>
|
| 103 |
+
<cat key="87" parent="86" flags="1" name="Federal Income Tax"/>
|
| 104 |
+
<cat key="96" parent="86" flags="1" name="State/Provincial"/>
|
| 105 |
+
<cat key="95" parent="86" flags="1" name="State Income Tax"/>
|
| 106 |
+
<cat key="94" parent="86" flags="1" name="Social Security Tax"/>
|
| 107 |
+
<cat key="93" parent="86" flags="1" name="Sales Tax"/>
|
| 108 |
+
<cat key="92" parent="86" flags="1" name="Real Estate Taxes"/>
|
| 109 |
+
<cat key="97" name="Travel/Vacation"/>
|
| 110 |
+
<cat key="99" parent="97" flags="1" name="Travel"/>
|
| 111 |
+
<cat key="98" parent="97" flags="1" name="Lodging"/>
|
| 112 |
+
<cat key="100" name="Utilities"/>
|
| 113 |
+
<cat key="101" flags="2" name="Income/Interest"/>
|
| 114 |
+
<cat key="102" flags="2" name="Investment Income"/>
|
| 115 |
+
<cat key="106" parent="102" flags="3" name="Tax-Exempt Interest"/>
|
| 116 |
+
<cat key="105" parent="102" flags="3" name="Interest"/>
|
| 117 |
+
<cat key="104" parent="102" flags="3" name="Dividends"/>
|
| 118 |
+
<cat key="103" parent="102" flags="3" name="Capital Gains"/>
|
| 119 |
+
<cat key="107" flags="2" name="Not an Expense"/>
|
| 120 |
+
<cat key="108" flags="2" name="Other Income"/>
|
| 121 |
+
<cat key="114" parent="108" flags="3" name="State & Local Tax Refund"/>
|
| 122 |
+
<cat key="113" parent="108" flags="3" name="Lotteries"/>
|
| 123 |
+
<cat key="112" parent="108" flags="3" name="Loan Principal Received"/>
|
| 124 |
+
<cat key="111" parent="108" flags="3" name="Gifts Received"/>
|
| 125 |
+
<cat key="110" parent="108" flags="3" name="Employee Stock Option"/>
|
| 126 |
+
<cat key="109" parent="108" flags="3" name="Child Support Received"/>
|
| 127 |
+
<cat key="115" parent="108" flags="3" name="Unemployment Compensation"/>
|
| 128 |
+
<cat key="116" flags="2" name="Retirement Income"/>
|
| 129 |
+
<cat key="119" parent="116" flags="3" name="Social Security Benefits"/>
|
| 130 |
+
<cat key="118" parent="116" flags="3" name="Pensions & Annuities"/>
|
| 131 |
+
<cat key="117" parent="116" flags="3" name="IRA Distribution"/>
|
| 132 |
+
<cat key="120" flags="2" name="Wage & Salary"/>
|
| 133 |
+
<cat key="126" parent="120" flags="3" name="Overtime"/>
|
| 134 |
+
<cat key="125" parent="120" flags="3" name="Net Pay"/>
|
| 135 |
+
<cat key="124" parent="120" flags="3" name="Gross Pay"/>
|
| 136 |
+
<cat key="123" parent="120" flags="3" name="Employer Matching"/>
|
| 137 |
+
<cat key="122" parent="120" flags="3" name="Commission"/>
|
| 138 |
+
<cat key="121" parent="120" flags="3" name="Bonus"/>
|
| 139 |
+
<ope date="739890" amount="-1450" account="1" payee="2" category="23" wording="October rent"/>
|
| 140 |
+
<ope date="739904" amount="-86.400000000000006" account="1" payee="3" category="13" wording="Electric bill"/>
|
| 141 |
+
<ope date="739913" amount="-38.75" account="1" payee="4" category="44" wording="Pantry restock"/>
|
| 142 |
+
<ope date="739917" amount="-59.990000000000002" account="1" payee="5" category="21" wording="Home internet"/>
|
| 143 |
+
<ope date="739919" amount="2180" account="1" flags="2" payee="6" category="125" wording="Paycheck"/>
|
| 144 |
+
</homebank>
|
bundle/evals/homebank.toml
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
tasks = ["record-grocery-expense"]
|
bundle/tasks/record-grocery-expense.json
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[
|
| 2 |
+
{"id":"env","type":"deploy_env","env_id":"homebank"},
|
| 3 |
+
{"id":"agent","type":"deploy_agent","env_ids":["homebank"]},
|
| 4 |
+
{"id":"skills","type":"add_skills","env_ids":["homebank"]},
|
| 5 |
+
{"id":"record","type":"start_computer_recording","env_id":"homebank","name":"agent","depends_on":["env"]},
|
| 6 |
+
{"id":"task","type":"prompt_agent","depends_on":["skills","record"],"prompt":"In HomeBank, record a new grocery expense in the Everyday Checking account of Documents/household.xhb: $64.18 paid to Fresh Market on November 4, 2026, category Groceries, memo \"Weekly groceries\". Then save the file."},
|
| 7 |
+
{"id":"check","type":"env_outcome_verifier","env_id":"homebank","file_artifact_id":"record-grocery-expense-check","verifier_id":"record-grocery-expense","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": "homebank"
|
| 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:6e90fa9d75c40361573d82ed150c30d841d85e96fb67fe903fb54275a6187b8e
|
| 3 |
+
size 4242974
|
media/solve-2.mp4
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5422400668b2d9be1ff4b51d67328d03dca4b89551ac3c186444382b3c264e55
|
| 3 |
+
size 3876349
|
media/witness.mp4
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ea728d138b8c87244cdb0d0d127752402cd824c40bb4caad1a1f38b4ab865684
|
| 3 |
+
size 15245517
|
results.json
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"environment": "HomeBank",
|
| 3 |
+
"app_version": "HomeBank 5.7 personal finance manager",
|
| 4 |
+
"task": "record-grocery-expense",
|
| 5 |
+
"prompt": "In HomeBank, record a new grocery expense in the Everyday Checking account of Documents/household.xhb: $64.18 paid to Fresh Market on November 4, 2026, category Groceries, memo \"Weekly groceries\". Then save the file.",
|
| 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 expense was recorded through computer actions, failed on a near miss (the amount changed to $64.81) 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": 38,
|
| 15 |
+
"usd": 1.78,
|
| 16 |
+
"checks": {
|
| 17 |
+
"record-grocery-expense": {
|
| 18 |
+
"score": 1.0,
|
| 19 |
+
"results": [
|
| 20 |
+
{
|
| 21 |
+
"id": "amount",
|
| 22 |
+
"result": true,
|
| 23 |
+
"description": "Documents/household.xhb at /root/children/[name=ope][@wording=Weekly groceries]/attributes/amount is \"-64.180000000000007\", within 0.001 of -64.18"
|
| 24 |
+
},
|
| 25 |
+
{
|
| 26 |
+
"id": "account",
|
| 27 |
+
"result": true,
|
| 28 |
+
"description": "Documents/household.xhb at /root/children/[name=ope][@wording=Weekly groceries]/attributes/account is \"1\""
|
| 29 |
+
},
|
| 30 |
+
{
|
| 31 |
+
"id": "date",
|
| 32 |
+
"result": true,
|
| 33 |
+
"description": "Documents/household.xhb at /root/children/[name=ope][@wording=Weekly groceries]/attributes/date is \"739924\""
|
| 34 |
+
},
|
| 35 |
+
{
|
| 36 |
+
"id": "payee",
|
| 37 |
+
"result": true,
|
| 38 |
+
"description": "Documents/household.xhb at /root/children/[name=ope][@wording=Weekly groceries]/attributes/payee is \"1\""
|
| 39 |
+
},
|
| 40 |
+
{
|
| 41 |
+
"id": "category",
|
| 42 |
+
"result": true,
|
| 43 |
+
"description": "Documents/household.xhb at /root/children/[name=ope][@wording=Weekly groceries]/attributes/category is \"44\""
|
| 44 |
+
},
|
| 45 |
+
{
|
| 46 |
+
"id": "rent-untouched",
|
| 47 |
+
"result": true,
|
| 48 |
+
"description": "Documents/household.xhb at /root/children/[name=ope][@wording=October rent]/attributes/amount is \"-1450\", within 0.001 of -1450"
|
| 49 |
+
}
|
| 50 |
+
]
|
| 51 |
+
}
|
| 52 |
+
}
|
| 53 |
+
},
|
| 54 |
+
{
|
| 55 |
+
"run": 2,
|
| 56 |
+
"verdict": "passed",
|
| 57 |
+
"turns": 43,
|
| 58 |
+
"usd": 1.47,
|
| 59 |
+
"checks": {
|
| 60 |
+
"record-grocery-expense": {
|
| 61 |
+
"score": 1.0,
|
| 62 |
+
"results": [
|
| 63 |
+
{
|
| 64 |
+
"id": "amount",
|
| 65 |
+
"result": true,
|
| 66 |
+
"description": "Documents/household.xhb at /root/children/[name=ope][@wording=Weekly groceries]/attributes/amount is \"-64.180000000000007\", within 0.001 of -64.18"
|
| 67 |
+
},
|
| 68 |
+
{
|
| 69 |
+
"id": "account",
|
| 70 |
+
"result": true,
|
| 71 |
+
"description": "Documents/household.xhb at /root/children/[name=ope][@wording=Weekly groceries]/attributes/account is \"1\""
|
| 72 |
+
},
|
| 73 |
+
{
|
| 74 |
+
"id": "date",
|
| 75 |
+
"result": true,
|
| 76 |
+
"description": "Documents/household.xhb at /root/children/[name=ope][@wording=Weekly groceries]/attributes/date is \"739924\""
|
| 77 |
+
},
|
| 78 |
+
{
|
| 79 |
+
"id": "payee",
|
| 80 |
+
"result": true,
|
| 81 |
+
"description": "Documents/household.xhb at /root/children/[name=ope][@wording=Weekly groceries]/attributes/payee is \"1\""
|
| 82 |
+
},
|
| 83 |
+
{
|
| 84 |
+
"id": "category",
|
| 85 |
+
"result": true,
|
| 86 |
+
"description": "Documents/household.xhb at /root/children/[name=ope][@wording=Weekly groceries]/attributes/category is \"44\""
|
| 87 |
+
},
|
| 88 |
+
{
|
| 89 |
+
"id": "rent-untouched",
|
| 90 |
+
"result": true,
|
| 91 |
+
"description": "Documents/household.xhb at /root/children/[name=ope][@wording=October rent]/attributes/amount is \"-1450\", within 0.001 of -1450"
|
| 92 |
+
}
|
| 93 |
+
]
|
| 94 |
+
}
|
| 95 |
+
}
|
| 96 |
+
}
|
| 97 |
+
]
|
| 98 |
+
}
|