Compare commits

..

No commits in common. "main" and "sickdays-v0.5.9" have entirely different histories.

221 changed files with 2069 additions and 7694 deletions

View File

@ -28,7 +28,7 @@ jobs:
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 .
run: pip install -r requirements.txt && pip install --no-deps -e .
- name: Run tests
- name: Run tests with coverage
run: python -m pytest -v

View File

@ -27,5 +27,22 @@ jobs:
- name: Install dependencies
run: dart pub get
- name: Run tests
run: dart test
- 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

View File

@ -26,5 +26,11 @@ jobs:
- name: Install dependencies
run: flutter pub get
- name: Run tests
run: flutter test
- 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

View File

@ -16,9 +16,10 @@ jobs:
- 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
# 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
# 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
@ -47,6 +48,22 @@ 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

View File

@ -27,5 +27,5 @@ jobs:
- name: Install dependencies
run: pip install -r requirements.txt
- name: Run tests
- name: Run tests with coverage
run: python -m pytest -v

View File

@ -26,5 +26,11 @@ jobs:
- name: Install dependencies
run: flutter pub get
- name: Run tests
run: flutter test
- 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

View File

@ -26,5 +26,11 @@ jobs:
- name: Install dependencies
run: flutter pub get
- name: Run tests
run: flutter test
- 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

View File

@ -19,9 +19,10 @@ jobs:
- 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
# 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
# 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,6 +51,22 @@ jobs:
# 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 }}-
# 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-earned_time-${{ env.pythonLocation }}-${{
hashFiles('earned_time/.pre-commit-config.yaml') }}
restore-keys: mypy-earned_time-${{ env.pythonLocation }}-
- name: Run the hooks
run: >-
pre-commit run --config earned_time/.pre-commit-config.yaml

View File

@ -32,5 +32,5 @@ jobs:
# No display needed: earned_time is stdlib-only policy, imported
# headless by the root gaming daemon.
- name: Run tests
- name: Run tests with coverage
run: python -m pytest -v

34
.github/workflows/file-length.yml vendored Normal file
View File

@ -0,0 +1,34 @@
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

View File

@ -19,9 +19,10 @@ jobs:
- 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
# 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
# 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,6 +51,22 @@ jobs:
# 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 }}-
# 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-focus-project-${{ env.pythonLocation }}-${{
hashFiles('focus_project/.pre-commit-config.yaml') }}
restore-keys: mypy-focus-project-${{ env.pythonLocation }}-
- name: Run the hooks
run: >-
pre-commit run --config focus_project/.pre-commit-config.yaml

View File

@ -30,5 +30,5 @@ jobs:
- name: Install dependencies
run: pip install -r requirements.txt && pip install --no-deps -e .
- name: Run tests
- name: Run tests with coverage
run: python -m pytest -v

View File

@ -19,9 +19,10 @@ jobs:
- 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
# 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
# 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,6 +51,22 @@ 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

View File

@ -36,9 +36,9 @@ jobs:
run: pip install ../crdt-sync
- name: Install dependencies
run: pip install --no-deps ../kuhy_credit && pip install -r requirements.txt && pip install --no-deps -e .
run: 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
- name: Run tests with coverage
run: python -m pytest -v

View File

@ -18,9 +18,10 @@ jobs:
- 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
# 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
# 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
@ -48,6 +49,22 @@ jobs:
# 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 }}-
# 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 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-game-recording-${{ env.pythonLocation }}-${{
hashFiles('game_recording/.pre-commit-config.yaml') }}
restore-keys: mypy-game-recording-${{ env.pythonLocation }}-
- name: Run the hooks
run: >-
pre-commit run --config game_recording/.pre-commit-config.yaml

View File

@ -31,5 +31,5 @@ jobs:
- name: Install dependencies
run: pip install -r requirements.txt
- name: Run tests
run: python -m pytest -v
- name: Run tests with coverage
run: python -m pytest -v --cov=game_recording

View File

@ -18,9 +18,10 @@ jobs:
- 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
# 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
# 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
@ -49,6 +50,22 @@ 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

View File

@ -45,5 +45,5 @@ jobs:
- name: Install a virtual X display
run: sudo apt-get update && sudo apt-get install -y xvfb
- name: Run tests
- name: Run tests with coverage
run: xvfb-run -a -s "-screen 0 1600x1200x24" python -m pytest -v

View File

@ -26,5 +26,11 @@ jobs:
- name: Install dependencies
run: flutter pub get
- name: Run tests
run: flutter test
- 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

View File

@ -28,5 +28,11 @@ jobs:
sudo mv "Godot_v${GODOT_VERSION}-stable_linux.x86_64" /usr/local/bin/godot
rm godot.zip
- name: Install gdtoolkit (pinned)
run: pip install -r godot_dev_tools/requirements-dev.txt
- name: Lint (gdlint, gdformat)
run: godot_dev_tools/lint.sh
- name: GUT against the stub host (GUT is fetched at its pinned tag)
run: godot_dev_tools/test.sh

View File

@ -26,5 +26,11 @@ jobs:
- name: Install dependencies
run: flutter pub get
- name: Run tests
run: flutter test
- 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

View File

@ -19,9 +19,10 @@ jobs:
- 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
# 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
# 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,6 +51,22 @@ jobs:
# 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 }}-
# 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-holds-${{ env.pythonLocation }}-${{
hashFiles('holds/.pre-commit-config.yaml') }}
restore-keys: mypy-holds-${{ env.pythonLocation }}-
- name: Run the hooks
run: >-
pre-commit run --config holds/.pre-commit-config.yaml

View File

@ -30,5 +30,5 @@ jobs:
- name: Install dependencies
run: pip install -r requirements.txt && pip install --no-deps -e .
- name: Run tests
- name: Run tests with coverage
run: python -m pytest -v

View File

@ -26,7 +26,9 @@ jobs:
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
- name: Lint
run: ruff check . && ruff format --check .
- name: Tests, Tk E2E and the drift check, 100% branch coverage
run: xvfb-run -a -s "-screen 0 1600x1200x24" python -m pytest -q
web:
@ -43,8 +45,9 @@ jobs:
- uses: actions/setup-python@v5
with: { python-version: "3.15.2" }
- run: pnpm install --frozen-lockfile
- name: Unit tests
run: pnpm test
- run: pnpm lint
- name: Unit tests, 100% coverage
run: pnpm coverage
- name: E2E in headless Chrome (window.open stubbed)
working-directory: .
env: { CHROMIUM: google-chrome }
@ -64,12 +67,13 @@ jobs:
- uses: actions/setup-python@v5
with: { python-version: "3.15.2" }
- run: flutter pub get
- name: Widget tests
run: flutter test
- run: flutter analyze
- name: Widget tests, 100% line coverage
run: flutter test --coverage && ../../scripts/check_coverage.sh coverage/lcov.info 100
- 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)
(cd example && flutter pub get && flutter analyze && flutter build web --release)
pip install -r ../../flutter_web_drive/requirements.txt
python3 ../e2e/flutter_web_e2e.py
@ -86,6 +90,8 @@ jobs:
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: Lint (gdlint, gdformat)
run: pip install -r godot_dev_tools/requirements-dev.txt && kuhy_credit/godot/lint.sh
- name: GUT unit tests + demo E2E (GUT fetched at its pinned tag)
env: { KUHY_CREDIT_GODOT_TIMEOUT: "50" }
run: kuhy_credit/godot/test.sh

View File

@ -19,9 +19,10 @@ jobs:
- 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
# 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
# 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,6 +51,22 @@ jobs:
# 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 }}-
# 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-leetcode-coach-${{ env.pythonLocation }}-${{
hashFiles('leetcode_coach/.pre-commit-config.yaml') }}
restore-keys: mypy-leetcode-coach-${{ env.pythonLocation }}-
- name: Run the hooks
run: >-
pre-commit run --config leetcode_coach/.pre-commit-config.yaml

View File

@ -30,5 +30,5 @@ jobs:
- name: Install dependencies
run: pip install -r requirements.txt && pip install --no-deps -e .
- name: Run tests
- name: Run tests with coverage
run: python -m pytest -v

View File

@ -27,5 +27,5 @@ jobs:
- name: Install dependencies
run: pip install -r requirements.txt
- name: Run tests
run: python -m pytest -v
- name: Run tests with coverage
run: python -m pytest -v --cov=music_theory

View File

@ -19,9 +19,10 @@ jobs:
- 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
# 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
# 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,6 +51,22 @@ jobs:
# 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 }}-
# 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-omniroute_offload-${{ env.pythonLocation }}-${{
hashFiles('omniroute_offload/.pre-commit-config.yaml') }}
restore-keys: mypy-omniroute_offload-${{ env.pythonLocation }}-
- name: Run the hooks
run: >-
pre-commit run --config omniroute_offload/.pre-commit-config.yaml

View File

@ -26,5 +26,11 @@ jobs:
- name: Install dependencies
run: flutter pub get
- name: Run tests
run: flutter test
- 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

View File

@ -26,5 +26,11 @@ jobs:
- name: Install dependencies
run: flutter pub get
- name: Run tests
run: flutter test
- 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

View File

@ -27,37 +27,50 @@ jobs:
python-version: "3.x"
- name: Install test dependencies
run: python -m pip install --upgrade pytest pyyaml packaging
run: python -m pip install --upgrade pytest pytest-cov pyyaml packaging
- name: dep_freshness
- name: dep_freshness — 100% branch coverage on the gate itself
run: |
PYTHONPATH=. python -m pytest dep_freshness/tests -q
PYTHONPATH=. python -m pytest dep_freshness/tests -q \
--cov=dep_freshness --cov-branch \
--cov-report=term-missing \
--cov-fail-under=99
- name: md_naming
run: PYTHONPATH=. python -m pytest md_naming/tests -q
- name: file_length
# 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
run: |
PYTHONPATH=. python -m pytest file_length/tests -q
PYTHONPATH=. python -m pytest file_length/tests -q \
--cov=file_length --cov-branch \
--cov-report=term-missing \
--cov-fail-under=100
- name: repo_contract
- name: repo_contract — 100% branch coverage on the gate itself
run: |
PYTHONPATH=. python -m pytest repo_contract/tests -q
PYTHONPATH=. python -m pytest repo_contract/tests -q \
--cov=repo_contract --cov-branch \
--cov-report=term-missing \
--cov-fail-under=100
# 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
- name: agent_ready — 100% branch coverage on the checker
run: |
PYTHONPATH=. python -m pytest agent_ready/tests -q
PYTHONPATH=. python -m pytest agent_ready/tests -q \
--cov=agent_ready --cov-branch \
--cov-report=term-missing \
--cov-fail-under=100
- name: coverage_gaps
- name: coverage_gaps — 100% branch coverage on the lister
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
PYTHONPATH=. python -m pytest coverage_gaps/tests -q \
--cov=coverage_gaps --cov-branch \
--cov-report=term-missing \
--cov-fail-under=100
# 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

View File

@ -19,9 +19,10 @@ jobs:
- 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
# 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
# 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,6 +51,22 @@ jobs:
# 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 }}-
# 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-sickdays-${{ env.pythonLocation }}-${{
hashFiles('sickdays/.pre-commit-config.yaml') }}
restore-keys: mypy-sickdays-${{ env.pythonLocation }}-
- name: Run the hooks
run: >-
pre-commit run --config sickdays/.pre-commit-config.yaml

View File

@ -33,7 +33,7 @@ jobs:
# 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
run: pip install ../crdt-sync && pip install --no-deps ../freedays
- name: Install dependencies
run: pip install -r requirements.txt && pip install --no-deps -e .
@ -45,5 +45,5 @@ jobs:
- name: Install a virtual X display
run: sudo apt-get update && sudo apt-get install -y xvfb
- name: Run tests
- name: Run tests with coverage
run: xvfb-run -a -s "-screen 0 1600x1200x24" python -m pytest -v

View File

@ -19,9 +19,10 @@ jobs:
- 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
# 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
# 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,6 +51,22 @@ jobs:
# 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 }}-
# 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-sql-drills-${{ env.pythonLocation }}-${{
hashFiles('sql_drills/.pre-commit-config.yaml') }}
restore-keys: mypy-sql-drills-${{ env.pythonLocation }}-
- name: Run the hooks
run: >-
pre-commit run --config sql_drills/.pre-commit-config.yaml

View File

@ -30,5 +30,5 @@ jobs:
- name: Install dependencies
run: pip install -r requirements.txt && pip install --no-deps -e .
- name: Run tests
- name: Run tests with coverage
run: python -m pytest -v

View File

@ -26,5 +26,11 @@ jobs:
- name: Install dependencies
run: flutter pub get
- name: Run tests
run: flutter test
- 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

View File

@ -30,5 +30,8 @@ jobs:
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Fixture + factory tests
run: pnpm test
- name: Lint (the preset lints itself)
run: pnpm lint
- name: Fixture + factory tests with the 100% coverage gate
run: pnpm coverage

View File

@ -27,11 +27,22 @@ jobs:
with:
node-version: "26.13.1"
# The preset is a `link:../ts_config` dependency. pnpm links the
# directory but installs nothing inside it, and a flat config imports
# its plugins from the preset's own node_modules -- so without this
# step the lint dies on "Cannot find package '@eslint/js'".
- name: Install the shared lint preset's dependencies
run: pnpm install --frozen-lockfile
working-directory: ts_config
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Run tests
run: pnpm test
- name: Lint
run: pnpm lint
- name: Run tests with the 100% coverage gate
run: pnpm coverage
# The tag ships a prebuilt dist/ because Vite does not transpile
# dependencies. A committed dist/ that does not match src/ would ship

View File

@ -27,11 +27,22 @@ jobs:
with:
node-version: "26.13.1"
# The preset is a `link:../ts_config` dependency. pnpm links the
# directory but installs nothing inside it, and a flat config imports
# its plugins from the preset's own node_modules -- so without this
# step the lint dies on "Cannot find package '@eslint/js'".
- name: Install the shared lint preset's dependencies
run: pnpm install --frozen-lockfile
working-directory: ts_config
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Run tests
run: pnpm test
- name: Lint
run: pnpm lint
- name: Run tests with the 100% coverage gate
run: pnpm coverage
# 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
View File

@ -23,6 +23,3 @@ firebase-debug.log
firebase-debug.*.log
firestore-debug.log
database-debug.log
# Claude Code harness worktrees: never commit them as gitlinks.
.claude/worktrees/

View File

@ -1,12 +1,19 @@
# 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.
# 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.
#
# The subprojects (gatelock/, crdt-sync/, web_ui/, design_system/,
# 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/, ...).
# 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
# (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
@ -14,6 +21,12 @@
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
# 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

View File

@ -1,7 +1,7 @@
# 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,
repo_contract, coverage_gaps, 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,
@ -15,13 +15,9 @@ 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: `PYTHONPATH=. python -m pytest -q agent_ready/tests coverage_gaps/tests dep_freshness/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)
- lint: `ruff check agent_ready coverage_gaps flutter_web_drive repo_contract`
- coverage: `PYTHONPATH=. python -m pytest -q agent_ready/tests flutter_web_drive/tests repo_contract/tests unified-design-system/tests --cov=agent_ready --cov=flutter_web_drive --cov=repo_contract --cov=conformance --cov=conformance_diff --cov-branch --cov-report=xml --cov-fail-under=100`
- coverage-gaps: `coverage-gaps coverage.xml`
- 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`.

View File

@ -1,40 +0,0 @@
# 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.

View File

@ -176,12 +176,3 @@ 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).

View File

