mirror of
https://github.com/kuhyx/utils.git
synced 2026-11-28 08:09:16 +01:00
Compare commits
358 Commits
ts_config-
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 5ed2129215 | |||
| 2399227b4e | |||
| 320be81bda | |||
| 593283d240 | |||
| a41f3c6847 | |||
| f370d313b5 | |||
| 13949dfd65 | |||
| 2f7e87c10e | |||
| 6e5b5d1c3a | |||
| 783934a376 | |||
| 9b82aba9c8 | |||
| ad89ea9714 | |||
| 58b0bbeaf9 | |||
| e1b15a9449 | |||
| c06f2daa9a | |||
| 77827e9abb | |||
| 80f0ca13ca | |||
| 644d372625 | |||
| e5e457d8a9 | |||
| eddd1a38f8 | |||
| 41af578702 | |||
| 171a7f8ae3 | |||
| ceb6e42c27 | |||
| 14f0f47c56 | |||
| 7917d70b97 | |||
| abfb596d7c | |||
| 5c2effe7d1 | |||
| 77a190400e | |||
| b0ca506397 | |||
| b25933f975 | |||
| 2f8cf7d6e5 | |||
| 727d494883 | |||
| ab3531458c | |||
| 1aa2ef7e8f | |||
| bbb5f1b185 | |||
| 18e41c2eab | |||
| b5b85433fc | |||
| 299e3b6fc2 | |||
| e2fb7535dd | |||
| c439f54784 | |||
| b00455722d | |||
| adeb40f68e | |||
| 73b3698421 | |||
| 0d86c41ee7 | |||
| d5ddcb4d99 | |||
| 2352c17723 | |||
| 3fffb413b2 | |||
| 7252ba0a76 | |||
| 7c10ae734f | |||
| b8e2bf8813 | |||
| 44ed951630 | |||
| c394641272 | |||
| 96fedf6442 | |||
| 22e04baed7 | |||
| 0e22457246 | |||
| d696189a2e | |||
| 826f9946e8 | |||
| 50473d2d26 | |||
| 5e69f01472 | |||
| c6725351cd | |||
| 8e5ddf87b7 | |||
| f27d42ff66 | |||
| 7a3a96b9ac | |||
| e9e53341b3 | |||
| 5a225c7807 | |||
| 2e397d1ed5 | |||
| 8b54c1cada | |||
| c75f6310b0 | |||
| ebaa2e5d1e | |||
| f05845e2f7 | |||
| efa1c2ab05 | |||
| db58478669 | |||
| 0e2570d272 | |||
| 5435a7ff97 | |||
| 7eff63a3c4 | |||
| d729d732a1 | |||
| 7ec573a373 | |||
| d36826e2b5 | |||
| 073cc24468 | |||
| 15ef5b44f1 | |||
| bb2f92f459 | |||
| dc8a63beb2 | |||
| 48dc28ad97 | |||
| d0cfc2ca1f | |||
| 781b82863c | |||
| 422a5e53d9 | |||
| 3078d28fea | |||
| 6f4ca64218 | |||
| dfc5d07f52 | |||
| a22b412463 | |||
| 10e4656b04 | |||
| eb4bd14754 | |||
| 8ca05a6764 | |||
| 50781df0bc | |||
| 1ea7dfd6d5 | |||
| 62e7ff801e | |||
| da1d7c0692 | |||
| 6e3f86ef0d | |||
| dde5566b2c | |||
| b84a27eecf | |||
| f304eadc53 | |||
| f2150949a0 | |||
| 115e050110 | |||
| 905d13774a | |||
| 6d72a7c804 | |||
| 0d9974c194 | |||
| 44b80ee6cf | |||
| 1869fdee02 | |||
| 4531be3870 | |||
| db2650b9c9 | |||
| 65e72d8ded | |||
| 1194517702 | |||
| c29d0989dd | |||
| f21bfa7a5b | |||
| de9d41d6f0 | |||
| a9342e63e1 | |||
| 2cfbeb5e99 | |||
| 1962d30333 | |||
| 3174480624 | |||
| 3225af8365 | |||
| 6a40f7530b | |||
| edd0f7a788 | |||
| ba58ac41e9 | |||
| 90286f6cb2 | |||
| 9102c4b6ff | |||
| 47f2d239c4 | |||
| c8bb0808aa | |||
| e5990c9c15 | |||
| 84343aec2d | |||
| db1ce8c378 | |||
| 0ef5461805 | |||
| eb9bdc5796 | |||
| 307248b60b | |||
| 33791da6ff | |||
| eebeb0b510 | |||
| 2813a88db6 | |||
| cc09e56cd2 | |||
| 51e562a764 | |||
| b0fad2b2e5 | |||
| c83d41a594 | |||
| 2bbfbd9439 | |||
| 2d341dd41e | |||
| 3084080d74 | |||
| 9d6b17fd28 | |||
| ae56037e41 | |||
| eef7af4c86 | |||
| 9daa376254 | |||
| 17e300af0a | |||
| afcc1a47c7 | |||
| 0527bc680d | |||
| 21a0b5ce1c | |||
| 4c1ffd900b | |||
| 5a87868763 | |||
| fe4e34287a | |||
| 2f4f79bd6e | |||
| 51b747a364 | |||
| 89f464828a | |||
| eaf7282ac1 | |||
| 6641d85f05 | |||
| 46ab26fa15 | |||
| f71b0532fd | |||
| 3017bbf220 | |||
| fd81332f27 | |||
| ebedbf4b27 | |||
| d4fca83c9f | |||
| 3121639732 | |||
| 59b33949e4 | |||
| 027e67b197 | |||
| 8dfc4fb55f | |||
| 4fee294aa0 | |||
| 1a74345c40 | |||
| 71ea92f3c2 | |||
| 7f3f79f58d | |||
| 97d043d424 | |||
| 7af6afe51a | |||
| c2165e9fb8 | |||
| 26079c34c2 | |||
| 22fdf2c344 | |||
| de7d5d17eb | |||
| 640985a421 | |||
| 70c8aa8fbb | |||
| ba4dd58545 | |||
| b50e245ceb | |||
| 88e4be5042 | |||
| 737bf624ca | |||
| 716231a7f3 | |||
| 11cb1d81d9 | |||
| e0c9befdeb | |||
| 612b0b3c0a | |||
| f865508eb4 | |||
| 1fb04ce59d | |||
| 6f0070b353 | |||
| aec96eefd3 | |||
| 35569a6335 | |||
| a233268b66 | |||
| 20a825e249 | |||
| 2bbb428f2c | |||
| af3c98a50e | |||
| fd013abf67 | |||
| 0f332c9057 | |||
| 86b2621cd4 | |||
| fe1f4a22ab | |||
| db70ba204d | |||
| 5b36e84793 | |||
| ae29e67e28 | |||
| 4d75ce6d48 | |||
| 637428585c | |||
| c25ae4e0d1 | |||
| 98c013ea3f | |||
| 213537d0ef | |||
| 11c5b2e32b | |||
| c98da93339 | |||
| d45b1086c3 | |||
| 8398ca4823 | |||
| 087ed1c400 | |||
| e852e3ce48 | |||
| 6d80efb50a | |||
| cbcee98d94 | |||
| 82119bdd47 | |||
| d666e47e16 | |||
| 8a3076783e | |||
| 5d11f97093 | |||
| eb1c015315 | |||
| f99b77af89 | |||
| 1e96563522 | |||
| 28d3fb1361 | |||
| bce59127eb | |||
| 1bfacdf51f | |||
| c74815b8ab | |||
| dccfe14ae9 | |||
| 343f015c81 | |||
| decf5824e6 | |||
| 648bde44b1 | |||
| bbb7f0f0c0 | |||
| 4c417472ec | |||
| f9899b9c56 | |||
| 254c8ce240 | |||
| 5be9a22970 | |||
| 888e8ae57d | |||
| a27bbec59a | |||
| 1c9b47e35c | |||
| b3c9611af2 | |||
| def48e346b | |||
| a2e7334dfe | |||
| a4c7d29595 | |||
| 1b5515fd8b | |||
| 94518c8433 | |||
| ea5be2e879 | |||
| f93a24e283 | |||
| d0f928ae22 | |||
| 99f4e171e3 | |||
| 29ea6e2c50 | |||
| 2c926928dc | |||
| a78c1e971b | |||
| 2531f9eeb3 | |||
| f47ed80584 | |||
| 2a9732a312 | |||
| e06df74caf | |||
| 2d2d8a41f8 | |||
| 6343499ed1 | |||
| ebf7ca624e | |||
| c22b14389a | |||
| c0e902e5cc | |||
| 28c243d066 | |||
| 96a0d8af07 | |||
| b730cffaf4 | |||
| d1ca1e3d5b | |||
| 20b2cdbc04 | |||
| e74aa7b0ea | |||
| ea3f78b711 | |||
| cca7dd680f | |||
| 9980407095 | |||
| abc3ada6c3 | |||
| a0fb279b1b | |||
| 08a4010a16 | |||
| 9733a29a65 | |||
| 3afa269e2e | |||
| 00085a7de6 | |||
| 35f6f95956 | |||
| 2d97dc4b0e | |||
| 26c55675dd | |||
| eef2d46f32 | |||
| 49a401debd | |||
| 09a3a15d64 | |||
| f1378e97f1 | |||
| 2ec1c6e9b1 | |||
| 67f14588f7 | |||
| ef244889fd | |||
| d3f01c36e1 | |||
| 8b7105e20c | |||
| 7f2443ce48 | |||
| bd64b27109 | |||
| 0a51c9998d | |||
| 6f76ba7228 | |||
| c6838bc865 | |||
| 221c481644 | |||
| c490ba5992 | |||
| af8c6c78bf | |||
| 894d76f811 | |||
| ba34b603a1 | |||
| 0ecdc4e4be | |||
| e9bb43b8e8 | |||
| cd76eb0a95 | |||
| 21da7bcc90 | |||
| bce1f6d0cc | |||
| e376660ab0 | |||
| 6d96c58f01 | |||
| 3f7af48a2b | |||
| d5ba2360e4 | |||
| 96e52d6c2a | |||
| b164bf9592 | |||
| 62ff982956 | |||
| 0323f36f56 | |||
| d29c00d09d | |||
| 1b15430ad4 | |||
| cd2fb5ac12 | |||
| 7e3921ad66 | |||
| 5d8fe86d95 | |||
| 2d300815ea | |||
| fd6c772eaf | |||
| 6f4f739ed7 | |||
| a745d6bdf4 | |||
| 6bfee3312f | |||
| 32c8a54045 | |||
| 6641927dbe | |||
| 223b57eb87 | |||
| abda028b05 | |||
| df7330f015 | |||
| 7e453ae996 | |||
| e07c6a4606 | |||
| 957b4df642 | |||
| ac1aae4f7a | |||
| 4ccaba1bb3 | |||
| 4f7a7734ae | |||
| 5a8efc3f0a | |||
| 6c71d531bb | |||
| ba6f8b09fd | |||
| 60fba8a738 | |||
| 694c013b6b | |||
| aeac9caaa1 | |||
| 4bd6bce0df | |||
| 0af237af3d | |||
| d2376fcaa6 | |||
| 8ad5e75ab4 | |||
| a639416cf5 | |||
| eeac2c71c8 | |||
| 6a79b48214 | |||
| ff19b95aa7 | |||
| 1a8833eb9a | |||
| 3acf913b32 | |||
| 580d6e9727 | |||
| ba7ea0926f | |||
| 8f5cd3c5cd | |||
| 8cfa96d0ed | |||
| 6f8471196f | |||
| 64e7061084 | |||
| b28dfdeb60 | |||
| cb64e93b97 |
5
.claude/settings.json
Normal file
5
.claude/settings.json
Normal file
@ -0,0 +1,5 @@
|
||||
{
|
||||
"enabledPlugins": {
|
||||
"dart-flutter@dart-flutter": true
|
||||
}
|
||||
}
|
||||
2
.dep-freshness-no-workflow
Normal file
2
.dep-freshness-no-workflow
Normal file
@ -0,0 +1,2 @@
|
||||
# Dependency freshness runs locally only (pre-commit hook); no GitHub Actions
|
||||
# workflow. This marker stops the fleet installer from re-adding it.
|
||||
34
.github/workflows/app-errors-tests.yml
vendored
Normal file
34
.github/workflows/app-errors-tests.yml
vendored
Normal file
@ -0,0 +1,34 @@
|
||||
name: app_errors tests
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
# The workflow's own file counts as app_errors: editing only this file would
|
||||
# otherwise trigger nothing, so a fix to the job itself could never prove
|
||||
# itself.
|
||||
paths: ['app_errors/**', '.github/workflows/app-errors-tests.yml']
|
||||
pull_request:
|
||||
branches: [main]
|
||||
paths: ['app_errors/**', '.github/workflows/app-errors-tests.yml']
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: app_errors
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.x"
|
||||
cache: pip
|
||||
cache-dependency-path: app_errors/requirements.txt
|
||||
|
||||
- name: Install dependencies
|
||||
run: pip install --no-deps ../kuhy_credit && pip install -r requirements.txt && pip install --no-deps -e .
|
||||
|
||||
- name: Run tests
|
||||
run: python -m pytest -v
|
||||
21
.github/workflows/crdt-sync-dart-tests.yml
vendored
21
.github/workflows/crdt-sync-dart-tests.yml
vendored
@ -27,22 +27,5 @@ jobs:
|
||||
- name: Install dependencies
|
||||
run: dart pub get
|
||||
|
||||
- name: Analyze
|
||||
run: dart analyze --fatal-infos
|
||||
|
||||
- name: Run tests with coverage
|
||||
run: dart test --coverage=coverage
|
||||
|
||||
# Unlike `flutter test --coverage`, `dart test --coverage` emits raw VM
|
||||
# JSON and no lcov. Skipping this step leaves a stale lcov.info on disk
|
||||
# that the gate below happily "passes" -- which is exactly how this
|
||||
# package drifted to 96% while believing it was at 100%.
|
||||
- name: Convert coverage to lcov
|
||||
run: |
|
||||
dart pub global activate coverage
|
||||
dart pub global run coverage:format_coverage \
|
||||
--lcov --in=coverage/test --out=coverage/lcov.info \
|
||||
--report-on=lib --packages=.dart_tool/package_config.json
|
||||
|
||||
- name: Enforce 100% line coverage
|
||||
run: scripts/check_coverage.sh coverage/lcov.info 100
|
||||
- name: Run tests
|
||||
run: dart test
|
||||
|
||||
10
.github/workflows/crdt-sync-flutter-tests.yml
vendored
10
.github/workflows/crdt-sync-flutter-tests.yml
vendored
@ -26,11 +26,5 @@ jobs:
|
||||
- name: Install dependencies
|
||||
run: flutter pub get
|
||||
|
||||
- name: Analyze
|
||||
run: flutter analyze
|
||||
|
||||
- name: Run tests with coverage
|
||||
run: flutter test --coverage
|
||||
|
||||
- name: Enforce 100% line coverage
|
||||
run: scripts/check_coverage.sh coverage/lcov.info 100
|
||||
- name: Run tests
|
||||
run: flutter test
|
||||
|
||||
23
.github/workflows/crdt-sync-precommit.yml
vendored
23
.github/workflows/crdt-sync-precommit.yml
vendored
@ -16,10 +16,9 @@ jobs:
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.x"
|
||||
# Only pre-commit itself. Every linting hook runs in its own isolated
|
||||
# env -- ruff, mypy, pylint, bandit and codespell each come from their
|
||||
# own repo+rev, and the local hooks need nothing beyond bash and
|
||||
# python3 -- so installing the full requirements.txt spent 9s a run on
|
||||
# Only pre-commit itself. Every hook runs in its own isolated
|
||||
# env -- ruff-format comes from its own repo+rev, and the local hooks
|
||||
# need nothing beyond bash and python3 -- so installing the full requirements.txt spent 9s a run on
|
||||
# packages no pre-commit-stage hook imports. Verified by running all
|
||||
# three configs green in a venv holding pre-commit and nothing else.
|
||||
# The pin is read out of requirements.txt rather than repeated here, so
|
||||
@ -48,22 +47,6 @@ jobs:
|
||||
# than a wrong hook, and cache still re-saves under the new
|
||||
# exact key after a prefix-only hit.
|
||||
restore-keys: pre-commit-crdt-sync-${{ env.pythonLocation }}-
|
||||
# mypy re-analyses the stdlib and every third-party stub from scratch
|
||||
# without this, which measured 10s of the hook step in CI against 0.25s
|
||||
# warm locally -- a 19MB cache dir does the whole difference. Keyed on
|
||||
# the config, not the sources: mypy's own cache metadata records the
|
||||
# interpreter, the flag set and a hash per source file, so it re-checks
|
||||
# what changed and cannot pass stale code. Deliberately NOT keyed on
|
||||
# github.sha -- that re-saves 19MB x3 every commit and would evict the
|
||||
# 68MB hook caches under the repo's 10GB LRU budget. A fixed key keeps
|
||||
# the expensive part, the dependency analysis, which is what costs 10s.
|
||||
- uses: actions/cache@v4
|
||||
with:
|
||||
path: .mypy_cache
|
||||
key: >-
|
||||
mypy-crdt-sync-${{ env.pythonLocation }}-${{
|
||||
hashFiles('crdt-sync/.pre-commit-config.yaml') }}
|
||||
restore-keys: mypy-crdt-sync-${{ env.pythonLocation }}-
|
||||
- name: Run the hooks
|
||||
run: >-
|
||||
pre-commit run --config crdt-sync/.pre-commit-config.yaml
|
||||
|
||||
2
.github/workflows/crdt-sync-tests.yml
vendored
2
.github/workflows/crdt-sync-tests.yml
vendored
@ -27,5 +27,5 @@ jobs:
|
||||
- name: Install dependencies
|
||||
run: pip install -r requirements.txt
|
||||
|
||||
- name: Run tests with coverage
|
||||
- name: Run tests
|
||||
run: python -m pytest -v
|
||||
|
||||
30
.github/workflows/data-transfer-flutter-tests.yml
vendored
Normal file
30
.github/workflows/data-transfer-flutter-tests.yml
vendored
Normal file
@ -0,0 +1,30 @@
|
||||
name: data_transfer_flutter tests
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths: ['data_transfer_flutter/**']
|
||||
pull_request:
|
||||
branches: [main]
|
||||
paths: ['data_transfer_flutter/**']
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: data_transfer_flutter
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Flutter
|
||||
uses: subosito/flutter-action@v2
|
||||
with:
|
||||
channel: stable
|
||||
|
||||
- name: Install dependencies
|
||||
run: flutter pub get
|
||||
|
||||
- name: Run tests
|
||||
run: flutter test
|
||||
62
.github/workflows/dependency-freshness.yml
vendored
62
.github/workflows/dependency-freshness.yml
vendored
@ -1,62 +0,0 @@
|
||||
name: dependency freshness
|
||||
|
||||
# Every dependency on its ecosystem's newest STABLE release, enforced on push
|
||||
# as well as at commit time. The local pre-commit hook only sees the manifests
|
||||
# in a commit and can be skipped entirely by a fresh clone that never ran
|
||||
# `pre-commit install`; this runs `--all` over the whole repo.
|
||||
#
|
||||
# `--strict` is CI-only. Offline the gate degrades to its cached answer and
|
||||
# passes, because `--no-verify` is banned locally and a hook that hard-failed
|
||||
# on a flaky connection would leave no way to commit. A runner is always
|
||||
# online, so here an undeterminable answer is a real failure.
|
||||
#
|
||||
# Expect this to go red for reasons this repo's commit did not cause: an
|
||||
# upstream release overnight is enough. That is the chosen behaviour -- the
|
||||
# alternative is a gate that only notices staleness when someone remembers to
|
||||
# look.
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
dependency-freshness:
|
||||
name: dependencies on newest stable
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
# The gate lives in the shared utils repo so every repo resolves the
|
||||
# same "latest stable" the same way. Checking it out beats vendoring a
|
||||
# copy, which is exactly how a gate and its survey start disagreeing.
|
||||
- name: Check out the shared gate
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
repository: kuhyx/utils
|
||||
path: .utils
|
||||
|
||||
# "3.x", never a pinned minor: the Python target IS the interpreter the
|
||||
# gate runs under (registries/toolchain.python_installed), so a runner
|
||||
# held a release behind this machine reports a repo's `requires-python`
|
||||
# as excluding "latest" while the same check passes locally. flax-docs-mcp
|
||||
# hit exactly that -- `>=3.14` green here, red on a 3.13 runner.
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.x"
|
||||
|
||||
- name: Install the gate's two runtime dependencies
|
||||
run: python -m pip install --upgrade pyyaml packaging
|
||||
|
||||
- name: Cache registry lookups
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.cache/dep-freshness
|
||||
key: dep-freshness-${{ hashFiles('**/pubspec.yaml', '**/pyproject.toml',
|
||||
'**/requirements*.txt', '**/package.json', '**/Cargo.toml', '**/go.mod') }}
|
||||
restore-keys: dep-freshness-
|
||||
|
||||
- name: Every dependency is on newest stable
|
||||
run: bash .utils/scripts/check_dependency_freshness.sh --all --strict
|
||||
10
.github/workflows/design-system-tests.yml
vendored
10
.github/workflows/design-system-tests.yml
vendored
@ -26,11 +26,5 @@ jobs:
|
||||
- name: Install dependencies
|
||||
run: flutter pub get
|
||||
|
||||
- name: Analyze
|
||||
run: flutter analyze
|
||||
|
||||
- name: Run tests with coverage
|
||||
run: flutter test --coverage
|
||||
|
||||
- name: Enforce 100% line coverage
|
||||
run: scripts/check_coverage.sh coverage/lcov.info 100
|
||||
- name: Run tests
|
||||
run: flutter test
|
||||
|
||||
56
.github/workflows/earned-time-precommit.yml
vendored
Normal file
56
.github/workflows/earned-time-precommit.yml
vendored
Normal file
@ -0,0 +1,56 @@
|
||||
name: earned_time pre-commit
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
# The workflow's own file counts as earned_time: editing only this file would
|
||||
# otherwise trigger nothing, so a fix to the job itself could never prove
|
||||
# itself.
|
||||
paths: ['earned_time/**', '.github/workflows/earned-time-precommit.yml']
|
||||
pull_request:
|
||||
branches: [main]
|
||||
paths: ['earned_time/**', '.github/workflows/earned-time-precommit.yml']
|
||||
|
||||
jobs:
|
||||
pre-commit:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.x"
|
||||
# Only pre-commit itself. Every hook runs in its own isolated
|
||||
# env -- ruff-format comes from its own repo+rev, and the local hooks
|
||||
# need nothing beyond bash and python3 -- so installing the full requirements.txt spent 9s a run on
|
||||
# packages no pre-commit-stage hook imports. Verified by running all
|
||||
# three configs green in a venv holding pre-commit and nothing else.
|
||||
# The pin is read out of requirements.txt rather than repeated here, so
|
||||
# it cannot drift from what the dependency-freshness gate governs.
|
||||
- name: Install pre-commit
|
||||
run: |
|
||||
pip install "$(grep '^pre-commit==' earned_time/requirements.txt)"
|
||||
|
||||
# Keyed on THIS package's config. pre-commit/action@v3.0.1 caches on
|
||||
# hashFiles('.pre-commit-config.yaml') -- the repo ROOT's -- so all three
|
||||
# package jobs shared one key, raced to overwrite it with hook sets built
|
||||
# from four different configs, and editing a per-package config did not
|
||||
# invalidate it. The cache was therefore silently wrong rather than
|
||||
# missing, and the hooks reinstalled from scratch on every run (38-49s).
|
||||
- uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.cache/pre-commit
|
||||
key: >-
|
||||
pre-commit-earned_time-${{ env.pythonLocation }}-${{
|
||||
hashFiles('earned_time/.pre-commit-config.yaml') }}
|
||||
# Prefix fallback, or this fix would evaporate on the very
|
||||
# event that motivated it: bumping a hook rev changes the
|
||||
# exact key, and a total miss means reinstalling every hook
|
||||
# again. pre-commit's store is keyed internally by hook
|
||||
# repo+rev, so a superseded entry is ignored disk rather
|
||||
# than a wrong hook, and cache still re-saves under the new
|
||||
# exact key after a prefix-only hit.
|
||||
restore-keys: pre-commit-earned_time-${{ env.pythonLocation }}-
|
||||
- name: Run the hooks
|
||||
run: >-
|
||||
pre-commit run --config earned_time/.pre-commit-config.yaml
|
||||
--all-files --show-diff-on-failure
|
||||
36
.github/workflows/earned-time-tests.yml
vendored
Normal file
36
.github/workflows/earned-time-tests.yml
vendored
Normal file
@ -0,0 +1,36 @@
|
||||
name: earned_time tests
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
# The workflow's own file counts as earned_time: editing only this file would
|
||||
# otherwise trigger nothing, so a fix to the job itself could never prove
|
||||
# itself.
|
||||
paths: ['earned_time/**', '.github/workflows/earned-time-tests.yml']
|
||||
pull_request:
|
||||
branches: [main]
|
||||
paths: ['earned_time/**', '.github/workflows/earned-time-tests.yml']
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: earned_time
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.x"
|
||||
cache: pip
|
||||
cache-dependency-path: earned_time/requirements.txt
|
||||
|
||||
- name: Install dependencies
|
||||
run: pip install -r requirements.txt && pip install --no-deps -e .
|
||||
|
||||
# No display needed: earned_time is stdlib-only policy, imported
|
||||
# headless by the root gaming daemon.
|
||||
- name: Run tests
|
||||
run: python -m pytest -v
|
||||
34
.github/workflows/file-length.yml
vendored
34
.github/workflows/file-length.yml
vendored
@ -1,34 +0,0 @@
|
||||
name: file length
|
||||
|
||||
# The 250-line cap, enforced on push as well as in pre-commit
|
||||
# (refactor_claude_todo.md, "make it permanent").
|
||||
#
|
||||
# Unlike the pre-commit hook, which only sees the files in a commit, this runs
|
||||
# over the whole tree: the hook keeps a violation from being *introduced*, and
|
||||
# this keeps one from surviving a path the hook never saw (a merge, a push
|
||||
# from a machine without hooks installed, a rebase that resurrects a file).
|
||||
#
|
||||
# No paths filter on purpose. The cap applies to every file in the repo, so
|
||||
# scoping this job to a subdirectory would be the one way to reintroduce the
|
||||
# problem it exists to catch.
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
branches: [main]
|
||||
|
||||
jobs:
|
||||
file-length:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.x"
|
||||
|
||||
- name: Every file is at most 250 lines
|
||||
run: bash scripts/check_file_length.sh --all
|
||||
56
.github/workflows/focus-project-precommit.yml
vendored
Normal file
56
.github/workflows/focus-project-precommit.yml
vendored
Normal file
@ -0,0 +1,56 @@
|
||||
name: focus-project pre-commit
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
# The workflow's own file counts as focus_project: editing only this file would
|
||||
# otherwise trigger nothing, so a fix to the job itself could never prove
|
||||
# itself.
|
||||
paths: ['focus_project/**', '.github/workflows/focus-project-precommit.yml']
|
||||
pull_request:
|
||||
branches: [main]
|
||||
paths: ['focus_project/**', '.github/workflows/focus-project-precommit.yml']
|
||||
|
||||
jobs:
|
||||
pre-commit:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.x"
|
||||
# Only pre-commit itself. Every hook runs in its own isolated
|
||||
# env -- ruff-format comes from its own repo+rev, and the local hooks
|
||||
# need nothing beyond bash and python3 -- so installing the full requirements.txt spent 9s a run on
|
||||
# packages no pre-commit-stage hook imports. Verified by running all
|
||||
# three configs green in a venv holding pre-commit and nothing else.
|
||||
# The pin is read out of requirements.txt rather than repeated here, so
|
||||
# it cannot drift from what the dependency-freshness gate governs.
|
||||
- name: Install pre-commit
|
||||
run: |
|
||||
pip install "$(grep '^pre-commit==' focus_project/requirements.txt)"
|
||||
|
||||
# Keyed on THIS package's config. pre-commit/action@v3.0.1 caches on
|
||||
# hashFiles('.pre-commit-config.yaml') -- the repo ROOT's -- so all three
|
||||
# package jobs shared one key, raced to overwrite it with hook sets built
|
||||
# from four different configs, and editing a per-package config did not
|
||||
# invalidate it. The cache was therefore silently wrong rather than
|
||||
# missing, and the hooks reinstalled from scratch on every run (38-49s).
|
||||
- uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.cache/pre-commit
|
||||
key: >-
|
||||
pre-commit-focus-project-${{ env.pythonLocation }}-${{
|
||||
hashFiles('focus_project/.pre-commit-config.yaml') }}
|
||||
# Prefix fallback, or this fix would evaporate on the very
|
||||
# event that motivated it: bumping a hook rev changes the
|
||||
# exact key, and a total miss means reinstalling every hook
|
||||
# again. pre-commit's store is keyed internally by hook
|
||||
# repo+rev, so a superseded entry is ignored disk rather
|
||||
# than a wrong hook, and cache still re-saves under the new
|
||||
# exact key after a prefix-only hit.
|
||||
restore-keys: pre-commit-focus-project-${{ env.pythonLocation }}-
|
||||
- name: Run the hooks
|
||||
run: >-
|
||||
pre-commit run --config focus_project/.pre-commit-config.yaml
|
||||
--all-files --show-diff-on-failure
|
||||
34
.github/workflows/focus-project-tests.yml
vendored
Normal file
34
.github/workflows/focus-project-tests.yml
vendored
Normal file
@ -0,0 +1,34 @@
|
||||
name: focus-project tests
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
# The workflow's own file counts as focus_project: editing only this file would
|
||||
# otherwise trigger nothing, so a fix to the job itself could never prove
|
||||
# itself.
|
||||
paths: ['focus_project/**', '.github/workflows/focus-project-tests.yml']
|
||||
pull_request:
|
||||
branches: [main]
|
||||
paths: ['focus_project/**', '.github/workflows/focus-project-tests.yml']
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: focus_project
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.x"
|
||||
cache: pip
|
||||
cache-dependency-path: focus_project/requirements.txt
|
||||
|
||||
- name: Install dependencies
|
||||
run: pip install -r requirements.txt && pip install --no-deps -e .
|
||||
|
||||
- name: Run tests
|
||||
run: python -m pytest -v
|
||||
23
.github/workflows/freedays-precommit.yml
vendored
23
.github/workflows/freedays-precommit.yml
vendored
@ -19,10 +19,9 @@ jobs:
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.x"
|
||||
# Only pre-commit itself. Every linting hook runs in its own isolated
|
||||
# env -- ruff, mypy, pylint, bandit and codespell each come from their
|
||||
# own repo+rev, and the local hooks need nothing beyond bash and
|
||||
# python3 -- so installing the full requirements.txt spent 9s a run on
|
||||
# Only pre-commit itself. Every hook runs in its own isolated
|
||||
# env -- ruff-format comes from its own repo+rev, and the local hooks
|
||||
# need nothing beyond bash and python3 -- so installing the full requirements.txt spent 9s a run on
|
||||
# packages no pre-commit-stage hook imports. Verified by running all
|
||||
# three configs green in a venv holding pre-commit and nothing else.
|
||||
# The pin is read out of requirements.txt rather than repeated here, so
|
||||
@ -51,22 +50,6 @@ jobs:
|
||||
# than a wrong hook, and cache still re-saves under the new
|
||||
# exact key after a prefix-only hit.
|
||||
restore-keys: pre-commit-freedays-${{ env.pythonLocation }}-
|
||||
# mypy re-analyses the stdlib and every third-party stub from scratch
|
||||
# without this, which measured 10s of the hook step in CI against 0.25s
|
||||
# warm locally -- a 19MB cache dir does the whole difference. Keyed on
|
||||
# the config, not the sources: mypy's own cache metadata records the
|
||||
# interpreter, the flag set and a hash per source file, so it re-checks
|
||||
# what changed and cannot pass stale code. Deliberately NOT keyed on
|
||||
# github.sha -- that re-saves 19MB x3 every commit and would evict the
|
||||
# 68MB hook caches under the repo's 10GB LRU budget. A fixed key keeps
|
||||
# the expensive part, the dependency analysis, which is what costs 10s.
|
||||
- uses: actions/cache@v4
|
||||
with:
|
||||
path: .mypy_cache
|
||||
key: >-
|
||||
mypy-freedays-${{ env.pythonLocation }}-${{
|
||||
hashFiles('freedays/.pre-commit-config.yaml') }}
|
||||
restore-keys: mypy-freedays-${{ env.pythonLocation }}-
|
||||
- name: Run the hooks
|
||||
run: >-
|
||||
pre-commit run --config freedays/.pre-commit-config.yaml
|
||||
|
||||
4
.github/workflows/freedays-tests.yml
vendored
4
.github/workflows/freedays-tests.yml
vendored
@ -36,9 +36,9 @@ jobs:
|
||||
run: pip install ../crdt-sync
|
||||
|
||||
- name: Install dependencies
|
||||
run: pip install -r requirements.txt && pip install --no-deps -e .
|
||||
run: pip install --no-deps ../kuhy_credit && pip install -r requirements.txt && pip install --no-deps -e .
|
||||
|
||||
# No display needed: freedays draws nothing. It is policy, a JSON file
|
||||
# and a CLI.
|
||||
- name: Run tests with coverage
|
||||
- name: Run tests
|
||||
run: python -m pytest -v
|
||||
|
||||
54
.github/workflows/game-recording-precommit.yml
vendored
Normal file
54
.github/workflows/game-recording-precommit.yml
vendored
Normal file
@ -0,0 +1,54 @@
|
||||
name: game_recording pre-commit
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
# The workflow's own file counts as game_recording: editing only this file used
|
||||
# to trigger nothing, so a fix to the job itself could never prove itself.
|
||||
paths: ['game_recording/**', '.github/workflows/game-recording-precommit.yml']
|
||||
pull_request:
|
||||
branches: [main]
|
||||
paths: ['game_recording/**', '.github/workflows/game-recording-precommit.yml']
|
||||
|
||||
jobs:
|
||||
pre-commit:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.x"
|
||||
# Only pre-commit itself. Every hook runs in its own isolated
|
||||
# env -- ruff-format comes from its own repo+rev, and the local hooks
|
||||
# need nothing beyond bash and python3 -- so installing the full requirements.txt spent 9s a run on
|
||||
# packages no pre-commit-stage hook imports. Verified by running this
|
||||
# package's config green in a venv holding pre-commit and nothing else.
|
||||
# The pin is read out of requirements.txt rather than repeated here, so
|
||||
# it cannot drift from what the dependency-freshness gate governs.
|
||||
- name: Install pre-commit
|
||||
run: |
|
||||
pip install "$(grep '^pre-commit==' game_recording/requirements.txt)"
|
||||
|
||||
# Keyed on THIS package's config. pre-commit/action@v3.0.1 caches on
|
||||
# hashFiles('.pre-commit-config.yaml') -- the repo ROOT's -- so editing
|
||||
# this package's config would not invalidate it, and other jobs in the
|
||||
# repo that cache hooks under that key could overwrite it with a
|
||||
# different hook set. A key from this config cannot go stale that way.
|
||||
- uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.cache/pre-commit
|
||||
key: >-
|
||||
pre-commit-game-recording-${{ env.pythonLocation }}-${{
|
||||
hashFiles('game_recording/.pre-commit-config.yaml') }}
|
||||
# Prefix fallback, or this fix would evaporate on the very
|
||||
# event that motivated it: bumping a hook rev changes the
|
||||
# exact key, and a total miss means reinstalling every hook
|
||||
# again. pre-commit's store is keyed internally by hook
|
||||
# repo+rev, so a superseded entry is ignored disk rather
|
||||
# than a wrong hook, and cache still re-saves under the new
|
||||
# exact key after a prefix-only hit.
|
||||
restore-keys: pre-commit-game-recording-${{ env.pythonLocation }}-
|
||||
- name: Run the hooks
|
||||
run: >-
|
||||
pre-commit run --config game_recording/.pre-commit-config.yaml
|
||||
--all-files --show-diff-on-failure
|
||||
35
.github/workflows/game-recording-tests.yml
vendored
Normal file
35
.github/workflows/game-recording-tests.yml
vendored
Normal file
@ -0,0 +1,35 @@
|
||||
name: game_recording tests
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
# The workflow's own file counts as game_recording: editing only this file used
|
||||
# to trigger nothing, so a fix to the job itself could never prove itself.
|
||||
paths: ['game_recording/**', '.github/workflows/game-recording-tests.yml']
|
||||
pull_request:
|
||||
branches: [main]
|
||||
paths: ['game_recording/**', '.github/workflows/game-recording-tests.yml']
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: game_recording
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.x"
|
||||
|
||||
# The finalize and library tests run the real ffmpeg and ffprobe.
|
||||
- name: Install ffmpeg
|
||||
run: sudo apt-get update && sudo apt-get install -y ffmpeg
|
||||
|
||||
- name: Install dependencies
|
||||
run: pip install -r requirements.txt
|
||||
|
||||
- name: Run tests
|
||||
run: python -m pytest -v
|
||||
23
.github/workflows/gatelock-precommit.yml
vendored
23
.github/workflows/gatelock-precommit.yml
vendored
@ -18,10 +18,9 @@ jobs:
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.x"
|
||||
# Only pre-commit itself. Every linting hook runs in its own isolated
|
||||
# env -- ruff, mypy, pylint, bandit and codespell each come from their
|
||||
# own repo+rev, and the local hooks need nothing beyond bash and
|
||||
# python3 -- so installing the full requirements.txt spent 9s a run on
|
||||
# Only pre-commit itself. Every hook runs in its own isolated
|
||||
# env -- ruff-format comes from its own repo+rev, and the local hooks
|
||||
# need nothing beyond bash and python3 -- so installing the full requirements.txt spent 9s a run on
|
||||
# packages no pre-commit-stage hook imports. Verified by running all
|
||||
# three configs green in a venv holding pre-commit and nothing else.
|
||||
# The pin is read out of requirements.txt rather than repeated here, so
|
||||
@ -50,22 +49,6 @@ jobs:
|
||||
# than a wrong hook, and cache still re-saves under the new
|
||||
# exact key after a prefix-only hit.
|
||||
restore-keys: pre-commit-gatelock-${{ env.pythonLocation }}-
|
||||
# mypy re-analyses the stdlib and every third-party stub from scratch
|
||||
# without this, which measured 10s of the hook step in CI against 0.25s
|
||||
# warm locally -- a 19MB cache dir does the whole difference. Keyed on
|
||||
# the config, not the sources: mypy's own cache metadata records the
|
||||
# interpreter, the flag set and a hash per source file, so it re-checks
|
||||
# what changed and cannot pass stale code. Deliberately NOT keyed on
|
||||
# github.sha -- that re-saves 19MB x3 every commit and would evict the
|
||||
# 68MB hook caches under the repo's 10GB LRU budget. A fixed key keeps
|
||||
# the expensive part, the dependency analysis, which is what costs 10s.
|
||||
- uses: actions/cache@v4
|
||||
with:
|
||||
path: .mypy_cache
|
||||
key: >-
|
||||
mypy-gatelock-${{ env.pythonLocation }}-${{
|
||||
hashFiles('gatelock/.pre-commit-config.yaml') }}
|
||||
restore-keys: mypy-gatelock-${{ env.pythonLocation }}-
|
||||
- name: Run the hooks
|
||||
run: >-
|
||||
pre-commit run --config gatelock/.pre-commit-config.yaml
|
||||
|
||||
14
.github/workflows/gatelock-tests.yml
vendored
14
.github/workflows/gatelock-tests.yml
vendored
@ -5,10 +5,10 @@ on:
|
||||
branches: [main]
|
||||
# The workflow's own file counts as gatelock: editing only this file used
|
||||
# to trigger nothing, so a fix to the job itself could never prove itself.
|
||||
paths: ['gatelock/**', '.github/workflows/gatelock-tests.yml']
|
||||
paths: ['gatelock/**', 'earned_time/**', 'freedays/**', 'sickdays/**', '.github/workflows/gatelock-tests.yml']
|
||||
pull_request:
|
||||
branches: [main]
|
||||
paths: ['gatelock/**', '.github/workflows/gatelock-tests.yml']
|
||||
paths: ['gatelock/**', 'earned_time/**', 'freedays/**', 'sickdays/**', '.github/workflows/gatelock-tests.yml']
|
||||
|
||||
jobs:
|
||||
test:
|
||||
@ -26,6 +26,14 @@ jobs:
|
||||
cache: pip
|
||||
cache-dependency-path: gatelock/requirements.txt
|
||||
|
||||
# The evening chain (gatelock.evening_chain) reads earned_time, freedays
|
||||
# and sickdays; they are siblings in this repo, so CI installs the
|
||||
# checkout, not a tag.
|
||||
- name: Install the sibling packages
|
||||
run: >-
|
||||
pip install ../crdt-sync ../earned_time
|
||||
&& pip install --no-deps ../freedays ../sickdays
|
||||
|
||||
- name: Install dependencies
|
||||
run: pip install -r requirements.txt
|
||||
|
||||
@ -37,5 +45,5 @@ jobs:
|
||||
- name: Install a virtual X display
|
||||
run: sudo apt-get update && sudo apt-get install -y xvfb
|
||||
|
||||
- name: Run tests with coverage
|
||||
- name: Run tests
|
||||
run: xvfb-run -a -s "-screen 0 1600x1200x24" python -m pytest -v
|
||||
|
||||
10
.github/workflows/github-device-auth-tests.yml
vendored
10
.github/workflows/github-device-auth-tests.yml
vendored
@ -26,11 +26,5 @@ jobs:
|
||||
- name: Install dependencies
|
||||
run: flutter pub get
|
||||
|
||||
- name: Analyze
|
||||
run: flutter analyze
|
||||
|
||||
- name: Run tests with coverage
|
||||
run: flutter test --coverage
|
||||
|
||||
- name: Enforce 100% line coverage
|
||||
run: scripts/check_coverage.sh coverage/lcov.info 100
|
||||
- name: Run tests
|
||||
run: flutter test
|
||||
|
||||
32
.github/workflows/godot-dev-tools-tests.yml
vendored
Normal file
32
.github/workflows/godot-dev-tools-tests.yml
vendored
Normal file
@ -0,0 +1,32 @@
|
||||
name: godot_dev_tools tests
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths: ['godot_dev_tools/**', '.github/workflows/godot-dev-tools-tests.yml']
|
||||
pull_request:
|
||||
branches: [main]
|
||||
paths: ['godot_dev_tools/**', '.github/workflows/godot-dev-tools-tests.yml']
|
||||
|
||||
env:
|
||||
GODOT_VERSION: "4.7.2"
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-python@v5
|
||||
with: { python-version: "3.15.2" }
|
||||
|
||||
- name: Install Godot
|
||||
run: |
|
||||
curl -fsSL -o godot.zip "https://github.com/godotengine/godot/releases/download/${GODOT_VERSION}-stable/Godot_v${GODOT_VERSION}-stable_linux.x86_64.zip"
|
||||
unzip -q godot.zip
|
||||
chmod +x "Godot_v${GODOT_VERSION}-stable_linux.x86_64"
|
||||
sudo mv "Godot_v${GODOT_VERSION}-stable_linux.x86_64" /usr/local/bin/godot
|
||||
rm godot.zip
|
||||
|
||||
- name: GUT against the stub host (GUT is fetched at its pinned tag)
|
||||
run: godot_dev_tools/test.sh
|
||||
30
.github/workflows/google-account-token-tests.yml
vendored
Normal file
30
.github/workflows/google-account-token-tests.yml
vendored
Normal file
@ -0,0 +1,30 @@
|
||||
name: google_account_token tests
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths: ['google_account_token/**']
|
||||
pull_request:
|
||||
branches: [main]
|
||||
paths: ['google_account_token/**']
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: google_account_token
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Flutter
|
||||
uses: subosito/flutter-action@v2
|
||||
with:
|
||||
channel: stable
|
||||
|
||||
- name: Install dependencies
|
||||
run: flutter pub get
|
||||
|
||||
- name: Run tests
|
||||
run: flutter test
|
||||
56
.github/workflows/holds-precommit.yml
vendored
Normal file
56
.github/workflows/holds-precommit.yml
vendored
Normal file
@ -0,0 +1,56 @@
|
||||
name: holds pre-commit
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
# The workflow's own file counts as holds: editing only this file would
|
||||
# otherwise trigger nothing, so a fix to the job itself could never prove
|
||||
# itself.
|
||||
paths: ['holds/**', '.github/workflows/holds-precommit.yml']
|
||||
pull_request:
|
||||
branches: [main]
|
||||
paths: ['holds/**', '.github/workflows/holds-precommit.yml']
|
||||
|
||||
jobs:
|
||||
pre-commit:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.x"
|
||||
# Only pre-commit itself. Every hook runs in its own isolated
|
||||
# env -- ruff-format comes from its own repo+rev, and the local hooks
|
||||
# need nothing beyond bash and python3 -- so installing the full requirements.txt spent 9s a run on
|
||||
# packages no pre-commit-stage hook imports. Verified by running all
|
||||
# three configs green in a venv holding pre-commit and nothing else.
|
||||
# The pin is read out of requirements.txt rather than repeated here, so
|
||||
# it cannot drift from what the dependency-freshness gate governs.
|
||||
- name: Install pre-commit
|
||||
run: |
|
||||
pip install "$(grep '^pre-commit==' holds/requirements.txt)"
|
||||
|
||||
# Keyed on THIS package's config. pre-commit/action@v3.0.1 caches on
|
||||
# hashFiles('.pre-commit-config.yaml') -- the repo ROOT's -- so all three
|
||||
# package jobs shared one key, raced to overwrite it with hook sets built
|
||||
# from four different configs, and editing a per-package config did not
|
||||
# invalidate it. The cache was therefore silently wrong rather than
|
||||
# missing, and the hooks reinstalled from scratch on every run (38-49s).
|
||||
- uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.cache/pre-commit
|
||||
key: >-
|
||||
pre-commit-holds-${{ env.pythonLocation }}-${{
|
||||
hashFiles('holds/.pre-commit-config.yaml') }}
|
||||
# Prefix fallback, or this fix would evaporate on the very
|
||||
# event that motivated it: bumping a hook rev changes the
|
||||
# exact key, and a total miss means reinstalling every hook
|
||||
# again. pre-commit's store is keyed internally by hook
|
||||
# repo+rev, so a superseded entry is ignored disk rather
|
||||
# than a wrong hook, and cache still re-saves under the new
|
||||
# exact key after a prefix-only hit.
|
||||
restore-keys: pre-commit-holds-${{ env.pythonLocation }}-
|
||||
- name: Run the hooks
|
||||
run: >-
|
||||
pre-commit run --config holds/.pre-commit-config.yaml
|
||||
--all-files --show-diff-on-failure
|
||||
34
.github/workflows/holds-tests.yml
vendored
Normal file
34
.github/workflows/holds-tests.yml
vendored
Normal file
@ -0,0 +1,34 @@
|
||||
name: holds tests
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
# The workflow's own file counts as holds: editing only this file would
|
||||
# otherwise trigger nothing, so a fix to the job itself could never prove
|
||||
# itself.
|
||||
paths: ['holds/**', '.github/workflows/holds-tests.yml']
|
||||
pull_request:
|
||||
branches: [main]
|
||||
paths: ['holds/**', '.github/workflows/holds-tests.yml']
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: holds
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.x"
|
||||
cache: pip
|
||||
cache-dependency-path: holds/requirements.txt
|
||||
|
||||
- name: Install dependencies
|
||||
run: pip install -r requirements.txt && pip install --no-deps -e .
|
||||
|
||||
- name: Run tests
|
||||
run: python -m pytest -v
|
||||
22
.github/workflows/kuhy-credit-drift.yml
vendored
Normal file
22
.github/workflows/kuhy-credit-drift.yml
vendored
Normal file
@ -0,0 +1,22 @@
|
||||
name: kuhy_credit drift
|
||||
|
||||
# Not path-filtered, like palette-drift: the sources live outside kuhy_credit/
|
||||
# (the M1 art, web_ui's tokens.css), so an edit there must be able to fail it.
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
branches: [main]
|
||||
|
||||
jobs:
|
||||
drift:
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: kuhy_credit
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
with: { python-version: "3.15.2" }
|
||||
- name: Every stack's generated file matches credit.json, the art and the tokens
|
||||
run: python3 -m generator.generate --check
|
||||
91
.github/workflows/kuhy-credit-tests.yml
vendored
Normal file
91
.github/workflows/kuhy-credit-tests.yml
vendored
Normal file
@ -0,0 +1,91 @@
|
||||
name: kuhy_credit tests
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths: ['kuhy_credit/**', 'flutter_web_drive/**', '.github/workflows/kuhy-credit-tests.yml']
|
||||
pull_request:
|
||||
branches: [main]
|
||||
paths: ['kuhy_credit/**', 'flutter_web_drive/**', '.github/workflows/kuhy-credit-tests.yml']
|
||||
|
||||
env:
|
||||
GODOT_VERSION: "4.7.2"
|
||||
|
||||
jobs:
|
||||
python:
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: kuhy_credit
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
with: { python-version: "3.15.2" }
|
||||
- name: Install the package, pytest and a virtual X display
|
||||
run: |
|
||||
sudo apt-get update && sudo apt-get install -y xvfb python3-tk \
|
||||
texlive-latex-base texlive-latex-recommended texlive-pictures
|
||||
pip install -r requirements-dev.txt && pip install --no-deps -e .
|
||||
- name: Tests, Tk E2E and the drift check
|
||||
run: xvfb-run -a -s "-screen 0 1600x1200x24" python -m pytest -q
|
||||
|
||||
web:
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: kuhy_credit/web
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v4
|
||||
with: { version: 12 }
|
||||
- uses: actions/setup-node@v4
|
||||
with: { node-version: "26.13.1" }
|
||||
- uses: actions/setup-python@v5
|
||||
with: { python-version: "3.15.2" }
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- name: Unit tests
|
||||
run: pnpm test
|
||||
- name: E2E in headless Chrome (window.open stubbed)
|
||||
working-directory: .
|
||||
env: { CHROMIUM: google-chrome }
|
||||
run: |
|
||||
pip install -r flutter_web_drive/requirements.txt
|
||||
python3 kuhy_credit/e2e/web_e2e.py
|
||||
|
||||
flutter:
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: kuhy_credit/flutter
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: subosito/flutter-action@v2
|
||||
with: { channel: stable }
|
||||
- uses: actions/setup-python@v5
|
||||
with: { python-version: "3.15.2" }
|
||||
- run: flutter pub get
|
||||
- name: Widget tests
|
||||
run: flutter test
|
||||
- name: Example web build + E2E in headless Chrome (window.open stubbed)
|
||||
env: { CHROMIUM: google-chrome }
|
||||
run: |
|
||||
(cd example && flutter pub get && flutter build web --release)
|
||||
pip install -r ../../flutter_web_drive/requirements.txt
|
||||
python3 ../e2e/flutter_web_e2e.py
|
||||
|
||||
godot:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
with: { python-version: "3.15.2" }
|
||||
- name: Install Godot
|
||||
run: |
|
||||
curl -fsSL -o godot.zip "https://github.com/godotengine/godot/releases/download/${GODOT_VERSION}-stable/Godot_v${GODOT_VERSION}-stable_linux.x86_64.zip"
|
||||
unzip -q godot.zip
|
||||
chmod +x "Godot_v${GODOT_VERSION}-stable_linux.x86_64"
|
||||
sudo mv "Godot_v${GODOT_VERSION}-stable_linux.x86_64" /usr/local/bin/godot
|
||||
rm godot.zip
|
||||
- name: GUT unit tests + demo E2E (GUT fetched at its pinned tag)
|
||||
env: { KUHY_CREDIT_GODOT_TIMEOUT: "50" }
|
||||
run: kuhy_credit/godot/test.sh
|
||||
56
.github/workflows/leetcode-coach-precommit.yml
vendored
Normal file
56
.github/workflows/leetcode-coach-precommit.yml
vendored
Normal file
@ -0,0 +1,56 @@
|
||||
name: leetcode-coach pre-commit
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
# The workflow's own file counts as leetcode_coach: editing only this file would
|
||||
# otherwise trigger nothing, so a fix to the job itself could never prove
|
||||
# itself.
|
||||
paths: ['leetcode_coach/**', '.github/workflows/leetcode-coach-precommit.yml']
|
||||
pull_request:
|
||||
branches: [main]
|
||||
paths: ['leetcode_coach/**', '.github/workflows/leetcode-coach-precommit.yml']
|
||||
|
||||
jobs:
|
||||
pre-commit:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.x"
|
||||
# Only pre-commit itself. Every hook runs in its own isolated
|
||||
# env -- ruff-format comes from its own repo+rev, and the local hooks
|
||||
# need nothing beyond bash and python3 -- so installing the full requirements.txt spent 9s a run on
|
||||
# packages no pre-commit-stage hook imports. Verified by running all
|
||||
# three configs green in a venv holding pre-commit and nothing else.
|
||||
# The pin is read out of requirements.txt rather than repeated here, so
|
||||
# it cannot drift from what the dependency-freshness gate governs.
|
||||
- name: Install pre-commit
|
||||
run: |
|
||||
pip install "$(grep '^pre-commit==' leetcode_coach/requirements.txt)"
|
||||
|
||||
# Keyed on THIS package's config. pre-commit/action@v3.0.1 caches on
|
||||
# hashFiles('.pre-commit-config.yaml') -- the repo ROOT's -- so all three
|
||||
# package jobs shared one key, raced to overwrite it with hook sets built
|
||||
# from four different configs, and editing a per-package config did not
|
||||
# invalidate it. The cache was therefore silently wrong rather than
|
||||
# missing, and the hooks reinstalled from scratch on every run (38-49s).
|
||||
- uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.cache/pre-commit
|
||||
key: >-
|
||||
pre-commit-leetcode-coach-${{ env.pythonLocation }}-${{
|
||||
hashFiles('leetcode_coach/.pre-commit-config.yaml') }}
|
||||
# Prefix fallback, or this fix would evaporate on the very
|
||||
# event that motivated it: bumping a hook rev changes the
|
||||
# exact key, and a total miss means reinstalling every hook
|
||||
# again. pre-commit's store is keyed internally by hook
|
||||
# repo+rev, so a superseded entry is ignored disk rather
|
||||
# than a wrong hook, and cache still re-saves under the new
|
||||
# exact key after a prefix-only hit.
|
||||
restore-keys: pre-commit-leetcode-coach-${{ env.pythonLocation }}-
|
||||
- name: Run the hooks
|
||||
run: >-
|
||||
pre-commit run --config leetcode_coach/.pre-commit-config.yaml
|
||||
--all-files --show-diff-on-failure
|
||||
34
.github/workflows/leetcode-coach-tests.yml
vendored
Normal file
34
.github/workflows/leetcode-coach-tests.yml
vendored
Normal file
@ -0,0 +1,34 @@
|
||||
name: leetcode-coach tests
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
# The workflow's own file counts as leetcode_coach: editing only this file would
|
||||
# otherwise trigger nothing, so a fix to the job itself could never prove
|
||||
# itself.
|
||||
paths: ['leetcode_coach/**', '.github/workflows/leetcode-coach-tests.yml']
|
||||
pull_request:
|
||||
branches: [main]
|
||||
paths: ['leetcode_coach/**', '.github/workflows/leetcode-coach-tests.yml']
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: leetcode_coach
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.x"
|
||||
cache: pip
|
||||
cache-dependency-path: leetcode_coach/requirements.txt
|
||||
|
||||
- name: Install dependencies
|
||||
run: pip install -r requirements.txt && pip install --no-deps -e .
|
||||
|
||||
- name: Run tests
|
||||
run: python -m pytest -v
|
||||
7
.github/workflows/md-naming.yml
vendored
7
.github/workflows/md-naming.yml
vendored
@ -1,6 +1,6 @@
|
||||
name: md-naming
|
||||
|
||||
# The four markdown namespaces, enforced on push as well as at commit time.
|
||||
# The markdown namespaces (README / CLAUDE* / DOCS*, no TODO*), enforced on push as well as at commit time.
|
||||
# The local pre-commit hook can be skipped (a fresh clone that never ran
|
||||
# `pre-commit install` has no hooks at all), so the convention needs a second
|
||||
# gate that no one can forget to install.
|
||||
@ -31,8 +31,3 @@ jobs:
|
||||
|
||||
- name: Enforce the naming convention
|
||||
run: bash .utils/scripts/check_md_naming.sh --all
|
||||
|
||||
# Warns only: no machine can prove a task is finished, so an old TODO
|
||||
# gets a nudge, never a failure.
|
||||
- name: Warn about stale TODOs
|
||||
run: PYTHONPATH=.utils python3 .utils/md_naming/stale.py
|
||||
|
||||
2
.github/workflows/music-theory-tests.yml
vendored
2
.github/workflows/music-theory-tests.yml
vendored
@ -27,5 +27,5 @@ jobs:
|
||||
- name: Install dependencies
|
||||
run: pip install -r requirements.txt
|
||||
|
||||
- name: Run tests with coverage
|
||||
- name: Run tests
|
||||
run: python -m pytest -v
|
||||
|
||||
56
.github/workflows/omniroute_offload-precommit.yml
vendored
Normal file
56
.github/workflows/omniroute_offload-precommit.yml
vendored
Normal file
@ -0,0 +1,56 @@
|
||||
name: omniroute_offload pre-commit
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
# The workflow's own file counts as omniroute_offload: editing only this file would
|
||||
# otherwise trigger nothing, so a fix to the job itself could never prove
|
||||
# itself.
|
||||
paths: ['omniroute_offload/**', '.github/workflows/omniroute_offload-precommit.yml']
|
||||
pull_request:
|
||||
branches: [main]
|
||||
paths: ['omniroute_offload/**', '.github/workflows/omniroute_offload-precommit.yml']
|
||||
|
||||
jobs:
|
||||
pre-commit:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.x"
|
||||
# Only pre-commit itself. Every hook runs in its own isolated
|
||||
# env -- ruff-format comes from its own repo+rev, and the local hooks
|
||||
# need nothing beyond bash and python3 -- so installing the full requirements.txt spent 9s a run on
|
||||
# packages no pre-commit-stage hook imports. Verified by running all
|
||||
# three configs green in a venv holding pre-commit and nothing else.
|
||||
# The pin is read out of requirements.txt rather than repeated here, so
|
||||
# it cannot drift from what the dependency-freshness gate governs.
|
||||
- name: Install pre-commit
|
||||
run: |
|
||||
pip install "$(grep '^pre-commit==' omniroute_offload/requirements.txt)"
|
||||
|
||||
# Keyed on THIS package's config. pre-commit/action@v3.0.1 caches on
|
||||
# hashFiles('.pre-commit-config.yaml') -- the repo ROOT's -- so all three
|
||||
# package jobs shared one key, raced to overwrite it with hook sets built
|
||||
# from four different configs, and editing a per-package config did not
|
||||
# invalidate it. The cache was therefore silently wrong rather than
|
||||
# missing, and the hooks reinstalled from scratch on every run (38-49s).
|
||||
- uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.cache/pre-commit
|
||||
key: >-
|
||||
pre-commit-omniroute_offload-${{ env.pythonLocation }}-${{
|
||||
hashFiles('omniroute_offload/.pre-commit-config.yaml') }}
|
||||
# Prefix fallback, or this fix would evaporate on the very
|
||||
# event that motivated it: bumping a hook rev changes the
|
||||
# exact key, and a total miss means reinstalling every hook
|
||||
# again. pre-commit's store is keyed internally by hook
|
||||
# repo+rev, so a superseded entry is ignored disk rather
|
||||
# than a wrong hook, and cache still re-saves under the new
|
||||
# exact key after a prefix-only hit.
|
||||
restore-keys: pre-commit-omniroute_offload-${{ env.pythonLocation }}-
|
||||
- name: Run the hooks
|
||||
run: >-
|
||||
pre-commit run --config omniroute_offload/.pre-commit-config.yaml
|
||||
--all-files --show-diff-on-failure
|
||||
5
.github/workflows/palette-drift.yml
vendored
5
.github/workflows/palette-drift.yml
vendored
@ -31,3 +31,8 @@ jobs:
|
||||
|
||||
- name: Categorical ramp still passes its constraints
|
||||
run: python3 unified-design-system/scripts/ramp_check.py
|
||||
|
||||
# Spacing, radius, type, shadow and motion: palette_check.py parses
|
||||
# hex only, so these scales were unguarded until structural_check.py.
|
||||
- name: Structural scales agree across all token sources
|
||||
run: python3 unified-design-system/scripts/structural_check.py
|
||||
|
||||
30
.github/workflows/platform-location-tests.yml
vendored
Normal file
30
.github/workflows/platform-location-tests.yml
vendored
Normal file
@ -0,0 +1,30 @@
|
||||
name: platform_location tests
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths: ['platform_location/**']
|
||||
pull_request:
|
||||
branches: [main]
|
||||
paths: ['platform_location/**']
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: platform_location
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Flutter
|
||||
uses: subosito/flutter-action@v2
|
||||
with:
|
||||
channel: stable
|
||||
|
||||
- name: Install dependencies
|
||||
run: flutter pub get
|
||||
|
||||
- name: Run tests
|
||||
run: flutter test
|
||||
19
.github/workflows/repo-contract.yml
vendored
Normal file
19
.github/workflows/repo-contract.yml
vendored
Normal file
@ -0,0 +1,19 @@
|
||||
name: repo-contract
|
||||
|
||||
# utils owns the shared gate, so it runs its own copy directly (no shim, no
|
||||
# second checkout). Other repos use repo_contract/templates/repo-contract.yml.
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
repo-contract:
|
||||
name: repo contract
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Enforce the repo contract
|
||||
run: bash scripts/check_repo_contract.sh
|
||||
30
.github/workflows/rtdb-relay-dart-tests.yml
vendored
Normal file
30
.github/workflows/rtdb-relay-dart-tests.yml
vendored
Normal file
@ -0,0 +1,30 @@
|
||||
name: rtdb_relay dart tests
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths: ['rtdb_relay/dart/**']
|
||||
pull_request:
|
||||
branches: [main]
|
||||
paths: ['rtdb_relay/dart/**']
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: rtdb_relay/dart
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Flutter
|
||||
uses: subosito/flutter-action@v2
|
||||
with:
|
||||
channel: stable
|
||||
|
||||
- name: Install dependencies
|
||||
run: flutter pub get
|
||||
|
||||
- name: Run tests
|
||||
run: flutter test
|
||||
47
.github/workflows/shared-gates-tests.yml
vendored
47
.github/workflows/shared-gates-tests.yml
vendored
@ -27,24 +27,43 @@ jobs:
|
||||
python-version: "3.x"
|
||||
|
||||
- name: Install test dependencies
|
||||
run: python -m pip install --upgrade pytest pytest-cov pyyaml packaging
|
||||
run: python -m pip install --upgrade pytest pyyaml packaging
|
||||
|
||||
- name: dep_freshness — 100% branch coverage on the gate itself
|
||||
- name: dep_freshness
|
||||
run: |
|
||||
PYTHONPATH=. python -m pytest dep_freshness/tests -q \
|
||||
--cov=dep_freshness --cov-branch \
|
||||
--cov-report=term-missing \
|
||||
--cov-fail-under=99
|
||||
PYTHONPATH=. python -m pytest dep_freshness/tests -q
|
||||
|
||||
- name: md_naming
|
||||
run: PYTHONPATH=. python -m pytest md_naming/tests -q
|
||||
|
||||
# Whole package at 100% branch: the gate is enforced in every repo and
|
||||
# now reads a per-repo `.file-length-exempt`, whose fail-closed rule is
|
||||
# exactly the kind of branch a partial suite would leave green by accident.
|
||||
- name: file_length — 100% branch coverage on the gate itself
|
||||
- name: file_length
|
||||
run: |
|
||||
PYTHONPATH=. python -m pytest file_length/tests -q \
|
||||
--cov=file_length --cov-branch \
|
||||
--cov-report=term-missing \
|
||||
--cov-fail-under=100
|
||||
PYTHONPATH=. python -m pytest file_length/tests -q
|
||||
|
||||
- name: repo_contract
|
||||
run: |
|
||||
PYTHONPATH=. python -m pytest repo_contract/tests -q
|
||||
|
||||
# Every web repo's pre-commit and CI run this checker against its dist/,
|
||||
# so a false green here ships an un-agent-ready site fleet-wide.
|
||||
- name: agent_ready
|
||||
run: |
|
||||
PYTHONPATH=. python -m pytest agent_ready/tests -q
|
||||
|
||||
- name: coverage_gaps
|
||||
run: |
|
||||
PYTHONPATH=. python -m pytest coverage_gaps/tests -q
|
||||
|
||||
# Its tests build throwaway repos with git, which the runner has.
|
||||
- name: devstats
|
||||
run: |
|
||||
PYTHONPATH=. python -m pytest devstats/tests -q
|
||||
|
||||
# gate_stamp.sh is the pre-push gate in every repo. Its tests drive real
|
||||
# pre-commit in throwaway repos, and the hook-id helper runs under
|
||||
# /usr/bin/python3 (the deployment interpreter), hence apt's PyYAML.
|
||||
- name: gate_stamp (step / full --list)
|
||||
run: |
|
||||
sudo apt-get update -q && sudo apt-get install -y python3-yaml
|
||||
python -m pip install --upgrade pre-commit
|
||||
PYTHONPATH=. python -m pytest scripts/tests -q
|
||||
|
||||
56
.github/workflows/sickdays-precommit.yml
vendored
Normal file
56
.github/workflows/sickdays-precommit.yml
vendored
Normal file
@ -0,0 +1,56 @@
|
||||
name: sickdays pre-commit
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
# The workflow's own file counts as sickdays: editing only this file would
|
||||
# otherwise trigger nothing, so a fix to the job itself could never prove
|
||||
# itself.
|
||||
paths: ['sickdays/**', '.github/workflows/sickdays-precommit.yml']
|
||||
pull_request:
|
||||
branches: [main]
|
||||
paths: ['sickdays/**', '.github/workflows/sickdays-precommit.yml']
|
||||
|
||||
jobs:
|
||||
pre-commit:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.x"
|
||||
# Only pre-commit itself. Every hook runs in its own isolated
|
||||
# env -- ruff-format comes from its own repo+rev, and the local hooks
|
||||
# need nothing beyond bash and python3 -- so installing the full requirements.txt spent 9s a run on
|
||||
# packages no pre-commit-stage hook imports. Verified by running all
|
||||
# three configs green in a venv holding pre-commit and nothing else.
|
||||
# The pin is read out of requirements.txt rather than repeated here, so
|
||||
# it cannot drift from what the dependency-freshness gate governs.
|
||||
- name: Install pre-commit
|
||||
run: |
|
||||
pip install "$(grep '^pre-commit==' sickdays/requirements.txt)"
|
||||
|
||||
# Keyed on THIS package's config. pre-commit/action@v3.0.1 caches on
|
||||
# hashFiles('.pre-commit-config.yaml') -- the repo ROOT's -- so all three
|
||||
# package jobs shared one key, raced to overwrite it with hook sets built
|
||||
# from four different configs, and editing a per-package config did not
|
||||
# invalidate it. The cache was therefore silently wrong rather than
|
||||
# missing, and the hooks reinstalled from scratch on every run (38-49s).
|
||||
- uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.cache/pre-commit
|
||||
key: >-
|
||||
pre-commit-sickdays-${{ env.pythonLocation }}-${{
|
||||
hashFiles('sickdays/.pre-commit-config.yaml') }}
|
||||
# Prefix fallback, or this fix would evaporate on the very
|
||||
# event that motivated it: bumping a hook rev changes the
|
||||
# exact key, and a total miss means reinstalling every hook
|
||||
# again. pre-commit's store is keyed internally by hook
|
||||
# repo+rev, so a superseded entry is ignored disk rather
|
||||
# than a wrong hook, and cache still re-saves under the new
|
||||
# exact key after a prefix-only hit.
|
||||
restore-keys: pre-commit-sickdays-${{ env.pythonLocation }}-
|
||||
- name: Run the hooks
|
||||
run: >-
|
||||
pre-commit run --config sickdays/.pre-commit-config.yaml
|
||||
--all-files --show-diff-on-failure
|
||||
49
.github/workflows/sickdays-tests.yml
vendored
Normal file
49
.github/workflows/sickdays-tests.yml
vendored
Normal file
@ -0,0 +1,49 @@
|
||||
name: sickdays tests
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
# The workflow's own file counts as sickdays: editing only this file would
|
||||
# otherwise trigger nothing, so a fix to the job itself could never prove
|
||||
# itself.
|
||||
paths: ['sickdays/**', '.github/workflows/sickdays-tests.yml']
|
||||
pull_request:
|
||||
branches: [main]
|
||||
paths: ['sickdays/**', '.github/workflows/sickdays-tests.yml']
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: sickdays
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.x"
|
||||
cache: pip
|
||||
cache-dependency-path: sickdays/requirements.txt
|
||||
|
||||
# crdt-sync and freedays are siblings in this repo, so they install from
|
||||
# the checkout rather than from a tag -- CI must test what is on this
|
||||
# branch, not what was last released. Deliberately NOT gatelock:
|
||||
# importing it pulls in tkinter, and this job has no display precisely
|
||||
# because sickdays must work without one.
|
||||
- name: Install the sibling packages
|
||||
run: pip install ../crdt-sync && pip install --no-deps ../freedays ../kuhy_credit
|
||||
|
||||
- name: Install dependencies
|
||||
run: pip install -r requirements.txt && pip install --no-deps -e .
|
||||
|
||||
# The library draws nothing, but sickdays.gui (0.3.0) does, and its
|
||||
# tests drive real Tk: option names and Checkbutton/variable wiring are
|
||||
# Tk's own behaviour. Headless they skip, taking coverage with them --
|
||||
# so the runner gets a virtual display, as gatelock's does.
|
||||
- name: Install a virtual X display
|
||||
run: sudo apt-get update && sudo apt-get install -y xvfb
|
||||
|
||||
- name: Run tests
|
||||
run: xvfb-run -a -s "-screen 0 1600x1200x24" python -m pytest -v
|
||||
56
.github/workflows/sql-drills-precommit.yml
vendored
Normal file
56
.github/workflows/sql-drills-precommit.yml
vendored
Normal file
@ -0,0 +1,56 @@
|
||||
name: sql-drills pre-commit
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
# The workflow's own file counts as sql_drills: editing only this file would
|
||||
# otherwise trigger nothing, so a fix to the job itself could never prove
|
||||
# itself.
|
||||
paths: ['sql_drills/**', '.github/workflows/sql-drills-precommit.yml']
|
||||
pull_request:
|
||||
branches: [main]
|
||||
paths: ['sql_drills/**', '.github/workflows/sql-drills-precommit.yml']
|
||||
|
||||
jobs:
|
||||
pre-commit:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.x"
|
||||
# Only pre-commit itself. Every hook runs in its own isolated
|
||||
# env -- ruff-format comes from its own repo+rev, and the local hooks
|
||||
# need nothing beyond bash and python3 -- so installing the full requirements.txt spent 9s a run on
|
||||
# packages no pre-commit-stage hook imports. Verified by running all
|
||||
# three configs green in a venv holding pre-commit and nothing else.
|
||||
# The pin is read out of requirements.txt rather than repeated here, so
|
||||
# it cannot drift from what the dependency-freshness gate governs.
|
||||
- name: Install pre-commit
|
||||
run: |
|
||||
pip install "$(grep '^pre-commit==' sql_drills/requirements.txt)"
|
||||
|
||||
# Keyed on THIS package's config. pre-commit/action@v3.0.1 caches on
|
||||
# hashFiles('.pre-commit-config.yaml') -- the repo ROOT's -- so all three
|
||||
# package jobs shared one key, raced to overwrite it with hook sets built
|
||||
# from four different configs, and editing a per-package config did not
|
||||
# invalidate it. The cache was therefore silently wrong rather than
|
||||
# missing, and the hooks reinstalled from scratch on every run (38-49s).
|
||||
- uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.cache/pre-commit
|
||||
key: >-
|
||||
pre-commit-sql-drills-${{ env.pythonLocation }}-${{
|
||||
hashFiles('sql_drills/.pre-commit-config.yaml') }}
|
||||
# Prefix fallback, or this fix would evaporate on the very
|
||||
# event that motivated it: bumping a hook rev changes the
|
||||
# exact key, and a total miss means reinstalling every hook
|
||||
# again. pre-commit's store is keyed internally by hook
|
||||
# repo+rev, so a superseded entry is ignored disk rather
|
||||
# than a wrong hook, and cache still re-saves under the new
|
||||
# exact key after a prefix-only hit.
|
||||
restore-keys: pre-commit-sql-drills-${{ env.pythonLocation }}-
|
||||
- name: Run the hooks
|
||||
run: >-
|
||||
pre-commit run --config sql_drills/.pre-commit-config.yaml
|
||||
--all-files --show-diff-on-failure
|
||||
34
.github/workflows/sql-drills-tests.yml
vendored
Normal file
34
.github/workflows/sql-drills-tests.yml
vendored
Normal file
@ -0,0 +1,34 @@
|
||||
name: sql-drills tests
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
# The workflow's own file counts as sql_drills: editing only this file would
|
||||
# otherwise trigger nothing, so a fix to the job itself could never prove
|
||||
# itself.
|
||||
paths: ['sql_drills/**', '.github/workflows/sql-drills-tests.yml']
|
||||
pull_request:
|
||||
branches: [main]
|
||||
paths: ['sql_drills/**', '.github/workflows/sql-drills-tests.yml']
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: sql_drills
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.x"
|
||||
cache: pip
|
||||
cache-dependency-path: sql_drills/requirements.txt
|
||||
|
||||
- name: Install dependencies
|
||||
run: pip install -r requirements.txt && pip install --no-deps -e .
|
||||
|
||||
- name: Run tests
|
||||
run: python -m pytest -v
|
||||
10
.github/workflows/sync-settings-ui-tests.yml
vendored
10
.github/workflows/sync-settings-ui-tests.yml
vendored
@ -26,11 +26,5 @@ jobs:
|
||||
- name: Install dependencies
|
||||
run: flutter pub get
|
||||
|
||||
- name: Analyze
|
||||
run: flutter analyze
|
||||
|
||||
- name: Run tests with coverage
|
||||
run: flutter test --coverage
|
||||
|
||||
- name: Enforce 100% line coverage
|
||||
run: scripts/check_coverage.sh coverage/lcov.info 100
|
||||
- name: Run tests
|
||||
run: flutter test
|
||||
|
||||
10
.github/workflows/ts-config-tests.yml
vendored
10
.github/workflows/ts-config-tests.yml
vendored
@ -7,6 +7,7 @@ on:
|
||||
pull_request:
|
||||
branches: [main]
|
||||
paths: ['ts_config/**']
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
test:
|
||||
@ -24,13 +25,10 @@ jobs:
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "24.21.0"
|
||||
node-version: "26.13.1"
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Lint (the preset lints itself)
|
||||
run: pnpm lint
|
||||
|
||||
- name: Fixture + factory tests with the 100% coverage gate
|
||||
run: pnpm coverage
|
||||
- name: Fixture + factory tests
|
||||
run: pnpm test
|
||||
|
||||
14
.github/workflows/ts-core-tests.yml
vendored
14
.github/workflows/ts-core-tests.yml
vendored
@ -3,10 +3,11 @@ name: ts_core tests
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths: ['ts_core/**']
|
||||
paths: ['ts_core/**', 'ts_config/**']
|
||||
pull_request:
|
||||
branches: [main]
|
||||
paths: ['ts_core/**']
|
||||
paths: ['ts_core/**', 'ts_config/**']
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
test:
|
||||
@ -24,16 +25,13 @@ jobs:
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "24.21.0"
|
||||
node-version: "26.13.1"
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Lint
|
||||
run: pnpm lint
|
||||
|
||||
- name: Run tests with the 100% coverage gate
|
||||
run: pnpm coverage
|
||||
- name: Run tests
|
||||
run: pnpm test
|
||||
|
||||
# The tag ships a prebuilt dist/ because Vite does not transpile
|
||||
# dependencies. A committed dist/ that does not match src/ would ship
|
||||
|
||||
14
.github/workflows/web-ui-tests.yml
vendored
14
.github/workflows/web-ui-tests.yml
vendored
@ -3,10 +3,11 @@ name: web_ui tests
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths: ['web_ui/**']
|
||||
paths: ['web_ui/**', 'ts_config/**']
|
||||
pull_request:
|
||||
branches: [main]
|
||||
paths: ['web_ui/**']
|
||||
paths: ['web_ui/**', 'ts_config/**']
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
test:
|
||||
@ -24,16 +25,13 @@ jobs:
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "24.21.0"
|
||||
node-version: "26.13.1"
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Lint
|
||||
run: pnpm lint
|
||||
|
||||
- name: Run tests with the 100% coverage gate
|
||||
run: pnpm coverage
|
||||
- name: Run tests
|
||||
run: pnpm test
|
||||
|
||||
# The tag ships a prebuilt dist/ because Vite does not transpile
|
||||
# dependencies. A committed dist/ that does not match src/ would ship
|
||||
|
||||
3
.gitignore
vendored
3
.gitignore
vendored
@ -23,3 +23,6 @@ firebase-debug.log
|
||||
firebase-debug.*.log
|
||||
firestore-debug.log
|
||||
database-debug.log
|
||||
|
||||
# Claude Code harness worktrees: never commit them as gitlinks.
|
||||
.claude/worktrees/
|
||||
|
||||
@ -1,19 +1,12 @@
|
||||
# Repo-wide gate for the shared 250-line file cap (refactor_claude_todo.md).
|
||||
#
|
||||
# A file that cannot be read in one piece forces re-reads and partial edits,
|
||||
# which is the largest avoidable cost in an LLM-assisted workflow. A refactor
|
||||
# without a gate silently regrows, so this is the part that makes it stick.
|
||||
#
|
||||
# Checks only the files in the commit, so an unrelated commit never breaks on
|
||||
# a violation it did not introduce, and it FAILS (exit 1) rather than warning.
|
||||
# No baseline and no allowlist -- those are suppressions.
|
||||
# Repo-wide gates. Lint, type checks, coverage thresholds and the 250-line file
|
||||
# cap are dropped (kuhy, 2026-11-27); formatters, the private/personal-data scan,
|
||||
# no-binaries, dependency freshness, no-noqa, md-naming and repo-contract stay.
|
||||
#
|
||||
# The subprojects (gatelock/, crdt-sync/, web_ui/, design_system/,
|
||||
# sync_settings_ui/) each keep their own .pre-commit-config.yaml for their own
|
||||
# linters, and carry this same hook so committing with one of those configs is
|
||||
# gated too. This root config is what `pre-commit install` wires up, and it is
|
||||
# the only one that covers the subprojects without a config of their own
|
||||
# (aur-publish/, guard-lib/, crdt_sync_dart/, file_length/, ...).
|
||||
# sync_settings_ui/, ...) each keep their own .pre-commit-config.yaml. This root
|
||||
# config is what `pre-commit install` wires up, and it is the only one that
|
||||
# covers the subprojects without a config of their own (guard-lib/,
|
||||
# crdt_sync_dart/, file_length/, ...).
|
||||
#
|
||||
# The path is repo-relative on purpose. pre-commit always runs hooks from the
|
||||
# git root, so this resolves the same locally and on a CI runner -- an absolute
|
||||
@ -21,14 +14,8 @@
|
||||
repos:
|
||||
- repo: local
|
||||
hooks:
|
||||
- id: file-length-cap
|
||||
name: file length <= 250 lines
|
||||
entry: bash scripts/check_file_length.sh
|
||||
language: system
|
||||
pass_filenames: true
|
||||
|
||||
# Four markdown namespaces (README / CLAUDE* / DOCS* / TODO*), plus the
|
||||
# rule that a TODO carries "REMOVE ME AFTER FINISH" and nothing else may.
|
||||
# Three markdown namespaces (README / CLAUDE* / DOCS*); TODO*.md is banned
|
||||
# (tasks live in the todo app).
|
||||
# Shared gate in ~/src/utils owns the namespaces and the exemption list, so
|
||||
# one repo's idea of a valid name cannot drift from every other repo's.
|
||||
# Since the 2026-09-11 reorganisation ~ holds eleven visible entries and
|
||||
@ -43,6 +30,13 @@ repos:
|
||||
language: system
|
||||
pass_filenames: true
|
||||
|
||||
- id: repo-contract
|
||||
name: repo contract (CLAUDE.md Commands + test_changed)
|
||||
entry: scripts/check_repo_contract.sh
|
||||
language: system
|
||||
pass_filenames: false
|
||||
files: ^(CLAUDE\.md|AGENTS\.md|scripts/test_changed\.sh)$|(^|/)(AndroidManifest\.xml|build\.gradle(\.kts)?|strings\.xml|pubspec\.yaml|repo-contract\.toml|[^/]+\.desktop|assets/icon/[^/]+\.png)$
|
||||
|
||||
- id: md-naming
|
||||
name: markdown naming convention
|
||||
entry: scripts/check_md_naming.sh
|
||||
@ -59,9 +53,14 @@ repos:
|
||||
# answer and passes with a loud banner; `--no-verify` is banned here, so
|
||||
# a hook that hard-failed on a flaky connection would leave no way to
|
||||
# commit at all. CI, always online, is the strict authority.
|
||||
#
|
||||
# Scoped to manifests this branch changed (vs merge-base with main), so
|
||||
# `--all-files` asks "did THIS change leave a stale pin?" and not "is
|
||||
# every project in the monorepo current?". CI `--all --strict` keeps
|
||||
# the repo-wide answer. See scripts/dep_freshness_changed.sh.
|
||||
- id: dependency-freshness
|
||||
name: dependencies on newest stable
|
||||
entry: bash scripts/check_dependency_freshness.sh
|
||||
entry: bash scripts/dep_freshness_changed.sh
|
||||
language: system
|
||||
pass_filenames: true
|
||||
files: >-
|
||||
|
||||
27
.pre-commit-hooks.yaml
Normal file
27
.pre-commit-hooks.yaml
Normal file
@ -0,0 +1,27 @@
|
||||
# Hooks other repos consume with `repo: https://github.com/kuhyx/utils`.
|
||||
# All three are post-* stages, so each clone must install them (see
|
||||
# todo_hooks/README.md). They never fail a git operation: the work has
|
||||
# already happened, so server/gh trouble prints one warning and exits 0.
|
||||
- id: todo-closer
|
||||
name: close Todo trailer tasks
|
||||
entry: scripts/todo_hooks.sh closer
|
||||
language: script
|
||||
stages: [post-commit]
|
||||
always_run: true
|
||||
pass_filenames: false
|
||||
|
||||
- id: todo-import-pr-merge
|
||||
name: import PR Todo sections (pull)
|
||||
entry: scripts/todo_hooks.sh import-pr post-merge
|
||||
language: script
|
||||
stages: [post-merge]
|
||||
always_run: true
|
||||
pass_filenames: false
|
||||
|
||||
- id: todo-import-pr-rewrite
|
||||
name: import PR Todo sections (pull --rebase)
|
||||
entry: scripts/todo_hooks.sh import-pr post-rewrite
|
||||
language: script
|
||||
stages: [post-rewrite]
|
||||
always_run: true
|
||||
pass_filenames: false
|
||||
27
CLAUDE.md
Normal file
27
CLAUDE.md
Normal file
@ -0,0 +1,27 @@
|
||||
# utils
|
||||
|
||||
Monorepo of shared gates and libraries (app_errors, dep_freshness, file_length, md_naming,
|
||||
repo_contract, coverage_gaps, devstats (`devstats/run.sh`: one-shot run + HTML report), crdt-sync, gatelock, freedays, sickdays, earned_time, music_theory, game_recording,
|
||||
flutter_web_drive (headless Flutter-web E2E driver + MCP), ...).
|
||||
`godot_dev_tools/` is a Godot addon (GDScript): `godot_dev_tools/test.sh` runs its GUT tests.
|
||||
`kuhy_credit/` is the shared "Created by kuhy" credit, one implementation per stack (web, Flutter,
|
||||
Godot, Tk, terminal, LaTeX) generated from `kuhy_credit/credit.json`; `kuhy_credit/README.md` lists each
|
||||
stack's test and E2E command, `python -m generator.generate --check` (from `kuhy_credit/`) the drift check.
|
||||
Python packages with a root-level `<pkg>/tests` run with `PYTHONPATH=.`;
|
||||
subprojects with their own `pyproject.toml` run via `scripts/run_subproject_tests.sh <dir>`.
|
||||
`scripts/check_repo_contract.sh` is the REAL shared gate (not a shim): never
|
||||
overwrite it with `repo_contract/templates/check_repo_contract.shim.sh`.
|
||||
|
||||
## Commands
|
||||
|
||||
- run: n/a: collection of gates and libraries, no single entry point
|
||||
- test: `PYTHONPATH=. python -m pytest -q agent_ready/tests coverage_gaps/tests dep_freshness/tests devstats/tests file_length/tests flutter_web_drive/tests home_paths/tests md_naming/tests repo_contract/tests scripts/tests unified-design-system/tests`
|
||||
- test-changed: `scripts/test_changed.sh`
|
||||
- lint: n/a: dropped (kuhy, 2026-11-27)
|
||||
- coverage: n/a: dropped (kuhy, 2026-11-27)
|
||||
- coverage-gaps: n/a: dropped (kuhy, 2026-11-27)
|
||||
- deploy: `git -C ~/src/utils pull --ff-only && ~/src/utils/scripts/deploy.sh` (installs the sickdays CLI + launcher from the live checkout, then exits 1 unless every released library's version tag is on origin and matches HEAD and the live `sickdays` runs the text-free checkout; `--verify-only` for the health check alone)
|
||||
|
||||
## Rules
|
||||
|
||||
- Offline-first: every app that syncs or shares data, whatever the transport, saves each write locally first (readable at once) and keeps all pulled data, details included (`~/.claude/rules/offline-first.instructions.md`; audit `DOCS-offline-first.md`). The `crdt_sync_dart` contract is in its README ("Offline-first contract"), check `cd crdt_sync_dart && dart test test/offline_first_test.dart`.
|
||||
61
DOCS-app-errors.md
Normal file
61
DOCS-app-errors.md
Normal file
@ -0,0 +1,61 @@
|
||||
# App errors and slow waits become board tickets
|
||||
|
||||
kuhy's rule (2026-11-17): every error, and every wait the user sees over 1 s, in
|
||||
any of his apps is reported automatically. The board then turns each one into a
|
||||
ticket that fixes itself. This doc covers the apps' half and the PC ingest. The
|
||||
board's half is todoImplementer `DOCS-errors.md`, with the contract in
|
||||
`contracts/app-error.schema.json`. The design is kartka's pipeline
|
||||
(`~/src/kartka`, `docs/DOCS-error-reports.md`), made shared.
|
||||
|
||||
## Pipeline
|
||||
|
||||
1. **Apps report.** Each report is one *entry* (see `app_errors/README.md`):
|
||||
- Flutter, `crdt_sync_flutter` 0.9.0: `installAppErrors` hooks
|
||||
`FlutterError.onError` and `PlatformDispatcher.onError`. `WaitWatch` turns
|
||||
a spinner shown over 1 s into `perf.slow`. The device deduplicates (30 s,
|
||||
20 a minute) and redacts each report, and queues it in
|
||||
`SharedPreferences`. It uploads to RTDB `/<app>/errors/<device>/<id>` with
|
||||
the build (versionCode).
|
||||
- Python/Tk, `gatelock` 0.15.0: `gatelock.error_report.install` hooks
|
||||
`sys.excepthook`, `threading.excepthook` and Tk callback errors.
|
||||
`watch_stalls(root, rep)` reports a frozen Tk loop over 1 s.
|
||||
`rep.wait(...)` and `rep.begin(...)` time a wait.
|
||||
- Godot, `godot_dev_tools` 0.2.0, `addons/app_errors`: an `OS.add_logger`
|
||||
logger catches script errors and `push_error`. A frame over 1 s, or
|
||||
`report_wait` over 1 s, becomes `perf.slow`. Headless runs and
|
||||
`APP_ERRORS_OFF=1` write nothing, so a game's own test gates file no
|
||||
tickets.
|
||||
- PC apps (Tk and Godot) append to the local spool
|
||||
`~/.local/state/app-errors-spool/<app>.jsonl`. They need no RTDB, because
|
||||
the ingest runs on the same PC.
|
||||
2. **The PC ingests.** `app-errors-ingest.timer` runs `app-errors ingest` every
|
||||
5 min. It reads RTDB through an already seeded crdt-sync session
|
||||
(`firebase_backup`) and reads the spool. It merges reports by signature
|
||||
(Dart signatures are kartka-identical), deletes what it read, and writes
|
||||
`~/.local/state/app-errors/<app>.json` as a contract `report`.
|
||||
3. **The board files tickets.** It scans that folder every 60 s and makes one
|
||||
ticket per `app:signature` (todoImplementer `DOCS-errors.md`).
|
||||
|
||||
`app-errors resolve <app> <signature>` sets `open: false`. A later report opens
|
||||
the error again only when it is a regression: a newer build when both sides
|
||||
know the build, else a report made after the resolve. The board never calls
|
||||
`resolve` on its own, because folder sources have no resolve hook. It tracks
|
||||
shipped fixes by `fixed_build`.
|
||||
|
||||
## Choices made (no questions asked, per the brief)
|
||||
|
||||
- kartka moved over on 2026-11-17: the shared ingest reads `/kartka` too
|
||||
(it parses kartka's older entry shape: `sourceId`, per-entry `build`),
|
||||
the board's `error_sources` is `[]` and `kartka-errors.timer` is retired.
|
||||
Ticket ids stayed the same: all 134 stored kartka signatures recompute
|
||||
identically.
|
||||
- Tk and Godot use the local spool instead of RTDB: they only run on the PC.
|
||||
- The Godot reporter is its own addon folder, mounted in every build. It is
|
||||
not part of `dev_tools`, which only loads for `--dev` runs.
|
||||
- Reporting is silent: no text, dialog or notification in any app.
|
||||
|
||||
## Install and check
|
||||
|
||||
`scripts/deploy.sh` runs `app_errors/install.sh`. That installs the venv and
|
||||
`~/.local/bin/app-errors`, enables the timer, and checks that the timer is
|
||||
active and the venv imports the live checkout.
|
||||
40
DOCS-offline-first.md
Normal file
40
DOCS-offline-first.md
Normal file
@ -0,0 +1,40 @@
|
||||
# Offline-first audit of kuhy's syncing apps
|
||||
|
||||
Rule: `~/.claude/rules/offline-first.instructions.md` (kuhy, 2026-11-27). Every app that syncs or shares data
|
||||
is offline-first: (a) a create/save lands locally first and is readable at once; (b) sync runs by itself and a
|
||||
network failure keeps the write and retries; (c) everything pulled, details included, is kept locally and shown
|
||||
offline and after a restart. Apps on `crdt_sync_dart` follow its README "Offline-first contract"
|
||||
(`crdt_sync_dart/test/offline_first_test.dart`).
|
||||
|
||||
Audit run 2026-11-27 by todoImplementer card c5ee9e59-9 (read-only sweep of `~/src/*` manifests, evidence as
|
||||
`file:line` under each app root, `lib/` left out for Dart apps). A FAIL row is fixed by its own commit; the
|
||||
"Fix" column names it. A new syncing app adds its row here when it ships.
|
||||
|
||||
| App | Sync | (a) | (b) | (c) | Verdict | Evidence | Fix |
|
||||
|---|---|---|---|---|---|---|---|
|
||||
| ~/src/todo | crdt_sync LogStore + Firebase/GitHub mirror | PASS | PASS | PASS | PASS | `data/note_repository.dart:59-60`, launch/pause/focus sync `ui/capture_screen.dart:118,180,187`, importLog before push `sync/sync_service.dart:171` | model app |
|
||||
| ~/src/todoImplementer/app | rtdb_relay board relay | FAIL | FAIL | FAIL | FAIL | new task existed only after a relay send `ui/board/new_task_sheet.dart:121-133`; board and task details never kept `sync/rtdb_board_relay.dart:106-118`, `ui/board/detail_page.dart:88-99` | T2603 board + details kept, prefetched per sync; T2604 outbox (kuhyx/todoImplementer) |
|
||||
| ~/src/home_inventory | crdt_sync LogStore + mirror | PASS | FAIL | PASS | FAIL | only the "Sync now" button syncs `screens/github_mirror_screen.dart:168` | pending |
|
||||
| ~/src/lyricanki | crdt_sync LogStore + openSync | PASS | FAIL | PASS | FAIL | sync only from `onSync` `screens/song_search_screen.dart:219` | pending |
|
||||
| ~/src/restaurant-rater | crdt_sync LogStore + openSync | PASS | FAIL | PASS | FAIL | no sync on launch/resume, a failed push waits for the next edit `sync/sync_bootstrap.dart:105`, `app.dart:17-26` | pending |
|
||||
| ~/src/leetcode-guard/app | crdt_sync snapshot + coach relay | FAIL | FAIL | FAIL | FAIL | coach requests memory-only `coach/controller_send.dart:25-37`; chat memory-only `coach/controller.dart:216-222` | pending |
|
||||
| ~/src/tutor/app | rtdb_relay | PASS | PASS | PASS | PASS | outbox for picks and reports `sync/put_outbox.dart`; archive flags queued and History kept `history/history.dart`; stats/today kept `home/remote_bits.dart`; last session kept `session/session_kept.dart`; e2e header kept so a cold start offline unlocks `sync/rtdb_client.dart`; every read/listen gated by `test/sync/offline_first_reads_test.dart` | d7f6e86, faf130a, b3df844, 0e4d7b1, 6ad66d4 (kuhyx/tutor) |
|
||||
| ~/src/screen-locker/stronglift_replacement/workout_app | crdt_sync syncLog + run queue | PASS | FAIL | FAIL | FAIL | failed workout push only logged `screens/workout_screen_finish.dart:125-130`; merge thrown away `services/workout_sync_session.dart:111` | pending |
|
||||
| ~/src/dufs-cloud/app | WebDAV | unverified | unverified | FAIL | FAIL | listings uncached `services/dufs_client.dart:65` | pending |
|
||||
| ~/src/signal-bot/app | HTTP management API | FAIL | FAIL | FAIL | FAIL | live reads, direct edits `api.dart:63-71,95` | pending |
|
||||
| ~/src/logo-review/app | HTTP review server | unverified | unverified | FAIL | FAIL | pictures session-only `ui/service_badge.dart:12`; feedback POST `api.dart:74` | pending |
|
||||
| ~/src/kuhytrack | own HTTP server + watchers | PASS | PASS | FAIL | N/A: archived | readers fetch live `web/dashboard.html:119`, `cli/ktq.py:58`; repo archived on GitHub 2026-11-02 | fix kept unpushed on local branch `todo/c5ee9e59-9-kuhytrack` (30ae4a8) |
|
||||
| ~/src/punchme | crdt_sync LogStore + openSync | PASS | PASS | PASS | PASS | store loads `sync/sync_bootstrap.dart:66` before openSync `:73`, push per write `:90` | none |
|
||||
| ~/src/diet-guard/app | crdt_sync + RTDB relay | PASS | PASS | PASS | PASS | `services/log_storage_service.dart:108`, WorkManager backstop `services/background_tasks_io.dart:21,36` | none |
|
||||
| ~/src/wake-alarm/phone_app | crdt_sync LogStore + native sync | PASS | PASS | PASS | PASS | `services/alarm_policy.dart:117-118`, `services/alarm_sync_service.dart:102-103` | none |
|
||||
| ~/src/daily-limits/app | crdt_sync RTDB + request queue | PASS | PASS | PASS | PASS | `services/limits_controller.dart:102-130`, `services/sync_once.dart:68-97` | none |
|
||||
| ~/src/home-guard/app | crdt_sync RTDB + upload queue | PASS | PASS | PASS | PASS | `screens/home_screen.dart:168-169`, zones cached `services/zone_sync.dart:73-87` (remote read before cache, no timeout `:105-108`) | none |
|
||||
| ~/src/phone-focus-mode/focus-owner | crdt_sync push + native queue | PASS | PASS | PASS | PASS | `android/.../UninstallEvents.kt:25,112-115` | none |
|
||||
| ~/src/kartka | own RTDB engine | PASS | PASS | PASS | PASS | `sync/decorators/synced_library.dart:35-42`, `sync/sync_engine.dart:127-129` | none |
|
||||
| ~/src/sufler | crdt_sync + RTDB relay | PASS | PASS | PASS | PASS | `assist/ask.dart:19-20,85,99` | none |
|
||||
| ~/src/book-guard/app | WebDAV outbox | PASS | PASS | PASS | PASS | `src/guard_api.dart:95,101-105,128-133` | none |
|
||||
| PC sides (Python): diet-guard, wake-alarm, screen-locker, leetcode-guard, daily-limits, build-your-x, home-guard | crdt-sync / RTDB | PASS | PASS | PASS | PASS | e.g. `diet_guard/_sync.py:181,242`, `wake_alarm/_sync_transport.py:5-18`; build-your-x trigger and home-guard zone merge unverified | none |
|
||||
| Relay workers: todoImplementer, tutor, sufler | rtdb_relay (PC) | ? | ? | ? | pending | not read yet | pending |
|
||||
|
||||
Not syncing (dropped): kuhylog, tunedeck, habit_stack (no sync wiring yet: it must meet this rule when it gets
|
||||
one), umbrella, game-research, pacman-yay-gui, WUT_Computer_Science, dufs-cloud/firebase_backup.
|
||||
72
README.md
72
README.md
@ -42,6 +42,38 @@ dependencies:
|
||||
path: sync_settings_ui
|
||||
```
|
||||
|
||||
## google_account_token/
|
||||
|
||||
Flutter plugin (Android only; other platforms return null): one-tap Google ID
|
||||
token via `AccountManager`, replacing `google_sign_in` in the sync apps.
|
||||
|
||||
Consume via:
|
||||
```yaml
|
||||
dependencies:
|
||||
google_account_token:
|
||||
git:
|
||||
url: https://github.com/kuhyx/utils
|
||||
ref: google_account_token-v0.1.0
|
||||
path: google_account_token
|
||||
```
|
||||
|
||||
## platform_location/
|
||||
|
||||
Flutter plugin (Android only): location through AOSP `LocationManager`
|
||||
(androidx `LocationManagerCompat`), replacing `geolocator`, whose Android
|
||||
side links non-free `play-services-location`. Used by umbrella and
|
||||
workout_app.
|
||||
|
||||
Consume via:
|
||||
```yaml
|
||||
dependencies:
|
||||
platform_location:
|
||||
git:
|
||||
url: https://github.com/kuhyx/utils
|
||||
ref: platform_location-v0.1.0
|
||||
path: platform_location
|
||||
```
|
||||
|
||||
## crdt-sync/
|
||||
|
||||
Python CRDT sync library (package: `crdt_sync`, not published to PyPI). Same
|
||||
@ -62,6 +94,13 @@ watcher + pacman hooks). Not a package — installed by running
|
||||
Consumed by `steam-backlog-enforcer` (expects a `guard-lib/install.sh`
|
||||
sibling clone) and referenced by `screen-locker`.
|
||||
|
||||
## app_errors/
|
||||
|
||||
The PC ingest of the shared app error and slow-wait reporting: RTDB and local
|
||||
spool reports in, todoImplementer board tickets out, on a systemd `--user`
|
||||
timer. The reporters live in `crdt_sync_flutter`, `gatelock` and
|
||||
`godot_dev_tools/addons/app_errors`. See [`DOCS-app-errors.md`](DOCS-app-errors.md).
|
||||
|
||||
## gatelock/
|
||||
|
||||
Python lock-window + HMAC log-integrity backend (package: `gatelock`, not
|
||||
@ -86,6 +125,17 @@ Consume via:
|
||||
music_theory @ git+https://github.com/kuhyx/utils@music-theory-v0.1.0#subdirectory=music_theory
|
||||
```
|
||||
|
||||
## game_recording/
|
||||
|
||||
Session recorder for a game (package: `game_recording`, stdlib only, not
|
||||
published to PyPI): records a dev run from outside the game and stamps its
|
||||
telemetry moments onto the video. A game configures it with one `Config`.
|
||||
|
||||
Consume via:
|
||||
```
|
||||
game_recording @ git+https://github.com/kuhyx/utils@game-recording-v0.1.1#subdirectory=game_recording
|
||||
```
|
||||
|
||||
## unified-design-system/
|
||||
|
||||
Not a package — the frozen design tokens (colors, spacing, type, radius,
|
||||
@ -113,3 +163,25 @@ planted violation per rule family proves each gate bites.
|
||||
"@kuhyx/ts-config": "github:kuhyx/utils#ts_config-v0.1.0&path:/ts_config"
|
||||
}
|
||||
```
|
||||
|
||||
## godot_dev_tools/
|
||||
|
||||
Godot addon (`addons/dev_tools/`): the F12 dev feedback mode of kuhy's games
|
||||
(annotate the frozen frame, save a bundle that `feedback_inbox` turns into a
|
||||
task). A game mounts it at a pinned tag; the game's own code stays a small host
|
||||
object. Read [`godot_dev_tools/README.md`](godot_dev_tools/README.md).
|
||||
|
||||
Consume via a shallow fetch of the tag, then mount the addon folder:
|
||||
```
|
||||
git clone --depth 1 --branch godot-dev-tools-v0.1.1 https://github.com/kuhyx/utils
|
||||
# link or copy godot_dev_tools/addons/dev_tools to res://addons/dev_tools
|
||||
```
|
||||
|
||||
## devstats/
|
||||
|
||||
`python -m devstats compare` (from the repo root, `PYTHONPATH=.`): kuhy's net
|
||||
LoC/day, commits and tags over 30/90/300 days across every repo in ~/src
|
||||
(worktrees and rewritten copies counted once, lockfiles/generated/vendored/data
|
||||
dropped by `devstats/excludes.py`), printed beside the figures from
|
||||
https://veszelovszki.com/a/tpe/. `--by-repo [N]` adds a top-N table (terminal
|
||||
only); `--write` regenerates [`devstats/DOCS-comparison.md`](devstats/DOCS-comparison.md).
|
||||
|
||||
@ -1,153 +0,0 @@
|
||||
# TODO — pylint `--fail-under=10` everywhere, and clear what that surfaces
|
||||
|
||||
REMOVE ME AFTER FINISH
|
||||
|
||||
## what
|
||||
|
||||
Ten pylint hooks across six repos still pass at `--fail-under=8.0`, which
|
||||
permanently tolerates two points of lint debt and lets a score *regress* from
|
||||
9.9 to 8.1 without failing anything. Move every one to `10`, and fix what
|
||||
that surfaces. Five other sites already run at `10`, so this is adopting an
|
||||
existing standard, not inventing one.
|
||||
|
||||
## the ten sites, exact
|
||||
|
||||
Measured 2026-09-12. "Score now" is that package's current rating under its
|
||||
own config, tests included.
|
||||
|
||||
| Repo / package | Site | Score now |
|
||||
|---|---|---|
|
||||
| `control-panel` | `.pre-commit-config.yaml:159` | 8.53 |
|
||||
| `leetcode-guard` | `.pre-commit-config.yaml:112` | 8.71 |
|
||||
| `screen-locker` | `.pre-commit-config.yaml:121` | 9.85 |
|
||||
| `screen-locker` | `.pre-commit-config.yaml:140` | (2nd pylint hook) |
|
||||
| `steam-backlog-enforcer` | `.pre-commit-config.yaml:124` | 8.76 |
|
||||
| `testsAndMisc/meta` | `.pre-commit-config.yaml:194` | 8.77 |
|
||||
| `utils/crdt-sync` | `.pre-commit-config.yaml:111` | 9.59 |
|
||||
| `utils/freedays` | `.pre-commit-config.yaml:109` | 8.55 |
|
||||
| `utils/gatelock` | `.pre-commit-config.yaml:109` | 9.18 |
|
||||
| `utils/music_theory` | `.pre-commit-config.yaml:113` | 8.54 |
|
||||
|
||||
`screen-locker` has **two** pylint hooks; both need the bump or the second one
|
||||
silently keeps the old bar.
|
||||
|
||||
Already at `10` — do not touch, these are the reference:
|
||||
`build-your-x`, `diet-guard`, `testsAndMisc` (root config),
|
||||
`wake-alarm`, `WUT_Computer_Science/.../translator/.pylintrc`.
|
||||
|
||||
## why the scores look bad, and why that is misleading
|
||||
|
||||
Every one of these configs runs `enable = "all"` with `disable = []` — the
|
||||
strictest pylint setting there is, including checks that are off by default.
|
||||
The raw findings are dominated by **test-file idioms**, not source defects.
|
||||
Measured on the four `utils` packages:
|
||||
|
||||
```
|
||||
crdt-sync 54 protected-access, 50 redefined-outer-name, 18 duplicate-code
|
||||
freedays 100 missing-function-docstring, 14 implicit-booleaness
|
||||
gatelock 147 redefined-outer-name, 142 protected-access
|
||||
music_theory 112 missing-function-docstring, 14 missing-module-docstring
|
||||
```
|
||||
|
||||
`redefined-outer-name` at that volume is pytest fixtures. `protected-access`
|
||||
is tests reaching into internals on purpose. Neither is a defect.
|
||||
|
||||
**The repos already at 10 solved this and wrote down why.** From
|
||||
`wake-alarm/pyproject.toml`, verbatim:
|
||||
|
||||
> `ignore = [".venv", "__pycache__", "tests"]` — "tests" is a basename match:
|
||||
> test suites intentionally use patterns (protected-access, magic-value
|
||||
> comparisons) that don't apply to source code, matching testsAndMisc's
|
||||
> pylint scope (tests are linted by ruff, not pylint there either).
|
||||
|
||||
So the fleet standard is: **pylint grades source, ruff grades tests.** The ten
|
||||
sites above are the outliers that never adopted it. Their `ruff` config
|
||||
already carries the equivalent test exemptions
|
||||
(`"**/tests/**/*.py" = ["ARG", "D", "PLC0415", "PLR2004", "S101", "SLF001"]`),
|
||||
so tests stay linted — by the tool that has the right rules for them.
|
||||
|
||||
## what is actually left after adopting the fleet config
|
||||
|
||||
Measured: `pylint --ignore=.venv,__pycache__,tests` plus wake-alarm's
|
||||
three-item `disable` list, run over source files only.
|
||||
|
||||
| Package | Score | Remaining findings |
|
||||
|---|---|---|
|
||||
| `crdt-sync` | 9.93 | 5 wrong-import-position, 3 duplicate-code, 1 too-many-locals, 1 invalid-name |
|
||||
| `freedays` | 9.63 | 3 import-error, 1 broad-exception-caught |
|
||||
| `gatelock` | 9.88 | 6 missing-function-docstring, 4 wrong-import-position, 3 too-many-instance-attributes, 3 import-outside-toplevel, 2 broad-exception-caught, 1 each too-many-arguments / invalid-name / duplicate-code / disallowed-name / chained-comparison |
|
||||
| `music_theory` | 9.42 | 10 import-error |
|
||||
|
||||
That is ~47 real findings across four packages, not the ~600 the raw run
|
||||
suggests. **`import-error` is almost certainly config, not code**: every repo
|
||||
already at 10 carries an `init-hook` the 8.0 repos lack —
|
||||
|
||||
```toml
|
||||
init-hook = "import sys; sys.path.insert(0, '.')"
|
||||
```
|
||||
|
||||
Try that first on `music_theory` and `freedays` before editing any import.
|
||||
|
||||
## must
|
||||
|
||||
- Every site at `--fail-under=10`. No `9.5`, no per-repo exception.
|
||||
- Adopt the reference config from `wake-alarm` / `diet-guard`: the `tests`
|
||||
basename ignore, the `init-hook`, and only then the residue fixes.
|
||||
- Fix findings in source. Prefer the fix to the disable, every time.
|
||||
- must not: add a `# pylint: disable=` comment, or extend `disable = [...]`
|
||||
beyond wake-alarm's three implicit-booleaness entries, **without asking
|
||||
kuhy first — every time, per `memories/code-quality.md`.** All seven
|
||||
"unavoidable" disables in a past konbini-67 session were reverted.
|
||||
- must not: exclude a source file from pylint to raise the score, or drop
|
||||
`enable = "all"`.
|
||||
- must not: touch the five sites already at `10`.
|
||||
- optional: `duplicate-code` findings may be genuine shared-code candidates
|
||||
for `utils`. Note them, do not force a refactor to hit the number.
|
||||
|
||||
## done
|
||||
|
||||
Both commands, from `~`:
|
||||
|
||||
```bash
|
||||
# 1. no site left below 10 (cov-fail-under is coverage, not pylint)
|
||||
! grep -rn --include=.pre-commit-config.yaml --include=.pylintrc \
|
||||
-E 'fail-under=(8|9)' ~/src ~/praca_magisterska 2>/dev/null \
|
||||
| grep -v cov-fail-under
|
||||
|
||||
# 2. every one of the nine packages passes its own pylint hook
|
||||
for d in ~/src/control-panel ~/src/leetcode-guard ~/src/screen-locker \
|
||||
~/src/steam-backlog-enforcer ~/src/testsAndMisc/meta \
|
||||
~/src/utils/crdt-sync ~/src/utils/freedays \
|
||||
~/src/utils/gatelock ~/src/utils/music_theory; do
|
||||
(cd "$d" && pre-commit run pylint --all-files) || echo "FAIL $d"
|
||||
done
|
||||
```
|
||||
|
||||
Command 1 prints nothing and exits 0; command 2 prints no `FAIL` line.
|
||||
|
||||
## verify
|
||||
|
||||
Desktop. Per repo, `pre-commit run --all-files` must be green — not just the
|
||||
pylint hook, since a fix that satisfies pylint can break `ruff`, `mypy` or the
|
||||
250-line cap. Then the test suite: these are behaviour-affecting edits
|
||||
(`broad-exception-caught` and `import-outside-toplevel` fixes especially), and
|
||||
every one of these packages holds a 100% coverage bar.
|
||||
|
||||
`utils` and `testsAndMisc` each have CI; push and confirm green rather than
|
||||
trusting the local run. `gatelock`'s Tk suite is flaky on a live X session —
|
||||
run it under `xvfb-run -a` and compare against a baseline worktree before
|
||||
blaming a change for a failure.
|
||||
|
||||
## read first
|
||||
|
||||
- `~/src/wake-alarm/pyproject.toml` — `[tool.pylint]`, the reference config.
|
||||
`diet-guard` is byte-similar; `build-your-x` also ignores `conftest.py`.
|
||||
- `~/.claude/memories/code-quality.md` — the suppression rule that governs
|
||||
every `disable` decision in this task.
|
||||
- `~/src/utils/rules/` is not involved; this is not a dependency change.
|
||||
|
||||
Each repo is its own git repo: commit per repo, work on `main`, stage
|
||||
narrowly. `utils` additionally runs the shared `md-naming` and file-length
|
||||
gates, so delete this file in that repo's final commit.
|
||||
|
||||
REMOVE ME AFTER FINISH
|
||||
97
agent_ready/DOCS-spec-notes.md
Normal file
97
agent_ready/DOCS-spec-notes.md
Normal file
@ -0,0 +1,97 @@
|
||||
# AgentReady spec notes
|
||||
|
||||
These notes record what the checker implements and where each rule comes from.
|
||||
Fetched 2026-10-22.
|
||||
|
||||
## Sources
|
||||
|
||||
- AgentReady v2.0 (October 2026, MIT):
|
||||
<https://github.com/agentready-org/standard/blob/main/spec/spec.md>,
|
||||
canonical site <https://agentready.org>.
|
||||
- AI Catalog (the format behind `AR-FIND-04`):
|
||||
<https://github.com/Agent-Card/ai-catalog/blob/main/specification/ai-catalog.md>.
|
||||
AgentReady defines no catalog schema of its own ("AgentReady does not
|
||||
introduce its own bespoke manifest"), so the checker uses this one.
|
||||
- llms.txt: the spec's informative "llms.txt shape" example, and <https://llmstxt.org/>.
|
||||
|
||||
## Requirements (quoted from spec.md)
|
||||
|
||||
| ID | Level | Requirement | Checker |
|
||||
|---|---|---|---|
|
||||
| AR-FIND-01 | MUST | "The site **MUST NOT** block agent and crawler access to public content, in `robots.txt` or at the network layer." | robots.txt is 200 `text/plain` and not HTML. It has a `User-agent: *` group, and no group has a blanket `Disallow: /`. In url mode the homepage returns 200 with no challenge page for ClaudeBot, GPTBot, Claude-SearchBot, OAI-SearchBot, Claude-User and ChatGPT-User. |
|
||||
| AR-FIND-02 | SHOULD | "Answers agents are expected to cite **SHOULD** be published on one canonical, current, first-party docs page." | SKIP (manual) |
|
||||
| AR-FIND-03 | SHOULD | "The site **SHOULD** list its pages in a `sitemap.xml` referenced from `robots.txt`." | robots.txt has a `Sitemap:` line. The sitemap is XML (by content type in url mode), and every `<loc>` is on the site's own host. |
|
||||
| AR-FIND-04 | MAY | "...publish an AI Catalog at `/.well-known/ai-catalog.json` listing every agent-facing resource it ships ... linked from the homepage head with `<link rel="ai-catalog">` and an HTTP `Link` header." | The catalog is valid (see the schema below) and lists `/llms.txt`. The homepage has `<link rel="ai-catalog">`. In url mode the homepage also sends a `Link: <...>; rel="ai-catalog"` header. |
|
||||
| AR-READ-01 | MUST | "The answer **MUST** be present in the initial HTML — server-rendered or prerendered, not injected by a single-page app after load." | The homepage and each sitemap page return 200 `text/html` with at least `--min-text` characters of visible body text. A page that is byte-identical to the homepage fails. An empty sitemap is a FAIL. |
|
||||
| AR-READ-02 | MUST | "...accurate HTTP status codes: `404` (or a valid redirect) for missing paths ... never a `200` for a missing page" | url mode: two random `/agentready-probe-<hex>` paths must end, after redirects, on a 404 or 410. dist mode: a `404.html` with text must exist. |
|
||||
| AR-READ-03 | SHOULD | "The homepage **SHOULD** be served as raw HTML with real links to docs, product, and pricing." | The homepage HTML has at least one `<a href>` to another page on the site. |
|
||||
| AR-READ-04 | SHOULD | "Docs pages **SHOULD** answer the tasks users bring to agents." | SKIP (manual) |
|
||||
| AR-READ-05 | SHOULD | "Code snippets **SHOULD** be fenced and language-tagged." | Every `<pre><code>` carries `language-*`, `lang-*` or `data-language`. Every fence in a markdown mirror has an info string. |
|
||||
| AR-READ-06 | SHOULD | "Discovery files (`llms.txt`, `.well-known/*`, `openapi.json`, `AGENTS.md`) **SHOULD** be linked from content agents already visit" | `/llms.txt` and the catalog (plus `/openapi.json` with `--act`) exist and are linked from the homepage, by `<link>` or `<a>`. |
|
||||
| AR-READ-07 | SHOULD | "The site **SHOULD** ship an `llms.txt`: a lean, described index of its key pages." | 200 `text/plain` or `text/markdown`, not HTML. It needs an H1 first, a `>` summary, and an `## H2` with a `- [name](url)` list; other prose is allowed. Every on-site link resolves. |
|
||||
| AR-READ-08 | SHOULD | "Key pages **SHOULD** carry JSON-LD — the homepage above all" | The homepage has a parseable `application/ld+json` block with `@context`. |
|
||||
| AR-READ-09 | MAY | "Pages **MAY** advertise a markdown mirror via `<link rel="alternate" type="text/markdown">` or an equivalent HTTP `Link:` header." | Every checked page advertises a mirror. The mirror is 200 `text/markdown` or `text/plain`, and is not HTML. |
|
||||
| AR-READ-10 | n/a | "`AR-READ-10` is retired." | not emitted |
|
||||
| AR-READ-11 | SHOULD | "Pricing **SHOULD** be published on a first-party page" | SKIP (n/a: no paid plans) |
|
||||
| AR-ACT-01 | SHOULD | auth completable by an agent; "OAuth 2.0 with discoverable metadata under `/.well-known`" | `--act`: either `oauth-protected-resource` has `resource`, or `oauth-authorization-server` has `issuer`. |
|
||||
| AR-ACT-02 | SHOULD | "A public API **SHOULD** be described by a machine-readable OpenAPI contract." | `--act`: `/openapi.json` has `openapi` and `paths`, and every operation has an `operationId`. |
|
||||
| AR-ACT-03 | SHOULD | "...expose an MCP server over Streamable HTTP at `/mcp`." | `--act`, url mode: a POST `initialize` gets a JSON-RPC result, or a 401 with `WWW-Authenticate`. |
|
||||
| AR-ACT-04 | MAY | "An MCP server **MAY** ship a server card" | `--act`: the catalog has an `application/mcp-server-card+json` entry. |
|
||||
| AR-ACT-05/06/08/09 | MAY/SHOULD | MCP Apps, SDKs+CLI, payments, NLWeb `/ask` | `--act`: SKIP (manual) |
|
||||
| AR-ACT-07 | SHOULD | "...register WebMCP tools on `document.modelContext`." | `--act`: `modelContext` appears in the homepage HTML or in its same-site scripts. |
|
||||
| AR-ACT-10 | MUST | "...**MUST** expose at least one interface an agent can act through: an MCP server (`AR-ACT-03`) or a CLI (`AR-ACT-06`)." | `--act`: same verdict as the `/mcp` probe. |
|
||||
|
||||
## kuhy's choices that are stricter than the spec
|
||||
|
||||
- Every in-scope item is required, whatever its strength. That includes the
|
||||
MAY items (FIND-04, READ-09).
|
||||
- The spec says a site "**MAY** block a training crawler". kuhy chose to allow
|
||||
training crawlers too, so a blanket `Disallow` for GPTBot, ClaudeBot or any
|
||||
other agent is a FAIL.
|
||||
- The act stage is off by default. Turn it on with `--act` only for sites with
|
||||
user actions. The spec allows this: "a purely informational site conforms on
|
||||
`AR-FIND-*` and `AR-READ-*` alone".
|
||||
|
||||
## AI Catalog schema (ai-catalog.md, specVersion 1.0)
|
||||
|
||||
- The media type is `application/ai-catalog+json`. When fetched by link
|
||||
discovery, plain `application/json` is also acceptable.
|
||||
- At the top level, the object MUST have:
|
||||
- `specVersion`: a string in "Major.Minor" form, for example `"1.0"`.
|
||||
- `entries`: an array, which may be empty.
|
||||
- The top level MAY have `host`, `extensions` and `signature`.
|
||||
- If `host` is present, it MUST have `displayName`. It MAY have
|
||||
`identifier`, `documentationUrl` and `logoUrl`.
|
||||
- Each entry MUST have:
|
||||
- `identifier`: a URI or URN. The recommended form is
|
||||
`urn:air:{publisher}:{namespace}:{name}`.
|
||||
- `type`: a media type, for example `application/mcp-server-card+json`.
|
||||
- **exactly one** of `url` or `data`.
|
||||
- `displayName` is optional on entries (ai-catalog ADR-0016).
|
||||
- Link discovery uses `Link: <...>; rel="ai-catalog"` or
|
||||
`<link rel="ai-catalog" href="..." type="application/ai-catalog+json">`.
|
||||
|
||||
Minimal valid example:
|
||||
|
||||
```json
|
||||
{"specVersion": "1.0",
|
||||
"host": {"displayName": "kuhy"},
|
||||
"entries": [{"identifier": "urn:air:kuhy.duckdns.org:docs:llms",
|
||||
"type": "text/plain", "url": "https://kuhy.duckdns.org/llms.txt"}]}
|
||||
```
|
||||
|
||||
Agentic Resource Discovery v0.91 (<https://agenticresourcediscovery.org/spec>)
|
||||
renamed the path to `/.well-known/ard.json` and the relation to `rel="ard"`.
|
||||
It keeps `ai-catalog.json` only as an optional predecessor. AgentReady v2.0
|
||||
still names `ai-catalog.json`, so that is the path the checker tests. It does
|
||||
not test `ard.json`.
|
||||
|
||||
## llms.txt shape (spec.md, informative)
|
||||
|
||||
```md
|
||||
# Acme
|
||||
> Acme ships a payments API for developers.
|
||||
|
||||
## Docs
|
||||
- [Quickstart](https://example.com/docs/quickstart): first charge in one request
|
||||
```
|
||||
93
agent_ready/README.md
Normal file
93
agent_ready/README.md
Normal file
@ -0,0 +1,93 @@
|
||||
# agent_ready
|
||||
|
||||
This tool checks kuhy's websites against [AgentReady](https://agentready.org)
|
||||
v2.0. It runs every find and read item, and the act items when you pass `--act`.
|
||||
It is Python 3 standard library only, with no dependencies.
|
||||
`DOCS-spec-notes.md` maps each `AR-*` ID to the check that tests it.
|
||||
|
||||
## Usage
|
||||
|
||||
```sh
|
||||
~/src/utils/agent_ready/check.sh dist <build-dir> [--act] [--min-text N] [--max-pages N]
|
||||
~/src/utils/agent_ready/check.sh url <base-url> [--act] [--min-text N] [--max-pages N] [--timeout S] [--budget S]
|
||||
```
|
||||
|
||||
The output is one line per check:
|
||||
|
||||
```text
|
||||
PASS AR-FIND-03 sitemap lists 12 pages
|
||||
FAIL AR-READ-02 soft 404, unknown paths must return 404: /agentready-probe-1a2b -> HTTP 200
|
||||
SKIP AR-READ-11 pricing page: n/a for sites without paid plans
|
||||
```
|
||||
|
||||
| exit | meaning |
|
||||
|---|---|
|
||||
| 0 | every check passed (SKIPs do not fail) |
|
||||
| 1 | at least one FAIL, at any strength: MUST, SHOULD or MAY |
|
||||
| 2 | usage error (bad arguments, missing directory, not an http(s) URL) |
|
||||
| 3 | network undeterminable: the homepage was unreachable, or a fetch timed out or hit the 45 s budget, and nothing failed |
|
||||
|
||||
## Pre-commit and CI (dist mode)
|
||||
|
||||
Point the checker at the build output after the build step. Dist mode checks
|
||||
that each file exists and is well-formed:
|
||||
|
||||
- robots.txt
|
||||
- sitemap.xml
|
||||
- llms.txt
|
||||
- the AI Catalog
|
||||
- 404.html
|
||||
- the text in every sitemap page's HTML
|
||||
- each page's markdown mirror
|
||||
|
||||
```yaml
|
||||
# .github/workflows/*.yml, after the build
|
||||
- run: ~/src/utils/agent_ready/check.sh dist dist/
|
||||
```
|
||||
|
||||
```yaml
|
||||
# .pre-commit-config.yaml (local hook; build first, e.g. in a wrapper script)
|
||||
- id: agent-ready
|
||||
name: AgentReady (build output)
|
||||
entry: bash -c 'pnpm build >/dev/null && ~/src/utils/agent_ready/check.sh dist dist'
|
||||
language: system
|
||||
pass_filenames: false
|
||||
```
|
||||
|
||||
Dist mode cannot check HTTP behaviour: content types, the `Link` header, real
|
||||
404 status, or responses to agent user-agents. Those checks print as SKIP, or
|
||||
the check falls back to "404.html exists".
|
||||
|
||||
## Post-deploy (url mode)
|
||||
|
||||
Run this once the deploy is live:
|
||||
|
||||
```sh
|
||||
~/src/utils/agent_ready/check.sh url https://kuhy.duckdns.org
|
||||
```
|
||||
|
||||
Url mode checks status codes **and** content types. A server that answers
|
||||
every path with `200 text/html` (an SPA fallback) fails on robots.txt, the
|
||||
sitemap, llms.txt, the catalog and the 404 probe. A status-only check would
|
||||
pass it. Url mode also checks that:
|
||||
|
||||
- `/agentready-probe-<random>` ends on a 404, after following redirects.
|
||||
- No sitemap page is byte-identical to the homepage shell.
|
||||
- The homepage answers 200 to ClaudeBot, GPTBot and the other agent
|
||||
user-agents.
|
||||
|
||||
## Tests
|
||||
|
||||
```sh
|
||||
~/.claude/scripts/capped.sh python -m pytest ~/src/utils/agent_ready/tests -q
|
||||
```
|
||||
|
||||
The test fixtures are generated in `tmp_path` by `tests/sitegen.py`, so there
|
||||
are no static mirror `.md` files to trip the markdown-naming gate. The good
|
||||
and bad build trees are served by loopback `http.server` instances in four
|
||||
shapes:
|
||||
|
||||
- compliant
|
||||
- SPA fallback
|
||||
- JSON 404 on every path
|
||||
- 403 to GPTBot
|
||||
1
agent_ready/__init__.py
Normal file
1
agent_ready/__init__.py
Normal file
@ -0,0 +1 @@
|
||||
"""AgentReady (agentready.org v2.0) compliance checker for kuhy's websites."""
|
||||
188
agent_ready/backends.py
Normal file
188
agent_ready/backends.py
Normal file
@ -0,0 +1,188 @@
|
||||
"""Two backends behind one ``get(path)``: a build directory and a live site.
|
||||
|
||||
DirSite answers like a plain static host (index.html for ``/x/``, a 404 for
|
||||
anything missing), so the find/read checks are written once for both modes.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import http.client
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from urllib.parse import unquote, urljoin, urlsplit
|
||||
|
||||
from agent_ready.report import Undeterminable
|
||||
|
||||
DEFAULT_UA = "Claude-User/1.0 (+agentready-check)"
|
||||
MAX_BODY = 5 * 1024 * 1024
|
||||
_EXT_MIME = {
|
||||
".html": "text/html",
|
||||
".md": "text/markdown",
|
||||
".txt": "text/plain",
|
||||
".xml": "application/xml",
|
||||
".json": "application/json",
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Response:
|
||||
"""A fetched resource: final status, bare media type, headers, body."""
|
||||
|
||||
status: int
|
||||
ctype: str
|
||||
body: bytes
|
||||
headers: dict[str, str] = field(default_factory=dict)
|
||||
|
||||
@property
|
||||
def text(self) -> str:
|
||||
"""Body decoded as UTF-8 (lenient)."""
|
||||
return self.body.decode("utf-8", "replace")
|
||||
|
||||
|
||||
class Site:
|
||||
"""Common URL handling; subclasses implement ``_fetch``."""
|
||||
|
||||
live = False
|
||||
|
||||
def __init__(self, origin: str) -> None:
|
||||
self.origin = origin.rstrip("/")
|
||||
self._cache: dict[tuple[str, str], Response | Undeterminable] = {}
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def to_path(self, url: str, base: str = "/") -> str | None:
|
||||
"""Site path for a URL or relative href; None when off-site."""
|
||||
absolute = urljoin(self.origin + base, url.strip())
|
||||
parts = urlsplit(absolute)
|
||||
if (
|
||||
parts.scheme not in ("http", "https")
|
||||
or parts.netloc != urlsplit(self.origin).netloc
|
||||
):
|
||||
return None
|
||||
return parts.path or "/"
|
||||
|
||||
def get(self, path: str, ua: str = DEFAULT_UA) -> Response:
|
||||
"""Fetch ``path`` (memoized, including network failures)."""
|
||||
key = (path, ua)
|
||||
with self._lock:
|
||||
hit = self._cache.get(key)
|
||||
if hit is None:
|
||||
try:
|
||||
hit = self._fetch(path, ua)
|
||||
except Undeterminable as exc:
|
||||
hit = exc
|
||||
with self._lock:
|
||||
self._cache[key] = hit
|
||||
if isinstance(hit, Undeterminable):
|
||||
raise hit
|
||||
return hit
|
||||
|
||||
def prefetch(self, paths: list[str], uas: tuple[str, ...] = (DEFAULT_UA,)) -> None:
|
||||
"""Warm the cache for every (path, ua) pair; parallel for live sites."""
|
||||
if not self.live:
|
||||
return
|
||||
pairs = [(p, ua) for p in dict.fromkeys(paths) for ua in uas]
|
||||
with ThreadPoolExecutor(max_workers=8) as pool:
|
||||
list(pool.map(lambda pair: self._safe_get(*pair), pairs))
|
||||
|
||||
def _safe_get(self, path: str, ua: str) -> None:
|
||||
try:
|
||||
self.get(path, ua)
|
||||
except Undeterminable:
|
||||
pass
|
||||
|
||||
def _fetch(self, path: str, ua: str) -> Response:
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
class DirSite(Site):
|
||||
"""A build output directory served the way a static host serves it."""
|
||||
|
||||
def __init__(self, root: Path) -> None:
|
||||
super().__init__("https://dist.invalid")
|
||||
self.root = root.resolve()
|
||||
|
||||
def file_for(self, path: str) -> Path | None:
|
||||
"""The file a static host would serve for ``path``."""
|
||||
rel = unquote(path.split("?", 1)[0]).lstrip("/")
|
||||
base = (self.root / rel).resolve()
|
||||
if not base.is_relative_to(self.root):
|
||||
return None
|
||||
cands = (
|
||||
[base / "index.html"]
|
||||
if path.endswith("/") or not rel
|
||||
else [base, base.with_name(base.name + ".html"), base / "index.html"]
|
||||
)
|
||||
return next((c for c in cands if c.is_file()), None)
|
||||
|
||||
def _fetch(self, path: str, ua: str) -> Response:
|
||||
target = self.file_for(path)
|
||||
if target is None:
|
||||
fallback = self.root / "404.html"
|
||||
body = fallback.read_bytes() if fallback.is_file() else b""
|
||||
return Response(404, "text/html", body)
|
||||
return Response(
|
||||
200,
|
||||
_EXT_MIME.get(target.suffix, "application/octet-stream"),
|
||||
target.read_bytes(),
|
||||
)
|
||||
|
||||
|
||||
class HttpSite(Site):
|
||||
"""A live site. Follows redirects; HTTP errors are responses, not raises."""
|
||||
|
||||
live = True
|
||||
|
||||
def __init__(self, base: str, timeout: float = 8.0, budget: float = 45.0) -> None:
|
||||
parts = urlsplit(base)
|
||||
super().__init__(f"{parts.scheme}://{parts.netloc}")
|
||||
self.timeout = timeout
|
||||
self.deadline = time.monotonic() + budget
|
||||
|
||||
def _remaining(self) -> float:
|
||||
left = self.deadline - time.monotonic()
|
||||
if left < 1:
|
||||
raise Undeterminable("overall time budget used up")
|
||||
return min(self.timeout, left)
|
||||
|
||||
def _fetch(self, path: str, ua: str) -> Response:
|
||||
return self.request(path, ua)
|
||||
|
||||
def request(
|
||||
self,
|
||||
path: str,
|
||||
ua: str = DEFAULT_UA,
|
||||
data: bytes | None = None,
|
||||
headers: dict[str, str] | None = None,
|
||||
) -> Response:
|
||||
"""Uncached GET (or POST when ``data`` is given)."""
|
||||
req = urllib.request.Request(
|
||||
self.origin + path,
|
||||
data=data,
|
||||
headers={"User-Agent": ua, "Accept": "*/*", **(headers or {})},
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=self._remaining()) as resp:
|
||||
return _response(resp.status, resp.headers, resp.read(MAX_BODY))
|
||||
except urllib.error.HTTPError as exc:
|
||||
return _response(exc.code, exc.headers, exc.read(MAX_BODY))
|
||||
except (
|
||||
urllib.error.URLError,
|
||||
TimeoutError,
|
||||
OSError,
|
||||
http.client.HTTPException,
|
||||
) as exc:
|
||||
raise Undeterminable(f"{path}: {getattr(exc, 'reason', exc)}") from exc
|
||||
|
||||
|
||||
def _response(status: int, headers: http.client.HTTPMessage, body: bytes) -> Response:
|
||||
"""Normalise headers: lowercase keys, repeated headers joined by ', '."""
|
||||
flat: dict[str, str] = {}
|
||||
for key in set(headers.keys()):
|
||||
flat[key.lower()] = ", ".join(headers.get_all(key) or [])
|
||||
ctype = flat.get("content-type", "").split(";", 1)[0].strip().lower()
|
||||
return Response(status, ctype, body, flat)
|
||||
137
agent_ready/check.py
Executable file
137
agent_ready/check.py
Executable file
@ -0,0 +1,137 @@
|
||||
#!/usr/bin/env python3
|
||||
"""AgentReady compliance checker (agentready.org spec v2.0).
|
||||
|
||||
check.py dist <build-dir> [--act] # pre-commit / CI: build output
|
||||
check.py url <base-url> [--act] # post-deploy: the live site
|
||||
|
||||
Prints ``PASS|FAIL|SKIP AR-XXX-NN <msg>`` per check. Exit 0 all pass, 1 any
|
||||
FAIL (every in-scope item is required, whatever its MUST/SHOULD/MAY
|
||||
strength), 2 usage error, 3 network undeterminable.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
if __package__ in (None, ""): # run as a plain script: make the package importable
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
|
||||
from agent_ready import checks_find, checks_read
|
||||
from agent_ready.backends import DirSite, HttpSite, Site
|
||||
from agent_ready.checks_act import run_act
|
||||
from agent_ready.context import HOME, Ctx
|
||||
from agent_ready.report import (
|
||||
EXIT_NETWORK,
|
||||
EXIT_USAGE,
|
||||
Report,
|
||||
Undeterminable,
|
||||
)
|
||||
|
||||
# (AR id used when a network failure aborts the check, check function)
|
||||
CHECKS: list[tuple[str, Callable[[Ctx], None]]] = [
|
||||
("AR-FIND-01", checks_find.check_robots),
|
||||
("AR-FIND-01", checks_find.check_agent_access),
|
||||
("AR-FIND-03", checks_find.check_sitemap),
|
||||
("AR-FIND-04", checks_find.check_catalog),
|
||||
("AR-READ-01", checks_read.check_pages),
|
||||
("AR-READ-02", checks_read.check_status_codes),
|
||||
("AR-READ-03", checks_read.check_homepage),
|
||||
("AR-READ-06", checks_read.check_discovery_links),
|
||||
("AR-READ-07", checks_read.check_llms),
|
||||
("AR-FIND-02", checks_read.skip_manual),
|
||||
("AR-ACT-10", run_act),
|
||||
]
|
||||
|
||||
|
||||
def parse_args(argv: list[str] | None) -> argparse.Namespace:
|
||||
"""Parse the command line (argparse exits 2 on usage errors)."""
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="agent_ready", description=__doc__.split("\n\n")[0]
|
||||
)
|
||||
sub = parser.add_subparsers(dest="mode", required=True)
|
||||
for mode, target in (
|
||||
("dist", "build output directory"),
|
||||
("url", "base URL, e.g. https://example.org"),
|
||||
):
|
||||
cmd = sub.add_parser(mode, help=f"check a {target}")
|
||||
cmd.add_argument("target", help=target)
|
||||
cmd.add_argument(
|
||||
"--act",
|
||||
action="store_true",
|
||||
help="also check the act stage (OpenAPI, MCP, auth)",
|
||||
)
|
||||
cmd.add_argument(
|
||||
"--min-text",
|
||||
type=int,
|
||||
default=100,
|
||||
help="min visible chars per page (default 100)",
|
||||
)
|
||||
cmd.add_argument(
|
||||
"--max-pages",
|
||||
type=int,
|
||||
default=40,
|
||||
help="url mode: max pages to fetch (default 40; dist checks all)",
|
||||
)
|
||||
url = sub.choices["url"]
|
||||
url.add_argument(
|
||||
"--timeout",
|
||||
type=float,
|
||||
default=8.0,
|
||||
help="per-request timeout in s (default 8)",
|
||||
)
|
||||
url.add_argument(
|
||||
"--budget",
|
||||
type=float,
|
||||
default=45.0,
|
||||
help="overall network budget in s (default 45)",
|
||||
)
|
||||
return parser.parse_args(argv)
|
||||
|
||||
|
||||
def make_site(args: argparse.Namespace) -> Site | None:
|
||||
"""Build the backend, or report a usage error and return None."""
|
||||
if args.mode == "dist":
|
||||
root = Path(args.target)
|
||||
if not root.is_dir():
|
||||
print(f"agent_ready: not a directory: {root}", file=sys.stderr)
|
||||
return None
|
||||
return DirSite(root)
|
||||
parts = urlsplit(args.target)
|
||||
if parts.scheme not in ("http", "https") or not parts.netloc:
|
||||
print(f"agent_ready: not an http(s) URL: {args.target}", file=sys.stderr)
|
||||
return None
|
||||
return HttpSite(args.target, timeout=args.timeout, budget=args.budget)
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
"""Run every check and return the exit code."""
|
||||
args = parse_args(argv)
|
||||
site = make_site(args)
|
||||
if site is None:
|
||||
return EXIT_USAGE
|
||||
report = Report(out=sys.stdout)
|
||||
ctx = Ctx(
|
||||
site=site,
|
||||
report=report,
|
||||
min_text=args.min_text,
|
||||
max_pages=args.max_pages,
|
||||
act=args.act,
|
||||
)
|
||||
try:
|
||||
site.get(HOME)
|
||||
except Undeterminable as exc:
|
||||
report.skip(
|
||||
"AR-FIND-01", f"undeterminable (network): homepage unreachable: {exc}"
|
||||
)
|
||||
return EXIT_NETWORK
|
||||
for ar_id, check in CHECKS:
|
||||
report.guard(ar_id, lambda check=check: check(ctx))
|
||||
return report.exit_code()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
10
agent_ready/check.sh
Executable file
10
agent_ready/check.sh
Executable file
@ -0,0 +1,10 @@
|
||||
#!/bin/bash
|
||||
# Thin wrapper: run the AgentReady checker from any cwd.
|
||||
# check.sh dist <build-dir> [--act]
|
||||
# check.sh url <base-url> [--act]
|
||||
# Exit codes: 0 all pass, 1 any FAIL, 2 usage error, 3 network undeterminable.
|
||||
set -euo pipefail
|
||||
|
||||
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
readonly HERE
|
||||
PYTHONPATH="$(dirname "$HERE")${PYTHONPATH:+:$PYTHONPATH}" exec python3 -m agent_ready.check "$@"
|
||||
156
agent_ready/checks_act.py
Normal file
156
agent_ready/checks_act.py
Normal file
@ -0,0 +1,156 @@
|
||||
"""Act stage: AR-ACT-01..10. Opt-in (``--act``): only for sites with user actions."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
from agent_ready import formats
|
||||
from agent_ready.backends import HttpSite
|
||||
from agent_ready.context import CATALOG, Ctx
|
||||
|
||||
_INIT = {
|
||||
"jsonrpc": "2.0",
|
||||
"id": 1,
|
||||
"method": "initialize",
|
||||
"params": {
|
||||
"protocolVersion": "2025-06-18",
|
||||
"capabilities": {},
|
||||
"clientInfo": {"name": "agentready-check", "version": "1"},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _json(ctx: Ctx, path: str) -> object | None:
|
||||
"""Parsed JSON at ``path`` when it is 200 and parses, else None."""
|
||||
resp = ctx.site.get(path)
|
||||
if resp.status != 200:
|
||||
return None
|
||||
try:
|
||||
return json.loads(resp.body)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def check_auth(ctx: Ctx) -> None:
|
||||
"""AR-ACT-01: OAuth metadata (RFC 9728 ``resource`` or RFC 8414 ``issuer``)."""
|
||||
prm = _json(ctx, "/.well-known/oauth-protected-resource")
|
||||
asm = _json(ctx, "/.well-known/oauth-authorization-server")
|
||||
ok = (isinstance(prm, dict) and "resource" in prm) or (
|
||||
isinstance(asm, dict) and "issuer" in asm
|
||||
)
|
||||
ctx.report.verdict(
|
||||
"AR-ACT-01",
|
||||
[]
|
||||
if ok
|
||||
else [
|
||||
"no OAuth metadata under /.well-known (oauth-protected-resource / oauth-authorization-server)"
|
||||
],
|
||||
"OAuth metadata discoverable under /.well-known",
|
||||
)
|
||||
|
||||
|
||||
def check_openapi(ctx: Ctx) -> None:
|
||||
"""AR-ACT-02: /openapi.json with paths and an operationId on every operation."""
|
||||
doc = _json(ctx, "/openapi.json")
|
||||
if not isinstance(doc, dict) or not isinstance(doc.get("openapi"), str):
|
||||
ctx.report.fail("AR-ACT-02", "/openapi.json missing or not an OpenAPI document")
|
||||
return
|
||||
paths = doc.get("paths") if isinstance(doc.get("paths"), dict) else {}
|
||||
ops = [
|
||||
op
|
||||
for item in paths.values()
|
||||
if isinstance(item, dict)
|
||||
for m, op in item.items()
|
||||
if m in ("get", "post", "put", "patch", "delete")
|
||||
]
|
||||
missing = sum(
|
||||
1 for op in ops if not (isinstance(op, dict) and op.get("operationId"))
|
||||
)
|
||||
problems = ["no operations in paths"] if not ops else []
|
||||
if missing:
|
||||
problems.append(f"{missing} operations lack operationId")
|
||||
ctx.report.verdict(
|
||||
"AR-ACT-02", problems, f"/openapi.json describes {len(ops)} operations"
|
||||
)
|
||||
|
||||
|
||||
def _mcp_ok(ctx: Ctx) -> bool | None:
|
||||
"""True if /mcp answers initialize (or is OAuth-gated); None in dist mode."""
|
||||
if not isinstance(ctx.site, HttpSite):
|
||||
return None
|
||||
headers = {
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json, text/event-stream",
|
||||
}
|
||||
resp = ctx.site.request("/mcp", data=json.dumps(_INIT).encode(), headers=headers)
|
||||
if resp.status == 401:
|
||||
return "www-authenticate" in resp.headers
|
||||
return resp.status == 200 and '"jsonrpc"' in resp.text and '"result"' in resp.text
|
||||
|
||||
|
||||
def check_mcp(ctx: Ctx) -> None:
|
||||
"""AR-ACT-03 MCP at /mcp, AR-ACT-04 server card, AR-ACT-10 an interface exists."""
|
||||
ok = _mcp_ok(ctx)
|
||||
if ok is None:
|
||||
ctx.report.skip("AR-ACT-03", "/mcp is a server endpoint: check in url mode")
|
||||
ctx.report.skip("AR-ACT-10", "MCP/CLI interface: check in url mode")
|
||||
else:
|
||||
ctx.report.verdict(
|
||||
"AR-ACT-03",
|
||||
[]
|
||||
if ok
|
||||
else [
|
||||
"/mcp does not answer an MCP initialize (nor 401 + WWW-Authenticate)"
|
||||
],
|
||||
"/mcp answers MCP initialize",
|
||||
)
|
||||
ctx.report.verdict(
|
||||
"AR-ACT-10",
|
||||
[]
|
||||
if ok
|
||||
else ["no MCP server at /mcp; a CLI (AR-ACT-06) cannot be auto-detected"],
|
||||
"agents can act through /mcp",
|
||||
)
|
||||
cards = [
|
||||
t
|
||||
for t in formats.catalog_types(_json(ctx, CATALOG))
|
||||
if t == "application/mcp-server-card+json"
|
||||
]
|
||||
ctx.report.verdict(
|
||||
"AR-ACT-04",
|
||||
[] if cards else ["AI Catalog lists no application/mcp-server-card+json entry"],
|
||||
"AI Catalog lists an MCP server card",
|
||||
)
|
||||
|
||||
|
||||
def check_webmcp(ctx: Ctx) -> None:
|
||||
"""AR-ACT-07: WebMCP tools registered on document.modelContext."""
|
||||
resp, page = ctx.home()
|
||||
sources = [resp.text]
|
||||
for src in page.scripts[:10]:
|
||||
path = ctx.site.to_path(src)
|
||||
if path:
|
||||
sources.append(ctx.site.get(path).text)
|
||||
found = any("modelContext" in s for s in sources)
|
||||
ctx.report.verdict(
|
||||
"AR-ACT-07",
|
||||
[] if found else ["no document.modelContext usage in homepage HTML/scripts"],
|
||||
"homepage registers WebMCP tools",
|
||||
)
|
||||
|
||||
|
||||
def run_act(ctx: Ctx) -> None:
|
||||
"""All act checks, or one SKIP line when the stage is off."""
|
||||
if not ctx.act:
|
||||
ctx.report.skip(
|
||||
"AR-ACT-10", "act stage off (pass --act for sites with user actions)"
|
||||
)
|
||||
return
|
||||
ctx.report.guard("AR-ACT-01", lambda: check_auth(ctx))
|
||||
ctx.report.guard("AR-ACT-02", lambda: check_openapi(ctx))
|
||||
ctx.report.guard("AR-ACT-03", lambda: check_mcp(ctx))
|
||||
ctx.report.guard("AR-ACT-07", lambda: check_webmcp(ctx))
|
||||
ctx.report.skip("AR-ACT-05", "MCP Apps ui:// view: manual review")
|
||||
ctx.report.skip("AR-ACT-06", "SDKs on npm/PyPI and a CLI: manual review")
|
||||
ctx.report.skip("AR-ACT-08", "agent payments: n/a unless the product charges")
|
||||
ctx.report.skip("AR-ACT-09", "NLWeb /ask endpoint: manual review")
|
||||
186
agent_ready/checks_find.py
Normal file
186
agent_ready/checks_find.py
Normal file
@ -0,0 +1,186 @@
|
||||
"""Find stage: AR-FIND-01..04 (robots.txt, agent access, sitemap, AI Catalog)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from agent_ready import formats
|
||||
from agent_ready.context import CATALOG, HOME, LLMS, Ctx, link_header_href
|
||||
from agent_ready.report import summarize
|
||||
|
||||
# Training, search-index and user-initiated fetchers named in the spec's
|
||||
# crawl-policy notes. Real UA strings for the two training crawlers.
|
||||
AGENT_UAS = {
|
||||
"ClaudeBot": "Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)",
|
||||
"GPTBot": "Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; GPTBot/1.1; +https://openai.com/gptbot)",
|
||||
"Claude-SearchBot": "Claude-SearchBot/1.0",
|
||||
"OAI-SearchBot": "OAI-SearchBot/1.0; +https://openai.com/searchbot",
|
||||
"Claude-User": "Claude-User/1.0",
|
||||
"ChatGPT-User": "ChatGPT-User/1.0; +https://openai.com/bot",
|
||||
}
|
||||
_CHALLENGE = (
|
||||
"just a moment",
|
||||
"cf-chl",
|
||||
"challenge-platform",
|
||||
"attention required",
|
||||
"captcha",
|
||||
)
|
||||
XML_TYPES = ("application/xml", "text/xml", "application/rss+xml")
|
||||
|
||||
|
||||
def check_robots(ctx: Ctx) -> None:
|
||||
"""AR-FIND-01: robots.txt exists, is plain text and blocks no agent."""
|
||||
resp = ctx.site.get("/robots.txt")
|
||||
if resp.status != 200:
|
||||
ctx.report.fail("AR-FIND-01", f"/robots.txt: HTTP {resp.status}")
|
||||
return
|
||||
problems = ctx.type_problem(resp, ("text/plain",), "/robots.txt")
|
||||
if formats.looks_like_html(resp.text):
|
||||
ctx.report.fail(
|
||||
"AR-FIND-01",
|
||||
"; ".join([*problems, "/robots.txt body is an HTML page (SPA fallback?)"]),
|
||||
)
|
||||
return
|
||||
ctx.robots_text = resp.text
|
||||
groups = formats.parse_robots(resp.text)
|
||||
if not formats.has_wildcard_group(groups):
|
||||
problems.append("no 'User-agent: *' group (spec: one rule for all agents)")
|
||||
blocked = formats.blocked_agents(groups)
|
||||
if blocked:
|
||||
problems.append(f"blanket Disallow for: {', '.join(blocked)}")
|
||||
ctx.report.verdict(
|
||||
"AR-FIND-01",
|
||||
problems,
|
||||
"robots.txt is plain text, has a * group and blocks no agent",
|
||||
)
|
||||
|
||||
|
||||
def check_agent_access(ctx: Ctx) -> None:
|
||||
"""AR-FIND-01 (bot protection): homepage is 200 for each agent UA (url mode)."""
|
||||
if not ctx.live:
|
||||
ctx.report.skip("AR-FIND-01", "agent user-agent fetches need url mode")
|
||||
return
|
||||
base, _ = ctx.home()
|
||||
ctx.site.prefetch([HOME], tuple(AGENT_UAS.values()))
|
||||
bad = []
|
||||
for name, ua in AGENT_UAS.items():
|
||||
resp = ctx.site.get(HOME, ua)
|
||||
lowered = resp.text[:20000].lower()
|
||||
if resp.status != 200:
|
||||
bad.append(f"{name} HTTP {resp.status}")
|
||||
elif resp.body != base.body and any(m in lowered for m in _CHALLENGE):
|
||||
bad.append(f"{name} got a challenge page")
|
||||
ctx.report.verdict("AR-FIND-01", bad, f"homepage 200 for {', '.join(AGENT_UAS)}")
|
||||
|
||||
|
||||
def _sitemap_paths(ctx: Ctx) -> list[str]:
|
||||
"""Sitemap locations from robots.txt (also fixes the dist-mode origin)."""
|
||||
urls = formats.robots_sitemaps(ctx.robots_text or "")
|
||||
if urls and not ctx.live:
|
||||
parts = urlsplit(urls[0])
|
||||
ctx.site.origin = f"{parts.scheme}://{parts.netloc}"
|
||||
paths = [p for u in urls if (p := ctx.site.to_path(u))]
|
||||
if ctx.robots_text is None:
|
||||
ctx.report.fail("AR-FIND-03", "no valid robots.txt to reference the sitemap")
|
||||
elif not urls:
|
||||
ctx.report.fail("AR-FIND-03", "robots.txt has no 'Sitemap:' line")
|
||||
elif not paths:
|
||||
ctx.report.fail(
|
||||
"AR-FIND-03", f"robots.txt Sitemap is on another host: {urls[0]}"
|
||||
)
|
||||
else:
|
||||
ctx.report.ok("AR-FIND-03", f"robots.txt references {summarize(urls)}")
|
||||
return paths or ["/sitemap.xml"]
|
||||
|
||||
|
||||
def _read_sitemap(ctx: Ctx, path: str, problems: list[str]) -> tuple[str, list[str]]:
|
||||
"""Fetch and parse one sitemap; record problems; return (kind, locs)."""
|
||||
resp = ctx.site.get(path)
|
||||
if resp.status != 200:
|
||||
problems.append(f"{path}: HTTP {resp.status}")
|
||||
return "", []
|
||||
problems.extend(ctx.type_problem(resp, XML_TYPES, path))
|
||||
try:
|
||||
return formats.parse_sitemap(resp.body)
|
||||
except ValueError as exc:
|
||||
problems.append(f"{path}: {exc}")
|
||||
return "", []
|
||||
|
||||
|
||||
def check_sitemap(ctx: Ctx) -> None:
|
||||
"""AR-FIND-03: sitemap referenced from robots.txt, valid XML, on-site <loc>s."""
|
||||
problems: list[str] = []
|
||||
locs: list[str] = []
|
||||
for path in _sitemap_paths(ctx)[:5]:
|
||||
kind, found = _read_sitemap(ctx, path, problems)
|
||||
if kind == "sitemapindex":
|
||||
for child in [p for u in found[:10] if (p := ctx.site.to_path(u))]:
|
||||
locs += _read_sitemap(ctx, child, problems)[1]
|
||||
else:
|
||||
locs += found
|
||||
if locs and not ctx.live and ctx.site.origin.endswith("dist.invalid"):
|
||||
parts = urlsplit(locs[0])
|
||||
ctx.site.origin = f"{parts.scheme}://{parts.netloc}"
|
||||
pages = [p for loc in locs if (p := ctx.site.to_path(loc))]
|
||||
if len(pages) < len(locs):
|
||||
problems.append(
|
||||
f"{len(locs) - len(pages)} <loc> URLs are not on {ctx.site.origin}"
|
||||
)
|
||||
if not locs and not problems:
|
||||
problems.append("sitemap has no <loc> entries")
|
||||
ctx.sitemap_pages = list(dict.fromkeys(pages))
|
||||
ctx.report.verdict(
|
||||
"AR-FIND-03", problems, f"sitemap lists {len(ctx.sitemap_pages)} pages"
|
||||
)
|
||||
|
||||
|
||||
def check_catalog(ctx: Ctx) -> None:
|
||||
"""AR-FIND-04: valid AI Catalog, lists llms.txt, linked from homepage head."""
|
||||
resp = ctx.site.get(CATALOG)
|
||||
problems: list[str] = []
|
||||
if resp.status != 200:
|
||||
problems.append(f"{CATALOG}: HTTP {resp.status}")
|
||||
else:
|
||||
problems += ctx.type_problem(
|
||||
resp, ("application/ai-catalog+json", "application/json"), CATALOG
|
||||
)
|
||||
try:
|
||||
doc = json.loads(resp.body)
|
||||
except ValueError:
|
||||
doc = None
|
||||
problems.append(f"{CATALOG} is not JSON")
|
||||
if doc is not None:
|
||||
problems += formats.catalog_problems(doc)
|
||||
listed = {ctx.site.to_path(u) for u in formats.catalog_urls(doc)}
|
||||
if ctx.exists(LLMS) and LLMS not in listed:
|
||||
problems.append("catalog has no entry for /llms.txt")
|
||||
ctx.report.verdict("AR-FIND-04", problems, f"{CATALOG} is a valid AI Catalog")
|
||||
home, scan = ctx.home()
|
||||
href = scan.link_href("ai-catalog")
|
||||
ok = href is not None and ctx.site.to_path(href) == CATALOG
|
||||
ctx.report.verdict(
|
||||
"AR-FIND-04",
|
||||
[]
|
||||
if ok
|
||||
else [
|
||||
'homepage head lacks <link rel="ai-catalog" href="/.well-known/ai-catalog.json">'
|
||||
],
|
||||
"homepage head links the catalog",
|
||||
)
|
||||
if not ctx.live:
|
||||
ctx.report.skip(
|
||||
"AR-FIND-04", "HTTP Link header can only be checked in url mode"
|
||||
)
|
||||
return
|
||||
header = link_header_href(home, "ai-catalog")
|
||||
ok = header is not None and ctx.site.to_path(header) == CATALOG
|
||||
ctx.report.verdict(
|
||||
"AR-FIND-04",
|
||||
[]
|
||||
if ok
|
||||
else [
|
||||
'homepage response lacks HTTP header Link: <...ai-catalog.json>; rel="ai-catalog"'
|
||||
],
|
||||
"homepage sends the ai-catalog Link header",
|
||||
)
|
||||
212
agent_ready/checks_read.py
Normal file
212
agent_ready/checks_read.py
Normal file
@ -0,0 +1,212 @@
|
||||
"""Read stage: AR-READ-01..09 and 11 (AR-READ-10 is retired in spec v2.0)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import secrets
|
||||
|
||||
from agent_ready import formats
|
||||
from agent_ready.context import CATALOG, HOME, LLMS, TEXT_TYPES, Ctx, link_header_href
|
||||
from agent_ready.htmlscan import scan
|
||||
from agent_ready.report import summarize
|
||||
|
||||
|
||||
def _pages(ctx: Ctx) -> list[str]:
|
||||
"""Homepage plus sitemap pages, capped. An empty sitemap is a READ-01 FAIL."""
|
||||
if not ctx.sitemap_pages:
|
||||
ctx.report.fail(
|
||||
"AR-READ-01", "sitemap yielded no pages; only the homepage was checked"
|
||||
)
|
||||
every = list(dict.fromkeys([HOME, *ctx.sitemap_pages]))
|
||||
pages = ctx.cap(every)
|
||||
if len(pages) < len(every):
|
||||
ctx.report.skip(
|
||||
"AR-READ-01",
|
||||
f"checked {len(pages)} of {len(every)} pages (--max-pages); rest unchecked",
|
||||
)
|
||||
ctx.site.prefetch(pages)
|
||||
return pages
|
||||
|
||||
|
||||
def _mirror_href(ctx: Ctx, path: str) -> str | None:
|
||||
"""Markdown mirror advertised by <link rel=alternate type=text/markdown> or Link header."""
|
||||
resp, page = ctx.page(path)
|
||||
href = page.link_href("alternate", "text/markdown")
|
||||
if href is None and ctx.live:
|
||||
href = link_header_href(resp, "alternate", "text/markdown")
|
||||
return href
|
||||
|
||||
|
||||
def check_pages(ctx: Ctx) -> None:
|
||||
"""AR-READ-01 text in initial HTML, AR-READ-05 tagged code, AR-READ-09 mirrors."""
|
||||
pages = _pages(ctx)
|
||||
home, _ = ctx.home()
|
||||
no_text: list[str] = []
|
||||
untagged: list[str] = []
|
||||
blocks = 0
|
||||
for path in pages:
|
||||
resp, page = ctx.page(path)
|
||||
if resp.status != 200:
|
||||
no_text.append(f"{path} (HTTP {resp.status})")
|
||||
continue
|
||||
if ctx.type_problem(resp, ("text/html",), path):
|
||||
no_text.append(f"{path} ({resp.ctype or 'no content-type'})")
|
||||
elif path != HOME and resp.body == home.body:
|
||||
no_text.append(f"{path} (byte-identical to the homepage shell)")
|
||||
elif len(page.text) < ctx.min_text:
|
||||
no_text.append(f"{path} ({len(page.text)} chars of text < {ctx.min_text})")
|
||||
blocks += page.code_blocks
|
||||
if page.untagged_code:
|
||||
untagged.append(f"{path} ({page.untagged_code} untagged <pre><code>)")
|
||||
ctx.report.verdict(
|
||||
"AR-READ-01",
|
||||
["answer not in initial HTML: " + summarize(no_text)] if no_text else [],
|
||||
f"{len(pages)} pages carry >= {ctx.min_text} chars of text without JS",
|
||||
)
|
||||
md_untagged = _check_mirrors(ctx, pages)
|
||||
untagged += md_untagged
|
||||
ctx.report.verdict(
|
||||
"AR-READ-05",
|
||||
["code without a language tag: " + summarize(untagged)] if untagged else [],
|
||||
f"{blocks} HTML code blocks (plus mirror fences) all language-tagged",
|
||||
)
|
||||
|
||||
|
||||
def _check_mirrors(ctx: Ctx, pages: list[str]) -> list[str]:
|
||||
"""AR-READ-09 for every page; returns mirrors with untagged fences (READ-05)."""
|
||||
bad: list[str] = []
|
||||
untagged: list[str] = []
|
||||
targets: dict[str, str] = {}
|
||||
for path in pages:
|
||||
if ctx.site.get(path).status != 200:
|
||||
continue
|
||||
href = _mirror_href(ctx, path)
|
||||
target = ctx.site.to_path(href, path) if href else None
|
||||
if target is None:
|
||||
bad.append(f"{path} (no text/markdown alternate link)")
|
||||
else:
|
||||
targets[path] = target
|
||||
ctx.site.prefetch(list(targets.values()))
|
||||
for path, target in targets.items():
|
||||
resp = ctx.site.get(target)
|
||||
if resp.status != 200:
|
||||
bad.append(f"{target} (HTTP {resp.status})")
|
||||
elif (
|
||||
ctx.type_problem(resp, TEXT_TYPES, target)
|
||||
or formats.looks_like_html(resp.text)
|
||||
or not resp.text.strip()
|
||||
):
|
||||
bad.append(f"{target} (not markdown: {resp.ctype or 'empty'})")
|
||||
elif n := formats.untagged_fences(resp.text):
|
||||
untagged.append(f"{target} ({n} untagged fences)")
|
||||
ctx.report.verdict(
|
||||
"AR-READ-09",
|
||||
["markdown mirror missing/broken: " + summarize(bad)] if bad else [],
|
||||
f"{len(targets)} pages advertise a working markdown mirror",
|
||||
)
|
||||
return untagged
|
||||
|
||||
|
||||
def check_status_codes(ctx: Ctx) -> None:
|
||||
"""AR-READ-02: unknown paths are a real 404 (url) / a 404.html exists (dist)."""
|
||||
if not ctx.live:
|
||||
resp = ctx.site.get(f"/agentready-probe-{secrets.token_hex(6)}")
|
||||
text = scan(resp.text).text if resp.body else ""
|
||||
ok = resp.status == 404 and len(text) >= 10
|
||||
ctx.report.verdict(
|
||||
"AR-READ-02",
|
||||
[] if ok else ["no 404.html with real text in the build output"],
|
||||
"404.html exists for unknown paths",
|
||||
)
|
||||
return
|
||||
token = secrets.token_hex(6)
|
||||
probes = [f"/agentready-probe-{token}", f"/agentready-probe-{token}/page.html"]
|
||||
ctx.site.prefetch(probes)
|
||||
bad = [
|
||||
f"{p} -> HTTP {s}"
|
||||
for p in probes
|
||||
if (s := ctx.site.get(p).status) not in (404, 410)
|
||||
]
|
||||
ctx.report.verdict(
|
||||
"AR-READ-02",
|
||||
["soft 404, unknown paths must return 404: " + ", ".join(bad)] if bad else [],
|
||||
"unknown paths return 404",
|
||||
)
|
||||
|
||||
|
||||
def check_homepage(ctx: Ctx) -> None:
|
||||
"""AR-READ-03 real links on the homepage, AR-READ-08 JSON-LD on it."""
|
||||
resp, page = ctx.home()
|
||||
links = {
|
||||
p
|
||||
for a in page.anchors
|
||||
if not a.startswith(("#", "javascript:", "mailto:"))
|
||||
and (p := ctx.site.to_path(a))
|
||||
and p != HOME
|
||||
}
|
||||
ok = resp.status == 200 and bool(links)
|
||||
ctx.report.verdict(
|
||||
"AR-READ-03",
|
||||
[] if ok else ["homepage HTML has no <a href> links to other pages"],
|
||||
f"homepage links {len(links)} pages in raw HTML",
|
||||
)
|
||||
problems = []
|
||||
if not page.jsonld_ok:
|
||||
problems.append(
|
||||
'homepage has no <script type="application/ld+json"> with @context'
|
||||
)
|
||||
if page.jsonld_bad:
|
||||
problems.append(
|
||||
f"{page.jsonld_bad} JSON-LD blocks fail to parse or lack @context"
|
||||
)
|
||||
ctx.report.verdict(
|
||||
"AR-READ-08", problems, f"homepage carries {page.jsonld_ok} JSON-LD blocks"
|
||||
)
|
||||
|
||||
|
||||
def check_discovery_links(ctx: Ctx) -> None:
|
||||
"""AR-READ-06: discovery files are linked from the homepage."""
|
||||
_, page = ctx.home()
|
||||
linked = {
|
||||
ctx.site.to_path(h)
|
||||
for h in [*page.anchors, *(href for _, _, href in page.links)]
|
||||
}
|
||||
files = [LLMS, CATALOG] + (["/openapi.json"] if ctx.act else [])
|
||||
for path in files:
|
||||
problems = []
|
||||
if not ctx.exists(path):
|
||||
problems.append(f"{path} does not exist")
|
||||
if path not in linked:
|
||||
problems.append(f"{path} is not linked from the homepage (<link> or <a>)")
|
||||
ctx.report.verdict(
|
||||
"AR-READ-06", problems, f"{path} exists and is linked from the homepage"
|
||||
)
|
||||
|
||||
|
||||
def check_llms(ctx: Ctx) -> None:
|
||||
"""AR-READ-07: llms.txt in the spec shape, every on-site link resolving."""
|
||||
resp = ctx.site.get(LLMS)
|
||||
if resp.status != 200:
|
||||
ctx.report.fail("AR-READ-07", f"{LLMS}: HTTP {resp.status}")
|
||||
return
|
||||
problems = ctx.type_problem(resp, TEXT_TYPES, LLMS) + formats.llms_problems(
|
||||
resp.text
|
||||
)
|
||||
if not formats.looks_like_html(resp.text):
|
||||
paths = [
|
||||
p for u in formats.llms_links(resp.text) if (p := ctx.site.to_path(u, LLMS))
|
||||
]
|
||||
paths = ctx.cap(paths)
|
||||
ctx.site.prefetch(paths)
|
||||
broken = [p for p in paths if ctx.site.get(p).status != 200]
|
||||
if broken:
|
||||
problems.append("broken links: " + summarize(broken))
|
||||
ctx.report.verdict("AR-READ-07", problems, f"{LLMS} has H1, summary and link lists")
|
||||
|
||||
|
||||
def skip_manual(ctx: Ctx) -> None:
|
||||
"""Items with no mechanical check (reported, never silently dropped)."""
|
||||
ctx.report.skip(
|
||||
"AR-FIND-02", "first-party docs page answering user questions: manual review"
|
||||
)
|
||||
ctx.report.skip("AR-READ-04", "docs pages answer users' tasks: manual review")
|
||||
ctx.report.skip("AR-READ-11", "pricing page: n/a for sites without paid plans")
|
||||
85
agent_ready/context.py
Normal file
85
agent_ready/context.py
Normal file
@ -0,0 +1,85 @@
|
||||
"""Shared state for one checker run (site, report, options, discoveries)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from agent_ready.backends import Response, Site
|
||||
from agent_ready.formats import looks_like_html
|
||||
from agent_ready.htmlscan import PageScan, scan
|
||||
from agent_ready.report import Report
|
||||
|
||||
HOME = "/"
|
||||
LLMS = "/llms.txt"
|
||||
CATALOG = "/.well-known/ai-catalog.json"
|
||||
TEXT_TYPES = ("text/plain", "text/markdown")
|
||||
|
||||
|
||||
@dataclass
|
||||
class Ctx:
|
||||
"""Everything a check needs; filled in as checks discover the site."""
|
||||
|
||||
site: Site
|
||||
report: Report
|
||||
min_text: int = 100
|
||||
max_pages: int = 40
|
||||
act: bool = False
|
||||
robots_text: str | None = None
|
||||
sitemap_pages: list[str] = field(default_factory=list)
|
||||
_scans: dict[str, PageScan] = field(default_factory=dict)
|
||||
|
||||
@property
|
||||
def live(self) -> bool:
|
||||
"""True in url mode (headers and content types are real)."""
|
||||
return self.site.live
|
||||
|
||||
def cap(self, items: list[str]) -> list[str]:
|
||||
"""Apply --max-pages in url mode only; dist mode is free, so check everything."""
|
||||
return items[: self.max_pages] if self.live else items
|
||||
|
||||
def page(self, path: str) -> tuple[Response, PageScan]:
|
||||
"""Fetch and scan an HTML page (scan memoized)."""
|
||||
resp = self.site.get(path)
|
||||
if path not in self._scans:
|
||||
self._scans[path] = scan(resp.text) if resp.status == 200 else PageScan()
|
||||
return resp, self._scans[path]
|
||||
|
||||
def home(self) -> tuple[Response, PageScan]:
|
||||
"""The homepage and its scan."""
|
||||
return self.page(HOME)
|
||||
|
||||
def type_problem(
|
||||
self, resp: Response, allowed: tuple[str, ...], what: str
|
||||
) -> list[str]:
|
||||
"""Content-type problem for live responses (dist mode has none)."""
|
||||
if (
|
||||
not self.live
|
||||
or resp.ctype in allowed
|
||||
or any(a.endswith("+xml") and resp.ctype.endswith("+xml") for a in allowed)
|
||||
):
|
||||
return []
|
||||
return [
|
||||
f"{what} served as {resp.ctype or 'no content-type'}, want {' or '.join(allowed)}"
|
||||
]
|
||||
|
||||
def exists(self, path: str) -> bool:
|
||||
"""True when ``path`` is 200 and, for a non-page file, not an HTML fallback."""
|
||||
resp = self.site.get(path)
|
||||
is_page = path.endswith(("/", ".html"))
|
||||
return resp.status == 200 and (is_page or not looks_like_html(resp.text))
|
||||
|
||||
|
||||
def link_header_href(resp: Response, rel: str, mime: str | None = None) -> str | None:
|
||||
"""href of the first RFC 8288 ``Link`` header value with ``rel`` (and type)."""
|
||||
for part in re.split(r",\s*(?=<)", resp.headers.get("link", "")):
|
||||
match = re.match(r"\s*<([^>]*)>(.*)", part)
|
||||
if not match:
|
||||
continue
|
||||
params = match.group(2).lower()
|
||||
rels = re.search(r'rel="?([^";]+)"?', params)
|
||||
if not rels or rel not in rels.group(1).split():
|
||||
continue
|
||||
if mime is None or re.search(rf'type="?{re.escape(mime)}"?', params):
|
||||
return match.group(1)
|
||||
return None
|
||||
213
agent_ready/formats.py
Normal file
213
agent_ready/formats.py
Normal file
@ -0,0 +1,213 @@
|
||||
"""Validators for the file formats AgentReady points at.
|
||||
|
||||
robots.txt (RFC 9309), sitemap.xml (sitemaps.org), llms.txt (agentready
|
||||
spec "llms.txt shape" / llmstxt.org) and the AI Catalog
|
||||
(github.com/Agent-Card/ai-catalog, specification/ai-catalog.md).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import xml.etree.ElementTree as ET
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
_LINK_ITEM = re.compile(r"^\s*[-*]\s+\[[^\]]+\]\(([^)\s]+)\)")
|
||||
_FENCE = re.compile(r"^\s{0,3}(```+|~~~+)\s*(\S*)")
|
||||
_SPEC_VERSION = re.compile(r"^\d+\.\d+$")
|
||||
|
||||
|
||||
def looks_like_html(text: str) -> bool:
|
||||
"""True when a supposedly plain-text/XML/JSON body is an HTML page."""
|
||||
head = text.lstrip()[:200].lower()
|
||||
return head.startswith(("<!doctype html", "<html")) or "<head" in head
|
||||
|
||||
|
||||
# --------------------------------------------------------------- robots.txt
|
||||
@dataclass
|
||||
class RobotsGroup:
|
||||
"""One ``User-agent`` group and its rules, in file order."""
|
||||
|
||||
agents: list[str] = field(default_factory=list)
|
||||
rules: list[tuple[str, str]] = field(default_factory=list)
|
||||
|
||||
|
||||
def parse_robots(text: str) -> list[RobotsGroup]:
|
||||
"""Parse robots.txt into groups (consecutive User-agent lines share one)."""
|
||||
groups: list[RobotsGroup] = []
|
||||
current: RobotsGroup | None = None
|
||||
for raw in text.splitlines():
|
||||
line = raw.split("#", 1)[0].strip()
|
||||
if ":" not in line:
|
||||
continue
|
||||
key, value = (part.strip() for part in line.split(":", 1))
|
||||
key = key.lower()
|
||||
if key == "user-agent":
|
||||
if current is None or current.rules:
|
||||
current = RobotsGroup()
|
||||
groups.append(current)
|
||||
current.agents.append(value.lower())
|
||||
elif key in ("allow", "disallow") and current is not None:
|
||||
current.rules.append((key, value))
|
||||
return groups
|
||||
|
||||
|
||||
def has_wildcard_group(groups: list[RobotsGroup]) -> bool:
|
||||
"""True when a ``User-agent: *`` group exists (one rule for all agents)."""
|
||||
return any("*" in g.agents for g in groups)
|
||||
|
||||
|
||||
def blocked_agents(groups: list[RobotsGroup]) -> list[str]:
|
||||
"""Agents whose group disallows the whole site (``/`` or ``/*``).
|
||||
|
||||
An empty ``Disallow:`` allows everything; an ``Allow: /`` in the same
|
||||
group wins over the blanket disallow (longest-match tie goes to allow).
|
||||
"""
|
||||
blocked: list[str] = []
|
||||
for group in groups:
|
||||
disallow_all = any(k == "disallow" and v in ("/", "/*") for k, v in group.rules)
|
||||
allow_all = any(k == "allow" and v in ("/", "/*") for k, v in group.rules)
|
||||
if disallow_all and not allow_all:
|
||||
blocked.extend(group.agents)
|
||||
return blocked
|
||||
|
||||
|
||||
def robots_sitemaps(text: str) -> list[str]:
|
||||
"""Return every ``Sitemap:`` URL."""
|
||||
out = []
|
||||
for raw in text.splitlines():
|
||||
key, _, value = raw.partition(":")
|
||||
if key.strip().lower() == "sitemap" and value.strip():
|
||||
out.append(value.strip())
|
||||
return out
|
||||
|
||||
|
||||
# -------------------------------------------------------------- sitemap.xml
|
||||
def parse_sitemap(body: bytes) -> tuple[str, list[str]]:
|
||||
"""Return (root kind ``urlset``/``sitemapindex``, list of <loc> values).
|
||||
|
||||
Raises ValueError for anything that is not a sitemap document.
|
||||
"""
|
||||
try:
|
||||
root = ET.fromstring(body)
|
||||
except ET.ParseError as exc:
|
||||
raise ValueError(f"not XML: {exc}") from exc
|
||||
kind = root.tag.rsplit("}", 1)[-1]
|
||||
if kind not in ("urlset", "sitemapindex"):
|
||||
raise ValueError(f"root element <{kind}> is not <urlset>/<sitemapindex>")
|
||||
locs = [
|
||||
(el.text or "").strip()
|
||||
for el in root.iter()
|
||||
if el.tag.rsplit("}", 1)[-1] == "loc"
|
||||
]
|
||||
return kind, [loc for loc in locs if loc]
|
||||
|
||||
|
||||
# ----------------------------------------------------------------- llms.txt
|
||||
def llms_problems(text: str) -> list[str]:
|
||||
"""Check llms.txt shape: H1 first, blockquote summary, H2 link lists."""
|
||||
if looks_like_html(text):
|
||||
return ["body is an HTML page, not llms.txt markdown"]
|
||||
lines = [ln for ln in text.splitlines() if ln.strip()]
|
||||
problems = []
|
||||
if not lines or not re.match(r"^# \S", lines[0]):
|
||||
problems.append("first line must be an H1 title ('# Name')")
|
||||
if not any(ln.startswith(">") for ln in lines[:4]):
|
||||
problems.append("missing blockquote summary ('> ...') after the H1")
|
||||
in_h2 = False
|
||||
links = 0
|
||||
for ln in lines:
|
||||
if ln.startswith("## "):
|
||||
in_h2 = True
|
||||
elif in_h2 and _LINK_ITEM.match(ln):
|
||||
links += 1
|
||||
if links == 0:
|
||||
problems.append("no '## Section' with a '- [name](url): notes' link list")
|
||||
return problems
|
||||
|
||||
|
||||
def llms_links(text: str) -> list[str]:
|
||||
"""Return every link-list URL in llms.txt, in order."""
|
||||
return [m.group(1) for ln in text.splitlines() if (m := _LINK_ITEM.match(ln))]
|
||||
|
||||
|
||||
# --------------------------------------------------------------- ai-catalog
|
||||
def catalog_problems(doc: object) -> list[str]:
|
||||
"""Validate an AI Catalog (Level 1 + Host Info if present)."""
|
||||
if not isinstance(doc, dict):
|
||||
return ["top level must be a JSON object"]
|
||||
problems = []
|
||||
version = doc.get("specVersion")
|
||||
if not isinstance(version, str):
|
||||
problems.append("missing string specVersion")
|
||||
elif not _SPEC_VERSION.match(version):
|
||||
problems.append(f"specVersion {version!r} is not 'Major.Minor'")
|
||||
host = doc.get("host")
|
||||
if host is not None and not (
|
||||
isinstance(host, dict) and isinstance(host.get("displayName"), str)
|
||||
):
|
||||
problems.append("host.displayName (string) is required when host is present")
|
||||
entries = doc.get("entries")
|
||||
if not isinstance(entries, list):
|
||||
return [*problems, "missing entries array"]
|
||||
for i, entry in enumerate(entries):
|
||||
problems.extend(f"entries[{i}]: {p}" for p in _entry_problems(entry))
|
||||
return problems
|
||||
|
||||
|
||||
def _entry_problems(entry: object) -> list[str]:
|
||||
"""Problems with one Catalog Entry."""
|
||||
if not isinstance(entry, dict):
|
||||
return ["must be an object"]
|
||||
problems = [
|
||||
f"missing string {k}"
|
||||
for k in ("identifier", "type")
|
||||
if not isinstance(entry.get(k), str)
|
||||
]
|
||||
if ("url" in entry) == ("data" in entry):
|
||||
problems.append("must carry exactly one of url/data")
|
||||
return problems
|
||||
|
||||
|
||||
def catalog_urls(doc: object) -> list[str]:
|
||||
"""Every entry ``url`` in a catalog (empty for invalid docs)."""
|
||||
if not isinstance(doc, dict) or not isinstance(doc.get("entries"), list):
|
||||
return []
|
||||
return [
|
||||
e["url"]
|
||||
for e in doc["entries"]
|
||||
if isinstance(e, dict) and isinstance(e.get("url"), str)
|
||||
]
|
||||
|
||||
|
||||
def catalog_types(doc: object) -> list[str]:
|
||||
"""Every entry ``type`` in a catalog."""
|
||||
if not isinstance(doc, dict) or not isinstance(doc.get("entries"), list):
|
||||
return []
|
||||
return [
|
||||
e["type"]
|
||||
for e in doc["entries"]
|
||||
if isinstance(e, dict) and isinstance(e.get("type"), str)
|
||||
]
|
||||
|
||||
|
||||
# ----------------------------------------------------------------- markdown
|
||||
def untagged_fences(text: str) -> int:
|
||||
"""Count opening code fences with no language info string."""
|
||||
count = 0
|
||||
open_fence = ""
|
||||
for line in text.splitlines():
|
||||
match = _FENCE.match(line)
|
||||
if not match:
|
||||
continue
|
||||
marker, info = match.groups()
|
||||
if open_fence:
|
||||
if (
|
||||
marker[0] == open_fence[0]
|
||||
and len(marker) >= len(open_fence)
|
||||
and not info
|
||||
):
|
||||
open_fence = ""
|
||||
continue
|
||||
open_fence = marker
|
||||
count += not info
|
||||
return count
|
||||
121
agent_ready/htmlscan.py
Normal file
121
agent_ready/htmlscan.py
Normal file
@ -0,0 +1,121 @@
|
||||
"""One-pass HTML scan: visible body text, links, JSON-LD and code blocks."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
from html.parser import HTMLParser
|
||||
|
||||
_HIDDEN = {"script", "style", "noscript", "template", "svg", "head", "title"}
|
||||
_LANG = re.compile(r"\b(language|lang)-\S+")
|
||||
|
||||
|
||||
@dataclass
|
||||
class PageScan:
|
||||
"""What an agent that does not run JavaScript sees in a page."""
|
||||
|
||||
text: str = ""
|
||||
links: list[tuple[set[str], str, str]] = field(default_factory=list)
|
||||
anchors: list[str] = field(default_factory=list)
|
||||
scripts: list[str] = field(default_factory=list)
|
||||
jsonld_ok: int = 0
|
||||
jsonld_bad: int = 0
|
||||
code_blocks: int = 0
|
||||
untagged_code: int = 0
|
||||
|
||||
def link_href(self, rel: str, mime: str | None = None) -> str | None:
|
||||
"""First ``<link>`` href with ``rel`` (and ``type`` if given)."""
|
||||
for rels, typ, href in self.links:
|
||||
if rel in rels and (mime is None or typ == mime):
|
||||
return href
|
||||
return None
|
||||
|
||||
|
||||
def _tagged(attrs: dict[str, str]) -> bool:
|
||||
"""True when an element carries a code-language marker."""
|
||||
return bool(_LANG.search(attrs.get("class", ""))) or bool(
|
||||
attrs.get("data-language") or attrs.get("data-lang")
|
||||
)
|
||||
|
||||
|
||||
class _Scanner(HTMLParser):
|
||||
def __init__(self) -> None:
|
||||
super().__init__(convert_charrefs=True)
|
||||
self.out = PageScan()
|
||||
self._hidden: list[str] = []
|
||||
self._text: list[str] = []
|
||||
self._pre: list[list[bool]] = [] # [pre_tagged, code_seen]
|
||||
self._ld: list[str] | None = None
|
||||
|
||||
def handle_starttag(
|
||||
self, tag: str, attr_list: list[tuple[str, str | None]]
|
||||
) -> None:
|
||||
attrs = {k: v or "" for k, v in attr_list}
|
||||
if tag == "body": # </head> is optional in HTML; <body> always ends it
|
||||
self._hidden = [h for h in self._hidden if h not in ("head", "title")]
|
||||
if tag == "link" and attrs.get("href"):
|
||||
rels = set(attrs.get("rel", "").lower().split())
|
||||
self.out.links.append((rels, attrs.get("type", "").lower(), attrs["href"]))
|
||||
elif tag == "a" and attrs.get("href"):
|
||||
self.out.anchors.append(attrs["href"])
|
||||
elif tag == "script":
|
||||
if attrs.get("src"):
|
||||
self.out.scripts.append(attrs["src"])
|
||||
if attrs.get("type", "").lower() == "application/ld+json":
|
||||
self._ld = []
|
||||
elif tag == "pre":
|
||||
self._pre.append([_tagged(attrs), False])
|
||||
elif tag == "code" and self._pre and not self._pre[-1][1]:
|
||||
self._pre[-1][1] = True
|
||||
self.out.code_blocks += 1
|
||||
self.out.untagged_code += not (self._pre[-1][0] or _tagged(attrs))
|
||||
if tag in _HIDDEN:
|
||||
self._hidden.append(tag)
|
||||
|
||||
def handle_endtag(self, tag: str) -> None:
|
||||
if tag == "script" and self._ld is not None:
|
||||
self._finish_ld("".join(self._ld))
|
||||
self._ld = None
|
||||
if tag == "pre" and self._pre:
|
||||
self._pre.pop()
|
||||
if tag in _HIDDEN and tag in self._hidden:
|
||||
while self._hidden and self._hidden.pop() != tag:
|
||||
pass
|
||||
|
||||
def handle_data(self, data: str) -> None:
|
||||
if self._ld is not None:
|
||||
self._ld.append(data)
|
||||
elif not self._hidden:
|
||||
self._text.append(data)
|
||||
|
||||
def _finish_ld(self, raw: str) -> None:
|
||||
try:
|
||||
doc = json.loads(raw)
|
||||
except ValueError:
|
||||
self.out.jsonld_bad += 1
|
||||
return
|
||||
nodes = doc if isinstance(doc, list) else [doc]
|
||||
ok = (
|
||||
all(
|
||||
isinstance(n, dict) and ("@context" in n or "@graph" in n)
|
||||
for n in nodes
|
||||
)
|
||||
and nodes
|
||||
)
|
||||
if ok:
|
||||
self.out.jsonld_ok += 1
|
||||
else:
|
||||
self.out.jsonld_bad += 1
|
||||
|
||||
def result(self) -> PageScan:
|
||||
self.out.text = re.sub(r"\s+", " ", " ".join(self._text)).strip()
|
||||
return self.out
|
||||
|
||||
|
||||
def scan(html: str) -> PageScan:
|
||||
"""Scan an HTML document."""
|
||||
parser = _Scanner()
|
||||
parser.feed(html)
|
||||
parser.close()
|
||||
return parser.result()
|
||||
73
agent_ready/report.py
Normal file
73
agent_ready/report.py
Normal file
@ -0,0 +1,73 @@
|
||||
"""Result lines (``PASS|FAIL|SKIP AR-XXX-NN msg``) and the exit-code policy."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass, field
|
||||
from typing import TextIO
|
||||
|
||||
EXIT_OK, EXIT_FAIL, EXIT_USAGE, EXIT_NETWORK = 0, 1, 2, 3
|
||||
|
||||
|
||||
class Undeterminable(Exception):
|
||||
"""A network-level failure (refused, timeout, deadline): no verdict."""
|
||||
|
||||
|
||||
@dataclass
|
||||
class Report:
|
||||
"""Collects check lines and decides the exit code.
|
||||
|
||||
Every in-scope item is required for kuhy's sites, so a FAIL of any
|
||||
strength (MUST/SHOULD/MAY) fails the run. SKIP never fails it.
|
||||
"""
|
||||
|
||||
out: TextIO = field(default_factory=lambda: sys.stdout)
|
||||
fails: int = 0
|
||||
undetermined: int = 0
|
||||
|
||||
def emit(self, status: str, ar_id: str, msg: str) -> None:
|
||||
"""Print one result line."""
|
||||
if status == "FAIL":
|
||||
self.fails += 1
|
||||
print(f"{status} {ar_id} {msg}", file=self.out, flush=True)
|
||||
|
||||
def ok(self, ar_id: str, msg: str) -> None:
|
||||
"""Emit PASS."""
|
||||
self.emit("PASS", ar_id, msg)
|
||||
|
||||
def fail(self, ar_id: str, msg: str) -> None:
|
||||
"""Emit FAIL."""
|
||||
self.emit("FAIL", ar_id, msg)
|
||||
|
||||
def skip(self, ar_id: str, msg: str) -> None:
|
||||
"""Emit SKIP."""
|
||||
self.emit("SKIP", ar_id, msg)
|
||||
|
||||
def verdict(self, ar_id: str, problems: list[str], pass_msg: str) -> bool:
|
||||
"""FAIL with the problems joined, or PASS with ``pass_msg``."""
|
||||
if problems:
|
||||
self.fail(ar_id, "; ".join(problems))
|
||||
return False
|
||||
self.ok(ar_id, pass_msg)
|
||||
return True
|
||||
|
||||
def guard(self, ar_id: str, fn: Callable[[], object]) -> None:
|
||||
"""Run a check; a network failure becomes an undeterminable SKIP."""
|
||||
try:
|
||||
fn()
|
||||
except Undeterminable as exc:
|
||||
self.undetermined += 1
|
||||
self.skip(ar_id, f"undeterminable (network): {exc}")
|
||||
|
||||
def exit_code(self) -> int:
|
||||
"""0 all pass, 1 any fail, 3 nothing failed but something undeterminable."""
|
||||
if self.fails:
|
||||
return EXIT_FAIL
|
||||
return EXIT_NETWORK if self.undetermined else EXIT_OK
|
||||
|
||||
|
||||
def summarize(items: list[str], limit: int = 4) -> str:
|
||||
"""Join up to ``limit`` items and note how many more there were."""
|
||||
head = ", ".join(items[:limit])
|
||||
return head + (f" (+{len(items) - limit} more)" if len(items) > limit else "")
|
||||
0
agent_ready/tests/__init__.py
Normal file
0
agent_ready/tests/__init__.py
Normal file
136
agent_ready/tests/conftest.py
Normal file
136
agent_ready/tests/conftest.py
Normal file
@ -0,0 +1,136 @@
|
||||
"""Fixtures: generated site trees and loopback HTTP servers that serve them."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import socket
|
||||
import threading
|
||||
from collections.abc import Callable, Iterator
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from agent_ready.tests import sitegen
|
||||
|
||||
_MIME = {
|
||||
".html": "text/html; charset=utf-8",
|
||||
".md": "text/markdown; charset=utf-8",
|
||||
".txt": "text/plain; charset=utf-8",
|
||||
".xml": "application/xml",
|
||||
".json": "application/json",
|
||||
}
|
||||
|
||||
|
||||
def _resolve(root: Path, path: str) -> Path | None:
|
||||
"""Map a URL path to a file the way a static host does."""
|
||||
rel = path.split("?", 1)[0].lstrip("/")
|
||||
cand = root / rel
|
||||
if path.endswith("/"):
|
||||
cand = cand / "index.html"
|
||||
return cand if cand.is_file() else None
|
||||
|
||||
|
||||
def make_handler(root: Path, mode: str, block_ua: str) -> type[BaseHTTPRequestHandler]:
|
||||
"""Build a handler class.
|
||||
|
||||
``mode`` is ``good`` (real 404s), ``spa`` (200 index.html for every path,
|
||||
the kuhy.duckdns.org trap) or ``json404`` (every non-root path is a JSON
|
||||
404, the popes.kuhy.duckdns.org shape).
|
||||
"""
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def log_message(self, *args: object) -> None: # silence test output
|
||||
return
|
||||
|
||||
def _send(
|
||||
self,
|
||||
status: int,
|
||||
ctype: str,
|
||||
body: bytes,
|
||||
extra: dict[str, str] | None = None,
|
||||
) -> None:
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", ctype)
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
for key, value in (extra or {}).items():
|
||||
self.send_header(key, value)
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def do_GET(self) -> None:
|
||||
if block_ua and block_ua in self.headers.get("User-Agent", ""):
|
||||
self._send(403, "text/html", b"<html>Just a moment...</html>")
|
||||
return
|
||||
origin = f"http://{self.headers['Host']}"
|
||||
if mode == "spa" or (mode == "json404" and self.path == "/"):
|
||||
body = (root / "index.html").read_bytes()
|
||||
self._send(200, "text/html; charset=utf-8", body)
|
||||
return
|
||||
target = None if mode == "json404" else _resolve(root, self.path)
|
||||
if target is None:
|
||||
if mode == "json404":
|
||||
self._send(404, "application/json", b'{"detail":"Not Found"}')
|
||||
else:
|
||||
self._send(404, "text/html", (root / "404.html").read_bytes())
|
||||
return
|
||||
if target.name == "ai-catalog.json":
|
||||
ctype = "application/ai-catalog+json"
|
||||
else:
|
||||
ctype = _MIME.get(target.suffix, "application/octet-stream")
|
||||
body = target.read_bytes().replace(sitegen.ORIGIN.encode(), origin.encode())
|
||||
extra = {}
|
||||
if self.path == "/":
|
||||
extra["Link"] = '</.well-known/ai-catalog.json>; rel="ai-catalog"'
|
||||
self._send(200, ctype, body, extra)
|
||||
|
||||
def do_POST(self) -> None:
|
||||
"""Minimal MCP: answer initialize at /mcp in good mode only."""
|
||||
self.rfile.read(int(self.headers.get("Content-Length", 0)))
|
||||
if mode == "good" and self.path == "/mcp":
|
||||
self._send(
|
||||
200, "application/json", b'{"jsonrpc":"2.0","id":1,"result":{}}'
|
||||
)
|
||||
else:
|
||||
self._send(200, "text/html", (root / "index.html").read_bytes())
|
||||
|
||||
return Handler
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def good_dir(tmp_path: Path) -> Path:
|
||||
"""A compliant build output."""
|
||||
return sitegen.build_good(tmp_path / "good")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def bad_dir(tmp_path: Path) -> Path:
|
||||
"""A build output failing every find/read item."""
|
||||
return sitegen.build_bad(tmp_path / "bad")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def serve() -> Iterator[Callable[..., str]]:
|
||||
"""Start loopback servers on demand; return their base URL."""
|
||||
servers: list[ThreadingHTTPServer] = []
|
||||
|
||||
def start(root: Path, mode: str = "good", block_ua: str = "") -> str:
|
||||
server = ThreadingHTTPServer(
|
||||
("127.0.0.1", 0), make_handler(root, mode, block_ua)
|
||||
)
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
servers.append(server)
|
||||
return f"http://127.0.0.1:{server.server_address[1]}"
|
||||
|
||||
yield start
|
||||
for server in servers:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def dead_url() -> str:
|
||||
"""A loopback URL with nothing listening (connection refused)."""
|
||||
with socket.socket() as sock:
|
||||
sock.bind(("127.0.0.1", 0))
|
||||
port = sock.getsockname()[1]
|
||||
return f"http://127.0.0.1:{port}"
|
||||
80
agent_ready/tests/fakes.py
Normal file
80
agent_ready/tests/fakes.py
Normal file
@ -0,0 +1,80 @@
|
||||
"""In-memory sites and CLI helpers for tests that need exact responses."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
|
||||
import pytest
|
||||
|
||||
from agent_ready.backends import DEFAULT_UA, HttpSite, Response, Site
|
||||
from agent_ready.check import main
|
||||
from agent_ready.context import Ctx
|
||||
from agent_ready.report import Report
|
||||
|
||||
HTML = "text/html"
|
||||
_MISSING = Response(404, HTML, b"")
|
||||
|
||||
|
||||
def resp(body: str, ctype: str = HTML, status: int = 200, **headers: str) -> Response:
|
||||
"""Build a Response; ``headers`` keys are already lowercase names."""
|
||||
return Response(status, ctype, body.encode(), dict(headers))
|
||||
|
||||
|
||||
class FakeSite(Site):
|
||||
"""A dist-like (``live=False``) site answering from a dict."""
|
||||
|
||||
def __init__(self, pages: dict[str, Response]) -> None:
|
||||
super().__init__("https://fake.test")
|
||||
self.pages = pages
|
||||
|
||||
def _fetch(self, path: str, ua: str) -> Response:
|
||||
return self.pages.get(path, _MISSING)
|
||||
|
||||
|
||||
class FakeHttp(HttpSite):
|
||||
"""A live site with no sockets: per-path (and per-UA) canned responses."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
pages: dict[str, Response],
|
||||
ua_pages: dict[tuple[str, str], Response] | None = None,
|
||||
mcp: Response | None = None,
|
||||
) -> None:
|
||||
super().__init__("https://fake.test")
|
||||
self.pages = pages
|
||||
self.ua_pages = ua_pages or {}
|
||||
self.mcp = mcp or _MISSING
|
||||
|
||||
def _fetch(self, path: str, ua: str) -> Response:
|
||||
return self.ua_pages.get((path, ua)) or self.pages.get(path, _MISSING)
|
||||
|
||||
def request(
|
||||
self,
|
||||
path: str,
|
||||
ua: str = DEFAULT_UA,
|
||||
data: bytes | None = None,
|
||||
headers: dict[str, str] | None = None,
|
||||
) -> Response:
|
||||
"""The canned MCP answer, whatever the request."""
|
||||
return self.mcp
|
||||
|
||||
|
||||
def make_ctx(site: Site, *, act: bool = False) -> tuple[Ctx, io.StringIO]:
|
||||
"""A Ctx writing to a StringIO; returns it with that buffer."""
|
||||
out = io.StringIO()
|
||||
return Ctx(site=site, report=Report(out=out), act=act), out
|
||||
|
||||
|
||||
def run_main(capsys: pytest.CaptureFixture[str], *argv: str) -> tuple[int, list[str]]:
|
||||
"""Run the CLI in-process; return exit code and output lines."""
|
||||
code = main(list(argv))
|
||||
return code, capsys.readouterr().out.splitlines()
|
||||
|
||||
|
||||
def lines_for(lines: list[str], ar_id: str, status: str = "") -> list[str]:
|
||||
"""Output lines for ``ar_id`` (optionally only one status)."""
|
||||
return [
|
||||
ln
|
||||
for ln in lines
|
||||
if ln.split()[1] == ar_id and (not status or ln.startswith(status))
|
||||
]
|
||||
153
agent_ready/tests/sitegen.py
Normal file
153
agent_ready/tests/sitegen.py
Normal file
@ -0,0 +1,153 @@
|
||||
"""Build good and bad site trees in a temp dir (no static fixture files).
|
||||
|
||||
Generated at test time on purpose: mirror files such as ``index.md`` would
|
||||
otherwise trip the repo's markdown-naming gate.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
ORIGIN = "https://example.test"
|
||||
|
||||
_TEXT = (
|
||||
"Dice roller for tabletop games. Roll any combination of polyhedral dice, "
|
||||
"keep the highest, and read the full breakdown of every throw. This text "
|
||||
"is in the initial HTML so an agent that never runs JavaScript can read it."
|
||||
)
|
||||
|
||||
_LD = json.dumps(
|
||||
{
|
||||
"@context": "https://schema.org",
|
||||
"@type": "WebSite",
|
||||
"name": "Dice",
|
||||
"url": ORIGIN,
|
||||
}
|
||||
)
|
||||
|
||||
CATALOG = {
|
||||
"specVersion": "1.0",
|
||||
"host": {"displayName": "kuhy", "identifier": "did:web:example.test"},
|
||||
"entries": [
|
||||
{
|
||||
"identifier": "urn:air:example.test:docs:llms",
|
||||
"displayName": "llms.txt",
|
||||
"type": "text/plain",
|
||||
"url": f"{ORIGIN}/llms.txt",
|
||||
}
|
||||
],
|
||||
}
|
||||
|
||||
LLMS = f"""# Dice
|
||||
> A dice roller for tabletop games.
|
||||
|
||||
Plain prose is allowed between sections.
|
||||
|
||||
## Pages
|
||||
- [Home]({ORIGIN}/): what the roller does
|
||||
- [About]({ORIGIN}/about/): who made it
|
||||
"""
|
||||
|
||||
ROBOTS = f"""# robots.txt
|
||||
User-agent: *
|
||||
Disallow: /search/
|
||||
|
||||
Sitemap: {ORIGIN}/sitemap.xml
|
||||
"""
|
||||
|
||||
SITEMAP = f"""<?xml version="1.0" encoding="UTF-8"?>
|
||||
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
|
||||
<url><loc>{ORIGIN}/</loc></url>
|
||||
<url><loc>{ORIGIN}/about/</loc></url>
|
||||
</urlset>
|
||||
"""
|
||||
|
||||
|
||||
def page(title: str, mirror: str, *, home: bool = False) -> str:
|
||||
"""Return a server-rendered HTML page with every read-stage feature."""
|
||||
head = [
|
||||
f"<title>{title}</title>",
|
||||
f'<link rel="alternate" type="text/markdown" href="{mirror}">',
|
||||
]
|
||||
if home:
|
||||
head += [
|
||||
'<link rel="ai-catalog" href="/.well-known/ai-catalog.json" type="application/ai-catalog+json">',
|
||||
'<link rel="alternate" type="text/plain" href="/llms.txt">',
|
||||
f'<script type="application/ld+json">{_LD}</script>',
|
||||
]
|
||||
return (
|
||||
'<!doctype html><html lang="en"><head>' + "".join(head) + "</head><body>"
|
||||
f"<h1>{title}</h1><p>{_TEXT}</p>"
|
||||
'<pre><code class="language-python">print("d20")</code></pre>'
|
||||
'<nav><a href="/">Home</a> <a href="/about/">About</a> <a href="/llms.txt">llms.txt</a></nav>'
|
||||
"</body></html>"
|
||||
)
|
||||
|
||||
|
||||
def mirror(title: str) -> str:
|
||||
"""Return a markdown mirror with a language-tagged fence."""
|
||||
return f"# {title}\n\n{_TEXT}\n\n```python\nprint('d20')\n```\n"
|
||||
|
||||
|
||||
def write(root: Path, rel: str, text: str) -> None:
|
||||
"""Write ``text`` to ``root/rel``, creating parent dirs."""
|
||||
path = root / rel
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(text, encoding="utf-8")
|
||||
|
||||
|
||||
def build_good(root: Path) -> Path:
|
||||
"""Create a fully compliant build output under ``root``."""
|
||||
write(root, "index.html", page("Dice", "/index.md", home=True))
|
||||
write(root, "index.md", mirror("Dice"))
|
||||
write(root, "about/index.html", page("About", "/about/index.md"))
|
||||
write(root, "about/index.md", mirror("About"))
|
||||
write(
|
||||
root,
|
||||
"404.html",
|
||||
"<!doctype html><html><body><h1>Not found</h1><p>No page at this address.</p></body></html>",
|
||||
)
|
||||
write(root, "robots.txt", ROBOTS)
|
||||
write(root, "sitemap.xml", SITEMAP)
|
||||
write(root, "llms.txt", LLMS)
|
||||
write(root, ".well-known/ai-catalog.json", json.dumps(CATALOG))
|
||||
return root
|
||||
|
||||
|
||||
SHELL = '<!doctype html><html><head><title>App</title></head><body><div id="root"></div><script src="/app.js"></script></body></html>'
|
||||
|
||||
|
||||
def build_bad(root: Path) -> Path:
|
||||
"""Create a build output that violates every find/read item."""
|
||||
write(root, "index.html", SHELL)
|
||||
write(root, "about/index.html", SHELL)
|
||||
write(
|
||||
root,
|
||||
"robots.txt",
|
||||
"User-agent: *\nDisallow:\n\nUser-agent: GPTBot\nDisallow: /\n",
|
||||
)
|
||||
write(root, "sitemap.xml", "<html>not xml")
|
||||
write(root, "llms.txt", "# Dice\n\n## Pages\n- [About](/about/)\n")
|
||||
write(
|
||||
root,
|
||||
".well-known/ai-catalog.json",
|
||||
json.dumps({"entries": [{"identifier": "x"}]}),
|
||||
)
|
||||
return root
|
||||
|
||||
|
||||
def add_pages(root: Path, count: int, *, broken_last: bool = False) -> None:
|
||||
"""Add ``count`` more sitemap pages; the last one an empty shell if asked."""
|
||||
urls = []
|
||||
for i in range(count):
|
||||
title = f"Post {i}"
|
||||
html = (
|
||||
SHELL if broken_last and i == count - 1 else page(title, f"/p{i}/index.md")
|
||||
)
|
||||
write(root, f"p{i}/index.html", html)
|
||||
write(root, f"p{i}/index.md", mirror(title))
|
||||
urls.append(f" <url><loc>{ORIGIN}/p{i}/</loc></url>\n")
|
||||
write(
|
||||
root, "sitemap.xml", SITEMAP.replace("</urlset>", "".join(urls) + "</urlset>")
|
||||
)
|
||||
75
agent_ready/tests/test_backends.py
Normal file
75
agent_ready/tests/test_backends.py
Normal file
@ -0,0 +1,75 @@
|
||||
"""Backend edge cases: URL mapping, memoized failures, traversal, deadline."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from agent_ready.backends import DirSite, HttpSite, Response, Site
|
||||
from agent_ready.report import Undeterminable
|
||||
from agent_ready.tests.fakes import FakeHttp, resp
|
||||
|
||||
|
||||
class FlakySite(Site):
|
||||
"""Raises Undeterminable on every fetch and counts the attempts."""
|
||||
|
||||
live = True
|
||||
|
||||
def __init__(self) -> None:
|
||||
super().__init__("https://flaky.test")
|
||||
self.attempts = 0
|
||||
|
||||
def _fetch(self, path: str, ua: str) -> Response:
|
||||
self.attempts += 1
|
||||
raise Undeterminable(f"{path}: boom")
|
||||
|
||||
|
||||
def test_to_path_rejects_offsite_and_non_http(tmp_path: Path) -> None:
|
||||
site = DirSite(tmp_path)
|
||||
assert site.to_path("https://other.test/x") is None
|
||||
assert site.to_path("mailto:a@b.test") is None
|
||||
assert site.to_path("/rel/") == "/rel/"
|
||||
assert site.to_path("https://dist.invalid") == "/"
|
||||
|
||||
|
||||
def test_failures_are_memoized() -> None:
|
||||
site = FlakySite()
|
||||
for _ in range(2):
|
||||
with pytest.raises(Undeterminable, match="boom"):
|
||||
site.get("/x")
|
||||
assert site.attempts == 1
|
||||
|
||||
|
||||
def test_prefetch_swallows_failures_then_get_raises() -> None:
|
||||
site = FlakySite()
|
||||
site.prefetch(["/a", "/b", "/a"])
|
||||
assert site.attempts == 2
|
||||
with pytest.raises(Undeterminable):
|
||||
site.get("/a")
|
||||
|
||||
|
||||
def test_base_fetch_is_abstract() -> None:
|
||||
with pytest.raises(NotImplementedError):
|
||||
Site("https://x.test")._fetch("/", "ua")
|
||||
|
||||
|
||||
def test_dist_never_serves_outside_root(tmp_path: Path) -> None:
|
||||
root = tmp_path / "dist"
|
||||
root.mkdir()
|
||||
(tmp_path / "secret.txt").write_text("nope")
|
||||
site = DirSite(root)
|
||||
assert site.file_for("/../secret.txt") is None
|
||||
assert site.get("/../secret.txt").status == 404
|
||||
|
||||
|
||||
def test_exhausted_budget_is_undeterminable() -> None:
|
||||
site = HttpSite("https://budget.test/anything", budget=0)
|
||||
with pytest.raises(Undeterminable, match="time budget"):
|
||||
site.get("/")
|
||||
|
||||
|
||||
def test_fake_http_serves_canned_pages() -> None:
|
||||
site = FakeHttp({"/": resp("hi")})
|
||||
assert site.get("/").text == "hi"
|
||||
assert site.get("/nope").status == 404
|
||||
153
agent_ready/tests/test_checks_dist.py
Normal file
153
agent_ready/tests/test_checks_dist.py
Normal file
@ -0,0 +1,153 @@
|
||||
"""Dist-mode scenarios: one mutation of the good tree per failing branch."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from agent_ready.tests import sitegen
|
||||
from agent_ready.tests.fakes import lines_for, run_main
|
||||
|
||||
OPENAPI_OP = {"get": {"operationId": "ping"}}
|
||||
|
||||
|
||||
def test_robots_without_wildcard_group(
|
||||
capsys: pytest.CaptureFixture[str], good_dir: Path
|
||||
) -> None:
|
||||
robots = f"User-agent: Foo\nDisallow: /x\n\nSitemap: {sitegen.ORIGIN}/sitemap.xml\n"
|
||||
sitegen.write(good_dir, "robots.txt", robots)
|
||||
_, lines = run_main(capsys, "dist", str(good_dir))
|
||||
assert "no 'User-agent: *' group" in lines_for(lines, "AR-FIND-01", "FAIL")[0]
|
||||
|
||||
|
||||
def test_sitemap_found_without_robots_reference_sets_origin(
|
||||
capsys: pytest.CaptureFixture[str], good_dir: Path
|
||||
) -> None:
|
||||
sitegen.write(good_dir, "robots.txt", "User-agent: *\nDisallow:\n")
|
||||
code, lines = run_main(capsys, "dist", str(good_dir))
|
||||
assert code == 1
|
||||
assert "no 'Sitemap:' line" in lines_for(lines, "AR-FIND-03", "FAIL")[0]
|
||||
assert lines_for(lines, "AR-FIND-03", "FAIL")[1:] == []
|
||||
assert lines_for(lines, "AR-READ-01", "PASS")
|
||||
|
||||
|
||||
def test_sitemap_index_follows_children(
|
||||
capsys: pytest.CaptureFixture[str], good_dir: Path
|
||||
) -> None:
|
||||
child = f"{sitegen.ORIGIN}/sitemap-pages.xml"
|
||||
index = (
|
||||
'<?xml version="1.0"?><sitemapindex '
|
||||
'xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'
|
||||
f"<sitemap><loc>{child}</loc></sitemap></sitemapindex>"
|
||||
)
|
||||
sitegen.write(good_dir, "sitemap-pages.xml", sitegen.SITEMAP)
|
||||
sitegen.write(good_dir, "sitemap.xml", index)
|
||||
code, lines = run_main(capsys, "dist", str(good_dir))
|
||||
assert code == 0, lines
|
||||
assert "lists 2 pages" in lines_for(lines, "AR-FIND-03", "PASS")[-1]
|
||||
|
||||
|
||||
def test_sitemap_with_offsite_locs_and_none_at_all(
|
||||
capsys: pytest.CaptureFixture[str], good_dir: Path
|
||||
) -> None:
|
||||
urlset = '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">{}</urlset>'
|
||||
off = urlset.format("<url><loc>https://other.test/x/</loc></url>")
|
||||
sitegen.write(good_dir, "sitemap.xml", off)
|
||||
_, lines = run_main(capsys, "dist", str(good_dir))
|
||||
assert "1 <loc> URLs are not on" in lines_for(lines, "AR-FIND-03", "FAIL")[0]
|
||||
sitegen.write(good_dir, "sitemap.xml", urlset.format(""))
|
||||
_, lines = run_main(capsys, "dist", str(good_dir))
|
||||
assert "no <loc> entries" in lines_for(lines, "AR-FIND-03", "FAIL")[0]
|
||||
assert "sitemap yielded no pages" in lines_for(lines, "AR-READ-01", "FAIL")[0]
|
||||
|
||||
|
||||
def test_sitemap_pages_missing_or_copies_of_the_shell(
|
||||
capsys: pytest.CaptureFixture[str], good_dir: Path
|
||||
) -> None:
|
||||
home = (good_dir / "index.html").read_text()
|
||||
sitegen.write(good_dir, "dup/index.html", home)
|
||||
extra = "".join(
|
||||
f"<url><loc>{sitegen.ORIGIN}/{p}/</loc></url>" for p in ("dup", "gone")
|
||||
)
|
||||
sitemap = (good_dir / "sitemap.xml").read_text()
|
||||
sitegen.write(
|
||||
good_dir, "sitemap.xml", sitemap.replace("</urlset>", extra + "</urlset>")
|
||||
)
|
||||
code, lines = run_main(capsys, "dist", str(good_dir))
|
||||
assert code == 1
|
||||
problem = lines_for(lines, "AR-READ-01", "FAIL")[0]
|
||||
assert "/gone/ (HTTP 404)" in problem
|
||||
assert "/dup/ (byte-identical to the homepage shell)" in problem
|
||||
|
||||
|
||||
def test_markdown_mirror_with_untagged_fence(
|
||||
capsys: pytest.CaptureFixture[str], good_dir: Path
|
||||
) -> None:
|
||||
sitegen.write(good_dir, "about/index.md", "# About\n\n```\nplain\n```\n")
|
||||
_, lines = run_main(capsys, "dist", str(good_dir))
|
||||
assert "about/index.md (1 untagged fences)" in lines_for(lines, "AR-READ-05")[0]
|
||||
|
||||
|
||||
def test_llms_with_broken_link(
|
||||
capsys: pytest.CaptureFixture[str], good_dir: Path
|
||||
) -> None:
|
||||
llms = (good_dir / "llms.txt").read_text() + "- [Gone](/gone/): missing\n"
|
||||
sitegen.write(good_dir, "llms.txt", llms)
|
||||
_, lines = run_main(capsys, "dist", str(good_dir))
|
||||
assert "broken links: /gone/" in lines_for(lines, "AR-READ-07", "FAIL")[0]
|
||||
|
||||
|
||||
def test_homepage_with_unparseable_json_ld(
|
||||
capsys: pytest.CaptureFixture[str], good_dir: Path
|
||||
) -> None:
|
||||
home = (good_dir / "index.html").read_text()
|
||||
sitegen.write(good_dir, "index.html", home.replace('"@context"', "@context"))
|
||||
_, lines = run_main(capsys, "dist", str(good_dir))
|
||||
assert "1 JSON-LD blocks fail" in lines_for(lines, "AR-READ-08", "FAIL")[-1]
|
||||
|
||||
|
||||
def test_webmcp_found_in_linked_script(
|
||||
capsys: pytest.CaptureFixture[str], good_dir: Path
|
||||
) -> None:
|
||||
home = (good_dir / "index.html").read_text()
|
||||
scripts = '<script src="https://cdn.other.test/x.js"></script><script src="/app.js"></script>'
|
||||
sitegen.write(good_dir, "index.html", home.replace("</body>", scripts + "</body>"))
|
||||
sitegen.write(good_dir, "app.js", "document.modelContext.registerTool({});")
|
||||
_, lines = run_main(capsys, "dist", str(good_dir), "--act")
|
||||
assert lines_for(lines, "AR-ACT-07", "PASS")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("doc", "status", "needle"),
|
||||
[
|
||||
({"openapi": "3.1.0", "paths": {"/p": OPENAPI_OP}}, "PASS", "1 operations"),
|
||||
(
|
||||
{"openapi": "3.1.0", "paths": {"/p": {"get": {}}}},
|
||||
"FAIL",
|
||||
"lack operationId",
|
||||
),
|
||||
({"openapi": "3.1.0", "paths": {}}, "FAIL", "no operations in paths"),
|
||||
({"openapi": "3.1.0", "paths": 5}, "FAIL", "no operations in paths"),
|
||||
(
|
||||
{
|
||||
"openapi": "3.1.0",
|
||||
"paths": {"/a": "x", "/b": {"parameters": [], "get": 1}},
|
||||
},
|
||||
"FAIL",
|
||||
"1 operations lack",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_openapi_document_shapes(
|
||||
capsys: pytest.CaptureFixture[str],
|
||||
good_dir: Path,
|
||||
doc: dict[str, object],
|
||||
status: str,
|
||||
needle: str,
|
||||
) -> None:
|
||||
sitegen.write(good_dir, "openapi.json", json.dumps(doc))
|
||||
_, lines = run_main(capsys, "dist", str(good_dir), "--act")
|
||||
found = lines_for(lines, "AR-ACT-02", status)
|
||||
assert found and needle in found[0], lines_for(lines, "AR-ACT-02")
|
||||
83
agent_ready/tests/test_checks_live.py
Normal file
83
agent_ready/tests/test_checks_live.py
Normal file
@ -0,0 +1,83 @@
|
||||
"""Live-mode checks driven by canned responses (no sockets, no network)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from agent_ready import checks_act, checks_find, checks_read
|
||||
from agent_ready.backends import Response
|
||||
from agent_ready.tests import sitegen
|
||||
from agent_ready.tests.fakes import FakeHttp, make_ctx, resp
|
||||
|
||||
LONG = "Readable text for agents that never run JavaScript. " * 4
|
||||
MD_LINK = '</index.md>; rel="alternate"; type="text/markdown"'
|
||||
|
||||
|
||||
def _home(*, ctype: str = "text/html", **headers: str) -> Response:
|
||||
return resp(f"<html><body><p>{LONG}</p></body></html>", ctype, **headers)
|
||||
|
||||
|
||||
def test_challenge_page_for_one_agent_is_reported() -> None:
|
||||
challenge = resp("<html>Just a moment...</html>")
|
||||
ua = checks_find.AGENT_UAS["GPTBot"]
|
||||
site = FakeHttp({"/": _home()}, ua_pages={("/", ua): challenge})
|
||||
ctx, out = make_ctx(site)
|
||||
checks_find.check_agent_access(ctx)
|
||||
assert out.getvalue().startswith("FAIL AR-FIND-01 GPTBot got a challenge page")
|
||||
|
||||
|
||||
def test_sitemap_on_another_host_is_a_failure() -> None:
|
||||
robots = "User-agent: *\nDisallow:\nSitemap: https://other.test/sitemap.xml\n"
|
||||
site = FakeHttp({"/robots.txt": resp(robots, "text/plain")})
|
||||
ctx, out = make_ctx(site)
|
||||
checks_find.check_robots(ctx)
|
||||
ctx.sitemap_pages = []
|
||||
assert checks_find._sitemap_paths(ctx) == ["/sitemap.xml"]
|
||||
assert (
|
||||
"Sitemap is on another host: https://other.test/sitemap.xml" in out.getvalue()
|
||||
)
|
||||
|
||||
|
||||
def test_markdown_mirror_advertised_only_by_link_header() -> None:
|
||||
site = FakeHttp(
|
||||
{
|
||||
"/": _home(link=MD_LINK),
|
||||
"/index.md": resp(sitegen.mirror("Home"), "text/markdown"),
|
||||
}
|
||||
)
|
||||
ctx, out = make_ctx(site)
|
||||
checks_read.check_pages(ctx)
|
||||
assert (
|
||||
"PASS AR-READ-09 1 pages advertise a working markdown mirror" in out.getvalue()
|
||||
)
|
||||
|
||||
|
||||
def test_page_served_with_wrong_content_type() -> None:
|
||||
ctx, out = make_ctx(FakeHttp({"/": _home(ctype="text/plain")}))
|
||||
checks_read.check_pages(ctx)
|
||||
assert (
|
||||
"FAIL AR-READ-01 answer not in initial HTML: / (text/plain)" in out.getvalue()
|
||||
)
|
||||
|
||||
|
||||
def _mcp(status: int, **headers: str) -> Response:
|
||||
return Response(status, "application/json", b"{}", dict(headers))
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("answer", "status"),
|
||||
[
|
||||
(_mcp(401, **{"www-authenticate": "Bearer"}), "PASS"),
|
||||
(_mcp(401), "FAIL"),
|
||||
],
|
||||
)
|
||||
def test_mcp_behind_oauth_needs_www_authenticate(answer: Response, status: str) -> None:
|
||||
ctx, out = make_ctx(FakeHttp({}, mcp=answer), act=True)
|
||||
checks_act.check_mcp(ctx)
|
||||
assert f"{status} AR-ACT-03" in out.getvalue()
|
||||
|
||||
|
||||
def test_act_off_reports_a_single_skip() -> None:
|
||||
ctx, out = make_ctx(FakeHttp({}))
|
||||
checks_act.run_act(ctx)
|
||||
assert out.getvalue().startswith("SKIP AR-ACT-10 act stage off")
|
||||
202
agent_ready/tests/test_cli.py
Normal file
202
agent_ready/tests/test_cli.py
Normal file
@ -0,0 +1,202 @@
|
||||
"""End-to-end tests of ``check.py`` in dist and url mode."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import runpy
|
||||
import subprocess
|
||||
import sys
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from agent_ready.check import main
|
||||
from agent_ready.tests import sitegen
|
||||
|
||||
LINE = re.compile(r"^(PASS|FAIL|SKIP) AR-(FIND|READ|ACT)-\d\d \S")
|
||||
PKG = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def run(capsys: pytest.CaptureFixture[str], *argv: str) -> tuple[int, list[str]]:
|
||||
"""Run the CLI in-process; return exit code and output lines."""
|
||||
code = main(list(argv))
|
||||
lines = capsys.readouterr().out.splitlines()
|
||||
bad = [ln for ln in lines if not LINE.match(ln)]
|
||||
assert not bad, bad
|
||||
return code, lines
|
||||
|
||||
|
||||
def statuses(lines: list[str], ar_id: str) -> set[str]:
|
||||
"""Return the set of statuses reported for ``ar_id``."""
|
||||
return {ln.split()[0] for ln in lines if ln.split()[1] == ar_id}
|
||||
|
||||
|
||||
def test_dist_good_passes(capsys: pytest.CaptureFixture[str], good_dir: Path) -> None:
|
||||
code, lines = run(capsys, "dist", str(good_dir))
|
||||
assert code == 0, "\n".join(lines)
|
||||
assert not [ln for ln in lines if ln.startswith("FAIL")]
|
||||
for ar_id in (
|
||||
"AR-FIND-01",
|
||||
"AR-FIND-03",
|
||||
"AR-FIND-04",
|
||||
"AR-READ-01",
|
||||
"AR-READ-02",
|
||||
"AR-READ-07",
|
||||
"AR-READ-09",
|
||||
):
|
||||
found = statuses(lines, ar_id)
|
||||
assert "PASS" in found and "FAIL" not in found, ar_id
|
||||
assert statuses(lines, "AR-READ-11") == {"SKIP"}
|
||||
assert statuses(lines, "AR-ACT-10") == {"SKIP"}
|
||||
|
||||
|
||||
def test_dist_bad_fails_every_item(
|
||||
capsys: pytest.CaptureFixture[str], bad_dir: Path
|
||||
) -> None:
|
||||
code, lines = run(capsys, "dist", str(bad_dir))
|
||||
assert code == 1
|
||||
for ar_id in (
|
||||
"AR-FIND-01",
|
||||
"AR-FIND-03",
|
||||
"AR-FIND-04",
|
||||
"AR-READ-01",
|
||||
"AR-READ-02",
|
||||
"AR-READ-03",
|
||||
"AR-READ-06",
|
||||
"AR-READ-07",
|
||||
"AR-READ-08",
|
||||
"AR-READ-09",
|
||||
):
|
||||
assert "FAIL" in statuses(lines, ar_id), ar_id
|
||||
assert any("gptbot" in ln for ln in lines if "AR-FIND-01" in ln)
|
||||
|
||||
|
||||
def test_dist_untagged_code_fails(
|
||||
capsys: pytest.CaptureFixture[str], good_dir: Path
|
||||
) -> None:
|
||||
about = good_dir / "about/index.html"
|
||||
about.write_text(about.read_text().replace(' class="language-python"', ""))
|
||||
code, lines = run(capsys, "dist", str(good_dir))
|
||||
assert code == 1
|
||||
assert "FAIL" in statuses(lines, "AR-READ-05")
|
||||
|
||||
|
||||
def test_dist_act_opt_in(capsys: pytest.CaptureFixture[str], good_dir: Path) -> None:
|
||||
code, lines = run(capsys, "dist", str(good_dir), "--act")
|
||||
assert code == 1
|
||||
assert "FAIL" in statuses(lines, "AR-ACT-02")
|
||||
|
||||
|
||||
def test_usage_errors(capsys: pytest.CaptureFixture[str], tmp_path: Path) -> None:
|
||||
assert main(["dist", str(tmp_path / "missing")]) == 2
|
||||
assert main(["url", "not-a-url"]) == 2
|
||||
with pytest.raises(SystemExit) as exc:
|
||||
main([])
|
||||
assert exc.value.code == 2
|
||||
|
||||
|
||||
def test_url_good_passes(
|
||||
capsys: pytest.CaptureFixture[str], good_dir: Path, serve: Callable[..., str]
|
||||
) -> None:
|
||||
code, lines = run(capsys, "url", serve(good_dir))
|
||||
assert code == 0, "\n".join(lines)
|
||||
assert statuses(lines, "AR-READ-02") == {"PASS"}
|
||||
|
||||
|
||||
def test_url_spa_fallback_fails(
|
||||
capsys: pytest.CaptureFixture[str], good_dir: Path, serve: Callable[..., str]
|
||||
) -> None:
|
||||
"""Every path 200 text/html: a status-only check would wrongly pass."""
|
||||
code, lines = run(capsys, "url", serve(good_dir, "spa"))
|
||||
assert code == 1
|
||||
for ar_id in (
|
||||
"AR-FIND-01",
|
||||
"AR-FIND-03",
|
||||
"AR-FIND-04",
|
||||
"AR-READ-01",
|
||||
"AR-READ-02",
|
||||
"AR-READ-07",
|
||||
"AR-READ-09",
|
||||
):
|
||||
assert "FAIL" in statuses(lines, ar_id), ar_id
|
||||
assert any("text/html" in ln for ln in lines if "AR-FIND-01" in ln)
|
||||
assert any(
|
||||
"does not exist" in ln for ln in lines if "AR-READ-06" in ln
|
||||
) # HTML fallback != file
|
||||
|
||||
|
||||
def test_url_json_404(
|
||||
capsys: pytest.CaptureFixture[str], good_dir: Path, serve: Callable[..., str]
|
||||
) -> None:
|
||||
code, lines = run(capsys, "url", serve(good_dir, "json404"))
|
||||
assert code == 1
|
||||
assert statuses(lines, "AR-READ-02") == {"PASS"}
|
||||
assert "FAIL" in statuses(lines, "AR-FIND-01")
|
||||
|
||||
|
||||
def test_url_blocked_agent(
|
||||
capsys: pytest.CaptureFixture[str], good_dir: Path, serve: Callable[..., str]
|
||||
) -> None:
|
||||
code, lines = run(capsys, "url", serve(good_dir, block_ua="GPTBot"))
|
||||
assert code == 1
|
||||
assert any(ln.startswith("FAIL AR-FIND-01") and "GPTBot" in ln for ln in lines)
|
||||
|
||||
|
||||
def test_url_unreachable_is_3(
|
||||
capsys: pytest.CaptureFixture[str], dead_url: str
|
||||
) -> None:
|
||||
assert main(["url", dead_url]) == 3
|
||||
|
||||
|
||||
def test_entry_points_from_other_cwd(good_dir: Path, tmp_path: Path) -> None:
|
||||
for cmd in (
|
||||
["bash", str(PKG / "check.sh")],
|
||||
[sys.executable, str(PKG / "check.py")],
|
||||
):
|
||||
proc = subprocess.run(
|
||||
[*cmd, "dist", str(good_dir)],
|
||||
cwd=tmp_path,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
assert proc.returncode == 0, proc.stdout + proc.stderr
|
||||
|
||||
|
||||
def test_dist_checks_every_page_url_caps_visibly(
|
||||
capsys: pytest.CaptureFixture[str], good_dir: Path, serve: Callable[..., str]
|
||||
) -> None:
|
||||
"""Dist mode ignores --max-pages; url mode names the cap instead of hiding it."""
|
||||
sitegen.add_pages(good_dir, 6, broken_last=True)
|
||||
code, lines = run(capsys, "dist", str(good_dir), "--max-pages", "3")
|
||||
assert code == 1
|
||||
assert any(ln.startswith("FAIL AR-READ-01") and "/p5/" in ln for ln in lines)
|
||||
code, lines = run(capsys, "url", serve(good_dir), "--max-pages", "3")
|
||||
assert any(ln.startswith("SKIP AR-READ-01 checked 3 of 8 pages") for ln in lines), (
|
||||
lines
|
||||
)
|
||||
|
||||
|
||||
def test_url_act_mcp(
|
||||
capsys: pytest.CaptureFixture[str], good_dir: Path, serve: Callable[..., str]
|
||||
) -> None:
|
||||
_, lines = run(capsys, "url", serve(good_dir), "--act")
|
||||
assert statuses(lines, "AR-ACT-03") == {"PASS"}
|
||||
assert statuses(lines, "AR-ACT-10") == {"PASS"}
|
||||
assert "FAIL" in statuses(lines, "AR-ACT-07")
|
||||
code, lines = run(capsys, "url", serve(good_dir, "spa"), "--act")
|
||||
assert code == 1
|
||||
assert statuses(lines, "AR-ACT-03") == {"FAIL"}
|
||||
assert statuses(lines, "AR-ACT-10") == {"FAIL"}
|
||||
|
||||
|
||||
def test_script_entry_point_in_process(good_dir: Path) -> None:
|
||||
"""Run check.py as ``__main__`` here so the guard lines count for coverage."""
|
||||
argv = ["check.py", "dist", str(good_dir)]
|
||||
with pytest.MonkeyPatch.context() as patch:
|
||||
patch.setattr(sys, "argv", argv)
|
||||
patch.setattr(sys, "path", list(sys.path)) # check.py prepends to it
|
||||
with pytest.raises(SystemExit) as exc:
|
||||
runpy.run_path(str(PKG / "check.py"), run_name="__main__")
|
||||
assert exc.value.code == 0
|
||||
186
agent_ready/tests/test_formats.py
Normal file
186
agent_ready/tests/test_formats.py
Normal file
@ -0,0 +1,186 @@
|
||||
"""Unit tests for the format validators and the HTML scanner."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from agent_ready import formats, htmlscan
|
||||
from agent_ready.tests import sitegen
|
||||
|
||||
# Verbatim from spec/spec.md "llms.txt shape (informative)".
|
||||
SPEC_LLMS = """# Acme
|
||||
> Acme ships a payments API for developers.
|
||||
|
||||
## Docs
|
||||
- [Quickstart](https://example.com/docs/quickstart): first charge in one request
|
||||
- [Authentication](https://example.com/docs/auth): API keys, scopes, rotation
|
||||
|
||||
## API
|
||||
- [OpenAPI](https://example.com/openapi.json): full request and response contract
|
||||
"""
|
||||
|
||||
# Shape of https://vercel.com/.well-known/ai-catalog.json (2026-10-22), trimmed.
|
||||
VERCEL_CATALOG = {
|
||||
"specVersion": "1.0",
|
||||
"host": {"displayName": "Vercel", "identifier": "https://vercel.com"},
|
||||
"entries": [
|
||||
{
|
||||
"identifier": "urn:air:vercel.com:api:rest",
|
||||
"displayName": "Vercel REST API",
|
||||
"type": "application/json",
|
||||
"url": "https://vercel.com/openapi.json",
|
||||
"tags": ["api"],
|
||||
}
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def test_llms_spec_example_is_valid() -> None:
|
||||
assert formats.llms_problems(SPEC_LLMS) == []
|
||||
|
||||
|
||||
def test_llms_allows_prose_and_plain_bullets() -> None:
|
||||
text = SPEC_LLMS.replace(
|
||||
"## API", "Version: v2.0\n\n## Notes\n- plain bullet\n\n## API"
|
||||
)
|
||||
assert formats.llms_problems(text) == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("mutate", "needle"),
|
||||
[
|
||||
(lambda t: t.replace("# Acme\n", ""), "H1"),
|
||||
(
|
||||
lambda t: t.replace("> Acme ships a payments API for developers.\n", ""),
|
||||
"blockquote",
|
||||
),
|
||||
(lambda t: "# Acme\n> summary\n\nno sections\n", "link list"),
|
||||
(lambda t: "<!doctype html><html></html>", "HTML"),
|
||||
],
|
||||
)
|
||||
def test_llms_rejects(mutate: object, needle: str) -> None:
|
||||
problems = formats.llms_problems(mutate(SPEC_LLMS)) # type: ignore[operator]
|
||||
assert any(needle in p for p in problems), problems
|
||||
|
||||
|
||||
def test_llms_links() -> None:
|
||||
assert formats.llms_links(SPEC_LLMS)[0] == "https://example.com/docs/quickstart"
|
||||
|
||||
|
||||
def test_catalog_valid_examples() -> None:
|
||||
assert formats.catalog_problems(VERCEL_CATALOG) == []
|
||||
assert formats.catalog_problems(sitegen.CATALOG) == []
|
||||
minimal = {
|
||||
"specVersion": "1.0",
|
||||
"entries": [{"identifier": "a", "type": "t", "data": {}}],
|
||||
}
|
||||
assert formats.catalog_problems(minimal) == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("doc", "needle"),
|
||||
[
|
||||
([], "object"),
|
||||
({"entries": []}, "specVersion"),
|
||||
({"specVersion": "1", "entries": []}, "Major.Minor"),
|
||||
({"specVersion": "1.0"}, "entries"),
|
||||
({"specVersion": "1.0", "entries": [{"type": "t", "url": "u"}]}, "identifier"),
|
||||
({"specVersion": "1.0", "entries": [{"identifier": "i", "url": "u"}]}, "type"),
|
||||
(
|
||||
{
|
||||
"specVersion": "1.0",
|
||||
"entries": [{"identifier": "i", "type": "t", "url": "u", "data": 1}],
|
||||
},
|
||||
"exactly one",
|
||||
),
|
||||
({"specVersion": "1.0", "entries": [], "host": {}}, "host.displayName"),
|
||||
],
|
||||
)
|
||||
def test_catalog_rejects(doc: object, needle: str) -> None:
|
||||
assert any(needle in p for p in formats.catalog_problems(doc)), (
|
||||
formats.catalog_problems(doc)
|
||||
)
|
||||
|
||||
|
||||
def test_robots_blanket_blocks() -> None:
|
||||
text = "User-agent: *\nDisallow:\n\nUser-Agent: GPTBot\nUser-agent: CCBot\nDisallow: /*\n"
|
||||
groups = formats.parse_robots(text)
|
||||
assert formats.has_wildcard_group(groups)
|
||||
assert formats.blocked_agents(groups) == ["gptbot", "ccbot"]
|
||||
|
||||
|
||||
def test_robots_partial_disallow_and_allow_override() -> None:
|
||||
text = "User-agent: *\nDisallow: /search/\n\nUser-agent: ClaudeBot\nDisallow: /\nAllow: /\n"
|
||||
assert formats.blocked_agents(formats.parse_robots(text)) == []
|
||||
assert formats.robots_sitemaps("Sitemap: https://x.test/s.xml\n") == [
|
||||
"https://x.test/s.xml"
|
||||
]
|
||||
|
||||
|
||||
def test_sitemap_parse() -> None:
|
||||
kind, locs = formats.parse_sitemap(sitegen.SITEMAP.encode())
|
||||
assert kind == "urlset"
|
||||
assert locs == ["https://example.test/", "https://example.test/about/"]
|
||||
with pytest.raises(ValueError):
|
||||
formats.parse_sitemap(b"<html>not xml")
|
||||
|
||||
|
||||
def test_untagged_fences() -> None:
|
||||
assert formats.untagged_fences("```python\nx\n```\n") == 0
|
||||
assert formats.untagged_fences("```\nx\n```\n~~~\ny\n~~~\n") == 2
|
||||
|
||||
|
||||
def test_htmlscan_good_home() -> None:
|
||||
scan = htmlscan.scan(sitegen.page("Dice", "/index.md", home=True))
|
||||
assert len(scan.text) > 150
|
||||
assert scan.code_blocks == 1 and scan.untagged_code == 0
|
||||
assert scan.link_href("alternate", "text/markdown") == "/index.md"
|
||||
assert scan.link_href("ai-catalog") == "/.well-known/ai-catalog.json"
|
||||
assert "/about/" in scan.anchors
|
||||
assert scan.jsonld_ok == 1
|
||||
|
||||
|
||||
def test_htmlscan_shell_has_no_text() -> None:
|
||||
scan = htmlscan.scan(sitegen.SHELL)
|
||||
assert scan.text.strip() == "" # <title> is head, not body text
|
||||
assert scan.anchors == []
|
||||
bare = htmlscan.scan(
|
||||
'<pre><code>x</code></pre><script type="application/ld+json">{bad</script>'
|
||||
)
|
||||
assert bare.untagged_code == 1 and bare.jsonld_bad == 1
|
||||
|
||||
|
||||
def test_sitemap_wrong_root_is_rejected() -> None:
|
||||
with pytest.raises(ValueError, match="not <urlset>"):
|
||||
formats.parse_sitemap(b"<feed><loc>https://x.test/</loc></feed>")
|
||||
|
||||
|
||||
def test_catalog_entry_must_be_an_object() -> None:
|
||||
doc = {"specVersion": "1.0", "entries": ["nope"]}
|
||||
assert formats.catalog_problems(doc) == ["entries[0]: must be an object"]
|
||||
|
||||
|
||||
def test_catalog_accessors_tolerate_invalid_docs() -> None:
|
||||
for doc in ([], {"entries": "x"}):
|
||||
assert formats.catalog_urls(doc) == []
|
||||
assert formats.catalog_types(doc) == []
|
||||
assert formats.catalog_urls(sitegen.CATALOG) == [f"{sitegen.ORIGIN}/llms.txt"]
|
||||
|
||||
|
||||
def test_fence_inside_fence_is_not_a_new_block() -> None:
|
||||
nested = "````md\n```\ninner\n```\n````\n"
|
||||
assert formats.untagged_fences(nested) == 0
|
||||
assert formats.untagged_fences("```python\n~~~\n```\n```\nz\n```\n") == 1
|
||||
|
||||
|
||||
def test_htmlscan_jsonld_without_context_is_bad() -> None:
|
||||
scan = htmlscan.scan(
|
||||
'<script type="application/ld+json">{"name": "x"}</script>'
|
||||
'<script type="application/ld+json">[]</script>'
|
||||
)
|
||||
assert scan.jsonld_ok == 0 and scan.jsonld_bad == 2
|
||||
|
||||
|
||||
def test_htmlscan_unclosed_inner_hidden_tag_closes_with_outer() -> None:
|
||||
scan = htmlscan.scan("<body><template><noscript>x</template><p>visible</p></body>")
|
||||
assert scan.text == "visible"
|
||||
54
agent_ready/tests/test_report_ctx.py
Normal file
54
agent_ready/tests/test_report_ctx.py
Normal file
@ -0,0 +1,54 @@
|
||||
"""Report policy, Link-header parsing and context helpers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
|
||||
from agent_ready.backends import Response
|
||||
from agent_ready.context import link_header_href
|
||||
from agent_ready.report import Report, Undeterminable, summarize
|
||||
from agent_ready.tests.fakes import FakeSite, make_ctx, resp
|
||||
|
||||
|
||||
def _boom() -> None:
|
||||
raise Undeterminable("refused")
|
||||
|
||||
|
||||
def test_guard_turns_network_failure_into_skip_and_exit_3() -> None:
|
||||
out = io.StringIO()
|
||||
report = Report(out=out)
|
||||
report.guard("AR-FIND-01", _boom)
|
||||
assert out.getvalue() == "SKIP AR-FIND-01 undeterminable (network): refused\n"
|
||||
assert report.exit_code() == 3
|
||||
report.fail("AR-FIND-01", "x")
|
||||
assert report.exit_code() == 1
|
||||
|
||||
|
||||
def test_summarize_notes_the_overflow() -> None:
|
||||
assert summarize(["a", "b"]) == "a, b"
|
||||
assert summarize(list("abcdef")) == "a, b, c, d (+2 more)"
|
||||
|
||||
|
||||
def _linked(link: str) -> Response:
|
||||
return Response(200, "text/html", b"", {"link": link})
|
||||
|
||||
|
||||
def test_link_header_skips_unusable_values() -> None:
|
||||
header = (
|
||||
"garbage, </no-rel>; type=x, </other>; rel=preload, "
|
||||
'</a.md>; rel="alternate"; type="text/plain", '
|
||||
'</b.md>; rel="alternate"; type="text/markdown"'
|
||||
)
|
||||
assert link_header_href(_linked(header), "alternate", "text/markdown") == "/b.md"
|
||||
assert link_header_href(_linked(header), "alternate") == "/a.md"
|
||||
assert link_header_href(_linked(header), "ai-catalog") is None
|
||||
assert link_header_href(_linked(""), "alternate") is None
|
||||
|
||||
|
||||
def test_exists_rejects_html_fallback_for_files() -> None:
|
||||
ctx, _ = make_ctx(
|
||||
FakeSite({"/f.txt": resp("<html><head></head>"), "/p/": resp("<html>")})
|
||||
)
|
||||
assert not ctx.exists("/f.txt")
|
||||
assert ctx.exists("/p/")
|
||||
assert not ctx.exists("/missing.txt")
|
||||
52
app_errors/README.md
Normal file
52
app_errors/README.md
Normal file
@ -0,0 +1,52 @@
|
||||
# app_errors
|
||||
|
||||
The PC side of kuhy's app error and slow-wait reporting. Every app reports
|
||||
errors, and every wait the user sees over 1 s (`perf.slow`). This ingest merges
|
||||
the reports by signature and writes `~/.local/state/app-errors/<app>.json` in
|
||||
the todoImplementer `contracts/app-error.schema.json` `report` shape. The board
|
||||
reads that folder and turns each open error into a self-fixing ticket
|
||||
(todoImplementer `DOCS-errors.md`).
|
||||
|
||||
Generalised from kartka's `tools/errors`. Dart signatures are byte-identical to
|
||||
kartka's. See `DOCS-app-errors.md` at the repo root for the whole pipeline.
|
||||
|
||||
## Where reports come from
|
||||
|
||||
| Reporter | Runs on | Writes |
|
||||
|---|---|---|
|
||||
| `crdt_sync_flutter` `installErrorReporting` | phone, desktop, web | RTDB `/<app>/errors/<device>/<id>` |
|
||||
| `gatelock.error_report.install` | PC (Tk) | spool `~/.local/state/app-errors-spool/<app>.jsonl` |
|
||||
| Godot `addons/app_errors` (`godot_dev_tools/`) | PC | the same spool |
|
||||
|
||||
The ingest skips `kartka` in RTDB, because kartka still runs its own ingest.
|
||||
|
||||
## Entry (one report, every language)
|
||||
|
||||
`at` (ISO UTC), `kind` (`uncaught.flutter`, `uncaught.python`, `uncaught.gdscript`,
|
||||
`ui.snackbar`, `perf.slow`, ...), `error`, `stack` (list of frames), plus these
|
||||
optional fields:
|
||||
|
||||
- `repo` (`owner/name`; default: the `origin` of `~/src/<app>` when it is on GitHub, else `kuhyx/<app>`)
|
||||
- `mark` (the substring that marks the app's own frames: `package:todo/`,
|
||||
`leetcode_guard/`, `res://`)
|
||||
- `route`
|
||||
- `operation`, `durationMs`, `waitId` and `still` (slow waits)
|
||||
- `build` (versionCode, 0 when unknown) and `version`
|
||||
|
||||
## Commands
|
||||
|
||||
```bash
|
||||
app-errors ingest # what the timer runs every 5 min
|
||||
app-errors ingest --keep # leave RTDB entries in place
|
||||
app-errors ingest --no-rtdb # local spool only
|
||||
app-errors resolve <app> <signature> # mark it fixed; a newer build reopens it
|
||||
```
|
||||
|
||||
`app_errors/install.sh` installs the venv
|
||||
(`~/.local/share/app-errors/venv`), the `app-errors` link and
|
||||
`app-errors-ingest.timer`. `scripts/deploy.sh` runs it.
|
||||
|
||||
RTDB access reuses an already seeded crdt-sync session (`--session`, default
|
||||
`firebase_backup`), so the ingest needs no sign-in of its own.
|
||||
|
||||
Tests: `cd app_errors && python -m pytest` (100 % branch coverage).
|
||||
2
app_errors/app_errors/__init__.py
Normal file
2
app_errors/app_errors/__init__.py
Normal file
@ -0,0 +1,2 @@
|
||||
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||
"""Shared app error and slow-wait ingest: RTDB and spool reports in, board tickets out."""
|
||||
72
app_errors/app_errors/cli.py
Normal file
72
app_errors/app_errors/cli.py
Normal file
@ -0,0 +1,72 @@
|
||||
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||
"""``app-errors``: ``ingest`` (what the timer runs) and ``resolve <app> <signature>``."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import datetime as dt
|
||||
import sys
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from kuhy_credit import credit_line
|
||||
|
||||
from app_errors import ingest, store
|
||||
from app_errors.rtdb import DEFAULT_SESSION, RtdbError, open_rtdb
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Sequence
|
||||
|
||||
|
||||
def _parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="app-errors",
|
||||
description=__doc__,
|
||||
epilog=credit_line(),
|
||||
)
|
||||
sub = parser.add_subparsers(dest="command", required=True)
|
||||
run = sub.add_parser("ingest", help="read RTDB and the spool, write the board reports")
|
||||
run.add_argument("--keep", action="store_true", help="leave RTDB entries in place")
|
||||
run.add_argument("--no-rtdb", action="store_true", help="read the local spool only")
|
||||
run.add_argument("--session", default=DEFAULT_SESSION, help="seeded crdt-sync credential store")
|
||||
res = sub.add_parser("resolve", help="mark an error fixed (a newer build reopens it)")
|
||||
res.add_argument("app")
|
||||
res.add_argument("signature")
|
||||
return parser
|
||||
|
||||
|
||||
def _ingest(args: argparse.Namespace) -> int:
|
||||
db, error = None, None
|
||||
if not args.no_rtdb:
|
||||
try:
|
||||
db = open_rtdb(args.session)
|
||||
except RtdbError as e:
|
||||
error = str(e)
|
||||
summary = ingest.run(ingest.default_paths(), db, keep=args.keep)
|
||||
error = error or summary.rtdb_error
|
||||
print(f"app-errors: {summary.merged} new") # noqa: T201 -- terminal-only CLI
|
||||
if error:
|
||||
print(f"app-errors: RTDB: {error}", file=sys.stderr) # noqa: T201
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
def _resolve(args: argparse.Namespace) -> int:
|
||||
paths = ingest.default_paths()
|
||||
state = store.load(paths.state)
|
||||
now = dt.datetime.now(dt.UTC).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
|
||||
if not store.resolve(state, args.app, args.signature, now=now):
|
||||
print(f"app-errors: unknown error {args.app} {args.signature}", file=sys.stderr) # noqa: T201
|
||||
return 1
|
||||
store.save(paths.state, state)
|
||||
store.write_reports(paths.reports, state)
|
||||
return 0
|
||||
|
||||
|
||||
def main(argv: Sequence[str] | None = None) -> int:
|
||||
"""Run the CLI; return the exit code."""
|
||||
args = _parser().parse_args(argv)
|
||||
return _ingest(args) if args.command == "ingest" else _resolve(args)
|
||||
|
||||
|
||||
if __name__ == "__main__": # pragma: no cover
|
||||
sys.exit(main())
|
||||
102
app_errors/app_errors/ingest.py
Normal file
102
app_errors/app_errors/ingest.py
Normal file
@ -0,0 +1,102 @@
|
||||
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||
"""One ingest pass: RTDB and the local spool in, the board's reports out.
|
||||
|
||||
In: RTDB ``/<app>/errors/<device>/<id>`` and the spool. Out:
|
||||
``<state>/app-errors/<app>.json``, the board's contract report.
|
||||
|
||||
RTDB entries are deleted once the state holding them is saved (``keep``
|
||||
leaves them; ``seen`` stops a second count). kartka is skipped: it still runs
|
||||
its own ingest (``~/src/kartka/tools/errors``), which the board reads through
|
||||
its ``kartka`` adapter, and two readers of ``/kartka/errors`` would race.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import functools
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from app_errors import origin, spool, store
|
||||
from app_errors.rtdb import RtdbError
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from app_errors.rtdb import Rtdb
|
||||
|
||||
#: Apps with their own ingest, never read here (kartka moved over 2026-11-17).
|
||||
SKIP_APPS: frozenset[str] = frozenset()
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Paths:
|
||||
"""Where the ingest keeps its state, writes reports and reads the spool."""
|
||||
|
||||
state: Path
|
||||
reports: Path
|
||||
spool: Path
|
||||
#: Checkouts: ``<src_root>/<app>``'s origin names the repo of a report without one.
|
||||
src_root: Path
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Summary:
|
||||
"""What one pass did."""
|
||||
|
||||
merged: int
|
||||
rtdb_error: str | None
|
||||
|
||||
|
||||
def default_paths() -> Paths:
|
||||
"""Return the state paths (``$XDG_STATE_HOME``, default ``~/.local/state``) and ``~/src``."""
|
||||
base = Path(os.environ.get("XDG_STATE_HOME") or Path.home() / ".local" / "state")
|
||||
return Paths(
|
||||
base / "app-errors-ingest" / "state.json",
|
||||
base / "app-errors",
|
||||
base / "app-errors-spool",
|
||||
Path.home() / "src",
|
||||
)
|
||||
|
||||
|
||||
def _rtdb_entries(
|
||||
db: Rtdb,
|
||||
) -> tuple[list[tuple[str, str, object]], dict[str, dict[str, object]]]:
|
||||
"""Return (app, device/id, entry) for every RTDB report, and the deletes that consume them."""
|
||||
found: list[tuple[str, str, object]] = []
|
||||
deletes: dict[str, dict[str, object]] = {}
|
||||
top = db.get("", shallow=True)
|
||||
for app in sorted(top) if isinstance(top, dict) else []:
|
||||
if app in SKIP_APPS or not store.APP_NAME.match(app):
|
||||
continue
|
||||
devices = db.get(f"{app}/errors")
|
||||
for device, entries in devices.items() if isinstance(devices, dict) else []:
|
||||
for entry_id, entry in entries.items() if isinstance(entries, dict) else []:
|
||||
found.append((app, f"{device}/{entry_id}", entry))
|
||||
deletes.setdefault(app, {})[f"{device}/{entry_id}"] = None
|
||||
return found, deletes
|
||||
|
||||
|
||||
def run(paths: Paths, db: Rtdb | None, *, keep: bool = False) -> Summary:
|
||||
"""Ingest everything once; RTDB failures are returned, the spool still goes in."""
|
||||
state = store.load(paths.state)
|
||||
repo_of = functools.partial(origin.repo_slug, paths.src_root, owner=store.OWNER)
|
||||
merged = 0
|
||||
rtdb_error = None
|
||||
deletes: dict[str, dict[str, object]] = {}
|
||||
if db is not None:
|
||||
try:
|
||||
found, deletes = _rtdb_entries(db)
|
||||
except RtdbError as e:
|
||||
found, rtdb_error = [], str(e)
|
||||
merged += sum(store.merge(state, a, k, e, repo_of=repo_of) for a, k, e in found)
|
||||
lines = spool.drain(paths.spool)
|
||||
merged += sum(store.merge(state, ln.app, ln.id, ln.entry, repo_of=repo_of) for ln in lines)
|
||||
store.save(paths.state, state)
|
||||
store.write_reports(paths.reports, state)
|
||||
if db is not None and not keep:
|
||||
try:
|
||||
for app, paths_gone in deletes.items():
|
||||
db.patch(f"{app}/errors", paths_gone)
|
||||
except RtdbError as e:
|
||||
rtdb_error = str(e)
|
||||
return Summary(merged, rtdb_error)
|
||||
61
app_errors/app_errors/origin.py
Normal file
61
app_errors/app_errors/origin.py
Normal file
@ -0,0 +1,61 @@
|
||||
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||
"""Which GitHub repo a local checkout is, read from its ``origin`` remote.
|
||||
|
||||
A folder name says nothing about the owner: ``~/src/cleanup-plate`` is
|
||||
``Sepci0/cleanup-plate`` and ``~/src/todo`` is ``kuhyx/todo-app``. Guessing
|
||||
``<owner>/<folder>`` filed tasks and error tickets under repos that do not exist, so the guess is
|
||||
only the fallback for a folder with no checkout or no GitHub origin.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
GIT_TIMEOUT = 5.0
|
||||
# https://[user@]github.com/o/n[.git], ssh://git@github.com[:port]/o/n[.git]
|
||||
# and git@github.com:o/n[.git]. Other hosts (a local mirror, a gitea) are not
|
||||
# the GitHub slug the board works with, so they fall back to the guess.
|
||||
_GITHUB = re.compile(
|
||||
r"^(?:https?://(?:[^@/]+@)?github\.com/|ssh://git@github\.com(?::\d+)?/"
|
||||
r"|git@github\.com:)(?P<slug>[^/\s]+/[^/\s]+?)(?:\.git)?/?$"
|
||||
)
|
||||
|
||||
|
||||
def slug_from_url(url: str) -> str | None:
|
||||
"""Return ``owner/name`` of a GitHub remote URL, or None for any other URL."""
|
||||
match = _GITHUB.match(url.strip())
|
||||
return match["slug"] if match else None
|
||||
|
||||
|
||||
def origin_slug(checkout: Path) -> str | None:
|
||||
"""Return the GitHub ``owner/name`` of ``checkout``'s origin, or None.
|
||||
|
||||
None when ``checkout`` is not a git checkout (a ``.git`` dir, or file for a
|
||||
worktree), has no ``origin``, git is missing or hangs, or origin is not
|
||||
GitHub. Checking ``.git`` first keeps git from walking up to a parent repo.
|
||||
"""
|
||||
git = shutil.which("git")
|
||||
if git is None or not (checkout / ".git").exists():
|
||||
return None
|
||||
try:
|
||||
out = subprocess.run(
|
||||
[git, "-C", str(checkout), "remote", "get-url", "origin"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
timeout=GIT_TIMEOUT,
|
||||
)
|
||||
except OSError, subprocess.SubprocessError:
|
||||
return None
|
||||
return None if out.returncode else slug_from_url(out.stdout)
|
||||
|
||||
|
||||
def repo_slug(src_root: Path, folder: str, owner: str) -> str:
|
||||
"""Return the slug of ``src_root/folder``'s origin, else ``owner/folder``."""
|
||||
return origin_slug(src_root / folder) or f"{owner}/{folder}"
|
||||
0
app_errors/app_errors/py.typed
Normal file
0
app_errors/app_errors/py.typed
Normal file
104
app_errors/app_errors/rtdb.py
Normal file
104
app_errors/app_errors/rtdb.py
Normal file
@ -0,0 +1,104 @@
|
||||
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||
"""A minimal RTDB REST client on a seeded crdt-sync Google session.
|
||||
|
||||
Ported from kartka's ``tools/errors`` (``kartka_errors.rtdb``), plus
|
||||
``shallow`` reads to list the apps. The sync account is Google-only, so the
|
||||
session is an already seeded ``~/.config/<store>/firebase_auth.json`` (crdt-
|
||||
sync's ``tool.seed_session`` writes one; it refreshes itself). The request URL
|
||||
carries the ID token (``?auth=``), so no error raised here ever includes it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
import json
|
||||
from typing import Protocol
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
#: The credential store read by default: the backup timer's, a PC-side reader
|
||||
#: of the same database (any seeded store of the sync account works).
|
||||
DEFAULT_SESSION = "firebase_backup"
|
||||
#: Per-request timeout, seconds (token refresh has its own, below).
|
||||
TIMEOUT = 15.0
|
||||
TOKEN_TIMEOUT = 8.0
|
||||
|
||||
type Opener = Callable[..., object]
|
||||
|
||||
|
||||
class RtdbError(RuntimeError):
|
||||
"""An RTDB request failed, or there is no session (the message never names the URL)."""
|
||||
|
||||
|
||||
class Rtdb(Protocol):
|
||||
"""Read and multi-path write access to RTDB."""
|
||||
|
||||
def get(self, path: str, *, shallow: bool = False) -> object:
|
||||
"""Return the decoded JSON at ``path`` (None when absent)."""
|
||||
...
|
||||
|
||||
def patch(self, path: str, data: dict[str, object]) -> None:
|
||||
"""Apply a multi-path update of ``path`` (a None value deletes)."""
|
||||
...
|
||||
|
||||
|
||||
class RestRtdb:
|
||||
"""RTDB over REST with ``?auth=<id token>``."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
database_url: str,
|
||||
id_token: Callable[[], str],
|
||||
opener: Opener = urllib.request.urlopen,
|
||||
) -> None:
|
||||
"""Talk to ``database_url`` with tokens from ``id_token``."""
|
||||
self._url = database_url.rstrip("/")
|
||||
self._id_token = id_token
|
||||
self._open = opener
|
||||
|
||||
def _send(self, method: str, path: str, body: bytes | None, query: str = "") -> object:
|
||||
try:
|
||||
token = self._id_token()
|
||||
except Exception as e: # noqa: BLE001 -- any refresh failure, typed only
|
||||
msg = f"RTDB {method} {path}: token refresh failed ({type(e).__name__})"
|
||||
raise RtdbError(msg) from None
|
||||
req = urllib.request.Request( # noqa: S310 -- https only, built here
|
||||
f"{self._url}/{path}.json?auth={token}{query}",
|
||||
data=body,
|
||||
method=method,
|
||||
headers={"Content-Type": "application/json"},
|
||||
)
|
||||
try:
|
||||
with self._open(req, timeout=TIMEOUT) as res: # type: ignore[attr-defined]
|
||||
return json.loads(res.read() or b"null")
|
||||
except urllib.error.HTTPError as e:
|
||||
msg = f"RTDB {method} {path}: HTTP {e.code}"
|
||||
raise RtdbError(msg) from None
|
||||
except (urllib.error.URLError, OSError, ValueError) as e:
|
||||
msg = f"RTDB {method} {path}: {type(e).__name__}"
|
||||
raise RtdbError(msg) from None
|
||||
|
||||
def get(self, path: str, *, shallow: bool = False) -> object:
|
||||
"""GET ``path``; raises :class:`RtdbError` on any failure."""
|
||||
return self._send("GET", path, None, "&shallow=true" if shallow else "")
|
||||
|
||||
def patch(self, path: str, data: dict[str, object]) -> None:
|
||||
"""PATCH ``data`` into ``path``; raises :class:`RtdbError`."""
|
||||
self._send("PATCH", path, json.dumps(data).encode())
|
||||
|
||||
|
||||
def open_rtdb(session: str = DEFAULT_SESSION) -> RestRtdb:
|
||||
"""Return the client on the seeded ``session``; :class:`RtdbError` without one."""
|
||||
import crdt_sync # noqa: PLC0415 -- only the RTDB path needs it; spool-only runs stay stdlib
|
||||
|
||||
try:
|
||||
config = crdt_sync.FirebaseConfig.load()
|
||||
except Exception as e: # noqa: BLE001 -- a missing or broken config, typed only
|
||||
msg = f"no Firebase config ({type(e).__name__})"
|
||||
raise RtdbError(msg) from None
|
||||
store = crdt_sync.credential_store_for(session)
|
||||
auth = crdt_sync.FirebaseTokenProvider(config.api_key, store, timeout_seconds=TOKEN_TIMEOUT)
|
||||
if not auth.has_session():
|
||||
msg = f"no seeded sign-in session '{session}'; seed one with crdt-sync's tool.seed_session --app {session}"
|
||||
raise RtdbError(msg)
|
||||
return RestRtdb(config.database_url, auth.id_token)
|
||||
128
app_errors/app_errors/signature.py
Normal file
128
app_errors/app_errors/signature.py
Normal file
@ -0,0 +1,128 @@
|
||||
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||
"""Group error reports: one signature per bug, however often it fires.
|
||||
|
||||
Ported from kartka's ``tools/errors`` (``kartka_errors.signature``) and kept
|
||||
byte-identical for Dart entries, so kartka's existing tickets keep their ids
|
||||
when it moves onto this ingest. Generalised in one place only: which stack
|
||||
frames belong to the app. An entry's ``mark`` names them (``package:todo/``
|
||||
for Dart, ``leetcode_guard/`` for Python, ``res://`` for GDScript); without
|
||||
one it is ``package:<app>/``.
|
||||
|
||||
A signature is the error type, the message with its volatile parts (numbers,
|
||||
ids, URLs) masked, and where it happened: the first app frame without line
|
||||
numbers (so an edit elsewhere in the file does not split it), else the route,
|
||||
else the entry kind. A slow wait is its route + operation, never its time.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import hashlib
|
||||
import re
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Mapping, Sequence
|
||||
|
||||
#: The longest normalised message kept in a signature.
|
||||
MAX_MESSAGE = 160
|
||||
#: The entry kind of a user-visible wait over a second.
|
||||
SLOW_KIND = "perf.slow"
|
||||
|
||||
_TYPE = re.compile(r"^(?:Unhandled error: )?([A-Z][\w$]*(?:Exception|Error))\b")
|
||||
#: Dart errors whose ``toString`` does not name their type.
|
||||
_DART_PREFIXES = {
|
||||
"Bad state": "StateError",
|
||||
"Invalid argument": "ArgumentError",
|
||||
"Unsupported operation": "UnsupportedError",
|
||||
"Null check operator": "TypeError",
|
||||
"Concurrent modification": "ConcurrentModificationError",
|
||||
}
|
||||
_URL = re.compile(r"(https?://\S+|<url>)")
|
||||
_UUID = re.compile(r"\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b", re.IGNORECASE)
|
||||
_HEX = re.compile(r"\b(?=[0-9a-f]*\d)[0-9a-f]{8,}\b", re.IGNORECASE)
|
||||
_NUMBER = re.compile(r"\b\d+(\.\d+)?\b")
|
||||
_SPACE = re.compile(r"\s+")
|
||||
_FRAME = re.compile(r"^#\d+\s+")
|
||||
_LINE_COL = re.compile(r"(\.(?:dart|py|gd))(:\d+)+")
|
||||
#: Frames of the reporting plumbing itself, never the bug's location.
|
||||
_PLUMBING = (
|
||||
"package:kartka/app/error_hooks.dart",
|
||||
"package:kartka/core/diagnostics/",
|
||||
"package:crdt_sync_flutter/src/errors/",
|
||||
"gatelock/error_report.py",
|
||||
"res://addons/app_errors/",
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Signature:
|
||||
"""What groups reports of one bug."""
|
||||
|
||||
id: str
|
||||
type: str
|
||||
message: str
|
||||
where: str
|
||||
|
||||
|
||||
def error_type(error: str, kind: str) -> str:
|
||||
"""Return the exception type named by ``error``, else ``kind``."""
|
||||
if match := _TYPE.match(error):
|
||||
return match[1]
|
||||
for prefix, name in _DART_PREFIXES.items():
|
||||
if error.startswith(prefix):
|
||||
return name
|
||||
return kind
|
||||
|
||||
|
||||
def normalise(message: str) -> str:
|
||||
"""Return ``message`` with URLs, uuids, long hex and numbers masked, trimmed."""
|
||||
text = _URL.sub("<url>", message)
|
||||
text = _UUID.sub("<uuid>", text)
|
||||
text = _HEX.sub("<hex>", text)
|
||||
text = _NUMBER.sub("<n>", text)
|
||||
return _SPACE.sub(" ", text).strip()[:MAX_MESSAGE]
|
||||
|
||||
|
||||
def top_frame(stack: Sequence[str], mark: str) -> str | None:
|
||||
"""Return the first frame containing ``mark`` outside the reporting plumbing."""
|
||||
for frame in stack:
|
||||
if mark in frame and not any(p in frame for p in _PLUMBING):
|
||||
return _LINE_COL.sub(r"\1", _FRAME.sub("", frame.strip()))
|
||||
return None
|
||||
|
||||
|
||||
def mark_of(entry: Mapping[str, object], app: str) -> str:
|
||||
"""Return the substring that marks the app's own frames in ``entry``."""
|
||||
mark = entry.get("mark")
|
||||
return mark if isinstance(mark, str) and mark else f"package:{app}/"
|
||||
|
||||
|
||||
def strings(value: object) -> list[str]:
|
||||
"""Return ``value`` as a list of strings; empty when it is not a list."""
|
||||
return [str(v) for v in value] if isinstance(value, list) else []
|
||||
|
||||
|
||||
def _digest(text: str) -> str:
|
||||
return hashlib.sha1(text.encode()).hexdigest()[:10] # noqa: S324 -- a grouping key, not security
|
||||
|
||||
|
||||
def signature(entry: Mapping[str, object], *, app: str) -> Signature:
|
||||
"""Return the signature of one report of ``app``."""
|
||||
kind = str(entry.get("kind", "?"))
|
||||
if kind == SLOW_KIND:
|
||||
operation = str(entry.get("operation") or "?")
|
||||
where = f"route {entry.get('route') or '?'}"
|
||||
return Signature(
|
||||
_digest(f"{SLOW_KIND}|{where}|{operation}"),
|
||||
SLOW_KIND,
|
||||
f"slow wait: {operation}",
|
||||
where,
|
||||
)
|
||||
error = str(entry.get("error", ""))
|
||||
frame = top_frame(strings(entry.get("stack")), mark_of(entry, app))
|
||||
route = entry.get("route")
|
||||
where = frame or (f"route {route}" if route else f"kind {kind}")
|
||||
kind_type = error_type(error, kind)
|
||||
message = normalise(error)
|
||||
return Signature(_digest(f"{kind_type}|{message}|{where}"), kind_type, message, where)
|
||||
66
app_errors/app_errors/spool.py
Normal file
66
app_errors/app_errors/spool.py
Normal file
@ -0,0 +1,66 @@
|
||||
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||
"""The local spool: how PC apps (Tk gate windows, Godot games) report.
|
||||
|
||||
They run on the PC the ingest runs on, so they need no RTDB: each report is
|
||||
one JSON line appended to ``<spool>/<app>.jsonl`` (the writers are
|
||||
``gatelock.error_report`` and the Godot ``app_errors`` addon; this module is
|
||||
the reference writer and the reader). The ingest claims a file by renaming it
|
||||
to ``.jsonl.ingesting`` before reading, so a line appended meanwhile lands in
|
||||
a fresh file and is never lost. The spool sits beside, not inside, the
|
||||
board's ``app-errors/`` folder, which reads every ``*.json`` there.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import hashlib
|
||||
import json
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from app_errors.store import APP_NAME
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterator, Mapping
|
||||
from pathlib import Path
|
||||
|
||||
SUFFIX = ".jsonl"
|
||||
CLAIMED = ".jsonl.ingesting"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Line:
|
||||
"""One spooled report: its app, a stable id and the decoded entry."""
|
||||
|
||||
app: str
|
||||
id: str
|
||||
entry: object
|
||||
|
||||
|
||||
def append(folder: Path, app: str, entry: Mapping[str, object]) -> None:
|
||||
"""Append ``entry`` as one line to ``app``'s spool file."""
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
with (folder / f"{app}{SUFFIX}").open("a", encoding="utf-8") as f:
|
||||
f.write(json.dumps(entry, sort_keys=True) + "\n")
|
||||
|
||||
|
||||
def _claim(folder: Path) -> list[Path]:
|
||||
for path in folder.glob(f"*{SUFFIX}"):
|
||||
path.replace(path.with_name(path.name.removesuffix(SUFFIX) + CLAIMED))
|
||||
return sorted(folder.glob(f"*{CLAIMED}"))
|
||||
|
||||
|
||||
def drain(folder: Path) -> Iterator[Line]:
|
||||
"""Yield every spooled line, then delete the files it came from."""
|
||||
if not folder.is_dir():
|
||||
return
|
||||
for path in _claim(folder):
|
||||
app = path.name.removesuffix(CLAIMED)
|
||||
if APP_NAME.match(app):
|
||||
for text in path.read_text(encoding="utf-8").splitlines():
|
||||
try:
|
||||
entry = json.loads(text)
|
||||
except ValueError:
|
||||
continue
|
||||
digest = hashlib.sha1(text.encode()).hexdigest()[:20] # noqa: S324 -- an id, not security
|
||||
yield Line(app, f"spool/{digest}", entry)
|
||||
path.unlink()
|
||||
224
app_errors/app_errors/store.py
Normal file
224
app_errors/app_errors/store.py
Normal file
@ -0,0 +1,224 @@
|
||||
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||
"""The local record of every report ingested, grouped by app and signature.
|
||||
|
||||
It is the source of truth once RTDB entries and spool lines are consumed:
|
||||
``seen`` makes a re-read count nothing twice, and each signature keeps its
|
||||
count, first and last time, newest build and its resolution. :func:`report`
|
||||
turns one app's records into the todoImplementer ``app-error`` contract
|
||||
(``contracts/app-error.schema.json``, ``report``).
|
||||
|
||||
Resolve and reopen: ``resolve`` stores the time and the newest build seen. A
|
||||
later report reopens the error only when it is a regression: a newer build
|
||||
when both sides know the build, else a report made after the resolve.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import tempfile
|
||||
from typing import TYPE_CHECKING, NotRequired, TypedDict, cast
|
||||
|
||||
from app_errors.signature import SLOW_KIND, mark_of, signature, strings, top_frame
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable, Mapping
|
||||
|
||||
#: Entry ids remembered for dedup (oldest dropped first).
|
||||
MAX_SEEN = 5000
|
||||
#: An app name the board accepts (the contract's ``app`` pattern).
|
||||
APP_NAME = re.compile(r"^[a-z0-9][a-z0-9_-]*$")
|
||||
_REPO = re.compile(r"^[^/\s]+/[^/\s]+$")
|
||||
#: The owner guessed for an app whose report names no repo and has no checkout.
|
||||
OWNER = "kuhyx"
|
||||
|
||||
|
||||
def guess_repo(app: str) -> str:
|
||||
"""Return ``OWNER/app``: the fallback when nothing better names the repo."""
|
||||
return f"{OWNER}/{app}"
|
||||
|
||||
|
||||
class Resolved(TypedDict):
|
||||
"""When the error was marked fixed, and the newest build seen then."""
|
||||
|
||||
at: str
|
||||
build: int
|
||||
|
||||
|
||||
class Rec(TypedDict):
|
||||
"""Everything known about one signature of one app."""
|
||||
|
||||
signature: str
|
||||
repo: str
|
||||
kind: str
|
||||
message: str
|
||||
top_frame: str | None
|
||||
route: str | None
|
||||
count: int
|
||||
first_seen: str
|
||||
last_seen: str
|
||||
build: int
|
||||
version_name: str | None
|
||||
longest_ms: NotRequired[int]
|
||||
resolved: Resolved | None
|
||||
|
||||
|
||||
class State(TypedDict):
|
||||
"""The whole state file."""
|
||||
|
||||
version: int
|
||||
seen: dict[str, str]
|
||||
apps: dict[str, dict[str, Rec]]
|
||||
|
||||
|
||||
def empty() -> State:
|
||||
"""Return a state that knows nothing."""
|
||||
return {"version": 1, "seen": {}, "apps": {}}
|
||||
|
||||
|
||||
def load(path: Path) -> State:
|
||||
"""Return the state at ``path``; empty when missing or unreadable."""
|
||||
try:
|
||||
data = json.loads(path.read_text())
|
||||
except OSError, ValueError:
|
||||
return empty()
|
||||
if not isinstance(data, dict) or data.get("version") != 1:
|
||||
return empty()
|
||||
return cast("State", data)
|
||||
|
||||
|
||||
def _atomic_write(path: Path, text: str) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=f".{path.stem}-")
|
||||
with os.fdopen(fd, "w") as f:
|
||||
f.write(text)
|
||||
Path(tmp).replace(path)
|
||||
|
||||
|
||||
def save(path: Path, state: State) -> None:
|
||||
"""Write ``state`` atomically (temp file + rename)."""
|
||||
_atomic_write(path, json.dumps(state, indent=1, sort_keys=True))
|
||||
|
||||
|
||||
def _int(value: object) -> int:
|
||||
return value if isinstance(value, int) and not isinstance(value, bool) and value >= 0 else 0
|
||||
|
||||
|
||||
def _str(value: object) -> str | None:
|
||||
return value if isinstance(value, str) and value else None
|
||||
|
||||
|
||||
def _reopens(resolved: Resolved, at: str, build: int) -> bool:
|
||||
if build and resolved["build"]:
|
||||
return build > resolved["build"]
|
||||
return at > resolved["at"]
|
||||
|
||||
|
||||
def merge(
|
||||
state: State,
|
||||
app: str,
|
||||
entry_id: str,
|
||||
raw: object,
|
||||
*,
|
||||
repo_of: Callable[[str], str] = guess_repo,
|
||||
) -> bool:
|
||||
"""Count one report ``raw`` of ``app`` under its signature; False when seen or not a report.
|
||||
|
||||
A new record takes the report's ``repo``, else ``repo_of(app)``.
|
||||
"""
|
||||
if not isinstance(raw, dict):
|
||||
return False
|
||||
entry = cast("Mapping[str, object]", raw)
|
||||
at, kind = entry.get("at"), entry.get("kind")
|
||||
if not isinstance(at, str) or not at or not isinstance(kind, str) or not kind:
|
||||
return False
|
||||
key = f"{app}/{entry_id}"
|
||||
if key in state["seen"]:
|
||||
return False
|
||||
state["seen"][key] = at
|
||||
while len(state["seen"]) > MAX_SEEN:
|
||||
del state["seen"][next(iter(state["seen"]))]
|
||||
sig = signature(entry, app=app)
|
||||
build = _int(entry.get("build"))
|
||||
recs = state["apps"].setdefault(app, {})
|
||||
rec = recs.get(sig.id)
|
||||
if rec is None:
|
||||
repo = _str(entry.get("repo"))
|
||||
rec = recs[sig.id] = {
|
||||
"signature": sig.id,
|
||||
"repo": repo if repo and _REPO.match(repo) else repo_of(app),
|
||||
"kind": kind,
|
||||
"message": sig.message,
|
||||
"top_frame": top_frame(strings(entry.get("stack")), mark_of(entry, app)),
|
||||
"route": _str(entry.get("route")),
|
||||
"count": 0,
|
||||
"first_seen": at,
|
||||
"last_seen": at,
|
||||
"build": 0,
|
||||
"version_name": None,
|
||||
"resolved": None,
|
||||
}
|
||||
rec["count"] += 1
|
||||
rec["first_seen"] = min(rec["first_seen"], at)
|
||||
rec["last_seen"] = max(rec["last_seen"], at)
|
||||
if build >= rec["build"]:
|
||||
rec["build"] = build
|
||||
rec["version_name"] = _str(entry.get("version")) or rec["version_name"]
|
||||
if kind == SLOW_KIND:
|
||||
rec["longest_ms"] = max(rec.get("longest_ms", 0), _int(entry.get("durationMs")))
|
||||
resolved = rec["resolved"]
|
||||
if resolved is not None and _reopens(resolved, at, build):
|
||||
rec["resolved"] = None
|
||||
return True
|
||||
|
||||
|
||||
def resolve(state: State, app: str, sig: str, *, now: str) -> bool:
|
||||
"""Mark ``app``'s ``sig`` fixed as of ``now``; False when there is no such error."""
|
||||
rec = state["apps"].get(app, {}).get(sig)
|
||||
if rec is None:
|
||||
return False
|
||||
rec["resolved"] = {"at": now, "build": rec["build"]}
|
||||
return True
|
||||
|
||||
|
||||
def _detail(rec: Rec) -> str | None:
|
||||
route = f"route {rec['route']}" if rec["route"] else None
|
||||
if rec["kind"] == SLOW_KIND:
|
||||
longest = f"longest wait {rec.get('longest_ms', 0)} ms"
|
||||
return f"{longest}, {route}" if route else longest
|
||||
return route
|
||||
|
||||
|
||||
def report(state: State, app: str) -> dict[str, object]:
|
||||
"""Return ``app``'s records as a contract ``report``."""
|
||||
errors = [
|
||||
{
|
||||
"app": app,
|
||||
"repo": rec["repo"],
|
||||
"signature": rec["signature"],
|
||||
"kind": rec["kind"],
|
||||
"message": rec["message"],
|
||||
"top_frame": rec["top_frame"],
|
||||
"count": rec["count"],
|
||||
"first_seen": rec["first_seen"],
|
||||
"last_seen": rec["last_seen"],
|
||||
"build": rec["build"],
|
||||
"version_name": rec["version_name"],
|
||||
"detail": _detail(rec),
|
||||
"open": rec["resolved"] is None,
|
||||
}
|
||||
for rec in sorted(state["apps"].get(app, {}).values(), key=lambda r: r["signature"])
|
||||
]
|
||||
return {"version": 1, "errors": errors}
|
||||
|
||||
|
||||
def write_reports(folder: Path, state: State) -> list[Path]:
|
||||
"""Write ``<folder>/<app>.json`` for every app with records; return the paths."""
|
||||
written = []
|
||||
for app in sorted(state["apps"]):
|
||||
path = folder / f"{app}.json"
|
||||
_atomic_write(path, json.dumps(report(state, app), indent=1))
|
||||
written.append(path)
|
||||
return written
|
||||
0
app_errors/app_errors/tests/__init__.py
Normal file
0
app_errors/app_errors/tests/__init__.py
Normal file
20
app_errors/app_errors/tests/checkout.py
Normal file
20
app_errors/app_errors/tests/checkout.py
Normal file
@ -0,0 +1,20 @@
|
||||
"""A real git checkout in a temp dir, built without kuhy's git config."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
GIT = shutil.which("git") or "git"
|
||||
|
||||
|
||||
def make_checkout(path: Path, origin: str | None) -> Path:
|
||||
"""Init a repo at ``path`` with remote ``origin`` (none when None)."""
|
||||
env = {"PATH": os.environ["PATH"], "HOME": str(path.parent), "GIT_CONFIG_NOSYSTEM": "1"}
|
||||
path.mkdir(parents=True)
|
||||
subprocess.run([GIT, "init", "-q", str(path)], check=True, env=env)
|
||||
if origin is not None:
|
||||
subprocess.run([GIT, "-C", str(path), "remote", "add", "origin", origin], check=True, env=env)
|
||||
return path
|
||||
74
app_errors/app_errors/tests/data/app-error.schema.json
Normal file
74
app_errors/app_errors/tests/data/app-error.schema.json
Normal file
@ -0,0 +1,74 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://todoimplementer.local/contracts/app-error.schema.json",
|
||||
"title": "App errors",
|
||||
"description": "What an app writes for the errors loop (DOCS-errors.md): `~/.local/state/app-errors/<app>.json` is a `report`; kartka's own state.json is mapped to the same `record` by an adapter. One record per identical error (signature).",
|
||||
"$defs": {
|
||||
"record": {
|
||||
"type": "object",
|
||||
"description": "One identical error or slow wait. The loop makes one ticket per `app:signature`.",
|
||||
"properties": {
|
||||
"app": { "type": "string", "pattern": "^[a-z0-9][a-z0-9_-]*$" },
|
||||
"repo": { "type": "string", "pattern": "^[^/\\s]+/[^/\\s]+$", "description": "owner/name of the repo that holds the fix." },
|
||||
"signature": { "type": "string", "minLength": 1, "pattern": "^\\S+$", "description": "Stable id of the error: the same error always gets the same one." },
|
||||
"kind": { "type": "string", "minLength": 1, "description": "crash, ui.error, perf.slow, ..." },
|
||||
"message": { "type": "string", "description": "Masked message (no secrets, no user data)." },
|
||||
"top_frame": { "type": ["string", "null"] },
|
||||
"count": { "type": "integer", "minimum": 1 },
|
||||
"first_seen": { "type": "string", "minLength": 1 },
|
||||
"last_seen": { "type": "string", "minLength": 1 },
|
||||
"build": { "type": "integer", "minimum": 0, "description": "Monotonic build of the newest report (Android versionCode); 0 when the source does not know it." },
|
||||
"version_name": { "type": ["string", "null"] },
|
||||
"detail": { "type": ["string", "null"], "description": "Free text: durations, route." },
|
||||
"open": { "type": "boolean", "description": "False once the source marks the error resolved; default true." }
|
||||
},
|
||||
"required": ["app", "repo", "signature", "kind", "message", "count", "first_seen", "last_seen", "build"],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"report": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"version": { "const": 1 },
|
||||
"errors": { "type": "array", "items": { "$ref": "#/$defs/record" } }
|
||||
},
|
||||
"required": ["version", "errors"],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"source": {
|
||||
"type": "object",
|
||||
"description": "One entry of settings.json `error_sources`. `resolve` and `build` are argv lists; `{signature}`, `{repo_dir}` and `{commit}` are replaced.",
|
||||
"properties": {
|
||||
"app": { "type": "string", "pattern": "^[a-z0-9][a-z0-9_-]*$" },
|
||||
"repo": { "type": "string", "pattern": "^[^/\\s]+/[^/\\s]+$" },
|
||||
"adapter": { "enum": ["kartka", "contract"] },
|
||||
"path": { "type": "string", "minLength": 1 },
|
||||
"resolve": { "type": "array", "items": { "type": "string" } },
|
||||
"build": { "type": "array", "items": { "type": "string" } }
|
||||
},
|
||||
"required": ["app", "repo", "adapter", "path"],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"ledger": {
|
||||
"type": "object",
|
||||
"description": "`<run root>/app-errors.json`: what the loop knows per `app:signature`.",
|
||||
"additionalProperties": { "$ref": "#/$defs/entry" }
|
||||
},
|
||||
"entry": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"state": { "enum": ["ticket", "shipped", "fixed"] },
|
||||
"repo": { "type": "string" },
|
||||
"title": { "type": "string" },
|
||||
"count": { "type": "integer", "minimum": 0 },
|
||||
"starts": { "type": "integer", "minimum": 0 },
|
||||
"commit": { "type": "string" },
|
||||
"shipped_at": { "type": "number" },
|
||||
"fixed_build": { "type": "integer", "minimum": 0 },
|
||||
"installed_at": { "type": "number" },
|
||||
"missing": { "type": "integer", "minimum": 0, "description": "Ticks the part was not on the board (a Ship may be closing it)." }
|
||||
},
|
||||
"required": ["state", "repo", "title", "count", "starts"],
|
||||
"additionalProperties": false
|
||||
}
|
||||
}
|
||||
}
|
||||
199
app_errors/app_errors/tests/test_ingest.py
Normal file
199
app_errors/app_errors/tests/test_ingest.py
Normal file
@ -0,0 +1,199 @@
|
||||
"""The ingest: RTDB and local spools in, one board report per app out."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from app_errors import cli, ingest, spool
|
||||
from app_errors.rtdb import RtdbError
|
||||
from app_errors.tests.checkout import make_checkout
|
||||
|
||||
|
||||
class FakeRtdb:
|
||||
"""An in-memory RTDB: ``get`` honours ``shallow``, ``patch`` deletes on None."""
|
||||
|
||||
def __init__(self, data: dict[str, object]) -> None:
|
||||
self.data = data
|
||||
self.patches: list[tuple[str, dict[str, object]]] = []
|
||||
self.fail = False
|
||||
|
||||
def _at(self, path: str) -> object:
|
||||
node: object = self.data
|
||||
for part in [p for p in path.split("/") if p]:
|
||||
if not isinstance(node, dict) or part not in node:
|
||||
return None
|
||||
node = node[part]
|
||||
return node
|
||||
|
||||
def get(self, path: str, *, shallow: bool = False) -> object:
|
||||
if self.fail:
|
||||
raise RtdbError("down")
|
||||
node = self._at(path)
|
||||
if shallow and isinstance(node, dict):
|
||||
return dict.fromkeys(node, True)
|
||||
return node
|
||||
|
||||
def patch(self, path: str, data: dict[str, object]) -> None:
|
||||
self.patches.append((path, data))
|
||||
for key, value in data.items():
|
||||
parts = [p for p in f"{path}/{key}".split("/") if p]
|
||||
node = self.data
|
||||
for part in parts[:-1]:
|
||||
node = node.setdefault(part, {}) # type: ignore[assignment]
|
||||
if value is None:
|
||||
node.pop(parts[-1], None)
|
||||
else:
|
||||
node[parts[-1]] = value
|
||||
|
||||
|
||||
def _crash(at: str) -> dict[str, object]:
|
||||
return {
|
||||
"repo": "kuhyx/todo",
|
||||
"at": at,
|
||||
"kind": "uncaught.flutter",
|
||||
"error": "Bad state: x",
|
||||
"build": 3,
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def dirs(tmp_path: Path) -> ingest.Paths:
|
||||
return ingest.Paths(
|
||||
state=tmp_path / "ingest" / "state.json",
|
||||
reports=tmp_path / "app-errors",
|
||||
spool=tmp_path / "app-errors-spool",
|
||||
src_root=tmp_path / "src",
|
||||
)
|
||||
|
||||
|
||||
def test_rtdb_entries_become_reports_and_are_deleted(dirs: ingest.Paths) -> None:
|
||||
db = FakeRtdb({
|
||||
"todo": {"errors": {"dev1": {"e1": _crash("2026-11-17T10:00:00Z"), "e2": _crash("2026-11-17T10:00:01Z")}}},
|
||||
# kartka's own pre-0.9 uploader shape: sourceId, build per entry.
|
||||
"kartka": {"errors": {"dev": {"k": {**_crash("2026-11-17T10:00:00Z"), "sourceId": "mangadex", "build": 556}}}},
|
||||
"other": {"data": 1},
|
||||
}) # fmt: skip
|
||||
summary = ingest.run(dirs, db)
|
||||
assert summary.merged == 3
|
||||
report = json.loads((dirs.reports / "todo.json").read_text())
|
||||
assert report["errors"][0]["count"] == 2
|
||||
kartka = json.loads((dirs.reports / "kartka.json").read_text()) # kartka moved over 2026-11-17
|
||||
assert kartka["errors"][0]["build"] == 556
|
||||
assert db.data["todo"] == {"errors": {"dev1": {}}} # ingested entries are removed from RTDB
|
||||
assert db.data["kartka"] == {"errors": {"dev": {}}}
|
||||
|
||||
|
||||
def test_keep_leaves_rtdb_and_still_counts_once(dirs: ingest.Paths) -> None:
|
||||
db = FakeRtdb({"todo": {"errors": {"d": {"e": _crash("2026-11-17T10:00:00Z")}}}})
|
||||
ingest.run(dirs, db, keep=True)
|
||||
ingest.run(dirs, db, keep=True)
|
||||
report = json.loads((dirs.reports / "todo.json").read_text())
|
||||
assert report["errors"][0]["count"] == 1
|
||||
assert db.patches == []
|
||||
|
||||
|
||||
def test_rtdb_down_still_ingests_spool(dirs: ingest.Paths) -> None:
|
||||
spool.append(dirs.spool, "tk-app", {"repo": "kuhyx/tk", "at": "2026-11-17T10:00:00Z",
|
||||
"kind": "uncaught.python", "error": "ValueError: x"}) # fmt: skip
|
||||
db = FakeRtdb({})
|
||||
db.fail = True
|
||||
summary = ingest.run(dirs, db)
|
||||
assert summary.merged == 1
|
||||
assert summary.rtdb_error == "down"
|
||||
assert json.loads((dirs.reports / "tk-app.json").read_text())["errors"][0]["repo"] == "kuhyx/tk"
|
||||
assert list(dirs.spool.glob("*")) == [] # the spool is consumed
|
||||
|
||||
|
||||
def test_report_without_repo_takes_the_checkouts_origin(dirs: ingest.Paths) -> None:
|
||||
# Regression: a report with no repo was filed under a guessed kuhyx/<app>;
|
||||
# the checkout's origin names the real one (here Sepci0/cleanup-plate).
|
||||
make_checkout(dirs.src_root / "cleanup-plate", "git@github.com:Sepci0/cleanup-plate.git")
|
||||
spool.append(dirs.spool, "cleanup-plate", {"at": "2026-11-17T10:00:00Z", "kind": "k", "error": "e"})
|
||||
spool.append(dirs.spool, "kartka", {"at": "2026-11-17T10:00:00Z", "kind": "k", "error": "e"})
|
||||
assert ingest.run(dirs, None).merged == 2
|
||||
repos = {app: json.loads((dirs.reports / f"{app}.json").read_text())["errors"][0]["repo"]
|
||||
for app in ("cleanup-plate", "kartka")} # fmt: skip
|
||||
assert repos == {"cleanup-plate": "Sepci0/cleanup-plate", "kartka": "kuhyx/kartka"}
|
||||
|
||||
|
||||
def test_no_rtdb_at_all(dirs: ingest.Paths) -> None:
|
||||
assert ingest.run(dirs, None).merged == 0
|
||||
|
||||
|
||||
def test_spool_bad_lines_and_bad_names_are_skipped(dirs: ingest.Paths) -> None:
|
||||
dirs.spool.mkdir(parents=True)
|
||||
(dirs.spool / "ok.jsonl").write_text('not json\n{"at": "2026-11-17T10:00:00Z", "kind": "k", "error": "e"}\n[]\n')
|
||||
(dirs.spool / "Bad Name.jsonl").write_text('{"at": "x", "kind": "k", "error": "e"}\n')
|
||||
assert ingest.run(dirs, None).merged == 1
|
||||
|
||||
|
||||
def test_leftover_claimed_spool_is_ingested(dirs: ingest.Paths) -> None:
|
||||
dirs.spool.mkdir(parents=True)
|
||||
(dirs.spool / "ok.jsonl.ingesting").write_text('{"at": "2026-11-17T10:00:00Z", "kind": "k", "error": "e"}\n')
|
||||
assert ingest.run(dirs, None).merged == 1
|
||||
assert list(dirs.spool.glob("*")) == []
|
||||
|
||||
|
||||
def test_rtdb_odd_shapes_are_skipped(dirs: ingest.Paths) -> None:
|
||||
db = FakeRtdb(
|
||||
{
|
||||
"todo": {"errors": {"d": "nope", "e": {"x": "nope"}}},
|
||||
"bad key!": {"errors": {}},
|
||||
}
|
||||
)
|
||||
assert ingest.run(dirs, db).merged == 0
|
||||
|
||||
|
||||
def test_cli_ingest_and_resolve(dirs: ingest.Paths, monkeypatch: pytest.MonkeyPatch,
|
||||
capsys: pytest.CaptureFixture[str]) -> None: # fmt: skip
|
||||
monkeypatch.setattr(ingest, "default_paths", lambda: dirs)
|
||||
spool.append(dirs.spool, "tk", {"at": "2026-11-17T10:00:00Z", "kind": "k", "error": "e"})
|
||||
assert cli.main(["ingest", "--no-rtdb"]) == 0
|
||||
sig = json.loads((dirs.reports / "tk.json").read_text())["errors"][0]["signature"]
|
||||
assert cli.main(["resolve", "tk", sig]) == 0
|
||||
assert json.loads((dirs.reports / "tk.json").read_text())["errors"][0]["open"] is False
|
||||
assert cli.main(["resolve", "tk", "missing"]) == 1
|
||||
assert "unknown" in capsys.readouterr().err
|
||||
|
||||
|
||||
def test_cli_ingest_rtdb_session_missing(dirs: ingest.Paths, monkeypatch: pytest.MonkeyPatch,
|
||||
capsys: pytest.CaptureFixture[str]) -> None: # fmt: skip
|
||||
monkeypatch.setattr(ingest, "default_paths", lambda: dirs)
|
||||
|
||||
def no_session(_app: str) -> FakeRtdb:
|
||||
raise RtdbError("no session")
|
||||
|
||||
monkeypatch.setattr(cli, "open_rtdb", no_session)
|
||||
spool.append(dirs.spool, "tk", {"at": "2026-11-17T10:00:00Z", "kind": "k", "error": "e"})
|
||||
assert cli.main(["ingest"]) == 1 # the spool still went in, but RTDB is reported broken
|
||||
assert (dirs.reports / "tk.json").exists()
|
||||
assert "no session" in capsys.readouterr().err
|
||||
|
||||
|
||||
def test_cli_ingest_with_rtdb(dirs: ingest.Paths, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setattr(ingest, "default_paths", lambda: dirs)
|
||||
db = FakeRtdb({"todo": {"errors": {"d": {"e": _crash("2026-11-17T10:00:00Z")}}}})
|
||||
monkeypatch.setattr(cli, "open_rtdb", lambda _app: db)
|
||||
assert cli.main(["ingest", "--keep", "--session", "x"]) == 0
|
||||
assert (dirs.reports / "todo.json").exists()
|
||||
|
||||
|
||||
def test_default_paths_follow_xdg(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
|
||||
monkeypatch.setenv("XDG_STATE_HOME", str(tmp_path))
|
||||
paths = ingest.default_paths()
|
||||
assert paths.reports == tmp_path / "app-errors"
|
||||
assert paths.spool == tmp_path / "app-errors-spool"
|
||||
assert paths.state == tmp_path / "app-errors-ingest" / "state.json"
|
||||
|
||||
|
||||
def test_help_ends_with_credit_line(capsys: pytest.CaptureFixture[str]) -> None:
|
||||
"""--help output ends with the kuhy credit line."""
|
||||
from kuhy_credit import credit_line
|
||||
|
||||
with pytest.raises(SystemExit):
|
||||
cli.main(["--help"])
|
||||
out = capsys.readouterr().out
|
||||
assert out.strip().endswith(credit_line())
|
||||
74
app_errors/app_errors/tests/test_origin.py
Normal file
74
app_errors/app_errors/tests/test_origin.py
Normal file
@ -0,0 +1,74 @@
|
||||
"""Origin lookup: every remote URL form, and every way a checkout has none."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
|
||||
from app_errors import origin as _origin
|
||||
from app_errors.origin import origin_slug, repo_slug, slug_from_url
|
||||
from app_errors.tests.checkout import make_checkout
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"url",
|
||||
[
|
||||
"https://github.com/Sepci0/cleanup-plate",
|
||||
"https://github.com/Sepci0/cleanup-plate.git",
|
||||
"https://github.com/Sepci0/cleanup-plate/\n",
|
||||
"https://kuhy@github.com/Sepci0/cleanup-plate.git",
|
||||
"git@github.com:Sepci0/cleanup-plate.git",
|
||||
"ssh://git@github.com/Sepci0/cleanup-plate",
|
||||
"ssh://git@github.com:22/Sepci0/cleanup-plate.git",
|
||||
],
|
||||
)
|
||||
def test_github_urls_give_the_slug(url: str) -> None:
|
||||
assert slug_from_url(url) == "Sepci0/cleanup-plate"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"url",
|
||||
[
|
||||
"/home/someone/mirror/cleanup-plate",
|
||||
"file:///srv/git/cleanup-plate.git",
|
||||
"https://gitea.example.org/Sepci0/cleanup-plate.git",
|
||||
"https://github.com/Sepci0",
|
||||
"https://github.com/Sepci0/cleanup-plate/extra",
|
||||
"",
|
||||
],
|
||||
)
|
||||
def test_other_urls_give_none(url: str) -> None:
|
||||
assert slug_from_url(url) is None
|
||||
|
||||
|
||||
def test_checkout_origin_is_read(tmp_path: Path) -> None:
|
||||
repo = make_checkout(tmp_path / "todo", "https://github.com/kuhyx/todo-app.git")
|
||||
assert origin_slug(repo) == "kuhyx/todo-app"
|
||||
|
||||
|
||||
def test_no_checkout_or_no_origin_is_none(tmp_path: Path) -> None:
|
||||
(tmp_path / "plain").mkdir()
|
||||
assert origin_slug(tmp_path / "missing") is None
|
||||
assert origin_slug(tmp_path / "plain") is None
|
||||
assert origin_slug(make_checkout(tmp_path / "bare", None)) is None
|
||||
|
||||
|
||||
def test_missing_or_hung_git_is_none(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
repo = make_checkout(tmp_path / "todo", "https://github.com/kuhyx/todo-app")
|
||||
|
||||
def hang(*args: object, **kwargs: object) -> None:
|
||||
raise subprocess.TimeoutExpired("git", _origin.GIT_TIMEOUT)
|
||||
|
||||
monkeypatch.setattr(subprocess, "run", hang)
|
||||
assert origin_slug(repo) is None
|
||||
monkeypatch.setattr(shutil, "which", lambda _: None)
|
||||
assert origin_slug(repo) is None
|
||||
|
||||
|
||||
def test_repo_slug_falls_back_to_the_owner_guess(tmp_path: Path) -> None:
|
||||
make_checkout(tmp_path / "todo", "git@github.com:kuhyx/todo-app.git")
|
||||
assert repo_slug(tmp_path, "todo", "kuhyx") == "kuhyx/todo-app"
|
||||
assert repo_slug(tmp_path, "museum", "kuhyx") == "kuhyx/museum"
|
||||
140
app_errors/app_errors/tests/test_rtdb.py
Normal file
140
app_errors/app_errors/tests/test_rtdb.py
Normal file
@ -0,0 +1,140 @@
|
||||
"""The REST client: URLs, shallow reads, typed errors that never name the token."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import email.message
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import types
|
||||
from typing import cast
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
import pytest
|
||||
|
||||
from app_errors import ingest, rtdb, store
|
||||
from app_errors.rtdb import RestRtdb, RtdbError
|
||||
|
||||
|
||||
class _Res(io.BytesIO):
|
||||
def __enter__(self) -> _Res:
|
||||
return self
|
||||
|
||||
def __exit__(self, *_: object) -> None:
|
||||
self.close()
|
||||
|
||||
|
||||
def test_get_and_patch_build_urls() -> None:
|
||||
seen: list[tuple[str, str, object]] = []
|
||||
|
||||
def opener(req: urllib.request.Request, timeout: float) -> _Res:
|
||||
seen.append((req.get_method(), req.full_url, req.data))
|
||||
return _Res(b'{"a": true}')
|
||||
|
||||
db = RestRtdb("https://db.example/", lambda: "TOK", opener)
|
||||
assert db.get("", shallow=True) == {"a": True}
|
||||
db.patch("todo/errors", {"d/e": None})
|
||||
assert seen[0][:2] == ("GET", "https://db.example/.json?auth=TOK&shallow=true")
|
||||
assert seen[1][0] == "PATCH"
|
||||
assert json.loads(cast("bytes", seen[1][2])) == {"d/e": None}
|
||||
|
||||
|
||||
def test_empty_body_is_none() -> None:
|
||||
assert RestRtdb("https://x", lambda: "t", lambda req, timeout: _Res(b"")).get("p") is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"exc",
|
||||
[
|
||||
urllib.error.HTTPError("u", 401, "no", email.message.Message(), None),
|
||||
urllib.error.URLError("down"),
|
||||
OSError("x"),
|
||||
],
|
||||
)
|
||||
def test_failures_are_typed_and_tokenless(exc: Exception) -> None:
|
||||
def opener(req: urllib.request.Request, timeout: float) -> _Res:
|
||||
raise exc
|
||||
|
||||
with pytest.raises(RtdbError) as info:
|
||||
RestRtdb("https://x", lambda: "SECRET", opener).get("p")
|
||||
assert "SECRET" not in str(info.value)
|
||||
|
||||
|
||||
def test_token_failure_is_typed() -> None:
|
||||
def boom() -> str:
|
||||
raise ValueError("SECRET")
|
||||
|
||||
with pytest.raises(RtdbError, match="token refresh failed"):
|
||||
RestRtdb("https://x", boom).get("p")
|
||||
|
||||
|
||||
def _fake_crdt(monkeypatch: pytest.MonkeyPatch, *, session: bool, config_ok: bool = True) -> None:
|
||||
mod = types.ModuleType("crdt_sync")
|
||||
|
||||
class Config:
|
||||
api_key, database_url = "k", "https://db"
|
||||
|
||||
@staticmethod
|
||||
def load() -> Config:
|
||||
if not config_ok:
|
||||
raise FileNotFoundError("cfg")
|
||||
return Config()
|
||||
|
||||
class Provider:
|
||||
def __init__(self, *_: object, **__: object) -> None: ...
|
||||
def has_session(self) -> bool:
|
||||
return session
|
||||
|
||||
def id_token(self) -> str:
|
||||
return "t"
|
||||
|
||||
mod.FirebaseConfig = Config # type: ignore[attr-defined]
|
||||
mod.FirebaseTokenProvider = Provider # type: ignore[attr-defined]
|
||||
mod.credential_store_for = lambda name: name # type: ignore[attr-defined]
|
||||
monkeypatch.setitem(sys.modules, "crdt_sync", mod)
|
||||
|
||||
|
||||
def test_open_rtdb(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
_fake_crdt(monkeypatch, session=True)
|
||||
assert isinstance(rtdb.open_rtdb("s"), RestRtdb)
|
||||
_fake_crdt(monkeypatch, session=False)
|
||||
with pytest.raises(RtdbError, match="no seeded"):
|
||||
rtdb.open_rtdb("s")
|
||||
_fake_crdt(monkeypatch, session=True, config_ok=False)
|
||||
with pytest.raises(RtdbError, match="no Firebase config"):
|
||||
rtdb.open_rtdb("s")
|
||||
|
||||
|
||||
class _PatchFails:
|
||||
def get(self, path: str, *, shallow: bool = False) -> object:
|
||||
if shallow:
|
||||
return {"todo": True}
|
||||
return {"d": {"e": {"at": "2026-11-17T10:00:00Z", "kind": "k", "error": "x"}}}
|
||||
|
||||
def patch(self, path: str, data: dict[str, object]) -> None:
|
||||
raise RtdbError("patch down")
|
||||
|
||||
|
||||
def test_delete_failure_is_reported_after_save(tmp_path: Path) -> None:
|
||||
paths = ingest.Paths(tmp_path / "s.json", tmp_path / "r", tmp_path / "sp", tmp_path / "src")
|
||||
summary = ingest.run(paths, _PatchFails())
|
||||
assert summary == ingest.Summary(1, "patch down")
|
||||
assert (tmp_path / "r" / "todo.json").exists()
|
||||
|
||||
|
||||
def test_old_state_version_and_seen_trim(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
path = tmp_path / "s.json"
|
||||
path.write_text('{"version": 0}')
|
||||
assert store.load(path) == store.empty()
|
||||
monkeypatch.setattr(store, "MAX_SEEN", 2)
|
||||
state = store.empty()
|
||||
for i in range(3):
|
||||
store.merge(
|
||||
state,
|
||||
"a",
|
||||
str(i),
|
||||
{"at": f"2026-11-17T10:00:0{i}Z", "kind": "k", "error": "x"},
|
||||
)
|
||||
assert list(state["seen"]) == ["a/1", "a/2"]
|
||||
89
app_errors/app_errors/tests/test_signature.py
Normal file
89
app_errors/app_errors/tests/test_signature.py
Normal file
@ -0,0 +1,89 @@
|
||||
"""Signatures: one per bug, kartka-identical for Dart, generalised for Python and GDScript."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app_errors.signature import normalise, signature, top_frame
|
||||
|
||||
|
||||
def test_dart_crash_matches_kartka_vector() -> None:
|
||||
# Vector from kartka_errors.signature (kartka 2026-11-17): moving kartka
|
||||
# onto this ingest must not rename its open tickets.
|
||||
entry = {
|
||||
"kind": "uncaught.flutter",
|
||||
"error": "Bad state: no element 42",
|
||||
"stack": [
|
||||
"#0 List.first (dart:core/list.dart:12:3)",
|
||||
"#1 Reader.open (package:kartka/reader/reader.dart:88:7)",
|
||||
],
|
||||
}
|
||||
sig = signature(entry, app="kartka")
|
||||
assert sig.id == "ffcd864656"
|
||||
assert sig.type == "StateError"
|
||||
assert sig.where == "Reader.open (package:kartka/reader/reader.dart)"
|
||||
|
||||
|
||||
def test_slow_wait_matches_kartka_vector() -> None:
|
||||
entry = {
|
||||
"kind": "perf.slow",
|
||||
"operation": "reader.open",
|
||||
"route": "/reader/:id",
|
||||
"durationMs": 2100,
|
||||
}
|
||||
sig = signature(entry, app="kartka")
|
||||
assert sig.id == "29a53e8824"
|
||||
assert sig.message == "slow wait: reader.open"
|
||||
|
||||
|
||||
def test_slow_wait_ignores_duration() -> None:
|
||||
one = {"kind": "perf.slow", "operation": "load", "durationMs": 1100}
|
||||
two = {"kind": "perf.slow", "operation": "load", "durationMs": 9000}
|
||||
assert signature(one, app="a").id == signature(two, app="a").id
|
||||
|
||||
|
||||
def test_mark_picks_app_frame_and_skips_plumbing() -> None:
|
||||
stack = [
|
||||
"#0 ErrorReporter.report (package:crdt_sync_flutter/src/errors/error_reporter.dart:5:1)",
|
||||
"#1 Home.build (package:todo/home.dart:10:2)",
|
||||
]
|
||||
assert top_frame(stack, "package:todo/") == "Home.build (package:todo/home.dart)"
|
||||
|
||||
|
||||
def test_python_frame_line_numbers_dropped() -> None:
|
||||
entry = {
|
||||
"kind": "uncaught.python",
|
||||
"error": "ValueError: bad 12",
|
||||
"stack": [
|
||||
"gatelock/error_report.py:40 in hook",
|
||||
"leetcode_guard/ui.py:123 in solve",
|
||||
],
|
||||
"mark": "leetcode_guard/",
|
||||
}
|
||||
sig = signature(entry, app="leetcode-guard")
|
||||
assert sig.where == "leetcode_guard/ui.py in solve"
|
||||
assert sig.type == "ValueError"
|
||||
assert sig.message == "ValueError: bad <n>"
|
||||
|
||||
|
||||
def test_godot_frame_and_kind_fallback() -> None:
|
||||
entry = {
|
||||
"kind": "uncaught.gdscript",
|
||||
"error": "Invalid access to property 'x'",
|
||||
"stack": [
|
||||
"res://addons/app_errors/error_reporter.gd:9 in _log",
|
||||
"res://scripts/car.gd:77 in _ready",
|
||||
],
|
||||
"mark": "res://",
|
||||
}
|
||||
sig = signature(entry, app="car-rental-sim")
|
||||
assert sig.where == "res://scripts/car.gd in _ready"
|
||||
assert sig.type == "uncaught.gdscript"
|
||||
|
||||
|
||||
def test_no_frame_falls_back_to_route_then_kind() -> None:
|
||||
assert signature({"kind": "ui.snackbar", "error": "x", "route": "/a"}, app="a").where == "route /a"
|
||||
assert signature({"kind": "ui.snackbar", "error": "x"}, app="a").where == "kind ui.snackbar"
|
||||
|
||||
|
||||
def test_normalise_masks_volatile_parts() -> None:
|
||||
text = "GET https://x.y/z 3f2a9c1d00ff 123e4567-e89b-12d3-a456-426614174000 took 15 s"
|
||||
assert normalise(text) == "GET <url> <hex> <uuid> took <n> s"
|
||||
144
app_errors/app_errors/tests/test_store.py
Normal file
144
app_errors/app_errors/tests/test_store.py
Normal file
@ -0,0 +1,144 @@
|
||||
"""The merged state: counts, builds, resolve and reopen, and the board report."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import jsonschema
|
||||
|
||||
from app_errors import store
|
||||
|
||||
SCHEMA = json.loads((Path(__file__).parent / "data" / "app-error.schema.json").read_text())
|
||||
|
||||
|
||||
def _crash(at: str, build: int = 7, **extra: object) -> dict[str, object]:
|
||||
return {
|
||||
"app": "todo",
|
||||
"repo": "kuhyx/todo",
|
||||
"at": at,
|
||||
"kind": "uncaught.flutter",
|
||||
"error": "Bad state: boom",
|
||||
"stack": ["#0 Home.build (package:todo/home.dart:3:1)"],
|
||||
"build": build,
|
||||
"version": "1.0.0",
|
||||
**extra,
|
||||
}
|
||||
|
||||
|
||||
def _report(state: store.State, app: str) -> dict[str, object]:
|
||||
report = store.report(state, app)
|
||||
jsonschema.Draft202012Validator({**SCHEMA, "$ref": "#/$defs/report"}).validate(report)
|
||||
return report
|
||||
|
||||
|
||||
def test_ten_identical_errors_are_one_record_with_count_ten() -> None:
|
||||
state = store.empty()
|
||||
for i in range(10):
|
||||
assert store.merge(state, "todo", f"dev/{i}", _crash(f"2026-11-17T10:00:{i:02d}Z"))
|
||||
errors = _report(state, "todo")["errors"]
|
||||
assert isinstance(errors, list)
|
||||
assert len(errors) == 1
|
||||
rec = errors[0]
|
||||
assert rec["count"] == 10
|
||||
assert rec["first_seen"] == "2026-11-17T10:00:00Z"
|
||||
assert rec["last_seen"] == "2026-11-17T10:00:09Z"
|
||||
assert rec["build"] == 7
|
||||
assert rec["version_name"] == "1.0.0"
|
||||
assert rec["open"] is True
|
||||
assert rec["repo"] == "kuhyx/todo"
|
||||
|
||||
|
||||
def test_same_entry_id_counts_once() -> None:
|
||||
state = store.empty()
|
||||
assert store.merge(state, "todo", "dev/a", _crash("2026-11-17T10:00:00Z"))
|
||||
assert not store.merge(state, "todo", "dev/a", _crash("2026-11-17T10:00:00Z"))
|
||||
assert state["apps"]["todo"][next(iter(state["apps"]["todo"]))]["count"] == 1
|
||||
|
||||
|
||||
def test_newest_build_wins() -> None:
|
||||
state = store.empty()
|
||||
store.merge(state, "todo", "a", _crash("2026-11-17T10:00:00Z", build=9))
|
||||
store.merge(state, "todo", "b", _crash("2026-11-17T11:00:00Z", build=4))
|
||||
assert _report(state, "todo")["errors"][0]["build"] == 9 # type: ignore[index]
|
||||
|
||||
|
||||
def test_slow_wait_detail_names_longest_wait() -> None:
|
||||
state = store.empty()
|
||||
for i, ms in enumerate((1500, 2100)):
|
||||
store.merge(
|
||||
state,
|
||||
"todo",
|
||||
f"w{i}",
|
||||
{"app": "todo", "repo": "kuhyx/todo", "at": f"2026-11-17T10:00:0{i}Z", "kind": "perf.slow",
|
||||
"error": f"list.load waited {ms} ms", "operation": "list.load", "route": "/", "durationMs": ms},
|
||||
) # fmt: skip
|
||||
rec = _report(state, "todo")["errors"][0] # type: ignore[index]
|
||||
assert rec["kind"] == "perf.slow"
|
||||
assert rec["count"] == 2
|
||||
assert "2100 ms" in rec["detail"]
|
||||
assert rec["build"] == 0
|
||||
|
||||
|
||||
def test_resolve_closes_and_older_build_does_not_reopen() -> None:
|
||||
state = store.empty()
|
||||
store.merge(state, "todo", "a", _crash("2026-11-17T10:00:00Z", build=7))
|
||||
sig = _report(state, "todo")["errors"][0]["signature"] # type: ignore[index]
|
||||
assert store.resolve(state, "todo", sig, now="2026-11-17T12:00:00Z")
|
||||
assert _report(state, "todo")["errors"][0]["open"] is False # type: ignore[index]
|
||||
store.merge(state, "todo", "b", _crash("2026-11-17T13:00:00Z", build=7))
|
||||
assert _report(state, "todo")["errors"][0]["open"] is False # type: ignore[index]
|
||||
store.merge(state, "todo", "c", _crash("2026-11-17T14:00:00Z", build=8))
|
||||
assert _report(state, "todo")["errors"][0]["open"] is True # type: ignore[index]
|
||||
|
||||
|
||||
def test_resolve_without_build_reopens_on_later_report() -> None:
|
||||
state = store.empty()
|
||||
store.merge(state, "tk", "a", _crash("2026-11-17T10:00:00Z", build=0, app="tk"))
|
||||
sig = _report(state, "tk")["errors"][0]["signature"] # type: ignore[index]
|
||||
store.resolve(state, "tk", sig, now="2026-11-17T12:00:00Z")
|
||||
store.merge(state, "tk", "b", _crash("2026-11-17T11:00:00Z", build=0, app="tk"))
|
||||
assert _report(state, "tk")["errors"][0]["open"] is False # type: ignore[index]
|
||||
store.merge(state, "tk", "c", _crash("2026-11-17T13:00:00Z", build=0, app="tk"))
|
||||
assert _report(state, "tk")["errors"][0]["open"] is True # type: ignore[index]
|
||||
|
||||
|
||||
def test_resolve_unknown_signature_is_false() -> None:
|
||||
assert not store.resolve(store.empty(), "todo", "nope", now="2026-11-17T12:00:00Z")
|
||||
|
||||
|
||||
def test_missing_repo_defaults_to_kuhyx_app() -> None:
|
||||
state = store.empty()
|
||||
entry = _crash("2026-11-17T10:00:00Z")
|
||||
del entry["repo"]
|
||||
store.merge(state, "todo", "a", entry)
|
||||
assert _report(state, "todo")["errors"][0]["repo"] == "kuhyx/todo" # type: ignore[index]
|
||||
|
||||
|
||||
def test_bad_entry_is_skipped() -> None:
|
||||
state = store.empty()
|
||||
assert not store.merge(state, "todo", "a", {"kind": 3})
|
||||
assert not store.merge(state, "todo", "b", "nope")
|
||||
assert store.report(state, "todo")["errors"] == []
|
||||
|
||||
|
||||
def test_save_and_load_round_trip(tmp_path: Path) -> None:
|
||||
state = store.empty()
|
||||
store.merge(state, "todo", "a", _crash("2026-11-17T10:00:00Z"))
|
||||
path = tmp_path / "s" / "state.json"
|
||||
store.save(path, state)
|
||||
assert store.load(path) == state
|
||||
path.write_text("{broken")
|
||||
assert store.load(path) == store.empty()
|
||||
assert store.load(tmp_path / "missing.json") == store.empty()
|
||||
|
||||
|
||||
def test_write_reports_writes_one_file_per_app(tmp_path: Path) -> None:
|
||||
state = store.empty()
|
||||
store.merge(state, "todo", "a", _crash("2026-11-17T10:00:00Z"))
|
||||
store.merge(state, "tk", "a", _crash("2026-11-17T10:00:00Z", app="tk"))
|
||||
written = store.write_reports(tmp_path, state)
|
||||
assert sorted(p.name for p in written) == ["tk.json", "todo.json"]
|
||||
data = json.loads((tmp_path / "todo.json").read_text())
|
||||
assert data["version"] == 1
|
||||
assert len(data["errors"]) == 1
|
||||
55
app_errors/install.sh
Executable file
55
app_errors/install.sh
Executable file
@ -0,0 +1,55 @@
|
||||
#!/bin/bash
|
||||
|
||||
# ============================================================================
|
||||
# Install the app-errors CLI and its ingest timer for the current user.
|
||||
#
|
||||
# Own venv at ~/.local/share/app-errors/venv, the package installed editable
|
||||
# from this checkout (run it from the live ~/src/utils, never a worktree).
|
||||
# crdt-sync comes from the sibling directory, so the venv runs what is on disk.
|
||||
# Idempotent: rerun it after any change. Exits non-zero unless the timer is
|
||||
# active and one ingest pass over the local spool succeeds.
|
||||
# ============================================================================
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
REPO_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
UTILS_DIR="$(dirname "$REPO_DIR")"
|
||||
readonly REPO_DIR UTILS_DIR
|
||||
readonly VENV_DIR="${HOME}/.local/share/app-errors/venv"
|
||||
readonly BIN_DIR="${HOME}/.local/bin"
|
||||
readonly UNIT_DIR="${HOME}/.config/systemd/user"
|
||||
readonly TIMER="app-errors-ingest.timer"
|
||||
|
||||
log() { printf 'install: %s\n' "$1" >&2; }
|
||||
fail() { printf 'install: FAILED -- %s\n' "$1" >&2; exit 1; }
|
||||
|
||||
build_venv() {
|
||||
[[ -x "$VENV_DIR/bin/python" ]] || /usr/bin/python3 -m venv "$VENV_DIR" || fail "venv"
|
||||
"$VENV_DIR/bin/pip" install --quiet "$UTILS_DIR/crdt-sync" || fail "crdt-sync"
|
||||
"$VENV_DIR/bin/pip" install --quiet --no-deps "$UTILS_DIR/kuhy_credit" || fail "kuhy_credit"
|
||||
"$VENV_DIR/bin/pip" install --quiet --no-deps -e "$REPO_DIR" || fail "app-errors"
|
||||
mkdir -p "$BIN_DIR"
|
||||
ln -sf "$VENV_DIR/bin/app-errors" "$BIN_DIR/app-errors"
|
||||
}
|
||||
|
||||
install_timer() {
|
||||
mkdir -p "$UNIT_DIR"
|
||||
install -m 0644 "$REPO_DIR/systemd/app-errors-ingest.service" "$REPO_DIR/systemd/$TIMER" "$UNIT_DIR/"
|
||||
systemctl --user daemon-reload
|
||||
systemctl --user enable --now "$TIMER"
|
||||
}
|
||||
|
||||
verify() {
|
||||
systemctl --user is-active --quiet "$TIMER" || fail "$TIMER is not active"
|
||||
"$VENV_DIR/bin/app-errors" ingest --no-rtdb >/dev/null || fail "a spool-only ingest pass failed"
|
||||
log "ok: $TIMER active, ingest runs"
|
||||
}
|
||||
|
||||
main() {
|
||||
log "installing app-errors from $REPO_DIR"
|
||||
build_venv
|
||||
install_timer
|
||||
verify
|
||||
}
|
||||
|
||||
main "$@"
|
||||
186
app_errors/pyproject.toml
Normal file
186
app_errors/pyproject.toml
Normal file
@ -0,0 +1,186 @@
|
||||
[project]
|
||||
name = "app-errors"
|
||||
version = "0.1.4"
|
||||
description = "Shared app error and slow-wait ingest: RTDB and local spool reports become todoImplementer error tickets"
|
||||
requires-python = ">=3.14"
|
||||
dependencies = [
|
||||
"crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync",
|
||||
"kuhy-credit @ git+https://github.com/kuhyx/utils@kuhy-credit-v0.3.2#subdirectory=kuhy_credit",
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
test = ["jsonschema==4.26.0", "pytest==9.2.0", "pytest-cov==7.1.0"]
|
||||
|
||||
[project.scripts]
|
||||
app-errors = "app_errors.cli:main"
|
||||
|
||||
[tool.setuptools]
|
||||
packages = ["app_errors"]
|
||||
|
||||
# py.typed: consumers type-check against the package (PEP 561).
|
||||
[tool.setuptools.package-data]
|
||||
app_errors = ["py.typed"]
|
||||
|
||||
[tool.ruff]
|
||||
target-version = "py314"
|
||||
line-length = 120
|
||||
include = ["*.py", "**/*.py"]
|
||||
exclude = [".git", ".venv", "__pycache__", "build", "dist", ".eggs"]
|
||||
|
||||
[tool.ruff.lint]
|
||||
select = ["ALL"]
|
||||
ignore = [
|
||||
"D203",
|
||||
"D213",
|
||||
"COM812",
|
||||
"ISC001",
|
||||
"S603",
|
||||
]
|
||||
fixable = ["ALL"]
|
||||
unfixable = []
|
||||
|
||||
[tool.ruff.lint.per-file-ignores]
|
||||
"**/tests/*.py" = ["ANN", "ARG", "CPY001", "D", "EM101", "PLC0415", "PLR2004", "PYI034", "S101", "SLF001", "TC002", "TC003", "TRY003"]
|
||||
"**/_fake_*.py" = ["ANN401", "ARG002"]
|
||||
"**/test_*.py" = ["ANN", "ARG", "CPY001", "D", "EM101", "PLC0415", "PLR2004", "PYI034", "S101", "SLF001", "TC002", "TC003", "TRY003"]
|
||||
|
||||
|
||||
[tool.ruff.lint.pydocstyle]
|
||||
convention = "google"
|
||||
|
||||
[tool.ruff.lint.isort]
|
||||
force-single-line = false
|
||||
force-sort-within-sections = true
|
||||
known-first-party = ["app_errors"]
|
||||
|
||||
[tool.ruff.lint.flake8-quotes]
|
||||
docstring-quotes = "double"
|
||||
inline-quotes = "double"
|
||||
|
||||
[tool.ruff.lint.flake8-tidy-imports]
|
||||
ban-relative-imports = "all"
|
||||
|
||||
[tool.ruff.format]
|
||||
quote-style = "double"
|
||||
indent-style = "space"
|
||||
skip-magic-trailing-comma = false
|
||||
line-ending = "auto"
|
||||
docstring-code-format = true
|
||||
|
||||
[tool.mypy]
|
||||
python_version = "3.14"
|
||||
strict = true
|
||||
warn_return_any = true
|
||||
warn_unused_configs = true
|
||||
disallow_untyped_defs = true
|
||||
disallow_incomplete_defs = true
|
||||
check_untyped_defs = true
|
||||
disallow_untyped_decorators = true
|
||||
no_implicit_optional = true
|
||||
warn_redundant_casts = true
|
||||
warn_unused_ignores = true
|
||||
warn_no_return = true
|
||||
warn_unreachable = true
|
||||
# crdt_sync ships no py.typed: its names would all be "unfollowed".
|
||||
disallow_any_unimported = false
|
||||
disallow_any_explicit = false
|
||||
disallow_any_generics = true
|
||||
disallow_subclassing_any = true
|
||||
strict_equality = true
|
||||
extra_checks = true
|
||||
ignore_missing_imports = true
|
||||
show_error_codes = true
|
||||
color_output = true
|
||||
exclude = [".venv/"]
|
||||
|
||||
[tool.pylint.main]
|
||||
# The repo root on the path, so pylint resolves the package's own imports the
|
||||
# same way pytest does instead of reporting import-error for them.
|
||||
init-hook = "import sys; sys.path.insert(0, 'app_errors')"
|
||||
analyse-fallback-blocks = true
|
||||
persistent = true
|
||||
jobs = 0
|
||||
py-version = "3.14"
|
||||
ignore = [".venv", "__pycache__"]
|
||||
# Test suites intentionally use patterns (protected-access, fixture-arg
|
||||
# shadowing) that don't apply to source code; ruff's per-file-ignores carry
|
||||
# the equivalent exemptions, so tests stay linted -- by ruff. This is the same
|
||||
# source-only pylint scope wake-alarm / diet-guard / testsAndMisc use. It has
|
||||
# to be `ignore-paths`, not `ignore = ["tests"]`: `ignore` only matches the
|
||||
# basename of what pylint is *given*, and pre-commit hands it explicit file
|
||||
# paths, so a directory name in `ignore` never fires under the hook.
|
||||
ignore-paths = ["^(.*/)?tests/.*$"]
|
||||
ignore-patterns = [".*\\.pyi$"]
|
||||
|
||||
[tool.pylint.basic]
|
||||
# snake_case, plus the ``do_<METHOD>`` names http.server dispatches on: the
|
||||
# stdlib looks handlers up as ``"do_" + command``, so ``do_GET`` is the only
|
||||
# spelling that works and cannot be renamed to satisfy the style.
|
||||
method-rgx = "([^\\W\\dA-Z][^\\WA-Z]{2,}|_[^\\WA-Z]*|__[^\\W\\dA-Z][^\\WA-Z]+__|do_[A-Z]+|of)$"
|
||||
|
||||
[tool.pylint.messages_control]
|
||||
enable = "all"
|
||||
disable = []
|
||||
|
||||
[tool.pylint.design]
|
||||
min-public-methods = 0
|
||||
max-module-lines = 1000
|
||||
max-attributes = 10
|
||||
|
||||
[tool.pylint.typecheck]
|
||||
generated-members = [
|
||||
".*\\.assert_called_once_with",
|
||||
".*\\.assert_called_once",
|
||||
".*\\.assert_called",
|
||||
".*\\.assert_not_called",
|
||||
".*\\.assert_any_call",
|
||||
".*\\.call_args",
|
||||
".*\\.call_args_list",
|
||||
".*\\.call_count",
|
||||
]
|
||||
|
||||
[tool.bandit]
|
||||
exclude_dirs = ["tests", ".venv"]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
testpaths = ["app_errors/tests"]
|
||||
python_files = ["test_*.py", "*_test.py"]
|
||||
python_classes = ["Test*"]
|
||||
python_functions = ["test_*"]
|
||||
addopts = [
|
||||
"-v",
|
||||
"--strict-markers",
|
||||
"--strict-config",
|
||||
"-ra",
|
||||
"--cov=app_errors",
|
||||
"--cov-branch",
|
||||
"--cov-report=term-missing",
|
||||
"--cov-report=lcov",
|
||||
]
|
||||
filterwarnings = [
|
||||
"error",
|
||||
"ignore::DeprecationWarning",
|
||||
"default::pytest.PytestUnraisableExceptionWarning",
|
||||
]
|
||||
|
||||
[tool.coverage.run]
|
||||
source = ["app_errors"]
|
||||
branch = true
|
||||
omit = [
|
||||
"*/__pycache__/*",
|
||||
"*/tests/*",
|
||||
"*/.venv/*",
|
||||
]
|
||||
|
||||
[tool.coverage.report]
|
||||
show_missing = true
|
||||
skip_covered = false
|
||||
exclude_lines = [
|
||||
"pragma: no cover",
|
||||
"raise NotImplementedError",
|
||||
"raise AssertionError",
|
||||
"if TYPE_CHECKING:",
|
||||
"^\\s*\\.\\.\\.$",
|
||||
'if __name__ == "__main__":',
|
||||
]
|
||||
partial_branches = ["pragma: no branch"]
|
||||
5
app_errors/requirements.txt
Normal file
5
app_errors/requirements.txt
Normal file
@ -0,0 +1,5 @@
|
||||
# Exact pins, enforced by the shared dependency-freshness gate.
|
||||
crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync
|
||||
jsonschema==4.26.0
|
||||
pytest==9.2.0
|
||||
pytest-cov==7.1.0
|
||||
10
app_errors/systemd/app-errors-ingest.service
Normal file
10
app_errors/systemd/app-errors-ingest.service
Normal file
@ -0,0 +1,10 @@
|
||||
[Unit]
|
||||
Description=Ingest app error and slow-wait reports for the todoImplementer board
|
||||
After=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStart=%h/.local/share/app-errors/venv/bin/app-errors ingest
|
||||
Nice=19
|
||||
IOSchedulingClass=idle
|
||||
TimeoutStartSec=120
|
||||
10
app_errors/systemd/app-errors-ingest.timer
Normal file
10
app_errors/systemd/app-errors-ingest.timer
Normal file
@ -0,0 +1,10 @@
|
||||
[Unit]
|
||||
Description=Ingest app error reports every 5 minutes
|
||||
|
||||
[Timer]
|
||||
OnBootSec=2min
|
||||
OnUnitActiveSec=5min
|
||||
Persistent=true
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user