Compare commits

..

10 Commits

Author SHA1 Message Date
d45b1086c3 focus_project: update_project, v0.3.0
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
earned_time pre-commit / pre-commit (push) Waiting to run
earned_time tests / test (push) Waiting to run
file length / file-length (push) Waiting to run
focus-project pre-commit / pre-commit (push) Waiting to run
focus-project tests / test (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
palette drift / palette (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
shared gate tests / gate unit tests (push) Waiting to run
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWYcmik6APnHfc9gEVy
2026-11-02 08:34:32 +01:00
8398ca4823 earned_time 0.19.0: focus project earner
earners_for swaps a focus project's replaced gates for one focus earner
paid per minute from the focus ledger (floor of summed minutes). The gaming
cut equals what the replaced penalised gates cost, so a project day is
neutral; maturity never delays it. An unusable focus_project means no
project (logged once).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWYcmik6APnHfc9gEVy
2026-11-02 08:23:50 +01:00
087ed1c400 pylint TODO: trim to the two repos left
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-02 08:20:39 +01:00
e852e3ce48 focus_project: isolate tracker env, v0.2.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWYcmik6APnHfc9gEVy
2026-11-02 08:19:30 +01:00
6d80efb50a focus_project: minutes, ledger, harvester
Fail-closed: a failing source logs and adds 0 minutes;
a bad key, ledger or registry exits 1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWYcmik6APnHfc9gEVy
2026-11-02 08:19:01 +01:00
cbcee98d94 Add structural_check: spacing/radius/type/motion drift
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-02 08:18:27 +01:00
82119bdd47 Drop motion-tokens twin; shipped (DOCS-motion)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-02 08:18:19 +01:00
d666e47e16 Merge remote-tracking branch 'origin/main' 2026-11-02 08:18:05 +01:00
8a3076783e focus_project: browser source adapter
Reads kuhytrack window+AFK buckets. Tracker down: 0 min.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWYcmik6APnHfc9gEVy
2026-11-02 08:17:46 +01:00
5d11f97093 Drop dufs theme twin; dufs-cloud copy gone
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-02 08:17:34 +01:00
47 changed files with 2836 additions and 746 deletions

View File

@ -31,3 +31,8 @@ jobs:
- name: Categorical ramp still passes its constraints
run: python3 unified-design-system/scripts/ramp_check.py
# Spacing, radius, type, shadow and motion: palette_check.py parses
# hex only, so these scales were unguarded until structural_check.py.
- name: Structural scales agree across all token sources
run: python3 unified-design-system/scripts/structural_check.py

View File

@ -4,89 +4,32 @@ REMOVE ME AFTER FINISH
## what
Ten pylint hooks across six repos still pass at `--fail-under=8.0`, which
permanently tolerates two points of lint debt and lets a score *regress* from
9.9 to 8.1 without failing anything. Move every one to `10`, and fix what
that surfaces. Five other sites already run at `10`, so this is adopting an
existing standard, not inventing one.
Two pylint hooks (`leetcode-guard`, `steam-backlog-enforcer`) still pass at
`--fail-under=8.0`, which permanently tolerates two points of lint debt and
lets a score *regress* from 9.9 to 8.1 without failing anything. Move both to
`10`, and fix what that surfaces. Every other site already runs at `10`, so
this is adopting an existing standard, not inventing one.
## the ten sites, exact
## what is left (updated 2026-11-02)
Measured 2026-09-12. "Score now" is that package's current rating under its
own config, tests included.
Done and verified (`pre-commit run pylint --all-files`, exit 0, each at
`--fail-under=10`): `control-panel`, `screen-locker` (both hooks),
`testsAndMisc/meta`, `utils/crdt-sync`, `utils/freedays`, `utils/gatelock`,
`utils/music_theory`.
| Repo / package | Site | Score now |
|---|---|---|
| `control-panel` | `.pre-commit-config.yaml:159` | 8.53 |
| `leetcode-guard` | `.pre-commit-config.yaml:112` | 8.71 |
| `screen-locker` | `.pre-commit-config.yaml:121` | 9.85 |
| `screen-locker` | `.pre-commit-config.yaml:140` | (2nd pylint hook) |
| `steam-backlog-enforcer` | `.pre-commit-config.yaml:124` | 8.76 |
| `testsAndMisc/meta` | `.pre-commit-config.yaml:194` | 8.77 |
| `utils/crdt-sync` | `.pre-commit-config.yaml:111` | 9.59 |
| `utils/freedays` | `.pre-commit-config.yaml:109` | 8.55 |
| `utils/gatelock` | `.pre-commit-config.yaml:109` | 9.18 |
| `utils/music_theory` | `.pre-commit-config.yaml:113` | 8.54 |
Still at `--fail-under=8.0`:
`screen-locker` has **two** pylint hooks; both need the bump or the second one
silently keeps the old bar.
| Repo | Site |
|---|---|
| `leetcode-guard` | `.pre-commit-config.yaml:126` |
| `steam-backlog-enforcer` | `.pre-commit-config.yaml:126` (ignore its `.claude/worktrees/` copies) |
Already at `10` — do not touch, these are the reference:
`build-your-x`, `diet-guard`, `testsAndMisc` (root config),
`wake-alarm`, `WUT_Computer_Science/.../translator/.pylintrc`.
## why the scores look bad, and why that is misleading
Every one of these configs runs `enable = "all"` with `disable = []` — the
strictest pylint setting there is, including checks that are off by default.
The raw findings are dominated by **test-file idioms**, not source defects.
Measured on the four `utils` packages:
```
crdt-sync 54 protected-access, 50 redefined-outer-name, 18 duplicate-code
freedays 100 missing-function-docstring, 14 implicit-booleaness
gatelock 147 redefined-outer-name, 142 protected-access
music_theory 112 missing-function-docstring, 14 missing-module-docstring
```
`redefined-outer-name` at that volume is pytest fixtures. `protected-access`
is tests reaching into internals on purpose. Neither is a defect.
**The repos already at 10 solved this and wrote down why.** From
`wake-alarm/pyproject.toml`, verbatim:
> `ignore = [".venv", "__pycache__", "tests"]` — "tests" is a basename match:
> test suites intentionally use patterns (protected-access, magic-value
> comparisons) that don't apply to source code, matching testsAndMisc's
> pylint scope (tests are linted by ruff, not pylint there either).
So the fleet standard is: **pylint grades source, ruff grades tests.** The ten
sites above are the outliers that never adopted it. Their `ruff` config
already carries the equivalent test exemptions
(`"**/tests/**/*.py" = ["ARG", "D", "PLC0415", "PLR2004", "S101", "SLF001"]`),
so tests stay linted — by the tool that has the right rules for them.
## what is actually left after adopting the fleet config
Measured: `pylint --ignore=.venv,__pycache__,tests` plus wake-alarm's
three-item `disable` list, run over source files only.
| Package | Score | Remaining findings |
|---|---|---|
| `crdt-sync` | 9.93 | 5 wrong-import-position, 3 duplicate-code, 1 too-many-locals, 1 invalid-name |
| `freedays` | 9.63 | 3 import-error, 1 broad-exception-caught |
| `gatelock` | 9.88 | 6 missing-function-docstring, 4 wrong-import-position, 3 too-many-instance-attributes, 3 import-outside-toplevel, 2 broad-exception-caught, 1 each too-many-arguments / invalid-name / duplicate-code / disallowed-name / chained-comparison |
| `music_theory` | 9.42 | 10 import-error |
That is ~47 real findings across four packages, not the ~600 the raw run
suggests. **`import-error` is almost certainly config, not code**: every repo
already at 10 carries an `init-hook` the 8.0 repos lack —
```toml
init-hook = "import sys; sys.path.insert(0, '.')"
```
Try that first on `music_theory` and `freedays` before editing any import.
Both live outside `utils`, so this file belongs to whichever session works
those repos. The method is the fleet standard: pylint grades source, ruff
grades tests. Copy the `[tool.pylint]` block (tests basename ignore,
`init-hook = "import sys; sys.path.insert(0, '.')"`) from `wake-alarm` /
`diet-guard`, bump to `10`, fix the residue in source. Read the `must`
rules below first.
## must
@ -110,15 +53,12 @@ Both commands, from `~`:
```bash
# 1. no site left below 10 (cov-fail-under is coverage, not pylint)
! grep -rn --include=.pre-commit-config.yaml --include=.pylintrc \
! grep -rn --exclude-dir=worktrees --include=.pre-commit-config.yaml --include=.pylintrc \
-E 'fail-under=(8|9)' ~/src ~/praca_magisterska 2>/dev/null \
| grep -v cov-fail-under
# 2. every one of the nine packages passes its own pylint hook
for d in ~/src/control-panel ~/src/leetcode-guard ~/src/screen-locker \
~/src/steam-backlog-enforcer ~/src/testsAndMisc/meta \
~/src/utils/crdt-sync ~/src/utils/freedays \
~/src/utils/gatelock ~/src/utils/music_theory; do
# 2. both remaining packages pass its own pylint hook
for d in ~/src/leetcode-guard ~/src/steam-backlog-enforcer; do
(cd "$d" && pre-commit run pylint --all-files) || echo "FAIL $d"
done
```

View File

@ -1,140 +0,0 @@
Add motion, haptic and sound tokens to the unified design system
## findings (3, ranked by value over effort)
1. **No motion token exists in any stack** — greenfield. Every app that wants an
animation currently invents its own number, and one already has.
2. **No haptic vocabulary exists** — the highest-value gap, because
`HapticFeedback` needs no dependency, so three of four apps can adopt it
the day this lands.
3. **`tokens.md` is 260 lines against a 250 cap** — it cannot absorb a new
section, so motion needs a sibling file.
## what
The shared design system has colour, spacing, radius, type and shadow tokens —
and **no motion tokens at all**. Verified 2026-08-16: no `Duration`, `Curve`,
`--duration-*`, `--ease-*`, or haptic constant exists in any stack copy. There is
not even a prose position that motion is out of scope.
Consequence across kuhy's Flutter fleet: **exactly one animation exists in four
apps** — a lone `AnimatedContainer(duration: Duration(milliseconds: 200))` with an
inline magic number. Every other transition is a Flutter/browser default.
Create the motion token layer so the per-app prompts (03–09) have something
canonical to consume instead of each inventing durations.
## where
Repo: `~/src/utils` (git repo, has CI + the file-length gate wired).
**Create** `~/src/utils/unified-design-system/motion.md` — the prose freeze.
**Do NOT append to `~/src/utils/unified-design-system/tokens.md`.** It is 260 lines
and the cap is 250, so it already fails the gate; adding to it makes that worse.
`screen-size.md` was split out of it for exactly this reason — follow that
precedent and add a pointer line in `tokens.md` only if you can do so without
growing it (i.e. by shortening another line).
Then mirror the tokens into the three code stacks:
| Stack | File | Form |
|---|---|---|
| Flutter/Dart | `~/src/utils/design_system/lib/src/tokens.dart` | `class AppDuration` / `class AppCurve` |
| web/React | `~/src/utils/web_ui/src/tokens.css` | `--duration-*`, `--ease-*` custom props |
| Python/Tkinter | `~/src/utils/gatelock/gatelock/_window.py` (`class LockConfig`) | int ms fields — **only if meaningful**; see `must not` |
There are **three** code stacks plus the prose freeze. Do not go hunting for a
fourth — it does not exist.
## must
- Define a **small** scale. Recommended, but use judgement:
`instant 0ms · fast 120ms · base 200ms · slow 320ms`, and easing
`standard (0.2, 0, 0, 1)` · `decelerate (0, 0, 0, 1)` · `accelerate (0.3, 0, 1, 1)`.
Justify each value in `motion.md` in one line — the file is a freeze, so the
reasoning has to survive without you.
- Include a **haptic** vocabulary mapped to Flutter's `HapticFeedback` API:
which semantic event gets `selectionClick` vs `lightImpact` vs `mediumImpact`.
This is the highest-value part — `HapticFeedback` needs no dependency, so
three of four apps can adopt it immediately.
- Include a **sound** vocabulary: named semantic cues (`confirm`, `complete`,
`error`) with the rule that sound ships **on** (opt-out) per app, and that
each app owns its own asset files.
- State the reduced-motion contract in `motion.md`: web uses
`@media (prefers-reduced-motion: reduce)`, Flutter uses
`MediaQuery.of(context).disableAnimations`. Motion tokens collapse to `0ms`
under it; **haptics and sound are unaffected** (they are not motion).
- Keep every file at or under **250 lines** (`~/src/utils/file_length/config.py`,
`MAX_LINES = 250`). `.md` and `.py` are capped; `.css` is not.
- **Cut tags at the end** — this is the step that makes the work reach consumers:
- `design_system-v0.2.0` (consumed by `~/src/todo`, currently on `v0.1.0`)
- `web_ui-v0.3.2` (consumed by `~/src/dufs-cloud/web`, currently on `v0.3.1`)
Print both tag names at the end of the session; prompts 06, 07 and 08 need them.
- must not: add motion values to the Tkinter `LockConfig` just for symmetry.
Tkinter has no animation framework. If a duration has no meaning there, mark
the row `n/a (tk)` in `motion.md` and leave the Python alone. An honest `n/a`
beats a dead constant.
- must not: express any motion token as a hex-looking value. The existing
`palette_check.py` parses `#RRGGBB` and would either ignore it or trip on it.
- must not: touch any colour token, or add a colour alongside the motion work.
That *would* break `palette_check.py`'s completeness half.
- must not: add `# noqa` or `type: ignore` anywhere.
- optional: a `prefers-reduced-motion` helper in
`~/src/utils/design_system/lib/src/` and/or `web_ui/src/` so consumers get the
collapse behaviour without reimplementing it. Nice, not required.
## done
All four hold:
1. `~/src/utils/unified-design-system/motion.md` exists, is ≤250 lines, and defines
duration, easing, haptic and sound vocabularies with a one-line rationale each.
2. `python3 ~/src/utils/file_length/check.py` (or
`~/src/utils/scripts/check_file_length.sh --all`) reports **no new** violations.
`tokens.md` (260), `nielsen-audit.md` (258) and `README.md` (257) are
pre-existing failures — do not fix them here, but do not add a fourth.
3. `python3 ~/src/utils/unified-design-system/scripts/palette_check.py` still exits 0.
4. Both tags exist: `git -C ~/src/utils tag | grep -E 'design_system-v0.2.0|web_ui-v0.3.2'`
prints two lines.
## verify
Desktop, any way you like — this prompt ships no UI. Run the two gate commands in
`done` and paste their output. Then confirm the token names you chose are what
prompts 03–09 will reference by printing the Dart class and the CSS custom-prop
block.
## read first
- `~/src/utils/unified-design-system/tokens.md` — the existing freeze; match its
table format and tone exactly. Note its length problem before editing.
- `~/src/utils/unified-design-system/screen-size.md` — the precedent for a sibling
file split out of `tokens.md` (32 lines; short and self-contained).
- `~/src/utils/design_system/lib/src/tokens.dart` — `AppPalette`, `AppSpacing`,
`AppRadius`, `AppTextSize`. Your `AppDuration`/`AppCurve` sit alongside these.
- `~/src/utils/web_ui/src/tokens.css` — the full custom-prop list.
- `~/src/utils/design_system/lib/src/feedback.dart` — `showToast`/`showError` and
`_show`. `confirm.dart` next to it **already imports
`package:flutter/services.dart`**, so `HapticFeedback` is one call away with no
new import. This is the natural home for a shared haptic helper.
- `~/src/utils/unified-design-system/scripts/palette_check.py` — read the four
`parse_*` regexes to see why motion tokens are invisible to it. Prompt 02
builds the checker that covers them; **do not extend this script here.**
## context you would otherwise rediscover
- **Green CI does not mean no drift for these tokens.** `palette_check.py` only
matches `#RRGGBB`, so a `--duration-fast: 120ms` is invisible to every one of
its parsers. `palette_map.py:159` claims structural values are "checked by the
scale check" — **no such script exists**. Prompt 02 writes it.
- `~/src/utils/gatelock/` is a package inside the `~/src/utils` monorepo, not a
standalone repo. It is consumed as a pinned git dependency.
- Only `~/src/todo` depends on `design_system`; diet-guard, workout_app and
wake_alarm hand-transcribe the token values into local `lib/ui/theme.dart`
copies. So tokens added here reach exactly one app automatically — the others
are handled per-prompt.
REMOVE ME AFTER FINISH

View File

@ -1,139 +0,0 @@
Add a structural-token drift checker to CI
## findings (2, ranked by value over effort)
1. **Spacing, radius and type have never been drift-checked** — `palette_check.py`
parses hex only, so three whole token categories can diverge across stacks
while CI stays green. Motion inherits the same hole.
2. **`palette_map.py` points at a "scale check" that does not exist** — a
comment describing a guarantee nobody wrote.
## what
`palette_check.py` guarantees the colour palette agrees across all stack copies.
It does **not** check anything else — verified 2026-08-16 by reading its four
parsers, every one of which requires a `#RRGGBB` value:
```python
parse_css : r"(--[a-z0-9-]+)\s*:\s*(#[0-9A-Fa-f]{6})\s*;"
parse_dart: r"static const Color (\w+) = Color\(0x[fF]{2}([0-9A-Fa-f]{6})\)"
parse_tk : r'^\s{4}(\w+):\s*str\s*=\s*"(#[0-9A-Fa-f]{6})"'
parse_md : r"^\|\s*`([a-z0-9-]+)`\s*\|\s*`(#[0-9A-Fa-f]{6})`"
```
So **spacing, radius and type have been silently unprotected all along**, and the
motion tokens added by prompt 01 inherit the same hole. A `--duration-fast: 120ms`
is invisible to every parser: CI passes while the stacks drift apart.
Worse, `scripts/palette_map.py:159` claims structural values are "checked by the
scale check" — **no such script exists anywhere in `~/src/utils`**. That comment
describes a check that was never written. This prompt writes it.
## where
Repo: `~/src/utils`.
**Create** `~/src/utils/unified-design-system/scripts/structural_check.py`.
**Edit** `~/src/utils/.github/workflows/palette-drift.yml` — add a step invoking it.
The workflow deliberately has no `paths:` filter; keep it that way.
**Fix** the stale comment at `~/src/utils/unified-design-system/scripts/palette_map.py`
(~:159) to name the real script.
Sources to compare (three code stacks + the prose freeze):
| Role | Path |
|---|---|
| prose freeze | `~/src/utils/unified-design-system/tokens.md` (spacing/radius/type) |
| motion freeze | `~/src/utils/unified-design-system/motion.md` (**created by prompt 01** — run it first) |
| web/React | `~/src/utils/web_ui/src/tokens.css` |
| Flutter/Dart | `~/src/utils/design_system/lib/src/tokens.dart` |
| Python/Tkinter | `~/src/utils/gatelock/gatelock/_window.py` (`class LockConfig`) |
## must
- Cover **motion** (durations, easing) **and** the already-unprotected
**spacing, radius and type** scales, in one checker.
- Mirror `palette_check.py`'s two-halves design, because it is the part that
actually works:
1. **Agreement** — for each mapped token, resolve it in every non-`n/a` stack
and fail if values disagree.
2. **Completeness, bidirectional** — every structural value parsed out of any
source must be mapped, or explicitly exempted. This is what catches
"added it to one stack, forgot the others".
- Support an explicit **`n/a` per stack**, and require a reason string. Tkinter
has no animation framework; a duration legitimately does not exist there. An
honest `n/a` with a reason is correct — a fabricated constant is not.
- **Adjudicate with exit codes.** Exit non-zero on drift with a message naming
the token and the disagreeing files. No warnings-only mode.
- Keep every file ≤ **250 lines** (`~/src/utils/file_length/config.py`). Note
`palette_check.py` is 231 and `palette_map.py` is 162 — that pair was split
precisely to stay under the cap. **Split yours the same way from the start**
(`structural_check.py` + `structural_map.py`) rather than discovering the
problem at 251 lines.
- Ruff-clean under the repo's config. No `# noqa`, no `type: ignore`.
- **Expect it to fail on first run.** Spacing/radius/type have never been
compared; there may be real pre-existing drift. That is the point of writing
it. Fix whatever it surfaces, in the stack copy that is wrong, and say in the
session summary what drifted.
- must not: weaken the checker, add an exemption, or narrow its scope to make it
green. If a token genuinely differs per stack for a good reason, encode it as
an `n/a`/variant **with the reason recorded**, not as a silent skip.
- must not: modify `palette_check.py`. It works; it is simply colour-only. The
two scripts run side by side.
- must not: change any token *value* to resolve a disagreement without saying so
explicitly — that is a design change, and `tokens.md` is a freeze. Surface it
and let kuhy decide which value is canonical.
- optional: teach it the shadow tier too, if that falls out cheaply.
## done
1. `python3 ~/src/utils/unified-design-system/scripts/structural_check.py` exits 0,
and exits non-zero when you deliberately break one stack copy (**test both
directions** — a checker that never fails is not a checker).
2. It is wired into `~/src/utils/.github/workflows/palette-drift.yml` and the
workflow passes.
3. `palette_map.py`'s "scale check" comment names the real script.
4. `~/src/utils/scripts/check_file_length.sh --all` reports no new violations.
5. The session summary states what drift, if any, the first run found.
## verify
Desktop. Run the script, paste the output. Then prove it fails: change one
spacing or duration value in **one** stack copy, re-run, paste the non-zero exit
and the message, and revert. Both halves of that demonstration are required —
the passing run alone proves nothing.
## read first
- `~/src/utils/unified-design-system/scripts/palette_check.py` — the design to
mirror. Read `NON_COLOUR_CSS`: it is the regex that currently *excludes*
spacing/radius/type/shadow from the colour check, and therefore the precise
list of what you are now covering.
- `~/src/utils/unified-design-system/scripts/palette_map.py` — the `PALETTE` tuple of
`Token(canonical, md, css, dart, tk, why)` rows. Your map wants the same shape,
including the `why` field.
- `~/src/utils/.github/workflows/palette-drift.yml` — how `palette_check.py` and
`ramp_check.py` are invoked; add your step alongside.
- `~/src/utils/unified-design-system/motion.md` — what prompt 01 created.
- `~/src/utils/unified-design-system/tokens.md` — the spacing/radius/type tables.
**Do not edit it**; it is 260 lines and already over the cap.
## context you would otherwise rediscover
- The four "stack copies" are really **three code stacks plus a prose freeze**.
There is no fourth code stack; do not hunt for one.
- `~/src/dufs-cloud/app/lib/ui/theme.dart` is a **fifth, uncompared copy** of the
palette (the Flutter app has no `design_system` dependency and hand-restates
every hex). It is out of scope here — prompt 07 wires it up properly. Do not
add it as a source to this checker; wait until 07 has removed it.
- Three Flutter apps (diet-guard, workout_app, wake_alarm) similarly
hand-transcribe tokens into local `lib/ui/theme.dart` files. Those are
deliberately outside the checker's scope for now — bringing them in is a much
larger job than this prompt.
- `~/src/utils/gatelock/` is a package inside this monorepo, not a separate repo.
REMOVE ME AFTER FINISH

View File

@ -1,141 +0,0 @@
Wire dufs-cloud's Flutter app to the shared design_system
## findings (2, ranked by value over effort)
1. **`app/lib/ui/theme.dart` is a fifth, uncompared palette copy** — hand-copied
hexes that `palette_check.py` has never seen, so it can drift silently while
CI stays green.
2. **The web half of the same repo is wired correctly** — which makes the
Flutter half's divergence an accident, not a decision.
## what
`~/src/dufs-cloud/app/lib/ui/theme.dart` is a **fifth, uncompared copy of the
palette**. Verified 2026-08-16: the Flutter app has no `design_system`
dependency at all — it hand-restates every hex (`Color(0xFF211D1B) // ink`,
`Color(0xFFB8862E) // accent`, …) with the shared token names appearing only in
comments. `palette_check.py` has never seen this file, so it can drift from the
frozen table silently and CI will stay green.
The web half of the same repo is wired correctly (`@kuhyx/web-ui`), which makes
the Flutter half's divergence an accident rather than a decision.
Fix the root cause: add the dependency, replace the hand-copied hexes with token
references, and delete the duplicate. This must land **before** prompt 08 adds
motion to this app, so that motion tokens arrive through the package instead of
becoming a sixth hand-copy.
## where
Repo: `~/src/dufs-cloud`. Flutter app: `~/src/dufs-cloud/app` (package `dufs_client`).
- `app/pubspec.yaml` — current deps: `archive, cupertino_icons, flutter,
flutter_secure_storage, http, image_picker, media_kit*, path, path_provider,
share_plus, shared_preferences, webview_flutter, xml`. **No `design_system`.**
- `app/lib/ui/theme.dart` — the hand-copy to eliminate.
- Every file referencing a colour from it — find them with a grep for the theme's
exported symbols rather than trusting any list here.
Source of truth:
- `~/src/utils/design_system/lib/src/tokens.dart` — `AppPalette`, `AppSpacing`,
`AppRadius`, `AppTextSize` (plus `AppDuration`/`AppCurve` if prompt 01 ran).
- `~/src/utils/design_system/lib/src/theme.dart` — `buildLightTheme()`,
`buildDarkTheme()`.
Reference implementation: `~/src/todo` is the only app already on the package. Its
`pubspec.yaml` uses a **git ref** (`design_system-v0.1.0`) and it has
deliberately **no local `theme.dart`**. Copy that shape.
## must
- Add `design_system` to `app/pubspec.yaml` using the **git ref** style matching
`~/src/todo` — not a local `path:` dependency. One dependency convention across the
fleet. Pin the tag prompt 01 cut (`design_system-v0.2.0` or whatever it
printed); if prompt 01 has not run, pin `design_system-v0.1.0` and let prompt
08 do the bump.
- Replace every hand-copied hex in `app/lib/ui/theme.dart` with the corresponding
token reference. **Verify each swap is value-identical before making it** — the
survey found the values byte-identical today, but confirm rather than assume;
a silent colour change in a live app is a real regression.
- Delete the duplicated token declarations once nothing references them. If the
app declares helper classes the shared package lacks, keep only those, and say
in the session summary which ones survived and why.
- Keep the app's visual output **identical**. This is a pure de-duplication: if
anything looks different afterwards, a value was wrong and you have found a
pre-existing drift — report it rather than papering over it.
- must not: change any colour, spacing, radius or type **value**. The shared
table is a freeze. If a value genuinely disagrees, stop and surface it — that
is a finding, and kuhy decides which side is canonical.
- must not: add motion/animation here. That is prompt 08. This prompt is
dependency plumbing only, so that a visual regression has exactly one possible
cause.
- must not: touch `~/src/dufs-cloud/web/` — its `@kuhyx/web-ui` wiring is already
correct.
- must not: leave a partial migration. Either the local theme file is gone (or
reduced to app-specific extras) and everything resolves through the package, or
the change is not done. A half-migrated theme is worse than the current state
because it hides *which* copy is authoritative.
- optional: once migrated, add `app/lib/ui/theme.dart`'s path to the structural
checker from prompt 02 if that is now meaningful. Probably it is not — after
this prompt there is nothing left there to compare.
## done
1. `app/pubspec.yaml` declares `design_system` at a git ref; `flutter pub get`
resolves.
2. No hard-coded palette hex remains in `app/lib/`. A grep for `Color(0xFF` in
`app/lib/ui/theme.dart` returns nothing (or only app-specific values that are
not palette tokens — name them if so).
3. `cd ~/src/dufs-cloud/app && flutter analyze` is clean.
4. `cd ~/src/dufs-cloud/app && flutter test` passes.
5. The app looks **the same** as before on device — verified by screenshot
comparison, not by reasoning about the diff.
6. `python3 ~/src/utils/unified-design-system/scripts/palette_check.py` still exits 0.
## verify
**On the phone**, and with a before/after comparison — a pure refactor is only
verified by showing nothing changed.
```
adb devices
cd ~/src/dufs-cloud/app
flutter build apk --release
adb install -r build/app/outputs/flutter-apk/app-release.apk
```
Take a screenshot of the browser screen and the settings screen **before**
starting (from the currently installed build) and after, and compare them. Never
`adb uninstall` or `pm clear` — the app holds a stored credential
(`flutter_secure_storage`) and wiping it means re-authenticating.
## read first
- `~/src/dufs-cloud/app/lib/ui/theme.dart` — in full, before touching anything. The
comments naming each token are your mapping table.
- `~/src/todo/pubspec.yaml` — the git-ref dependency line to copy, and the comment
explaining why no local theme exists.
- `~/src/utils/design_system/lib/src/tokens.dart` — the canonical names.
- `~/src/dufs-cloud/DESIGN_AUDIT_TODO.md` — a prior audit of this repo; check whether
it already records theme findings so you do not contradict it.
## context you would otherwise rediscover
- The web half consumes `@kuhyx/web-ui` at tag **`web_ui-v0.3.1`**, declared in
`~/src/dufs-cloud/web/package.json` as
`"github:kuhyx/utils#web_ui-v0.3.1&path:/web_ui"`. It is correctly wired; the
only app-local CSS value is `--overlay: rgba(33, 29, 27, 0.82)` in
`web/src/index.css`. Prompt 08 bumps that tag — not this prompt.
- `@kuhyx/web-ui` is **pnpm-only**; npm cannot install a monorepo subdirectory.
Irrelevant here (this prompt is Flutter-only) but fatal if you wander into
`web/`.
- `palette_check.py` compares four sources and has never included this file, so
"CI is green" told you nothing about it. That is the whole reason this prompt
exists.
- Three other Flutter apps (diet-guard, workout_app, wake_alarm) have the same
hand-copy pattern. They are **out of scope** — migrating them is a separate,
larger job, and doing one app properly is the point here.
REMOVE ME AFTER FINISH

View File

@ -168,17 +168,14 @@ How far to trust a gate is computed from its ledger, never listed by name:
- `done_today(earner, ledger, key_file, *, now=None) -> bool | None`
- `first_credit_at(earner, ledger, key_file, day) -> float | None` — unix time
of the earliest verified credit for `day`, on its matcher's stamp
(`_match.CREDIT_STAMPS`; Anki/Automation: `created_at`). It can lie outside
`day` (Anki's rollover, a rest day declared the evening before).
- `credit_units(earner, ledger, key_file, day) -> int | None` — the units
the verified rows pay for `day`: 1 per row (the workout), or the row's own
count (the tutor's `detail.minutes`, legacy block rows 15; from 0.10.0 the
day's sum scaled to its weekday quota). A repeated `entry_id` pays once,
its smallest count; `max_units` is applied by `resolve`.
(`_match.CREDIT_STAMPS`; else `created_at`); it can lie outside `day`.
- `credit_units(earner, ledger, key_file, day) -> int | None` — the units the
verified rows pay for `day`: 1 per row (the workout), or the row's own count
(`detail.minutes`: tutor, legacy blocks 15, from 0.10.0 scaled to its weekday
quota; focus). A repeated `entry_id` pays once; `resolve` applies `max_units`.
- `earners_for(day)`, `all_earners()`, `registries()` — the registry in force
on a day, and every earner of every registry (what a ledger watcher must
watch). They read `earned_time.EARNERS` through the package, so a consumer
test that patches it still registers its stand-in.
watch). They read `earned_time.EARNERS` through the package, so a patch holds.
- `shutdown_minutes_for(earner, day)`, `extra_shutdown_minutes_for(earner, day)`,
`shutdown_ceiling_for(day)` (ints), `on_ladder(day) -> bool` — what a status
view lists as still left to earn. `Earner.shutdown_for(units, day=None)` is
@ -187,14 +184,21 @@ How far to trust a gate is computed from its ledger, never listed by name:
## The workout ledger
`WORKOUT` is `kind="counted"` with a ledger at
`~/.local/share/workout_locker/ledger.json`, written by screen-locker: one
signed credit row per credited unit,
`{"kind": "credit", "entry_id", "day", "detail": {"completed_at", "source"}}`.
`workout_match` counts a `runnerup_tcx` row when `completed_at` falls in the
window, and a `rest_day` row on the `day` it names — only if
`detail.declared_at` is before that day's local midnight. A rest day declared
on the day itself is logged and does not count.
`WORKOUT` is `kind="counted"`, ledger `~/.local/share/workout_locker/ledger.json`
(screen-locker; one signed credit row per unit, `detail.completed_at`/`source`).
`workout_match` counts a `runnerup_tcx` row by `completed_at`, a `rest_day` row
on its `day` only if `detail.declared_at` predates that day (else logged, no).
## The focus project (0.19.0)
While `focus_project.active(day)` returns a project, `earners_for` drops the
gates it `replaces` (`book` = `reading`) and adds one counted `focus` earner
(`max_units` = `daily_minutes`) paying what they paid (shutdown by their rungs,
gaming by `max_gaming_minutes`: 60+60+60 over 120 min = 1.5/min):
`floor(summed minutes * pay / daily_minutes)`, never per row. The penalty runs
from the start day, cutting what the replaced gates cost; maturity never delays it. Ledger `~/.local/share/focus_project/ledger.json`:
signed `credit` rows, `entry_id` `<project>-<YYYYMMDD>-m<n>`, `detail.minutes` (positive int),
`detail.ended_at` (else `day`). `focus_project` unusable = no project (logged).
## Adding a gate
@ -208,43 +212,39 @@ on the day itself is logged and does not count.
```python
PIANO = Earner(
name="piano", # also screen-locker's "piano_bonus_date" stamp
label="piano",
gaming_minutes=30,
shutdown_minutes=30, # pre-ladder value
penalty_from=date(2026, 11, 1), # gaming base drops by 30 from then on
ledger=".local/share/piano_guard/ledger.json",
match=piano_match, # which verified credit rows count today
missing_ledger_is_no=True,
)
```
Then give it a rung in `TUTOR_LADDER` (`PIANO.name: Rung(20)`), and, if its
matcher decides on an event stamp, an entry in `_match.CREDIT_STAMPS`.
Then a rung in `TUTOR_LADDER` (`PIANO.name: Rung(20)`) and, for an event
stamp, an entry in `_match.CREDIT_STAMPS`.
On the ladder a new earner's rung comes out of the floor from its penalty
start (a pure bonus: the day its pin lands; the ceiling is fixed): re-split
the rungs and ship it the day the gate can actually be satisfied.
3. Bump the version, tag `earned-time-vX.Y.Z`, and bump the pin in both
consumers. Neither needs code for a ledger-backed flat earner.
A new rung comes out of the floor from its penalty start (a pure bonus:
the day its pin lands): ship it the day the gate can be satisfied.
3. Bump, tag `earned-time-vX.Y.Z`, re-pin every consumer (no code needed).
## Rules the consumers rely on
- **Minutes everywhere.** Shutdown is minutes after local midnight.
- **Paths are passed in.** No reader resolves a real path itself, except the
switch file: consumer tests patch `earned_time._leisure.LEISURE_FROM_PATH`.
- **Paths are passed in.** Only the switch file is resolved here
(patch `earned_time._leisure.LEISURE_FROM_PATH`).
- **`None` is "could not check", never "no".** It earns nothing (fail closed),
but consumers log it. A missing answer in `resolve()` is logged as well; an
unknown earner name raises.
- **The HMAC key is root-owned and 0644 on purpose.** User-run gates must sign
rows, so the user reads it; root owns it so no user process can replace it.
It stops casual edits and corruption, not a determined forger with a shell.
- **Stdlib only.** The gaming daemon imports this as root, headless.
- **The HMAC key is root 0644 on purpose.** User-run gates sign rows with it;
it stops casual edits, not a determined forger with a shell.
- **Stdlib only.** The root gaming daemon imports this headless; `focus_project`
(stdlib too) is imported lazily and may be absent.
## Install
```console
pip install --user --break-system-packages --no-deps "earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.18.0#subdirectory=earned_time"
pip install --user --break-system-packages --no-deps "earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.19.0#subdirectory=earned_time"
```
The root `steam-backlog-enforcer.service` sets `HOME=/home/kuhy`, so it imports
from the same user site-packages. Test: `scripts/run_subproject_tests.sh earned_time`.
The root `steam-backlog-enforcer.service` sets `HOME=/home/kuhy` and imports from
the same user site-packages. Test: `scripts/run_subproject_tests.sh earned_time`.

View File

@ -43,6 +43,7 @@ from earned_time._credits import (
first_credit_at,
)
from earned_time._evidence import real_credit
from earned_time._focus import FOCUS_LEDGER, FocusEarner
from earned_time._ladder import (
ANKI_WAIVED_FROM,
LADDER,
@ -105,6 +106,7 @@ __all__ = [
"ANKI_WAIVED_FROM",
"AUTOMATION",
"EARNERS",
"FOCUS_LEDGER",
"GAMING_BASE_MINUTES",
"GAMING_CEILING_MINUTES",
"LADDER",
@ -132,6 +134,7 @@ __all__ = [
"WORKOUT",
"Base",
"Earner",
"FocusEarner",
"Level",
"Maturity",
"Resolution",

View File

@ -20,6 +20,7 @@ from pathlib import Path
import sys
from typing import TYPE_CHECKING, Final
from earned_time._focus import FOCUS_WATCH
from earned_time._maturity import Maturity, maturity
from earned_time._registry import all_earners, earners_for
@ -57,9 +58,14 @@ def _gates(day: date) -> list[tuple[str, Earner, Maturity]]:
and after ``TUTOR_FROM`` until 0.9.0); those get their ledger's directory
appended.
"""
earners = [e for e in all_earners() if e.ledger is not None]
names = Counter(e.name for e in earners)
registered = earners_for(day)
earners = [
e
for e in (*all_earners(), *registered)
if e.ledger is not None and e is not FOCUS_WATCH
]
earners = list(dict.fromkeys(earners))
names = Counter(e.name for e in earners)
gates = []
for item in earners:
ledger = Path(str(item.ledger))

View File

@ -0,0 +1,109 @@
# Copyright (c) 2026 Krzysztof Rudnicki
"""The focus project (0.19.0): replaced gates stand down, one earner pays."""
from __future__ import annotations
from dataclasses import dataclass
from datetime import date, timedelta
import importlib
import logging
from typing import Any, Final
from earned_time._ladder import shutdown_units_minutes
from earned_time._match import focus_match
from earned_time._policy import Earner
__all__ = [
"FOCUS_LEDGER",
"FOCUS_WATCH",
"FocusEarner",
"focus_earner",
"with_focus",
]
FOCUS_LEDGER: Final = ".local/share/focus_project/ledger.json"
_SYNONYMS: Final = {"book": "reading"}
_logger: Final = logging.getLogger(__name__)
_warned: set[str] = set()
@dataclass(frozen=True)
class FocusEarner(Earner):
"""Counted; ``gaming_minutes``/``shutdown_minutes`` pay a FULL day.
``cut_gaming_minutes``: the base cut, what the replaced penalised gates cost.
"""
cut_gaming_minutes: int = 0
def gaming_for(self, units: int) -> int:
"""Gaming minutes of ``units`` focused minutes, floored."""
return self.capped(units) * self.gaming_minutes // (self.max_units or 1)
def shutdown_for(
self,
units: int,
day: date | None = None, # noqa: ARG002
) -> int:
"""Shutdown minutes of ``units`` focused minutes, floored."""
return self.capped(units) * self.shutdown_minutes // (self.max_units or 1)
def _active(day: date) -> Any: # noqa: ANN401
"""The active project on ``day``; ``None`` for none or on any failure."""
try:
return importlib.import_module("focus_project").active(day)
except Exception as exc: # noqa: BLE001 # pylint: disable=broad-exception-caught
message = f"focus_project unusable ({type(exc).__name__}: {exc})"
if message not in _warned:
_warned.add(message)
_logger.warning("%s; behaving as if no project is active", message)
return None
def focus_earner(project: Any, dropped: tuple[Earner, ...], day: date) -> Earner: # noqa: ANN401
"""The ``focus`` earner paying what ``dropped`` paid, over ``project``."""
return FocusEarner(
name="focus",
label="Focus",
gaming_minutes=sum(e.max_gaming_minutes for e in dropped),
cut_gaming_minutes=sum(
e.max_gaming_minutes for e in dropped if e.penalty_from is not None
),
shutdown_minutes=sum(
shutdown_units_minutes(e, e.max_units or 1, day) for e in dropped
),
kind="counted",
max_units=int(project.daily_minutes),
penalty_from=project.start,
confirmed_on=project.start - timedelta(days=1),
ledger=FOCUS_LEDGER,
match=focus_match,
missing_ledger_is_no=True,
)
FOCUS_WATCH: Final = FocusEarner(
name="focus",
label="Focus",
gaming_minutes=0,
shutdown_minutes=0,
kind="counted",
max_units=1,
ledger=FOCUS_LEDGER,
match=focus_match,
missing_ledger_is_no=True,
)
def with_focus(registry: tuple[Earner, ...], day: date) -> tuple[Earner, ...]:
"""``registry`` reshaped by the active project; unchanged if none."""
project = _active(day)
if project is None:
return registry
gates = {_SYNONYMS.get(g, g) for g in project.replaces}
dropped = tuple(e for e in registry if e.name in gates)
if not dropped or int(project.daily_minutes) < 1:
return registry
kept = tuple(e for e in registry if e not in dropped)
return (*kept, focus_earner(project, dropped, day))

View File

@ -156,13 +156,15 @@ def shutdown_minutes_for(item: Earner, day: date) -> int:
without a rung, its own ``shutdown_minutes``.
"""
rung = _rung(item, day)
return item.shutdown_minutes if rung is None else rung.first
return item.shutdown_for(1, day) if rung is None else rung.first
def extra_shutdown_minutes_for(item: Earner, day: date) -> int:
"""What ``item``'s second unit earns on ``day`` (counted only)."""
rung = _rung(item, day)
return item.extra_shutdown_minutes if rung is None else rung.second
if rung is not None:
return rung.second
return item.shutdown_for(2, day) - item.shutdown_for(1, day)
def shutdown_units_minutes(item: Earner, units: int, day: date) -> int:

View File

@ -167,6 +167,30 @@ def tutor_match(row: dict[str, object], window: Window) -> bool:
return landed
def focus_minutes(row: dict[str, object]) -> int | None:
"""Minutes a focus row pays: ``detail.minutes``, a positive int, else ``None``."""
detail = row.get("detail")
raw = detail.get("minutes") if isinstance(detail, dict) else None
if isinstance(raw, bool) or not isinstance(raw, int) or raw < 1:
return None
return raw
def focus_match(row: dict[str, object], window: Window) -> bool:
"""A focus credit counts on the day of ``detail.ended_at``, else its ``day``."""
if focus_minutes(row) is None:
_logger.warning("focus credit %r has bad minutes", row.get("entry_id"))
return False
detail = row.get("detail")
landed = _within(
detail.get("ended_at") if isinstance(detail, dict) else None, window
)
if landed is not None:
return landed
local = datetime.fromtimestamp(window[0], tz=UTC).astimezone()
return row.get("day") == local.date().isoformat()
# The ``detail`` field each matcher decides on: the unix second the work
# happened, which :func:`earned_time._credits.credit_time` reports. A matcher
# without one (Anki's day key) falls back to the row's ``created_at``.
@ -176,6 +200,7 @@ CREDIT_STAMPS: Final[Mapping[CreditMatch, str]] = MappingProxyType(
reading_match: "ended_at",
workout_match: "completed_at",
tutor_match: "ended_at",
focus_match: "ended_at",
}
)
# How many units one counting row pays, per matcher; a matcher without an
@ -183,7 +208,7 @@ CREDIT_STAMPS: Final[Mapping[CreditMatch, str]] = MappingProxyType(
# count (``detail.minutes``): book-guard's ``detail.minutes`` is a string
# and means something else, so this is never read generically.
ROW_UNITS: Final[Mapping[CreditMatch, Callable[[dict[str, object]], int | None]]] = (
MappingProxyType({tutor_match: tutor_minutes})
MappingProxyType({tutor_match: tutor_minutes, focus_match: focus_minutes})
)
# Which ledger row kinds each matcher is shown; a matcher without an entry
# sees only ``credit`` rows. LeetCode also sees ``charge`` rows, so a day

View File

@ -31,6 +31,7 @@ from datetime import UTC, date, datetime, timedelta
from typing import TYPE_CHECKING, Final, Literal
from earned_time._evidence import credit_history
from earned_time._focus import FocusEarner
if TYPE_CHECKING:
from pathlib import Path
@ -100,11 +101,12 @@ def penalty_start(earner: Earner, first_credit: date | None) -> date | None:
(never paid out, or could not check): :func:`confirmed_start` when kuhy
set ``confirmed_on`` -- fail closed, deleting a ledger lifts nothing --
else ``None``, not penalised. ``None`` for a pure bonus. Never earlier
than ``penalty_from``.
than ``penalty_from``. A focus earner is never delayed: its first credit
comes on the day its penalty starts (0.19.0).
"""
start = confirmed_start(earner)
if start is None:
return None
if start is None or isinstance(earner, FocusEarner):
return start
if first_credit is None:
return start if earner.confirmed_on is not None else None
return max(start, first_credit + _DAY)

View File

@ -14,6 +14,7 @@ from functools import cache
import sys
from typing import TYPE_CHECKING, Final
from earned_time._focus import FOCUS_WATCH, with_focus
from earned_time._ladder import ANKI_WAIVED_FROM, TUTOR_FROM
if TYPE_CHECKING:
@ -38,12 +39,14 @@ def earners_for(day: date | None = None) -> tuple[Earner, ...]:
"""The registry in force on ``day`` (default today).
Between ``ANKI_WAIVED_FROM`` and ``TUTOR_FROM`` the old registry without
Anki and the anki-backed Automation: neither penalised nor paid.
Anki and the anki-backed Automation: neither penalised nor paid. From
``TUTOR_FROM`` an active focus project swaps its replaced earners for one
``focus`` earner (:mod:`earned_time._focus`, 0.19.0).
"""
target = day or datetime.now(tz=UTC).astimezone().date()
before, tutor = registries()
if target >= TUTOR_FROM:
return tutor
return with_focus(tutor, target)
if target >= ANKI_WAIVED_FROM:
return _without_waived(before)
return before
@ -64,4 +67,5 @@ def all_earners() -> tuple[Earner, ...]:
seen: dict[Earner, None] = {}
for registry in registries():
seen.update(dict.fromkeys(registry))
seen[FOCUS_WATCH] = None
return tuple(seen)

View File

@ -25,6 +25,7 @@ from datetime import UTC, date, datetime
import logging
from typing import TYPE_CHECKING, Final
from earned_time._focus import FocusEarner
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
@ -45,6 +46,16 @@ def _today() -> date:
return datetime.now(tz=UTC).astimezone().date()
def _gaming_cut(item: Earner) -> int:
"""The gaming base cut of a penalised earner: what it can pay.
A focus earner cuts only what the gates it replaced cost (LeetCode's was free).
"""
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:
@ -117,7 +128,7 @@ def _base(
penalised = [e for e in registry if _penalised(e, target, first_credits)]
return Base(
gaming_minutes=base_minutes(leisure=on)
- sum(e.max_gaming_minutes for e in penalised),
- sum(_gaming_cut(e) for e in penalised),
shutdown_minutes=_shutdown_floor(target, registry, penalised),
)

View File

@ -3,6 +3,8 @@
from __future__ import annotations
import sys
from types import SimpleNamespace
from typing import TYPE_CHECKING
import pytest
@ -21,6 +23,14 @@ def _no_real_switch_file(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Non
)
@pytest.fixture(autouse=True)
def _no_real_focus_project(monkeypatch: pytest.MonkeyPatch) -> None:
"""Never read the real projects.json: no project is active unless a test says."""
monkeypatch.setitem(
sys.modules, "focus_project", SimpleNamespace(active=lambda _day: None)
)
@pytest.fixture
def key_file(tmp_path: Path) -> Path:
"""The test HMAC key, written where a test can point ``maturity`` at it."""

View File

@ -0,0 +1,248 @@
# Copyright (c) 2026 Krzysztof Rudnicki
"""The focus project earner: registry swap, pay, rounding, penalty, fail mode."""
from __future__ import annotations
from datetime import date, timedelta
import logging
import sys
from types import SimpleNamespace
from typing import TYPE_CHECKING
import pytest
import earned_time
from earned_time import (
TUTOR_EARNERS,
FocusEarner,
all_earners,
credit_units,
earners_for,
extra_shutdown_minutes_for,
maturity,
penalty_start,
resolve,
shutdown_minutes_for,
)
from earned_time._focus import focus_earner
from earned_time._match import focus_match, focus_minutes
from earned_time.tests._maturity_rows import at, ledger_file, signed
if TYPE_CHECKING:
from pathlib import Path
START = date(2026, 11, 2)
DAY = START + timedelta(days=1)
def project(**changes: object) -> SimpleNamespace:
"""A fake ``focus_project.Project`` (the contract's fields)."""
fields: dict[str, object] = {
"start": START,
"end": START + timedelta(days=3),
"replaces": ("leetcode", "reading", "tutor"),
"daily_minutes": 120,
}
return SimpleNamespace(**{**fields, **changes})
def activate(monkeypatch: pytest.MonkeyPatch, active: object) -> None:
"""Make ``focus_project.active`` return ``active`` on project days only."""
def on(day: date) -> object:
return active if START <= day <= START + timedelta(days=3) else None
monkeypatch.setitem(sys.modules, "focus_project", SimpleNamespace(active=on))
def row(
minutes: object, n: int, day: date = DAY, **detail: object
) -> dict[str, object]:
"""A signed focus credit row ending at noon on ``day``."""
return signed(
{
"kind": "credit",
"entry_id": f"hr-{day:%Y%m%d}-m{n}",
"day": day.isoformat(),
"detail": {"minutes": minutes, "ended_at": at(day), **detail},
}
)
def focus(monkeypatch: pytest.MonkeyPatch, **changes: object) -> FocusEarner:
"""Today's focus earner under a fake project."""
activate(monkeypatch, project(**changes))
(found,) = (e for e in earners_for(DAY) if e.name == "focus")
assert isinstance(found, FocusEarner)
return found
def test_the_replaced_gates_leave_and_focus_joins(
monkeypatch: pytest.MonkeyPatch,
) -> None:
activate(monkeypatch, project())
assert [e.name for e in earners_for(DAY)] == ["workout", "focus"]
assert earners_for(START - timedelta(days=1)) is TUTOR_EARNERS
assert earners_for(START + timedelta(days=4)) is TUTOR_EARNERS
def test_book_is_a_synonym_and_unreplaced_gates_stay(
monkeypatch: pytest.MonkeyPatch,
) -> None:
activate(monkeypatch, project(replaces=("book",)))
assert [e.name for e in earners_for(DAY)] == [
"workout",
"leetcode",
"tutor",
"focus",
]
item = earners_for(DAY)[-1]
assert (item.gaming_minutes, item.shutdown_minutes) == (60, 60)
@pytest.mark.parametrize(
"changes", [{"replaces": ("anki",)}, {"replaces": ()}, {"daily_minutes": 0}]
)
def test_a_project_that_changes_nothing_leaves_the_registry(
monkeypatch: pytest.MonkeyPatch, changes: dict[str, object]
) -> None:
activate(monkeypatch, project(**changes))
assert earners_for(DAY) is TUTOR_EARNERS
def test_a_full_day_pays_what_the_replaced_gates_paid(
monkeypatch: pytest.MonkeyPatch,
) -> None:
item = focus(monkeypatch)
assert item.max_units == 120
assert (item.gaming_for(120), item.shutdown_for(120, DAY)) == (180, 180)
assert (item.gaming_for(999), item.shutdown_for(999, DAY)) == (180, 180)
assert (item.max_gaming_minutes, item.gaming_for(-5)) == (180, 0)
def test_pay_is_floored_on_the_summed_minutes(monkeypatch: pytest.MonkeyPatch) -> None:
item = focus(monkeypatch)
assert [item.gaming_for(n) for n in (1, 2, 3, 7)] == [1, 3, 4, 10]
assert [item.shutdown_for(n, DAY) for n in (1, 2, 3, 7)] == [1, 3, 4, 10]
def test_many_small_rows_pay_what_one_row_pays(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, key_file: Path
) -> None:
item = focus(monkeypatch)
many = ledger_file(tmp_path, [row(1, n) for n in range(1, 8)])
one = tmp_path / "one.json"
one.write_text(ledger_file(tmp_path, [row(7, 7)]).read_text(encoding="utf-8"))
units = credit_units(item, many, key_file, DAY)
assert units == credit_units(item, one, key_file, DAY) == 7
assert item.gaming_for(units or 0) == 10
def test_resolve_prices_base_terms_and_ceiling(monkeypatch: pytest.MonkeyPatch) -> None:
activate(monkeypatch, project())
nothing = resolve({"workout": 0, "focus": 0}, DAY, leisure=False)
assert nothing.base.gaming_minutes == 300 - 120
assert nothing.base.shutdown_minutes == 18 * 60
half = resolve({"workout": 0, "focus": 60}, DAY, leisure=False)
assert half.gaming_minutes == 180 + 90
assert half.shutdown_minutes == 18 * 60 + 90
full = resolve({"workout": 1, "focus": 120}, DAY, leisure=False)
assert full.shutdown_minutes == 23 * 60
def test_a_project_day_is_neutral_against_the_gates_it_replaced(
monkeypatch: pytest.MonkeyPatch,
) -> None:
activate(monkeypatch, project())
zero = {"workout": 0, "leetcode": 0, "reading": 0, "tutor": 0, "focus": 0}
done = {"workout": 1, "leetcode": 1, "reading": 1, "tutor": 60, "focus": 120}
for answers in (zero, done):
old = resolve(answers, DAY, TUTOR_EARNERS, leisure=False)
new = resolve(answers, DAY, leisure=False)
assert (new.gaming_minutes, new.shutdown_minutes) == (
old.gaming_minutes,
old.shutdown_minutes,
)
def test_the_penalty_is_not_delayed_by_the_first_credit(
monkeypatch: pytest.MonkeyPatch,
) -> None:
item = focus(monkeypatch)
assert penalty_start(item, START) == penalty_start(item, None) == START
answers = {"workout": 0, "focus": 0}
plain = resolve(answers, START, leisure=False)
paid = resolve(answers, START, first_credits={"focus": START}, leisure=False)
assert paid.base == plain.base
assert plain.base.gaming_minutes == 300 - 120
def test_maturity_reads_the_focus_ledger(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, key_file: Path
) -> None:
item = focus(monkeypatch)
ledger = ledger_file(tmp_path, [row(30, 30, START), row(30, 60, START)])
found = maturity(item, ledger, key_file, DAY)
assert (found.first_credit, found.penalty_start) == (START, START)
def test_the_first_and_second_minute_follow_the_floor(
monkeypatch: pytest.MonkeyPatch,
) -> None:
item = focus(monkeypatch)
assert shutdown_minutes_for(item, DAY) == 1
assert extra_shutdown_minutes_for(item, DAY) == 2
assert shutdown_minutes_for(earned_time.ANKI, date(2026, 10, 9)) == 30
assert extra_shutdown_minutes_for(earned_time.ANKI, date(2026, 10, 9)) == 0
def test_the_path_unit_watches_the_focus_ledger() -> None:
assert earned_time.FOCUS_LEDGER in {e.ledger for e in all_earners()}
def test_focus_pays_only_replaced_gates_that_exist() -> None:
item = focus_earner(project(), (earned_time.LEETCODE,), DAY)
assert (item.gaming_minutes, item.shutdown_minutes) == (60, 60)
@pytest.mark.parametrize("failure", [ImportError("gone"), ValueError("bad json")])
def test_a_broken_focus_project_means_no_project_and_logs_once(
monkeypatch: pytest.MonkeyPatch,
caplog: pytest.LogCaptureFixture,
failure: Exception,
) -> None:
def broken(_day: date) -> object:
raise failure
monkeypatch.setitem(sys.modules, "focus_project", SimpleNamespace(active=broken))
monkeypatch.setattr("earned_time._focus._warned", set())
with caplog.at_level(logging.WARNING):
assert earners_for(DAY) is TUTOR_EARNERS
assert earners_for(DAY) is TUTOR_EARNERS
assert sum("behaving as if no project" in m for m in caplog.messages) == 1
def test_a_missing_package_is_no_project(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setitem(sys.modules, "focus_project", None)
assert earners_for(DAY) is TUTOR_EARNERS
def test_rows_count_by_ended_at_then_by_day(caplog: pytest.LogCaptureFixture) -> None:
window = earned_time.day_window(DAY)
assert focus_match(row(5, 5), window)
assert not focus_match(row(5, 5, START), window)
nostamp = signed(
{"kind": "credit", "day": DAY.isoformat(), "detail": {"minutes": 5}}
)
assert focus_match(nostamp, window)
assert not focus_match({**nostamp, "day": START.isoformat()}, window)
with caplog.at_level(logging.WARNING):
assert not focus_match(row(0, 1), window)
assert "bad minutes" in caplog.text
@pytest.mark.parametrize("bad", [0, -1, True, 1.5, "5", None])
def test_minutes_must_be_a_positive_int(bad: object) -> None:
assert focus_minutes({"detail": {"minutes": bad}}) is None
assert focus_minutes({"detail": "x"}) is None
assert focus_minutes({"detail": {"minutes": 4}}) == 4

View File

@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "earned-time"
version = "0.18.0"
version = "0.19.0"
description = "Penalty-then-reward registry: what every gate app earns in gaming time and shutdown time"
requires-python = ">=3.14"
dependencies = []

View File

@ -22,12 +22,14 @@ from focus_project._api import (
stands_down,
)
from focus_project._errors import RegistryError
from focus_project._model import Project
from focus_project._model import Limits, Project
from focus_project._update import update_project
from focus_project.activity import record_activity
from focus_project.minutes import minutes_for
from focus_project.status import status
__all__ = [
"Limits",
"Project",
"RegistryError",
"active",
@ -38,4 +40,5 @@ __all__ = [
"record_activity",
"stands_down",
"status",
"update_project",
]

View File

@ -18,6 +18,32 @@ def normalize_gate(gate: str) -> str:
return _ALIASES.get(gate, gate)
@dataclass(frozen=True)
class Limits:
"""The minute targets that held up to and including ``until``."""
until: date
daily_minutes: int
unlock_minutes: int
def to_dict(self) -> dict[str, Any]:
"""The history row in projects.json."""
return {
"until": self.until.isoformat(),
"daily_minutes": self.daily_minutes,
"unlock_minutes": self.unlock_minutes,
}
@classmethod
def from_dict(cls, row: Any) -> Limits: # noqa: ANN401
"""Parse a history row (errors surface as RegistryError upstream)."""
return cls(
until=date.fromisoformat(row["until"]),
daily_minutes=int(row["daily_minutes"]),
unlock_minutes=int(row["unlock_minutes"]),
)
@dataclass(frozen=True)
class Project:
"""One time-boxed focus project; at most one is active per day."""
@ -33,6 +59,21 @@ class Project:
site_patterns: tuple[str, ...] = ()
ended_on: date | None = None
created_ms: int = 0
# Earlier targets, oldest first: an edit applies from its day, never back.
history: tuple[Limits, ...] = ()
def _limits_on(self, day: date) -> Limits | None:
return next((h for h in self.history if day <= h.until), None)
def daily_on(self, day: date) -> int:
"""The daily target that held on ``day``."""
past = self._limits_on(day)
return self.daily_minutes if past is None else past.daily_minutes
def unlock_on(self, day: date) -> int:
"""The unlock target that held on ``day``."""
past = self._limits_on(day)
return self.unlock_minutes if past is None else past.unlock_minutes
@property
def last_day(self) -> date:
@ -61,6 +102,7 @@ class Project:
"site_patterns": list(self.site_patterns),
"ended_on": self.ended_on.isoformat() if self.ended_on else None,
"created_ms": self.created_ms,
"history": [h.to_dict() for h in self.history],
}
@classmethod
@ -80,6 +122,7 @@ class Project:
site_patterns=tuple(row.get("site_patterns", ())),
ended_on=date.fromisoformat(ended) if ended else None,
created_ms=int(row.get("created_ms", 0)),
history=tuple(Limits.from_dict(h) for h in row.get("history", ())),
)
except (KeyError, TypeError, ValueError, AttributeError) as exc:
msg = f"bad project row {row!r}: {exc}"

View File

@ -0,0 +1,105 @@
# Copyright (c) 2026 Krzysztof Rudnicki
"""update_project: edit a project with create's validation, never the past."""
from __future__ import annotations
from dataclasses import replace
from datetime import date, timedelta
from typing import Any
from focus_project import _store
from focus_project._api import _validate
from focus_project._model import Limits, Project, normalize_gate
_EDITABLE = frozenset(
{
"name",
"start",
"end",
"replaces",
"daily_minutes",
"unlock_minutes",
"subjects",
"site_patterns",
}
)
_TUPLES = ("subjects", "site_patterns")
def _apply(project: Project, changes: dict[str, Any], today: date) -> Project:
"""The edited project; ValueError for what an edit may not touch."""
if project.ended_on is not None:
msg = f"project {project.id!r} ended on {project.ended_on}"
raise ValueError(msg)
if project.last_day < today:
msg = f"project {project.id!r} is over (ended {project.last_day})"
raise ValueError(msg)
fields = {k: v for k, v in changes.items() if k not in _TUPLES}
if "replaces" in changes:
fields["replaces"] = tuple(
dict.fromkeys(map(normalize_gate, changes["replaces"]))
)
for key in _TUPLES:
if key in changes:
fields[key] = tuple(changes[key])
new_start = changes.get("start", project.start)
if new_start != project.start and today > min(project.start, new_start):
msg = f"cannot move start of a started project ({project.start})"
raise ValueError(msg)
if "end" in changes and changes["end"] < today:
msg = f"end {changes['end']} is in the past"
raise ValueError(msg)
edited = replace(project, **fields)
return _keep_past_limits(project, edited, today)
def _keep_past_limits(old: Project, new: Project, today: date) -> Project:
"""Freeze the old targets for the days before ``today`` if they changed."""
changed = (old.daily_minutes, old.unlock_minutes) != (
new.daily_minutes,
new.unlock_minutes,
)
cutoff = today - timedelta(days=1)
if not changed or cutoff < old.start:
return new
if old.history and old.history[-1].until == cutoff:
return new
row = Limits(cutoff, old.daily_minutes, old.unlock_minutes)
return replace(new, history=(*old.history, row))
def update_project(
project_id: str,
*,
today: date | None = None,
**changes: Any, # noqa: ANN401
) -> Project:
"""Edit ``project_id``; ValueError on bad input, overlap or a past edit.
Editable: name, start, end, replaces, daily_minutes, unlock_minutes,
subjects, site_patterns. A started project's start cannot move; changed
minute targets apply from ``today`` (default: now) on, earlier days keep
theirs. KeyError for an unknown id.
"""
unknown = sorted(set(changes) - _EDITABLE)
if unknown:
msg = f"cannot change {unknown}"
raise ValueError(msg)
today = today or date.today() # noqa: DTZ011
with _store.locked():
existing = _store.read_all()
for i, project in enumerate(existing):
if project.id != project_id:
continue
edited = _apply(project, changes, today)
_validate(edited)
for other in existing:
if other.id != project_id and (
edited.start <= other.last_day and other.start <= edited.last_day
):
msg = f"project overlaps {other.id!r}"
raise ValueError(msg)
existing[i] = edited
_store.write_all(existing)
return edited
raise KeyError(project_id)

View File

@ -0,0 +1,62 @@
# Copyright (c) 2026 Krzysztof Rudnicki
"""The harvester: turn credited focus minutes into signed ledger rows.
Run by ``focus-project-harvest.service`` (``.path`` on activity.jsonl plus a
one-minute ``.timer``). Harvests yesterday too, so work recorded just before
midnight is paid once the next run sees it. Failure modes, by path:
* a source that errors: logged, contributes 0, the run continues (fail closed);
* an unreadable registry, signing key or ledger: logged, exit status 1, so
the unit shows ``failed`` instead of silently crediting nothing.
"""
from __future__ import annotations
from datetime import date, timedelta
import logging
import sys
import time
from focus_project import _api, ledger
from focus_project._errors import RegistryError
from focus_project.minutes import minutes_for
_LOG = logging.getLogger("focus_project.harvest")
def harvest_day(day: date, now: float) -> int:
"""Credit ``day``; return the minutes added (0 with no project)."""
project = _api.active(day)
if project is None:
return 0
total = minutes_for(day)
added = ledger.credit_to(project, day, total, now=now)
if added:
_LOG.info(
"credited %d min to %s on %s (total %d)", added, project.id, day, total
)
return added
def harvest(now: float | None = None) -> int:
"""Harvest yesterday and today; 0 on success, 1 if any path failed."""
moment = time.time() if now is None else now
today = date.fromtimestamp(moment) # noqa: DTZ012 (local day)
status = 0
for day in (today - timedelta(days=1), today):
try:
harvest_day(day, moment)
except (RegistryError, ledger.LedgerError, OSError) as exc:
_LOG.error("harvest %s failed: %s", day, exc)
status = 1
return status
def main() -> None:
"""Entry point of ``python -m focus_project.harvest``."""
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
sys.exit(harvest())
if __name__ == "__main__":
main()

View File

@ -0,0 +1,178 @@
# Copyright (c) 2026 Krzysztof Rudnicki
"""The signed credit ledger the ``focus`` earner reads.
Row contract (earned_time's "tutor row contract"): ``detail.minutes`` is the
positive increment the row pays, ``entry_id`` is
``<project>-<YYYYMMDD>-m<n>`` with ``n`` the day's cumulative credited
minutes AFTER the row (so ids never overlap and a retry rewrites the same
id), ``day`` is the local date, ``detail.ended_at`` is when the last paid
minute ended and never passes the day's end. The only writer is the
harvester; every write is read back and verified.
"""
from __future__ import annotations
import fcntl
import json
import logging
import os
from pathlib import Path
import tempfile
import time
from typing import TYPE_CHECKING, Any, Final
import earned_time
from focus_project._paths import data_dir
from focus_project.sources import day_bounds
if TYPE_CHECKING:
from datetime import date
from focus_project._model import Project
CREDIT: Final = "credit"
KEY_ENV: Final = "FOCUS_PROJECT_KEY"
_REAL_KEY: Final = Path("/etc/workout-locker/hmac.key")
_LOG = logging.getLogger(__name__)
class LedgerError(Exception):
"""The ledger exists but is not a ledger: never silently emptied."""
def key_path() -> Path:
"""The signing key: ``$FOCUS_PROJECT_KEY`` or the shared root-owned key."""
override = os.environ.get(KEY_ENV)
return Path(override) if override else _REAL_KEY
def ledger_path() -> Path:
"""The ledger file inside the data dir."""
return data_dir() / "ledger.json"
def read_key() -> bytes | None:
"""The signing key, or None if unreadable or empty (logged)."""
try:
return key_path().read_bytes().strip() or None
except OSError as exc:
_LOG.warning("signing key %s unreadable: %s", key_path(), exc)
return None
def read_rows(path: Path) -> list[Any]:
"""The raw ``entries`` array; a missing file is empty.
Raises:
LedgerError: unreadable, not JSON, or no entries array.
"""
try:
raw = json.loads(path.read_text(encoding="utf-8"))
except FileNotFoundError:
return []
except (OSError, ValueError) as exc:
msg = f"{path} is unreadable: {exc}"
raise LedgerError(msg) from exc
rows = raw.get("entries") if isinstance(raw, dict) else None
if not isinstance(rows, list):
msg = f"{path} has no entries array"
raise LedgerError(msg)
return rows
def _write_rows(path: Path, rows: list[Any]) -> None:
"""Atomically replace the ledger: readers see the old file or the new one."""
path.parent.mkdir(parents=True, exist_ok=True)
with tempfile.NamedTemporaryFile(
"w", encoding="utf-8", dir=path.parent, suffix=".tmp", delete=False
) as handle:
json.dump({"version": 1, "entries": rows}, handle, indent=1)
handle.flush()
os.fsync(handle.fileno())
Path(handle.name).replace(path)
def paid_minutes(rows: list[Any], key: bytes, project_id: str, day: date) -> int:
"""Minutes already paid for ``project_id`` on ``day`` by verified rows.
A repeated ``entry_id`` pays once, at its smallest count.
"""
by_id: dict[str, int] = {}
for row in rows:
if not (isinstance(row, dict) and row.get("kind") == CREDIT):
continue
detail = row.get("detail")
if not isinstance(detail, dict):
continue
minutes = detail.get("minutes")
if (
row.get("day") != day.isoformat()
or detail.get("project") != project_id
or not isinstance(minutes, int)
or isinstance(minutes, bool)
or minutes < 1
or not earned_time.verified(row, key)
):
continue
eid = str(row.get("entry_id"))
by_id[eid] = min(by_id.get(eid, minutes), minutes)
return sum(by_id.values())
def build_row( # noqa: PLR0913
project_id: str, day: date, total: int, minutes: int, key: bytes, *, now: float
) -> dict[str, Any]:
"""The signed row paying ``minutes`` that bring the day's total to ``total``."""
ended = min(now, day_bounds(day)[1] - 1)
row: dict[str, Any] = {
"kind": CREDIT,
"entry_id": f"{project_id}-{day:%Y%m%d}-m{total}",
"day": day.isoformat(),
"created_at": float(now),
"detail": {
"project": project_id,
"minutes": int(minutes),
"total": int(total),
"ended_at": float(ended),
},
}
row["hmac"] = str(earned_time.entry_signature(row, key))
return row
def credit_to(
project: Project, day: date, total: int, *, now: float | None = None
) -> int:
"""Pay the day up to ``total`` cumulative minutes; return minutes added.
Idempotent: nothing is written when the ledger already pays ``total`` or
more. Raises LedgerError (unreadable ledger, unreadable key, unverifiable
write) so the harvester can fail loudly instead of crediting nothing quietly.
"""
key = read_key()
if key is None:
msg = f"signing key {key_path()} unreadable"
raise LedgerError(msg)
path = ledger_path()
path.parent.mkdir(parents=True, exist_ok=True)
with path.with_suffix(".lock").open("w") as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
rows = read_rows(path)
paid = paid_minutes(rows, key, project.id, day)
if total <= paid:
return 0
row = build_row(
project.id, day, total, total - paid, key, now=now or time.time()
)
if any(
isinstance(r, dict) and r.get("entry_id") == row["entry_id"] for r in rows
):
msg = f"entry_id {row['entry_id']} already present but unverified"
raise LedgerError(msg)
_write_rows(path, [*rows, row])
stored = read_rows(path)
if paid_minutes(stored, key, project.id, day) != total:
msg = f"row {row['entry_id']} not found verified on read-back"
raise LedgerError(msg)
return total - paid

View File

@ -1,15 +1,42 @@
# Copyright (c) 2026 Krzysztof Rudnicki
"""Credited focus minutes per day. Owned by agent D: replace the body.
"""Credited focus minutes per day: the union of every source's intervals.
Contract: union of activity intervals on the local calendar day, capped at
the active project's daily_minutes. This stub returns 0 until D lands.
the active project's ``daily_minutes``; overlaps never double count; whole
minutes (floor). An unreadable registry reads as 0 (logged): fail closed.
"""
from __future__ import annotations
from datetime import date # noqa: TC003
import logging
from focus_project import _api, sources
from focus_project._errors import RegistryError
_LOG = logging.getLogger(__name__)
def minutes_for(day: date) -> int: # noqa: ARG001
"""Minutes of focus work credited on ``day`` (stub: always 0)."""
return 0
def union_seconds(spans: list[sources.Interval]) -> float:
"""Total length of the union of ``spans``."""
total = 0.0
end = float("-inf")
for lo, hi in sorted(spans):
if hi <= end:
continue
total += hi - max(lo, end)
end = hi
return total
def minutes_for(day: date) -> int:
"""Minutes of focus work credited on ``day`` (0 with no project active)."""
try:
project = _api.active(day)
except (RegistryError, OSError) as exc:
_LOG.warning("focus_project registry unreadable, 0 minutes: %s", exc)
return 0
if project is None:
return 0
seconds = union_seconds(sources.collect(day, project))
return min(int(seconds // 60), project.daily_on(day))

View File

@ -63,17 +63,13 @@ def collect_by_source(day: date, project: Project) -> dict[str, list[Interval]]:
module_name = f"{__name__}.{name}"
try:
module = importlib.import_module(module_name)
except ModuleNotFoundError as exc:
if exc.name == module_name:
except Exception as exc: # noqa: BLE001 (a broken adapter must add 0)
if isinstance(exc, ModuleNotFoundError) and exc.name == module_name:
_LOG.info("source %s: not installed (inactive)", name)
continue
_LOG.exception("source %s: import failed, contributes 0", name)
found[name] = []
continue
except Exception: # noqa: BLE001 (any broken adapter must contribute 0)
_LOG.exception("source %s: import failed, contributes 0", name)
found[name] = []
continue
try:
found[name] = clip(list(module.intervals(day, project)), bounds)
except Exception: # noqa: BLE001 (fail closed: this source adds 0)

View File

@ -0,0 +1,80 @@
# Copyright (c) 2026 Krzysztof Rudnicki
"""Adapter for ``activity.jsonl``: the timer and every heartbeat writer.
``timer`` events form segments ``start -> checkin ... -> stop``. A span
between two consecutive events counts only if the gap is at most
:data:`MAX_GAP_S`: a missed check-in stops the segment, and a late check-in
starts a fresh one. Time after the last check-in is not credited until the
next event vouches for it. Every other source (tutor, sql_drills, ...) is a
heartbeat covering the five minutes before it. Only events recorded for
``project`` count.
"""
from __future__ import annotations
import json
import logging
from typing import TYPE_CHECKING, Any
from focus_project._paths import activity_path
from focus_project.sources import Interval, heartbeat_interval
if TYPE_CHECKING:
from datetime import date
from focus_project._model import Project
MAX_GAP_S = 600.0
_LOG = logging.getLogger(__name__)
def read_events(project_id: str) -> list[dict[str, Any]]:
"""Well-formed events of ``project_id`` in time order; junk lines skipped."""
try:
text = activity_path().read_text(encoding="utf-8")
except FileNotFoundError:
return []
events: list[dict[str, Any]] = []
for line in text.splitlines():
try:
row = json.loads(line)
ok = (
isinstance(row, dict)
and row.get("project") == project_id
and isinstance(row["ts"], (int, float))
and not isinstance(row["ts"], bool)
)
except ValueError, KeyError:
ok = False
if ok:
events.append(row)
elif line.strip():
_LOG.debug("activity line skipped: %.80s", line)
events.sort(key=lambda e: e["ts"])
return events
def timer_intervals(events: list[dict[str, Any]]) -> list[Interval]:
"""Credited spans of the ``timer`` events (already time-ordered)."""
spans: list[Interval] = []
last: float | None = None # the last event of the open segment
for event in events:
ts = float(event["ts"])
kind = event.get("kind")
if kind not in {"start", "checkin", "stop"}:
continue
if last is not None and ts - last <= MAX_GAP_S:
spans.append((last, ts))
last = None if kind == "stop" else ts
return spans
def intervals(day: date, project: Project) -> list[Interval]: # noqa: ARG001
"""Timer segments plus heartbeats of ``project`` (the registry clips)."""
events = read_events(project.id)
timer = [e for e in events if e.get("source") == "timer"]
beats = [e for e in events if e.get("source") != "timer"]
return [
*timer_intervals(timer),
*(heartbeat_interval(float(e["ts"])) for e in beats),
]

View File

@ -0,0 +1,188 @@
# Copyright (c) 2026 Krzysztof Rudnicki
"""Browser evidence: active window/URL time on the project's sites.
Reads the kuhytrack activity server (read-only GETs, the same data the PC
watcher and the phone bridge write): ``currentwindow`` buckets give
``{app, title[, url]}`` spans, ``afkstatus`` buckets of the same host trim
them to time the user was present. A host without an AFK bucket (the phone)
is taken as present.
Matching is case-insensitive. A ``site_patterns`` entry such as
``leetcode.com`` matches as-is in the url/title/app, or, when the window is
a browser, by its stem (``leetcode``) in the title: Chrome-family titles
carry the page name, not the host. Stems under four characters are ignored.
Failure modes (named): no tracker config -> inactive, 0 minutes; tracker
unreachable or broken -> raises, so the registry logs it and counts 0; an
AFK bucket with no events that day -> 0 for that host (fail closed).
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import UTC, date, datetime
import json
import logging
import os
from pathlib import Path
from typing import TYPE_CHECKING, Any
from urllib.parse import urlencode
from urllib.request import Request, urlopen
from focus_project.sources import Interval, day_bounds
if TYPE_CHECKING:
from focus_project._model import Project
_LOG = logging.getLogger(__name__)
# Long window events start before midnight; ask a little earlier.
LOOKBACK_S = 3600
TIMEOUT_S = 5
MIN_STEM = 4
BROWSERS = (
"helium",
"librewolf",
"firefox",
"chrom",
"brave",
"vivaldi",
"opera",
"msedge",
"zen",
)
_ENV_DEFAULT = "~/.config/kuhytrack/env"
_urlopen = urlopen
@dataclass(frozen=True)
class Config:
"""Where the tracker listens and the bearer token (may be empty)."""
url: str
token: str
def _config() -> Config | None:
"""The tracker's own ``KT_URL``/``KT_TOKEN`` env file, or None if absent."""
path = Path(os.environ.get("KUHYTRACK_ENV", _ENV_DEFAULT)).expanduser()
try:
lines = path.read_text(encoding="utf-8").splitlines()
except OSError:
return None
values: dict[str, str] = {}
for line in lines:
key, sep, value = line.strip().partition("=")
if sep and not key.startswith("#"):
values[key.strip()] = value.strip().strip("'\"")
url = values.get("KT_URL", "")
return Config(url.rstrip("/"), values.get("KT_TOKEN", "")) if url else None
def _get_json(cfg: Config, path: str, params: dict[str, str] | None = None) -> Any: # noqa: ANN401
"""One authenticated GET returning parsed JSON."""
url = cfg.url + path + (f"?{urlencode(params)}" if params else "")
request = Request(url) # noqa: S310 (operator-configured http URL)
if cfg.token:
request.add_header("Authorization", f"Bearer {cfg.token}")
with _urlopen(request, timeout=TIMEOUT_S) as response:
return json.load(response)
def _merge(spans: list[Interval]) -> list[Interval]:
"""Sorted, non-overlapping union of ``spans``."""
out: list[Interval] = []
for start, end in sorted(spans):
if out and start <= out[-1][1]:
out[-1] = (out[-1][0], max(out[-1][1], end))
else:
out.append((start, end))
return out
def _intersect(left: list[Interval], right: list[Interval]) -> list[Interval]:
"""Overlap of two merged span lists."""
out: list[Interval] = []
for a0, a1 in left:
for b0, b1 in right:
lo, hi = max(a0, b0), min(a1, b1)
if hi > lo:
out.append((lo, hi))
return out
def _needles(patterns: tuple[str, ...]) -> tuple[list[str], list[str]]:
"""``(full, stems)``: lowercase host patterns and their page-title stems."""
full: list[str] = []
stems: list[str] = []
for raw in patterns:
pattern = raw.strip().lower().removeprefix("www.")
if not pattern:
continue
full.append(pattern)
stem = pattern.split(".", 1)[0]
if "." in pattern and len(stem) >= MIN_STEM:
stems.append(stem)
return full, stems
def _matches(data: dict[str, Any], full: list[str], stems: list[str]) -> bool:
fields = {
k: str(data.get(k, "")).lower() for k in ("url", "title", "app", "package")
}
text = " ".join(fields.values()).replace("www.", "")
if any(needle in text for needle in full):
return True
if any(b in fields["app"] for b in BROWSERS):
return any(stem in fields["title"] for stem in stems)
return False
def _epoch(stamp: str) -> float:
return datetime.fromisoformat(stamp).timestamp()
def _spans(events: list[dict[str, Any]]) -> list[Interval]:
out: list[Interval] = []
for event in events:
start = _epoch(event["timestamp"])
out.append((start, start + float(event.get("duration") or 0)))
return out
def intervals(day: date, project: Project) -> list[Interval]:
"""Present time on the project's sites; see the module docstring."""
full, stems = _needles(project.site_patterns)
if not full:
return []
cfg = _config()
if cfg is None:
_LOG.info("browser source: no kuhytrack config (inactive)")
return []
lo, hi = day_bounds(day)
stamp = "%Y-%m-%dT%H:%M:%S.000Z"
params = {
"start": datetime.fromtimestamp(lo - LOOKBACK_S, UTC).strftime(stamp),
"end": datetime.fromtimestamp(hi, UTC).strftime(stamp),
}
def events(bucket: dict[str, Any]) -> list[dict[str, Any]]:
return list(_get_json(cfg, f"/api/0/buckets/{bucket['id']}/events", params))
buckets = list(_get_json(cfg, "/api/0/buckets").values())
present: dict[str, list[Interval]] = {}
for bucket in buckets:
if bucket["type"] == "afkstatus":
live = [e for e in events(bucket) if e["data"].get("status") == "not-afk"]
present.setdefault(bucket["hostname"], []).extend(_spans(live))
on_site: dict[str, list[Interval]] = {}
for bucket in buckets:
if bucket["type"] == "currentwindow":
hits = [e for e in events(bucket) if _matches(e["data"], full, stems)]
on_site.setdefault(bucket["hostname"], []).extend(_spans(hits))
out: list[Interval] = []
for host, spans in on_site.items():
merged = _merge(spans)
out.extend(
_intersect(merged, _merge(present[host])) if host in present else merged
)
return out

View File

@ -0,0 +1,67 @@
# Copyright (c) 2026 Krzysztof Rudnicki
"""Adapter for accepted LeetCode submissions (leetcode-guard's ledger).
Read-only. Each accepted submission (``ac:<id>`` credit row, HMAC verified)
is a heartbeat at ``detail.submitted_at``, so it covers the five minutes
before it. The window is deliberately NOT longer: the time spent reading and
thinking on the site is the browser adapter's to count, and a submission
alone proves only that work happened, not for how long. Applies only to a
project whose ``site_patterns`` name leetcode; any other project is not
LeetCode practice. No readable signing key: contributes nothing (logged).
"""
from __future__ import annotations
import logging
import os
from pathlib import Path
from typing import TYPE_CHECKING
import earned_time
from focus_project import ledger
from focus_project.sources import Interval, heartbeat_interval
if TYPE_CHECKING:
from datetime import date
from focus_project._model import Project
LEDGER_ENV = "FOCUS_PROJECT_LEETCODE_LEDGER"
_LOG = logging.getLogger(__name__)
def ledger_file() -> Path:
"""leetcode-guard's ledger, or the test override."""
override = os.environ.get(LEDGER_ENV)
if override:
return Path(override)
return Path.home() / ".local" / "share" / "leetcode_guard" / "ledger.json"
def _submitted_at(row: object, key: bytes) -> float | None:
"""The submission time of a verified accepted-submission row, else None."""
if not (
isinstance(row, dict)
and row.get("kind") == "credit"
and str(row.get("entry_id", "")).startswith("ac:")
and earned_time.verified(row, key)
):
return None
detail = row.get("detail")
try:
return float(detail["submitted_at"]) # type: ignore[index]
except KeyError, TypeError, ValueError:
return None
def intervals(day: date, project: Project) -> list[Interval]: # noqa: ARG001
"""One heartbeat per accepted submission (the registry clips to the day)."""
if not any("leetcode" in pattern.lower() for pattern in project.site_patterns):
return []
key = ledger.read_key()
if key is None:
_LOG.warning("leetcode source: no signing key, contributes 0")
return []
stamps = (_submitted_at(row, key) for row in ledger.read_rows(ledger_file()))
return [heartbeat_interval(ts) for ts in stamps if ts is not None]

View File

@ -26,8 +26,8 @@ def status(day: date) -> dict[str, Any]:
"project": project.id,
"name": project.name,
"minutes": minutes.minutes_for(day),
"daily_minutes": project.daily_minutes,
"unlock_minutes": project.unlock_minutes,
"daily_minutes": project.daily_on(day),
"unlock_minutes": project.unlock_on(day),
"ends": project.last_day.isoformat(),
"replaces": list(project.replaces),
}

View File

@ -19,6 +19,10 @@ if TYPE_CHECKING:
def _redirect_state(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
"""Point the data directory at ``tmp_path`` before any test runs."""
monkeypatch.setenv("FOCUS_PROJECT_DATA", str(tmp_path / "data"))
# Read-only evidence files and the signing key: never the real ones.
monkeypatch.setenv("FOCUS_PROJECT_LEETCODE_LEDGER", str(tmp_path / "lc.json"))
monkeypatch.setenv("KUHYTRACK_ENV", str(tmp_path / "no-kuhytrack-env"))
monkeypatch.setenv("FOCUS_PROJECT_KEY", str(tmp_path / "hmac.key"))
@pytest.fixture

View File

@ -0,0 +1,181 @@
# Copyright (c) 2026 Krzysztof Rudnicki
"""Signed rows, idempotency, harvester paths."""
from __future__ import annotations
from datetime import date, timedelta
import json
import logging
from pathlib import Path # noqa: TC003
import earned_time
import pytest
import focus_project as fp
from focus_project import harvest, ledger, minutes
from focus_project.tests.test_minutes import D1, at, events, project
KEY = b"k" * 32
@pytest.fixture(autouse=True)
def _key(tmp_path: Path) -> None:
(tmp_path / "hmac.key").write_bytes(KEY)
def rows() -> list[dict]:
return json.loads(ledger.ledger_path().read_text())["entries"]
def beats(*times: float) -> None:
events(*(("tutor", "heartbeat", t) for t in times))
def test_credit_writes_signed_row_with_contract_fields() -> None:
project()
beats(at(9, 30))
assert harvest.harvest(now=at(9, 31)) == 0
(row,) = rows()
assert row["entry_id"] == "hr-20261102-m5"
assert row["day"] == "2026-11-02"
assert row["detail"]["minutes"] == 5
assert row["detail"]["project"] == "hr"
assert row["detail"]["ended_at"] == at(9, 31)
assert earned_time.verified(row, KEY)
def test_second_run_is_idempotent() -> None:
project()
beats(at(9, 30))
harvest.harvest(now=at(9, 31))
harvest.harvest(now=at(9, 32))
assert len(rows()) == 1
def test_growth_writes_increment_rows_that_sum_to_total() -> None:
project()
beats(at(9, 30))
harvest.harvest(now=at(9, 31))
beats(at(9, 38)) # union: 9:25..9:30 + 9:33..9:38 = 10
harvest.harvest(now=at(9, 39))
got = rows()
assert [r["entry_id"] for r in got] == ["hr-20261102-m5", "hr-20261102-m10"]
assert [r["detail"]["minutes"] for r in got] == [5, 5]
assert ledger.paid_minutes(got, KEY, "hr", D1) == minutes.minutes_for(D1) == 10
def test_yesterday_is_harvested_after_midnight() -> None:
project()
beats(at(23, 58))
harvest.harvest(now=at(0, 1, day=D1 + timedelta(days=1)))
(row,) = rows()
assert row["day"] == "2026-11-02"
assert row["detail"]["ended_at"] < at(0, 0, day=D1 + timedelta(days=1))
def test_no_project_writes_nothing() -> None:
beats(at(9, 30))
assert harvest.harvest(now=at(9, 31)) == 0
assert not ledger.ledger_path().exists()
def test_unreadable_key_fails_loudly_and_writes_nothing(
tmp_path: Path, caplog: pytest.LogCaptureFixture
) -> None:
(tmp_path / "hmac.key").unlink()
project()
beats(at(9, 30))
with caplog.at_level(logging.ERROR):
assert harvest.harvest(now=at(9, 31)) == 1
assert "unreadable" in caplog.text
assert not ledger.ledger_path().exists()
def test_corrupt_ledger_is_not_emptied() -> None:
project()
beats(at(9, 30))
ledger.ledger_path().parent.mkdir(parents=True, exist_ok=True)
ledger.ledger_path().write_text("{oops")
assert harvest.harvest(now=at(9, 31)) == 1
assert ledger.ledger_path().read_text() == "{oops"
def test_ledger_without_entries_array_is_an_error() -> None:
ledger.ledger_path().parent.mkdir(parents=True, exist_ok=True)
ledger.ledger_path().write_text('{"entries": 3}')
with pytest.raises(ledger.LedgerError):
ledger.read_rows(ledger.ledger_path())
def test_broken_registry_fails_loudly(monkeypatch: pytest.MonkeyPatch) -> None:
def boom(_day: date) -> None:
msg = "corrupt"
raise fp.RegistryError(msg)
monkeypatch.setattr("focus_project._api.active", boom)
assert harvest.harvest(now=at(9, 31)) == 1
def test_empty_key_file_counts_as_unreadable(tmp_path: Path) -> None:
(tmp_path / "hmac.key").write_bytes(b"\n")
assert ledger.read_key() is None
def test_forged_and_malformed_rows_do_not_count() -> None:
good = ledger.build_row("hr", D1, 5, 5, KEY, now=at(9))
forged = {
**good,
"entry_id": "hr-20261102-m50",
"detail": {**good["detail"], "minutes": 50},
}
other_key = ledger.build_row("hr", D1, 9, 9, b"x" * 32, now=at(9))
junk: list = [
"str",
{"kind": "charge"},
{**good, "detail": "no"},
{**good, "day": "2026-11-03"},
{**good, "detail": {**good["detail"], "project": "other"}},
{**good, "detail": {**good["detail"], "minutes": True}},
{**good, "detail": {**good["detail"], "minutes": 0}},
forged,
other_key,
]
assert ledger.paid_minutes([good, *junk], KEY, "hr", D1) == 5
def test_repeated_entry_id_pays_once_at_smallest() -> None:
a = ledger.build_row("hr", D1, 10, 10, KEY, now=at(9))
b = ledger.build_row("hr", D1, 10, 4, KEY, now=at(9))
assert ledger.paid_minutes([a, b], KEY, "hr", D1) == 4
def test_unverified_same_id_row_blocks_write() -> None:
p = project_obj()
row = ledger.build_row("hr", D1, 5, 5, KEY, now=at(9))
row["hmac"] = "bad"
ledger.ledger_path().parent.mkdir(parents=True, exist_ok=True)
ledger.ledger_path().write_text(json.dumps({"entries": [row]}))
with pytest.raises(ledger.LedgerError, match="unverified"):
ledger.credit_to(p, D1, 5, now=at(9))
def test_readback_failure_is_reported(monkeypatch: pytest.MonkeyPatch) -> None:
p = project_obj()
real = ledger._write_rows
monkeypatch.setattr(ledger, "_write_rows", lambda path, _rows: real(path, []))
with pytest.raises(ledger.LedgerError, match="read-back"):
ledger.credit_to(p, D1, 5, now=at(9))
def project_obj() -> fp.Project:
project()
found = fp.active(D1)
assert found is not None
return found
def test_main_exits_with_status(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(harvest, "harvest", lambda: 7)
with pytest.raises(SystemExit) as info:
harvest.main()
assert info.value.code == 7

View File

@ -0,0 +1,129 @@
# Copyright (c) 2026 Krzysztof Rudnicki
"""The accepted-submission adapter, incl. read-only replay of the real ledger."""
from __future__ import annotations
from datetime import date
import json
from pathlib import Path
from typing import Any
import earned_time
import pytest
import focus_project as fp
from focus_project import minutes, sources
from focus_project.sources import leetcode
from focus_project.tests.test_minutes import D1, at, project
KEY = b"k" * 32
def ac_row(ts: float, eid: str = "ac:1", key: bytes = KEY) -> dict:
row: dict[str, Any] = {
"entry_id": eid,
"kind": "credit",
"day": "2026-11-02",
"amount": 1,
"detail": {"title_slug": "x", "submitted_at": str(int(ts))},
}
row["hmac"] = earned_time.entry_signature(row, key)
return row
def write(tmp_path: Path, *rows: object) -> None:
(tmp_path / "hmac.key").write_bytes(KEY)
(tmp_path / "lc.json").write_text(json.dumps({"version": 1, "entries": list(rows)}))
def test_submission_is_a_five_minute_heartbeat(tmp_path: Path) -> None:
project()
write(tmp_path, ac_row(at(10)), ac_row(at(10, 2), "ac:2"))
assert minutes.minutes_for(D1) == 7 # union 9:55..10:02
def test_other_rows_and_forgeries_ignored(tmp_path: Path) -> None:
project()
charge = {**ac_row(at(10), "charge:2026-11-02"), "kind": "charge"}
bad_detail = ac_row(at(10), "ac:3")
bad_detail["detail"] = {"submitted_at": "soon"}
bad_detail["hmac"] = earned_time.entry_signature(bad_detail, KEY)
no_detail = ac_row(at(10), "ac:4")
no_detail["detail"] = None
no_detail["hmac"] = earned_time.entry_signature(no_detail, KEY)
write(
tmp_path,
charge,
ac_row(at(10), "ac:5", key=b"x" * 32),
bad_detail,
no_detail,
"junk",
)
assert minutes.minutes_for(D1) == 0
def test_project_without_leetcode_pattern_ignores_ledger(tmp_path: Path) -> None:
fp.create_project(
"sql",
name="SQL",
start=D1,
end=D1,
replaces=["reading"],
daily_minutes=60,
unlock_minutes=10,
site_patterns=["sqlzoo.net"],
)
write(tmp_path, ac_row(at(10)))
assert minutes.minutes_for(D1) == 0
def test_no_key_contributes_zero(
tmp_path: Path, caplog: pytest.LogCaptureFixture
) -> None:
project()
write(tmp_path, ac_row(at(10)))
(tmp_path / "hmac.key").unlink()
assert minutes.minutes_for(D1) == 0
assert "no signing key" in caplog.text
def test_missing_or_corrupt_ledger_contributes_zero(tmp_path: Path) -> None:
project()
(tmp_path / "hmac.key").write_bytes(KEY)
assert minutes.minutes_for(D1) == 0
(tmp_path / "lc.json").write_text("{")
assert minutes.minutes_for(D1) == 0 # LedgerError caught by collect
def test_default_ledger_path(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
monkeypatch.delenv(leetcode.LEDGER_ENV)
monkeypatch.setenv("HOME", str(tmp_path))
assert (
leetcode.ledger_file() == tmp_path / ".local/share/leetcode_guard/ledger.json"
)
REAL = Path.home() / ".local/share/leetcode_guard/ledger.json"
REAL_KEY = Path("/etc/workout-locker/hmac.key")
@pytest.mark.skipif(not (REAL.exists() and REAL_KEY.exists()), reason="no live ledger")
def test_read_only_replay_of_real_ledger(monkeypatch: pytest.MonkeyPatch) -> None:
"""Every real accepted submission yields a heartbeat; nothing is written."""
before = REAL.stat().st_mtime_ns
monkeypatch.setenv(leetcode.LEDGER_ENV, str(REAL))
monkeypatch.setenv("FOCUS_PROJECT_KEY", str(REAL_KEY))
proj = fp.Project(
id="x",
name="x",
start=date(2026, 1, 1),
end=date(2026, 12, 31),
replaces=("leetcode",),
daily_minutes=120,
unlock_minutes=30,
site_patterns=("leetcode.com",),
)
got = leetcode.intervals(D1, proj)
assert got
assert all(b - a == sources.HEARTBEAT_WINDOW_S for a, b in got)
assert REAL.stat().st_mtime_ns == before

View File

@ -0,0 +1,202 @@
# Copyright (c) 2026 Krzysztof Rudnicki
"""minutes_for: union of intervals, gap rule, cap, project filter."""
from __future__ import annotations
from datetime import date, datetime
import json
from typing import TYPE_CHECKING
import focus_project as fp
from focus_project import minutes
from focus_project._paths import activity_path
if TYPE_CHECKING:
import pytest
D1 = date(2026, 11, 2)
def at(hour: int, minute: int = 0, second: int = 0, day: date = D1) -> float:
"""Local unix time on ``day``."""
return (
datetime(day.year, day.month, day.day, hour, minute, second)
.astimezone()
.timestamp()
)
def project(daily: int = 120) -> None:
fp.create_project(
"hr",
name="HR prep",
start=D1,
end=date(2026, 11, 5),
replaces=["leetcode"],
daily_minutes=daily,
unlock_minutes=min(30, daily),
site_patterns=["leetcode.com"],
)
def events(*rows: tuple[str, str, float]) -> None:
activity_path().parent.mkdir(parents=True, exist_ok=True)
with activity_path().open("a", encoding="utf-8") as handle:
for source, kind, ts in rows:
row = {
"ts": ts,
"source": source,
"kind": kind,
"project": "hr",
"dev": "pc",
}
handle.write(json.dumps(row) + "\n")
def test_no_project_is_zero() -> None:
events(("timer", "start", at(9)), ("timer", "stop", at(9, 5)))
assert minutes.minutes_for(D1) == 0
def test_timer_start_checkin_stop() -> None:
project()
events(
("timer", "start", at(9)),
("timer", "checkin", at(9, 5)),
("timer", "checkin", at(9, 10)),
("timer", "stop", at(9, 12)),
)
assert minutes.minutes_for(D1) == 12
def test_missed_checkin_stops_the_segment() -> None:
project()
events(
("timer", "start", at(9)),
("timer", "checkin", at(9, 5)),
("timer", "checkin", at(9, 30)), # 25 min gap > 600 s: not credited
("timer", "stop", at(9, 33)),
)
assert minutes.minutes_for(D1) == 5 + 3
def test_gap_of_exactly_600s_counts() -> None:
project()
events(("timer", "start", at(9)), ("timer", "checkin", at(9, 10)))
assert minutes.minutes_for(D1) == 10
def test_open_timer_credits_only_up_to_last_checkin() -> None:
project()
events(("timer", "start", at(9)), ("timer", "checkin", at(9, 4)))
assert minutes.minutes_for(D1) == 4
def test_stop_without_open_segment_ignored() -> None:
project()
events(
("timer", "stop", at(9)),
("timer", "start", at(10)),
("timer", "stop", at(10, 2)),
)
assert minutes.minutes_for(D1) == 2
def test_start_while_open_acts_as_checkin() -> None:
project()
events(
("timer", "start", at(9)),
("timer", "start", at(9, 3)),
("timer", "stop", at(9, 5)),
)
assert minutes.minutes_for(D1) == 5
def test_heartbeat_covers_five_minutes() -> None:
project()
events(("sql_drills", "heartbeat", at(11)))
assert minutes.minutes_for(D1) == 5
def test_overlaps_never_double_count() -> None:
project()
events(
("timer", "start", at(9)),
("timer", "stop", at(9, 6)),
("tutor", "heartbeat", at(9, 5)), # [9:00, 9:05] inside the timer span
("sql_drills", "heartbeat", at(9, 8)), # [9:03, 9:08] extends it by 2
)
assert minutes.minutes_for(D1) == 8
def test_capped_at_daily_minutes() -> None:
project(daily=10)
events(
("timer", "start", at(9)),
("timer", "stop", at(9, 8)),
("tutor", "heartbeat", at(12)),
)
assert minutes.minutes_for(D1) == 10
def test_other_day_and_other_project_events_ignored() -> None:
project()
events(("tutor", "heartbeat", at(11, day=date(2026, 11, 3))))
with activity_path().open("a", encoding="utf-8") as handle:
row = {"ts": at(11), "source": "tutor", "kind": "heartbeat", "project": "x"}
handle.write(json.dumps(row) + "\n")
row = {"ts": at(12), "source": "tutor", "kind": "heartbeat", "project": None}
handle.write(json.dumps(row) + "\n")
assert minutes.minutes_for(D1) == 0
def test_garbage_lines_skipped() -> None:
project()
events(("tutor", "heartbeat", at(11)))
with activity_path().open("a", encoding="utf-8") as handle:
handle.write(
"not json\n[1]\n" + json.dumps({"ts": "x", "project": "hr"}) + "\n\n"
)
handle.write(
json.dumps({"ts": at(12), "source": "tutor", "project": "hr"}) + "\n"
)
assert minutes.minutes_for(D1) == 5 + 5
def test_interval_spanning_midnight_is_clipped() -> None:
project()
events(("tutor", "heartbeat", at(0, 2))) # covers 23:57..00:02 of D1
assert minutes.minutes_for(D1) == 2
assert minutes.minutes_for(date(2026, 11, 1)) == 0 # no project there
def test_broken_registry_reads_zero(monkeypatch: pytest.MonkeyPatch) -> None:
from focus_project import _api, _errors
def boom(_day: date) -> None:
msg = "corrupt"
raise _errors.RegistryError(msg)
monkeypatch.setattr(_api, "active", boom)
assert minutes.minutes_for(D1) == 0
def test_missing_activity_file_is_zero() -> None:
project()
assert minutes.minutes_for(D1) == 0
def test_contained_heartbeat_adds_nothing() -> None:
project()
events(
("timer", "start", at(9)),
("timer", "stop", at(9, 10)),
("tutor", "heartbeat", at(9, 8)),
)
assert minutes.minutes_for(D1) == 10
def test_non_timer_kinds_from_timer_source_ignored() -> None:
project()
events(("timer", "heartbeat", at(9)))
assert minutes.minutes_for(D1) == 0

View File

@ -0,0 +1,208 @@
# Copyright (c) 2026 Krzysztof Rudnicki
"""The browser adapter: window/URL time on a project's sites, AFK-trimmed."""
from __future__ import annotations
from datetime import UTC, date, datetime
from typing import Any
from urllib.error import URLError
import pytest
from focus_project import sources
from focus_project._model import Project
from focus_project.sources import browser
DAY = date(2026, 11, 2)
LO, HI = sources.day_bounds(DAY)
CFG = browser.Config("http://tracker.test", "tok")
def _project(*patterns: str) -> Project:
return Project(
id="p",
name="P",
start=DAY,
end=DAY,
replaces=("leetcode",),
daily_minutes=120,
unlock_minutes=30,
site_patterns=patterns,
)
def _iso(offset: float) -> str:
stamp = datetime.fromtimestamp(LO + offset, UTC)
return stamp.strftime("%Y-%m-%dT%H:%M:%S.000Z")
def _ev(offset: float, dur: float, **data: str) -> dict[str, Any]:
return {"timestamp": _iso(offset), "duration": dur, "data": data}
def _bucket(bid: str, kind: str, host: str) -> dict[str, Any]:
return {"id": bid, "type": kind, "hostname": host}
def _fake_tracker(
monkeypatch: pytest.MonkeyPatch,
buckets: list[dict[str, Any]],
events: dict[str, list[dict[str, Any]]],
) -> list[tuple[str, dict[str, str] | None]]:
calls: list[tuple[str, dict[str, str] | None]] = []
def fake(
_cfg: browser.Config, path: str, params: dict[str, str] | None = None
) -> Any: # noqa: ANN401
calls.append((path, params))
if path == "/api/0/buckets":
return {b["id"]: b for b in buckets}
bid = path.split("/")[4]
return events.get(bid, [])
monkeypatch.setattr(browser, "_get_json", fake)
monkeypatch.setattr(browser, "_config", lambda: CFG)
return calls
WIN = _bucket("win_pc", "currentwindow", "pc")
AFK = _bucket("afk_pc", "afkstatus", "pc")
ACTIVE_ALL = [_ev(0, 86000, status="not-afk")]
def test_title_stem_in_browser_counts(monkeypatch: pytest.MonkeyPatch) -> None:
_fake_tracker(
monkeypatch,
[WIN, AFK],
{
"win_pc": [
_ev(100, 600, app="Helium", title="Two Sum - LeetCode - Helium")
],
"afk_pc": ACTIVE_ALL,
},
)
assert browser.intervals(DAY, _project("leetcode.com")) == [(LO + 100, LO + 700)]
def test_stem_ignored_outside_browsers(monkeypatch: pytest.MonkeyPatch) -> None:
_fake_tracker(
monkeypatch,
[WIN, AFK],
{
"win_pc": [_ev(0, 600, app="Terminator", title="notes on leetcode")],
"afk_pc": ACTIVE_ALL,
},
)
assert browser.intervals(DAY, _project("leetcode.com")) == []
def test_full_pattern_matches_any_app_and_url(monkeypatch: pytest.MonkeyPatch) -> None:
_fake_tracker(
monkeypatch,
[WIN],
{
"win_pc": [
_ev(0, 60, app="x", title="t", url="https://HackerRank.com/a"),
_ev(100, 60, app="mpv", title="www.hackerrank.com talk"),
]
},
)
got = browser.intervals(DAY, _project("hackerrank.com"))
assert got == [(LO, LO + 60), (LO + 100, LO + 160)]
def test_afk_time_is_cut(monkeypatch: pytest.MonkeyPatch) -> None:
_fake_tracker(
monkeypatch,
[WIN, AFK],
{
"win_pc": [_ev(0, 1000, app="Helium", title="LeetCode")],
"afk_pc": [
_ev(100, 200, status="not-afk"),
_ev(500, 100, status="not-afk"),
],
},
)
assert browser.intervals(DAY, _project("leetcode.com")) == [
(LO + 100, LO + 300),
(LO + 500, LO + 600),
]
def test_afk_bucket_without_events_fails_closed(
monkeypatch: pytest.MonkeyPatch,
) -> None:
_fake_tracker(
monkeypatch,
[WIN, AFK],
{"win_pc": [_ev(0, 1000, app="Helium", title="LeetCode")], "afk_pc": []},
)
assert browser.intervals(DAY, _project("leetcode.com")) == []
def test_phone_bucket_has_no_afk_filter(monkeypatch: pytest.MonkeyPatch) -> None:
phone = _bucket("win_ph", "currentwindow", "pixel6a")
_fake_tracker(
monkeypatch,
[phone],
{"win_ph": [_ev(10, 90, app="Chrome", title="HackerRank")]},
)
assert browser.intervals(DAY, _project("hackerrank.com")) == [(LO + 10, LO + 100)]
def test_hosts_do_not_borrow_each_others_afk(monkeypatch: pytest.MonkeyPatch) -> None:
other = _bucket("afk_other", "afkstatus", "other")
_fake_tracker(
monkeypatch,
[WIN, AFK, other],
{
"win_pc": [_ev(0, 100, app="Helium", title="LeetCode")],
"afk_pc": ACTIVE_ALL,
"afk_other": [],
},
)
assert browser.intervals(DAY, _project("leetcode.com")) == [(LO, LO + 100)]
def test_no_patterns_no_calls(monkeypatch: pytest.MonkeyPatch) -> None:
calls = _fake_tracker(monkeypatch, [WIN], {})
assert browser.intervals(DAY, _project()) == []
assert calls == []
def test_short_stem_needs_the_full_pattern(monkeypatch: pytest.MonkeyPatch) -> None:
_fake_tracker(
monkeypatch,
[WIN],
{"win_pc": [_ev(0, 60, app="Helium", title="go to the shop")]},
)
assert browser.intervals(DAY, _project("go.dev")) == []
def test_query_is_bounded_to_the_day(monkeypatch: pytest.MonkeyPatch) -> None:
calls = _fake_tracker(monkeypatch, [WIN], {})
browser.intervals(DAY, _project("leetcode.com"))
params = next(p for path, p in calls if path.endswith("/events"))
assert params is not None
assert params["start"] < params["end"]
def test_no_config_is_inactive(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(browser, "_config", lambda: None)
assert browser.intervals(DAY, _project("leetcode.com")) == []
def test_unreachable_tracker_raises_for_the_registry(
monkeypatch: pytest.MonkeyPatch,
) -> None:
reason = "down"
def boom(*_a: object, **_k: object) -> None:
raise URLError(reason)
monkeypatch.setattr(browser, "_get_json", boom)
monkeypatch.setattr(browser, "_config", lambda: CFG)
project = _project("leetcode.com")
with pytest.raises(URLError):
browser.intervals(DAY, project)
assert sources.collect_by_source(DAY, project)["browser"] == []

View File

@ -0,0 +1,81 @@
# Copyright (c) 2026 Krzysztof Rudnicki
"""The browser adapter's plumbing: env-file config, HTTP, span maths."""
from __future__ import annotations
import io
from typing import TYPE_CHECKING, Any
from focus_project.sources import browser
if TYPE_CHECKING:
from pathlib import Path
import pytest
CFG = browser.Config("http://tracker.test", "tok")
def test_config_from_env_file(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
env = tmp_path / "env"
env.write_text("# c\nKT_URL=http://h:1\nKT_TOKEN='abc'\nJUNK\n")
monkeypatch.setenv("KUHYTRACK_ENV", str(env))
assert browser._config() == browser.Config("http://h:1", "abc")
def test_config_missing_file_is_none(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
monkeypatch.setenv("KUHYTRACK_ENV", str(tmp_path / "absent"))
assert browser._config() is None
def test_config_without_url_is_none(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
env = tmp_path / "env"
env.write_text("KT_TOKEN=abc\n")
monkeypatch.setenv("KUHYTRACK_ENV", str(env))
assert browser._config() is None
def test_get_json_sends_bearer_and_query(monkeypatch: pytest.MonkeyPatch) -> None:
seen: dict[str, Any] = {}
def fake_open(req: Any, timeout: float) -> io.BytesIO: # noqa: ANN401
seen["url"] = req.full_url
seen["auth"] = req.get_header("Authorization")
seen["timeout"] = timeout
return io.BytesIO(b'{"ok": 1}')
monkeypatch.setattr(browser, "_urlopen", fake_open)
assert browser._get_json(CFG, "/x", {"a": "b"}) == {"ok": 1}
assert seen == {
"url": "http://tracker.test/x?a=b",
"auth": "Bearer tok",
"timeout": 5,
}
def test_get_json_without_token_sends_no_header(
monkeypatch: pytest.MonkeyPatch,
) -> None:
seen: dict[str, Any] = {}
def fake_open(req: Any, timeout: float) -> io.BytesIO: # noqa: ANN401
seen["auth"] = req.get_header("Authorization")
return io.BytesIO(b"[]")
monkeypatch.setattr(browser, "_urlopen", fake_open)
assert browser._get_json(browser.Config("http://t", ""), "/x") == []
assert seen["auth"] is None
def test_intersect_and_merge() -> None:
merged = browser._merge([(5, 9), (0, 3), (2, 4), (9, 10)])
assert merged == [(0, 4), (5, 10)]
assert browser._intersect(merged, [(3, 6), (8, 20)]) == [(3, 4), (5, 6), (8, 10)]
def test_blank_pattern_is_ignored() -> None:
assert browser._needles((" ", "LeetCode.com")) == (["leetcode.com"], ["leetcode"])

View File

@ -9,14 +9,14 @@ import sys
import types
from typing import TYPE_CHECKING
import pytest
from focus_project import sources
from focus_project._model import Project
if TYPE_CHECKING:
from collections.abc import Callable
import pytest
DAY = date(2026, 11, 2)
PROJECT = Project(
id="p",
@ -92,3 +92,17 @@ def test_missing_adapter_is_inactive_not_an_error(
_fake(monkeypatch, "activity", _none)
monkeypatch.setattr(sources, "ADAPTERS", ("activity", "nonexistent"))
assert "nonexistent" not in sources.collect_by_source(DAY, PROJECT)
def test_broken_adapter_import_contributes_zero(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
def broken(name: str) -> None:
raise ImportError(name)
monkeypatch.setattr(sources.importlib, "import_module", broken)
with caplog.at_level(logging.ERROR):
result = sources.collect_by_source(DAY, PROJECT)
assert all(spans == [] for spans in result.values())
assert set(result) == set(sources.ADAPTERS)
assert "import failed" in caplog.text

View File

@ -0,0 +1,173 @@
# Copyright (c) 2026 Krzysztof Rudnicki
"""update_project: same validation as create, no rewriting of the past."""
from __future__ import annotations
from datetime import date, timedelta
import json
from typing import TYPE_CHECKING
import pytest
import focus_project as fp
if TYPE_CHECKING:
from pathlib import Path
D1 = date(2026, 11, 2)
D4 = date(2026, 11, 5)
DAY = timedelta(days=1)
def _make(pid: str = "hr", start: date = D1, end: date = D4) -> fp.Project:
return fp.create_project(
pid,
name="HackerRank prep",
start=start,
end=end,
replaces=["leetcode", "reading"],
daily_minutes=120,
unlock_minutes=30,
)
def test_update_changes_fields_and_normalizes() -> None:
_make()
got = fp.update_project(
"hr",
today=D1,
name="Interview",
end=D4 + DAY,
replaces=["book", "tutor", "book"],
subjects=["a"],
site_patterns=["x.com"],
)
assert fp.list_projects() == [got]
assert got.name == "Interview"
assert got.end == D4 + DAY
assert got.replaces == ("reading", "tutor")
assert got.subjects == ("a",)
assert got.site_patterns == ("x.com",)
assert got.created_ms == fp.list_projects()[0].created_ms
def test_update_nothing_is_a_noop() -> None:
before = _make()
assert fp.update_project("hr", today=D1) == before
def test_update_defaults_today_to_real_today() -> None:
now = date.today() # noqa: DTZ011
_make("now", start=now, end=now + DAY)
assert fp.update_project("now", name="X").name == "X"
def test_unknown_id_and_field() -> None:
_make()
with pytest.raises(KeyError):
fp.update_project("nope", today=D1, name="x")
with pytest.raises(ValueError, match="cannot change"):
fp.update_project("hr", today=D1, ended_on=D4)
@pytest.mark.parametrize(
("kw", "match"),
[
({"name": " "}, "name"),
({"end": D1 - DAY}, "end"),
({"replaces": ["workout"]}, "gate"),
({"replaces": []}, "replace"),
({"daily_minutes": 0}, "daily_minutes"),
({"unlock_minutes": 121}, "unlock_minutes"),
({"daily_minutes": 20}, "unlock_minutes"),
],
)
def test_update_validation(kw: dict[str, object], match: str) -> None:
before = _make()
with pytest.raises(ValueError, match=match):
fp.update_project("hr", today=D1, **kw)
assert fp.list_projects() == [before]
def test_update_overlap_rejected_self_is_not_overlap() -> None:
_make()
_make("next", start=D4 + DAY, end=D4 + 3 * DAY)
with pytest.raises(ValueError, match="overlap"):
fp.update_project("hr", today=D1, end=D4 + DAY)
fp.update_project("hr", today=D1, end=D4) # own range is fine
assert fp.update_project("hr", today=D1, start=D1, end=D4).end == D4
def test_past_start_refused_future_start_editable() -> None:
_make()
with pytest.raises(ValueError, match="start"):
fp.update_project("hr", today=D1 + DAY, start=D1 + 2 * DAY)
assert fp.update_project("hr", today=D1 + DAY, start=D1).start == D1
fp.update_project("hr", today=D1 - DAY, start=D1 + DAY)
assert fp.list_projects()[0].start == D1 + DAY
with pytest.raises(ValueError, match="start"):
fp.update_project("hr", today=D1, start=D1 - 2 * DAY)
def test_ended_and_finished_projects_refused() -> None:
_make()
with pytest.raises(ValueError, match="over"):
fp.update_project("hr", today=D4 + DAY, name="late")
fp.end_project("hr", D1)
with pytest.raises(ValueError, match="ended"):
fp.update_project("hr", today=D1, name="x")
def test_end_in_the_past_refused() -> None:
_make()
with pytest.raises(ValueError, match="past"):
fp.update_project("hr", today=D1 + 2 * DAY, end=D1 + DAY)
def test_daily_change_applies_from_today(data: Path) -> None:
_make()
fp.update_project("hr", today=D1 + 2 * DAY, daily_minutes=60, unlock_minutes=10)
p = fp.list_projects()[0]
assert (p.daily_minutes, p.unlock_minutes) == (60, 10)
assert p.daily_on(D1 + DAY) == 120
assert p.unlock_on(D1 + DAY) == 30
assert p.daily_on(D1 + 2 * DAY) == 60
assert p.unlock_on(D4) == 10
# a second edit the same day keeps the preserved past, a later day adds a row
fp.update_project("hr", today=D1 + 2 * DAY, daily_minutes=90)
assert len(fp.list_projects()[0].history) == 1
fp.update_project("hr", today=D4, daily_minutes=45, unlock_minutes=5)
p = fp.list_projects()[0]
assert [h.until for h in p.history] == [D1 + DAY, D4 - DAY]
assert p.daily_on(D1 + 2 * DAY) == 90
assert p.daily_on(D4) == 45
raw = json.loads((data / "projects.json").read_text())["projects"][0]
assert raw["history"][0] == {
"until": "2026-11-03",
"daily_minutes": 120,
"unlock_minutes": 30,
}
def test_future_project_daily_change_keeps_no_history() -> None:
_make()
fp.update_project("hr", today=D1 - DAY, daily_minutes=60, unlock_minutes=10)
p = fp.list_projects()[0]
assert p.history == ()
assert p.daily_on(D1) == 60
fp.update_project("hr", today=D1, daily_minutes=50) # first day: nothing past
assert fp.list_projects()[0].history == ()
def test_same_value_edit_adds_no_history() -> None:
_make()
fp.update_project("hr", today=D1 + DAY, daily_minutes=120, name="n")
assert fp.list_projects()[0].history == ()
def test_status_and_minutes_use_the_day_values(tmp_path: Path) -> None:
_make()
fp.update_project("hr", today=D1 + DAY, daily_minutes=60, unlock_minutes=10)
assert fp.status(D1)["daily_minutes"] == 120
assert fp.status(D1)["unlock_minutes"] == 30
assert fp.status(D1 + DAY)["daily_minutes"] == 60

View File

@ -0,0 +1,33 @@
#!/bin/bash
# Install + enable the focus_project harvester units (systemd --user).
# Run as the desktop user (never sudo). Idempotent. Needs focus_project
# importable by /usr/bin/python3 (see install.sh).
set -euo pipefail
REPO_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly REPO_DIR
readonly UNIT_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user"
readonly DATA_DIR="${FOCUS_PROJECT_DATA:-$HOME/.local/share/focus_project}"
readonly UNITS=(focus-project-harvest.service focus-project-harvest.path focus-project-harvest.timer)
if [[ "$(id -u)" -eq 0 ]]; then
echo "run as your own user, not root" >&2
exit 1
fi
(cd / && /usr/bin/python3 -c 'import focus_project') ||
{
echo "focus_project not importable: run $REPO_DIR/install.sh first" >&2
exit 1
}
# The .path unit watches files inside this directory.
mkdir -p "$DATA_DIR" "$UNIT_DIR"
for unit in "${UNITS[@]}"; do
install -m 0644 "$REPO_DIR/systemd/$unit" "$UNIT_DIR/$unit"
done
systemctl --user daemon-reload
systemctl --user enable --now focus-project-harvest.path focus-project-harvest.timer
for unit in "${UNITS[@]}"; do
diff -q "$REPO_DIR/systemd/$unit" "$UNIT_DIR/$unit"
done
echo "focus-project-harvest units installed and enabled"

View File

@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "focus_project"
version = "0.1.0"
version = "0.3.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.

View File

@ -0,0 +1,10 @@
[Unit]
Description=focus_project: harvest the moment activity or a LeetCode accept lands
[Path]
PathChanged=%h/.local/share/focus_project/activity.jsonl
PathChanged=%h/.local/share/leetcode_guard/ledger.json
Unit=focus-project-harvest.service
[Install]
WantedBy=default.target

View File

@ -0,0 +1,10 @@
[Unit]
Description=focus_project: credit focus minutes to the signed ledger
# The .path unit fires on every activity line; bursts must not trip the limit.
StartLimitIntervalSec=0
[Service]
Type=oneshot
WorkingDirectory=/
ExecStart=/usr/bin/python3 -m focus_project.harvest
Nice=10

View File

@ -0,0 +1,11 @@
[Unit]
Description=focus_project: harvest every minute (covers sources with no file event)
[Timer]
OnBootSec=1min
OnUnitInactiveSec=1min
AccuracySec=5s
Unit=focus-project-harvest.service
[Install]
WantedBy=timers.target

View File

@ -1,177 +0,0 @@
> **This file is a ready-to-use prompt.** Open this repo and say
> "do dopamine-ux-02-structural-check". It is self-contained -- it needs no context from
> any other session.
>
> Canonical copy: `~/src/utils/dopamine-ux/02-structural-check.md` (source of truth; this is a
> distributed copy). Running order and cross-prompt rules: `~/src/utils/dopamine-ux/00-INDEX.md`.
> Generated 2026-08-16 from a survey of this repo -- line numbers are accurate
> as of that date; **anchor on the symbol names, not the line numbers.**
## ⛔ WHEN YOU FINISH THIS PROMPT
Do **both**, in the same session that completes the work:
1. **Delete this file** and commit that deletion together with the
implementation:
```bash
git rm prompts/dopamine-ux-02-structural-check.md
```
Do not leave a finished prompt lying in the repo -- a stale prompt is
indistinguishable from a pending one, and the next session will re-run it.
2. **Log completion in the canonical index**, in `~/src/utils` (a *different* repo,
so it needs its own commit):
```bash
cd ~/src/utils
# append to the "Completion log" table in dopamine-ux/00-INDEX.md:
# | 02-structural-check.md | DONE <YYYY-MM-DD> | <impl commit sha> | <one-line note> |
git add dopamine-ux/00-INDEX.md
git commit -m "dopamine-ux: mark 02-structural-check.md done"
git push
```
If you finish only part of the prompt, do **neither** -- instead edit this file
to strike out what is done and state what remains, so the next session starts
from the true state. Partial completion must never be recorded as DONE.
---
Add a structural-token drift checker to CI
## findings (2, ranked by value over effort)
1. **Spacing, radius and type have never been drift-checked** — `palette_check.py`
parses hex only, so three whole token categories can diverge across stacks
while CI stays green. Motion inherits the same hole.
2. **`palette_map.py` points at a "scale check" that does not exist** — a
comment describing a guarantee nobody wrote.
## what
`palette_check.py` guarantees the colour palette agrees across all stack copies.
It does **not** check anything else — verified 2026-08-16 by reading its four
parsers, every one of which requires a `#RRGGBB` value:
```python
parse_css : r"(--[a-z0-9-]+)\s*:\s*(#[0-9A-Fa-f]{6})\s*;"
parse_dart: r"static const Color (\w+) = Color\(0x[fF]{2}([0-9A-Fa-f]{6})\)"
parse_tk : r'^\s{4}(\w+):\s*str\s*=\s*"(#[0-9A-Fa-f]{6})"'
parse_md : r"^\|\s*`([a-z0-9-]+)`\s*\|\s*`(#[0-9A-Fa-f]{6})`"
```
So **spacing, radius and type have been silently unprotected all along**, and the
motion tokens added by prompt 01 inherit the same hole. A `--duration-fast: 120ms`
is invisible to every parser: CI passes while the stacks drift apart.
Worse, `scripts/palette_map.py:159` claims structural values are "checked by the
scale check" — **no such script exists anywhere in `~/src/utils`**. That comment
describes a check that was never written. This prompt writes it.
## where
Repo: `~/src/utils`.
**Create** `~/src/utils/unified-design-system/scripts/structural_check.py`.
**Edit** `~/src/utils/.github/workflows/palette-drift.yml` — add a step invoking it.
The workflow deliberately has no `paths:` filter; keep it that way.
**Fix** the stale comment at `~/src/utils/unified-design-system/scripts/palette_map.py`
(~:159) to name the real script.
Sources to compare (three code stacks + the prose freeze):
| Role | Path |
|---|---|
| prose freeze | `~/src/utils/unified-design-system/tokens.md` (spacing/radius/type) |
| motion freeze | `~/src/utils/unified-design-system/motion.md` (**created by prompt 01** — run it first) |
| web/React | `~/src/utils/web_ui/src/tokens.css` |
| Flutter/Dart | `~/src/utils/design_system/lib/src/tokens.dart` |
| Python/Tkinter | `~/src/utils/gatelock/gatelock/_window.py` (`class LockConfig`) |
## must
- Cover **motion** (durations, easing) **and** the already-unprotected
**spacing, radius and type** scales, in one checker.
- Mirror `palette_check.py`'s two-halves design, because it is the part that
actually works:
1. **Agreement** — for each mapped token, resolve it in every non-`n/a` stack
and fail if values disagree.
2. **Completeness, bidirectional** — every structural value parsed out of any
source must be mapped, or explicitly exempted. This is what catches
"added it to one stack, forgot the others".
- Support an explicit **`n/a` per stack**, and require a reason string. Tkinter
has no animation framework; a duration legitimately does not exist there. An
honest `n/a` with a reason is correct — a fabricated constant is not.
- **Adjudicate with exit codes.** Exit non-zero on drift with a message naming
the token and the disagreeing files. No warnings-only mode.
- Keep every file ≤ **250 lines** (`~/src/utils/file_length/config.py`). Note
`palette_check.py` is 231 and `palette_map.py` is 162 — that pair was split
precisely to stay under the cap. **Split yours the same way from the start**
(`structural_check.py` + `structural_map.py`) rather than discovering the
problem at 251 lines.
- Ruff-clean under the repo's config. No `# noqa`, no `type: ignore`.
- **Expect it to fail on first run.** Spacing/radius/type have never been
compared; there may be real pre-existing drift. That is the point of writing
it. Fix whatever it surfaces, in the stack copy that is wrong, and say in the
session summary what drifted.
- must not: weaken the checker, add an exemption, or narrow its scope to make it
green. If a token genuinely differs per stack for a good reason, encode it as
an `n/a`/variant **with the reason recorded**, not as a silent skip.
- must not: modify `palette_check.py`. It works; it is simply colour-only. The
two scripts run side by side.
- must not: change any token *value* to resolve a disagreement without saying so
explicitly — that is a design change, and `tokens.md` is a freeze. Surface it
and let kuhy decide which value is canonical.
- optional: teach it the shadow tier too, if that falls out cheaply.
## done
1. `python3 ~/src/utils/unified-design-system/scripts/structural_check.py` exits 0,
and exits non-zero when you deliberately break one stack copy (**test both
directions** — a checker that never fails is not a checker).
2. It is wired into `~/src/utils/.github/workflows/palette-drift.yml` and the
workflow passes.
3. `palette_map.py`'s "scale check" comment names the real script.
4. `~/src/utils/scripts/check_file_length.sh --all` reports no new violations.
5. The session summary states what drift, if any, the first run found.
## verify
Desktop. Run the script, paste the output. Then prove it fails: change one
spacing or duration value in **one** stack copy, re-run, paste the non-zero exit
and the message, and revert. Both halves of that demonstration are required —
the passing run alone proves nothing.
## read first
- `~/src/utils/unified-design-system/scripts/palette_check.py` — the design to
mirror. Read `NON_COLOUR_CSS`: it is the regex that currently *excludes*
spacing/radius/type/shadow from the colour check, and therefore the precise
list of what you are now covering.
- `~/src/utils/unified-design-system/scripts/palette_map.py` — the `PALETTE` tuple of
`Token(canonical, md, css, dart, tk, why)` rows. Your map wants the same shape,
including the `why` field.
- `~/src/utils/.github/workflows/palette-drift.yml` — how `palette_check.py` and
`ramp_check.py` are invoked; add your step alongside.
- `~/src/utils/unified-design-system/motion.md` — what prompt 01 created.
- `~/src/utils/unified-design-system/tokens.md` — the spacing/radius/type tables.
**Do not edit it**; it is 260 lines and already over the cap.
## context you would otherwise rediscover
- The four "stack copies" are really **three code stacks plus a prose freeze**.
There is no fourth code stack; do not hunt for one.
- `~/src/dufs-cloud/app/lib/ui/theme.dart` is a **fifth, uncompared copy** of the
palette (the Flutter app has no `design_system` dependency and hand-restates
every hex). It is out of scope here — prompt 07 wires it up properly. Do not
add it as a source to this checker; wait until 07 has removed it.
- Three Flutter apps (diet-guard, workout_app, wake_alarm) similarly
hand-transcribe tokens into local `lib/ui/theme.dart` files. Those are
deliberately outside the checker's scope for now — bringing them in is a much
larger job than this prompt.
- `~/src/utils/gatelock/` is a package inside this monorepo, not a separate repo.
REMOVE ME AFTER FINISH

View File

@ -156,7 +156,7 @@ PALETTE: tuple[Token, ...] = (
)
# Tokens a source legitimately defines that are not colours in the palette --
# structural/typographic values checked by the scale check, not the hex check.
# structural/typographic values checked by structural_check.py, not the hex check.
NON_COLOUR_CSS = re.compile(
r"^--(radius|space|text|tracking|font|measure|shadow)-|^--(font-sans|font-mono|measure)$"
)

View File

@ -0,0 +1,138 @@
"""Verify spacing, radius, type, shadow and motion agree across all stacks.
`palette_check.py` guards colour only (every parser wants `#RRGGBB`), so these
scales were unprotected until now. Same two halves:
* agreement -- each mapped token resolves in every stack that is not `n/a`
for it, and all stacks carry the same value
* completeness -- every structural name any source defines is mapped or
exempted with a reason, in both directions (a stale exemption also fails)
Sources: DOCS-tokens.md + DOCS-motion.md (prose freeze), web_ui tokens.css,
design_system tokens.dart, gatelock _theme.py.
Run: python3 unified-design-system/scripts/structural_check.py
Exit 0 = agree and complete; 1 = drift, a missing value or an unmapped name.
"""
from __future__ import annotations
import re
import sys
from dataclasses import dataclass
from pathlib import Path
import structural_parse as sp
from structural_map import EXEMPT, STACKS, TOKENS
ROOT = Path(__file__).resolve().parents[2]
SOURCE_FILES: dict[str, str] = {
"md": "unified-design-system/DOCS-tokens.md",
"motion": "unified-design-system/DOCS-motion.md",
"css": "web_ui/src/tokens.css",
"dart": "design_system/lib/src/tokens.dart",
"tk": "gatelock/gatelock/_theme.py",
}
@dataclass
class Result:
"""One check outcome."""
ok: bool
detail: str
def norm(kind: str, raw: str) -> str:
"""Reduce a raw source value to a comparable string for its kind."""
if kind == "shadow":
return " ".join(raw.split())
nums = re.findall(r"-?\d*\.?\d+", raw)
if kind == "ease":
return ",".join(f"{float(n):g}" for n in nums)
if not nums:
return "0" if "zero" in raw else raw.strip()
return f"{float(nums[0]):g}"
def load(root: Path) -> dict[str, sp.Table]:
"""Parse every source under `root` into `{stack: {key: raw}}`."""
def read(key: str) -> str:
return (root / SOURCE_FILES[key]).read_text(encoding="utf-8")
return {
"md": {**sp.parse_tokens_md(read("md")), **sp.parse_motion_md(read("motion"))},
"css": sp.parse_css(read("css")),
"dart": sp.parse_dart(read("dart")),
"tk": sp.parse_tk(read("tk")),
}
def check_agreement(src: dict[str, sp.Table]) -> list[Result]:
"""Every mapped token must carry one value in every non-`n/a` stack."""
results: list[Result] = []
for token in TOKENS:
kind = token.canonical.split(".")[0]
names = {"md": token.canonical, **{s: getattr(token, s) for s in STACKS}}
seen: dict[str, str] = {}
missing: list[str] = []
for stack, name in names.items():
if name is None:
continue
if name in src[stack]:
seen[stack] = norm(kind, src[stack][name])
else:
missing.append(f"{stack}:{name} ({SOURCE_FILES[stack]})")
if missing:
results.append(Result(False, f"{token.canonical:<20} MISSING {', '.join(missing)}"))
elif len(set(seen.values())) > 1:
detail = ", ".join(f"{s}={v}" for s, v in seen.items())
files = ", ".join(SOURCE_FILES[s] for s in seen)
results.append(Result(False, f"{token.canonical:<20} DRIFT {detail} [{files}]"))
else:
results.append(
Result(True, f"{token.canonical:<20} {next(iter(seen.values()))} x{len(seen)}")
)
return results
def check_completeness(src: dict[str, sp.Table]) -> list[Result]:
"""No unmapped name in any source, and no exemption for a vanished name."""
results: list[Result] = []
for stack in ("md", *STACKS):
if stack == "md":
mapped = {t.canonical for t in TOKENS}
else:
mapped = {getattr(t, stack) for t in TOKENS if getattr(t, stack)}
exempt = EXEMPT.get(stack, {})
extras = sorted(n for n in src[stack] if n not in mapped and n not in exempt)
stale = sorted(n for n in exempt if n not in src[stack])
if extras:
msg = f"{stack:<4} defines unmapped name(s): {', '.join(extras)} -- add to TOKENS or EXEMPT"
results.append(Result(False, msg))
if stale:
results.append(Result(False, f"{stack:<4} stale exemption(s): {', '.join(stale)}"))
if not extras and not stale:
results.append(Result(True, f"{stack:<4} all {len(src[stack])} parsed name(s) accounted for"))
return results
def run(root: Path) -> list[Result]:
"""Both halves of the check against the sources under `root`."""
src = load(root)
return [*check_agreement(src), *check_completeness(src)]
def main(root: Path = ROOT) -> int:
"""Print the report; non-zero on any failing check."""
results = run(root)
for r in results:
print(("PASS " if r.ok else "FAIL ") + r.detail)
failures = sum(not r.ok for r in results)
print(f"\n{failures} failing check(s)")
return 1 if failures else 0
if __name__ == "__main__":
sys.exit(main())

View File

@ -0,0 +1,87 @@
"""The canonical structural-token table: spacing, radius, type, shadow, motion.
Colour is `palette_map.py`; this is its twin for everything that is not a
colour. Pure data -- parsing and comparison live in `structural_check.py`.
A canonical key is `<kind>.<name>` (`space.sm`, `duration.fast`) and is also
the key the prose freezes (`DOCS-tokens.md`, `DOCS-motion.md`) are parsed
into, so the md stack needs no column of its own. A `None` name means the
token is intentionally absent from that stack and `why` must say so: an
honest `n/a` with a reason, never a fabricated constant.
"""
from __future__ import annotations
from dataclasses import dataclass
STACKS = ("css", "dart", "tk")
@dataclass(frozen=True)
class Token:
"""One canonical structural token and its name in each code stack."""
canonical: str
css: str | None
dart: str | None
tk: str | None
why: str = ""
def __post_init__(self) -> None:
"""Refuse an absence that carries no recorded reason."""
if None in (self.css, self.dart, self.tk) and not self.why:
msg = f"{self.canonical}: a stack is n/a but `why` is empty"
raise ValueError(msg)
_TK_NO_RADIUS = "Tk has no corner-radius primitive: widgets are square."
_TK_NO_MOTION = "Tkinter has no animation framework; a duration would be dead."
_NO_SHADOW = (
"Dark-first Flutter/Tk surfaces take no shadow (elevation is a fill step); "
"only web light surfaces opt in."
)
_STEPS = ("xs", "sm", "md", "lg", "xl", "xxl")
_TYPE = ("display", "title", "subtitle", "body", "label", "caption")
TOKENS: tuple[Token, ...] = (
*(
Token(f"space.{s}", f"--space-{i}", f"AppSpacing.{s}", f"LockSpacing.{s}")
for i, s in enumerate(_STEPS, 1)
),
*(
Token(f"radius.{s}", f"--radius-{s}", f"AppRadius.{s}", None, _TK_NO_RADIUS)
for s in ("sm", "md", "lg")
),
*(
Token(f"text.{t}", f"--text-{t}", f"AppTextSize.{t}", f"LockTypography.{t}")
for t in _TYPE
),
*(Token(f"shadow.{n}", f"--shadow-{n}", None, None, _NO_SHADOW) for n in (1, 2)),
*(
Token(f"duration.{d}", f"--duration-{d}", f"AppDuration.{d}", None, _TK_NO_MOTION)
for d in ("instant", "fast", "base", "slow")
),
*(
Token(f"ease.{e}", f"--ease-{e}", f"AppCurve.{e}", None, _TK_NO_MOTION)
for e in ("standard", "decelerate", "accelerate")
),
)
# Names a source defines that are deliberately outside the compared scales.
# Per stack, name -> reason. A silent skip is the fail-open path this closes.
_TRACKING = "Tracking is an approximate range in the freeze ('tight, e.g. -0.2px'), not a value."
EXEMPT: dict[str, dict[str, str]] = {
"css": {
"--tracking-display": _TRACKING,
"--tracking-title": _TRACKING,
"--tracking-label": _TRACKING,
"--tracking-caption": _TRACKING,
"--font-sans": "Font stacks are per-platform by design (DOCS-tokens.md, Typography).",
"--font-mono": "Font stacks are per-platform by design (DOCS-tokens.md, Typography).",
"--measure": "Web-only prose line-length cap (rule 21); no Dart/Tk text measure.",
},
"dart": {},
"tk": {
"LockSpacing.focus_thickness": "Focus-ring width (operability doc), not a scale step.",
},
}

View File

@ -0,0 +1,110 @@
"""Parsers for `structural_check.py`: one per source, all fail closed.
Every parser returns `{key: raw_value}` and raises `SystemExit` when the
structure it expects is gone. Returning `{}` would make a moved file read as
"0 parsed, 0 drifted" -- the exact vacuous pass `palette_check.py` was bitten
by -- so a vanished section is an error, never a skip.
"""
from __future__ import annotations
import re
Table = dict[str, str]
def _die(msg: str) -> None:
raise SystemExit(f"structural_check: {msg}")
def section(text: str, header: str) -> str:
"""Body of the `## <header>` section, up to the next `## ` heading."""
m = re.search(rf"^## {re.escape(header)}.*?$(.*?)(?=^## |\Z)", text, re.M | re.S)
if not m:
_die(f"section '## {header}' not found; the freeze was renamed or moved")
return m.group(1)
def parse_tokens_md(text: str) -> Table:
"""Spacing, radius, type and shadow rows from `DOCS-tokens.md`."""
found: Table = {}
steps = re.search(r"`([^`\n]*·[^`\n]*)`", section(text, "Spacing scale"))
if steps:
for name, val in re.findall(r"(\w+) (\d+)", steps.group(1)):
found[f"space.{name}"] = val
for name, val in re.findall(r"`(\w+) (\d+)`", section(text, "Corner radius scale")):
found[f"radius.{name}"] = val
for name, val in re.findall(
r"^\|\s*`(\w+)`\s*\|\s*(\d+)\s*\|", section(text, "Typography scale"), re.M
):
found[f"text.{name}"] = val
for level, val in re.findall(
r"Level (\d)[^`\n]*`([^`\n]+)`", section(text, "Shadow policy")
):
found[f"shadow.{level}"] = val
return found
def parse_motion_md(text: str) -> Table:
"""Duration and easing rows from `DOCS-motion.md`."""
found: Table = {}
row = r"^\|\s*`(\w+)`\s*\|\s*`([^`]+)`"
for name, val in re.findall(row, section(text, "Duration"), re.M):
found[f"duration.{name}"] = val
for name, val in re.findall(row, section(text, "Easing"), re.M):
found[f"ease.{name}"] = val
return found
def parse_css(text: str) -> Table:
"""Root-scope structural custom properties from `tokens.css`.
Everything from the first `@media` on is overrides (reduced motion, dark
shadows); the freeze is the root block above it.
"""
text = re.sub(r"/\*.*?\*/", "", text, flags=re.S) # prose may name tokens
cut = text.find("@media")
if cut == -1:
_die("tokens.css has no @media block; cannot find the end of :root")
decl = re.compile(
r"(--(?:space|radius|text|shadow|duration|ease|tracking|font|measure)[a-z0-9-]*)"
r"\s*:\s*([^;]+);"
)
return {
name: value.strip()
for name, value in decl.findall(text[:cut])
if not value.strip().startswith("#") # `--text`, `--text-muted`: colours
}
def _classes(text: str, opener: str) -> list[tuple[str, str]]:
"""(name, body) of each class; `opener` is the regex that starts one."""
parts = list(re.finditer(opener, text, re.M))
if not parts:
return []
ends = [m.start() for m in parts[1:]] + [len(text)]
return [(m.group(1), text[m.end() : end]) for m, end in zip(parts, ends, strict=True)]
def parse_dart(text: str) -> Table:
"""`static const double|Duration|Curve` members, keyed `Class.member`."""
found: Table = {}
member = re.compile(r"static const (?:double|Duration|Curve) (\w+) = ([^;]+);")
for cls, body in _classes(text, r"^abstract final class (\w+)"):
for name, value in member.findall(body):
found[f"{cls}.{name}"] = value.strip()
if not found:
_die("tokens.dart has no double/Duration/Curve constants")
return found
def parse_tk(text: str) -> Table:
"""Integer dataclass fields, keyed `Class.field`."""
found: Table = {}
field = re.compile(r"^ {4}(\w+):\s*int\s*=\s*(\d+)", re.M)
for cls, body in _classes(text, r"^class (\w+)"):
for name, value in field.findall(body):
found[f"{cls}.{name}"] = value
if not found:
_die("_theme.py has no int fields; the scales moved out of it")
return found

View File

@ -0,0 +1,182 @@
"""Tests for scripts/structural_check.py: both directions of the checker."""
from __future__ import annotations
import shutil
import subprocess
import sys
from pathlib import Path
import pytest
import structural_check
import structural_map
REAL_ROOT = Path(__file__).resolve().parents[2]
@pytest.fixture
def root(tmp_path: Path) -> Path:
"""A scratch copy of the five source files, mutable per test."""
for rel in structural_check.SOURCE_FILES.values():
dest = tmp_path / rel
dest.parent.mkdir(parents=True, exist_ok=True)
shutil.copy(REAL_ROOT / rel, dest)
return tmp_path
def edit(root: Path, stack: str, old: str, new: str) -> None:
path = root / structural_check.SOURCE_FILES[stack]
text = path.read_text(encoding="utf-8")
assert old in text, f"{old!r} not in {path}"
path.write_text(text.replace(old, new, 1), encoding="utf-8")
def failures(root: Path) -> list[str]:
return [r.detail for r in structural_check.run(root) if not r.ok]
def test_real_tree_is_green() -> None:
assert failures(REAL_ROOT) == []
assert structural_check.main(REAL_ROOT) == 0
@pytest.mark.parametrize(
("stack", "old", "new", "token"),
[
("css", "--space-2: 8px", "--space-2: 9px", "space.sm"),
("dart", "double sm = 8;", "double sm = 9;", "space.sm"),
("tk", "sm: int = 8", "sm: int = 9", "space.sm"),
("css", "--duration-fast: 120ms;", "--duration-fast: 130ms;", "duration.fast"),
("dart", "milliseconds: 200", "milliseconds: 210", "duration.base"),
("css", "cubic-bezier(0.3, 0, 1, 1)", "cubic-bezier(0.4, 0, 1, 1)", "ease.accelerate"),
("dart", "Cubic(0, 0, 0, 1)", "Cubic(0, 0, 0, 2)", "ease.decelerate"),
("css", "--radius-md: 12px", "--radius-md: 13px", "radius.md"),
("tk", "title: int = 24", "title: int = 25", "text.title"),
("css", "0 4px 8px rgba", "0 5px 8px rgba", "shadow.2"),
("md", "`sm 8` (buttons", "`sm 7` (buttons", "radius.sm"),
("motion", "`200ms`", "`210ms`", "duration.base"),
],
)
def test_value_drift_fails_naming_the_token(
root: Path, stack: str, old: str, new: str, token: str
) -> None:
edit(root, stack, old, new)
found = failures(root)
assert any(token in line and "DRIFT" in line for line in found), found
assert structural_check.main(root) == 1
def test_missing_in_a_stack_fails(root: Path) -> None:
edit(root, "css", "--space-2: 8px;", "")
assert any("space.sm" in f and "MISSING" in f for f in failures(root))
def test_unmapped_css_token_fails_completeness(root: Path) -> None:
edit(root, "css", "--space-6: 48px;", "--space-6: 48px; --space-7: 64px;")
assert any("css" in f and "--space-7" in f for f in failures(root))
def test_unmapped_dart_token_fails_completeness(root: Path) -> None:
edit(root, "dart", "static const double xxl = 48;", "static const double xxl = 48;\n static const double huge = 64;")
assert any("dart" in f and "AppSpacing.huge" in f for f in failures(root))
def test_unmapped_tk_token_fails_completeness(root: Path) -> None:
edit(root, "tk", "xxl: int = 48", "xxl: int = 48\n huge: int = 64")
assert any("tk" in f and "LockSpacing.huge" in f for f in failures(root))
def test_unmapped_md_token_fails_completeness(root: Path) -> None:
edit(root, "motion", "| `slow` | `320ms` |", "| `glacial` | `900ms` |\n| `slow` | `320ms` |")
assert any("md" in f and "duration.glacial" in f for f in failures(root))
def test_unmapped_shadow_in_md_fails(root: Path) -> None:
edit(root, "md", "- Level 1 (e.g. a dropdown)", "- Level 3 (e.g. a toast): `0 8px 16px rgba(0, 0, 0, 0.2)`\n - Level 1 (e.g. a dropdown)")
assert any("shadow.3" in f for f in failures(root))
def test_stale_exemption_fails(root: Path) -> None:
edit(root, "css", "--measure: 40rem;", "")
assert any("--measure" in f and "stale" in f for f in failures(root))
def test_missing_section_fails_closed(root: Path) -> None:
edit(root, "md", "## Spacing scale (4px base)", "## Renamed")
with pytest.raises(SystemExit):
structural_check.run(root)
def test_missing_class_fails_closed(root: Path) -> None:
edit(root, "tk", "class LockSpacing", "class Renamed")
# Renamed class still has int fields, so the tokens map to nothing.
assert any("LockSpacing" in f for f in failures(root))
def test_no_dart_class_fails_closed(root: Path) -> None:
path = root / structural_check.SOURCE_FILES["dart"]
path.write_text("// empty\n", encoding="utf-8")
with pytest.raises(SystemExit):
structural_check.run(root)
def test_no_tk_ints_fails_closed(root: Path) -> None:
path = root / structural_check.SOURCE_FILES["tk"]
path.write_text("x = 1\n", encoding="utf-8")
with pytest.raises(SystemExit):
structural_check.run(root)
def test_css_without_media_fails_closed(root: Path) -> None:
path = root / structural_check.SOURCE_FILES["css"]
text = path.read_text(encoding="utf-8")
path.write_text(text.replace("@media", "@supports"), encoding="utf-8")
with pytest.raises(SystemExit):
structural_check.run(root)
def test_absent_stack_requires_a_reason() -> None:
with pytest.raises(ValueError, match="why"):
structural_map.Token("space.zz", "--space-zz", None, "x")
@pytest.mark.parametrize(
("kind", "raw", "expected"),
[
("space", "8px", "8"),
("duration", "Duration.zero", "0"),
("duration", "0ms", "0"),
("duration", "Duration(milliseconds: 120)", "120"),
("ease", "cubic-bezier(0.2, 0, 0, 1)", "0.2,0,0,1"),
("ease", "Cubic(0.2, 0, 0, 1)", "0.2,0,0,1"),
("shadow", "0 2px 4px", "0 2px 4px"),
("space", "none", "none"),
],
)
def test_norm(kind: str, raw: str, expected: str) -> None:
assert structural_check.norm(kind, raw) == expected
def test_cli_exit_codes(root: Path) -> None:
script = REAL_ROOT / "unified-design-system/scripts/structural_check.py"
ok = subprocess.run([sys.executable, str(script)], check=False, capture_output=True)
assert ok.returncode == 0
edit(root, "css", "--space-2: 8px", "--space-2: 9px")
scratch = root / "unified-design-system/scripts"
scratch.mkdir(parents=True)
for name in ("structural_check.py", "structural_map.py", "structural_parse.py"):
shutil.copy(script.parent / name, scratch / name)
bad = subprocess.run(
[sys.executable, str(scratch / "structural_check.py")],
check=False,
capture_output=True,
text=True,
)
assert bad.returncode == 1
assert "space.sm" in bad.stdout
assert "DRIFT" in bad.stdout
def test_spacing_line_absent_is_not_invented(root: Path) -> None:
edit(root, "md", "`xs 4 · sm 8", "xs 4 · sm 8")
assert any("MISSING" in f and "space." in f for f in failures(root))