mirror of
https://github.com/kuhyx/utils.git
synced 2026-11-27 22:49:15 +01:00
Compare commits
No commits in common. "main" and "freedays-v0.4.4" have entirely different histories.
main
...
freedays-v
8
.github/workflows/shared-gates-tests.yml
vendored
8
.github/workflows/shared-gates-tests.yml
vendored
@ -72,14 +72,6 @@ jobs:
|
||||
--cov-report=term-missing \
|
||||
--cov-fail-under=100
|
||||
|
||||
# Its tests build throwaway repos with git, which the runner has.
|
||||
- name: devstats — 100% branch coverage
|
||||
run: |
|
||||
PYTHONPATH=. python -m pytest devstats/tests -q \
|
||||
--cov=devstats --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
|
||||
# /usr/bin/python3 (the deployment interpreter), hence apt's PyYAML.
|
||||
|
||||
3
.gitignore
vendored
3
.gitignore
vendored
@ -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/
|
||||
|
||||
12
CLAUDE.md
12
CLAUDE.md
@ -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: `ruff check agent_ready coverage_gaps devstats flutter_web_drive repo_contract`
|
||||
- coverage: `PYTHONPATH=. python -m pytest -q agent_ready/tests devstats/tests flutter_web_drive/tests repo_contract/tests unified-design-system/tests --cov=agent_ready --cov=devstats --cov=flutter_web_drive --cov=repo_contract --cov=conformance --cov=conformance_diff --cov-branch --cov-report=xml --cov-fail-under=100`
|
||||
- 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`.
|
||||
|
||||
@ -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.
|
||||
@ -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).
|
||||
|
||||
@ -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
|
||||
|
||||
@ -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);
|
||||
}
|
||||
|
||||
@ -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:
|
||||
|
||||
@ -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 {
|
||||
|
||||
@ -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);
|
||||
});
|
||||
});
|
||||
}
|
||||
@ -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:
|
||||
|
||||
@ -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:
|
||||
|
||||
@ -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
|
||||
|
||||
@ -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 []
|
||||
|
||||
|
||||
|
||||
@ -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)
|
||||
|
||||
@ -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,
|
||||
)
|
||||
]
|
||||
@ -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
|
||||
|
||||
@ -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
|
||||
@ -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,
|
||||
}
|
||||
|
||||
|
||||
|
||||
@ -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"
|
||||
|
||||
@ -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
|
||||
@ -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",
|
||||
)
|
||||
@ -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`
|
||||
@ -1 +0,0 @@
|
||||
"""devstats: kuhy's git output (net LoC/day, commits, tags) vs the 100x article."""
|
||||
@ -1,5 +0,0 @@
|
||||
"""`python -m devstats compare` entry point."""
|
||||
|
||||
from devstats.cli import main
|
||||
|
||||
raise SystemExit(main())
|
||||
@ -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,
|
||||
)
|
||||
@ -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
|
||||
@ -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
|
||||
@ -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
|
||||
@ -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"
|
||||
@ -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
|
||||
@ -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]
|
||||
@ -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, ())
|
||||
@ -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()
|
||||
@ -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')
|
||||
@ -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 $?
|
||||
@ -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
|
||||
@ -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)), ())
|
||||
@ -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>")
|
||||
@ -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"]
|
||||
|
||||
@ -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"}
|
||||
@ -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 == []
|
||||
@ -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
|
||||
@ -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))
|
||||
@ -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
|
||||
@ -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
|
||||
@ -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.
|
||||
@ -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.
|
||||
@ -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
|
||||
|
||||
@ -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",
|
||||
|
||||
@ -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)
|
||||
@ -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:
|
||||
|
||||
@ -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
|
||||
|
||||
|
||||
@ -8,8 +8,8 @@ an hour; it asks :func:`earned_time.resolve` and applies the answer.
|
||||
**Penalty, then reward.** A gate with ``penalty_from`` lowers the base by
|
||||
exactly what it pays back, from that day on (never before the reward that
|
||||
pays for it: a same-day loss on 2026-09-26). Ceilings stay put. From
|
||||
``LADDER_FROM`` shutdown follows the sleep ladder (:mod:`earned_time._ladder`);
|
||||
the review top-up (0.23.0) is in :mod:`earned_time._review`.
|
||||
``LADDER_FROM`` shutdown follows the sleep ladder (:mod:`earned_time._ladder`).
|
||||
The review top-up (``REVIEW``, 0.23.0) lives in :mod:`earned_time._review`.
|
||||
|
||||
**The registry is per day** (:func:`earners_for`). From ``TUTOR_FROM`` Anki
|
||||
is retired -- neither penalised nor paid -- and the tutor (``TUTOR``) is the
|
||||
@ -61,23 +61,24 @@ class Earner:
|
||||
label: Human name, for logs and reason strings.
|
||||
gaming_minutes: Gaming time the first unit earns.
|
||||
shutdown_minutes: How much later shutdown moves for the first unit.
|
||||
kind: ``"flat"`` earns once a day from a yes/no answer; ``"counted"``
|
||||
per unit (the workout), its live credit applied by the consumer.
|
||||
kind: ``"flat"`` earns once per day from a yes/no answer;
|
||||
``"counted"`` earns per unit (the workout), and its live credit is
|
||||
applied by the consumer that counts the units.
|
||||
extra_shutdown_minutes: Each further unit, for ``"counted"`` earners.
|
||||
extra_gaming_minutes: Gaming time each further unit earns
|
||||
(``"counted"``); the workout's are 0, the tutor's 1 (per minute).
|
||||
max_units: The most units one day can pay; ``None`` is unbounded.
|
||||
penalty_from: From this day the gaming base drops by the most the
|
||||
earner can pay (:attr:`max_gaming_minutes`); ``None``: a pure bonus.
|
||||
ledger: The gate's HMAC-signed ledger, relative to the home directory;
|
||||
``None``: no shared reader, the consumer supplies the answer.
|
||||
earner can pay (:attr:`max_gaming_minutes`). ``None`` means a pure
|
||||
bonus.
|
||||
ledger: The gate's HMAC-signed ledger, relative to the home directory.
|
||||
``None`` means no shared reader: the consumer supplies the answer.
|
||||
match: Which verified ``credit`` rows count for today.
|
||||
missing_ledger_is_no: A ledger that does not exist yet is an honest
|
||||
"no" (the gate never ran), not a fault.
|
||||
confirmed_on: The day kuhy confirmed a real working session, by hand;
|
||||
``None`` keeps the gate "new" (:func:`earned_time.maturity`).
|
||||
progress_source: ``detail.source`` of the gate's signed ``progress``
|
||||
rows (0.24.0, ``_progress``); ``None``: the yes/no answer alone.
|
||||
confirmed_on: The day kuhy confirmed a real working session; set by
|
||||
hand, never derived. ``None`` keeps the gate "new"
|
||||
(:func:`earned_time.maturity`).
|
||||
|
||||
``shutdown_minutes`` and ``extra_shutdown_minutes`` are the pre-ladder
|
||||
values; from ``LADDER_FROM`` the earner's :class:`Rung` in ``LADDER``
|
||||
@ -97,7 +98,6 @@ class Earner:
|
||||
extra_gaming_minutes: int = 0
|
||||
max_units: int | None = None
|
||||
confirmed_on: date | None = None
|
||||
progress_source: str | None = None
|
||||
|
||||
@property
|
||||
def topup(self) -> bool:
|
||||
@ -106,7 +106,7 @@ class Earner:
|
||||
|
||||
@property
|
||||
def evidence(self) -> RowEvidence | None:
|
||||
"""A reader that pays from all rows instead of ``match``."""
|
||||
"""A reader that pays from all rows instead of ``match`` (``_review``)."""
|
||||
return None
|
||||
|
||||
def capped(self, units: int) -> int:
|
||||
@ -143,13 +143,13 @@ WORKOUT: Final = Earner(
|
||||
shutdown_minutes=2 * 60,
|
||||
kind="counted",
|
||||
extra_shutdown_minutes=60,
|
||||
# One signed row per credited unit (a verified TCX, or a rest day).
|
||||
# screen-locker writes one signed row per credited unit (a verified
|
||||
# RunnerUp TCX, or a rest day); ``credit_units`` counts them.
|
||||
ledger=".local/share/workout_locker/ledger.json",
|
||||
match=workout_match,
|
||||
missing_ledger_is_no=True,
|
||||
# First verified credit, read off the real ledger (0.6.0, 2026-10-09).
|
||||
confirmed_on=date(2026, 10, 1),
|
||||
progress_source="workout",
|
||||
)
|
||||
LEETCODE: Final = Earner(
|
||||
name="leetcode",
|
||||
@ -160,7 +160,6 @@ LEETCODE: Final = Earner(
|
||||
match=leetcode_match,
|
||||
# First verified credit, read off the real ledger (0.6.0, 2026-10-09).
|
||||
confirmed_on=date(2026, 8, 12),
|
||||
progress_source="leetcode",
|
||||
)
|
||||
READING: Final = Earner(
|
||||
name="reading",
|
||||
@ -173,7 +172,6 @@ READING: Final = Earner(
|
||||
missing_ledger_is_no=True,
|
||||
# First verified credit, read off the real ledger (0.6.0, 2026-10-09).
|
||||
confirmed_on=date(2026, 10, 2),
|
||||
progress_source="reading",
|
||||
)
|
||||
ANKI: Final = Earner(
|
||||
name="anki",
|
||||
@ -185,8 +183,9 @@ ANKI: Final = Earner(
|
||||
match=anki_match,
|
||||
missing_ledger_is_no=True,
|
||||
)
|
||||
# anki-guard's ``automation`` quota (its own ledger, same row shape): the Anki
|
||||
# day matcher applies unchanged. Days before ``TUTOR_FROM`` only; then TUTOR.
|
||||
# Same gate, same row shape: anki-guard's ``automation`` quota (the Automation
|
||||
# deck only) writes its own ledger, so the Anki day matcher applies unchanged.
|
||||
# Days before ``TUTOR_FROM`` only; from then on see TUTOR.
|
||||
AUTOMATION: Final = Earner(
|
||||
name="automation",
|
||||
label="Automation",
|
||||
@ -198,8 +197,9 @@ AUTOMATION: Final = Earner(
|
||||
missing_ledger_is_no=True,
|
||||
)
|
||||
|
||||
# From ``TUTOR_FROM``: the tutor pays per active minute (a 0.7.0 15-minute
|
||||
# block row counts 15), up to 60 a day; Anki's 30 is folded in.
|
||||
# From ``TUTOR_FROM``: the tutor pays per active minute (0.8.0; a 0.7.0
|
||||
# 15-minute block row counts 15), up to 60 a day; Anki's 30 is folded in.
|
||||
# Named ``automation`` until 0.9.0 (rows carry no earner name).
|
||||
TUTOR: Final = Earner(
|
||||
name="tutor",
|
||||
label="Tutor",
|
||||
@ -214,8 +214,9 @@ TUTOR: Final = Earner(
|
||||
ledger=".local/share/tutor/ledger.json",
|
||||
match=tutor_match,
|
||||
missing_ledger_is_no=True,
|
||||
# Confirmed 2026-10-10 before any block paid; dated a day early so the -60
|
||||
# penalty applies on TUTOR_FROM itself (it starts at confirmed_on + 1).
|
||||
# Confirmed by kuhy on 2026-10-10 before any block had paid out, dated the
|
||||
# day before so the -60 gaming penalty applies on TUTOR_FROM itself
|
||||
# (penalty starts at confirmed_on + 1).
|
||||
confirmed_on=date(2026, 10, 9),
|
||||
)
|
||||
|
||||
|
||||
@ -1,140 +0,0 @@
|
||||
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||
"""The signed progress fact (0.24.0): "done N of target M for day D".
|
||||
|
||||
earned_time cannot derive a gate's plan, so each gate signs the fact in its own
|
||||
ledger and this module only reads it (DOCS-progress.md). The row::
|
||||
|
||||
{"kind": "progress", "entry_id": "progress:<day>:<done>:<target>",
|
||||
"day": "<day>", "amount": 0, "device": ..., "created_at": ...,
|
||||
"detail": {"source": <progress source>, "for_day": "YYYY-MM-DD",
|
||||
"done": "<digits>", "target": "<digits>"}, "hmac": ...}
|
||||
|
||||
**Fail closed.** Everything but a verified, well-formed, same-day row is
|
||||
``None``, and ``None`` means "pays by today's yes/no rule", never more.
|
||||
Unreadable inputs are logged at warning; nothing here raises.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING, Final
|
||||
|
||||
from earned_time._ledger import read_key, read_rows, verified
|
||||
from earned_time._registry import earners_for
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Container
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
from earned_time._policy import Earner
|
||||
|
||||
_KIND: Final = "progress"
|
||||
# Digits a count may have: far beyond any real plan, below int()'s own limit.
|
||||
_MAX_DIGITS: Final = 9
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Progress:
|
||||
"""``done`` units of a ``target``-unit plan, as the gate signed it."""
|
||||
|
||||
done: int
|
||||
target: int
|
||||
|
||||
|
||||
def _count(raw: object) -> int | None:
|
||||
"""A count from ASCII digits only (never an int, float, sign or space)."""
|
||||
if not (isinstance(raw, str) and raw.isascii() and raw.isdigit()):
|
||||
return None
|
||||
return int(raw) if len(raw) <= _MAX_DIGITS else None
|
||||
|
||||
|
||||
def _fact(row: dict[str, object], source: str, day: date) -> Progress | None:
|
||||
"""One row's fact, if it is for ``source`` and ``day`` and well formed."""
|
||||
if row.get("kind") != _KIND:
|
||||
return None
|
||||
detail = row.get("detail")
|
||||
if not isinstance(detail, dict):
|
||||
return None
|
||||
if detail.get("source") != source or detail.get("for_day") != day.isoformat():
|
||||
return None
|
||||
done, target = _count(detail.get("done")), _count(detail.get("target"))
|
||||
if done is None or not target:
|
||||
return None
|
||||
return Progress(min(done, target), target)
|
||||
|
||||
|
||||
def read_progress(
|
||||
earner: Earner,
|
||||
ledger: Path,
|
||||
key_file: Path,
|
||||
day: date,
|
||||
*,
|
||||
gate_off: bool = False,
|
||||
) -> Progress | None:
|
||||
"""``earner``'s signed progress for ``day``, or ``None``.
|
||||
|
||||
Of the rows that verify and match, the last one in file order wins, and
|
||||
``done`` and ``target`` both come from it. A later row that fails
|
||||
verification, is for another kind, source or day, or has unreadable numbers
|
||||
is skipped, so the last good row wins. ``None`` for: no good row, an
|
||||
unreadable ledger or key (logged), ``gate_off`` (the gate has no price
|
||||
today), or an earner with no ``progress_source``.
|
||||
"""
|
||||
source = earner.progress_source
|
||||
if gate_off or source is None:
|
||||
return None
|
||||
key = read_key(key_file)
|
||||
rows = None if key is None else read_rows(ledger, earner)
|
||||
if key is None or rows is None:
|
||||
return None
|
||||
# The last good row in file order wins, as one (done, target) pair: a gate
|
||||
# can re-derive its target within a day, so mixing rows would pair a stale
|
||||
# target with a new done. Nothing here reads created_at or device (the
|
||||
# workout ledger writes neither).
|
||||
for row in reversed(rows):
|
||||
if (
|
||||
isinstance(row, dict)
|
||||
and (f := _fact(row, source, day))
|
||||
and verified(row, key)
|
||||
):
|
||||
return f
|
||||
return None
|
||||
|
||||
|
||||
def progress_map(
|
||||
day: date,
|
||||
home: Path,
|
||||
key_file: Path,
|
||||
*,
|
||||
earners: tuple[Earner, ...] | None = None,
|
||||
gate_off: Container[str] = frozenset(),
|
||||
) -> dict[str, Progress]:
|
||||
"""Every registered earner's progress on ``day``, for ``resolve(progress=)``.
|
||||
|
||||
Args:
|
||||
day: The day; also picks the registry (:func:`earners_for`).
|
||||
home: The home the earners' ``ledger`` paths are relative to.
|
||||
key_file: The shared HMAC key.
|
||||
earners: A registry to read instead of ``earners_for(day)``.
|
||||
gate_off: Names of the earners whose gate is off today, as the consumer
|
||||
passes ``gate_off`` to ``done_today`` (they get no progress).
|
||||
|
||||
Returns:
|
||||
``{earner name: Progress}``, only for earners with a fact: empty means
|
||||
every term pays by its yes/no answer, exactly as in 0.23.0.
|
||||
"""
|
||||
found: dict[str, Progress] = {}
|
||||
for item in earners_for(day) if earners is None else earners:
|
||||
if item.ledger is None:
|
||||
continue
|
||||
fact = read_progress(
|
||||
item,
|
||||
home / item.ledger,
|
||||
key_file,
|
||||
day,
|
||||
gate_off=item.name in gate_off,
|
||||
)
|
||||
if fact is not None:
|
||||
found[item.name] = fact
|
||||
return found
|
||||
@ -14,7 +14,6 @@ if TYPE_CHECKING:
|
||||
from datetime import date
|
||||
|
||||
from earned_time._policy import Earner
|
||||
from earned_time._progress import Progress
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@ -40,15 +39,12 @@ class Term:
|
||||
"could not check" (and for no answer at all).
|
||||
gaming_minutes: Gaming minutes earned.
|
||||
shutdown_minutes: Shutdown minutes earned.
|
||||
progress: The signed progress the pay is a share of (0.24.0): set only
|
||||
when the answer was a no and a row paid; ``None`` otherwise.
|
||||
"""
|
||||
|
||||
earner: Earner
|
||||
answer: int | None
|
||||
gaming_minutes: int
|
||||
shutdown_minutes: int
|
||||
progress: Progress | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
|
||||
@ -25,21 +25,19 @@ from datetime import UTC, date, datetime
|
||||
import logging
|
||||
from typing import TYPE_CHECKING, Final
|
||||
|
||||
from earned_time._floor import gaming_cut, is_penalised, shutdown_floor
|
||||
from earned_time._focus import FocusEarner
|
||||
from earned_time._gaming import gaming_enforced
|
||||
from earned_time._ladder import shutdown_ceiling_for
|
||||
from earned_time._ladder import on_ladder, shutdown_ceiling_for
|
||||
from earned_time._leisure import base_minutes, ceiling_minutes, is_leisure
|
||||
from earned_time._maturity import confirmed_start, penalty_start
|
||||
from earned_time._policy import SHUTDOWN_BASE_MINUTES, Earner
|
||||
from earned_time._registry import all_earners, earners_for
|
||||
from earned_time._resolution import Base, Resolution, Term
|
||||
from earned_time._share import term_for
|
||||
from earned_time._sick import sick_or
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Mapping
|
||||
|
||||
from earned_time._policy import Earner
|
||||
from earned_time._progress import Progress
|
||||
|
||||
_logger: Final = logging.getLogger(__name__)
|
||||
|
||||
Answer = int | bool | None
|
||||
@ -49,6 +47,56 @@ def _today() -> date:
|
||||
return datetime.now(tz=UTC).astimezone().date()
|
||||
|
||||
|
||||
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 _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)
|
||||
|
||||
|
||||
def base_for(
|
||||
day: date | None = None,
|
||||
earners: tuple[Earner, ...] | None = None,
|
||||
@ -59,7 +107,7 @@ def base_for(
|
||||
"""The floor for ``day`` (default today) under ``earners`` (default its own).
|
||||
|
||||
Gaming: every penalty in force, the most each earner can pay, taken off
|
||||
the gaming base. Shutdown: see ``_floor.shutdown_floor`` -- the two are
|
||||
the gaming base. Shutdown: see :func:`_shutdown_floor` -- the two are
|
||||
derived separately so the ladder can never move a gaming minute.
|
||||
``first_credits`` (per earner name) delays each penalty, and the ladder
|
||||
rung, to :func:`penalty_start`; omitted, 0.5.0's ``penalty_from`` applies.
|
||||
@ -80,13 +128,20 @@ def _base(
|
||||
*,
|
||||
on: bool,
|
||||
) -> Base:
|
||||
penalised = [e for e in registry if is_penalised(e, target, first_credits)]
|
||||
penalised = [e for e in registry if _penalised(e, target, first_credits)]
|
||||
return Base(
|
||||
gaming_minutes=base_minutes(leisure=on) - sum(gaming_cut(e) for e in penalised),
|
||||
shutdown_minutes=shutdown_floor(target, registry, penalised),
|
||||
gaming_minutes=base_minutes(leisure=on)
|
||||
- sum(_gaming_cut(e) for e in penalised),
|
||||
shutdown_minutes=_shutdown_floor(target, registry, penalised),
|
||||
)
|
||||
|
||||
|
||||
def _units(answer: Answer) -> int | None:
|
||||
if answer is None:
|
||||
return None
|
||||
return max(0, int(answer))
|
||||
|
||||
|
||||
def _check_registered(
|
||||
answers: Mapping[str, Answer], registry: tuple[Earner, ...]
|
||||
) -> None:
|
||||
@ -98,25 +153,19 @@ def _check_registered(
|
||||
raise KeyError(msg)
|
||||
|
||||
|
||||
def _term(
|
||||
item: Earner,
|
||||
answers: Mapping[str, Answer],
|
||||
day: date,
|
||||
progress: Mapping[str, Progress] | None,
|
||||
) -> Term:
|
||||
"""``item``'s term on ``day``; no answer at all is logged and earns nothing.
|
||||
|
||||
The pay itself is :func:`~earned_time.term_for`, shared with every consumer.
|
||||
"""
|
||||
def _term(item: Earner, answers: Mapping[str, Answer], day: date) -> Term:
|
||||
"""``item``'s term on ``day``; no answer at all is logged and earns nothing."""
|
||||
if item.name not in answers:
|
||||
_logger.warning(
|
||||
"No answer for the %s earner; it earns nothing today", item.label
|
||||
)
|
||||
return term_for(
|
||||
item,
|
||||
day,
|
||||
answer=answers.get(item.name),
|
||||
progress=(progress or {}).get(item.name),
|
||||
units = _units(answers.get(item.name))
|
||||
count = units or 0
|
||||
return Term(
|
||||
earner=item,
|
||||
answer=units,
|
||||
gaming_minutes=item.gaming_for(count),
|
||||
shutdown_minutes=item.shutdown_for(count, day),
|
||||
)
|
||||
|
||||
|
||||
@ -128,7 +177,6 @@ def resolve(
|
||||
first_credits: Mapping[str, date | None] | None = None,
|
||||
sick: bool = False,
|
||||
leisure: bool | None = None,
|
||||
progress: Mapping[str, Progress] | None = None,
|
||||
) -> Resolution:
|
||||
"""Sum the base and every earned term, each capped at its ceiling.
|
||||
|
||||
@ -157,10 +205,6 @@ def resolve(
|
||||
shutdown are unchanged. From ``GAMING_UNLIMITED_FROM`` (0.22.0)
|
||||
``None`` is always the old base: read
|
||||
``Resolution.gaming_enforced``, the budget is not a limit.
|
||||
progress: Per earner name, its signed progress (0.24.0,
|
||||
:func:`~earned_time.progress_map`). A term uses it only when its
|
||||
answer is ``0``/``False``, and then pays that share of a yes; a
|
||||
true answer pays full and ``None`` nothing. Omitted: 0.23.0 exactly.
|
||||
|
||||
Returns:
|
||||
The resolution, with a term for every registered earner.
|
||||
@ -175,7 +219,7 @@ def resolve(
|
||||
# One switch-file read per resolve, so base and cap can never disagree.
|
||||
on = is_leisure(target, leisure=leisure)
|
||||
base = _base(target, registry, first_credits, on=on)
|
||||
terms = [_term(item, answers, target, progress) for item in registry]
|
||||
terms = [_term(item, answers, target) for item in registry]
|
||||
gaming = base.gaming_minutes + sum(t.gaming_minutes for t in terms)
|
||||
earned = min(
|
||||
shutdown_ceiling_for(target),
|
||||
|
||||
@ -243,5 +243,4 @@ REVIEW: Final = ReviewEarner(
|
||||
ledger=REVIEW_LEDGER,
|
||||
match=review_match,
|
||||
missing_ledger_is_no=True,
|
||||
progress_source="review",
|
||||
)
|
||||
|
||||
@ -1,130 +0,0 @@
|
||||
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||
"""Proportional pay (0.24.0): ``done`` of ``target`` units pays that share.
|
||||
|
||||
Equal slices, floored, nothing held back (kuhy, 2026-11-22: "50% of pages you
|
||||
get 50% of bonus"). One piece of arithmetic for every earner that pays by
|
||||
share: the focus earner's minutes and the gates' signed progress alike.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import TYPE_CHECKING, Final
|
||||
|
||||
from earned_time._ladder import REVIEW_PROGRESS_FROM, shutdown_minutes_for
|
||||
from earned_time._resolution import Term
|
||||
from earned_time._review import ReviewEarner
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from datetime import date
|
||||
|
||||
from earned_time._policy import Earner
|
||||
from earned_time._progress import Progress
|
||||
|
||||
_logger: Final = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def share_minutes(full: int, done: int, target: int) -> int:
|
||||
"""``full * done // target``, ``done`` clamped to ``[0, target]``.
|
||||
|
||||
A ``target`` below 1 has no share to pay: ``0``, never a division error.
|
||||
"""
|
||||
if target < 1:
|
||||
return 0
|
||||
return full * min(max(done, 0), target) // target
|
||||
|
||||
|
||||
def gaming_share(item: Earner, progress: Progress) -> int:
|
||||
"""The gaming minutes ``progress`` earns ``item``: a share of its first unit."""
|
||||
return share_minutes(item.gaming_for(1), progress.done, progress.target)
|
||||
|
||||
|
||||
def shutdown_share(item: Earner, progress: Progress, day: date) -> int:
|
||||
"""The shutdown minutes ``progress`` earns ``item`` on ``day``.
|
||||
|
||||
A share of what :func:`~earned_time.shutdown_minutes_for` says a yes pays
|
||||
that day, so the ladder rung (not the pre-ladder number) is what is split.
|
||||
"""
|
||||
return share_minutes(
|
||||
shutdown_minutes_for(item, day), progress.done, progress.target
|
||||
)
|
||||
|
||||
|
||||
def share_term(item: Earner, units: int | None, day: date, share: Progress) -> Term:
|
||||
"""``item``'s term on ``day`` when it is paid as a share of ``share``."""
|
||||
return Term(
|
||||
item,
|
||||
units,
|
||||
gaming_share(item, share),
|
||||
shutdown_share(item, share, day),
|
||||
share,
|
||||
)
|
||||
|
||||
|
||||
def _review_term(
|
||||
item: Earner, units: int | None, day: date, progress: Progress | None
|
||||
) -> Term:
|
||||
"""The review's term from ``REVIEW_PROGRESS_FROM``: a credited review needs a row.
|
||||
|
||||
Only a credited review (a yes) pays, and then ``bonus * done // target`` of
|
||||
the signed row, never more than the full bonus. A yes with no row pays 0:
|
||||
a row that fails verification is no row, so it pays 0 too (fail closed,
|
||||
logged). A no and ``None`` pay 0 whatever a row says, since the guard's
|
||||
accepted submission, not the row, is the evidence a review happened.
|
||||
"""
|
||||
share = progress if units else None
|
||||
if units and share is None:
|
||||
_logger.warning(
|
||||
"%s credited with no progress row on %s; it pays nothing",
|
||||
item.label,
|
||||
day,
|
||||
)
|
||||
if share is None:
|
||||
return Term(item, units, 0, 0)
|
||||
return share_term(item, units, day, share)
|
||||
|
||||
|
||||
def term_for(
|
||||
earner: Earner,
|
||||
day: date,
|
||||
*,
|
||||
answer: int | bool | None,
|
||||
progress: Progress | None = None,
|
||||
) -> Term:
|
||||
"""What ``earner`` pays on ``day``: the one derivation, for every consumer.
|
||||
|
||||
:func:`~earned_time.resolve` builds each of its terms here, so a consumer
|
||||
pricing one earner (the screen-locker's live pass) cannot disagree with it:
|
||||
consumers never re-derive a share. Read ``shutdown_minutes`` and
|
||||
``gaming_minutes`` off the result; ``Term.progress`` is the row it was
|
||||
paid from.
|
||||
|
||||
Args:
|
||||
earner: The earner (its ladder rung on ``day`` is the full pay).
|
||||
day: The day priced.
|
||||
answer: The consumer's answer: a unit count (``True``/``False`` are
|
||||
1/0), or ``None`` for "could not check", which earns nothing.
|
||||
progress: The earner's verified signed row for ``day``
|
||||
(:func:`~earned_time.read_progress`), or ``None`` for no row.
|
||||
|
||||
Returns:
|
||||
The term. A yes pays full as ever. A no pays ``full * done // target``
|
||||
of ``progress``, floored, never above full, and nothing without a row.
|
||||
The review is the exception: from ``REVIEW_PROGRESS_FROM`` only a yes
|
||||
pays, only by its row, and a yes with no row pays 0; before it the row
|
||||
is ignored (0.23.0).
|
||||
"""
|
||||
units = None if answer is None else max(0, int(answer))
|
||||
if isinstance(earner, ReviewEarner):
|
||||
if day >= REVIEW_PROGRESS_FROM:
|
||||
return _review_term(earner, units, day, progress)
|
||||
progress = None
|
||||
if progress is not None and units is not None and units < 1:
|
||||
return share_term(earner, units, day, progress)
|
||||
count = units or 0
|
||||
return Term(
|
||||
earner=earner,
|
||||
answer=units,
|
||||
gaming_minutes=earner.gaming_for(count),
|
||||
shutdown_minutes=earner.shutdown_for(count, day),
|
||||
)
|
||||
@ -1,118 +0,0 @@
|
||||
{
|
||||
"default|2026-09-25": "d5979f10258f71c6f5cd260ad0322b85a2fc6a6a37daf3f66b5e88e403ce5dc5",
|
||||
"default|2026-09-26": "dbef32ae2e44f810457a2d8610158fe28238835ecf2d090ac4bbd5a919e701e8",
|
||||
"default|2026-10-01": "4e22126dd25c1122dee871989e059f32464422b527f5fcb799a8bbb732497497",
|
||||
"default|2026-10-05": "24414c7ce713131d552e98e1416b9829412e40902e318c0a2710274940b6582f",
|
||||
"default|2026-10-06": "745a60043a5a7ad0d0542af2d7c0789298d08098e83b143889f0f902a25fb9c3",
|
||||
"default|2026-10-08": "275c28712ee1f572c527299e2bcaca45a17e2ebc72046de193f0e59667245b4b",
|
||||
"default|2026-10-09": "1035a892e1dc16b4857d455a51ecc1e9ad2544ff196e2fb2f0c923155ea9269c",
|
||||
"default|2026-10-10": "20621ebccd4ac601d85acc22f07126fe566103b5b19967116991a9289991d6b7",
|
||||
"default|2026-10-17": "590d3ec70bf86126cab0344beb8be26a0c4b6370119375095fd7c363c13f6470",
|
||||
"default|2026-10-18": "3d896c49e432f4f084da7e641a7ad6b41b62a583f587c3047a112ae4dc554372",
|
||||
"default|2026-11-01": "fa00273b89a31779a1984941eb7d982e40970be8c440e93c38bcb2117d52d36d",
|
||||
"default|2026-11-08": "82ff6c26f6d0c354852f8c3e7c0b3a28f0bc7fbd33af001b992b6c374b937ed4",
|
||||
"default|2026-11-14": "95bbfcb5bf25f9f49f8487efad5cbb52cce9282251f283f54d3266647a24e6fa",
|
||||
"default|2026-11-15": "de061cd23f3aca9e5683f7407be497bcb635d63e39c2c521206ef51874531e45",
|
||||
"default|2026-11-16": "f9f4203012c609f443a555a54a992bdb49bab735ab9cbdb5dd2038458e038283",
|
||||
"default|2026-11-17": "416630114779c76670126c8b72e9cd58f4b7b72f20c6481fbd6ac4034e9b72e4",
|
||||
"default|2026-11-18": "71d8dba9daa713f36eb39dd8cb0da68dd41b6e92fd0b26bc7ce4f9f1513daac4",
|
||||
"default|2026-11-19": "89de5b7902c05a1fe76803606d5dd427af26de0574fa9478c3741de7ac4f9f5e",
|
||||
"default|2026-11-20": "43f2bcc8ed42ee51a2709be1ca5e538d8f3aac7d390279f540f95ee17af9473e",
|
||||
"default|2026-11-21": "39fd48906c41982b4cbf1508c19680e13296e11135586cae7bb5bfd003d271da",
|
||||
"default|2026-11-22": "90442925d88982f99ac7cf13256d33d677f8e43d73d1c680a5f99b37d2ddbcb7",
|
||||
"default|2026-11-23": "6606c5fbd9b5e74431a6a9ba6b58f09ca1c71eb1c37e960d68cbd65b075617f3",
|
||||
"default|2026-11-24": "427b689f8e0931ea09254bfb518a790ddefc00fa1ce1fb13b0281f7bde6cbb47",
|
||||
"default|2026-11-25": "387960d1560514130f792581afd82e49e17e6253dc7ec7df326b664b6e910c4c",
|
||||
"default|2026-11-26": "ba5fa2369f422283795973929fef3b1c129474f565078adec2ce46dd52a085ff",
|
||||
"default|2026-11-27": "c5178b0a166b8034bb2afa9521f3b90c9714356c5cdb154e82789892da1549d7",
|
||||
"default|2026-12-25": "3bb71f9165f0d7b9939f3ee765b33b44f4dfb49b349ad501973187f421de930e",
|
||||
"default|2027-01-01": "a527db8c78abefa1713cbbd1854da5405d68eaf108094ebd00824a31bfd02507",
|
||||
"default|2027-01-02": "b19381c6d2e1ddd94d8a9e9d4f30a85962e8a3141207cfacaa860fd8a5af617b",
|
||||
"focus|2026-09-25": "d5979f10258f71c6f5cd260ad0322b85a2fc6a6a37daf3f66b5e88e403ce5dc5",
|
||||
"focus|2026-09-26": "dbef32ae2e44f810457a2d8610158fe28238835ecf2d090ac4bbd5a919e701e8",
|
||||
"focus|2026-10-01": "4e22126dd25c1122dee871989e059f32464422b527f5fcb799a8bbb732497497",
|
||||
"focus|2026-10-05": "24414c7ce713131d552e98e1416b9829412e40902e318c0a2710274940b6582f",
|
||||
"focus|2026-10-06": "745a60043a5a7ad0d0542af2d7c0789298d08098e83b143889f0f902a25fb9c3",
|
||||
"focus|2026-10-08": "275c28712ee1f572c527299e2bcaca45a17e2ebc72046de193f0e59667245b4b",
|
||||
"focus|2026-10-09": "1035a892e1dc16b4857d455a51ecc1e9ad2544ff196e2fb2f0c923155ea9269c",
|
||||
"focus|2026-10-10": "bd737f83f7fa5e4102f7569b3a7fb812eaa0bcf40962f8574c3113e340a79e70",
|
||||
"focus|2026-10-17": "c7ff06df21447e99a5b294518dfd5894daa0849eb3070ea3410a6bf2bd484111",
|
||||
"focus|2026-10-18": "123a39d01c7357dec4619727b2bf73c26b124a474dc617941846b5215bd06cc5",
|
||||
"focus|2026-11-01": "ecdc41b29f7f9080786cb381b635741d59986809dd0704f30883fa332ded4360",
|
||||
"focus|2026-11-08": "6f04e00b4d78fc09ab04f30be5be5183e8027bf8c9fcc13f59a1538bbdee2b3b",
|
||||
"focus|2026-11-14": "3a4f25853003afce725ba6fad82b70c3215f5f6b4e1c5cf8d30bc9ac56244fa0",
|
||||
"focus|2026-11-15": "16ace51d54a9061bf46774f1e68bc6645368e5a840be7e7872564dc29e6465c0",
|
||||
"focus|2026-11-16": "bf6f84c43b9151df924e256bc3428bb9bbb89d3955f53bad4805280370b09a2a",
|
||||
"focus|2026-11-17": "266ea63e52649e8c99f0303cd4b62822d9bb959f11c70b164d1c0b269a89f5ea",
|
||||
"focus|2026-11-18": "80810b3477afa7d451602bf6c069bc2b6e5899554f1860098f581051f6d6dc2a",
|
||||
"focus|2026-11-19": "db9eee4e86164768f3490ea87f3227b8a650dcc5115e8f6c2343314bbd6ce3a5",
|
||||
"focus|2026-11-20": "19ad7d5b809ff2e45b24c0210c7d646685c9603a6571f910f0164841f5602c37",
|
||||
"focus|2026-11-21": "601f04bbd20441e3e6698a34f8ae33e010f8500123a1df6870d8582f7d64e447",
|
||||
"focus|2026-11-22": "9c8817239021615b856eca46d84af0b62cf4a35285857aa959700b004ac4f45e",
|
||||
"focus|2026-11-23": "e9404c84795b66c5b17728feb99e4570820e17cbffcb4d11a081cfa4e20521d9",
|
||||
"focus|2026-11-24": "1659bf90ace7713910f941ea6a872e740f8c8130bfd886143ddee5ff5f3bb21d",
|
||||
"focus|2026-11-25": "2f0ae0b3892fd26d8c2376d0629aa2414a5d192169ff36beb4c09e879d2483de",
|
||||
"focus|2026-11-26": "a706d2f25df525a3023677de18e9e68f68bf13be3fea5b6925bb96f6e287c715",
|
||||
"focus|2026-11-27": "dc9bd93cef5acc080d61242c0b36ec8986f1e17d4db9a068cc8d24318536e00d",
|
||||
"focus|2026-12-25": "0562f87b3326ad18de00d15bbe438c331ebf86755c2f189017e86baef730af4c",
|
||||
"focus|2027-01-01": "8fb10422496f3b11deacfe4f5d126d67b02121048e2b278ac7cbce553cbd7038",
|
||||
"focus|2027-01-02": "b72518c6a21ba3894fb6ea8da831fa6866a28b38f1026936688a714fa7776da9",
|
||||
"legacy|2026-09-25": "d5979f10258f71c6f5cd260ad0322b85a2fc6a6a37daf3f66b5e88e403ce5dc5",
|
||||
"legacy|2026-09-26": "dbef32ae2e44f810457a2d8610158fe28238835ecf2d090ac4bbd5a919e701e8",
|
||||
"legacy|2026-10-01": "4e22126dd25c1122dee871989e059f32464422b527f5fcb799a8bbb732497497",
|
||||
"legacy|2026-10-05": "24414c7ce713131d552e98e1416b9829412e40902e318c0a2710274940b6582f",
|
||||
"legacy|2026-10-06": "745a60043a5a7ad0d0542af2d7c0789298d08098e83b143889f0f902a25fb9c3",
|
||||
"legacy|2026-10-08": "275c28712ee1f572c527299e2bcaca45a17e2ebc72046de193f0e59667245b4b",
|
||||
"legacy|2026-10-09": "2b5fb5c0f9bf3a4631c80ae2efb2cdc594763ec570cc094704ae2739cf3df150",
|
||||
"legacy|2026-10-10": "cbc35da122acec19a7eee1ab0e37fa70924ff39b8ded4e0b7e4d7fd8c2cbe459",
|
||||
"legacy|2026-10-17": "d687d087d85206e909b8b2deb466abf673147df23b428eeeebd38a7ae2ac59ad",
|
||||
"legacy|2026-10-18": "4514f9d56c4a811724ba9713773e13a2af5074819ad20a1c3a79261dfb21e242",
|
||||
"legacy|2026-11-01": "61a3161ddd39183f4951aae7b6918ab4e0ccf9462391a9e3c752c5adb9b081d5",
|
||||
"legacy|2026-11-08": "34e0d74573b635f080299a072fc11456fd9448ab420f2a15b8cf9b85d83434b9",
|
||||
"legacy|2026-11-14": "520bf1f006cafe0314ecb66e8ff2efcee5d333a2460c5a106c48d473c97b4b80",
|
||||
"legacy|2026-11-15": "128309ec209bea89907880b4917adaeff4349df297789adf46cdec1dd365c0f8",
|
||||
"legacy|2026-11-16": "2fe908c5f4f5e3dea92e53f88adbc5c44292b23f6166d8d2211657be543592cc",
|
||||
"legacy|2026-11-17": "68a378804b51e74f93eb8e9cea737f17bafaf4d8b3582bbb0cda1f587183a39c",
|
||||
"legacy|2026-11-18": "f8638a6b302d430813afe1500ee2d1c583deb5fb3710bca201f2551e5868b09d",
|
||||
"legacy|2026-11-19": "23f219575fcc0227a3065d972b5f5777d02867f8b7d1722f7480496c21281fcb",
|
||||
"legacy|2026-11-20": "83405fea6c8bd58a9756a027207edcd2f9cda37253a36ecda771ce375c469d9e",
|
||||
"legacy|2026-11-21": "ccefec48376ec2983f70b48eefb03bf4c7858dd5ecf89d6ea68c6caf4eebce52",
|
||||
"legacy|2026-11-22": "74fa20db1b9ad54034ae331e8e383afe49cd325c9c0c2123e41ad81188ed6704",
|
||||
"legacy|2026-11-23": "b280ae281fc74d0ff3c6cca3ac720b39f16f286711ce0558d7bd9cd666064514",
|
||||
"legacy|2026-11-24": "d10b1c62a9b3108601375b51bcb19a6171e404b4d787a724ce7819aba9dee127",
|
||||
"legacy|2026-11-25": "0dd2c361c31809bb7ad45db247bd87c11858e2baaa0c76e307f17b5799c06cc4",
|
||||
"legacy|2026-11-26": "ab64833e0624ab99018d4d947ec6a07d59f515b6f7ca71b5d82b66eeb6df60a8",
|
||||
"legacy|2026-11-27": "3f115a8b773aac85f714b36aae4fdb988d1d939a81d5c7d9474c2d0825092774",
|
||||
"legacy|2026-12-25": "351426011def5d7f18c1605ec9baa549dcce76a2c5f360f7598330b71d38313d",
|
||||
"legacy|2027-01-01": "d8a36c6bea32939787ba42144cc4e8eb2eb7837e109f5efd649f3e877f9f954e",
|
||||
"legacy|2027-01-02": "fb7b2bee44f6a2c32f38ef7b911e1cee4ca8dd6d78fba626c1724b3ab78b81ec",
|
||||
"tutor|2026-09-25": "20bef4cc33e99150b682c1d95b875c9cfd28f91ceee98e1ef535b836c3c4f52f",
|
||||
"tutor|2026-09-26": "63d8533206bd4f0bf5cbcfae1f2616415a761ec47517bd886354ec423d9833c1",
|
||||
"tutor|2026-10-01": "5e77e89e108d380d50aa0cc18cf8959c9531bb653c378f969bbebcb68e7b43cc",
|
||||
"tutor|2026-10-05": "e552a8f912ffaf3ac701bc6c43bd793a35bfe12d222e00120ac6aa77e1e81762",
|
||||
"tutor|2026-10-06": "696c340c5c86e107439f6dc3fbe61bea226f2593f31f0a5785f0822e395493e3",
|
||||
"tutor|2026-10-08": "c49cb68a23e92411738664e4010c7f7870b0e14bf7a8e56bce82a637b9ce62c5",
|
||||
"tutor|2026-10-09": "ac727597998ffca9f78fe122546f1d4e3caaa9b71161b061137b469cc536ba67",
|
||||
"tutor|2026-10-10": "20621ebccd4ac601d85acc22f07126fe566103b5b19967116991a9289991d6b7",
|
||||
"tutor|2026-10-17": "590d3ec70bf86126cab0344beb8be26a0c4b6370119375095fd7c363c13f6470",
|
||||
"tutor|2026-10-18": "3d896c49e432f4f084da7e641a7ad6b41b62a583f587c3047a112ae4dc554372",
|
||||
"tutor|2026-11-01": "fa00273b89a31779a1984941eb7d982e40970be8c440e93c38bcb2117d52d36d",
|
||||
"tutor|2026-11-08": "82ff6c26f6d0c354852f8c3e7c0b3a28f0bc7fbd33af001b992b6c374b937ed4",
|
||||
"tutor|2026-11-14": "95bbfcb5bf25f9f49f8487efad5cbb52cce9282251f283f54d3266647a24e6fa",
|
||||
"tutor|2026-11-15": "de061cd23f3aca9e5683f7407be497bcb635d63e39c2c521206ef51874531e45",
|
||||
"tutor|2026-11-16": "f9f4203012c609f443a555a54a992bdb49bab735ab9cbdb5dd2038458e038283",
|
||||
"tutor|2026-11-17": "416630114779c76670126c8b72e9cd58f4b7b72f20c6481fbd6ac4034e9b72e4",
|
||||
"tutor|2026-11-18": "71d8dba9daa713f36eb39dd8cb0da68dd41b6e92fd0b26bc7ce4f9f1513daac4",
|
||||
"tutor|2026-11-19": "89de5b7902c05a1fe76803606d5dd427af26de0574fa9478c3741de7ac4f9f5e",
|
||||
"tutor|2026-11-20": "43f2bcc8ed42ee51a2709be1ca5e538d8f3aac7d390279f540f95ee17af9473e",
|
||||
"tutor|2026-11-21": "39fd48906c41982b4cbf1508c19680e13296e11135586cae7bb5bfd003d271da",
|
||||
"tutor|2026-11-22": "90442925d88982f99ac7cf13256d33d677f8e43d73d1c680a5f99b37d2ddbcb7",
|
||||
"tutor|2026-11-23": "6679f84c03a5fe1aaf32dc17f70a2dc80a47212deb980d9d3b5179b8448007c6",
|
||||
"tutor|2026-11-24": "4959850db79e70ebe57b4fa02d278367c0da6f0acf3f9025804bdfa6912b1b6f",
|
||||
"tutor|2026-11-25": "047a58fcacabdeecf6807aa9425cd01bf10f1bf9e81787894031597647f16bd2",
|
||||
"tutor|2026-11-26": "51bfd3b993519a766dc80b970619318955f27d739b14220f59e8af060c8380a0",
|
||||
"tutor|2026-11-27": "5382d19c7635caa6b285de2820baf70df320f42764e282eb57267340afaad471",
|
||||
"tutor|2026-12-25": "786053a1c98d38984ee5a8a4d6140f6f5e0d38f53df4f1ee09ef1e9569693442",
|
||||
"tutor|2027-01-01": "af65fe00513b98a604671a3980085bbcfaffb9365e35c5594357829f671c5bc1",
|
||||
"tutor|2027-01-02": "699ab7775e270d33585fb01ede7596834a39e4aac4b2d53156e47b1fcdb99436"
|
||||
}
|
||||
@ -1,126 +0,0 @@
|
||||
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||
"""One digest per (registry, day) of everything ``resolve`` answers.
|
||||
|
||||
Standalone on purpose: it imports only ``earned_time``, so the same file runs
|
||||
in-process against the working tree and, as ``python -P _grid_dump.py`` from
|
||||
another directory, against whatever ``earned_time`` the interpreter installed
|
||||
(the 0.23.0 oracle of ``test_progress_dark``). It touches no live state: the
|
||||
leisure switch file and the focus project are stood in for.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, timedelta
|
||||
import hashlib
|
||||
import itertools
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
from tempfile import TemporaryDirectory
|
||||
from types import SimpleNamespace
|
||||
|
||||
import earned_time
|
||||
|
||||
FOCUS = SimpleNamespace(
|
||||
start=date(2026, 11, 1), daily_minutes=120, replaces=("book", "leetcode")
|
||||
)
|
||||
# Around every dated switch: the ladder, the tutor, the waiver, unified pay,
|
||||
# the focus start, no gaming budget, the review top-up, the parked leisure day.
|
||||
SPOTS = (
|
||||
date(2026, 9, 25),
|
||||
date(2026, 9, 26),
|
||||
date(2026, 10, 1),
|
||||
date(2026, 10, 5),
|
||||
date(2026, 10, 6),
|
||||
date(2026, 10, 8),
|
||||
date(2026, 10, 9),
|
||||
date(2026, 10, 10),
|
||||
date(2026, 10, 17),
|
||||
date(2026, 10, 18),
|
||||
date(2026, 11, 1),
|
||||
date(2026, 11, 8),
|
||||
date(2026, 11, 15),
|
||||
date(2026, 11, 16),
|
||||
date(2026, 11, 22),
|
||||
date(2026, 11, 23),
|
||||
date(2026, 11, 24),
|
||||
date(2026, 12, 25),
|
||||
date(2027, 1, 1),
|
||||
date(2027, 1, 2),
|
||||
)
|
||||
DAYS = tuple(
|
||||
sorted({*SPOTS, *(date(2026, 11, 14) + timedelta(days=n) for n in range(14))})
|
||||
)
|
||||
OPTIONS: tuple[int | None, ...] = (None, 0, 1, 60)
|
||||
# From this day a credited review with no progress row pays nothing, which is
|
||||
# not 0.23.0's answer (REVIEW_PROGRESS_FROM, a literal: 0.23.0 has no such name).
|
||||
# From it the review is only asked "no" and "could not check", which agree.
|
||||
REVIEW_PROGRESS_FROM = date(2026, 11, 24)
|
||||
REVIEW_OPTIONS: tuple[int | None, ...] = (None, 0)
|
||||
|
||||
|
||||
def _registry(mode: str, day: date) -> tuple[earned_time.Earner, ...]:
|
||||
if mode == "legacy":
|
||||
return earned_time.EARNERS
|
||||
if mode == "tutor":
|
||||
return earned_time.TUTOR_EARNERS
|
||||
return earned_time.earners_for(day)
|
||||
|
||||
|
||||
def _lines(mode: str, day: date, extra: dict[str, object]) -> list[str]:
|
||||
registry = _registry(mode, day)
|
||||
names = [e.name for e in registry]
|
||||
explicit = None if mode == "default" else registry
|
||||
out = [repr(earned_time.base_for(day, explicit))]
|
||||
options = [
|
||||
REVIEW_OPTIONS if name == "review" and day >= REVIEW_PROGRESS_FROM else OPTIONS
|
||||
for name in names
|
||||
]
|
||||
for values in itertools.product(*options):
|
||||
answers = dict(zip(names, values, strict=True))
|
||||
for sick, leisure in ((False, None), (True, None), (False, True)):
|
||||
res = earned_time.resolve(
|
||||
answers, day, explicit, sick=sick, leisure=leisure, **extra
|
||||
)
|
||||
terms = [
|
||||
(t.earner.name, t.answer, t.gaming_minutes, t.shutdown_minutes)
|
||||
for t in res.terms
|
||||
]
|
||||
out.append(
|
||||
repr(
|
||||
(
|
||||
res.day,
|
||||
res.base,
|
||||
terms,
|
||||
res.gaming_minutes,
|
||||
res.shutdown_minutes,
|
||||
res.sick,
|
||||
res.sick_lift_minutes,
|
||||
res.gaming_enforced,
|
||||
)
|
||||
)
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
def dump(**extra: object) -> dict[str, str]:
|
||||
"""``"mode|day"`` -> sha256 of every resolution of that registry and day.
|
||||
|
||||
``extra`` is passed to every ``resolve`` (the new ``progress=``).
|
||||
"""
|
||||
digests: dict[str, str] = {}
|
||||
with TemporaryDirectory() as tmp:
|
||||
earned_time._leisure.LEISURE_FROM_PATH = Path(tmp) / "missing"
|
||||
for mode in ("default", "legacy", "tutor", "focus"):
|
||||
sys.modules["focus_project"] = SimpleNamespace(
|
||||
active=lambda _d, on=mode == "focus": FOCUS if on else None
|
||||
)
|
||||
for day in DAYS:
|
||||
name = "default" if mode == "focus" else mode
|
||||
body = "\n".join(_lines(name, day, extra))
|
||||
digests[f"{mode}|{day}"] = hashlib.sha256(body.encode()).hexdigest()
|
||||
return digests
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.stdout.write(json.dumps(dump(), indent=0, sort_keys=True) + "\n")
|
||||
@ -1,91 +0,0 @@
|
||||
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||
"""Signed ``progress`` rows and ledger files for the partial-pay tests."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
import json
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from earned_time.tests._maturity_rows import signed
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
from earned_time import Earner
|
||||
|
||||
# A day on the unified ladder, with the review top-up registered.
|
||||
DAY = date(2026, 11, 24)
|
||||
|
||||
|
||||
def progress(
|
||||
source: str = "leetcode",
|
||||
done: object = "1",
|
||||
target: object = "3",
|
||||
day: date = DAY,
|
||||
**detail: object,
|
||||
) -> dict[str, object]:
|
||||
"""One signed progress row, exactly as the gates write it."""
|
||||
fields: dict[str, object] = {
|
||||
"source": source,
|
||||
"for_day": day.isoformat(),
|
||||
"done": done,
|
||||
"target": target,
|
||||
**detail,
|
||||
}
|
||||
return signed(
|
||||
{
|
||||
"kind": "progress",
|
||||
"entry_id": f"progress:{day.isoformat()}:{done}:{target}",
|
||||
"day": day.isoformat(),
|
||||
"amount": 0,
|
||||
"device": "pc",
|
||||
"created_at": f"{day.isoformat()}T12:00:00+00:00",
|
||||
"detail": fields,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def write(path: Path, rows: list[object]) -> Path:
|
||||
"""A ledger file at ``path`` holding ``rows``."""
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(json.dumps({"entries": rows}), encoding="utf-8")
|
||||
return path
|
||||
|
||||
|
||||
def home_ledger(home: Path, earner: Earner) -> Path:
|
||||
"""Where a consumer finds ``earner``'s ledger under ``home``."""
|
||||
return home / str(earner.ledger)
|
||||
|
||||
|
||||
def tampered(row: dict[str, object], **detail: object) -> dict[str, object]:
|
||||
"""``row`` with its detail edited after signing (the old HMAC kept)."""
|
||||
old = row["detail"]
|
||||
assert isinstance(old, dict)
|
||||
return {**row, "detail": {**old, **detail}}
|
||||
|
||||
|
||||
def bare(
|
||||
done: object = "1",
|
||||
target: object = "3",
|
||||
source: str = "workout",
|
||||
day: date = DAY,
|
||||
) -> dict[str, object]:
|
||||
"""A signed progress row with no ``created_at`` and no ``device``.
|
||||
|
||||
The workout ledger writes rows like this; the reader must accept them.
|
||||
"""
|
||||
return signed(
|
||||
{
|
||||
"kind": "progress",
|
||||
"entry_id": f"progress:{day.isoformat()}:{done}:{target}",
|
||||
"day": day.isoformat(),
|
||||
"amount": 0,
|
||||
"detail": {
|
||||
"source": source,
|
||||
"for_day": day.isoformat(),
|
||||
"done": done,
|
||||
"target": target,
|
||||
},
|
||||
}
|
||||
)
|
||||
@ -1,69 +0,0 @@
|
||||
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||
"""Dark by default: with no progress row every answer is 0.23.0's, bit for bit.
|
||||
|
||||
``_golden_0_23_0.json`` pins a digest per (registry, day) of every resolution
|
||||
over a grid of answers, sick and leisure switches, produced by 0.23.0 itself
|
||||
(``_grid_dump.py``). The live oracle re-derives it from an installed 0.23.0
|
||||
when the interpreter has one, in a subprocess so ``sys.path`` stays untouched.
|
||||
The one exception is the review from ``REVIEW_PROGRESS_FROM``: a credited
|
||||
review with no row pays nothing, so the grid asks it only no or unknown there.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
from earned_time.tests._grid_dump import dump
|
||||
|
||||
HERE = Path(__file__).parent
|
||||
GOLDEN = json.loads((HERE / "_golden_0_23_0.json").read_text(encoding="utf-8"))
|
||||
OLD = "0.23.0"
|
||||
|
||||
|
||||
def _differing(got: dict[str, str]) -> list[str]:
|
||||
return sorted(k for k in GOLDEN if got.get(k) != GOLDEN[k]) + sorted(
|
||||
set(got) - set(GOLDEN)
|
||||
)
|
||||
|
||||
|
||||
def test_no_progress_resolve_equals_the_0_23_0_result_for_every_registry() -> None:
|
||||
assert _differing(dump()) == []
|
||||
|
||||
|
||||
def test_an_empty_progress_map_resolves_as_no_map() -> None:
|
||||
assert _differing(dump(progress={})) == []
|
||||
assert _differing(dump(progress=None)) == []
|
||||
|
||||
|
||||
def test_the_installed_0_23_0_agrees_with_the_pin(tmp_path: Path) -> None:
|
||||
env = {k: v for k, v in os.environ.items() if k != "PYTHONPATH"}
|
||||
probe = subprocess.run(
|
||||
[
|
||||
sys.executable,
|
||||
"-P",
|
||||
"-c",
|
||||
"import importlib.metadata as m; print(m.version('earned-time'))",
|
||||
],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
cwd=tmp_path,
|
||||
env=env,
|
||||
)
|
||||
if probe.stdout.strip() != OLD:
|
||||
pytest.skip(f"no installed earned-time {OLD} to ask")
|
||||
oracle = subprocess.run(
|
||||
[sys.executable, "-P", str(HERE / "_grid_dump.py")],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=True,
|
||||
cwd=tmp_path,
|
||||
env=env,
|
||||
)
|
||||
assert json.loads(oracle.stdout) == GOLDEN
|
||||
@ -1,169 +0,0 @@
|
||||
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||
"""Among a day's good progress rows the last in file order wins, as one pair."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import timedelta
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import pytest
|
||||
|
||||
from earned_time import (
|
||||
LEETCODE,
|
||||
READING,
|
||||
WORKOUT,
|
||||
Progress,
|
||||
entry_signature,
|
||||
read_progress,
|
||||
)
|
||||
from earned_time.tests._maturity_rows import signed
|
||||
from earned_time.tests._progress_rows import (
|
||||
DAY,
|
||||
bare,
|
||||
progress,
|
||||
tampered,
|
||||
write,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
|
||||
Reader = Callable[..., Progress | None]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def read(tmp_path: Path, key_file: Path) -> Reader:
|
||||
"""Read LeetCode progress for ``DAY`` out of a ledger holding ``rows``."""
|
||||
|
||||
def reader(rows: list[object]) -> Progress | None:
|
||||
ledger = write(tmp_path / "ledger.json", rows)
|
||||
return read_progress(LEETCODE, ledger, key_file, DAY)
|
||||
|
||||
return reader
|
||||
|
||||
|
||||
def test_a_later_row_with_a_lower_target_wins_whole(read: Reader) -> None:
|
||||
rows = [progress(done="1", target="5"), progress(done="2", target="3")]
|
||||
assert read(rows) == Progress(2, 3)
|
||||
|
||||
|
||||
def test_a_later_row_with_a_lower_done_wins_whole(read: Reader) -> None:
|
||||
rows = [progress(done="2", target="3"), progress(done="1", target="3")]
|
||||
assert read(rows) == Progress(1, 3)
|
||||
|
||||
|
||||
def test_a_later_row_with_a_higher_pair_wins_whole(read: Reader) -> None:
|
||||
rows = [progress(done="1", target="3"), progress(done="2", target="4")]
|
||||
assert read(rows) == Progress(2, 4)
|
||||
|
||||
|
||||
def test_file_order_decides_not_the_numbers(read: Reader) -> None:
|
||||
rows = [progress(done="1", target="3"), progress(done="2", target="4")]
|
||||
assert read(rows[::-1]) == Progress(1, 3)
|
||||
|
||||
|
||||
def test_the_last_row_of_three_wins(read: Reader) -> None:
|
||||
rows = [
|
||||
progress(done="3", target="3"),
|
||||
progress(done="1", target="6"),
|
||||
progress(done="2", target="6"),
|
||||
]
|
||||
assert read(rows) == Progress(2, 6)
|
||||
|
||||
|
||||
def test_a_trailing_forged_row_is_skipped(read: Reader) -> None:
|
||||
forged = tampered(progress(done="3", target="3"), done="2")
|
||||
assert read([progress(done="1", target="3"), forged]) == Progress(1, 3)
|
||||
|
||||
|
||||
def test_a_trailing_row_with_the_wrong_key_is_skipped(read: Reader) -> None:
|
||||
row = progress(done="3", target="3")
|
||||
row["hmac"] = entry_signature(row, b"someone else")
|
||||
assert read([progress(done="1", target="3"), row]) == Progress(1, 3)
|
||||
|
||||
|
||||
def test_a_trailing_unsigned_row_is_skipped(read: Reader) -> None:
|
||||
row = progress(done="3", target="3")
|
||||
del row["hmac"]
|
||||
assert read([progress(done="1", target="3"), row]) == Progress(1, 3)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("junk", ["garbage", 7, None, [], ["x"], {}, {"kind": 1}])
|
||||
def test_a_trailing_garbage_entry_is_skipped(read: Reader, junk: object) -> None:
|
||||
assert read([progress(done="1", target="3"), junk]) == Progress(1, 3)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"bad", [("x", "3"), ("1", "x"), ("1", "0"), ("", "3"), ("1", "9" * 5000)]
|
||||
)
|
||||
def test_a_trailing_unparsable_row_is_skipped(
|
||||
read: Reader, bad: tuple[str, str]
|
||||
) -> None:
|
||||
rows = [progress(done="1", target="3"), progress(done=bad[0], target=bad[1])]
|
||||
assert read(rows) == Progress(1, 3)
|
||||
|
||||
|
||||
def test_a_trailing_credit_row_is_skipped(read: Reader) -> None:
|
||||
credit = signed({**progress(done="3", target="3"), "kind": "credit"})
|
||||
assert read([progress(done="1", target="3"), credit]) == Progress(1, 3)
|
||||
|
||||
|
||||
def test_trailing_rows_of_another_day_or_source_are_skipped(read: Reader) -> None:
|
||||
rows = [
|
||||
progress(done="1", target="3"),
|
||||
progress(done="3", target="3", day=DAY - timedelta(days=1)),
|
||||
progress(done="3", target="3", day=DAY + timedelta(days=1)),
|
||||
progress(done="3", target="3", source="reading"),
|
||||
progress(done="3", target="3", source="workout"),
|
||||
]
|
||||
assert read(rows) == Progress(1, 3)
|
||||
|
||||
|
||||
def test_a_malformed_detail_row_is_skipped(read: Reader) -> None:
|
||||
rows = [progress(done="1", target="3"), {**progress(), "detail": "x"}]
|
||||
assert read(rows) == Progress(1, 3)
|
||||
|
||||
|
||||
def test_only_bad_rows_read_as_none(read: Reader) -> None:
|
||||
rows = [progress(done="x"), progress(source="reading"), "garbage"]
|
||||
assert read(rows) is None
|
||||
|
||||
|
||||
def test_rows_without_created_at_and_device_are_accepted(
|
||||
tmp_path: Path, key_file: Path
|
||||
) -> None:
|
||||
first, last = bare(done="1", target="3"), bare(done="2", target="3")
|
||||
assert "created_at" not in last
|
||||
assert "device" not in last
|
||||
ledger = write(tmp_path / "w.json", [first, last])
|
||||
assert read_progress(WORKOUT, ledger, key_file, DAY) == Progress(2, 3)
|
||||
|
||||
|
||||
def test_the_rule_does_not_read_created_at(read: Reader) -> None:
|
||||
early = signed(
|
||||
{**bare(done="2", source="leetcode"), "created_at": "2026-11-24T23:00:00+00:00"}
|
||||
)
|
||||
late = signed(
|
||||
{**bare(done="1", source="leetcode"), "created_at": "2026-11-24T01:00:00+00:00"}
|
||||
)
|
||||
# File order, not timestamps: the later row in the file wins.
|
||||
assert read([early, late]) == Progress(1, 3)
|
||||
assert read([late, early]) == Progress(2, 3)
|
||||
|
||||
|
||||
def test_each_source_reads_its_own_last_row(tmp_path: Path, key_file: Path) -> None:
|
||||
rows = [
|
||||
bare(done="1", target="3", source="workout"),
|
||||
progress(done="2", target="4", source="reading"),
|
||||
bare(done="3", target="3", source="workout"),
|
||||
progress(done="1", target="9", source="reading"),
|
||||
]
|
||||
ledger = write(tmp_path / "mixed.json", rows)
|
||||
assert read_progress(WORKOUT, ledger, key_file, DAY) == Progress(3, 3)
|
||||
assert read_progress(READING, ledger, key_file, DAY) == Progress(1, 9)
|
||||
|
||||
|
||||
def test_the_last_good_row_is_still_capped_at_its_target(read: Reader) -> None:
|
||||
rows = [progress(done="1", target="3"), progress(done="9", target="4")]
|
||||
assert read(rows) == Progress(4, 4)
|
||||
@ -1,218 +0,0 @@
|
||||
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||
"""The progress reader: one signed fact, every other state is ``None``."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import timedelta
|
||||
from itertools import combinations
|
||||
import logging
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import pytest
|
||||
|
||||
from earned_time import (
|
||||
LEETCODE,
|
||||
READING,
|
||||
REVIEW,
|
||||
TUTOR,
|
||||
WORKOUT,
|
||||
Earner,
|
||||
Progress,
|
||||
entry_signature,
|
||||
progress_map,
|
||||
read_progress,
|
||||
)
|
||||
from earned_time.tests._maturity_rows import KEY
|
||||
from earned_time.tests._progress_rows import (
|
||||
DAY,
|
||||
home_ledger,
|
||||
progress,
|
||||
tampered,
|
||||
write,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
|
||||
Reader = Callable[..., Progress | None]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def read(tmp_path: Path, key_file: Path) -> Reader:
|
||||
"""Read LeetCode progress for ``DAY`` out of a ledger holding ``rows``."""
|
||||
|
||||
def reader(rows: list[object], *, gate_off: bool = False) -> Progress | None:
|
||||
ledger = write(tmp_path / "ledger.json", rows)
|
||||
return read_progress(LEETCODE, ledger, key_file, DAY, gate_off=gate_off)
|
||||
|
||||
return reader
|
||||
|
||||
|
||||
def test_a_signed_matching_row_reads_as_progress(read: Reader) -> None:
|
||||
assert read([progress(done="1", target="3")]) == Progress(1, 3)
|
||||
|
||||
|
||||
def test_no_row_reads_as_none(read: Reader) -> None:
|
||||
assert read([]) is None
|
||||
|
||||
|
||||
def test_a_credit_row_is_not_progress(read: Reader) -> None:
|
||||
row = {**progress(), "kind": "credit"}
|
||||
assert read([{**row, "hmac": entry_signature(row, KEY)}]) is None
|
||||
|
||||
|
||||
def test_a_wrong_day_row_reads_as_none(read: Reader) -> None:
|
||||
assert read([progress(day=DAY - timedelta(days=1))]) is None
|
||||
assert read([progress(day=DAY + timedelta(days=1))]) is None
|
||||
|
||||
|
||||
def test_another_gates_source_reads_as_none(read: Reader) -> None:
|
||||
assert read([progress(source="reading")]) is None
|
||||
|
||||
|
||||
def test_an_unsigned_row_reads_as_none(read: Reader) -> None:
|
||||
row = progress()
|
||||
del row["hmac"]
|
||||
assert read([row]) is None
|
||||
|
||||
|
||||
def test_an_edited_row_reads_as_none(read: Reader) -> None:
|
||||
assert read([tampered(progress(done="1", target="3"), done="3")]) is None
|
||||
|
||||
|
||||
def test_a_row_signed_with_another_key_reads_as_none(read: Reader) -> None:
|
||||
row = progress()
|
||||
row["hmac"] = entry_signature(row, b"someone else")
|
||||
assert read([row]) is None
|
||||
|
||||
|
||||
ARABIC_ONE = chr(0x661)
|
||||
ARABIC_THREE = chr(0x663)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"bad",
|
||||
[1, 1.0, True, None, "", " 1", "1 ", "+1", "-1", "1.0", "1e1", "0x1", ARABIC_ONE],
|
||||
)
|
||||
def test_done_must_be_ascii_digits(read: Reader, bad: object) -> None:
|
||||
assert read([progress(done=bad, target="3")]) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"bad",
|
||||
[3, 3.0, True, None, "", " 3", "3 ", "+3", "-3", "3.0", "0", "00", ARABIC_THREE],
|
||||
)
|
||||
def test_target_must_be_ascii_digits_and_positive(read: Reader, bad: object) -> None:
|
||||
assert read([progress(done="1", target=bad)]) is None
|
||||
|
||||
|
||||
def test_absurdly_long_digit_strings_read_as_none(read: Reader) -> None:
|
||||
assert read([progress(done="1", target="9" * 5000)]) is None
|
||||
|
||||
|
||||
def test_done_over_target_is_capped(read: Reader) -> None:
|
||||
assert read([progress(done="7", target="3")]) == Progress(3, 3)
|
||||
|
||||
|
||||
def test_zero_done_is_a_valid_zero(read: Reader) -> None:
|
||||
assert read([progress(done="0", target="3")]) == Progress(0, 3)
|
||||
|
||||
|
||||
def test_a_bad_row_beside_a_good_one_is_ignored(read: Reader) -> None:
|
||||
rows = [progress(done="x", target="3"), progress(done="2", target="3")]
|
||||
assert read(rows) == Progress(2, 3)
|
||||
|
||||
|
||||
def test_gate_off_ignores_progress(read: Reader) -> None:
|
||||
assert read([progress()], gate_off=True) is None
|
||||
assert read([progress()], gate_off=False) == Progress(1, 3)
|
||||
|
||||
|
||||
def test_an_earner_without_a_progress_source_reads_as_none(
|
||||
tmp_path: Path, key_file: Path
|
||||
) -> None:
|
||||
ledger = write(tmp_path / "t.json", [progress(source="tutor")])
|
||||
assert TUTOR.progress_source is None
|
||||
assert read_progress(TUTOR, ledger, key_file, DAY) is None
|
||||
|
||||
|
||||
def test_every_gate_with_a_fact_names_its_source() -> None:
|
||||
sources = {e.name: e.progress_source for e in (WORKOUT, LEETCODE, READING, REVIEW)}
|
||||
assert sources == {
|
||||
"workout": "workout",
|
||||
"leetcode": "leetcode",
|
||||
"reading": "reading",
|
||||
"review": "review",
|
||||
}
|
||||
|
||||
|
||||
def test_an_unreadable_key_reads_as_none_and_is_logged(
|
||||
tmp_path: Path, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
ledger = write(tmp_path / "ledger.json", [progress()])
|
||||
with caplog.at_level(logging.WARNING):
|
||||
assert read_progress(LEETCODE, ledger, tmp_path / "no.key", DAY) is None
|
||||
assert "integrity key" in caplog.text
|
||||
|
||||
|
||||
def test_an_unreadable_ledger_reads_as_none_and_is_logged(
|
||||
tmp_path: Path, key_file: Path, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
bad = tmp_path / "ledger.json"
|
||||
bad.write_text("not json", encoding="utf-8")
|
||||
with caplog.at_level(logging.WARNING):
|
||||
assert read_progress(LEETCODE, bad, key_file, DAY) is None
|
||||
assert "not valid JSON" in caplog.text
|
||||
|
||||
|
||||
def test_a_missing_ledger_reads_as_none(tmp_path: Path, key_file: Path) -> None:
|
||||
assert read_progress(READING, tmp_path / "gone.json", key_file, DAY) is None
|
||||
|
||||
|
||||
def test_deleting_rows_never_raises_the_share_at_one_target(read: Reader) -> None:
|
||||
rows: list[object] = [progress(done=str(n), target="5") for n in (0, 1, 2, 4, 5)]
|
||||
full = read(rows)
|
||||
assert full == Progress(5, 5)
|
||||
for size in range(len(rows) + 1):
|
||||
for kept in combinations(rows, size):
|
||||
got = read(list(kept))
|
||||
assert got is None or got.done <= full.done
|
||||
|
||||
|
||||
def test_progress_map_holds_only_earners_with_a_fact(
|
||||
tmp_path: Path, key_file: Path
|
||||
) -> None:
|
||||
write(
|
||||
home_ledger(tmp_path, WORKOUT),
|
||||
[progress(source="workout", done="1", target="2")],
|
||||
)
|
||||
write(home_ledger(tmp_path, LEETCODE), [progress(done="2", target="3")])
|
||||
found = progress_map(DAY, tmp_path, key_file)
|
||||
assert found == {"workout": Progress(1, 2), "leetcode": Progress(2, 3)}
|
||||
|
||||
|
||||
def test_progress_map_skips_a_gate_that_is_off(tmp_path: Path, key_file: Path) -> None:
|
||||
write(home_ledger(tmp_path, LEETCODE), [progress()])
|
||||
assert progress_map(DAY, tmp_path, key_file, gate_off={"leetcode"}) == {}
|
||||
|
||||
|
||||
def test_progress_map_over_an_explicit_registry(tmp_path: Path, key_file: Path) -> None:
|
||||
write(home_ledger(tmp_path, LEETCODE), [progress()])
|
||||
assert progress_map(DAY, tmp_path, key_file, earners=(WORKOUT,)) == {}
|
||||
assert progress_map(DAY, tmp_path, key_file, earners=(LEETCODE,)) == {
|
||||
"leetcode": Progress(1, 3)
|
||||
}
|
||||
|
||||
|
||||
def test_a_row_without_a_detail_object_reads_as_none(read: Reader) -> None:
|
||||
for junk in (None, "x", ["done"]):
|
||||
row = {**progress(), "detail": junk}
|
||||
assert read([{**row, "hmac": entry_signature(row, KEY)}, 7, "x"]) is None
|
||||
|
||||
|
||||
def test_progress_map_skips_an_earner_with_no_ledger(
|
||||
tmp_path: Path, key_file: Path
|
||||
) -> None:
|
||||
bare = Earner(name="bare", label="bare", gaming_minutes=1, shutdown_minutes=1)
|
||||
assert progress_map(DAY, tmp_path, key_file, earners=(bare,)) == {}
|
||||
@ -1,226 +0,0 @@
|
||||
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||
"""Partial pay: a share of the full pay for a no, never more than a yes."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime, time
|
||||
from itertools import product
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import pytest
|
||||
|
||||
from earned_time import (
|
||||
LEETCODE,
|
||||
REVIEW,
|
||||
Earner,
|
||||
FocusEarner,
|
||||
Progress,
|
||||
credit_units,
|
||||
done_today,
|
||||
maturity,
|
||||
progress_map,
|
||||
resolve,
|
||||
shutdown_minutes_for,
|
||||
)
|
||||
from earned_time._share import share_minutes
|
||||
from earned_time.tests._maturity_rows import solve
|
||||
from earned_time.tests._progress_rows import DAY, home_ledger, progress, write
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
# A day on the unified ladder: LeetCode pays 60 and shuts down 60 later.
|
||||
LADDER = date(2026, 11, 22)
|
||||
NOTHING: dict[str, int | bool | None] = {
|
||||
"workout": 0,
|
||||
"leetcode": False,
|
||||
"reading": False,
|
||||
"tutor": 0,
|
||||
}
|
||||
|
||||
|
||||
def test_sixty_times_one_over_three_is_twenty_through_resolve() -> None:
|
||||
day = resolve(NOTHING, LADDER, progress={"leetcode": Progress(1, 3)})
|
||||
term = day.term("leetcode")
|
||||
assert (term.gaming_minutes, term.shutdown_minutes) == (20, 20)
|
||||
assert day.shutdown_minutes == resolve(NOTHING, LADDER).shutdown_minutes + 20
|
||||
|
||||
|
||||
def test_a_true_answer_pays_full_whatever_the_row_says() -> None:
|
||||
answers = {**NOTHING, "leetcode": True}
|
||||
plain = resolve(answers, LADDER)
|
||||
shown = resolve(answers, LADDER, progress={"leetcode": Progress(1, 3)})
|
||||
assert shown == plain
|
||||
assert shown.term("leetcode").progress is None
|
||||
|
||||
|
||||
def test_an_answer_of_none_earns_nothing_even_with_a_full_row() -> None:
|
||||
answers = {**NOTHING, "leetcode": None}
|
||||
shown = resolve(answers, LADDER, progress={"leetcode": Progress(3, 3)})
|
||||
assert shown == resolve(answers, LADDER)
|
||||
assert shown.term("leetcode").shutdown_minutes == 0
|
||||
|
||||
|
||||
def test_a_missing_answer_earns_nothing_even_with_a_full_row() -> None:
|
||||
answers = {k: v for k, v in NOTHING.items() if k != "leetcode"}
|
||||
shown = resolve(answers, LADDER, progress={"leetcode": Progress(3, 3)})
|
||||
assert shown.term("leetcode").shutdown_minutes == 0
|
||||
|
||||
|
||||
def test_a_complete_row_with_a_no_answer_pays_in_full() -> None:
|
||||
shown = resolve(NOTHING, LADDER, progress={"leetcode": Progress(3, 3)})
|
||||
assert shown.term("leetcode").shutdown_minutes == 60
|
||||
assert shown.term("leetcode").gaming_minutes == 60
|
||||
|
||||
|
||||
def test_the_share_floors() -> None:
|
||||
shown = resolve(NOTHING, LADDER, progress={"leetcode": Progress(1, 7)})
|
||||
assert shown.term("leetcode").shutdown_minutes == 60 // 7
|
||||
|
||||
|
||||
def test_term_progress_says_why() -> None:
|
||||
shown = resolve(NOTHING, LADDER, progress={"leetcode": Progress(2, 3)})
|
||||
assert shown.term("leetcode").progress == Progress(2, 3)
|
||||
assert shown.term("leetcode").answer == 0
|
||||
assert shown.term("reading").progress is None
|
||||
|
||||
|
||||
def test_a_counted_workout_pays_a_share_of_its_rung() -> None:
|
||||
shown = resolve(NOTHING, LADDER, progress={"workout": Progress(1, 2)})
|
||||
assert shown.term("workout").shutdown_minutes == 120 // 2
|
||||
assert shown.term("workout").gaming_minutes == 120 // 2
|
||||
|
||||
|
||||
def test_a_pre_ladder_day_shares_the_old_pay() -> None:
|
||||
day = date(2026, 10, 4)
|
||||
shown = resolve(NOTHING, day, progress={"reading": Progress(1, 4)})
|
||||
assert shown.term("reading").shutdown_minutes == 60 // 4
|
||||
|
||||
|
||||
def test_the_share_uses_the_ladder_rung_not_the_old_pay() -> None:
|
||||
day = date(2026, 10, 16)
|
||||
assert shutdown_minutes_for(LEETCODE, day) == 50
|
||||
shown = resolve(NOTHING, day, progress={"leetcode": Progress(1, 2)})
|
||||
assert shown.term("leetcode").shutdown_minutes == 25
|
||||
assert shown.term("leetcode").gaming_minutes == 30
|
||||
|
||||
|
||||
def test_the_review_pays_a_share_of_its_top_up() -> None:
|
||||
half = {"review": Progress(1, 2)}
|
||||
paid = resolve({**NOTHING, "review": True}, DAY, progress=half)
|
||||
assert paid.term("review").shutdown_minutes == 10
|
||||
# The review's own rule (test_review_progress.py): a no pays nothing.
|
||||
unpaid = resolve({**NOTHING, "review": False}, DAY, progress=half)
|
||||
assert unpaid.term("review").shutdown_minutes == 0
|
||||
|
||||
|
||||
def test_a_progress_for_an_earner_not_in_the_registry_is_ignored() -> None:
|
||||
answers = {k: v for k, v in NOTHING.items() if k != "tutor"}
|
||||
got = resolve(answers, date(2026, 10, 4), progress={"tutor": Progress(1, 2)})
|
||||
assert got == resolve(answers, date(2026, 10, 4))
|
||||
|
||||
|
||||
def test_a_sick_day_pays_the_partial_on_top_of_eight_pm() -> None:
|
||||
day = resolve(NOTHING, LADDER, sick=True, progress={"leetcode": Progress(1, 3)})
|
||||
assert day.shutdown_minutes == 20 * 60 + 20
|
||||
|
||||
|
||||
def test_a_sick_day_partials_stack_and_stop_at_the_ceiling() -> None:
|
||||
both = {"leetcode": Progress(3, 3), "reading": Progress(3, 3)}
|
||||
day = resolve({**NOTHING, "workout": 1}, LADDER, sick=True, progress=both)
|
||||
assert day.shutdown_minutes == 23 * 60
|
||||
|
||||
|
||||
def test_a_sick_day_with_a_none_answer_gets_no_partial() -> None:
|
||||
answers = {**NOTHING, "leetcode": None}
|
||||
day = resolve(answers, LADDER, sick=True, progress={"leetcode": Progress(3, 3)})
|
||||
assert day.shutdown_minutes == 20 * 60
|
||||
|
||||
|
||||
@pytest.mark.parametrize("answers", [NOTHING, {**NOTHING, "leetcode": True}])
|
||||
def test_a_progress_row_never_pays_more_than_a_yes(
|
||||
answers: dict[str, int | bool | None],
|
||||
) -> None:
|
||||
yes = resolve({**NOTHING, "leetcode": True}, LADDER)
|
||||
for done, target in product(range(6), range(1, 6)):
|
||||
got = resolve(answers, LADDER, progress={"leetcode": Progress(done, target)})
|
||||
assert got.shutdown_minutes <= yes.shutdown_minutes
|
||||
assert got.gaming_minutes <= yes.gaming_minutes
|
||||
|
||||
|
||||
def test_deleting_rows_never_raises_the_pay_at_one_target(
|
||||
tmp_path: Path, key_file: Path
|
||||
) -> None:
|
||||
rows = [progress(done=str(n), target="4") for n in (0, 1, 2, 3)]
|
||||
full = _pay(tmp_path, key_file, rows)
|
||||
for mask in product((False, True), repeat=len(rows)):
|
||||
kept: list[object] = [r for r, keep in zip(rows, mask, strict=True) if keep]
|
||||
assert _pay(tmp_path, key_file, kept) <= full
|
||||
|
||||
|
||||
def _pay(tmp_path: Path, key_file: Path, rows: list[object]) -> int:
|
||||
write(home_ledger(tmp_path, LEETCODE), rows)
|
||||
found = progress_map(DAY, tmp_path, key_file)
|
||||
return resolve(NOTHING, DAY, progress=found).shutdown_minutes
|
||||
|
||||
|
||||
def test_gate_off_keeps_progress_out_of_the_pay(tmp_path: Path, key_file: Path) -> None:
|
||||
write(home_ledger(tmp_path, LEETCODE), [progress(done="2", target="3")])
|
||||
on = progress_map(DAY, tmp_path, key_file)
|
||||
off = progress_map(DAY, tmp_path, key_file, gate_off={"leetcode"})
|
||||
assert resolve(NOTHING, DAY, progress=on).term("leetcode").shutdown_minutes == 40
|
||||
assert resolve(NOTHING, DAY, progress=off).term("leetcode").shutdown_minutes == 0
|
||||
|
||||
|
||||
def test_a_progress_row_is_not_a_credit_for_maturity(
|
||||
tmp_path: Path, key_file: Path
|
||||
) -> None:
|
||||
today = date(2026, 10, 9)
|
||||
solves: list[object] = [solve(date(2026, 10, 1)), solve(date(2026, 10, 5))]
|
||||
extra = [progress(day=today, done="3", target="3"), progress(done="1")]
|
||||
bare = write(tmp_path / "bare.json", solves)
|
||||
mixed = write(tmp_path / "mixed.json", [*solves, *extra])
|
||||
assert maturity(LEETCODE, mixed, key_file, today) == maturity(
|
||||
LEETCODE, bare, key_file, today
|
||||
)
|
||||
alone = write(tmp_path / "alone.json", extra)
|
||||
seen = maturity(LEETCODE, alone, key_file, today)
|
||||
assert (seen.credit_days, seen.credit_rows, seen.first_credit) == (0, 0, None)
|
||||
|
||||
|
||||
def test_a_progress_row_is_not_a_done_answer(tmp_path: Path, key_file: Path) -> None:
|
||||
ledger = write(home_ledger(tmp_path, LEETCODE), [progress(done="3", target="3")])
|
||||
assert done_today(LEETCODE, ledger, key_file, now=_noon(DAY)) is False
|
||||
assert credit_units(LEETCODE, ledger, key_file, DAY) == 0
|
||||
|
||||
|
||||
def _noon(day: date) -> datetime:
|
||||
return datetime.combine(day, time(12)).astimezone()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("pay", [0, 1, 7, 60, 100, 120, 180, 240])
|
||||
@pytest.mark.parametrize("target", [1, 2, 3, 7, 60, 120])
|
||||
def test_the_focus_share_floors_exactly_as_before(pay: int, target: int) -> None:
|
||||
earner = FocusEarner(
|
||||
name="focus",
|
||||
label="Focus",
|
||||
gaming_minutes=pay,
|
||||
shutdown_minutes=pay,
|
||||
kind="counted",
|
||||
max_units=target,
|
||||
)
|
||||
for units in range(-2, target + 3):
|
||||
clamped = min(max(units, 0), target)
|
||||
assert earner.gaming_for(units) == clamped * pay // target
|
||||
assert earner.shutdown_for(units, DAY) == clamped * pay // target
|
||||
assert share_minutes(pay, units, target) == clamped * pay // target
|
||||
|
||||
|
||||
def test_the_share_of_a_zero_target_is_nothing() -> None:
|
||||
assert share_minutes(60, 5, 0) == 0
|
||||
assert share_minutes(60, -1, 3) == 0
|
||||
|
||||
|
||||
def test_progress_source_defaults_to_none() -> None:
|
||||
assert Earner("x", "x", 1, 1).progress_source is None
|
||||
assert REVIEW.progress_source == "review"
|
||||
@ -1,175 +0,0 @@
|
||||
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||
"""The review's partial pay: from REVIEW_PROGRESS_FROM no row means no pay."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, timedelta
|
||||
import logging
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import pytest
|
||||
|
||||
from earned_time import (
|
||||
REVIEW,
|
||||
REVIEW_FROM,
|
||||
REVIEW_PROGRESS_FROM,
|
||||
REVIEW_SHUTDOWN_MINUTES,
|
||||
Progress,
|
||||
progress_map,
|
||||
resolve,
|
||||
)
|
||||
from earned_time.tests._progress_rows import (
|
||||
home_ledger,
|
||||
progress,
|
||||
tampered,
|
||||
write,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
NOTHING: dict[str, int | bool | None] = {
|
||||
"workout": 0,
|
||||
"leetcode": False,
|
||||
"reading": False,
|
||||
"tutor": 0,
|
||||
}
|
||||
ON = date(2026, 11, 24)
|
||||
DAYS = [ON, ON + timedelta(days=1), date(2027, 1, 1)]
|
||||
Share = dict[str, Progress]
|
||||
|
||||
|
||||
def _review(
|
||||
answer: int | None,
|
||||
day: date,
|
||||
*,
|
||||
sick: bool = False,
|
||||
progress: Share | None = None,
|
||||
) -> int:
|
||||
answers = {**NOTHING, "review": answer}
|
||||
return resolve(answers, day, sick=sick, progress=progress).shutdown_minutes
|
||||
|
||||
|
||||
def _paid(day: date, share: Share | None = None, *, sick: bool = False) -> int:
|
||||
"""What the credited review adds to the day's shutdown over no review."""
|
||||
got = _review(1, day, sick=sick, progress=share)
|
||||
return got - _review(0, day, sick=sick, progress=share)
|
||||
|
||||
|
||||
def test_the_switch_is_the_day_after_the_release() -> None:
|
||||
assert date(2026, 11, 24) == REVIEW_PROGRESS_FROM
|
||||
assert REVIEW_FROM + timedelta(days=1) == REVIEW_PROGRESS_FROM
|
||||
|
||||
|
||||
def test_before_the_switch_the_review_pays_as_in_0_23_0() -> None:
|
||||
day = REVIEW_PROGRESS_FROM - timedelta(days=1)
|
||||
assert _paid(day) == REVIEW_SHUTDOWN_MINUTES
|
||||
# A row changes nothing yet: a yes pays full, a no pays nothing.
|
||||
half: Share = {"review": Progress(1, 2)}
|
||||
assert _paid(day, half) == REVIEW_SHUTDOWN_MINUTES
|
||||
assert _review(0, day, progress=half) == _review(0, day)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("day", DAYS)
|
||||
def test_a_credited_review_with_no_row_pays_nothing(day: date) -> None:
|
||||
assert _paid(day) == 0
|
||||
assert _paid(day, {}) == 0
|
||||
assert _paid(day, {"leetcode": Progress(1, 2)}) == 0
|
||||
term = resolve({**NOTHING, "review": True}, day).term("review")
|
||||
assert (term.shutdown_minutes, term.gaming_minutes, term.progress) == (0, 0, None)
|
||||
assert term.answer == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("day", DAYS)
|
||||
def test_a_row_pays_equal_slices_of_the_bonus(day: date) -> None:
|
||||
assert _paid(day, {"review": Progress(1, 2)}) == 10
|
||||
assert _paid(day, {"review": Progress(2, 2)}) == 20
|
||||
assert _paid(day, {"review": Progress(0, 2)}) == 0
|
||||
assert _paid(day, {"review": Progress(1, 3)}) == 20 // 3
|
||||
assert _paid(day, {"review": Progress(2, 3)}) == 40 // 3
|
||||
|
||||
|
||||
def test_a_row_never_pays_more_than_the_full_bonus() -> None:
|
||||
assert _paid(ON, {"review": Progress(9, 2)}) == 20
|
||||
assert _paid(ON, {"review": Progress(5, 5)}) == 20
|
||||
|
||||
|
||||
def test_the_term_shows_the_row_it_was_paid_from() -> None:
|
||||
row = Progress(1, 2)
|
||||
term = resolve({**NOTHING, "review": 1}, ON, progress={"review": row}).term(
|
||||
"review"
|
||||
)
|
||||
assert term.progress == row
|
||||
assert term.gaming_minutes == 0
|
||||
|
||||
|
||||
@pytest.mark.parametrize("answer", [0, None])
|
||||
def test_a_row_without_a_credited_review_pays_nothing(
|
||||
answer: int | None,
|
||||
) -> None:
|
||||
full: Share = {"review": Progress(2, 2)}
|
||||
assert _review(answer, ON, progress=full) == _review(0, ON)
|
||||
term = resolve({**NOTHING, "review": answer}, ON, progress=full).term("review")
|
||||
assert term.shutdown_minutes == 0
|
||||
assert term.progress is None
|
||||
|
||||
|
||||
def test_a_sick_day_follows_the_same_rule() -> None:
|
||||
assert _paid(ON, sick=True) == 0
|
||||
assert _paid(ON, {"review": Progress(1, 2)}, sick=True) == 10
|
||||
assert _paid(ON, {"review": Progress(2, 2)}, sick=True) == 20
|
||||
|
||||
|
||||
def test_other_earners_keep_the_yes_no_rule_without_a_row() -> None:
|
||||
plain = resolve({**NOTHING, "leetcode": True}, ON)
|
||||
assert plain.term("leetcode").shutdown_minutes == 60
|
||||
shown = resolve(NOTHING, ON, progress={"leetcode": Progress(1, 3)})
|
||||
assert shown.term("leetcode").shutdown_minutes == 20
|
||||
assert resolve(NOTHING, ON).term("leetcode").shutdown_minutes == 0
|
||||
|
||||
|
||||
def test_a_missing_review_answer_still_earns_nothing() -> None:
|
||||
answers = dict(NOTHING)
|
||||
shown = resolve(answers, ON, progress={"review": Progress(2, 2)})
|
||||
assert shown.term("review").shutdown_minutes == 0
|
||||
|
||||
|
||||
def test_a_credited_review_without_a_row_is_logged(
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
with caplog.at_level(logging.WARNING, logger="earned_time._share"):
|
||||
resolve({**NOTHING, "review": True}, ON)
|
||||
assert "no progress row" in caplog.text
|
||||
assert REVIEW.label in caplog.text
|
||||
|
||||
|
||||
def test_no_warning_with_a_row_or_before_the_switch(
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
with caplog.at_level(logging.WARNING, logger="earned_time._share"):
|
||||
resolve({**NOTHING, "review": True}, ON, progress={"review": Progress(1, 2)})
|
||||
resolve({**NOTHING, "review": True}, REVIEW_FROM)
|
||||
assert "no progress row" not in caplog.text
|
||||
|
||||
|
||||
def test_a_row_that_fails_verification_counts_as_no_row(
|
||||
tmp_path: Path, key_file: Path
|
||||
) -> None:
|
||||
good = progress(source="review", done="2", target="2", day=ON)
|
||||
forged = tampered(good, done="2")
|
||||
forged["hmac"] = "0" * 64
|
||||
for rows, expected in (([good], 20), ([forged], 0), ([], 0)):
|
||||
write(home_ledger(tmp_path, REVIEW), list(rows))
|
||||
share = progress_map(ON, tmp_path, key_file)
|
||||
assert _paid(ON, share) == expected
|
||||
|
||||
|
||||
def test_the_last_good_row_prices_the_day(tmp_path: Path, key_file: Path) -> None:
|
||||
rows = [
|
||||
progress(source="review", done="1", target="2", day=ON),
|
||||
progress(source="review", done="2", target="2", day=ON),
|
||||
]
|
||||
write(home_ledger(tmp_path, REVIEW), list(rows))
|
||||
assert _paid(ON, progress_map(ON, tmp_path, key_file)) == 20
|
||||
write(home_ledger(tmp_path, REVIEW), list(rows[:1]))
|
||||
assert _paid(ON, progress_map(ON, tmp_path, key_file)) == 10
|
||||
@ -1,8 +1,5 @@
|
||||
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||
"""The review top-up in the day (0.23.0): added last, capped, never a rung.
|
||||
|
||||
On ``REVIEW_FROM``, the day before ``REVIEW_PROGRESS_FROM``: the flat pay, no row.
|
||||
"""
|
||||
"""The review top-up in the day (0.23.0): added last, capped, never a rung."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@ -21,14 +18,11 @@ from earned_time import (
|
||||
shutdown_ceiling_for,
|
||||
shutdown_minutes_for,
|
||||
)
|
||||
from earned_time.tests._review_rows import DAY as ROWS_DAY
|
||||
from earned_time.tests._review_rows import accepted, home_with, review
|
||||
from earned_time.tests._review_rows import DAY, accepted, home_with, review
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
# The last day before REVIEW_PROGRESS_FROM: the flat 0.23.0 pay, no row needed.
|
||||
DAY = REVIEW_FROM
|
||||
NOTHING: dict[str, int | bool | None] = {
|
||||
"workout": 0,
|
||||
"leetcode": False,
|
||||
@ -124,6 +118,6 @@ def test_a_sick_day_before_unlimited_gaming_adds_it_too() -> None:
|
||||
|
||||
def test_maturity_never_penalises_it(tmp_path: Path, key_file: Path) -> None:
|
||||
ledger = home_with(tmp_path, [review()], [accepted()])
|
||||
verdict = maturity(REVIEW, ledger, key_file, ROWS_DAY)
|
||||
verdict = maturity(REVIEW, ledger, key_file, DAY)
|
||||
assert verdict.penalty_start is None
|
||||
assert any("top-up" in reason for reason in verdict.reasons)
|
||||
|
||||
@ -1,142 +0,0 @@
|
||||
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||
"""``term_for``: the one place an earner's pay for a day is derived.
|
||||
|
||||
``resolve`` builds its terms through it, so a consumer pricing one earner (the
|
||||
screen-locker's live pass) can never disagree with ``resolve``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from itertools import product
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from earned_time import (
|
||||
LEETCODE,
|
||||
REVIEW,
|
||||
REVIEW_PROGRESS_FROM,
|
||||
WORKOUT,
|
||||
Earner,
|
||||
Progress,
|
||||
Term,
|
||||
earners_for,
|
||||
resolve,
|
||||
shutdown_minutes_for,
|
||||
term_for,
|
||||
)
|
||||
|
||||
DAYS = (
|
||||
date(2026, 10, 5),
|
||||
date(2026, 10, 16),
|
||||
date(2026, 11, 22),
|
||||
REVIEW_PROGRESS_FROM.replace(day=REVIEW_PROGRESS_FROM.day - 1),
|
||||
REVIEW_PROGRESS_FROM,
|
||||
REVIEW_PROGRESS_FROM.replace(day=REVIEW_PROGRESS_FROM.day + 1),
|
||||
date(2027, 1, 1),
|
||||
)
|
||||
ANSWERS: tuple[int | bool | None, ...] = (True, False, None, 0, 1, 2)
|
||||
FACTS: tuple[Progress | None, ...] = (
|
||||
None,
|
||||
Progress(0, 3),
|
||||
Progress(1, 3),
|
||||
Progress(2, 3),
|
||||
Progress(3, 3),
|
||||
Progress(1, 1),
|
||||
Progress(7, 2),
|
||||
)
|
||||
LADDER = date(2026, 11, 22)
|
||||
|
||||
|
||||
def test_the_signature_is_keyword_clear() -> None:
|
||||
loose: Any = term_for
|
||||
with pytest.raises(TypeError):
|
||||
loose(LEETCODE, LADDER, 1)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("day", DAYS)
|
||||
def test_term_for_equals_the_term_resolve_builds(day: date) -> None:
|
||||
for item, answer, fact in product(earners_for(day), ANSWERS, FACTS):
|
||||
others = {e.name: 0 for e in earners_for(day)}
|
||||
asked = resolve(
|
||||
{**others, item.name: answer},
|
||||
day,
|
||||
progress=None if fact is None else {item.name: fact},
|
||||
).term(item.name)
|
||||
got = term_for(item, day, answer=answer, progress=fact)
|
||||
assert got == asked, (item.name, day, answer, fact)
|
||||
assert isinstance(got, Term)
|
||||
|
||||
|
||||
def test_a_generic_earner_pays_a_share_of_the_ladder_rung() -> None:
|
||||
full = shutdown_minutes_for(LEETCODE, LADDER)
|
||||
assert full == 60
|
||||
row = Progress(1, 3)
|
||||
assert term_for(LEETCODE, LADDER, answer=False, progress=row).shutdown_minutes == 20
|
||||
assert term_for(LEETCODE, LADDER, answer=False, progress=row).gaming_minutes == 20
|
||||
assert term_for(LEETCODE, LADDER, answer=False).shutdown_minutes == 0
|
||||
|
||||
|
||||
def test_a_yes_pays_full_whatever_the_row_says() -> None:
|
||||
low = term_for(LEETCODE, LADDER, answer=True, progress=Progress(1, 3))
|
||||
assert low.shutdown_minutes == shutdown_minutes_for(LEETCODE, LADDER)
|
||||
assert low.progress is None
|
||||
|
||||
|
||||
def test_a_row_never_pays_above_full() -> None:
|
||||
term = term_for(LEETCODE, LADDER, answer=False, progress=Progress(9, 3))
|
||||
assert term.shutdown_minutes == shutdown_minutes_for(LEETCODE, LADDER)
|
||||
|
||||
|
||||
def test_none_earns_nothing_even_with_a_full_row() -> None:
|
||||
assert term_for(LEETCODE, LADDER, answer=None, progress=Progress(3, 3)) == Term(
|
||||
LEETCODE, None, 0, 0
|
||||
)
|
||||
|
||||
|
||||
def test_the_review_follows_its_dated_rule() -> None:
|
||||
row = Progress(1, 3)
|
||||
before = REVIEW_PROGRESS_FROM.replace(day=REVIEW_PROGRESS_FROM.day - 1)
|
||||
assert term_for(REVIEW, before, answer=True, progress=row).shutdown_minutes == 20
|
||||
assert term_for(REVIEW, before, answer=False, progress=row).shutdown_minutes == 0
|
||||
on = REVIEW_PROGRESS_FROM
|
||||
assert term_for(REVIEW, on, answer=True, progress=row).shutdown_minutes == 6
|
||||
assert term_for(REVIEW, on, answer=True).shutdown_minutes == 0
|
||||
assert term_for(REVIEW, on, answer=False, progress=row).shutdown_minutes == 0
|
||||
|
||||
|
||||
def test_a_counted_earner_pays_per_unit() -> None:
|
||||
day = LADDER
|
||||
one = term_for(WORKOUT, day, answer=1).shutdown_minutes
|
||||
assert term_for(WORKOUT, day, answer=True).shutdown_minutes == one
|
||||
assert term_for(WORKOUT, day, answer=0).shutdown_minutes == 0
|
||||
|
||||
|
||||
def _expected(
|
||||
item: Earner, day: date, answer: int | None, fact: Progress | None
|
||||
) -> int:
|
||||
"""The shutdown minutes by the written rules, not by the library's code."""
|
||||
if answer is None:
|
||||
return 0
|
||||
full = shutdown_minutes_for(item, day)
|
||||
yes = answer is True or answer >= 1
|
||||
if item is REVIEW and day >= REVIEW_PROGRESS_FROM:
|
||||
if not yes or fact is None:
|
||||
return 0
|
||||
return full * min(fact.done, fact.target) // fact.target
|
||||
if yes or (item is REVIEW) or fact is None:
|
||||
return item.shutdown_for(max(0, int(answer)), day)
|
||||
return full * min(fact.done, fact.target) // fact.target
|
||||
|
||||
|
||||
@pytest.mark.parametrize("day", DAYS)
|
||||
def test_the_minutes_follow_the_written_rules(day: date) -> None:
|
||||
for item, answer, fact in product(earners_for(day), ANSWERS, FACTS):
|
||||
got = term_for(item, day, answer=answer, progress=fact)
|
||||
assert got.shutdown_minutes == _expected(item, day, answer, fact), (
|
||||
item.name,
|
||||
day,
|
||||
answer,
|
||||
fact,
|
||||
)
|
||||
@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "earned-time"
|
||||
version = "0.24.0"
|
||||
version = "0.23.0"
|
||||
description = "Penalty-then-reward registry: what every gate app earns in gaming time and shutdown time"
|
||||
requires-python = ">=3.14"
|
||||
dependencies = []
|
||||
@ -35,7 +35,7 @@ unfixable = []
|
||||
|
||||
[tool.ruff.lint.pylint]
|
||||
# Same as [tool.pylint.design] max-args: resolve()'s keyword-only switches.
|
||||
max-args = 7
|
||||
max-args = 6
|
||||
|
||||
[tool.ruff.lint.pydocstyle]
|
||||
convention = "google"
|
||||
@ -111,10 +111,10 @@ disable = []
|
||||
min-public-methods = 0
|
||||
max-module-lines = 1000
|
||||
# Earner is a frozen registry record: its fields are the policy (cf. music_theory).
|
||||
max-attributes = 14
|
||||
max-attributes = 13
|
||||
# resolve()'s keyword-only switches (first_credits, sick, leisure) are the
|
||||
# public API every consumer calls; bundling them would break each caller.
|
||||
max-args = 7
|
||||
max-args = 6
|
||||
|
||||
[tool.pylint.typecheck]
|
||||
generated-members = [
|
||||
|
||||
@ -117,7 +117,7 @@ repos:
|
||||
# Kept in step with pyproject.toml, so pylint resolves the crdt_sync
|
||||
# imports instead of scoring every one of them as import-error.
|
||||
- crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync
|
||||
- earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.24.0#subdirectory=earned_time
|
||||
- earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.23.0#subdirectory=earned_time
|
||||
|
||||
- repo: https://github.com/PyCQA/bandit
|
||||
rev: 1.9.4
|
||||
|
||||
@ -4,11 +4,11 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "focus_project"
|
||||
version = "0.10.1"
|
||||
version = "0.10.0"
|
||||
description = "Time-boxed focus projects: replace chosen gates, pay a daily-minutes gate"
|
||||
requires-python = ">=3.14"
|
||||
# Stdlib only on purpose: guards import it from the system python.
|
||||
dependencies = ["earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.24.0#subdirectory=earned_time"]
|
||||
dependencies = ["earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.23.0#subdirectory=earned_time"]
|
||||
|
||||
[tool.setuptools.packages.find]
|
||||
include = ["focus_project*"]
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
# floor is satisfied by anything newer, so it tells a checker nothing
|
||||
# about whether this repo is actually current.
|
||||
bandit[toml]==1.9.4
|
||||
earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.24.0#subdirectory=earned_time
|
||||
earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.23.0#subdirectory=earned_time
|
||||
mypy==2.4.1
|
||||
pre-commit==4.7.0
|
||||
pylint==4.1.4
|
||||
|
||||
@ -84,11 +84,7 @@ class Reporter:
|
||||
version: str | None = None
|
||||
threshold: float = 1.0
|
||||
still_after: float = 5.0
|
||||
#: Wall time: entry timestamps, ids and the rate-limit minutes.
|
||||
clock: Callable[[], float] = time.time
|
||||
#: Elapsed time for waits. Never the wall clock: chrony stepped it 1.33 s
|
||||
#: into a fresh lock on 2026-11-25 and that read as a 1.5 s freeze.
|
||||
monotonic: Callable[[], float] = time.monotonic
|
||||
_guard: _Guard = field(default_factory=_Guard)
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
@ -188,7 +184,7 @@ class Reporter:
|
||||
self,
|
||||
operation,
|
||||
route,
|
||||
self.monotonic(),
|
||||
self.clock(),
|
||||
f"{int(self.clock() * 1000):x}-{self._guard.serial}",
|
||||
)
|
||||
|
||||
@ -222,7 +218,7 @@ class SlowWait:
|
||||
self._timer.start()
|
||||
|
||||
def _ms(self) -> int:
|
||||
return round((self.reporter.monotonic() - self.started) * 1000)
|
||||
return round((self.reporter.clock() - self.started) * 1000)
|
||||
|
||||
def _still(self) -> None:
|
||||
if self._ended:
|
||||
|
||||
@ -42,8 +42,8 @@ if TYPE_CHECKING:
|
||||
output: int
|
||||
|
||||
class _XRoot(Protocol):
|
||||
def xrandr_get_screen_resources_current(self) -> _ScreenResources:
|
||||
"""Mirror ``root.xrandr_get_screen_resources_current()``."""
|
||||
def xrandr_get_screen_resources(self) -> _ScreenResources:
|
||||
"""Mirror ``root.xrandr_get_screen_resources()``."""
|
||||
|
||||
def xrandr_get_output_primary(self) -> _PrimaryReply:
|
||||
"""Mirror ``root.xrandr_get_output_primary()``."""
|
||||
@ -124,10 +124,7 @@ class RandrBackend:
|
||||
def _scan(self) -> tuple[Output, ...]:
|
||||
"""Enumerate outputs via RandR. Raises on any protocol problem."""
|
||||
root = self._display.screen().root
|
||||
# The cached server state, not a full re-probe of every output (53 ms
|
||||
# vs 0.2 ms on NVIDIA, on the Tk thread every recovery tick). Hotplug
|
||||
# still lands: the driver updates that state and sends the RandR event.
|
||||
resources = root.xrandr_get_screen_resources_current()
|
||||
resources = root.xrandr_get_screen_resources()
|
||||
timestamp = resources.config_timestamp
|
||||
primary_id = self._primary_output_id(root)
|
||||
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||
"""Reading outputs by shelling out to `xrandr --current`.
|
||||
"""Reading outputs by shelling out to `xrandr --query`.
|
||||
|
||||
Split from :mod:`gatelock._outputs`, which keeps the value types and the
|
||||
enumerator that picks a source. This is the fallback path: slower than the
|
||||
@ -77,7 +77,7 @@ def parse_xrandr_query(text: str) -> tuple[Output, ...]:
|
||||
|
||||
|
||||
def scan_xrandr() -> tuple[Output, ...] | None:
|
||||
"""Enumerate outputs by shelling out to ``xrandr --current``.
|
||||
"""Enumerate outputs by shelling out to ``xrandr --query``.
|
||||
|
||||
Returns:
|
||||
The parsed outputs, or None if xrandr is missing, failed, timed out or
|
||||
@ -89,24 +89,24 @@ def scan_xrandr() -> tuple[Output, ...] | None:
|
||||
return None
|
||||
try:
|
||||
completed = subprocess.run(
|
||||
[binary, "--current"],
|
||||
[binary, "--query"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=_XRANDR_TIMEOUT_S,
|
||||
check=False,
|
||||
)
|
||||
except (subprocess.TimeoutExpired, OSError) as exc:
|
||||
_logger.warning("xrandr --current failed to run: %s", exc)
|
||||
_logger.warning("xrandr --query failed to run: %s", exc)
|
||||
return None
|
||||
if completed.returncode != 0:
|
||||
_logger.warning(
|
||||
"xrandr --current exited %d: %s",
|
||||
"xrandr --query exited %d: %s",
|
||||
completed.returncode,
|
||||
completed.stderr.strip(),
|
||||
)
|
||||
return None
|
||||
outputs = parse_xrandr_query(completed.stdout)
|
||||
if not outputs:
|
||||
_logger.warning("xrandr --current produced no parseable output lines")
|
||||
_logger.warning("xrandr --query produced no parseable output lines")
|
||||
return None
|
||||
return outputs
|
||||
|
||||
@ -60,16 +60,14 @@ def watch_stalls(root: tk.Misc, reporter: Reporter) -> None:
|
||||
|
||||
The operation is ``tk.mainloop``: a blocking call on the Tk thread.
|
||||
"""
|
||||
# Lateness is monotonic: a wall-clock step (NTP at login) is not a freeze.
|
||||
last = [reporter.monotonic()]
|
||||
last = [reporter.clock()]
|
||||
|
||||
def tick() -> None:
|
||||
now = reporter.monotonic()
|
||||
now = reporter.clock()
|
||||
late = round((now - last[0]) * 1000) - STALL_TICK_MS
|
||||
last[0] = now
|
||||
if late > reporter.threshold * 1000:
|
||||
stamp = int(reporter.clock() * 1000)
|
||||
reporter.slow("tk.mainloop", late, wait_id=f"stall-{stamp:x}")
|
||||
reporter.slow("tk.mainloop", late, wait_id=f"stall-{int(now * 1000):x}")
|
||||
with suppress(tk.TclError): # the window is gone: the watch ends
|
||||
root.after(STALL_TICK_MS, tick)
|
||||
|
||||
|
||||
@ -34,7 +34,6 @@ def reporter(tmp_path: Path, clock: Clock) -> Reporter:
|
||||
build=5,
|
||||
version="0.3.0",
|
||||
clock=clock,
|
||||
monotonic=clock,
|
||||
)
|
||||
|
||||
|
||||
@ -126,25 +125,6 @@ def test_stall_watch_reports_a_frozen_loop(
|
||||
assert entry["durationMs"] == 2500 - error_report.STALL_TICK_MS
|
||||
|
||||
|
||||
def test_stall_watch_ignores_a_wall_clock_step(tmp_path: Path) -> None:
|
||||
# chrony stepped the wall clock +1.33 s 3 s into a lock (2026-11-25):
|
||||
# lateness is monotonic time, so the step is not a freeze.
|
||||
wall, mono = Clock(), Clock()
|
||||
rep = Reporter(app="tk-app", repo="r", spool=tmp_path, clock=wall, monotonic=mono)
|
||||
root = MagicMock()
|
||||
error_report.watch_stalls(root, rep)
|
||||
tick = root.after.call_args.args[1]
|
||||
mono.t += 0.1
|
||||
wall.t += 1.431
|
||||
tick()
|
||||
assert spool_lines(tmp_path, "tk-app") == []
|
||||
mono.t += 2.5 # a real 2.5 s freeze is still reported
|
||||
wall.t += 2.5
|
||||
tick()
|
||||
(entry,) = spool_lines(tmp_path, "tk-app")
|
||||
assert entry["durationMs"] == 2500 - error_report.STALL_TICK_MS
|
||||
|
||||
|
||||
def test_stall_watch_stops_with_the_window(reporter: Reporter, clock: Clock) -> None:
|
||||
root = MagicMock()
|
||||
error_report.watch_stalls(root, reporter)
|
||||
|
||||
@ -29,7 +29,6 @@ def reporter(tmp_path: Path, clock: Clock) -> Reporter:
|
||||
build=5,
|
||||
version="0.3.0",
|
||||
clock=clock,
|
||||
monotonic=clock,
|
||||
)
|
||||
|
||||
|
||||
@ -103,20 +102,6 @@ def test_slow_wait_over_threshold_is_written(
|
||||
assert entry["error"] == "coach.load waited 2000 ms"
|
||||
|
||||
|
||||
def test_slow_wait_measures_monotonic_time(tmp_path: Path) -> None:
|
||||
wall, mono = Clock(), Clock()
|
||||
rep = Reporter(app="leetcode-guard", repo="r", spool=tmp_path, clock=wall, monotonic=mono)
|
||||
with rep.wait("op"):
|
||||
wall.t += 1.5 # a clock step, not a wait
|
||||
mono.t += 0.2
|
||||
assert spool_lines(tmp_path) == []
|
||||
with rep.wait("op"):
|
||||
mono.t += 1.2
|
||||
wall.t -= 3.0 # stepped back: the wait is still 1.2 s
|
||||
(entry,) = spool_lines(tmp_path)
|
||||
assert entry["durationMs"] == 1200
|
||||
|
||||
|
||||
def test_fast_wait_writes_nothing(
|
||||
reporter: Reporter, tmp_path: Path, clock: Clock
|
||||
) -> None:
|
||||
|
||||
@ -148,13 +148,7 @@ class TestScanXrandr:
|
||||
def test_success(self) -> None:
|
||||
"""A clean run parses stdout."""
|
||||
completed = MagicMock(returncode=0, stdout=XRANDR_REAL, stderr="")
|
||||
with (
|
||||
patch("gatelock._xrandr.shutil.which", return_value="/usr/bin/xrandr"),
|
||||
patch("gatelock._xrandr.subprocess.run", return_value=completed) as run,
|
||||
):
|
||||
assert real_scan_xrandr() is not None
|
||||
# --current reads the server's state; --query re-probes every output.
|
||||
assert run.call_args.args[0] == ["/usr/bin/xrandr", "--current"]
|
||||
assert self._run(return_value=completed) is not None
|
||||
|
||||
def test_missing_binary(self) -> None:
|
||||
"""xrandr not on PATH degrades rather than raising."""
|
||||
|
||||
@ -60,11 +60,9 @@ def _randr_display(*, outputs: dict[int, dict[str, object]]) -> MagicMock:
|
||||
"""Build a fake Xlib display exposing ``outputs``."""
|
||||
display = MagicMock()
|
||||
root = MagicMock()
|
||||
root.xrandr_get_screen_resources_current.return_value = _reply(
|
||||
root.xrandr_get_screen_resources.return_value = _reply(
|
||||
config_timestamp=1, outputs=list(outputs)
|
||||
)
|
||||
# The full probe re-polls every output (53 ms on NVIDIA, per tick): never.
|
||||
root.xrandr_get_screen_resources.side_effect = AssertionError("full probe")
|
||||
root.xrandr_get_output_primary.return_value = _reply(output=1)
|
||||
display.screen.return_value.root = root
|
||||
|
||||
|
||||
@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "gatelock"
|
||||
version = "0.16.2"
|
||||
version = "0.16.1"
|
||||
description = "Shared per-output lock-window + HMAC log-integrity backend for blocking-overlay apps"
|
||||
requires-python = ">=3.14"
|
||||
dependencies = [] # pure stdlib — tkinter is bundled with Python
|
||||
@ -21,7 +21,7 @@ randr = ["python-xlib==0.33"]
|
||||
# must not refuse to start over a missing dependency, and only the chain's
|
||||
# own CLI imports these (lazily). Pins match book-guard / leetcode-guard.
|
||||
evening = [
|
||||
"earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.24.0#subdirectory=earned_time",
|
||||
"earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.23.0#subdirectory=earned_time",
|
||||
"freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.4#subdirectory=freedays",
|
||||
"sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.9#subdirectory=sickdays",
|
||||
]
|
||||
|
||||
@ -64,11 +64,7 @@ IGNORED_SEGMENTS = frozenset(
|
||||
|
||||
# Third-party trees. Their layout is not ours to police, and `~/Unity` in a
|
||||
# vendored Unity MCP server is correct for the machine it was written for.
|
||||
# `synced` is ~/.claude/skills/synced: Claude-managed skill copies that are
|
||||
# regenerated, so an edit there would not stick.
|
||||
THIRD_PARTY_PARTS = frozenset(
|
||||
{"mcp-servers", "vendor", "node_modules", "third_party", "vendored", "synced"}
|
||||
)
|
||||
THIRD_PARTY_PARTS = frozenset({"mcp-servers", "vendor", "node_modules", "third_party", "vendored"})
|
||||
|
||||
# Test corpora spell pre-move paths on purpose -- system-maintenance's own
|
||||
# manifest already protects its fixtures under `refs.skip_paths`, for the
|
||||
|
||||
@ -94,7 +94,6 @@ def test_third_party_and_test_trees_are_skipped(tmp_path: Path) -> None:
|
||||
for rel in (
|
||||
"mcp-servers/a.py",
|
||||
"vendor/b.py",
|
||||
"skills/synced/x/scripts/f.py",
|
||||
"repo/tests/c.py",
|
||||
"repo/test_d.py",
|
||||
"repo/e_test.py",
|
||||
|
||||
@ -28,7 +28,7 @@ Stdlib only unless noted. Import only what you need.
|
||||
| Review | `review_cli` (`/leetcode review`, skeleton sheets), `flagged` (guard CLI reader), `review_ledger` (the coach's own signed ledger) |
|
||||
| Content | `fetch_problem`, `toolbox.json`, `answer_key`, `clusters.json` |
|
||||
| Cards | `toolbox_cards`, `card_rules`, `make_cards` (needs genanki), `anki_connect` |
|
||||
| Models | `claude_cli` (haiku/sonnet via `claude -p`), `local_backend` (Ollama), `omniroute_backend` (OmniRoute `free-best`), `free_chain` (OmniRoute, then Ollama) |
|
||||
| Models | `claude_cli` (haiku/sonnet via `claude -p`), `local_backend` (Ollama) |
|
||||
| Relay | `relay.*`: state machine, grading, run-code, HTTP + RTDB (needs requests, crdt-sync) |
|
||||
| Clients | `leetcode_repl` (`leetcode` command), `cluster_cli`, `local_session`, `how_to` |
|
||||
|
||||
@ -52,9 +52,9 @@ means paste it), `fetch_problem.render(q, lang) -> str` (markdown with
|
||||
refuse and show `note`; otherwise forward `sent` to the coach and show `note`
|
||||
if non-empty. Logs `req`, `req_check`, `code`, `reveal`.
|
||||
- `ask` (gate, `req_check.check`, `looks_like_code`, graders) is CLI-style `(args, prompt, **kw)`
|
||||
(default: haiku, then the free chain) or a structured `(system, prompt, schema) -> dict`
|
||||
(default: haiku, then Ollama) or a structured `(system, prompt, schema) -> dict`
|
||||
model function such as the tutor's `ask_model` (answers are labelled `via: "model"`;
|
||||
any raise falls through to the free chain, then fails open to `unverified`).
|
||||
any raise falls through to Ollama, then fails open to `unverified`).
|
||||
- `gate.refusal_note()`, `gate.code_seen()`, `gate.events()`, `gate.sql()`,
|
||||
`gate.leaks(reply, user_texts) -> [names]` (bounce and regenerate),
|
||||
`gate.after_reply(text) -> text without the rung marker` (logs `rung`).
|
||||
@ -92,11 +92,7 @@ and +10 days), `cluster_progress()`, `next_new(...)`, `cluster_of(slug)`. A
|
||||
(`DOCS-review.md`). `review-finish` takes only a slug the guard flags now and
|
||||
writes one signed row per slug to
|
||||
`~/.local/share/leetcode-coach/review_ledger.json` (`review_ledger.record`),
|
||||
then the `review` event. It never touches the guard's ledger. Each credit row
|
||||
is written with a `progress` row ("done N of target M", source `review`) in
|
||||
the same rename: the target is the number of flagged solves when the day's
|
||||
first review is finished and stays frozen that day, `done` is the day's signed
|
||||
review rows capped at it (`earned_time` 0.24.0 pays `bonus * done // target`).
|
||||
then the `review` event. It never touches the guard's ledger.
|
||||
|
||||
**Toolbox + cards.** `toolbox.load_safe() -> Toolbox` (`.entries`,
|
||||
`.properties`), `toolbox_cards.cards_for(names) -> [Card]` (property list ->
|
||||
|
||||
@ -11,16 +11,10 @@ toolbox name, but the TUI has already streamed it (2026-09-21: the blocked
|
||||
`for` loop was visible above the rewrite); print mode waits. TUI: best-effort.
|
||||
|
||||
**Offline / out of quota.** `leetcode --local <url>` coaches on
|
||||
`qwen3:30b-a3b-instruct-2507` via Ollama. On "You've hit your ... limit" the
|
||||
REPL, the relay coach and the graders switch by themselves, history intact, to
|
||||
the free chain (`free_chain.py`, kuhy 2026-11-27): OmniRoute `free-best` on
|
||||
127.0.0.1:20128 (`omniroute_backend.py`, Bearer key from
|
||||
`~/.config/omniroute/api_key`), then Ollama when the gateway is down, empty or
|
||||
too small for the prompt. One timeout covers the whole chain. With no hooks
|
||||
there, `local_coach.py` runs the same detectors on every draft, whichever
|
||||
rung wrote it; three leaky drafts are withheld. `leetcode --free <url>` runs
|
||||
interactive `claude-free` with this skill from a fresh `/tmp` dir (the free
|
||||
providers log prompts; nothing private is in reach there). Everything above `## Model and client` is its system prompt,
|
||||
`qwen3:30b-a3b-instruct-2507` via Ollama, and the REPL switches there by
|
||||
itself, history intact, on "You've hit your ... limit". With no hooks there,
|
||||
`local_coach.py` runs the same detectors on every draft; three leaky drafts
|
||||
are withheld. Everything above `## Model and client` is its system prompt,
|
||||
minus section 1. `python3 -m leetcode_coach.eval_local`: acceptance run.
|
||||
|
||||
## The req-before-code gate (DOCS-coach-spec.md decisions 4-8)
|
||||
@ -28,8 +22,7 @@ minus section 1. `python3 -m leetcode_coach.eval_local`: acceptance run.
|
||||
Both REPL paths run `phase.PhaseGate` on every block kuhy sends:
|
||||
|
||||
- `req: ...` is the requirement list. `req_check` judges it on
|
||||
`claude -p --model haiku` (no tools, hooks or session file), then on the
|
||||
free chain (OmniRoute, then Ollama),
|
||||
`claude -p --model haiku` (no tools, hooks or session file), then on Ollama,
|
||||
and fails OPEN (`unverified`) when neither answers. It may only name
|
||||
missing properties from the `toolbox.json` vocabulary; anything else it says
|
||||
is dropped before kuhy sees it.
|
||||
|
||||
@ -59,10 +59,6 @@ taught. You find the one cause, log it, and that starts the cold re-test clock
|
||||
- exit 0, `review logged: ...` and `ledger row: written`: the solve is no
|
||||
longer flagged, and the re-test falls due 3 and 10 days from today
|
||||
(`leetcode --retest <slug>`).
|
||||
The same write adds a `progress` row (`progress:<day>:<done>:<target>`),
|
||||
so a review pays its share of the day's bonus: the target is how many
|
||||
solves were flagged when that day's first review finished and does not
|
||||
change after it.
|
||||
- `refused: ...` (exit 1): the slug is not flagged or an argument is
|
||||
wrong. Nothing was written.
|
||||
- `could not check: ...` (exit 2): nothing was written. Tell kuhy; do not
|
||||
|
||||
@ -36,8 +36,6 @@ python3 ~/.claude/skills/leetcode/fetch_problem.py "<first token>"
|
||||
never quote it to kuhy unasked.
|
||||
|
||||
Default starter language is JavaScript (`--lang python3` etc. if kuhy asks).
|
||||
Then `python3 ~/.claude/skills/leetcode/history.py "<first token>"`: his own attempts,
|
||||
failed and accepted, with code. For you only: never paste it back; ask where it broke.
|
||||
|
||||
## 2. Open
|
||||
|
||||
@ -216,8 +214,8 @@ the method appeared.
|
||||
## 5d. Cold re-test
|
||||
|
||||
`[cold re-test]` in the arguments (`leetcode --retest <slug>`, due +3 and
|
||||
+10 days after a solve) means kuhy solved this before; `history.py` has his old
|
||||
code, for you only: it is solved cold. In the opening, say plainly: **do NOT
|
||||
+10 days after a solve) means kuhy solved this before; you have no history,
|
||||
so do not ask about the old code. In the opening, say plainly: **do NOT
|
||||
submit on LeetCode** -- a resubmission mints a gate credit. Then coach as
|
||||
usual, requirement list first, and judge by running the statement's examples
|
||||
locally with `node` (section 4). The normal exit and post-mortem (5, 5b)
|
||||
@ -236,15 +234,17 @@ Runs on **sonnet, opus or fable** as written. Haiku went in circles (~30
|
||||
micro-questions on an Easy, 2026-10-18); `model:` frontmatter is ignored for
|
||||
skills (2026-09-18), so only if you are haiku, the **first line** of your
|
||||
opening message is
|
||||
|
||||
> Type `/model sonnet` now — learning sessions are gated to sonnet, opus or
|
||||
> fable; your next message is refused until you do (or send `keep model`).
|
||||
|
||||
then continue with the opening (`hooks/leetcode_model_gate_userprompt.sh`).
|
||||
then continue with the opening. `hooks/leetcode_model_gate_userprompt.sh`
|
||||
enforces it from the next prompt on.
|
||||
|
||||
The right client is `leetcode <url>` (print mode: the Stop hook can still
|
||||
withhold a reply; a usage limit moves it to OmniRoute, then Ollama). `--local`:
|
||||
Ollama only; `--free`: `claude-free` from /tmp. The local system prompt is all
|
||||
above this section. Docs: `DOCS-clients.md` (clients, gates), `DOCS-how-to.md`.
|
||||
withhold a reply; the TUI has already streamed it). `leetcode --local` runs
|
||||
offline on Ollama; its system prompt is everything above this section. Docs:
|
||||
`DOCS-clients.md` (clients, gates, session log), `DOCS-how-to.md` (commands).
|
||||
|
||||
Skeleton sheets: only when kuhy asks, only after his first code, and one
|
||||
counts above H1. Rules: `DOCS-skeletons.md`; the command: `DOCS-review.md`.
|
||||
|
||||
@ -8,7 +8,6 @@ checker treats it as "haiku did not answer" and falls back.
|
||||
The signal for a spent plan is the synthetic reply "You've hit your session
|
||||
limit · resets 3pm (Europe/Warsaw)" (error rate_limit, HTTP 429), as recorded
|
||||
in real transcripts on 2026-09-26.
|
||||
Claude Code's banners ("5-hour limit reached", "Weekly limit reached") count too.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@ -24,11 +23,7 @@ from typing import Any
|
||||
|
||||
_LOG = logging.getLogger(__name__)
|
||||
|
||||
LIMIT_RE = re.compile(
|
||||
r"hit your (?:\w+ )?limit"
|
||||
r"|(?:usage|session|weekly|daily|opus|sonnet|\d+-hour) limit reached",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
LIMIT_RE = re.compile(r"hit your (?:\w+ )?limit|usage limit reached", re.IGNORECASE)
|
||||
RATE_LIMIT_STATUS = 429
|
||||
|
||||
|
||||
|
||||
@ -1,71 +0,0 @@
|
||||
"""The coach's model chain once Claude is out: OmniRoute ``free-best``, then Ollama.
|
||||
|
||||
kuhy 2026-11-27: on a Claude usage limit the REPL, the relay and the graders go
|
||||
on with the free models through OmniRoute, and with the local Ollama model only
|
||||
when the gateway is down, empty or the prompt too long for it. Each rung is a
|
||||
``chat(messages, timeout=...) -> LocalReply``; any transport error (``OSError``
|
||||
covers ``URLError``, refused connections, timeouts and
|
||||
:class:`~leetcode_coach.omniroute_backend.GatewayError`) or a context overflow
|
||||
moves on to the next. The last rung's error propagates, so the callers' own
|
||||
"model is down" handling stays as it was.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
import logging
|
||||
import time
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from leetcode_coach import local_backend, omniroute_backend
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Sequence
|
||||
|
||||
_LOG = logging.getLogger(__name__)
|
||||
|
||||
|
||||
Rung = Callable[..., local_backend.LocalReply]
|
||||
"""One model of the chain: ``rung(messages, timeout=seconds) -> LocalReply``."""
|
||||
|
||||
|
||||
def chat(
|
||||
messages: list[dict[str, str]],
|
||||
*,
|
||||
timeout: float = omniroute_backend.REQUEST_TIMEOUT_S,
|
||||
rungs: Sequence[Rung] | None = None,
|
||||
on_fallback: Callable[[str], None] | None = None,
|
||||
clock: Callable[[], float] = time.monotonic,
|
||||
) -> local_backend.LocalReply:
|
||||
"""The first rung's reply that comes back; ``on_fallback`` hears each skip.
|
||||
|
||||
``timeout`` bounds the whole chain, not each rung: a rung gets what the
|
||||
ones before it left, so the relay's per-request cap still holds.
|
||||
|
||||
Raises:
|
||||
OSError: every rung's transport failed (the last error).
|
||||
ContextOverflowError: the last rung could not fit the prompt either.
|
||||
"""
|
||||
# Looked up per call, so a test that swaps a backend's `chat` is honoured.
|
||||
chain = (
|
||||
(omniroute_backend.chat, local_backend.chat) if rungs is None else tuple(rungs)
|
||||
)
|
||||
deadline = clock() + timeout
|
||||
for rung in chain[:-1]:
|
||||
try:
|
||||
return rung(messages, timeout=_left(deadline, clock))
|
||||
except (OSError, local_backend.ContextOverflowError) as exc:
|
||||
why = f"omniroute failed ({type(exc).__name__}: {exc}); next model"
|
||||
_LOG.warning("%s", why)
|
||||
if on_fallback is not None:
|
||||
on_fallback(why)
|
||||
return chain[-1](messages, timeout=_left(deadline, clock))
|
||||
|
||||
|
||||
def _left(deadline: float, clock: Callable[[], float]) -> float:
|
||||
"""Seconds until ``deadline``; a ``TimeoutError`` when under one is left."""
|
||||
left = deadline - clock()
|
||||
if left < 1.0:
|
||||
msg = "no time left for another model"
|
||||
raise TimeoutError(msg)
|
||||
return left
|
||||
@ -1,111 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Print kuhy's own submissions on one problem, failed and accepted, with code.
|
||||
|
||||
Usage: history.py <url-or-slug>
|
||||
|
||||
kuhy, 2026-11-22: a Claude coaching a problem "should also have access to my
|
||||
history of approaches", including the ones that succeeded. leetcode-guard's
|
||||
one-minute harvester mirrors every submission (status, time, code) into
|
||||
``~/.local/share/leetcode_guard/history/<slug>.json`` (``_history_store`` in
|
||||
leetcode-guard documents the shape). This reads that mirror, read-only, and
|
||||
prints a bounded summary: the newest :data:`SHOWN` submissions, each code
|
||||
cut at :data:`CODE_CHARS`. The mirror is display-only context and never a
|
||||
gate input; nothing here writes.
|
||||
|
||||
Exit codes: 0 printed (also "no mirror yet" and "unreadable"), 1 bad input.
|
||||
|
||||
Stdlib only and free of package imports, like ``fetch_problem.py``: SKILL.md
|
||||
runs it by path. Its stdout IS its interface (T201 exemption in pyproject.toml).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import sys
|
||||
from typing import Final
|
||||
|
||||
HISTORY_DIR: Final = Path.home() / ".local" / "share" / "leetcode_guard" / "history"
|
||||
SHOWN: Final = 12
|
||||
"""Newest submissions printed; older ones are counted, not shown."""
|
||||
CODE_CHARS: Final = 1500
|
||||
"""Code longer than this is cut: one huge paste must not flood the context."""
|
||||
_ARGC: Final = 2
|
||||
"""argv is the script and one problem."""
|
||||
|
||||
|
||||
def slug_from(arg: str) -> str:
|
||||
"""A full problem URL or a bare slug; anything else raises ``ValueError``."""
|
||||
found = re.search(r"leetcode\.(?:com|cn)/problems/([a-z0-9-]+)", arg)
|
||||
if found:
|
||||
return found.group(1)
|
||||
if re.fullmatch(r"[a-z0-9]+(?:-[a-z0-9]+)*", arg):
|
||||
return arg
|
||||
msg = f"not a LeetCode slug: {arg!r}"
|
||||
raise ValueError(msg)
|
||||
|
||||
|
||||
def _when(raw: object) -> str:
|
||||
"""Unix seconds as a UTC minute, ``?`` when off."""
|
||||
if isinstance(raw, int) and not isinstance(raw, bool):
|
||||
return datetime.fromtimestamp(raw, tz=UTC).strftime("%Y-%m-%d %H:%M UTC")
|
||||
return "?"
|
||||
|
||||
|
||||
def _row(item: dict[str, object]) -> str:
|
||||
"""One submission: a header line and its code block."""
|
||||
stats = ", ".join(str(item.get(key, "?")) for key in ("lang", "runtime", "memory"))
|
||||
head = f"### {item.get('status', '?')} - {_when(item.get('timestamp'))} - {stats}"
|
||||
code = item.get("code")
|
||||
if not isinstance(code, str):
|
||||
return f"{head}\n(code not mirrored yet)"
|
||||
cut = "\n[cut]" if len(code) > CODE_CHARS else ""
|
||||
return f"{head}\n```\n{code[:CODE_CHARS]}{cut}\n```"
|
||||
|
||||
|
||||
def render(arg: str) -> str:
|
||||
"""The summary for one problem, as markdown."""
|
||||
slug = slug_from(arg)
|
||||
path = HISTORY_DIR / f"{slug}.json"
|
||||
if not path.exists():
|
||||
return f"No mirrored submissions for {slug} yet."
|
||||
try:
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
except OSError, ValueError:
|
||||
data = None
|
||||
rows = data.get("submissions") if isinstance(data, dict) else None
|
||||
if not isinstance(rows, list):
|
||||
return f"The submission mirror for {slug} is unreadable."
|
||||
items = [item for item in rows if isinstance(item, dict)]
|
||||
items.sort(key=lambda item: _stamp(item.get("timestamp")), reverse=True)
|
||||
accepted = sum(item.get("status") == "Accepted" for item in items)
|
||||
title = f"{len(items)} submissions ({accepted} accepted)"
|
||||
parts = [f"# kuhy's submissions on {slug}: {title}"]
|
||||
parts += [_row(item) for item in items[:SHOWN]]
|
||||
if len(items) > SHOWN:
|
||||
parts.append(f"({len(items) - SHOWN} older not shown)")
|
||||
return "\n\n".join(parts)
|
||||
|
||||
|
||||
def _stamp(raw: object) -> int:
|
||||
"""A sort key: the timestamp, 0 when off."""
|
||||
return raw if isinstance(raw, int) and not isinstance(raw, bool) else 0
|
||||
|
||||
|
||||
def main() -> int:
|
||||
"""Print the summary for the problem named on argv."""
|
||||
if len(sys.argv) != _ARGC:
|
||||
print("usage: history.py <url-or-slug>", file=sys.stderr)
|
||||
return 1
|
||||
try:
|
||||
print(render(sys.argv[1]))
|
||||
except ValueError as exc:
|
||||
print(str(exc), file=sys.stderr)
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@ -5,11 +5,6 @@
|
||||
# Print mode matters: the no-solution Stop gate can only withhold a reply
|
||||
# from a client that waits for hooks, and the interactive TUI streams first.
|
||||
# leetcode <url-or-slug> [what you are stuck on...]
|
||||
# leetcode --free <url-or-slug> [...] interactive claude-free (OmniRoute
|
||||
# free-best, no Claude quota) with the /leetcode skill, started in
|
||||
# /tmp/leetcode-free: claude-free runs only from a public directory, and
|
||||
# the free providers log prompts, so nothing private is in reach. One
|
||||
# fixed dir, so Claude Code asks to trust it once, not every session.
|
||||
#
|
||||
# Symlinked from ~/.local/bin/leetcode. The package is found through
|
||||
# install.sh's editable install, like the Stop-hook shim; no PYTHONPATH here,
|
||||
@ -19,24 +14,4 @@
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
readonly CLAUDE_FREE="${LEETCODE_CLAUDE_FREE_BIN:-claude-free}"
|
||||
readonly FREE_DIR="${LEETCODE_FREE_DIR:-/tmp/leetcode-free}"
|
||||
|
||||
run_free() {
|
||||
[[ -e "${FREE_DIR}" || -L "${FREE_DIR}" ]] || mkdir -m 700 "${FREE_DIR}"
|
||||
# /tmp is shared: never start in a dir someone else planted there.
|
||||
[[ -O "${FREE_DIR}" && ! -L "${FREE_DIR}" ]] || {
|
||||
echo "leetcode: ${FREE_DIR} is not a directory you own" >&2
|
||||
exit 77
|
||||
}
|
||||
cd "${FREE_DIR}"
|
||||
exec "${CLAUDE_FREE}" "/leetcode $*"
|
||||
}
|
||||
|
||||
if [[ "${1:-}" == --free ]]; then
|
||||
shift
|
||||
[[ $# -gt 0 ]] || { echo "Usage: leetcode --free <url-or-slug> [stuck on...]" >&2; exit 64; }
|
||||
run_free "$@"
|
||||
fi
|
||||
|
||||
exec /usr/bin/python3 -P -m leetcode_coach.leetcode_repl "$@"
|
||||
|
||||
@ -12,10 +12,8 @@ sent before an accepted ``req:`` list is refused here and never reaches the
|
||||
model. Replies lose their ``<!-- rung:Hn -->`` marker (logged) before printing.
|
||||
|
||||
When Claude answers with its usage-limit message (`claude_cli.is_limit_hit`)
|
||||
the session continues on the free models (`local_session.py`, `free=True`:
|
||||
OmniRoute `free-best`, then Ollama) with the conversation so far and the same
|
||||
gate; `--local` starts on Ollama alone. `--free` starts `claude-free` itself
|
||||
(the launcher, from a fresh /tmp dir).
|
||||
the session continues on the local model (`local_session.py`) with the
|
||||
conversation so far and the same gate; `--local` starts there.
|
||||
|
||||
Input: a block ends on an empty line (paste code, then press Enter twice).
|
||||
`quit` or Ctrl-D leaves. `reveal` is passed through like any other message.
|
||||
@ -72,10 +70,8 @@ def run_claude(model: str, problem: list[str]) -> int:
|
||||
opener = local_session.opening_message(problem[1:])
|
||||
first = ask(["--model", model], "/leetcode " + " ".join(problem))
|
||||
if is_limit_hit(first):
|
||||
print(f"[{first.get('result', 'usage limit')} -- switching to the free models]")
|
||||
return local_session.run(
|
||||
problem[0], [], opener, read_block, gate=gate, free=True
|
||||
)
|
||||
print(f"[{first.get('result', 'usage limit')} -- switching to local model]")
|
||||
return local_session.run(problem[0], [], opener, read_block, gate=gate)
|
||||
session = first.get("session_id")
|
||||
print(gate.after_reply(str(first.get("result", ""))))
|
||||
if not session:
|
||||
@ -93,11 +89,8 @@ def run_claude(model: str, problem: list[str]) -> int:
|
||||
print("\n...", flush=True)
|
||||
reply = ask(["--model", model, "--resume", session], sent)
|
||||
if is_limit_hit(reply):
|
||||
why = reply.get("result", "usage limit")
|
||||
print(f"[{why} -- continuing on the free models]")
|
||||
return local_session.run(
|
||||
problem[0], history, sent, read_block, gate=gate, free=True
|
||||
)
|
||||
print(f"[{reply.get('result', 'usage limit')} -- continuing locally]")
|
||||
return local_session.run(problem[0], history, sent, read_block, gate=gate)
|
||||
print(gate.after_reply(str(reply.get("result", ""))))
|
||||
history += [
|
||||
{"role": "user", "content": sent},
|
||||
@ -124,7 +117,6 @@ def main(argv: list[str]) -> int:
|
||||
print("Usage: leetcode [--local] <url-or-slug> [what you are stuck on...]")
|
||||
print(" LEETCODE_MODEL=sonnet|fable leetcode ... (default: opus)")
|
||||
print(" --local coach on the local Ollama model (free, offline)")
|
||||
print(" --free interactive claude-free (OmniRoute free models), from /tmp")
|
||||
print(" leetcode due | --cluster <name> | --retest <slug> (--dry-run)")
|
||||
print(" leetcode report req-before-code, max rung, reveal per problem")
|
||||
return 0
|
||||
|
||||
@ -49,10 +49,6 @@ class LocalReply:
|
||||
text: str
|
||||
seconds: float
|
||||
prompt_tokens: int
|
||||
via: str = "ollama"
|
||||
"""Which rung answered: ``ollama`` or ``omniroute`` (``free_chain``)."""
|
||||
model: str = MODEL
|
||||
"""The model that answered (an OmniRoute ``free-best`` member's own name)."""
|
||||
|
||||
|
||||
def strip_think(text: str) -> str:
|
||||
|
||||
@ -1,12 +1,9 @@
|
||||
"""Run a /leetcode coaching loop without Claude.
|
||||
"""Run a /leetcode coaching loop on the local model.
|
||||
|
||||
Entered by `leetcode --local` (Ollama only), or by the REPL mid-session when
|
||||
Claude reports a usage limit (`free=True`: OmniRoute `free-best` first, Ollama
|
||||
only when the gateway fails, `free_chain`) -- in which case `history` already
|
||||
holds the turns so far, so the model picks up where Claude stopped instead of
|
||||
starting over. Every draft passes the same no-solution gate
|
||||
(`local_coach.respond`). Its prints ARE the session (T201 exemption in
|
||||
pyproject.toml).
|
||||
Entered by `leetcode --local`, or by the REPL mid-session when Claude reports a
|
||||
usage limit -- in which case `history` already holds the turns so far, so the
|
||||
local model picks up where Claude stopped instead of starting over. Its prints
|
||||
ARE the session (T201 exemption in pyproject.toml).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@ -17,13 +14,7 @@ import sys
|
||||
from typing import TYPE_CHECKING
|
||||
import urllib.error
|
||||
|
||||
from leetcode_coach import (
|
||||
free_chain,
|
||||
local_backend,
|
||||
local_cards,
|
||||
local_coach,
|
||||
omniroute_backend,
|
||||
)
|
||||
from leetcode_coach import local_backend, local_cards, local_coach
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
@ -130,80 +121,15 @@ def _screen(gate: phase.PhaseGate | None, block: str) -> str | None:
|
||||
return sent
|
||||
|
||||
|
||||
class GpuRefusedError(ConnectionError):
|
||||
"""kuhy declined to load the local model: the chain has no rung left."""
|
||||
|
||||
|
||||
class OllamaAfterGpuCheck:
|
||||
"""The free chain's last rung: Ollama, once kuhy agrees to load it (asked once)."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
"""Nothing asked yet."""
|
||||
self.agreed = False
|
||||
|
||||
def __call__(
|
||||
self, messages: list[dict[str, str]], *, timeout: float
|
||||
) -> local_backend.LocalReply:
|
||||
"""Announce the fall-through, check the GPU once, then ask Ollama."""
|
||||
if not self.agreed:
|
||||
print(f"[OmniRoute down: local {local_backend.MODEL} via Ollama]")
|
||||
if not confirm_gpu():
|
||||
print("[not loading the local model]")
|
||||
msg = "local model declined"
|
||||
raise GpuRefusedError(msg)
|
||||
self.agreed = True
|
||||
return local_backend.chat(messages, timeout=timeout)
|
||||
|
||||
|
||||
def free_chat(
|
||||
rung: OllamaAfterGpuCheck,
|
||||
) -> Callable[[list[dict[str, str]]], local_backend.LocalReply]:
|
||||
"""One session's chat: OmniRoute, then ``rung``."""
|
||||
|
||||
def chat(messages: list[dict[str, str]]) -> local_backend.LocalReply:
|
||||
return free_chain.chat(messages, rungs=(omniroute_backend.chat, rung))
|
||||
|
||||
return chat
|
||||
|
||||
|
||||
def _coach(
|
||||
statement: str,
|
||||
history: list[dict[str, str]],
|
||||
gate: phase.PhaseGate | None,
|
||||
*,
|
||||
free: bool,
|
||||
) -> local_coach.LocalCoach | None:
|
||||
"""The coach, announced; ``None`` when kuhy declines the local model."""
|
||||
if not free and not confirm_gpu():
|
||||
print("[not loading the local model]")
|
||||
return None
|
||||
coach = local_coach.LocalCoach.start(statement, history)
|
||||
if free:
|
||||
coach.chat = free_chat(OllamaAfterGpuCheck())
|
||||
if gate is not None:
|
||||
gate.known = statement
|
||||
coach.leak_guard = gate.leaks
|
||||
label = (
|
||||
f"free: {omniroute_backend.MODEL} via OmniRoute"
|
||||
if free
|
||||
else f"local: {local_backend.MODEL} via Ollama"
|
||||
)
|
||||
print(f"[{label}]\n\n...", flush=True)
|
||||
return coach
|
||||
|
||||
|
||||
def run(
|
||||
problem: str,
|
||||
history: list[dict[str, str]],
|
||||
first: str,
|
||||
read: Callable[[], str | None],
|
||||
gate: phase.PhaseGate | None = None,
|
||||
*,
|
||||
free: bool = False,
|
||||
) -> int:
|
||||
"""Coach without Claude until kuhy quits. `first` is sent before reading input.
|
||||
"""Coach locally until kuhy quits. `first` is sent before reading input.
|
||||
|
||||
`free` (the usage-limit hand-over) coaches on OmniRoute first, Ollama after.
|
||||
With a `gate`, every block passes the req-before-code phase gate first and
|
||||
every reply the toolbox leak check (`first` was screened by the caller).
|
||||
"""
|
||||
@ -211,18 +137,20 @@ def run(
|
||||
if not statement:
|
||||
return 1
|
||||
try:
|
||||
coach = _coach(statement, history, gate, free=free)
|
||||
if coach is None:
|
||||
if not confirm_gpu():
|
||||
print("[not loading the local model]")
|
||||
return 1
|
||||
coach = local_coach.LocalCoach.start(statement, history)
|
||||
if gate is not None:
|
||||
gate.known = statement
|
||||
coach.leak_guard = gate.leaks
|
||||
print(f"[local: {local_backend.MODEL} via Ollama]\n\n...", flush=True)
|
||||
show(coach.respond(first), coach, gate)
|
||||
while (block := read()) is not None and not is_quit(block):
|
||||
if (sent := _screen(gate, block)) is None:
|
||||
continue
|
||||
print("\n...", flush=True)
|
||||
show(coach.respond(sent), coach, gate)
|
||||
except GpuRefusedError:
|
||||
print("[neither OmniRoute nor Ollama answered: try again later]")
|
||||
return 1
|
||||
except (urllib.error.URLError, ConnectionError) as exc:
|
||||
_LOG.warning("Ollama is not reachable: %s", exc)
|
||||
print(f"[Ollama is not reachable at {local_backend.OLLAMA_URL}: {exc}]")
|
||||
|
||||
@ -1,131 +0,0 @@
|
||||
"""OmniRoute transport for the /leetcode coach: the free models, after Claude.
|
||||
|
||||
When Claude reports a usage limit the coach goes on with OmniRoute's
|
||||
``free-best`` chain (kuhy 2026-11-27), and with Ollama only if the gateway is
|
||||
down (``free_chain``). One non-streaming OpenAI ``/v1/chat/completions`` call
|
||||
per reply, so the no-solution gate in ``local_coach`` judges the whole draft
|
||||
before anything reaches the screen, exactly as for Ollama.
|
||||
|
||||
The gateway is local (docker ``omniroute`` on 127.0.0.1:20128); a non-loopback
|
||||
URL is refused. The free providers behind it log prompts: the coach's prompts
|
||||
carry the problem and kuhy's attempts and nothing else (kuhy accepted that).
|
||||
An empty answer (``content: null`` from a reasoning member, an empty choice
|
||||
list) is a :class:`GatewayError`, so the chain falls through instead of
|
||||
showing nothing.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import time
|
||||
from typing import TYPE_CHECKING, Any, Final
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
from leetcode_coach import local_backend
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
|
||||
DEFAULT_URL: Final = "http://127.0.0.1:20128"
|
||||
URL_ENV: Final = "LEETCODE_OMNIROUTE_URL"
|
||||
"""Overrides :data:`DEFAULT_URL` (a test's fake gateway, a dead port)."""
|
||||
KEY_FILE = Path.home() / ".config" / "omniroute" / "api_key"
|
||||
MODEL: Final = "free-best"
|
||||
MAX_TOKENS: Final = 4000
|
||||
"""Reasoning members spend small budgets on thinking and return nothing."""
|
||||
CONTEXT_TOKENS: Final = 32768
|
||||
"""The combo's prompt limit; a longer prompt would be cut silently."""
|
||||
TEMPERATURE: Final = 0.4
|
||||
REQUEST_TIMEOUT_S: Final = 120.0
|
||||
_LOOPBACK: Final = frozenset({"127.0.0.1", "localhost", "::1"})
|
||||
|
||||
|
||||
class GatewayError(ConnectionError):
|
||||
"""The gateway answered nothing usable; the chain moves to the next rung."""
|
||||
|
||||
|
||||
def gateway_url() -> str:
|
||||
"""The gateway base URL, read at call time."""
|
||||
return os.environ.get(URL_ENV) or DEFAULT_URL
|
||||
|
||||
|
||||
def read_key(path: Path | None = None) -> str:
|
||||
"""The gateway's Bearer key (never printed)."""
|
||||
try:
|
||||
return (path or KEY_FILE).read_text(encoding="utf-8").strip()
|
||||
except OSError as exc:
|
||||
msg = f"OmniRoute key unreadable: {exc}"
|
||||
raise GatewayError(msg) from exc
|
||||
|
||||
|
||||
def http_json(
|
||||
url: str,
|
||||
payload: dict[str, Any],
|
||||
timeout: float,
|
||||
*,
|
||||
key_file: Path | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""POST ``payload`` with the Bearer key to the local gateway; decode the JSON."""
|
||||
host = urllib.parse.urlsplit(url).hostname or ""
|
||||
if not url.startswith("http://") or host not in _LOOPBACK:
|
||||
msg = f"refusing a non-loopback gateway URL: {url}"
|
||||
raise ValueError(msg)
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
data=json.dumps(payload).encode(),
|
||||
headers={
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": f"Bearer {read_key(key_file)}",
|
||||
},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
||||
answer: dict[str, Any] = json.loads(resp.read().decode())
|
||||
return answer
|
||||
|
||||
|
||||
def _content(data: dict[str, Any]) -> str:
|
||||
"""The first choice's text, or ``""``."""
|
||||
choices = data.get("choices") or [{}]
|
||||
message = choices[0].get("message") or {}
|
||||
return str(message.get("content") or "")
|
||||
|
||||
|
||||
def chat(
|
||||
messages: list[dict[str, str]],
|
||||
*,
|
||||
post: Callable[[str, dict[str, Any], float], dict[str, Any]] = http_json,
|
||||
clock: Callable[[], float] = time.monotonic,
|
||||
timeout: float = REQUEST_TIMEOUT_S,
|
||||
) -> local_backend.LocalReply:
|
||||
"""Ask ``free-best`` for the next assistant message.
|
||||
|
||||
Raises:
|
||||
ContextOverflowError: the prompt would not fit the combo's limit.
|
||||
GatewayError: the gateway answered no text.
|
||||
"""
|
||||
if local_backend.estimate_tokens(messages) >= CONTEXT_TOKENS:
|
||||
msg = f"conversation too long for the gateway ({CONTEXT_TOKENS} tokens)"
|
||||
raise local_backend.ContextOverflowError(msg)
|
||||
payload = {
|
||||
"model": MODEL,
|
||||
"messages": messages,
|
||||
"stream": False,
|
||||
"max_tokens": MAX_TOKENS,
|
||||
"temperature": TEMPERATURE,
|
||||
}
|
||||
start = clock()
|
||||
data = post(f"{gateway_url()}/v1/chat/completions", payload, timeout)
|
||||
text = local_backend.strip_think(_content(data))
|
||||
if not text:
|
||||
msg = f"{MODEL} answered no text"
|
||||
raise GatewayError(msg)
|
||||
return local_backend.LocalReply(
|
||||
text=text,
|
||||
seconds=clock() - start,
|
||||
prompt_tokens=int((data.get("usage") or {}).get("prompt_tokens") or 0),
|
||||
via="omniroute",
|
||||
model=str(data.get("model") or MODEL),
|
||||
)
|
||||
@ -23,13 +23,7 @@ import time
|
||||
from typing import TYPE_CHECKING, Any, Final
|
||||
import urllib.error
|
||||
|
||||
from leetcode_coach import (
|
||||
claude_cli,
|
||||
free_chain,
|
||||
local_backend,
|
||||
local_cards,
|
||||
local_coach,
|
||||
)
|
||||
from leetcode_coach import claude_cli, local_backend, local_cards, local_coach
|
||||
from leetcode_coach.relay.errors import CoachError
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@ -66,9 +60,9 @@ class CoachChat:
|
||||
def __init__(
|
||||
self,
|
||||
ask: Callable[..., dict[str, Any]] = claude_cli.ask,
|
||||
local_chat: Callable[..., local_backend.LocalReply] = free_chain.chat,
|
||||
local_chat: Callable[..., local_backend.LocalReply] = local_backend.chat,
|
||||
) -> None:
|
||||
"""Bind the claude call and the free chain (OmniRoute, then Ollama)."""
|
||||
"""Bind the claude call and the local model (both injectable)."""
|
||||
self._ask = ask
|
||||
self._local_chat = local_chat
|
||||
self.monotonic: Callable[[], float] = time.monotonic
|
||||
|
||||
@ -16,7 +16,7 @@ import logging
|
||||
import threading
|
||||
from typing import TYPE_CHECKING, Any, Final
|
||||
|
||||
from leetcode_coach import answer_key, claude_cli, free_chain, local_backend, toolbox
|
||||
from leetcode_coach import answer_key, claude_cli, local_backend, toolbox
|
||||
from leetcode_coach.relay import config, grading, protocol, runcode, steps, turns
|
||||
from leetcode_coach.relay.chat import REQUEST_CAP_S, CoachChat
|
||||
from leetcode_coach.relay.errors import CoachError
|
||||
@ -45,7 +45,7 @@ class Deps:
|
||||
|
||||
state_dir: Path = field(default_factory=config.state_dir)
|
||||
ask: Callable[..., dict[str, Any]] = claude_cli.ask
|
||||
local_chat: Callable[..., local_backend.LocalReply] = free_chain.chat
|
||||
local_chat: Callable[..., local_backend.LocalReply] = local_backend.chat
|
||||
fetch: Callable[[str], tuple[str, str] | None] = turns.fetch_statement
|
||||
probe: AcceptedProbe = field(default_factory=AcceptedProbe)
|
||||
run_code: Callable[[str, str], dict[str, Any]] = runcode.run
|
||||
|
||||
@ -1,10 +1,9 @@
|
||||
"""Judge kuhy's requirement list, and ambiguous code, on a cheap model.
|
||||
|
||||
DOCS-coach-spec.md decision 5: a separate ``claude -p --model haiku`` call (the
|
||||
coaching session stays on opus), the free chain (`free_chain`: OmniRoute
|
||||
`free-best`, then Ollama) when haiku is out of quota, errors or answers
|
||||
something that is not the JSON asked for, and when neither answers the gate
|
||||
fails OPEN: ``unverified``, kuhy continues.
|
||||
coaching session stays on opus), Ollama through `local_backend` when haiku
|
||||
is out of quota, errors or answers something that is not the JSON asked for,
|
||||
and when neither answers the gate fails OPEN: ``unverified``, kuhy continues.
|
||||
|
||||
The checker may only name *missing properties* from the toolbox vocabulary.
|
||||
That is enforced here, not trusted to the prompt: every ``missing`` item that
|
||||
@ -26,7 +25,7 @@ import logging
|
||||
from typing import TYPE_CHECKING, Any
|
||||
import urllib.error
|
||||
|
||||
from leetcode_coach import claude_cli, free_chain, local_backend
|
||||
from leetcode_coach import claude_cli, local_backend
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
@ -37,8 +36,7 @@ _LOG = logging.getLogger(__name__)
|
||||
|
||||
HAIKU_TIMEOUT_S = 50.0
|
||||
LOCAL_TIMEOUT_S = 200.0
|
||||
"""The free chain's share of a check (both rungs together, ``free_chain``):
|
||||
with haiku's 50 s it fits the relay's 280 s cap."""
|
||||
"""Ollama's share of a check: with haiku's 50 s it fits the relay's 280 s cap."""
|
||||
HAIKU_ARGS = [
|
||||
"--model",
|
||||
"haiku",
|
||||
@ -177,7 +175,7 @@ def ask_models[T](
|
||||
ask: Callable[..., dict[str, Any]] | None,
|
||||
schema: dict[str, Any] | None = None,
|
||||
) -> tuple[T, str] | None:
|
||||
"""The first validated answer and who gave it, then the free chain.
|
||||
"""The first validated answer and who gave it, then Ollama.
|
||||
|
||||
`ask` is the CLI-style ``(args, prompt, **kw)`` (default: haiku) or a
|
||||
structured ``(system, prompt, schema) -> dict`` model function.
|
||||
@ -191,7 +189,7 @@ def ask_models[T](
|
||||
if got is not None:
|
||||
return got, via
|
||||
try:
|
||||
local = free_chain.chat(
|
||||
local = local_backend.chat(
|
||||
[
|
||||
{"role": "system", "content": system},
|
||||
{"role": "user", "content": prompt},
|
||||
@ -199,10 +197,10 @@ def ask_models[T](
|
||||
timeout=LOCAL_TIMEOUT_S,
|
||||
)
|
||||
except (urllib.error.URLError, OSError, local_backend.ContextOverflowError) as exc:
|
||||
_LOG.warning("the free models could not answer the check either: %s", exc)
|
||||
_LOG.warning("Ollama could not answer the check either: %s", exc)
|
||||
return None
|
||||
got = validate(extract_json(local.text))
|
||||
return None if got is None else (got, local.via)
|
||||
return None if got is None else (got, "ollama")
|
||||
|
||||
|
||||
def check(
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user