@ -5,7 +5,7 @@ description = "Shared app error and slow-wait ingest: RTDB and local spool repor
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",
"kuhy-credit @ git+https://github.com/kuhyx/utils@kuhy-credit-v0.3.1#subdirectory=kuhy_credit",
]
[project.optional-dependencies]
@ -173,6 +173,7 @@ omit = [
]
[tool.coverage.report]
fail_under = 100
show_missing = true
skip_covered = false
exclude_lines = [

View File

@ -26,7 +26,7 @@ test = [
requires-dist = [
{ name = "crdt-sync", git = "https://github.com/kuhyx/utils?subdirectory=crdt-sync&rev=crdt-sync-v0.11.1" },
{ name = "jsonschema", marker = "extra == 'test'", specifier = "==4.26.0" },
{ name = "kuhy-credit", git = "https://github.com/kuhyx/utils?subdirectory=kuhy_credit&rev=kuhy-credit-v0.3.2" },
{ name = "kuhy-credit", git = "https://github.com/kuhyx/utils?subdirectory=kuhy_credit&rev=kuhy-credit-v0.3.1" },
{ name = "pytest", marker = "extra == 'test'", specifier = "==9.2.0" },
{ name = "pytest-cov", marker = "extra == 'test'", specifier = "==7.1.0" },
]
@ -400,8 +400,8 @@ wheels = [
[[package]]
name = "kuhy-credit"
version = "0.3.2"
source = { git = "https://github.com/kuhyx/utils?subdirectory=kuhy_credit&rev=kuhy-credit-v0.3.2#adeb40f68e1d6c701da43e396fc46bffa3ef10c7" }
version = "0.3.1"
source = { git = "https://github.com/kuhyx/utils?subdirectory=kuhy_credit&rev=kuhy-credit-v0.3.1#2352c177232a4b4594573a3b1126697ef32851f7" }
[[package]]
name = "packaging"

View File

@ -31,6 +31,8 @@ repos:
- id: check-merge-conflict
- id: detect-private-key
- id: debug-statements
- id: name-tests-test
args: [--pytest-test-first]
- id: check-ast
- id: mixed-line-ending
args: [--fix=lf]
@ -38,6 +40,11 @@ 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
- id: subproject-scope
name: subproject scope regex still matches
entry: scripts/check_subproject_scope.sh crdt-sync
@ -60,16 +67,85 @@ repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.17.4
hooks:
- id: ruff
args: [--fix, --unsafe-fixes, --exit-non-zero-on-fix, --show-fixes]
types_or: [python, pyi]
- id: ruff-format
types_or: [python, pyi]
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v2.4.0
hooks:
- id: mypy
additional_dependencies:
- types-requests
args:
- --ignore-missing-imports
- --no-error-summary
- --disable-error-code=no-untyped-def
- --disable-error-code=no-untyped-call
- --disable-error-code=var-annotated
- --disable-error-code=no-any-unimported
- --disable-error-code=type-arg
- --disable-error-code=no-any-return
- --disable-error-code=misc
- --disable-error-code=unused-ignore
- --disable-error-code=unreachable
- --disable-error-code=assignment
- --disable-error-code=no-redef
- --disable-error-code=attr-defined
- --disable-error-code=arg-type
- --disable-error-code=union-attr
- --disable-error-code=call-overload
- --disable-error-code=return-value
- --disable-error-code=redundant-cast
- --disable-error-code=empty-body
- --disable-error-code=list-item
- repo: https://github.com/pylint-dev/pylint
rev: v4.1.4
hooks:
- id: pylint
args:
- --rcfile=crdt-sync/pyproject.toml
- --fail-under=10
# One process: with --jobs>1 pylint pickles its AST via dill, which
# dies on Python 3.15 (code objects lost co_lnotab), 2026-11-16.
- --jobs=1
additional_dependencies:
# Kept in step with pyproject.toml, so pylint resolves the e2e imports.
- argon2-cffi==25.1.0
- pynacl==1.6.2
- pytest
- requests
- repo: https://github.com/PyCQA/bandit
rev: 1.9.4
hooks:
- id: bandit
args:
- -c
- crdt-sync/pyproject.toml
- --severity-level=high
- --confidence-level=medium
- --skip=B113
additional_dependencies: ["bandit[toml]"]
exclude: ^(crdt-sync/crdt_sync/tests/|.*test.*\.py$)
- repo: local
hooks:
- id: pytest
name: pytest
- id: pytest-coverage
name: pytest with coverage enforcement
entry: scripts/run_subproject_tests.sh crdt-sync
language: script
types: [python]
pass_filenames: false
require_serial: true
stages: [pre-push]
- repo: https://github.com/codespell-project/codespell
rev: v2.3.0
hooks:
- id: codespell
args:
- --skip=*.json,*.lock,.git,__pycache__,.venv

View File

@ -171,6 +171,7 @@ omit = [
]
[tool.coverage.report]
fail_under = 100
show_missing = true
skip_covered = false
exclude_lines = [

View File

@ -173,16 +173,6 @@ the core stays web-safe. Querying is deliberately **not** in the library — a
The Python side mirrors the on-disk format via `crdt_sync.dump_log`/`read_log`
(load/save only; no reactive stream — that's a Dart/Flutter convenience).
## Offline-first contract
Apps on this library are offline-first: write user data to `LogStore` first
and show it at once, never block the UI on the network. Run `syncLog` ticks
in the background and treat a `RemoteSyncError` as "try later", never as a
lost write. After every tick, `replaceAll` the merged result so pulled peer
data is cached locally and stays readable offline. Load the store before
`openSync` (crdt_sync_flutter): it may return null or hit the network, and
never gates local data. `test/offline_first_test.dart` checks this contract.
## Development
```bash

View File

@ -1,5 +1,4 @@
import 'dart:io';
import 'dart:math';
import 'store.dart';
@ -8,12 +7,10 @@ import 'store.dart';
/// Writes atomically -- to a per-process temp file, then `rename`d over the
/// real path -- so a concurrent reader (e.g. a background sync isolate writing
/// while the foreground app also writes) never observes a half-written file.
/// The pid plus a random per-instance token in the temp name keep two
/// writers from colliding: two processes, and two instances in one process
/// (a Flutter app's UI engine and a headless engine share a pid -- wake_alarm
/// lost a publish to exactly that, 2026-11-22). Within one instance, writes
/// are serialized in issue order (last issued wins), so overlapping calls
/// (e.g. per-keystroke saves) never share the temp file mid-flight. This generalizes diet_guard's hand-rolled `LogStorageService`
/// The pid in the temp name keeps two processes from colliding; within one
/// instance, writes are serialized in issue order (last issued wins), so
/// overlapping calls (e.g. per-keystroke saves) never share the temp file
/// mid-flight. This generalizes diet_guard's hand-rolled `LogStorageService`
/// write scheme.
///
/// Lives behind the `package:crdt_sync/crdt_sync_io.dart` entrypoint, not the
@ -22,14 +19,10 @@ import 'store.dart';
class FileLogPersistence implements LogPersistence {
/// Persists to [file]. The app chooses the path (e.g. via `path_provider`);
/// the library takes no dependency on where app documents live.
FileLogPersistence(this._file)
: _token = Random.secure().nextInt(1 << 32).toRadixString(36);
FileLogPersistence(this._file);
final File _file;
/// Tells this instance's temp file apart from another's in this process.
final String _token;
/// Completes when the most recently issued write has settled. Never
/// rejects, so one failed write cannot block the ones queued after it.
Future<void> _tail = Future<void>.value();
@ -54,7 +47,7 @@ class FileLogPersistence implements LogPersistence {
Future<void> _writeNow(String text) async {
await _file.parent.create(recursive: true);
final tmp = File('${_file.path}.$pid.$_token.tmp');
final tmp = File('${_file.path}.$pid.tmp');
await tmp.writeAsString(text);
await tmp.rename(_file.path);
}

View File

@ -2,7 +2,7 @@ name: crdt_sync
description: >-
Shared CRDT merge scheme + GitHub-Contents-API sync transport for
cross-device apps. Pure Dart, no Flutter dependency.
version: 0.14.2
version: 0.14.1
publish_to: 'none'
environment:

View File

@ -149,30 +149,6 @@ void main() {
},
);
test(
'two instances on one file in one process never share a temp file',
() async {
// Regression (wake_alarm, 2026-11-22): a Flutter app's UI engine and
// a headless engine each hold a FileLogPersistence for the same log
// in one process, so one pid. Both wrote `<file>.<pid>.tmp`; the
// first rename moved it away and the other publish died with
// PathNotFoundException.
final file = File('${dir.path}/log.json');
final a = FileLogPersistence(file);
final b = FileLogPersistence(file);
await Future.wait([
for (var i = 0; i < 25; i++) ...[
a.write('{"a":$i}'),
b.write('{"b":$i}'),
],
]);
expect(await a.read(), anyOf('{"a":24}', '{"b":24}'));
expect(dir.listSync().map((e) => e.uri.pathSegments.last), [
'log.json',
]);
},
);
test(
'a failed write rejects its caller but does not block later writes',
() async {

View File

@ -1,199 +0,0 @@
// Offline-first contract: writes are stored locally first and readable at
// once; an unreachable remote makes syncLog throw without losing the write;
// pulled peer data is cached locally for offline reads.
import 'dart:convert';
import 'package:crdt_sync/crdt_sync.dart';
import 'package:test/test.dart';
class _MemPersistence implements LogPersistence {
String? text;
@override
Future<String?> read() async => text;
@override
Future<void> write(String t) async => text = t;
}
/// A remote that is unreachable: every call throws RemoteSyncError.
class _OfflineRemote implements RemoteStore {
@override
Future<List<String>> listDirectory(String path) async =>
throw RemoteSyncError('offline');
@override
Future<String?> getFileText(String path) async =>
throw RemoteSyncError('offline');
@override
Future<void> putFileText(
String path,
String text, {
required String message,
}) async => throw RemoteSyncError('offline');
@override
Future<void> deleteFile(String path, {String? message}) async =>
throw RemoteSyncError('offline');
@override
Future<bool> canAccessRemote() async => throw RemoteSyncError('offline');
@override
void close() {}
}
/// An in-memory reachable remote: a `Map<String, String>` of files;
/// listDirectory returns the distinct next path segment of every key under
/// [pathPrefix].
class _MemRemote implements RemoteStore {
final Map<String, String> files = {};
@override
Future<List<String>> listDirectory(String path) async {
final prefix = '$path/';
return files.keys
.where((key) => key.startsWith(prefix))
.map((key) => key.substring(prefix.length).split('/').first)
.toSet()
.toList();
}
@override
Future<String?> getFileText(String path) async => files[path];
@override
Future<void> putFileText(
String path,
String text, {
required String message,
}) async => files[path] = text;
@override
Future<void> deleteFile(String path, {String? message}) async {
files.remove(path);
}
@override
Future<bool> canAccessRemote() async => true;
@override
void close() {}
}
String _encode(Log log) =>
jsonEncode(log.map((id, r) => MapEntry(id, r.toJson())));
Log _decode(String text) => (jsonDecode(text) as Map<String, dynamic>).map(
(id, d) => MapEntry(id, Record.fromJson(d as Map<String, dynamic>)),
);
void main() {
group('offline-first contract', () {
test(
'a write is readable at once and survives a restart with no network',
() async {
final persistence = _MemPersistence();
final store = LogStore(persistence: persistence, nodeId: 'phone');
await store.load();
await store.upsert(
Record(id: 'a', fields: {'title': ('milk', store.nextHlc())}),
);
// Readable at once, no remote involved; a fresh store on the same
// persistence sees it after load.
expect(store.get('a'), isNotNull);
final restarted = LogStore(persistence: persistence, nodeId: 'phone');
await restarted.load();
expect(restarted.get('a'), isNotNull);
},
);
test('a failed tick leaves the local log intact', () async {
final persistence = _MemPersistence();
final store = LogStore(persistence: persistence, nodeId: 'phone');
await store.load();
await store.upsert(
Record(id: 'a', fields: {'title': ('milk', store.nextHlc())}),
);
await expectLater(
syncLog(
client: _OfflineRemote(),
deviceId: 'phone',
pathPrefix: 'app-sync/devices',
localLog: store.snapshot(),
encode: _encode,
decode: _decode,
),
throwsA(isA<RemoteSyncError>()),
);
expect(store.get('a'), isNotNull);
expect(persistence.text, contains('"a"'));
});
test('the offline write is pushed once the remote is back', () async {
final persistence = _MemPersistence();
final store = LogStore(persistence: persistence, nodeId: 'phone');
await store.load();
await store.upsert(
Record(id: 'a', fields: {'title': ('milk', store.nextHlc())}),
);
// Offline tick fails; once the remote is back it pushes the write.
await expectLater(
syncLog(
client: _OfflineRemote(),
deviceId: 'phone',
pathPrefix: 'app-sync/devices',
localLog: store.snapshot(),
encode: _encode,
decode: _decode,
),
throwsA(isA<RemoteSyncError>()),
);
final remote = _MemRemote();
await syncLog(
client: remote,
deviceId: 'phone',
pathPrefix: 'app-sync/devices',
localLog: store.snapshot(),
encode: _encode,
decode: _decode,
);
final pushed = remote.files['app-sync/devices/phone/log.json'];
expect(pushed, isNotNull);
expect(_decode(pushed!).containsKey('a'), isTrue);
});
test('pulled records are stored locally, readable offline', () async {
final persistence = _MemPersistence();
final store = LogStore(persistence: persistence, nodeId: 'phone');
await store.load();
final peerStore = LogStore(persistence: _MemPersistence(), nodeId: 'pc');
await peerStore.load();
await peerStore.upsert(
Record(id: 'b', fields: {'title': ('bread', peerStore.nextHlc())}),
);
final remote = _MemRemote()
..files['app-sync/devices/pc/log.json'] = _encode(peerStore.snapshot());
final merged = await syncLog(
client: remote,
deviceId: 'phone',
pathPrefix: 'app-sync/devices',
localLog: store.snapshot(),
encode: _encode,
decode: _decode,
);
await store.replaceAll(merged);
final restarted = LogStore(persistence: persistence, nodeId: 'phone');
await restarted.load();
expect(restarted.get('b'), isNotNull);
});
});
}

View File

@ -61,11 +61,11 @@ packages:
dependency: "direct main"
description:
path: crdt_sync_dart
ref: "crdt_sync_dart-v0.14.2"
resolved-ref: "171a7f8ae34cec78df17a680e42878ca0b97c137"
ref: "crdt_sync_dart-v0.14.1"
resolved-ref: edd0f7a7882cb1d3904932ba94faa282d08165df
url: "https://github.com/kuhyx/utils"
source: git
version: "0.14.2"
version: "0.14.1"
crypto:
dependency: "direct main"
description:

View File

@ -4,7 +4,7 @@ description: >-
persisted per-install device id, and a one-call bootstrap. Removes the
~150 lines of firebase_backend.dart every consuming app was copying.
publish_to: 'none'
version: 0.9.2
version: 0.9.1
environment:
sdk: ^3.12.2
@ -13,7 +13,7 @@ dependencies:
crdt_sync:
git:
url: https://github.com/kuhyx/utils
ref: crdt_sync_dart-v0.14.2
ref: crdt_sync_dart-v0.14.1
path: crdt_sync_dart
crypto: 3.0.8
flutter:

View File

@ -27,6 +27,11 @@ 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
- id: subproject-scope
name: subproject scope regex still matches
entry: scripts/check_subproject_scope.sh data_transfer_flutter
@ -45,9 +50,16 @@ repos:
entry: bash -c 'cd data_transfer_flutter && dart format --set-exit-if-changed lib test'
language: system
pass_filenames: false
- id: flutter-test
name: flutter test
entry: bash -c 'cd data_transfer_flutter && flutter test'
- id: flutter-analyze
name: flutter analyze
entry: bash -c 'cd data_transfer_flutter && flutter analyze'
language: system
pass_filenames: false
- id: flutter-test-coverage
name: flutter test --coverage with 100% line-coverage gate
entry: >-
bash -c 'cd data_transfer_flutter && flutter test --coverage &&
scripts/check_coverage.sh coverage/lcov.info 100'
language: system
pass_filenames: false
require_serial: true

View File

@ -23,10 +23,6 @@ MAVEN: Final = "maven"
# wait for, so the only reading of "current" it admits is "at HEAD".
GITCOMMIT: Final = "gitcommit"
TOOLCHAIN: Final = "toolchain"
# One package out of an Arch-style repo db (`<repo>.db`), pinned by a small
# `key=value` lock file. Versions are `epoch:pkgver-pkgrel` and compare with
# pacman's vercmp, never PEP 440 (see registries/pacman_repo.py).
PACMAN_REPO: Final = "pacman-repo"
# The constraint a workflow parser writes for a version MATRIX. Standing
# decision (kuhy, 2026-08-28): one toolchain version per repo, always newest,
# so a matrix is a finding to delete rather than a range to satisfy.
@ -42,7 +38,6 @@ ECOSYSTEMS: Final = (
MAVEN,
GITCOMMIT,
TOOLCHAIN,
PACMAN_REPO,
)
# --- Registry endpoints -----------------------------------------------------
@ -139,12 +134,6 @@ MANIFEST_GLOBS: Final = (
"gradle-wrapper.properties",
)
REQUIREMENTS_PATTERN: Final = r"^requirements.*\.txt$"
# A pacman-repo lock has no fixed filename (`proton-native.lock` is one), so
# it is recognised by content instead of a glob: a `*.lock` file whose first
# few KB hold a `repo=` line ending in `.db`. The read is bounded because
# `--all` sniffs every Cargo.lock and pubspec.lock too.
PACMAN_LOCK_SUFFIX: Final = ".lock"
PACMAN_LOCK_SNIFF_BYTES: Final = 4096
# `.utils` is where every CI workflow checks the shared gate out, INSIDE the
# repo being checked. Without it `--all` walks utils' own manifests and fails

View File

@ -19,7 +19,6 @@ from dep_freshness.parsers import (
golang,
gradle,
javascript,
pacman_lock,
pubspec,
python,
rust,
@ -47,7 +46,6 @@ def is_manifest(path: Path) -> bool:
or bool(_REQUIREMENTS.match(path.name))
or workflow.is_workflow(path)
or gradle.is_catalog(path)
or pacman_lock.is_lock(path)
)
@ -62,8 +60,6 @@ def parse_manifest(path: Path) -> list[Dep]:
return workflow.parse(path)
if gradle.is_catalog(path):
return gradle.parse_catalog(path)
if pacman_lock.is_lock(path):
return pacman_lock.parse(path)
return []

View File

@ -15,10 +15,9 @@ purpose:
from __future__ import annotations
from dep_freshness._tables import GITCOMMIT, MATRIX, PACMAN_REPO, TOOLCHAIN
from dep_freshness._tables import GITCOMMIT, MATRIX, TOOLCHAIN
from dep_freshness.constraints import lower_bound, satisfies
from dep_freshness.models import Dep, Finding, Severity
from dep_freshness.registries.pacman_repo import vercmp
from dep_freshness.resolve import Answer
from dep_freshness.versions import behind, google_api_key
@ -47,29 +46,6 @@ def _commit(dep: Dep, heads: str) -> Finding | None:
)
def _pacman(dep: Dep, answer: str) -> Finding | None:
"""A repo db lists ONE version per package; any other pin is undownloadable.
`answer` is `"<version> <sha256>"`. Compared with pacman's vercmp, so an
epoch outranks a bigger pkgver. The checksum goes into the detail so the
bump is a paste, and a right version with a wrong checksum is caught.
"""
version, _, sha = answer.partition(" ")
fix = f"version={version}" + (f" sha256={sha}" if sha else "")
if not dep.pinned:
return Finding(dep, Severity.UNPINNED, version, detail=f"pin {fix}")
if vercmp(dep.pinned, version) != 0:
return Finding(dep, Severity.STALE, version, detail=f"the repo serves {fix}")
if sha and dep.locked and dep.locked != sha.lower():
return Finding(
dep,
Severity.LOCK_MISMATCH,
version,
detail=f"lock sha256 {dep.locked} != the repo's {sha}",
)
return None
def _generation(dep: Dep, pin, latest: str) -> Finding | None:
"""A Google API client is judged inside its own generation only."""
gen, rank = pin
@ -154,8 +130,6 @@ def judge(dep: Dep, answer: Answer) -> Finding | None:
return _toolchain(dep, latest)
if dep.ecosystem == GITCOMMIT:
return _commit(dep, latest)
if dep.ecosystem == PACMAN_REPO:
return _pacman(dep, latest)
pin = google_api_key(dep.pinned or "")
if pin is not None:
return _generation(dep, pin, latest)

View File

@ -1,81 +0,0 @@
"""A pacman-repo lock -> one package pinned out of an Arch-style repo db.
The format is one `key=value` per line, `#` comments allowed:
name=proton-cachyos-native
repo=https://mirror.cachyos.org/repo/x86_64/cachyos/cachyos.db
version=1:11.0.20261015-1
sha256=<hex>
There is no fixed filename, so `is_lock` recognises one by content: a
`*.lock` file whose first few KB hold a `repo=` line ending in `.db`. That
keeps Cargo.lock, pubspec.lock and friends out without a name list, and lets
pre-commit pass the file by name. `version` is kept verbatim: the epoch makes
it unreadable to `exact_pin`, and the judge compares it with pacman's vercmp.
`sha256` rides in `Dep.locked`, the field for "what the lock resolved to".
"""
from __future__ import annotations
import re
from pathlib import Path
from dep_freshness._tables import (
PACMAN_LOCK_SNIFF_BYTES,
PACMAN_LOCK_SUFFIX,
PACMAN_REPO,
)
from dep_freshness.models import Dep
from dep_freshness.registries.pacman_repo import qualified_name
_REPO_DB = re.compile(r"^\s*repo\s*=\s*\S+\.db\s*$", re.MULTILINE)
def is_lock(path: Path) -> bool:
"""True for a `*.lock` whose head names a repo `.db`."""
if not path.name.endswith(PACMAN_LOCK_SUFFIX):
return False
try:
with path.open("rb") as handle:
head = handle.read(PACMAN_LOCK_SNIFF_BYTES)
except OSError:
return False
return bool(_REPO_DB.search(head.decode("utf-8", errors="replace")))
def _fields(text: str) -> dict[str, tuple[str, int]]:
"""`key -> (value, 1-based line)`; the first occurrence of a key wins."""
fields: dict[str, tuple[str, int]] = {}
for number, line in enumerate(text.splitlines(), start=1):
stripped = line.strip()
if not stripped or stripped.startswith("#") or "=" not in stripped:
continue
key, _, value = stripped.partition("=")
fields.setdefault(key.strip(), (value.strip(), number))
return fields
def parse(path: Path) -> list[Dep]:
if not is_lock(path):
return []
try:
fields = _fields(path.read_text(encoding="utf-8", errors="replace"))
except OSError:
return []
name, name_line = fields.get("name", ("", 0))
repo, _ = fields.get("repo", ("", 0))
if not name or not repo:
return []
version, version_line = fields.get("version", ("", 0))
sha, _ = fields.get("sha256", ("", 0))
return [
Dep(
ecosystem=PACMAN_REPO,
name=qualified_name(repo, name),
constraint=version,
path=path,
line=version_line or name_line,
pinned=version or None,
locked=sha.lower() or None,
)
]

View File

@ -112,20 +112,6 @@ def get_text(url: str, accept: str | None = None) -> str | None:
Same contract as `get_json`; Maven metadata is XML, not JSON.
"""
body = get_bytes(url, accept)
if body is None:
return None
try:
return body.decode("utf-8")
except UnicodeDecodeError as exc:
raise Offline(f"{url}: {exc}") from exc
def get_bytes(url: str, accept: str | None = None) -> bytes | None:
"""Fetch a raw body, or raise `Offline` / return None on 404.
Same contract as `get_json`; a pacman repo `.db` is a compressed tar.
"""
if not host_reachable(url):
raise Offline(url)
headers = {"User-Agent": USER_AGENT}
@ -139,7 +125,7 @@ def get_bytes(url: str, accept: str | None = None) -> bytes | None:
attempt += 1
try:
with urlopen(request, timeout=HTTP_TIMEOUT * attempt) as response:
return response.read()
return response.read().decode("utf-8")
except HTTPError as exc:
if exc.code == 404:
return None

View File

@ -1,179 +0,0 @@
"""Arch-style package repos: the one version a repo `.db` lists for a package.
A repo db (`cachyos.db`, `extra.db`) is a tar, gzip- or zstd-compressed, with
one `<name>-<version>/desc` entry per package. The desc file holds `%NAME%`,
`%VERSION%` and `%SHA256SUM%` blocks. A repo keeps exactly ONE version of each
package, so "newest stable" is simply whatever the db lists.
The repo URL travels inside the dep name as `<repo-url>#<package>`, because
the resolver and the cache only ever see the name (the gittag lesson). Arch
package names cannot contain `#`, so `rpartition` splits it unambiguously.
That string is also the cache key and the allowlist label.
The answer is `"<version> <sha256>"`, space-joined like gitcommit's heads:
the judge needs the version to compare and the checksum to check the lock's.
Versions compare with pacman's `vercmp` (a port of libalpm's version.c),
never PEP 440: `1:11.0.20261015-1` is not a version `packaging` can read.
"""
from __future__ import annotations
import io
import tarfile
from dep_freshness.registries.http import Offline, get_bytes
try: # stdlib since Python 3.14; tarfile's "r:*" reads zstd through it
import compression.zstd # noqa: F401
_HAS_ZSTD = True
except ImportError: # pragma: no cover - this machine runs 3.15
_HAS_ZSTD = False
_ZSTD_MAGIC = b"\x28\xb5\x2f\xfd"
_SEPARATOR = "#"
def qualified_name(repo: str, package: str) -> str:
"""The dep name for `package` out of the db at `repo`."""
return f"{repo.strip()}{_SEPARATOR}{package.strip()}"
def split_name(name: str) -> tuple[str, str]:
"""`(repo_url, package)` back out of a `qualified_name`."""
repo, _, package = name.rpartition(_SEPARATOR)
return repo, package
def _fields(desc: str) -> dict[str, str]:
"""`{"NAME": ..., "VERSION": ...}`: the first line under each `%KEY%`."""
fields: dict[str, str] = {}
lines = desc.splitlines()
for number, line in enumerate(lines[:-1]):
if len(line) > 2 and line.startswith("%") and line.endswith("%"):
fields.setdefault(line.strip("%"), lines[number + 1].strip())
return fields
def _open(url: str, body: bytes) -> tarfile.TarFile:
if body.startswith(_ZSTD_MAGIC) and not _HAS_ZSTD:
# `Offline`, not a bare error: `Resolver.latest` catches only that, so
# anything else would crash the gate instead of reporting UNKNOWN
# (exit 3 under --strict) with this message in the degraded banner.
raise Offline(
f"{url} is zstd-compressed; reading it needs Python 3.14+ "
"(compression.zstd)"
)
try:
return tarfile.open(fileobj=io.BytesIO(body), mode="r:*")
except tarfile.TarError as exc:
# A captive portal's HTML is a broken network, not an answer.
raise Offline(f"{url}: not a repo db ({exc})") from exc
def latest(name: str) -> str | None:
"""`"<version> <sha256>"` the repo lists for the package, or None.
Matched on `%NAME%`, not the directory name: `foo-` also prefixes
`foo-git-1.0-1/`. The tar is untrusted, so it is read, never extracted.
"""
repo, package = split_name(name)
body = get_bytes(repo)
if body is None:
return None
with _open(repo, body) as tar:
for member in tar:
if not (
member.isfile()
and member.name.startswith(f"{package}-")
and member.name.endswith("/desc")
):
continue
handle = tar.extractfile(member)
if handle is None:
continue
fields = _fields(handle.read().decode("utf-8", errors="replace"))
if fields.get("NAME") == package and fields.get("VERSION"):
sha = fields.get("SHA256SUM", "")
return f"{fields['VERSION']} {sha}".strip()
return None
# --- vercmp -----------------------------------------------------------------
def _alnum(char: str) -> bool:
return char.isascii() and char.isalnum()
def _rpmvercmp(a: str, b: str) -> int:
"""libalpm's `rpmvercmp`: segment-wise compare of one EVR component."""
if a == b:
return 0
i = j = 0
while i < len(a) and j < len(b):
sep_a, sep_b = i, j
while i < len(a) and not _alnum(a[i]):
i += 1
while j < len(b) and not _alnum(b[j]):
j += 1
if i >= len(a) or j >= len(b):
break
# A longer separator run sorts higher (`1.0..1` > `1.0.1`).
if i - sep_a != j - sep_b:
return -1 if i - sep_a < j - sep_b else 1
start_a, start_b = i, j
numeric = a[i].isdigit()
same_kind = str.isdigit if numeric else (lambda c: c.isascii() and c.isalpha())
while i < len(a) and same_kind(a[i]):
i += 1
while j < len(b) and same_kind(b[j]):
j += 1
seg_a, seg_b = a[start_a:i], b[start_b:j]
if not seg_b:
# Different segment kinds: a number beats letters.
return 1 if numeric else -1
if numeric:
seg_a, seg_b = seg_a.lstrip("0"), seg_b.lstrip("0")
if len(seg_a) != len(seg_b):
return 1 if len(seg_a) > len(seg_b) else -1
if seg_a != seg_b:
return 1 if seg_a > seg_b else -1
if i >= len(a) and j >= len(b):
return 0
# One side has more left: `1.0.a` > `1.0`, but `1.0a` < `1.0`.
if (i >= len(a) and not b[j].isalpha()) or (i < len(a) and a[i].isalpha()):
return -1
return 1
def _evr(text: str) -> tuple[str, str, str | None]:
"""`(epoch, pkgver, pkgrel)`; epoch defaults to "0", pkgrel may be None."""
digits = 0
while digits < len(text) and text[digits].isdigit():
digits += 1
if digits < len(text) and text[digits] == ":":
epoch, rest = text[:digits] or "0", text[digits + 1 :]
else:
epoch, rest = "0", text
version, dash, release = rest.rpartition("-")
if not dash:
return epoch, rest, None
return epoch, version, release
def vercmp(left: str, right: str) -> int:
"""-1, 0 or 1, exactly as pacman's `vercmp left right` prints.
A missing pkgrel on either side compares equal on pkgrel, so `1.0`
matches `1.0-7`.
"""
if left == right:
return 0
epoch_l, ver_l, rel_l = _evr(left)
epoch_r, ver_r, rel_r = _evr(right)
result = _rpmvercmp(epoch_l, epoch_r) or _rpmvercmp(ver_l, ver_r)
if result == 0 and rel_l is not None and rel_r is not None:
result = _rpmvercmp(rel_l, rel_r)
return result

View File

@ -18,7 +18,6 @@ from dep_freshness._tables import (
MAVEN,
MAX_WORKERS,
NPM,
PACMAN_REPO,
PUB,
PYPI,
TOOLCHAIN,
@ -32,7 +31,6 @@ from dep_freshness.registries import (
gomod,
maven,
npmjs,
pacman_repo,
pub,
pypi,
)
@ -48,7 +46,6 @@ _LOOKUP = {
GITTAG: gittag.latest,
MAVEN: maven.latest,
GITCOMMIT: gitcommit.latest,
PACMAN_REPO: pacman_repo.latest,
}

View File

@ -9,7 +9,6 @@ a reason no commit can fix, which is why that combination is an error.
from __future__ import annotations
from datetime import date, timedelta
from pathlib import Path
import pytest
@ -124,9 +123,7 @@ def test_a_transitive_entry_may_not_carry_an_expiry(tmp_path):
load(tmp_path)
@pytest.mark.parametrize(
"field", ["ecosystem", "package", "pinned", "reason", "blocked_by"]
)
@pytest.mark.parametrize("field", ["ecosystem", "package", "pinned", "reason", "blocked_by"])
def test_every_required_field_is_required(tmp_path, field):
# Blank the value rather than deleting the line: dropping `ecosystem:`
# would also drop the `-` that makes the entry a list item, and the test
@ -142,10 +139,7 @@ def test_every_required_field_is_required(tmp_path, field):
def test_a_malformed_transitive_blocker_is_an_error(tmp_path):
_allowlist(
tmp_path,
TRANSITIVE.replace(
"transitive:firebase_core@4.2.0", "transitive:firebase_core"
),
tmp_path, TRANSITIVE.replace("transitive:firebase_core@4.2.0", "transitive:firebase_core")
)
with pytest.raises(AllowlistError, match="transitive:<package>@<version>"):
load(tmp_path)
@ -155,8 +149,7 @@ def test_a_bad_expiry_format_is_an_error(tmp_path):
_allowlist(
tmp_path,
_discretionary(30).replace(
(date.today() + __import__("datetime").timedelta(days=30)).isoformat(),
"next tuesday",
(date.today() + __import__("datetime").timedelta(days=30)).isoformat(), "next tuesday"
),
)
with pytest.raises(AllowlistError, match="YYYY-MM-DD"):
@ -191,9 +184,7 @@ def test_the_shared_allowlist_is_inherited(tmp_path, no_shared_allowlist):
"""A fleet-wide blocker must not have to be copied into forty repos."""
no_shared_allowlist.write_text(TRANSITIVE, encoding="utf-8")
entries = load(tmp_path)
assert [(e.ecosystem, e.package) for e in entries] == [
("pub", "plugin_platform_interface")
]
assert [(e.ecosystem, e.package) for e in entries] == [("pub", "plugin_platform_interface")]
def test_a_repo_entry_overrides_the_shared_one(tmp_path, no_shared_allowlist):
@ -210,15 +201,10 @@ def test_a_repo_entry_overrides_the_shared_one(tmp_path, no_shared_allowlist):
assert entries[0].reason == "this repo has its own reason"
def test_shared_and_repo_entries_for_different_packages_both_apply(
tmp_path, no_shared_allowlist
):
def test_shared_and_repo_entries_for_different_packages_both_apply(tmp_path, no_shared_allowlist):
no_shared_allowlist.write_text(TRANSITIVE, encoding="utf-8")
_allowlist(tmp_path, _discretionary(30))
assert {e.package for e in load(tmp_path)} == {
"plugin_platform_interface",
"abandoned",
}
assert {e.package for e in load(tmp_path)} == {"plugin_platform_interface", "abandoned"}
def test_a_malformed_shared_allowlist_is_an_error(tmp_path, no_shared_allowlist):
@ -231,9 +217,5 @@ def test_the_shared_path_defaults_to_the_gate_repo(monkeypatch):
from dep_freshness.allowlist import shared_path
monkeypatch.delenv("DEP_FRESHNESS_SHARED_ALLOWLIST", raising=False)
import dep_freshness
# The gate repo is whatever checkout holds the package (~/src/utils, a
# worktree, a snapshot), so compare paths, not the folder's name.
assert shared_path().name == NAME
assert shared_path().parent == Path(dep_freshness.__file__).resolve().parent.parent
assert shared_path().parent.name == "utils"

View File

@ -1,135 +0,0 @@
"""A pacman-repo lock: parsed, discovered, and judged end to end.
The consumer is steam-game-installer's `steam_installer/data/proton-native.lock`,
which pins one package out of the CachyOS repo. Pre-commit hands the gate the
file by name, so `is_manifest` must accept it on content, not on a glob.
"""
from __future__ import annotations
import json
import pytest
from dep_freshness import check, discover
from dep_freshness.models import Severity
from dep_freshness.parsers import pacman_lock
from dep_freshness.registries import pacman_repo
from dep_freshness.tests.conftest import write
from dep_freshness.tests.test_pacman_repo import SHA, build_db
REPO = "https://mirror.cachyos.org/repo/x86_64/cachyos/cachyos.db"
LOCK = f"""\
# pacman-repo lock: newest stable package from an Arch-style repo db
name=proton-cachyos-native
repo={REPO}
version=1:11.0.20261015-1
sha256={SHA}
"""
LOCK_PATH = "steam_installer/data/proton-native.lock"
def test_the_lock_parses_to_one_pinned_dep(repo):
path = write(repo, LOCK_PATH, LOCK)
[dep] = pacman_lock.parse(path)
assert dep.ecosystem == "pacman-repo"
assert pacman_repo.split_name(dep.name) == (REPO, "proton-cachyos-native")
assert dep.pinned == "1:11.0.20261015-1"
assert dep.locked == SHA
assert dep.line == 4 # the version= line is what a bump edits
@pytest.mark.parametrize(
("name", "body"),
[
("Cargo.lock", '[[package]]\nname = "serde"\nversion = "1.0.0"\n'),
("other.lock", "name=x\nrepo=https://example.org/not-a-db.json\n"),
("proton-native.txt", LOCK),
],
)
def test_other_files_are_not_pacman_locks(repo, name, body):
path = write(repo, name, body)
assert not discover.is_manifest(path)
assert discover.parse_manifest(path) == []
def test_the_lock_is_discovered_by_content(repo):
path = write(repo, LOCK_PATH, LOCK)
assert discover.is_manifest(path)
assert path in discover.find_manifests(repo)
def test_a_lock_without_a_version_is_unpinned(repo):
path = write(repo, "x.lock", LOCK.replace("version=1:11.0.20261015-1\n", ""))
[dep] = pacman_lock.parse(path)
assert dep.pinned is None
@pytest.fixture
def gate(repo, monkeypatch):
"""Run the CLI on the lock, with the repo db answering `served`."""
def invoke(lock_body, served, *flags):
name, version, sha = served
body = build_db({name: version}, sha=sha)
monkeypatch.setattr(pacman_repo, "get_bytes", lambda _url: body)
path = write(repo, LOCK_PATH, lock_body)
monkeypatch.chdir(repo)
return check.main([*flags, str(path)])
return invoke
CURRENT = ("proton-cachyos-native", "1:11.0.20261015-1", SHA)
def test_a_current_lock_passes(gate):
assert gate(LOCK, CURRENT, "--strict") == 0
def test_a_lock_behind_the_repo_fails(gate, capsys):
old = LOCK.replace("1:11.0.20261015-1", "1:10.0.20250101-1")
assert gate(old, CURRENT) == 1
out = capsys.readouterr()
text = out.out + out.err
assert "proton-cachyos-native" in text
assert "1:11.0.20261015-1" in text
assert SHA in text # the bump is copy-pasteable
def test_an_epoch_beats_a_bigger_pkgver(gate):
# PEP 440 would read `11.0` > `1:2.0` (or nothing at all); pacman says the
# epoch wins, so a lock on 11.0 is behind a repo on 1:2.0.
old = LOCK.replace("1:11.0.20261015-1", "11.0-1")
assert gate(old, ("proton-cachyos-native", "1:2.0-1", SHA)) == 1
def test_a_right_version_with_a_wrong_sha_is_a_mismatch(gate, capsys):
assert gate(LOCK, (*CURRENT[:2], "cd" * 32), "--json") == 1
payload = json.loads(capsys.readouterr().out)
assert Severity.LOCK_MISMATCH.value in json.dumps(payload)
def test_a_package_the_repo_dropped_is_undeterminable(gate):
assert gate(LOCK, ("something-else", "1.0-1", SHA), "--strict") == 3
def test_offline_with_a_cold_cache_is_undeterminable(repo, monkeypatch):
from dep_freshness.registries import http
http.force_offline(True)
path = write(repo, LOCK_PATH, LOCK)
monkeypatch.chdir(repo)
assert check.main(["--strict", str(path)]) == 3
assert check.main([str(path)]) == 0 # pre-commit degrades, never corners
def test_zstd_on_an_old_python_is_undeterminable_not_a_crash(
repo, monkeypatch, capsys
):
body = build_db({"proton-cachyos-native": "1:11.0.20261015-1"}, "zst")
monkeypatch.setattr(pacman_repo, "get_bytes", lambda _url: body)
monkeypatch.setattr(pacman_repo, "_HAS_ZSTD", False)
path = write(repo, LOCK_PATH, LOCK)
monkeypatch.chdir(repo)
assert check.main(["--strict", str(path)]) == 3
out = capsys.readouterr()
assert "compression.zstd" in out.out + out.err

View File

@ -1,146 +0,0 @@
"""The pacman-repo adapter: pacman `vercmp` order and reading a repo `.db`.
Versions here are `epoch:pkgver-pkgrel`, which PEP 440 cannot read at all:
`versions.behind` answers False for every pair, so a stale lock would read
as current. The ordering tests below come from the vercmp(8) man page, and
the differential test checks them against the real `/usr/bin/vercmp`.
"""
from __future__ import annotations
import io
import itertools
import shutil
import subprocess
import tarfile
import pytest
from dep_freshness.registries import pacman_repo
from dep_freshness.registries.http import Offline
REPO = "https://mirror.example.org/repo/x86_64/extra/extra.db"
SHA = "ab" * 32
# vercmp(8): "1.0a < 1.0b < 1.0beta < 1.0p < 1.0pre < 1.0rc < 1.0 < 1.0.a < 1.0.1"
MAN_ORDER = ["1.0a", "1.0b", "1.0beta", "1.0p", "1.0pre", "1.0rc", "1.0", "1.0.a",
"1.0.1"]
PAIRS = [
("1:1.0", "2.0", 1),
("0:2.0", "2.0", 0),
("1:11.0.20261015-1", "1:10.0.20250101-1", 1),
("1:11.0.20261015-1", "1:11.0.20261015-1", 0),
("1.0-1", "1.0-2", -1),
("1.0", "1.0-7", 0), # a missing pkgrel compares equal
("1.0.0", "1.0", 1),
("1.0_1", "1.0.1", 0), # any non-alphanumeric run is one separator
("1.0", "1.0.0.0", -1),
("2.0", "10.0", -1),
("1.001", "1.1", 0),
("r123", "r45", 1),
]
@pytest.mark.parametrize(("left", "right"), list(itertools.pairwise(MAN_ORDER)))
def test_vercmp_follows_the_man_page_order(left, right):
assert pacman_repo.vercmp(left, right) == -1
assert pacman_repo.vercmp(right, left) == 1
@pytest.mark.parametrize(("left", "right", "expected"), PAIRS)
def test_vercmp_epoch_and_pkgrel(left, right, expected):
assert pacman_repo.vercmp(left, right) == expected
@pytest.mark.skipif(not shutil.which("vercmp"), reason="pacman's vercmp absent")
@pytest.mark.parametrize(
("left", "right"),
[*itertools.pairwise(MAN_ORDER), *((a, b) for a, b, _ in PAIRS)],
)
def test_vercmp_agrees_with_pacman(left, right):
real = subprocess.run(
["vercmp", left, right], capture_output=True, text=True, check=True
).stdout.strip()
assert pacman_repo.vercmp(left, right) == int(real)
def _desc(name: str, version: str, sha: str = SHA) -> bytes:
return (
f"%FILENAME%\n{name}-{version}-x86_64.pkg.tar.zst\n\n%NAME%\n{name}\n\n"
f"%VERSION%\n{version}\n\n%SHA256SUM%\n{sha}\n\n"
).encode()
def build_db(
packages: dict[str, str], compression: str = "gz", sha: str = SHA
) -> bytes:
"""A repo db the way repo-add writes it: one `<name>-<ver>/desc` per package."""
raw = io.BytesIO()
with tarfile.open(fileobj=raw, mode=f"w:{compression}") as tar:
for name, version in packages.items():
body = _desc(name, version, sha)
info = tarfile.TarInfo(f"{name}-{version}/desc")
info.size = len(body)
tar.addfile(info, io.BytesIO(body))
return raw.getvalue()
@pytest.fixture
def serve(monkeypatch):
"""Answer the next `get_bytes` with `body`, recording the URL asked for."""
asked: list[str] = []
def install(body):
def fake(url):
asked.append(url)
return body
monkeypatch.setattr(pacman_repo, "get_bytes", fake)
return asked
return install
@pytest.mark.parametrize("compression", ["gz", "zst"])
def test_latest_reads_version_and_sha_from_the_db(serve, compression):
asked = serve(build_db({"proton-native": "1:11.0-1", "zlib": "1.3-1"},
compression))
name = pacman_repo.qualified_name(REPO, "proton-native")
assert pacman_repo.latest(name) == f"1:11.0-1 {SHA}"
assert asked == [REPO]
def test_a_sibling_sharing_the_name_prefix_is_not_the_package(serve):
serve(build_db({"proton-native-v3": "9:9.0-1", "proton-native": "1:2.0-1"}))
name = pacman_repo.qualified_name(REPO, "proton-native")
assert pacman_repo.latest(name).split()[0] == "1:2.0-1"
def test_a_package_the_db_does_not_list_is_none(serve):
serve(build_db({"zlib": "1.3-1"}))
assert pacman_repo.latest(pacman_repo.qualified_name(REPO, "nope")) is None
def test_a_missing_db_is_none(serve):
serve(None)
assert pacman_repo.latest(pacman_repo.qualified_name(REPO, "x")) is None
def test_a_db_that_is_not_a_tar_is_offline(serve):
serve(b"<html>captive portal</html>")
with pytest.raises(Offline):
pacman_repo.latest(pacman_repo.qualified_name(REPO, "x"))
def test_zstd_without_compression_zstd_names_the_missing_module(
serve, monkeypatch
):
serve(build_db({"x": "1.0-1"}, "zst"))
monkeypatch.setattr(pacman_repo, "_HAS_ZSTD", False)
with pytest.raises(Offline, match="compression.zstd"):
pacman_repo.latest(pacman_repo.qualified_name(REPO, "x"))
def test_qualified_name_round_trips():
assert pacman_repo.split_name(pacman_repo.qualified_name(REPO, "x")) == (
REPO,
"x",
)

View File

@ -27,6 +27,11 @@ 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
- id: subproject-scope
name: subproject scope regex still matches
entry: scripts/check_subproject_scope.sh design_system
@ -40,9 +45,16 @@ repos:
entry: bash -c 'cd design_system && dart format --set-exit-if-changed lib test'
language: system
pass_filenames: false
- id: flutter-test
name: flutter test
entry: bash -c 'cd design_system && flutter test'
- id: flutter-analyze
name: flutter analyze
entry: bash -c 'cd design_system && flutter analyze'
language: system
pass_filenames: false
- id: flutter-test-coverage
name: flutter test --coverage with 100% line-coverage gate
entry: >-
bash -c 'cd design_system && flutter test --coverage &&
scripts/check_coverage.sh coverage/lcov.info 100'
language: system
pass_filenames: false
require_serial: true

View File

@ -1,54 +0,0 @@
# devstats: kuhy vs "the 100x programmer" article
Generated 2026-11-27 by `python -m devstats compare --write` (utils/devstats).
Article: https://veszelovszki.com/a/tpe/ (Cmdr, posted 2026-10-24).
- kuhy: every repo under ~/src, each piece of work once (worktrees, clones
and rewritten copies folded in), commits on the local default branch plus
its `origin/` tracking ref as last fetched (each SHA once; nothing fetched
or pulled), `--no-merges`, authored by kuhy's address (agent-made commits
included). Committer date, local time.
- Net LoC = insertions − deletions of code paths. Docs/translations are left
out of the headline like the article's; the "+docs" row adds them back.
- Cmdr's figures are per calendar day; the baseline (194) is per day with a
push, so kuhy's per-active-day column divides by days with ≥1 counted commit.
- ×0.67 is the article's "Discount it by 33% to compensate for the AI bloat".
## LoC per calendar day vs Cmdr
| window | row | kuhy net LoC/day | ins/day | del/day | Cmdr LoC/day |
|---|---|---|---|---|---|
| 30 d | raw | 26,280 | 36,348 | 10,068 | 12,000 |
| 30 d | ×0.67 | 17,608 | 24,353 | 6,745 | 8,040 |
| 30 d | +docs | 26,716 | 37,628 | 10,912 | — |
| 90 d | raw | 19,733 | 24,779 | 5,046 | 9,700 |
| 90 d | ×0.67 | 13,221 | 16,602 | 3,381 | 6,499 |
| 90 d | +docs | 20,163 | 25,647 | 5,484 | — |
| 300 d ≈ lifetime (10 mo) | raw | 7,733 | 11,255 | 3,522 | 4,500 |
| 300 d ≈ lifetime (10 mo) | ×0.67 | 5,181 | 7,541 | 2,360 | 3,015 |
| 300 d ≈ lifetime (10 mo) | +docs | 8,080 | 11,976 | 3,897 | — |
## Per active day vs the 194 LoC/workday baseline
| window | active days | row | kuhy net LoC/active day | baseline LoC/workday | kuhy ÷ 194 | kuhy commits/active day | Cmdr commits/workday |
|---|---|---|---|---|---|---|---|
| 30 d | 24 | raw | 32,851 | 194 | 169.3× | 148 | 160 |
| 30 d | 24 | ×0.67 | 22,010 | 194 | 113.5× | | |
| 90 d | 77 | raw | 23,065 | 194 | 118.9× | 83 | — |
| 90 d | 77 | ×0.67 | 15,453 | 194 | 79.7× | | |
| 300 d ≈ lifetime (10 mo) | 181 | raw | 12,816 | 194 | 66.1× | 48 | 55 |
| 300 d ≈ lifetime (10 mo) | 181 | ×0.67 | 8,587 | 194 | 44.3× | | |
## Totals
| window | net code LoC | insertions | deletions | net +docs | excluded share | commits | tags | tags/week | Cmdr releases/week | repos with ≥1 tag |
|---|---|---|---|---|---|---|---|---|---|---|
| 30 d | 788,415 | 1,090,449 | 302,034 | 801,473 | 23% | 3,556 | 732 | 170.8 | ~2 | 26 |
| 90 d | 1,775,992 | 2,230,132 | 454,140 | 1,814,652 | 23% | 6,383 | 1233 | 95.9 | ~2 | 28 |
| 300 d ≈ lifetime (10 mo) | 2,319,758 | 3,376,373 | 1,056,615 | 2,423,874 | 32% | 8,607 | 1668 | 38.9 | ~2 | 31 |
## Exclude list (first match wins)
- excluded: `node_modules/`, `vendor/`, `third_party/`, `addons/`, `.venv/`, `.dart_tool/`, `dist/`, `build/`, `generated/`, `htmlcov/`, `coverage/`, `__snapshots__/`, `*.lock`, `*.lockb`, `package-lock.json`, `npm-shrinkwrap.json`, `pnpm-lock.yaml`, `go.sum`, `*.g.dart`, `*.freezed.dart`, `*.mocks.dart`, `*.gr.dart`, `*.pb.go`, `*_pb2.py`, `*.min.js`, `*.min.css`, `*.map`, `coverage.xml`, `lcov.info`, `*.lcov`, `*.import`, `*.uid`, `*.snap`, `data/`, `assets/`, `fixtures/`, `*.json`, `*.jsonl`, `*.ndjson`, `*.geojson`, `*.csv`, `*.tsv`, `*.txt`, `*.tcx`, `*.gpx`, `*.tres`, `*.svg`, `*.log`
- docs: `docs/`, `doc/`, `l10n/`, `locales/`, `i18n/`, `translations/`, `*.md`, `*.mdx`, `*.rst`, `*.adoc`, `*.arb`, `*.po`, `*.pot`, `LICENSE*`, `COPYING*`
- code: `godot_dev_tools/`, `package.json`, `tsconfig*.json`, `jsconfig.json`, `deno.json`, `requirements*.txt`, `CMakeLists.txt`, `*.py`, `*.dart`, `*.ts`, `*.tsx`, `*.js`, `*.jsx`, `*.mjs`, `*.gd`, `*.go`, `*.kt`, `*.kts`, `*.java`, `*.sh`, `*.c`, `*.h`, `*.cpp`, `*.rs`, `*.lua`

View File

@ -1 +0,0 @@
"""devstats: kuhy's git output (net LoC/day, commits, tags) vs the 100x article."""

View File

@ -1,5 +0,0 @@
"""`python -m devstats compare` entry point."""
from devstats.cli import main
raise SystemExit(main())

View File

@ -1,116 +0,0 @@
"""Per-window totals over every repo's commits and tags."""
from __future__ import annotations
from collections.abc import Sequence
from dataclasses import dataclass, replace
from datetime import datetime
from devstats.excludes import classify
from devstats.numstat import Commit
DAY = 86_400
@dataclass(frozen=True)
class RepoData:
"""Counted commits (already filtered to the chosen emails) and (sha, ts) tags of one repo."""
name: str
commits: tuple[Commit, ...]
tags: tuple[tuple[str, int], ...]
@dataclass(frozen=True)
class Window:
"""Totals for the last `days` days."""
days: int
code_ins: int
code_del: int
docs_ins: int
docs_del: int
excluded_lines: int
all_lines: int
commits: int
active_days: int
tags: int
repos_with_tags: int
@property
def net(self) -> int:
"""Headline: code insertions minus deletions (docs and excluded paths left out)."""
return self.code_ins - self.code_del
@property
def net_with_docs(self) -> int:
"""Net including markdown/translations ("+docs")."""
return self.net + self.docs_ins - self.docs_del
@property
def excluded_share(self) -> float:
"""Share of all changed lines (ins+del) the exclude list dropped."""
return self.excluded_lines / self.all_lines if self.all_lines else 0.0
def dedup(repos: Sequence[RepoData]) -> list[RepoData]:
"""Count each piece of work once across repos.
A filter-repo split (testsAndMisc -> testsAndMisc-archive) or a fork
(kuhytrack -> leisure-watch) carries the same commits, rewritten or not.
Copies share email + author time + subject; the copy with the larger diff
is kept (the earlier repo on a tie), the others are dropped. A tag object
seen in an earlier repo (a clone) is dropped too.
"""
best: dict[tuple[str, int, str], tuple[int, Commit]] = {}
for i, repo in enumerate(repos):
for c in repo.commits:
seen = best.get(c.identity)
if seen is None or c.churn > seen[1].churn:
best[c.identity] = (i, c)
keep = {(i, c.sha) for i, c in best.values()}
seen_tags: set[str] = set()
out = []
for i, repo in enumerate(repos):
tags = tuple(t for t in repo.tags if t[0] not in seen_tags)
seen_tags.update(sha for sha, _ in repo.tags)
out.append(replace(repo, commits=tuple(c for c in repo.commits if (i, c.sha) in keep),
tags=tags))
return out
def window_totals(repos: Sequence[RepoData], days: int, now: float) -> Window:
"""Aggregate `repos` over the `days` days before `now`."""
cutoff = now - days * DAY
sums = {"code": [0, 0], "docs": [0, 0], "excluded": [0, 0]}
commits = 0
dates: set[object] = set()
tags = repos_with_tags = 0
for repo in repos:
for c in repo.commits:
if c.ts < cutoff:
continue
commits += 1
dates.add(datetime.fromtimestamp(c.ts).date())
for f in c.files:
if not f.binary:
bucket = sums[classify(f.path)]
bucket[0] += f.ins
bucket[1] += f.dels
n = sum(1 for _, t in repo.tags if cutoff <= t <= now)
tags += n
repos_with_tags += n > 0
excluded = sum(sums["excluded"])
return Window(
days=days,
code_ins=sums["code"][0],
code_del=sums["code"][1],
docs_ins=sums["docs"][0],
docs_del=sums["docs"][1],
excluded_lines=excluded,
all_lines=excluded + sum(sums["code"]) + sum(sums["docs"]),
commits=commits,
active_days=len(dates),
tags=tags,
repos_with_tags=repos_with_tags,
)

View File

@ -1,21 +0,0 @@
"""Figures from https://veszelovszki.com/a/tpe/ (post dated 2026-10-24).
Cmdr's LoC/day are per calendar day, weekends included, and exclude
"generated code, libraries, docs, etc." (docs and translations are a separate
"+800k"). The windows are the article's: last 30 days ~12,000, last 90 days
~9,700, lifetime (~10 months) 4,500. The 194 baseline is Sourcegraph LoC per
day "when I pushed code", i.e. per active day. Commits: ~160/workday in
October, ~55/workday lifetime, no 90-day figure. Releases: ~2/week.
"Discount it by 33%" (x0.67) applies to Cmdr's rates, not to the baseline.
"""
from __future__ import annotations
URL = "https://veszelovszki.com/a/tpe/"
WINDOWS: tuple[int, ...] = (30, 90, 300)
LABELS = {30: "30 d", 90: "90 d", 300: "300 d ≈ lifetime (10 mo)"}
CMDR_LOC_PER_DAY = {30: 12_000, 90: 9_700, 300: 4_500}
CMDR_COMMITS_PER_WORKDAY: dict[int, int | None] = {30: 160, 90: None, 300: 55}
BASELINE_LOC_PER_WORKDAY = 194
RELEASES_PER_WEEK = 2
AI_DISCOUNT = 0.67

View File

@ -1,86 +0,0 @@
"""`python -m devstats compare [--root DIR]... [--email ADDR]... [--by-repo [N]] [--write] [--html PATH]`."""
from __future__ import annotations
import argparse
import sys
import time
from collections.abc import Sequence
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime
from pathlib import Path
from typing import TextIO
from devstats import article as A
from devstats.aggregate import DAY, RepoData, Window, dedup, window_totals
from devstats.discover import Repo, discover
from devstats.report_html import page
from devstats.numstat import read_commits
from devstats.refs import list_refs, resolve, tag_times
from devstats.render import by_repo, document, report
DEFAULT_EMAIL = "krzysztofrudnicki0@gmail.com"
DOC_PATH = Path(__file__).resolve().parent / "DOCS-comparison.md"
EXIT_NO_REPOS = 2
def build_parser() -> argparse.ArgumentParser:
"""Argument parser with the single `compare` subcommand."""
parser = argparse.ArgumentParser(prog="devstats", description="kuhy's git output vs the 100x article")
sub = parser.add_subparsers(dest="cmd", required=True)
cmp = sub.add_parser("compare", help="print kuhy's 30/90/300-day numbers beside the article's")
cmp.add_argument("--root", action="append", type=Path, default=[],
help="directory (or repo) whose child repos are walked (repeatable; "
"given roots replace the default ~/src)")
cmp.add_argument("--email", action="append", default=[],
help=f"extra author email to count (repeatable; {DEFAULT_EMAIL} always counts)")
cmp.add_argument("--by-repo", nargs="?", type=int, const=10, default=0, metavar="N",
help="also print the top N repos (terminal only, default N=10)")
cmp.add_argument("--write", action="store_true", help="rewrite devstats/DOCS-comparison.md")
cmp.add_argument("--html", type=Path, metavar="PATH",
help="also write the report page (bar chart + tables) to PATH")
return parser
def _collect(repo: Repo, emails: frozenset[str], since: int) -> tuple[RepoData, list[str]]:
"""Commits by `emails` on the repo's default branch since `since`, its tags, warnings."""
refs = list_refs(repo.path)
default = resolve(refs)
tags = tuple(tag_times(refs))
if default.branch is None:
return RepoData(repo.name, (), tags), [f"{repo.name}: no main/master/origin HEAD branch, skipped"]
commits = tuple(c for c in read_commits(repo.path, default.log_refs, since) if c.email in emails)
return RepoData(repo.name, commits, tags), []
def main(argv: Sequence[str] | None = None, *, now: float | None = None, out: TextIO = sys.stdout,
err: TextIO = sys.stderr, doc_path: Path = DOC_PATH) -> int:
"""Run the CLI; returns the exit code (2 when no repo was found)."""
args = build_parser().parse_args(argv)
now = time.time() if now is None else now
roots = args.root or [Path.home() / "src"]
emails = frozenset(e.lower() for e in (DEFAULT_EMAIL, *args.email))
repos, warnings = discover(roots)
if not repos:
print(f"devstats: no git repos under {', '.join(map(str, roots))}", file=err)
return EXIT_NO_REPOS
since = int(now - max(A.WINDOWS) * DAY)
with ThreadPoolExecutor(max_workers=8) as pool:
results = list(pool.map(lambda r: _collect(r, emails, since), repos))
data = dedup([d for d, _ in results])
for w in (*warnings, *(w for _, ws in results for w in ws)):
print(f"warning: {w}", file=err)
windows: list[Window] = [window_totals(data, d, now) for d in A.WINDOWS]
print(report(windows), file=out)
if args.by_repo:
per_repo = [(d.name, [window_totals([d], days, now) for days in A.WINDOWS]) for d in data]
print(by_repo(per_repo, args.by_repo), file=out)
date = datetime.fromtimestamp(now).date().isoformat()
if args.write:
doc_path.write_text(document(windows, date))
print(f"wrote {doc_path}", file=out)
if args.html:
args.html.parent.mkdir(parents=True, exist_ok=True)
args.html.write_text(page(windows, date))
print(f"report: {args.html}", file=out)
return 0

View File

@ -1,47 +0,0 @@
"""Find repos one level under each root and fold worktrees into their repo.
Worktrees (e.g. the sb-wt-* signal-bot checkouts) share one git common dir
with their main repo, so deduplicating on it counts every repo once, named
after the common dir's parent whichever checkout was walked first.
"""
from __future__ import annotations
from collections.abc import Sequence
from dataclasses import dataclass
from pathlib import Path
from devstats.gitcmd import GitError, git
@dataclass(frozen=True)
class Repo:
"""One repository: display name and a checkout path to run git in."""
name: str
path: Path
def _candidates(root: Path) -> list[Path]:
"""The root itself if it is a checkout, else its direct children that are."""
if (root / ".git").exists():
return [root]
if not root.is_dir():
return []
return sorted(p for p in root.iterdir() if p.is_dir() and (p / ".git").exists())
def discover(roots: Sequence[Path]) -> tuple[list[Repo], list[str]]:
"""Repos under `roots`, one per git common dir, plus warnings for broken ones."""
seen: dict[Path, Repo] = {}
warnings: list[str] = []
for root in roots:
for path in _candidates(root):
try:
out = git(path, "rev-parse", "--path-format=absolute", "--git-common-dir")
except GitError:
warnings.append(f"{path.name}: not a readable git repo, skipped")
continue
common = Path(out.decode().strip())
seen.setdefault(common, Repo(name=common.parent.name, path=path))
return sorted(seen.values(), key=lambda r: r.name), warnings

View File

@ -1,92 +0,0 @@
"""THE exclude list: which changed paths count as code, docs or dropped churn.
One ordered constant, first match wins. A pattern ending in "/" matches any
directory component of the path; any other pattern is a glob on the file name.
Vendored/build directories come first so nothing inside node_modules/ or
addons/ is rescued by a later rule; source files (by extension) are kept
before the data/, assets/ and fixtures/ directory rules, so lib/data/*.dart
and a fixtures/ fake binary in Python stay code; the code keeps come before the file excludes so
package.json survives `*.json`; translation dirs come before `*.json` so
locales/en.json counts as docs, like the article's "+800k translations and docs".
Judgment calls, calibrated on the 30-day top-40 churn list (2026-11-27):
- `*.txt` is data (one word list was ~10% of all churn) except requirements/CMake.
- `*.json` is data (eval dumps, fixtures, baselines) except a few config names.
- Godot `addons/` is vendored (GUT, copies of dev_tools) except the source of
kuhy's own addon under `godot_dev_tools/`; `*.tres` is data; `*.import`/`*.uid` are
generated; `*.tscn` scenes stay code (authored structure).
- `fixtures/` is test data; test code (source extensions) inside it stays.
"""
from __future__ import annotations
from fnmatch import fnmatchcase
from typing import Literal
Bucket = Literal["code", "docs", "excluded"]
RULES: tuple[tuple[Bucket, str], ...] = (
# kuhy's own Godot addon source (utils/godot_dev_tools); games carry vendored copies
("code", "godot_dev_tools/"),
# vendored and build-output directories (any depth): everything inside goes
*(
("excluded", d)
for d in (
"node_modules/", "vendor/", "third_party/", "addons/", ".venv/", ".dart_tool/",
"dist/", "build/", "generated/", "htmlcov/", "coverage/", "__snapshots__/",
)
),
# config files that would otherwise fall under a data glob below
*(
("code", f)
for f in ("package.json", "tsconfig*.json", "jsconfig.json", "deno.json",
"requirements*.txt", "CMakeLists.txt")
),
# translations and docs directories
*(("docs", d) for d in ("docs/", "doc/", "l10n/", "locales/", "i18n/", "translations/")),
# lockfiles
*(
("excluded", f)
for f in ("*.lock", "*.lockb", "package-lock.json", "npm-shrinkwrap.json",
"pnpm-lock.yaml", "go.sum")
),
# generated files
*(
("excluded", f)
for f in ("*.g.dart", "*.freezed.dart", "*.mocks.dart", "*.gr.dart", "*.pb.go",
"*_pb2.py", "*.min.js", "*.min.css", "*.map", "coverage.xml", "lcov.info",
"*.lcov", "*.import", "*.uid", "*.snap")
),
# source files stay code even inside the data dirs below (lib/data/*.dart)
*(
("code", f)
for f in ("*.py", "*.dart", "*.ts", "*.tsx", "*.js", "*.jsx", "*.mjs", "*.gd", "*.go",
"*.kt", "*.kts", "*.java", "*.sh", "*.c", "*.h", "*.cpp", "*.rs", "*.lua")
),
# data and asset directories: whatever is not source in them is data
*(("excluded", d) for d in ("data/", "assets/", "fixtures/")),
# data and assets
*(
("excluded", f)
for f in ("*.json", "*.jsonl", "*.ndjson", "*.geojson", "*.csv", "*.tsv", "*.txt",
"*.tcx", "*.gpx", "*.tres", "*.svg", "*.log")
),
# docs and translations
*(
("docs", f)
for f in ("*.md", "*.mdx", "*.rst", "*.adoc", "*.arb", "*.po", "*.pot",
"LICENSE*", "COPYING*")
),
)
def classify(path: str) -> Bucket:
"""Bucket for one repo-relative path (binaries are handled by the caller)."""
*dirs, name = path.split("/")
for bucket, pattern in RULES:
if pattern.endswith("/"):
if any(fnmatchcase(d, pattern[:-1]) for d in dirs):
return bucket
elif fnmatchcase(name, pattern):
return bucket
return "code"

View File

@ -1,26 +0,0 @@
"""Read-only git subprocess wrapper.
GIT_OPTIONAL_LOCKS=0 stops even read commands from refreshing the index of a
walked repo, so a run never changes anything in kuhy's checkouts.
"""
from __future__ import annotations
import os
import subprocess
from pathlib import Path
class GitError(RuntimeError):
"""git exited non-zero."""
def git(repo: Path, *args: str) -> bytes:
"""Run `git -C repo args...` and return raw stdout, raising GitError on failure."""
env = {**os.environ, "GIT_OPTIONAL_LOCKS": "0", "LC_ALL": "C"}
proc = subprocess.run(
["git", "-C", str(repo), *args], env=env, capture_output=True, check=False
)
if proc.returncode != 0:
raise GitError(proc.stderr.decode(errors="replace").strip())
return proc.stdout

View File

@ -1,91 +0,0 @@
"""One `git log --numstat -z` pass per repo, parsed into commits and file changes.
Record layout (git 2.x): `\\x1e<sha>\\x1f<committer ts>\\x1f<author email>\\x1f<author ts>\\x1f<subject>\\0`,
then a newline before the first entry, then per file either
`ins\\tdel\\tpath\\0` or, for a rename, `ins\\tdel\\t\\0old\\0new\\0`.
Binaries report `-` for both counts.
"""
from __future__ import annotations
from collections.abc import Sequence
from dataclasses import dataclass
from datetime import UTC, datetime
from pathlib import Path
from devstats.gitcmd import git
FORMAT = "%x1e%H%x1f%ct%x1f%ae%x1f%at%x1f%s"
@dataclass(frozen=True)
class FileChange:
"""Line counts for one path in one commit."""
path: str
ins: int
dels: int
binary: bool
@dataclass(frozen=True)
class Commit:
"""One non-merge commit: committer timestamp, lowercased author email, files.
`author_ts` + `subject` survive history rewrites (filter-repo splits, forks),
so together with the email they identify the same work across repos.
"""
sha: str
ts: int
email: str
files: tuple[FileChange, ...]
author_ts: int = 0
subject: str = ""
@property
def identity(self) -> tuple[str, int, str]:
"""Key that is equal for a commit and its rewritten copy in another repo."""
return (self.email, self.author_ts, self.subject)
@property
def churn(self) -> int:
"""Changed lines (ins+del) over all files."""
return sum(f.ins + f.dels for f in self.files)
def _parse_files(tokens: list[str]) -> tuple[FileChange, ...]:
"""Turn the NUL-split numstat tokens of one commit into FileChanges."""
files: list[FileChange] = []
i = 0
while i < len(tokens):
tok = tokens[i].lstrip("\n")
i += 1
if not tok:
continue
ins, dels, path = tok.split("\t", 2)
if not path: # rename: old and new path follow as their own tokens
path = tokens[i + 1]
i += 2
binary = ins == "-"
files.append(FileChange(path, 0 if binary else int(ins), 0 if binary else int(dels), binary))
return tuple(files)
def parse_log(raw: bytes) -> list[Commit]:
"""Parse the output of `git log --numstat -z --format=FORMAT`."""
commits: list[Commit] = []
for record in raw.decode(errors="replace").split("\x1e")[1:]:
header, _, body = record.partition("\0")
sha, ts, email, author_ts, subject = header.split("\x1f", 4)
files = _parse_files(body.split("\0"))
commits.append(Commit(sha, int(ts), email.lower(), files, int(author_ts), subject))
return commits
def read_commits(repo: Path, refs: Sequence[str], since_ts: int) -> list[Commit]:
"""Non-merge commits reachable from any of `refs`, committed at or after `since_ts`."""
since = datetime.fromtimestamp(since_ts, UTC).isoformat()
raw = git(repo, "log", *refs, "--no-merges", f"--since={since}", "--numstat", "-z",
f"--format={FORMAT}", "--")
return [c for c in parse_log(raw) if c.ts >= since_ts]

View File

@ -1,66 +0,0 @@
"""Default-branch resolution from refs on disk (never fetches, never pulls).
The local default branch is logged together with its `origin/` tracking ref
when the two tips differ. Work landed with `git push origin HEAD:main` from a
worktree sits only on the tracking ref until the checkout is pulled, and kuhy's
live checkouts (tutor, todo) must not be pulled by a stats run. `git log` walks
the union, so each SHA counts once and a diverged repo counts both sides.
origin/HEAD only names the branch; a branch that exists only on origin/ is not
counted (no local checkout of that work).
"""
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from devstats.gitcmd import git
_FORMAT = "%(refname)%09%(symref)%09%(objectname)%09%(committerdate:unix)%09%(creatordate:unix)"
_ORIGIN = "refs/remotes/origin/"
@dataclass(frozen=True)
class Ref:
"""One ref: tip sha, tip committer ts (0 for tag objects), symref target, creator ts."""
sha: str
ts: int
symref: str
created: int
@dataclass(frozen=True)
class DefaultRefs:
"""The default branch name and the refs whose union is logged."""
branch: str | None
log_refs: tuple[str, ...]
def list_refs(repo: Path) -> dict[str, Ref]:
"""Every local branch, origin remote-tracking ref and tag, in one git call."""
out = git(repo, "for-each-ref", f"--format={_FORMAT}", "refs/heads", "refs/remotes/origin",
"refs/tags").decode(errors="replace")
refs: dict[str, Ref] = {}
for line in out.splitlines():
name, symref, sha, ts, created = line.split("\t")
refs[name] = Ref(sha=sha, ts=int(ts or 0), symref=symref, created=int(created or 0))
return refs
def tag_times(refs: dict[str, Ref]) -> list[tuple[str, int]]:
"""(object sha, creator ts) of every tag: tagger date, or the commit date if lightweight."""
return [(r.sha, r.created) for name, r in refs.items() if name.startswith("refs/tags/")]
def resolve(refs: dict[str, Ref]) -> DefaultRefs:
"""origin/HEAD's branch, else main, else master: the first that exists locally."""
head = refs.get(_ORIGIN + "HEAD")
candidates = [head.symref.removeprefix(_ORIGIN)] if head and head.symref else []
for branch in (*candidates, "main", "master"):
local, remote = refs.get("refs/heads/" + branch), refs.get(_ORIGIN + branch)
if local:
tracking = (_ORIGIN + branch,) if remote and remote.sha != local.sha else ()
return DefaultRefs(branch, ("refs/heads/" + branch, *tracking))
return DefaultRefs(None, ())

View File

@ -1,125 +0,0 @@
"""Tables of kuhy beside the article, plus the optional per-repo breakdown.
The `*_rows` builders return (head, rows) of plain cell strings; the markdown
here and the HTML page in `devstats.report_html` both render those, so the page and
the terminal always show the same numbers.
"""
from __future__ import annotations
from collections.abc import Sequence
from devstats import article as A
from devstats.aggregate import Window
from devstats.excludes import RULES
DASH = "—"
Table = tuple[tuple[str, ...], list[list[str]]]
def num(x: float) -> str:
"""Whole number with thousands separators."""
return f"{x:,.0f}"
def _table(head: Sequence[str], rows: Sequence[Sequence[str]]) -> list[str]:
out = ["| " + " | ".join(head) + " |", "|" + "---|" * len(head)]
out += ["| " + " | ".join(r) + " |" for r in rows]
return out
def per_calendar_day(windows: Sequence[Window]) -> Table:
"""kuhy raw / ×0.67 / +docs LoC per calendar day beside Cmdr raw / ×0.67."""
rows = []
for w in windows:
d, cmdr, label = w.days, A.CMDR_LOC_PER_DAY[w.days], A.LABELS[w.days]
for row, k in (("raw", 1.0), ("×0.67", A.AI_DISCOUNT)):
rows.append([label, row, num(w.net * k / d), num(w.code_ins * k / d),
num(w.code_del * k / d), num(cmdr * k)])
rows.append([label, "+docs", num(w.net_with_docs / d), num((w.code_ins + w.docs_ins) / d),
num((w.code_del + w.docs_del) / d), DASH])
head = ("window", "row", "kuhy net LoC/day", "ins/day", "del/day", "Cmdr LoC/day")
return head, rows
def per_active_day(windows: Sequence[Window]) -> Table:
"""kuhy per active day beside the 194 baseline, plus commits beside Cmdr's."""
rows = []
base = A.BASELINE_LOC_PER_WORKDAY
for w in windows:
active = max(w.active_days, 1)
cmdr_commits = A.CMDR_COMMITS_PER_WORKDAY[w.days]
for row, k in (("raw", 1.0), ("×0.67", A.AI_DISCOUNT)):
per = w.net * k / active
commits = [num(w.commits / active), DASH if cmdr_commits is None else num(cmdr_commits)]
rows.append([A.LABELS[w.days], str(w.active_days), row, num(per), str(base),
f"{per / base:.1f}×", *(commits if row == "raw" else ["", ""])])
head = ("window", "active days", "row", "kuhy net LoC/active day", "baseline LoC/workday",
"kuhy ÷ 194", "kuhy commits/active day", "Cmdr commits/workday")
return head, rows
def totals(windows: Sequence[Window]) -> Table:
"""Raw totals, the share the exclude list removed, and tags."""
rows = [
[A.LABELS[w.days], num(w.net), num(w.code_ins), num(w.code_del), num(w.net_with_docs),
f"{w.excluded_share:.0%}", num(w.commits), str(w.tags), f"{w.tags / (w.days / 7):.1f}",
f"~{A.RELEASES_PER_WEEK}", str(w.repos_with_tags)]
for w in windows
]
head = ("window", "net code LoC", "insertions", "deletions", "net +docs", "excluded share",
"commits", "tags", "tags/week", "Cmdr releases/week", "repos with ≥1 tag")
return head, rows
def sections(windows: Sequence[Window]) -> list[tuple[str, Table]]:
"""(title, table) of each comparison table, in print order."""
return [("LoC per calendar day vs Cmdr", per_calendar_day(windows)),
("Per active day vs the 194 LoC/workday baseline", per_active_day(windows)),
("Totals", totals(windows))]
def report(windows: Sequence[Window]) -> str:
"""The comparison tables, as printed and as written to DOCS-comparison.md."""
blocks = ["\n".join([f"## {title}", "", *_table(head, rows)])
for title, (head, rows) in sections(windows)]
return "\n\n".join(blocks) + "\n"
def by_repo(per_repo: Sequence[tuple[str, Sequence[Window]]], top: int) -> str:
"""Top-`top` repos by 300-day net code LoC (terminal only, never written)."""
ranked = sorted(per_repo, key=lambda item: -item[1][-1].net)[:top]
head = ("repo", *(f"net {A.LABELS[d].split(' ≈')[0]}" for d in A.WINDOWS), "commits 300 d")
rows = [[name, *(num(w.net) for w in ws), num(ws[-1].commits)] for name, ws in ranked]
return "\n".join(["## Top repos", "", *_table(head, rows)]) + "\n"
def exclude_list() -> str:
"""The exclude list grouped by bucket, for the doc."""
lines = []
for bucket in ("excluded", "docs", "code"):
pats = ", ".join(f"`{p}`" for b, p in RULES if b == bucket)
lines.append(f"- {bucket}: {pats}")
return "\n".join(lines) + "\n"
def document(windows: Sequence[Window], date: str) -> str:
"""Full DOCS-comparison.md body: aggregates only, no repo names."""
intro = f"""# devstats: kuhy vs "the 100x programmer" article
Generated {date} by `python -m devstats compare --write` (utils/devstats).
Article: {A.URL} (Cmdr, posted 2026-10-24).
- kuhy: every repo under ~/src, each piece of work once (worktrees, clones
and rewritten copies folded in), commits on the local default branch plus
its `origin/` tracking ref as last fetched (each SHA once; nothing fetched
or pulled), `--no-merges`, authored by kuhy's address (agent-made commits
included). Committer date, local time.
- Net LoC = insertions − deletions of code paths. Docs/translations are left
out of the headline like the article's; the "+docs" row adds them back.
- Cmdr's figures are per calendar day; the baseline (194) is per day with a
push, so kuhy's per-active-day column divides by days with ≥1 counted commit.
- ×0.67 is the article's "Discount it by 33% to compensate for the AI bloat".
"""
return intro + report(windows) + "\n## Exclude list (first match wins)\n\n" + exclude_list()

View File

@ -1,90 +0,0 @@
"""Static HTML report: a kuhy-vs-Cmdr bar chart above the three terminal tables.
One self-contained file (inline CSS, no script, no network), so it stays
readable after the run ends and opens from `file://`. Table cells come from
`render.sections`, the same builders the terminal prints, so the numbers match.
Colours are the unified-design-system tokens: kuhy `cat-3`, Cmdr `cat-2` (the
pair that passes the dataviz CVD check; `cat-1`/`cat-2` fall to dE 6.9 protan).
"""
from __future__ import annotations
from collections.abc import Sequence
from html import escape
from devstats import article as A
from devstats.aggregate import Window
from devstats.render import num, sections
KUHY, CMDR = "#C85A32", "#398FC0"
BAR_SHARE = 82 # % of the track the longest bar fills; the rest holds its value label
CSS = """
:root{--bg:#F6F4F3;--card:#FCFBFB;--line:#E0DAD7;--text:#211D1B;--muted:#70625B;color-scheme:light dark}
@media (prefers-color-scheme:dark){:root{--bg:#211D1B;--card:#2B2624;--line:#463E3A;--text:#ECEAE9;
--muted:#AAA09A}}
html{font-size:16px}@media (min-width:2400px){html{font-size:22px}}
body{margin:0;background:var(--bg);color:var(--text);font:1rem/1.5 system-ui,sans-serif}
main{max-width:100rem;margin:0 auto;padding:1.5rem 1rem 3rem;box-sizing:border-box}
h2{font-size:1.125rem;font-weight:600;margin:2rem 0 .75rem}
.card{background:var(--card);border:1px solid var(--line);border-radius:8px;padding:1rem}
.scroll{overflow-x:auto}
.legend{display:flex;gap:1.5rem;margin:0 0 .75rem}.legend span{display:flex;align-items:center;gap:.4rem}
.sw{width:.75rem;height:.75rem;border-radius:2px}
.chart{display:grid;grid-template-columns:max-content 1fr;gap:1rem .75rem;align-items:center}
.lab{color:var(--muted);text-align:right;font-size:.875rem}
.pair{display:grid;gap:2px;border-left:1px solid var(--line)}
.track{display:flex;align-items:center;gap:.4rem;font-size:.875rem;font-variant-numeric:tabular-nums}
.bar{height:1rem;border-radius:0 4px 4px 0}
table{border-collapse:collapse;font-variant-numeric:tabular-nums;white-space:nowrap}
th,td{padding:.375rem .75rem;border-bottom:1px solid var(--line);text-align:right}
th{color:var(--muted);font-weight:600}th:nth-child(-n+2),td:nth-child(-n+2){text-align:left}
tr:last-child td{border-bottom:0}
"""
def _bars(windows: Sequence[Window]) -> list[tuple[str, float, float]]:
"""(row label, kuhy net LoC/day, Cmdr LoC/day) for each window, raw then x0.67."""
out = []
for w in windows:
label = A.LABELS[w.days].split(" ≈")[0]
for row, k in (("raw", 1.0), ("×0.67", A.AI_DISCOUNT)):
out.append((f"{label} · {row}", w.net * k / w.days, A.CMDR_LOC_PER_DAY[w.days] * k))
return out
def _track(who: str, label: str, value: float, peak: float, colour: str) -> str:
"""One bar (none when value <= 0) plus its value, with a hover tooltip."""
share = max(value, 0) / peak * BAR_SHARE
bar = (f'<i class="bar" style="width:{share:.1f}%;background:{colour}" '
f'title="{escape(f"{who} {label}: {num(value)}")}"></i>') if share > 0 else ""
return f'<div class="track">{bar}<span>{num(value)}</span></div>'
def chart(windows: Sequence[Window]) -> str:
"""Horizontal paired bars, kuhy above Cmdr, LoC per calendar day; HTML so text scales."""
bars = _bars(windows)
peak = max([1.0, *(max(k, c) for _, k, c in bars)])
legend = "".join(f'<span><i class="sw" style="background:{c}"></i>{who}</span>'
for who, c in (("kuhy", KUHY), ("Cmdr", CMDR)))
rows = "".join(f'<div class="lab">{escape(label)}</div><div class="pair">'
f"{_track('kuhy', label, k, peak, KUHY)}{_track('Cmdr', label, c, peak, CMDR)}</div>"
for label, k, c in bars)
return (f'<div class="legend">{legend}</div>'
f'<div class="chart" role="img" aria-label="kuhy vs Cmdr LoC per day">{rows}</div>')
def _html_table(head: Sequence[str], rows: Sequence[Sequence[str]]) -> str:
cells = "".join(f"<th>{escape(h)}</th>" for h in head)
body = "".join("<tr>" + "".join(f"<td>{escape(c)}</td>" for c in r) + "</tr>" for r in rows)
return f'<div class="card scroll"><table><thead><tr>{cells}</tr></thead><tbody>{body}</tbody></table></div>'
def page(windows: Sequence[Window], date: str) -> str:
"""The whole report page."""
tables = "".join(f"<h2>{escape(title)}</h2>{_html_table(head, rows)}"
for title, (head, rows) in sections(windows))
return (f'<!doctype html>\n<html lang="en"><head><meta charset="utf-8">'
f'<meta name="viewport" content="width=device-width,initial-scale=1">'
f"<title>devstats {escape(date)}</title><style>{CSS}</style></head><body><main>"
f'<div class="card">{chart(windows)}</div>{tables}</main></body></html>\n')

View File

@ -1,92 +0,0 @@
#!/bin/bash
# ============================================================================
# One-shot devstats run: installs python3/git when missing (pacman), runs
# `python -m devstats compare` over ~/src (or the given --root), prints the
# tables, writes ~/data/devstats/report.html and opens it unless --no-open.
# Works from any cwd: the repo root is found from this script's own path.
# Usage: run.sh [--no-open] [compare flags...] (run.sh --help lists them)
# Exit: devstats' own code (2 = no repos), 3 = setup failed.
# ============================================================================
set -euo pipefail
SELF="$(realpath "${BASH_SOURCE[0]}")"
readonly SELF
REPO_ROOT="$(dirname "$(dirname "$SELF")")"
readonly REPO_ROOT
readonly REPORT="$HOME/data/devstats/report.html"
readonly CAPPED="$HOME/.claude/scripts/capped.sh"
readonly EXIT_SETUP=3
die() {
echo "devstats: $*" >&2
exit "$EXIT_SETUP"
}
# Install every missing tool first, then re-check, so one run installs both.
ensure_tools() {
local pair tool pkg
for pair in python3:python git:git; do
tool="${pair%%:*}" pkg="${pair#*:}"
if ! command -v "$tool" >/dev/null; then
sudo pacman -S --needed "$pkg" || die "pacman could not install $pkg"
fi
done
for tool in python3 git; do
command -v "$tool" >/dev/null || die "$tool still missing after install"
done
}
# devstats needs datetime.UTC (3.11+); it has no third-party dependencies.
check_python() {
local ver major minor
ver="$(python3 -c 'import sys; print("%d.%d" % sys.version_info[:2])')"
major="${ver%%.*}" minor="${ver#*.}"
if ((major < 3 || (major == 3 && minor < 11))); then
die "python3 >= 3.11 required, found $ver"
fi
}
# Capped (2 GiB, 10 % CPU, idle IO) when kuhy's capped.sh exists, plain otherwise.
run_devstats() {
local cmd=(env "PYTHONPATH=$REPO_ROOT${PYTHONPATH:+:$PYTHONPATH}" python3 -P -m devstats compare "$@")
if [[ -x "$CAPPED" ]]; then
"$CAPPED" "${cmd[@]}"
else
"${cmd[@]}"
fi
}
usage() {
echo "usage: run.sh [--no-open] [compare flags...]"
echo " --no-open write $REPORT but do not open it"
echo
run_devstats --help
}
main() {
local open=1 help=0 args=() arg rc=0
for arg in "$@"; do
case "$arg" in
--no-open) open=0 ;;
-h | --help) help=1 ;;
*) args+=("$arg") ;;
esac
done
ensure_tools
check_python
if ((help)); then
usage
return 0
fi
if ((open)) && ! command -v xdg-open >/dev/null; then
die "xdg-open missing: install xdg-utils or pass --no-open"
fi
run_devstats "${args[@]}" --html "$REPORT" || rc=$?
if ((rc == 0 && open)); then
setsid -f xdg-open "$REPORT" >/dev/null 2>&1
fi
return "$rc"
}
main "$@"; exit $?

View File

@ -1,110 +0,0 @@
"""Throwaway git repos with pinned dates, under a redirected HOME/git config.
Every test that runs git goes through `isolated_git`, so neither the real
~/.gitconfig nor any hook from it can leak in, and dates are explicit so the
window maths is deterministic.
"""
from __future__ import annotations
import os
import subprocess
import sys
from dataclasses import dataclass
from pathlib import Path
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
ME = "krzysztofrudnicki0@gmail.com"
DAY = 86_400
# 2026-11-18 12:00 UTC: far from midnight in any timezone the tests run in.
NOW = 1_795_003_200
@pytest.fixture(autouse=True)
def isolated_git(tmp_path_factory: pytest.TempPathFactory, monkeypatch: pytest.MonkeyPatch) -> None:
"""Point HOME and the global git config at an empty scratch dir."""
home = tmp_path_factory.mktemp("home")
cfg = home / "gitconfig"
cfg.write_text("[user]\n\tname = T\n\temail = t@example.com\n[init]\n\tdefaultBranch = main\n")
monkeypatch.setenv("HOME", str(home))
monkeypatch.setenv("GIT_CONFIG_GLOBAL", str(cfg))
monkeypatch.setenv("GIT_CONFIG_NOSYSTEM", "1")
monkeypatch.setenv("TZ", "UTC")
def run(cwd: Path, *args: str, env: dict[str, str] | None = None) -> str:
"""Run git in `cwd` and return stdout."""
full = {**os.environ, **(env or {})}
return subprocess.run(
["git", *args], cwd=cwd, env=full, check=True, capture_output=True, text=True
).stdout.strip()
@dataclass
class Repo:
"""A scratch repository with helpers that pin author/committer dates."""
path: Path
def _env(self, ts: int, email: str) -> dict[str, str]:
date = f"@{ts} +0000"
return {
"GIT_AUTHOR_DATE": date,
"GIT_COMMITTER_DATE": date,
"GIT_AUTHOR_EMAIL": email,
"GIT_COMMITTER_EMAIL": email,
"GIT_AUTHOR_NAME": "A",
"GIT_COMMITTER_NAME": "A",
}
def commit(self, files: dict[str, str | bytes | None], ts: int, email: str = ME) -> str:
"""Write/delete `files` (None deletes) and commit them at `ts`."""
for name, content in files.items():
target = self.path / name
if content is None:
run(self.path, "rm", "-q", name)
continue
target.parent.mkdir(parents=True, exist_ok=True)
if isinstance(content, bytes):
target.write_bytes(content)
else:
target.write_text(content)
run(self.path, "add", name)
run(self.path, "commit", "-q", "--allow-empty", "-m", "c", env=self._env(ts, email))
return run(self.path, "rev-parse", "HEAD")
def rename(self, old: str, new: str, ts: int, extra: str = "") -> str:
"""`git mv old new`, optionally appending a line, committed at `ts`."""
run(self.path, "mv", old, new)
if extra:
with (self.path / new).open("a") as fh:
fh.write(extra)
run(self.path, "add", new)
run(self.path, "commit", "-q", "-m", "mv", env=self._env(ts, ME))
return run(self.path, "rev-parse", "HEAD")
def tag(self, name: str, ts: int, annotated: bool = False) -> None:
"""Create a lightweight or annotated tag dated `ts`."""
args = ["tag", "-a", "-m", name, name] if annotated else ["tag", name]
run(self.path, *args, env=self._env(ts, ME))
def lines(n: int, prefix: str = "x") -> str:
"""`n` distinct lines of text."""
return "".join(f"{prefix}{i}\n" for i in range(n))
@pytest.fixture
def make_repo(tmp_path: Path):
"""Factory: `make_repo("name", branch="main")` -> initialised Repo."""
def _make(name: str, branch: str = "main", root: Path | None = None) -> Repo:
path = (root or tmp_path / "src") / name
path.mkdir(parents=True)
run(path, "init", "-q", "-b", branch)
return Repo(path)
return _make

View File

@ -1,59 +0,0 @@
"""Window totals: buckets, active days, excluded share, tags."""
from __future__ import annotations
from devstats.aggregate import RepoData, dedup, window_totals
from devstats.numstat import Commit, FileChange
from .conftest import DAY, NOW
def commit(days_ago: float, *files: FileChange) -> Commit:
ts = int(NOW - days_ago * DAY)
return Commit(sha=f"s{days_ago}", ts=ts, email="me", files=files, author_ts=ts, subject=f"c{days_ago}")
def fc(path: str, ins: int, dels: int, binary: bool = False) -> FileChange:
return FileChange(path, ins, dels, binary=binary)
def test_window_totals_split_buckets_and_windows() -> None:
repo = RepoData(
name="r",
commits=(
commit(1, fc("a.py", 100, 20), fc("README.md", 10, 0), fc("uv.lock", 50, 20)),
commit(1.2, fc("b.py", 5, 5), fc("logo.png", 0, 0, binary=True)),
commit(40, fc("c.py", 30, 0)),
commit(400, fc("d.py", 999, 0)),
),
tags=(("t1", NOW - 2 * DAY), ("t2", NOW - 50 * DAY), ("t3", NOW - 500 * DAY), ("t4", NOW + DAY)),
)
empty = RepoData(name="e", commits=(), tags=())
w30 = window_totals([repo, empty], 30, NOW)
assert (w30.code_ins, w30.code_del, w30.net) == (105, 25, 80)
assert w30.net_with_docs == 90
assert w30.commits == 2
assert w30.active_days == 1
assert w30.tags == 1
assert w30.repos_with_tags == 1
assert w30.excluded_share == 70 / 210
w90 = window_totals([repo], 90, NOW)
assert (w90.net, w90.commits, w90.active_days, w90.tags) == (110, 3, 2, 2)
def test_empty_window_has_zero_share() -> None:
w = window_totals([], 30, NOW)
assert (w.net, w.excluded_share, w.active_days) == (0, 0.0, 0)
def test_dedup_keeps_the_larger_copy_of_rewritten_work() -> None:
small = Commit("x1", 10, "me", (fc("a.py", 1, 0),), author_ts=5, subject="s")
big = Commit("x2", 20, "me", (fc("a.py", 9, 0), fc("b.py", 1, 0)), author_ts=5, subject="s")
other = Commit("x3", 30, "me", (fc("c.py", 1, 0),), author_ts=6, subject="s")
tie = Commit("x4", 40, "me", (fc("d.py", 1, 0),), author_ts=7, subject="t")
a = RepoData("archive", (small, tie), (("t", 1), ("u", 2)))
b = RepoData("main", (big, other, tie), (("t", 1),))
got = dedup([a, b])
assert [c.sha for c in got[0].commits] == ["x4"]
assert [c.sha for c in got[1].commits] == ["x2", "x3"]
assert (got[0].tags, got[1].tags) == ((("t", 1), ("u", 2)), ())

View File

@ -1,124 +0,0 @@
"""End to end: `python -m devstats compare` over a scratch ~/src."""
from __future__ import annotations
import io
from pathlib import Path
import pytest
from devstats.cli import main
from .conftest import DAY, NOW, lines, run
@pytest.fixture
def src(make_repo, tmp_path: Path) -> Path:
"""signal-bot + a worktree, a master-only repo, a collaborator, a local main behind origin."""
bot = make_repo("signal-bot")
bot.commit({"bot.py": lines(100), "README.md": lines(40), "pnpm-lock.yaml": lines(500)}, NOW - DAY)
bot.commit({"bot.py": None}, NOW - 50 * DAY + 1) # dates out of order on purpose: kept by --since
bot.commit({"x.py": lines(10)}, NOW - 2 * DAY, email="ppolgon@gmail.com")
bot.tag("v1", NOW - DAY, annotated=True)
bot.commit({"pushed.py": lines(3)}, NOW - DAY + 60) # only origin/main has it: counted all the same
run(bot.path, "update-ref", "refs/remotes/origin/main", "HEAD")
run(bot.path, "update-ref", "refs/heads/main", "HEAD~1") # local main behind origin
run(bot.path, "worktree", "add", "-q", str(tmp_path / "src" / "sb-wt-a"), "-b", "wt")
old = make_repo("old", branch="master")
old.commit({"o.py": lines(20)}, NOW - 200 * DAY)
nob = make_repo("nobranch", branch="dev")
nob.commit({"n.py": lines(7)}, NOW - DAY)
return tmp_path / "src"
def compare(*args: str, doc: Path) -> tuple[int, str, str]:
out, err = io.StringIO(), io.StringIO()
rc = main(["compare", *args], now=NOW, out=out, err=err, doc_path=doc)
return rc, out.getvalue(), err.getvalue()
def test_compare_prints_all_windows_and_article_figures(src: Path, tmp_path: Path) -> None:
doc = tmp_path / "DOCS-comparison.md"
rc, out, err = compare("--root", str(src), doc=doc)
assert rc == 0
for needle in ("30 d", "90 d", "300 d ≈ lifetime (10 mo)", "12,000", "9,700", "4,500", "×0.67", "194",
"160", "55", "+docs", "excluded", "tags/week", "repos with ≥1 tag", "÷ 194"):
assert needle in out, needle
assert "signal-bot" not in err # no "behind its upstream" warning any more
assert "nobranch: no main/master/origin HEAD branch, skipped" in err
assert not doc.exists()
assert "signal-bot" not in out
def test_by_repo_folds_worktrees_and_write_has_no_repo_names(src: Path, tmp_path: Path) -> None:
doc = tmp_path / "DOCS-comparison.md"
rc, out, _ = compare("--root", str(src), "--by-repo", "--write", doc=doc)
assert rc == 0
assert "signal-bot" in out
assert "sb-wt" not in out
text = doc.read_text()
assert "Generated 2026-11-18" in text
assert "pnpm-lock.yaml" in text # the exclude list is printed
for name in ("signal-bot", "sb-wt", "old", "nobranch"):
assert f"| {name}" not in text
def test_origin_only_commit_is_counted_once(src: Path, tmp_path: Path) -> None:
rc, out, _ = compare("--root", str(src), "--by-repo", doc=tmp_path / "d.md")
assert rc == 0
# bot.py, its deletion and pushed.py (origin-only); the worktree adds nothing
assert "| signal-bot | 103 | 3 | 3 | 3 |" in out
def test_a_local_clone_changes_nothing_but_the_repo_list(src: Path, tmp_path: Path) -> None:
doc = tmp_path / "d.md"
_, before, _ = compare("--root", str(src), doc=doc)
run(src, "clone", "-q", "signal-bot", "bot-clone")
_, after, _ = compare("--root", str(src), doc=doc)
assert before == after
def test_email_flag_adds_the_collaborator(src: Path, tmp_path: Path) -> None:
doc = tmp_path / "d.md"
_, base, _ = compare("--root", str(src), "--by-repo", "1", doc=doc)
_, more, _ = compare("--root", str(src), "--by-repo", "1", "--email", "PPolgon@gmail.com", doc=doc)
assert base != more
def test_default_root_is_home_src(src: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("HOME", str(tmp_path))
rc, out, _ = compare(doc=tmp_path / "d.md")
assert rc == 0
assert "| 30 d" in out
def test_no_repos_is_an_error(tmp_path: Path) -> None:
rc, _, err = compare("--root", str(tmp_path / "empty"), doc=tmp_path / "d.md")
assert rc == 2
assert "no git repos" in err
def test_compare_leaves_the_walked_repos_untouched(src: Path, tmp_path: Path) -> None:
before = {p: run(p, "for-each-ref") + run(p, "status", "--porcelain") for p in src.iterdir()}
compare("--root", str(src), doc=tmp_path / "d.md")
after = {p: run(p, "for-each-ref") + run(p, "status", "--porcelain") for p in src.iterdir()}
assert before == after
assert not (src / "signal-bot" / ".git" / "FETCH_HEAD").exists()
def test_module_entry_point(monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]) -> None:
import runpy
monkeypatch.setattr("sys.argv", ["devstats", "compare", "--help"])
with pytest.raises(SystemExit) as exc:
runpy.run_module("devstats", run_name="__main__")
assert exc.value.code == 0
assert "--by-repo" in capsys.readouterr().out
def test_html_flag_writes_the_page_and_prints_its_path_last(src: Path, tmp_path: Path) -> None:
target = tmp_path / "deep" / "report.html"
rc, out, _ = compare("--root", str(src), "--html", str(target), doc=tmp_path / "d.md")
assert rc == 0
assert out.rstrip().endswith(f"report: {target}")
assert target.read_text().startswith("<!doctype html>")

View File

@ -1,31 +0,0 @@
"""Repo discovery: one level under each root, worktrees folded into their repo."""
from __future__ import annotations
from pathlib import Path
from devstats.discover import discover
from .conftest import DAY, NOW, lines, run
def test_worktrees_count_once_under_the_main_repo(make_repo, tmp_path: Path) -> None:
main = make_repo("signal-bot")
main.commit({"a.py": lines(1)}, NOW - DAY)
run(main.path, "worktree", "add", "-q", str(tmp_path / "src" / "sb-wt-a"), "-b", "wt-a")
make_repo("other")
(tmp_path / "src" / "not-a-repo").mkdir()
(tmp_path / "src" / "file.txt").write_text("x")
broken = tmp_path / "src" / "broken"
broken.mkdir()
(broken / ".git").write_text("gitdir: /nonexistent/worktree\n")
repos, warnings = discover([tmp_path / "src"])
assert [r.name for r in repos] == ["other", "signal-bot"]
assert warnings == ["broken: not a readable git repo, skipped"]
def test_a_root_that_is_itself_a_repo_and_duplicate_roots(make_repo, tmp_path: Path) -> None:
repo = make_repo("solo", root=tmp_path)
repos, _ = discover([repo.path, repo.path, tmp_path / "missing"])
assert [r.name for r in repos] == ["solo"]

View File

@ -1,72 +0,0 @@
"""The one exclude list decides what counts as code, docs or dropped churn."""
from __future__ import annotations
import pytest
from devstats.excludes import RULES, classify
@pytest.mark.parametrize(
("path", "bucket"),
[
("src/main.py", "code"),
("tests/test_main.py", "code"),
("lib/screen.dart", "code"),
("scenes/level.tscn", "code"),
("Makefile", "code"),
("package.json", "code"),
("web/tsconfig.app.json", "code"),
("requirements-dev.txt", "code"),
("native/CMakeLists.txt", "code"),
# lockfiles
("web/pnpm-lock.yaml", "excluded"),
("package-lock.json", "excluded"),
("uv.lock", "excluded"),
("app/pubspec.lock", "excluded"),
("go.sum", "excluded"),
# generated
("lib/model.g.dart", "excluded"),
("lib/model.freezed.dart", "excluded"),
("static/app.min.js", "excluded"),
("coverage.xml", "excluded"),
("icon.svg.import", "excluded"),
("player.gd.uid", "excluded"),
("android/build/reports/problems/problems-report.html", "excluded"),
("web/dist/index.js", "excluded"),
# vendored
("web/node_modules/x/index.js", "excluded"),
("addons/gut/gut.gd", "excluded"),
("game/addons/dev_tools/panel.gd", "excluded"),
("godot_dev_tools/addons/dev_tools/panel.gd", "code"),
("third_party/lib.c", "excluded"),
("vendor/pkg/a.go", "excluded"),
# data / assets
("pacman/words.txt", "excluded"),
("tools/eval/data/reference.json", "excluded"),
("assets/audio/MANIFEST.json", "excluded"),
("tests/fixtures/run.tcx", "excluded"),
("tests/fixtures/host/q.py", "code"),
("app/lib/data/repo.dart", "code"),
("app/lib/data/repo.g.dart", "excluded"),
("assets/fonts/Inter.ttf.txt", "excluded"),
("web/build/main.js", "excluded"),
("games/chips/sea.tres", "excluded"),
("report.csv", "excluded"),
# docs and translations
("README.md", "docs"),
("docs/guide.py", "docs"),
("lib/l10n/app_pl.arb", "docs"),
("public/locales/en.json", "docs"),
("LICENSE", "docs"),
# an excluded dir beats a docs file and a code keep
("node_modules/x/README.md", "excluded"),
("node_modules/x/package.json", "excluded"),
],
)
def test_classify(path: str, bucket: str) -> None:
assert classify(path) == bucket
def test_rules_use_known_buckets_only() -> None:
assert {bucket for bucket, _ in RULES} == {"code", "docs", "excluded"}

View File

@ -1,17 +0,0 @@
"""No devstats module may share a stdlib module's name.
`python -m devstats` run from inside `devstats/` puts that dir first on
sys.path, so a `devstats/html.py` replaced the stdlib `html` for every import.
"""
from __future__ import annotations
import sys
from pathlib import Path
PACKAGE = Path(__file__).resolve().parents[1]
def test_no_module_shadows_the_stdlib() -> None:
clashes = sorted(p.name for p in PACKAGE.glob("*.py") if p.stem in sys.stdlib_module_names)
assert clashes == []

View File

@ -1,81 +0,0 @@
"""Parsing `git log --numstat -z` and reading one ref set from a real repo."""
from __future__ import annotations
from devstats.numstat import FileChange, parse_log, read_commits
from .conftest import DAY, ME, NOW, lines
def test_parse_empty_input() -> None:
assert parse_log(b"") == []
def test_parse_commit_without_files_then_rename_first() -> None:
raw = (
b"\x1eaaa\x1f100\x1fMe@X.com\x1f90\x1fFix: a\x1fb\x00\n"
b"\x1ebbb\x1f200\x1fme@x.com\x1f190\x1fsecond\x00\n"
b"3\t1\t\x00old.py\x00new.py\x00-\t-\tlogo.png\x002\t0\tb.md\x00"
)
first, second = parse_log(raw)
assert first.sha == "aaa"
assert first.ts == 100
assert first.email == "me@x.com"
assert first.files == ()
assert (first.author_ts, first.subject) == (90, "Fix: a\x1fb")
assert second.identity == ("me@x.com", 190, "second")
assert second.churn == 6
assert second.files == (
FileChange("new.py", 3, 1, binary=False),
FileChange("logo.png", 0, 0, binary=True),
FileChange("b.md", 2, 0, binary=False),
)
def test_read_commits_skips_merges_and_old_commits(make_repo) -> None:
repo = make_repo("r")
repo.commit({"old.py": lines(50)}, NOW - 400 * DAY)
repo.commit({"a.py": lines(10)}, NOW - 5 * DAY)
base = repo.path
from .conftest import run
run(base, "checkout", "-q", "-b", "side")
repo.commit({"b.py": lines(4)}, NOW - 4 * DAY)
run(base, "checkout", "-q", "main")
repo.commit({"c.py": lines(2)}, NOW - 3 * DAY)
run(
base,
"merge",
"-q",
"--no-ff",
"-m",
"m",
"side",
env={"GIT_COMMITTER_DATE": f"@{NOW - 2 * DAY} +0000", "GIT_AUTHOR_DATE": f"@{NOW - 2 * DAY} +0000"},
)
repo.rename("a.py", "z.py", NOW - DAY, extra="tail\n")
got = read_commits(base, ["refs/heads/main"], NOW - 300 * DAY)
files = sorted(f.path for c in got for f in c.files)
assert files == ["a.py", "b.py", "c.py", "z.py"]
assert all(c.email == ME for c in got)
rename = next(c for c in got if any(f.path == "z.py" for f in c.files))
assert rename.files == (FileChange("z.py", 1, 0, binary=False),)
def test_read_commits_dedups_commits_reachable_from_two_refs(make_repo) -> None:
repo = make_repo("r")
repo.commit({"a.py": lines(3)}, NOW - DAY)
from .conftest import run
run(repo.path, "update-ref", "refs/remotes/origin/main", "HEAD")
got = read_commits(repo.path, ["refs/heads/main", "refs/remotes/origin/main"], NOW - 30 * DAY)
assert len(got) == 1
def test_binary_and_pure_rename_from_a_real_repo(make_repo) -> None:
repo = make_repo("r")
repo.commit({"logo.png": b"\x00\x01\x02", "a.py": lines(5)}, NOW - 2 * DAY)
repo.rename("a.py", "b.py", NOW - DAY)
got = read_commits(repo.path, ["refs/heads/main"], NOW - 30 * DAY)
assert got[0].files == (FileChange("b.py", 0, 0, binary=False),)
assert FileChange("logo.png", 0, 0, binary=True) in got[1].files

View File

@ -1,63 +0,0 @@
"""Default-branch resolution: the local branch plus its origin/ tracking ref."""
from __future__ import annotations
from devstats.refs import Ref, list_refs, resolve, tag_times
from .conftest import DAY, NOW, lines, run
def ref(ts: int, sha: str = "s", symref: str = "") -> Ref:
return Ref(sha=sha, ts=ts, symref=symref, created=ts)
def test_origin_head_names_the_branch_and_both_tips_are_logged() -> None:
refs = {
"refs/remotes/origin/HEAD": ref(0, symref="refs/remotes/origin/trunk"),
"refs/remotes/origin/trunk": ref(NOW, sha="o"),
"refs/heads/trunk": ref(NOW - 2 * DAY - DAY // 2, sha="l"),
"refs/heads/main": ref(NOW),
}
got = resolve(refs)
assert got.branch == "trunk"
assert got.log_refs == ("refs/heads/trunk", "refs/remotes/origin/trunk")
def test_falls_back_to_main_then_master_without_origin() -> None:
assert resolve({"refs/heads/main": ref(1)}).log_refs == ("refs/heads/main",)
got = resolve({"refs/heads/master": ref(1), "refs/heads/dev": ref(2)})
assert (got.branch, got.log_refs) == ("master", ("refs/heads/master",))
def test_origin_only_branch_is_not_counted() -> None:
got = resolve({"refs/remotes/origin/HEAD": ref(0, symref="refs/remotes/origin/main"),
"refs/remotes/origin/main": ref(1)})
assert (got.branch, got.log_refs) == (None, ())
def test_no_default_branch() -> None:
got = resolve({"refs/heads/dev": ref(1)})
assert got.branch is None
assert got.log_refs == ()
def test_equal_tips_log_once_any_difference_logs_both() -> None:
same = {"refs/heads/main": ref(5, sha="a"), "refs/remotes/origin/main": ref(5, sha="a")}
ahead = {"refs/heads/main": ref(9, sha="a"), "refs/remotes/origin/main": ref(5, sha="b")}
assert resolve(same).log_refs == ("refs/heads/main",)
assert resolve(ahead).log_refs == ("refs/heads/main", "refs/remotes/origin/main")
def test_list_refs_reads_branches_remotes_and_tags(make_repo) -> None:
repo = make_repo("r")
repo.commit({"a.py": lines(1)}, NOW - 10 * DAY)
repo.tag("v1", NOW - 9 * DAY, annotated=True)
repo.tag("light", NOW - 8 * DAY)
run(repo.path, "update-ref", "refs/remotes/origin/main", "HEAD")
run(repo.path, "symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/main")
refs = list_refs(repo.path)
assert refs["refs/remotes/origin/HEAD"].symref == "refs/remotes/origin/main"
assert refs["refs/heads/main"].ts == NOW - 10 * DAY
# annotated: tagger date; lightweight: the commit's date
assert sorted(ts for _, ts in tag_times(refs)) == [NOW - 10 * DAY, NOW - 9 * DAY]
assert refs["refs/tags/light"].sha in dict(tag_times(refs))

View File

@ -1,52 +0,0 @@
"""The static report page: chart above tables, cells identical to the terminal's."""
from __future__ import annotations
import re
from html import unescape
from devstats.aggregate import Window
from devstats.report_html import CMDR, KUHY, chart, page
from devstats.render import report
def window(days: int, net: int) -> Window:
return Window(days=days, code_ins=max(net, 0), code_del=max(-net, 0), docs_ins=5, docs_del=1,
excluded_lines=10, all_lines=100, active_days=3, commits=7, tags=2, repos_with_tags=1)
WINDOWS = [window(30, 3000), window(90, 900), window(300, 30)]
def md_cells(text: str) -> list[str]:
"""Body cells of every markdown table (header and separator rows skipped)."""
cells = []
for block in text.split("## ")[1:]:
rows = [ln for ln in block.splitlines() if ln.startswith("|")][2:]
cells += [c.strip() for r in rows for c in r.strip("|").split("|")]
return cells
def test_page_cells_match_the_terminal_tables() -> None:
html = page(WINDOWS, "2026-11-27")
tds = [unescape(c) for c in re.findall(r"<td>(.*?)</td>", html)]
assert tds == md_cells(report(WINDOWS))
assert "<title>devstats 2026-11-27</title>" in html
def test_chart_comes_before_the_tables_and_names_both_series() -> None:
html = page(WINDOWS, "d")
assert html.index('class="chart"') < html.index("<table")
assert "</i>kuhy</span>" in html and "</i>Cmdr</span>" in html
assert html.count(f'background:{KUHY}" title=') == 6
assert html.count(f'background:{CMDR}" title=') == 6
assert 'title="kuhy 30 d · raw: 100"' in html
assert 'title="Cmdr 300 d · ×0.67: 3,015"' in html
assert 'style="width:82.0%;background:#398FC0" title="Cmdr 30 d · raw: 12,000"' in html
def test_zero_or_negative_net_draws_no_bar_but_keeps_the_value() -> None:
html = chart([window(30, 0), window(90, -900), window(300, 0)])
assert f"background:{KUHY}\" title=" not in html
assert "<span>-10</span>" in html # -900 / 90 d, printed as is
assert html.count(f'background:{CMDR}" title=') == 6

View File

@ -1,138 +0,0 @@
"""`devstats/run.sh`: tool setup, the compare run, the HTML report and its opener.
The autouse `isolated_git` fixture points HOME at a scratch dir, so the report
lands under it, `~/.claude/scripts/capped.sh` is absent (uncapped run) and the
real ~/data/devstats is never touched. Every run passes `--no-open` or puts a
recording `xdg-open` first on PATH, so nothing opens on kuhy's display.
"""
from __future__ import annotations
import os
import shutil
import subprocess
import time
from pathlib import Path
import pytest
from .conftest import DAY, lines
RUN_SH = Path(__file__).resolve().parents[1] / "run.sh"
# What run.sh needs besides python3 and git, for the stripped-PATH cases.
BASE_TOOLS = ("bash", "realpath", "dirname", "mkdir", "cat", "setsid", "env")
def run_sh(*args: str, path: str | None = None, cwd: Path | str = "/") -> subprocess.CompletedProcess[str]:
"""Run run.sh from an unrelated cwd (or `cwd`), optionally with a replaced PATH."""
env = dict(os.environ)
if path is not None:
env["PATH"] = path
return subprocess.run([str(RUN_SH), *args], cwd=cwd, env=env, capture_output=True, text=True,
check=False, timeout=50)
def report_path() -> Path:
return Path(os.environ["HOME"]) / "data" / "devstats" / "report.html"
@pytest.fixture
def src(make_repo, tmp_path: Path) -> Path:
"""One repo with a fresh commit by kuhy's address."""
repo = make_repo("app")
repo.commit({"app.py": lines(30)}, int(time.time()) - DAY)
return tmp_path / "src"
def test_run_prints_tables_writes_report_and_no_warnings(src: Path) -> None:
proc = run_sh("--no-open", "--root", str(src))
assert proc.returncode == 0, proc.stderr
assert "## LoC per calendar day vs Cmdr" in proc.stdout
assert "| 30 d | raw | 1 |" in proc.stdout # 30 lines / 30 days
assert proc.stdout.rstrip().endswith(f"report: {report_path()}")
assert "warning:" not in proc.stderr
page = report_path().read_text()
assert page.startswith("<!doctype html>")
assert 'class="chart"' in page
def test_run_from_inside_the_package_dir(src: Path) -> None:
"""`python -m` from devstats/ must not let a package module shadow the stdlib."""
proc = run_sh("--no-open", "--root", str(src), cwd=RUN_SH.parent)
assert proc.returncode == 0, proc.stderr
assert report_path().read_text().startswith("<!doctype html>")
def test_empty_root_exits_2_and_writes_no_report(tmp_path: Path) -> None:
empty = tmp_path / "empty"
empty.mkdir()
proc = run_sh("--no-open", "--root", str(empty))
assert proc.returncode == 2
assert f"devstats: no git repos under {empty}" in proc.stderr
assert not report_path().exists()
def test_help_lists_own_and_compare_flags() -> None:
proc = run_sh("--help")
assert proc.returncode == 0
for flag in ("--no-open", "--root", "--email", "--by-repo", "--write"):
assert flag in proc.stdout, flag
def _recorder(bindir: Path, name: str, log: Path) -> None:
"""A fake `name` that appends its argv to `log` and exits 0."""
exe = bindir / name
exe.write_text(f'#!/bin/bash\necho "$*" >> "{log}"\n')
exe.chmod(0o755)
def _wait_for(path: Path) -> str:
"""The detached opener writes its log a moment after run.sh exits."""
deadline = time.monotonic() + 5
while not path.exists() and time.monotonic() < deadline:
time.sleep(0.05)
return path.read_text() if path.exists() else ""
def test_opens_report_only_without_no_open(src: Path, tmp_path: Path) -> None:
bindir, log = tmp_path / "bin", tmp_path / "xdg-open.log"
bindir.mkdir()
_recorder(bindir, "xdg-open", log)
path = f"{bindir}:{os.environ['PATH']}"
assert run_sh("--no-open", "--root", str(src), path=path).returncode == 0
assert run_sh("--root", str(tmp_path / "nothing"), path=path).returncode == 2
time.sleep(0.3)
assert not log.exists()
assert run_sh("--root", str(src), path=path).returncode == 0
assert _wait_for(log) == f"{report_path()}\n"
def _stripped_path(tmp_path: Path) -> Path:
"""A PATH dir holding only BASE_TOOLS: no python3, no git."""
bindir = tmp_path / "shim"
bindir.mkdir()
for tool in BASE_TOOLS:
found = shutil.which(tool)
assert found, tool
(bindir / tool).symlink_to(found)
return bindir
def test_missing_tools_are_installed_with_pacman(tmp_path: Path) -> None:
bindir, log = _stripped_path(tmp_path), tmp_path / "sudo.log"
_recorder(bindir, "sudo", log)
proc = run_sh("--no-open", path=str(bindir))
assert log.read_text().splitlines() == ["pacman -S --needed python", "pacman -S --needed git"]
assert proc.returncode == 3
assert "devstats: python3 still missing after install" in proc.stderr
def test_old_python_is_refused(tmp_path: Path) -> None:
bindir = _stripped_path(tmp_path)
(bindir / "git").symlink_to(shutil.which("git") or "git")
fake = bindir / "python3"
fake.write_text("#!/bin/bash\necho 3.10\n")
fake.chmod(0o755)
proc = run_sh("--no-open", path=str(bindir))
assert proc.returncode == 3
assert "devstats: python3 >= 3.11 required, found 3.10" in proc.stderr

View File

@ -31,6 +31,10 @@ repos:
- id: check-merge-conflict
- id: detect-private-key
- id: debug-statements
- id: name-tests-test
args: [--pytest-test-first]
# Shared test helpers (rows, fixtures) are _private modules, not tests.
exclude: ^earned_time/earned_time/tests/_[a-z_]+\.py$
- id: check-ast
- id: mixed-line-ending
args: [--fix=lf]
@ -38,6 +42,11 @@ 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
- id: subproject-scope
name: subproject scope regex still matches
entry: scripts/check_subproject_scope.sh earned_time
@ -60,16 +69,81 @@ repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.17.2
hooks:
- id: ruff
args: [--fix, --unsafe-fixes, --exit-non-zero-on-fix, --show-fixes]
types_or: [python, pyi]
- id: ruff-format
types_or: [python, pyi]
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.13.0
hooks:
- id: mypy
args:
- --ignore-missing-imports
- --no-error-summary
- --disable-error-code=no-untyped-def
- --disable-error-code=no-untyped-call
- --disable-error-code=var-annotated
- --disable-error-code=no-any-unimported
- --disable-error-code=type-arg
- --disable-error-code=no-any-return
- --disable-error-code=misc
- --disable-error-code=unused-ignore
- --disable-error-code=unreachable
- --disable-error-code=assignment
- --disable-error-code=no-redef
- --disable-error-code=attr-defined
- --disable-error-code=arg-type
- --disable-error-code=union-attr
- --disable-error-code=call-overload
- --disable-error-code=return-value
- --disable-error-code=redundant-cast
- --disable-error-code=empty-body
- --disable-error-code=list-item
- repo: https://github.com/pylint-dev/pylint
rev: v4.1.4
hooks:
- id: pylint
args:
- --rcfile=earned_time/pyproject.toml
- --fail-under=10
# One process: with --jobs>1 pylint pickles its AST via dill, which
# dies on Python 3.15 (code objects lost co_lnotab), 2026-11-16.
- --jobs=1
additional_dependencies:
- pytest
- repo: https://github.com/PyCQA/bandit
rev: 1.9.4
hooks:
- id: bandit
args:
- -c
- earned_time/pyproject.toml
- --severity-level=high
- --confidence-level=medium
- --skip=B113
additional_dependencies: ["bandit[toml]"]
exclude: ^(earned_time/earned_time/tests/|.*test.*\.py$)
- repo: local
hooks:
- id: pytest
name: pytest
- id: pytest-coverage
name: pytest with coverage enforcement
entry: scripts/run_subproject_tests.sh earned_time
language: script
types: [python]
pass_filenames: false
require_serial: true
stages: [pre-push]
- repo: https://github.com/codespell-project/codespell
rev: v2.3.0
hooks:
- id: codespell
args:
- --skip=*.json,*.lock,.git,__pycache__,.venv
# `checkin` is a timer event name on the wire, not a typo.
- --ignore-words-list=checkin

View File

@ -1,129 +0,0 @@
# Progress: partial pay (0.24.0)
kuhy's rule (2026-11-22): a gate pays its bonus in proportion to progress, in
equal slices, nothing held back. Half the pages is half the bonus. It covers the
shutdown bonus, its gaming twin and sick days.
earned_time cannot derive a gate's plan, so the gate signs a fact, "done N of
target M for day D", and earned_time only reads it. A day with no such row
resolves exactly as 0.23.0 did, for every registry and day.
## The row
One signed ledger row, in the gate's own ledger (`Earner.ledger`):
```json
{"kind": "progress", "entry_id": "progress:<for_day>:<done>:<target>",
"day": "<for_day>", "amount": 0, "device": "...", "created_at": "...",
"detail": {"source": "<progress source>", "for_day": "YYYY-MM-DD",
"done": "<digits>", "target": "<digits>"},
"hmac": "<entry_signature>"}
```
All four `detail` values are strings. The sources: `workout`, `leetcode`,
`reading`, `review` (`Earner.progress_source`; the tutor and the focus earner
have none and never pay by share).
## The reader
`read_progress(earner, ledger, key_file, day, *, gate_off=False)` returns a
`Progress(done, target)` or `None`. A row counts only when all of this holds:
- its HMAC verifies with the shared key;
- `kind` is `progress`;
- `detail.source` is the earner's `progress_source`;
- `detail.for_day` is the day asked;
- `done` and `target` are strings of ASCII digits 0-9, at most nine of them
(no int, float, sign, space, empty string or other script's digits);
- `target` is at least 1.
`done` is capped at `target`. Among the matching rows that verify, the last one
in file order wins, and `done` and `target` both come from that one row. A gate
can re-derive its target within a day (book-guard does), so mixing rows would
pair a stale target with a new done. The rule reads neither `created_at` nor
`device` (the workout ledger writes neither). A later row that fails any check
above is skipped, so the last good row wins; no good row is `None`. A signed
row copied to the end of the file wins as it is: the key is the trust, not the
position.
`progress_map(day, home, key_file, *, earners=None, gate_off=())` does this for
every earner of `earners_for(day)` (or the registry given) and returns
`{earner name: Progress}`, holding only earners that have a fact. Pass the names
of the earners whose gate is off today as `gate_off`, as for `done_today`.
## The pay
`resolve(answers, day, ..., progress=progress_map(...))`. A term uses its
progress only when its answer is `0` or `False`, and then pays
`full * done // target`, floored, where `full` is what a yes pays that day: the
ladder rung for shutdown (`shutdown_minutes_for`), the earner's first-unit pay
for gaming. A true answer pays full exactly as before, whatever the row says.
An answer of `None` ("could not check") and a missing answer still earn nothing,
even beside a complete row. `Term.progress` holds the fact a term was paid from
(`None` otherwise), so a view can show why. A sick day adds each term's pay
to 20:00, so a partial pays its share at rung pay, capped at the ceiling.
The focus earner already paid N/M floored; it now calls the same arithmetic
(`_share.share_minutes`), with the same floor.
## Every failure is fail-closed
`None` means "pays by today's yes/no rule", never more. Each of these is `None`:
- no row for the earner and day: the gate has said nothing;
- a bad or missing signature, or a row edited after signing: a forged claim;
- another day or another gate's source: a fact about something else;
- bad integers (typed as numbers, signed, padded, empty, too long): unreadable;
- a zero target: no plan, so no share;
- an unreadable or empty key, an unreadable or malformed ledger: logged at
warning, never raised;
- `gate_off`: the gate has no price today, so there is nothing to split;
- an earner without a `progress_source`.
A bad row among good rows is skipped, not fatal.
## The review: no row, no pay (from `REVIEW_PROGRESS_FROM`)
kuhy's rule (2026-11-22): the review top-up pays in equal slices, `bonus * done
// target`, the writer freezing the target at the day's first review. From
`REVIEW_PROGRESS_FROM` (2026-11-24, the day after the 2026-11-23 release; a rule
that lowers pay never lands on its deploy day) the review differs from the other
earners:
- a credited review (a yes) pays only by its row: `done` of `target` of 20
minutes, never more than 20; the gaming twin is 0 as ever, and a sick day adds
the same minutes on top of 20:00;
- a credited review with no row pays **0**, not the flat 20, and logs a warning;
- a row that fails verification (bad signature, edited, wrong day or source,
unreadable numbers) is no row, so it pays 0 too. This is deliberate: fail
closed, visible in the log, never a flat 20 for a row nobody can vouch for;
- a no or `None` pays 0 whatever a row says: the guard's accepted submission, not
the row, is the evidence that a review happened (`DOCS-review.md`).
Before `REVIEW_PROGRESS_FROM` the review pays as in 0.23.0 (a yes pays 20, a no
0) and ignores every progress row.
## One derivation: `term_for`
`term_for(earner, day, *, answer, progress=None) -> Term` is the only place an
earner's pay for a day is derived, and `resolve` builds every one of its terms
through it. A consumer that prices one earner (the screen-locker's live pass)
reads the row with `read_progress` and calls it; it reads `shutdown_minutes`
and `gaming_minutes` off the `Term`. **Consumers never re-derive a share**: the
review's dated rule, the ladder rung, the floor and the cap at full all live
here, and a local `full * done // target` goes stale the day a rule changes.
```python
fact = earned_time.read_progress(earner, ledger, key_file, day, gate_off=off)
pay = earned_time.term_for(earner, day, answer=answer, progress=fact).shutdown_minutes
```
`answer` is the unit count (`True`/`False` are 1/0) or `None`; `progress` is the
verified row or `None`. A test pins that the two always agree for every earner,
answer, row and day either side of `REVIEW_PROGRESS_FROM`.
## Not credits
A `progress` row has `amount` 0 and its own kind. `done_today`, `credit_units`,
`first_credit_at` and `maturity` never see it, so it cannot earn a bonus, mature
a gate or start a penalty.

View File

@ -1,31 +0,0 @@
# The tutor row contract (0.8.0)
Moved out of the README (0.24.0) to keep it under the line cap; unchanged.
**Mixed-day safe.** `credit_units` sums what
each counting row pays instead of counting rows (`_credits.row_units`, the
per-matcher reader `_match.ROW_UNITS`):
- `detail.minutes` (a positive JSON int, never a bool/float/string) is the
active minutes the row pays. A row **without** it is a 0.7.0 15-minute
block and pays 15 (`LEGACY_TUTOR_MINUTES`), so a day that mixes block rows
and minute rows sums both, and an all-block day resolves exactly as 0.7.0
did (min(15 n, 60) = 15 min(n, 4)). A row whose `minutes` is present but
invalid is refused by `tutor_match` (logged) and pays nothing anywhere.
- An `entry_id` pays once; rows repeated under one id pay the **smallest**
of their counts, so a replay or a rewrite can never raise a credit.
- What the writer ([kuhyx/tutor](https://github.com/kuhyx/tutor) `tutor/credit.py`) must guarantee: every
new row carries `detail.minutes`; one row per credited minute,
`entry_id = f"{session_id}-m{n}"` with `n` the session's n-th credited
active minute (deterministic, so a retry rewrites the same id; never the
`-b{n}` form); ids never cover overlapping minutes (no cumulative "total so
far" rows); `detail.ended_at` is when the last paid minute ended (it picks
the day, so a multi-minute row must never span local midnight); its own
daily cap sums minutes (block rows as 15) up to 60. N-minute rows (e.g.
every 5 minutes) are allowed under the same rules; each write fires
screen-locker's `earner-bonus.path`, so per-minute rows rewrite the
shutdown schedule once a minute.
Days before `TUTOR_FROM` resolve on `EARNERS` exactly as before. Consumers must
iterate `earners_for(day)`, never `EARNERS`; `resolve`/`base_for` default to
it, and ignore answers for an earner of another day's registry.

View File

@ -92,9 +92,33 @@ penalty has started, the gaming base drops by the full 60
done is 3 h / 18:50 and everything done is still 8 h / 23:00. Until then
(given `first_credits`, see below) it costs nothing: 4 h / 19:50.
**The tutor row contract (0.8.0, mixed-day safe)** — `detail.minutes`, one row per
credited minute, the legacy 15-minute block, an `entry_id` paying once and what
the writer must guarantee: [DOCS-tutor.md](DOCS-tutor.md).
**The tutor row contract (0.8.0, mixed-day safe).** `credit_units` sums what
each counting row pays instead of counting rows (`_credits.row_units`, the
per-matcher reader `_match.ROW_UNITS`):
- `detail.minutes` (a positive JSON int, never a bool/float/string) is the
active minutes the row pays. A row **without** it is a 0.7.0 15-minute
block and pays 15 (`LEGACY_TUTOR_MINUTES`), so a day that mixes block rows
and minute rows sums both, and an all-block day resolves exactly as 0.7.0
did (min(15 n, 60) = 15 min(n, 4)). A row whose `minutes` is present but
invalid is refused by `tutor_match` (logged) and pays nothing anywhere.
- An `entry_id` pays once; rows repeated under one id pay the **smallest**
of their counts, so a replay or a rewrite can never raise a credit.
- What the writer ([kuhyx/tutor](https://github.com/kuhyx/tutor) `tutor/credit.py`) must guarantee: every
new row carries `detail.minutes`; one row per credited minute,
`entry_id = f"{session_id}-m{n}"` with `n` the session's n-th credited
active minute (deterministic, so a retry rewrites the same id; never the
`-b{n}` form); ids never cover overlapping minutes (no cumulative "total so
far" rows); `detail.ended_at` is when the last paid minute ended (it picks
the day, so a multi-minute row must never span local midnight); its own
daily cap sums minutes (block rows as 15) up to 60. N-minute rows (e.g.
every 5 minutes) are allowed under the same rules; each write fires
screen-locker's `earner-bonus.path`, so per-minute rows rewrite the
shutdown schedule once a minute.
Days before `TUTOR_FROM` resolve on `EARNERS` exactly as before. Consumers must
iterate `earners_for(day)`, never `EARNERS`; `resolve`/`base_for` default to
it, and ignore answers for an earner of another day's registry.
**Gap waiver** (`ANKI_WAIVED_FROM`, 2026-10-09): no anki/automation earner.
@ -121,18 +145,6 @@ From 2026-11-23 a finished, backed coach review adds 20 shutdown minutes once a
day, capped at the ceiling; never a rung, never in the floor. The row contract
and the rules are in [DOCS-review.md](DOCS-review.md).
## Partial pay (0.24.0)
A gate signs "done N of target M for day D" and `resolve(..., progress=)` pays a
no that share of a yes (`60 * 1 // 3 = 20`), for shutdown, gaming and sick
days, from the day's last good row. A yes pays full and "could not check"
nothing, as ever; with no row anywhere every output is 0.23.0's, the review
excepted. The row, the reader and every fail-closed case are in
[DOCS-progress.md](DOCS-progress.md). The review differs from `REVIEW_PROGRESS_FROM` (2026-11-24): a credited review
pays only by its row (`20 * done // target`), and with no verified row pays 0.
One earner's pay for a day is `term_for(earner, day, *, answer, progress=None)`,
the code `resolve` itself uses: consumers never re-derive a share.
## Gate maturity (0.6.0)
How far to trust a gate, computed from its ledger by `maturity()`, is in
@ -141,7 +153,7 @@ How far to trust a gate, computed from its ledger by `maturity()`, is in
## API
- `resolve(answers, day=None, earners=None, *, first_credits=None, sick=False,
leisure=None, progress=None) -> Resolution` — the one sum. `sick_shutdown_from(paid_minutes,
leisure=None) -> Resolution` — the one sum. `sick_shutdown_from(paid_minutes,
day) -> int`. `base_for(day=None, earners=None, *, first_credits=None,
leisure=None) -> Base` — the day's floors. `gaming_base_minutes_for(day)`,
`gaming_ceiling_minutes_for(day) -> int` — the gaming base and cap.
@ -167,11 +179,6 @@ How far to trust a gate, computed from its ledger by `maturity()`, is in
`REVIEW_SOURCE`, `GUARD_LEDGER`, `ACCEPTED_LOOKBACK_DAYS`, `review_match`,
`paid_reviews`, `guard_ledger_for(ledger, earner) -> Path | None`;
`Earner.topup` and `Earner.evidence` (0.23.0).
- `progress_map(day, home, key_file, *, earners=None, gate_off=()) ->
dict[str, Progress]`, `read_progress(earner, ledger, key_file, day, *,
gate_off=False) -> Progress | None`, `Progress(done, target)`,
`Earner.progress_source`, `Term.progress`, `REVIEW_PROGRESS_FROM`,
`term_for(earner, day, *, answer, progress=None) -> Term` (0.24.0).
## The workout ledger
@ -235,7 +242,7 @@ Unbacked timer time pays 0 from 2026-11-08 (focus_project 0.10.0).
## Install
```console
pip install --user --break-system-packages --no-deps "earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.24.0#subdirectory=earned_time"
pip install --user --break-system-packages --no-deps "earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.23.0#subdirectory=earned_time"
```
The root `steam-backlog-enforcer.service` sets `HOME=/home/kuhy` and imports from

View File

@ -26,10 +26,6 @@ A consumer's whole integration::
gaming budget; shutdown is the only carrot. ``Resolution.gaming_enforced``
carries it; a consumer that applies a budget lifts the limit on ``False``.
``progress`` (0.24.0): a gate signs "done N of M"; ``progress_map(day, home,
key_file)`` reads it, ``resolve(..., progress=...)`` pays a no that share of a
yes (``DOCS-progress.md``). No row anywhere resolves exactly as 0.23.0.
``sick`` (0.11.0) only raises shutdown to at least 20:00; gaming is unchanged.
``leisure`` (0.16.0): ``None`` follows the switch file on ``day``, ``True``
prices gaming with the leisure base and cap (the shadow budget), ``False``
@ -57,7 +53,6 @@ from earned_time._ladder import (
ANKI_WAIVED_FROM,
LADDER,
LADDER_FROM,
REVIEW_PROGRESS_FROM,
SHUTDOWN_CEILING_MINUTES,
TUTOR_FROM,
TUTOR_LADDER,
@ -106,7 +101,6 @@ from earned_time._policy import (
Earner,
earner,
)
from earned_time._progress import Progress, progress_map, read_progress
from earned_time._quota import TUTOR_QUOTA_FROM, TUTOR_QUOTA_MINUTES, tutor_quota_for
from earned_time._registry import all_earners, earners_for, registries
from earned_time._resolve import Base, Resolution, Term, base_for, resolve
@ -122,7 +116,6 @@ from earned_time._review import (
paid_reviews,
review_match,
)
from earned_time._share import term_for
from earned_time._sick import SICK_SHUTDOWN_FLOOR_MINUTES, sick_shutdown_from
__all__ = [
@ -149,7 +142,6 @@ __all__ = [
"REVIEW",
"REVIEW_FROM",
"REVIEW_LEDGER",
"REVIEW_PROGRESS_FROM",
"REVIEW_SHUTDOWN_MINUTES",
"REVIEW_SOURCE",
"SHUTDOWN_BASE_MINUTES",
@ -170,7 +162,6 @@ __all__ = [
"FocusEarner",
"Level",
"Maturity",
"Progress",
"Resolution",
"Rung",
"Term",
@ -196,8 +187,6 @@ __all__ = [
"on_ladder",
"paid_reviews",
"penalty_start",
"progress_map",
"read_progress",
"real_credit",
"registries",
"resolve",
@ -205,7 +194,6 @@ __all__ = [
"shutdown_ceiling_for",
"shutdown_minutes_for",
"sick_shutdown_from",
"term_for",
"today_window",
"tutor_quota_for",
"verified",

View File

@ -1,71 +0,0 @@
# Copyright (c) 2026 Krzysztof Rudnicki
"""The floor's parts: what a penalty cuts, when it bites, the shutdown floor.
Split from :mod:`earned_time._resolve` (0.24.0) to keep both under the line
cap; :func:`earned_time.base_for` is still defined there.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
from earned_time._focus import FocusEarner
from earned_time._ladder import on_ladder, shutdown_ceiling_for
from earned_time._maturity import confirmed_start, penalty_start
from earned_time._policy import SHUTDOWN_BASE_MINUTES
if TYPE_CHECKING:
from collections.abc import Mapping
from datetime import date
from earned_time._policy import Earner
def gaming_cut(item: Earner) -> int:
"""What a penalty in force takes off the gaming base: all ``item`` can pay.
A focus earner cuts what the gates it replaced paid; it pays more (0.21.0).
"""
if isinstance(item, FocusEarner):
return item.cut_gaming_minutes
return item.max_gaming_minutes
def is_penalised(
item: Earner, day: date, first_credits: Mapping[str, date | None] | None
) -> bool:
"""Whether ``item``'s cut is in force on ``day``.
Without ``first_credits``: ``penalty_from`` alone, as in 0.5.0. With it:
:func:`penalty_start` of the earner's first real credit (``None`` -- never
paid out, or could not check -- is not penalised unless ``confirmed_on``
is set: fail closed); an earner missing from it still waits for the day
after its ``confirmed_on``.
"""
if first_credits is None:
return item.penalised_on(day)
start = (
penalty_start(item, first_credits[item.name])
if item.name in first_credits
else confirmed_start(item)
)
return start is not None and day >= start
def shutdown_floor(day: date, earners: tuple[Earner, ...], cut: list[Earner]) -> int:
"""Shutdown of a day that earned nothing; ``cut``: the penalties in force.
On the ladder: the ceiling minus the most each earner can pay (all of a
capped earner's units), so doing everything lands exactly on the ceiling
-- but only a pure bonus (no ``penalty_from``) or an earner in ``cut``: a
gate whose penalty has not started cannot lower the floor (0.6.1), nor can
a top-up (0.23.0). Before it: the old base minus the penalties in force.
"""
if on_ladder(day):
rungs = (
e for e in earners if not e.topup and (e.penalty_from is None or e in cut)
)
return shutdown_ceiling_for(day) - sum(
e.shutdown_for(e.max_units or 1, day) for e in rungs
)
return SHUTDOWN_BASE_MINUTES - sum(e.shutdown_minutes for e in cut)

View File

@ -12,7 +12,6 @@ from typing import TYPE_CHECKING, Final, Protocol
from earned_time._ladder import shutdown_units_minutes
from earned_time._match import focus_match
from earned_time._policy import Earner
from earned_time._share import share_minutes
if TYPE_CHECKING:
from collections.abc import Iterable
@ -54,9 +53,7 @@ class FocusEarner(Earner):
def gaming_for(self, units: int) -> int:
"""Gaming minutes of ``units`` focused minutes, floored."""
return share_minutes(
self.gaming_minutes, self.capped(units), self.max_units or 1
)
return self.capped(units) * self.gaming_minutes // (self.max_units or 1)
def shutdown_for(
self,
@ -65,9 +62,7 @@ class FocusEarner(Earner):
) -> int:
"""Shutdown minutes of ``units`` focused minutes, floored."""
del day # the base signature takes it; focus pay is the same every day
return share_minutes(
self.shutdown_minutes, self.capped(units), self.max_units or 1
)
return self.capped(units) * self.shutdown_minutes // (self.max_units or 1)
def _active(day: date) -> _Project | None:

View File

@ -55,11 +55,6 @@ ANKI_WAIVED_FROM: Final = date(2026, 10, 9)
# screen-locker's late-credit rule shipped (46393fa, 2026-10-17): an 18:00
# floor without it locked out a credit landing after the shutdown.
UNIFIED_FROM: Final = date(2026, 10, 18)
# From this day a credited LeetCode review with no verified progress row pays
# nothing, and with one pays ``bonus * done // target`` (0.24.0). It lowers
# pay, so it lands the day after the release (2026-11-23), never on it. Before
# it the review pays exactly as in 0.23.0, a row or not.
REVIEW_PROGRESS_FROM: Final = date(2026, 11, 24)
_SLEEP_MINUTES: Final = 8 * 60
_DAY_MINUTES: Final = 24 * 60

Some files were not shown because too many files have changed in this diff Show More