quotapilot 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,9 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.pyc
4
+ .pytest_cache/
5
+ .mypy_cache/
6
+ .ruff_cache/
7
+ dist/
8
+ build/
9
+ *.egg-info/
@@ -0,0 +1,10 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0
4
+
5
+ First release.
6
+
7
+ - `decide`: project what each account loses at the measured (or average) pace, which account to
8
+ drain first, burn or normal, and the secondary-window-first rule with carry-over.
9
+ - `Account`, `Config`, `project`, `pace_from_history`, `average_pace`.
10
+ - `quotapilot.adapters.claude_swap`: read `cswap list --json` into accounts.
@@ -0,0 +1,23 @@
1
+ # Contributing
2
+
3
+ Bug reports with the numbers that surprise you are the most useful thing: the accounts
4
+ (used percent and reset times), the history samples and the `Config` you passed.
5
+
6
+ Changes are made here. A change is released as a new version, and the projects that use
7
+ quotapilot bump their pin.
8
+
9
+ ## Setup
10
+
11
+ ```bash
12
+ python -m venv .venv && . .venv/bin/activate
13
+ pip install -e ".[dev]"
14
+ pytest
15
+ ruff check . && ruff format --check . && mypy quotapilot
16
+ ```
17
+
18
+ ## Rules
19
+
20
+ - `quotapilot/core.py` imports the standard library only. No runtime dependency.
21
+ - Python 3.9 compatible.
22
+ - Every datetime is timezone-aware.
23
+ - A change to the algorithm comes with a test that pins the numbers.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Dylan Merigaud
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,131 @@
1
+ Metadata-Version: 2.5
2
+ Name: quotapilot
3
+ Version: 0.1.0
4
+ Summary: Project what expires unused across several accounts with weekly quota windows, and say which account to drain first. No dependencies, no network.
5
+ Project-URL: Homepage, https://github.com/DylanMerigaud/quotapilot
6
+ Project-URL: Source, https://github.com/DylanMerigaud/quotapilot
7
+ Project-URL: Issues, https://github.com/DylanMerigaud/quotapilot/issues
8
+ Project-URL: Changelog, https://github.com/DylanMerigaud/quotapilot/blob/main/CHANGELOG.md
9
+ Author: Dylan Merigaud
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: accounts,claude,claude-swap,quota,rate-limit,scheduling,usage
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.9
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Typing :: Typed
24
+ Requires-Python: >=3.9
25
+ Provides-Extra: dev
26
+ Requires-Dist: build; extra == 'dev'
27
+ Requires-Dist: mypy; extra == 'dev'
28
+ Requires-Dist: pytest>=7; extra == 'dev'
29
+ Requires-Dist: ruff; extra == 'dev'
30
+ Provides-Extra: test
31
+ Requires-Dist: pytest>=7; extra == 'test'
32
+ Description-Content-Type: text/markdown
33
+
34
+ # quotapilot
35
+
36
+ You have several accounts, each with a weekly quota window that resets at its own time. Whatever
37
+ is not used before a reset is lost. quotapilot looks at how much each account has used and how
38
+ fast you burn, projects what expires unused, tells you which account to drain first, and says
39
+ whether you are in `burn` (something will expire) or `normal` (nothing will).
40
+
41
+ Pure Python, standard library only, no network, Python 3.9 and up.
42
+
43
+ ```bash
44
+ pip install quotapilot
45
+ ```
46
+
47
+ ## Example
48
+
49
+ ```python
50
+ from datetime import datetime, timedelta, timezone
51
+
52
+ from quotapilot import Account, decide
53
+
54
+ now = datetime(2026, 11, 18, 12, 0, tzinfo=timezone.utc)
55
+ accounts = [
56
+ Account("work", used_pct=80, reset=now + timedelta(hours=20)),
57
+ Account("personal", used_pct=10, reset=now + timedelta(hours=100)),
58
+ ]
59
+ # history: (when, account name, used percent) samples of the last day, oldest first
60
+ history = [(now - timedelta(hours=8), "work", 72), (now, "work", 80)]
61
+
62
+ result = decide(accounts, history, now)
63
+ print(result["summary"])
64
+ print(result["state"], result["drain_first"], result["pace_pct_h"])
65
+ ```
66
+
67
+ `decide` returns a dict: `state` (`burn` or `normal`), `drain_first`, `pace_pct_h` and
68
+ `pace_source` (`measured` from your history, else the `average` over the elapsed weeks),
69
+ `lost_units` and `unavoidable_units`, one row per account (`room_pct`, `lost_pct`, `lost_units`,
70
+ `empty_at`), and a one-line English `summary` with times in UTC.
71
+
72
+ A unit is what you decide it is. By default one unit is one percent point of one account-week.
73
+ Set `Config(units_per_week=1000, max_units_per_h=40, burn_floor_units=10)` to count in your own
74
+ units, to get `unavoidable_units` (what would still expire even at your maximum pace), and to say
75
+ how many lost units make a `burn`.
76
+
77
+ The optional secondary window (`Account.secondary_pct`, `secondary_reset`) is a second, narrower
78
+ quota some providers add, such as a per-model weekly limit. When the account to drain first loses
79
+ nothing, the account whose secondary window just reset or dropped is named in `secondary_first`
80
+ and held there for `secondary_hold_h` hours; pass the last result back as `previous=` to carry it.
81
+
82
+ ## With claude-swap
83
+
84
+ quotapilot is an addon above [claude-swap](https://github.com/realiti4/claude-swap), not a
85
+ replacement. claude-swap holds your accounts and does the switching. quotapilot only decides.
86
+ Feed it the output of `cswap list --json`:
87
+
88
+ ```python
89
+ from datetime import datetime, timezone
90
+
91
+ from quotapilot import decide
92
+ from quotapilot.adapters import claude_swap
93
+
94
+ # accounts = claude_swap.read() # runs `cswap list --json` and parses it
95
+ payload = { # the shape of `cswap list --json`
96
+ "accounts": [
97
+ {
98
+ "number": 1,
99
+ "usageStatus": "ok",
100
+ "usage": {"sevenDay": {"pct": 42, "resetsAt": "2026-11-21T09:00:00Z"}},
101
+ },
102
+ {
103
+ "number": 2,
104
+ "usageStatus": "ok",
105
+ "usage": {"sevenDay": {"pct": 90, "resetsAt": "2026-11-19T09:00:00Z"}},
106
+ },
107
+ ]
108
+ }
109
+ accounts = claude_swap.parse_list(payload)
110
+ now = datetime(2026, 11, 18, 12, 0, tzinfo=timezone.utc)
111
+ print(decide(accounts, [], now)["summary"])
112
+ ```
113
+
114
+ `parse_list(data, secondary_name=...)` picks the per-model weekly window of `usage.scoped` by
115
+ name for the secondary window (the first one when omitted).
116
+
117
+ ## What it does not do
118
+
119
+ - It does not switch accounts. You (or claude-swap) act on `drain_first`.
120
+ - The core makes no network call and calls no provider API. Only `claude_swap.read()` runs
121
+ `cswap list --json`, and claude-swap fetches the usage itself.
122
+ - It stores no account, no credential and no history: you pass the samples in.
123
+
124
+ ## Contributing
125
+
126
+ Changes are made in this repository, released as a new version, and the projects that use
127
+ quotapilot bump their pin. See [CONTRIBUTING.md](CONTRIBUTING.md).
128
+
129
+ ## License
130
+
131
+ MIT
@@ -0,0 +1,98 @@
1
+ # quotapilot
2
+
3
+ You have several accounts, each with a weekly quota window that resets at its own time. Whatever
4
+ is not used before a reset is lost. quotapilot looks at how much each account has used and how
5
+ fast you burn, projects what expires unused, tells you which account to drain first, and says
6
+ whether you are in `burn` (something will expire) or `normal` (nothing will).
7
+
8
+ Pure Python, standard library only, no network, Python 3.9 and up.
9
+
10
+ ```bash
11
+ pip install quotapilot
12
+ ```
13
+
14
+ ## Example
15
+
16
+ ```python
17
+ from datetime import datetime, timedelta, timezone
18
+
19
+ from quotapilot import Account, decide
20
+
21
+ now = datetime(2026, 11, 18, 12, 0, tzinfo=timezone.utc)
22
+ accounts = [
23
+ Account("work", used_pct=80, reset=now + timedelta(hours=20)),
24
+ Account("personal", used_pct=10, reset=now + timedelta(hours=100)),
25
+ ]
26
+ # history: (when, account name, used percent) samples of the last day, oldest first
27
+ history = [(now - timedelta(hours=8), "work", 72), (now, "work", 80)]
28
+
29
+ result = decide(accounts, history, now)
30
+ print(result["summary"])
31
+ print(result["state"], result["drain_first"], result["pace_pct_h"])
32
+ ```
33
+
34
+ `decide` returns a dict: `state` (`burn` or `normal`), `drain_first`, `pace_pct_h` and
35
+ `pace_source` (`measured` from your history, else the `average` over the elapsed weeks),
36
+ `lost_units` and `unavoidable_units`, one row per account (`room_pct`, `lost_pct`, `lost_units`,
37
+ `empty_at`), and a one-line English `summary` with times in UTC.
38
+
39
+ A unit is what you decide it is. By default one unit is one percent point of one account-week.
40
+ Set `Config(units_per_week=1000, max_units_per_h=40, burn_floor_units=10)` to count in your own
41
+ units, to get `unavoidable_units` (what would still expire even at your maximum pace), and to say
42
+ how many lost units make a `burn`.
43
+
44
+ The optional secondary window (`Account.secondary_pct`, `secondary_reset`) is a second, narrower
45
+ quota some providers add, such as a per-model weekly limit. When the account to drain first loses
46
+ nothing, the account whose secondary window just reset or dropped is named in `secondary_first`
47
+ and held there for `secondary_hold_h` hours; pass the last result back as `previous=` to carry it.
48
+
49
+ ## With claude-swap
50
+
51
+ quotapilot is an addon above [claude-swap](https://github.com/realiti4/claude-swap), not a
52
+ replacement. claude-swap holds your accounts and does the switching. quotapilot only decides.
53
+ Feed it the output of `cswap list --json`:
54
+
55
+ ```python
56
+ from datetime import datetime, timezone
57
+
58
+ from quotapilot import decide
59
+ from quotapilot.adapters import claude_swap
60
+
61
+ # accounts = claude_swap.read() # runs `cswap list --json` and parses it
62
+ payload = { # the shape of `cswap list --json`
63
+ "accounts": [
64
+ {
65
+ "number": 1,
66
+ "usageStatus": "ok",
67
+ "usage": {"sevenDay": {"pct": 42, "resetsAt": "2026-11-21T09:00:00Z"}},
68
+ },
69
+ {
70
+ "number": 2,
71
+ "usageStatus": "ok",
72
+ "usage": {"sevenDay": {"pct": 90, "resetsAt": "2026-11-19T09:00:00Z"}},
73
+ },
74
+ ]
75
+ }
76
+ accounts = claude_swap.parse_list(payload)
77
+ now = datetime(2026, 11, 18, 12, 0, tzinfo=timezone.utc)
78
+ print(decide(accounts, [], now)["summary"])
79
+ ```
80
+
81
+ `parse_list(data, secondary_name=...)` picks the per-model weekly window of `usage.scoped` by
82
+ name for the secondary window (the first one when omitted).
83
+
84
+ ## What it does not do
85
+
86
+ - It does not switch accounts. You (or claude-swap) act on `drain_first`.
87
+ - The core makes no network call and calls no provider API. Only `claude_swap.read()` runs
88
+ `cswap list --json`, and claude-swap fetches the usage itself.
89
+ - It stores no account, no credential and no history: you pass the samples in.
90
+
91
+ ## Contributing
92
+
93
+ Changes are made in this repository, released as a new version, and the projects that use
94
+ quotapilot bump their pin. See [CONTRIBUTING.md](CONTRIBUTING.md).
95
+
96
+ ## License
97
+
98
+ MIT
@@ -0,0 +1,19 @@
1
+ """Project a week on three synthetic accounts, offline."""
2
+
3
+ from datetime import datetime, timedelta, timezone
4
+
5
+ from quotapilot import Account, Config, decide
6
+
7
+ now = datetime(2026, 11, 18, 12, 0, tzinfo=timezone.utc)
8
+ accounts = [
9
+ Account("work", used_pct=95, reset=now + timedelta(hours=10)),
10
+ Account("personal", used_pct=20, reset=now + timedelta(hours=60)),
11
+ Account("spare", used_pct=5, reset=now + timedelta(hours=120)),
12
+ ]
13
+ history = [(now - timedelta(hours=8), "work", 87), (now, "work", 95)]
14
+
15
+ result = decide(accounts, history, now, config=Config(max_units_per_h=3.0))
16
+ print(result["summary"])
17
+ for row in result["accounts"]:
18
+ print(f"{row['name']:>9} room {row['room_pct']:5.1f}% lost {row['lost_pct']:5.1f}%")
19
+ print("unavoidable:", result["unavoidable_units"])
@@ -0,0 +1,53 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.18"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "quotapilot"
7
+ dynamic = ["version"]
8
+ description = "Project what expires unused across several accounts with weekly quota windows, and say which account to drain first. No dependencies, no network."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "Dylan Merigaud" }]
14
+ keywords = ["quota", "rate-limit", "usage", "claude", "claude-swap", "accounts", "scheduling"]
15
+ classifiers = [
16
+ "Development Status :: 3 - Alpha",
17
+ "Intended Audience :: Developers",
18
+ "License :: OSI Approved :: MIT License",
19
+ "Operating System :: OS Independent",
20
+ "Programming Language :: Python :: 3",
21
+ "Programming Language :: Python :: 3.9",
22
+ "Programming Language :: Python :: 3.10",
23
+ "Programming Language :: Python :: 3.11",
24
+ "Programming Language :: Python :: 3.12",
25
+ "Programming Language :: Python :: 3.13",
26
+ "Typing :: Typed",
27
+ ]
28
+ dependencies = []
29
+
30
+ [project.urls]
31
+ Homepage = "https://github.com/DylanMerigaud/quotapilot"
32
+ Source = "https://github.com/DylanMerigaud/quotapilot"
33
+ Issues = "https://github.com/DylanMerigaud/quotapilot/issues"
34
+ Changelog = "https://github.com/DylanMerigaud/quotapilot/blob/main/CHANGELOG.md"
35
+
36
+ [project.optional-dependencies]
37
+ test = ["pytest>=7"]
38
+ dev = ["pytest>=7", "ruff", "mypy", "build"]
39
+
40
+ [tool.hatch.version]
41
+ path = "quotapilot/__init__.py"
42
+
43
+ [tool.hatch.build.targets.wheel]
44
+ packages = ["quotapilot"]
45
+
46
+ [tool.hatch.build.targets.sdist]
47
+ include = ["/quotapilot", "/tests", "/examples", "/README.md", "/LICENSE", "/CHANGELOG.md", "/CONTRIBUTING.md", "/ruff.toml"]
48
+
49
+ [tool.mypy]
50
+ strict = true
51
+
52
+ [tool.pytest.ini_options]
53
+ testpaths = ["tests"]
@@ -0,0 +1,21 @@
1
+ """quotapilot: where to burn the weekly quota of several accounts so the least expires."""
2
+
3
+ from .core import (
4
+ Account,
5
+ Config,
6
+ average_pace,
7
+ decide,
8
+ pace_from_history,
9
+ project,
10
+ )
11
+
12
+ __version__ = "0.1.0"
13
+
14
+ __all__ = [
15
+ "Account",
16
+ "Config",
17
+ "average_pace",
18
+ "decide",
19
+ "pace_from_history",
20
+ "project",
21
+ ]
File without changes
@@ -0,0 +1,92 @@
1
+ """Read the accounts of claude-swap (https://github.com/realiti4/claude-swap).
2
+
3
+ claude-swap holds the accounts and switches between them. This module only turns the JSON of
4
+ `cswap list --json` into `quotapilot.Account` rows. The primary window is the seven-day one; the
5
+ secondary window is the per-model weekly limit listed under `usage.scoped`.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import subprocess
12
+ from datetime import datetime, timezone
13
+ from typing import Any, Callable
14
+
15
+ from ..core import Account
16
+
17
+
18
+ def parse_at(text: Any) -> datetime | None:
19
+ """An ISO stamp as an aware datetime (a naive one is read as local time), None if unreadable."""
20
+ try:
21
+ dt = datetime.fromisoformat(str(text).replace("Z", "+00:00"))
22
+ except (ValueError, TypeError):
23
+ return None
24
+ return dt if dt.tzinfo else dt.astimezone()
25
+
26
+
27
+ def _window(usage: dict[str, Any] | None, key: str) -> tuple[float | None, datetime | None]:
28
+ w = (usage or {}).get(key)
29
+ if not isinstance(w, dict) or w.get("pct") is None:
30
+ return None, None
31
+ return float(w["pct"]), parse_at(w.get("resetsAt"))
32
+
33
+
34
+ def parse_list(
35
+ data: dict[str, Any] | list[Any],
36
+ now: datetime | None = None,
37
+ secondary_name: str | None = None,
38
+ ) -> list[Account]:
39
+ """The accounts of a `cswap list --json` payload (the object, or just its `accounts` list).
40
+
41
+ `secondary_name` picks the window of `usage.scoped` (the per-model weekly limits) that becomes
42
+ the secondary window, by its `name`. None takes the first scoped window that has a percent.
43
+ `now` is not used to read the rows.
44
+ Raises ValueError, KeyError or TypeError on a malformed row.
45
+ """
46
+ rows = data["accounts"] if isinstance(data, dict) else data
47
+ accounts: list[Account] = []
48
+ for r in rows:
49
+ name = str(r["number"])
50
+ usage = r.get("usage") if r.get("usageStatus") == "ok" else None
51
+ if usage is not None and not isinstance(usage, dict):
52
+ raise TypeError(f"usage of {name} is {type(usage).__name__}")
53
+ pct, reset = _window(usage, "sevenDay")
54
+ secondary_pct: float | None = None
55
+ secondary_reset: datetime | None = None
56
+ for s in (usage or {}).get("scoped") or []:
57
+ if s.get("pct") is None or (secondary_name and s.get("name") != secondary_name):
58
+ continue
59
+ secondary_pct, secondary_reset = float(s["pct"]), parse_at(s.get("resetsAt"))
60
+ if not secondary_name:
61
+ break
62
+ accounts.append(
63
+ Account(
64
+ name=name,
65
+ used_pct=pct,
66
+ reset=reset,
67
+ secondary_pct=secondary_pct,
68
+ secondary_reset=secondary_reset,
69
+ usable=usage is not None and pct is not None,
70
+ )
71
+ )
72
+ return accounts
73
+
74
+
75
+ def read(
76
+ run: Callable[..., Any] = subprocess.run,
77
+ binary: str = "cswap",
78
+ timeout: float = 120,
79
+ secondary_name: str | None = None,
80
+ ) -> list[Account]:
81
+ """Run `cswap list --json` and parse it. RuntimeError when it fails or is unreadable."""
82
+ try:
83
+ out = run([binary, "list", "--json"], capture_output=True, text=True, timeout=timeout)
84
+ except Exception as e:
85
+ raise RuntimeError(f"cswap list failed: {e}") from e
86
+ if out.returncode != 0:
87
+ raise RuntimeError(f"cswap list exit {out.returncode}: {(out.stderr or '').strip()[:120]}")
88
+ try:
89
+ data = json.loads(out.stdout)
90
+ return parse_list(data, datetime.now(timezone.utc), secondary_name)
91
+ except (ValueError, KeyError, TypeError, AttributeError) as e:
92
+ raise RuntimeError(f"cswap list bad json: {type(e).__name__}: {e}") from e
@@ -0,0 +1,264 @@
1
+ """Pure core of quotapilot: stdlib only, every datetime timezone-aware, any zone accepted."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from datetime import datetime, timedelta, timezone
7
+ from typing import Any, Optional, Sequence, Tuple
8
+
9
+ Sample = Tuple[datetime, str, Optional[float]]
10
+
11
+
12
+ @dataclass
13
+ class Account:
14
+ """One account and its quota windows, as percent used and the reset instant.
15
+
16
+ The primary window is the weekly one. The secondary window is a second, narrower window some
17
+ providers have (for example a per-model weekly limit).
18
+ """
19
+
20
+ name: str
21
+ used_pct: float | None
22
+ reset: datetime | None
23
+ secondary_pct: float | None = None
24
+ secondary_reset: datetime | None = None
25
+ usable: bool = True
26
+
27
+
28
+ @dataclass(frozen=True)
29
+ class Config:
30
+ """Every constant of the algorithm. Defaults: one unit is one percent point of a week."""
31
+
32
+ week_hours: float = 168
33
+ units_per_week: float = 100.0
34
+ max_units_per_h: float | None = None
35
+ burn_floor_units: float = 1.0
36
+ secondary_min_room_pct: float = 10
37
+ secondary_drop_pct: float = 20
38
+ min_span_h: float = 6
39
+ history_h: float = 24
40
+ secondary_hold_h: float = 24
41
+
42
+
43
+ DEFAULT = Config()
44
+
45
+
46
+ def _counted(accounts: Sequence[Account]) -> list[Account]:
47
+ return [a for a in accounts if a.usable and a.used_pct is not None and a.reset is not None]
48
+
49
+
50
+ def _iso(dt: datetime) -> str:
51
+ return dt.astimezone(timezone.utc).isoformat()
52
+
53
+
54
+ def _hours(delta: timedelta) -> float:
55
+ return delta.total_seconds() / 3600
56
+
57
+
58
+ def pace_from_history(
59
+ samples: Sequence[Sample], now: datetime, config: Config = DEFAULT
60
+ ) -> float | None:
61
+ """Points per hour measured over the last `history_h` hours, None when the span is too short.
62
+
63
+ Each sample is (at, account name, used percent). A drop of the percent (a reset) is skipped.
64
+ """
65
+ kept = [
66
+ (s[0], s[1], s[2])
67
+ for s in samples
68
+ if s[2] is not None and timedelta(0) <= now - s[0] <= timedelta(hours=config.history_h)
69
+ ]
70
+ if not kept:
71
+ return None
72
+ span = _hours(max(s[0] for s in kept) - min(s[0] for s in kept))
73
+ if span < config.min_span_h:
74
+ return None
75
+ by_name: dict[str, list[tuple[datetime, float]]] = {}
76
+ for at, name, pct in kept:
77
+ assert pct is not None
78
+ by_name.setdefault(name, []).append((at, pct))
79
+ total = 0.0
80
+ for rows in by_name.values():
81
+ rows.sort(key=lambda r: r[0])
82
+ for (_, a), (_, b) in zip(rows, rows[1:]):
83
+ if b - a > 0:
84
+ total += b - a
85
+ return total / span
86
+
87
+
88
+ def average_pace(accounts: Sequence[Account], now: datetime, config: Config = DEFAULT) -> float:
89
+ """Points per hour averaged over the elapsed part of each account's week."""
90
+ total = 0.0
91
+ for a in _counted(accounts):
92
+ assert a.reset is not None and a.used_pct is not None
93
+ if a.reset <= now:
94
+ continue # stale reading: the week already refilled, its used_pct says nothing
95
+ left = _hours(a.reset - now)
96
+ elapsed = min(float(config.week_hours), max(1.0, config.week_hours - left))
97
+ total += a.used_pct / elapsed
98
+ return total
99
+
100
+
101
+ def _walk(
102
+ accounts: Sequence[Account], pace: float, now: datetime
103
+ ) -> list[tuple[Account, float, float, datetime | None]]:
104
+ """Unrounded walk: (account, room, lost, empty_at) in reset order."""
105
+ out: list[tuple[Account, float, float, datetime | None]] = []
106
+ t = now
107
+ for a in sorted(_counted(accounts), key=lambda x: x.reset): # type: ignore[arg-type,return-value]
108
+ assert a.reset is not None and a.used_pct is not None
109
+ lost = 0.0
110
+ empty_at = None
111
+ if a.reset <= now:
112
+ room = 0.0
113
+ else:
114
+ room = max(0.0, 100 - a.used_pct)
115
+ if pace <= 0:
116
+ lost = room
117
+ else:
118
+ need_h = room / pace
119
+ avail_h = max(0.0, _hours(a.reset - t))
120
+ if need_h <= avail_h:
121
+ t = t + timedelta(hours=need_h)
122
+ empty_at = t
123
+ else:
124
+ lost = room - pace * avail_h
125
+ t = max(t, a.reset)
126
+ out.append((a, room, lost, empty_at))
127
+ return out
128
+
129
+
130
+ def project(
131
+ accounts: Sequence[Account], pace: float, now: datetime, config: Config = DEFAULT
132
+ ) -> list[dict[str, Any]]:
133
+ """What each counted account loses at this pace, draining in reset order."""
134
+ out: list[dict[str, Any]] = []
135
+ for a, room, lost, empty_at in _walk(accounts, pace, now):
136
+ assert a.reset is not None and a.used_pct is not None
137
+ out.append(
138
+ {
139
+ "name": a.name,
140
+ "used_pct": round(a.used_pct, 1),
141
+ "reset": _iso(a.reset),
142
+ "room_pct": round(room, 1),
143
+ "lost_pct": round(lost, 1),
144
+ "lost_units": round(lost / 100 * config.units_per_week, 1),
145
+ "empty_at": _iso(empty_at) if empty_at else None,
146
+ }
147
+ )
148
+ return out
149
+
150
+
151
+ def _secondary_qualifies(
152
+ a: Account, now: datetime, previous: dict[str, Any] | None, config: Config
153
+ ) -> bool:
154
+ assert a.reset is not None and a.used_pct is not None
155
+ if a.secondary_reset is not None:
156
+ diff = abs(_hours(a.secondary_reset - a.reset))
157
+ if diff > 1 and _hours(a.secondary_reset - now) > config.week_hours - 24:
158
+ return True
159
+ if previous and a.secondary_pct is not None:
160
+ for p in previous.get("accounts") or []:
161
+ if p.get("name") != a.name or p.get("secondary_pct") is None:
162
+ continue
163
+ prev_used = p.get("used_pct")
164
+ if (
165
+ p["secondary_pct"] - a.secondary_pct >= config.secondary_drop_pct
166
+ and prev_used is not None
167
+ and a.used_pct >= prev_used
168
+ ):
169
+ return True
170
+ return False
171
+
172
+
173
+ def _secondary_carried(
174
+ name: str, now: datetime, previous: dict[str, Any] | None, config: Config
175
+ ) -> str | None:
176
+ """The previous secondary_since of `name` when it was secondary_first less than
177
+ `secondary_hold_h` ago."""
178
+ if not previous or previous.get("secondary_first") != name:
179
+ return None
180
+ since = previous.get("secondary_since")
181
+ try:
182
+ at = datetime.fromisoformat(str(since))
183
+ except (TypeError, ValueError):
184
+ return None
185
+ if at.tzinfo is None:
186
+ return None
187
+ held = timedelta(0) <= now - at < timedelta(hours=config.secondary_hold_h)
188
+ return str(since) if held else None
189
+
190
+
191
+ def _clock(dt: datetime) -> str:
192
+ return dt.astimezone(timezone.utc).strftime("%H:%M")
193
+
194
+
195
+ def decide(
196
+ accounts: Sequence[Account],
197
+ history: Sequence[Sample],
198
+ now: datetime,
199
+ previous: dict[str, Any] | None = None,
200
+ config: Config = DEFAULT,
201
+ ) -> dict[str, Any]:
202
+ """Project the loss of every account, pick the account to drain first, say burn or normal.
203
+
204
+ `previous` is the dict a former call returned; it carries the secondary-first rule over time.
205
+ """
206
+ measured = pace_from_history(history, now, config)
207
+ pace = measured if measured is not None else average_pace(accounts, now, config)
208
+ rows = project(accounts, pace, now, config)
209
+ extra = {a.name: a for a in _counted(accounts)}
210
+ for r in rows:
211
+ acc = extra[r["name"]]
212
+ r["secondary_pct"] = acc.secondary_pct
213
+ r["secondary_reset"] = _iso(acc.secondary_reset) if acc.secondary_reset else None
214
+ lost_units = round(sum(r["lost_units"] for r in rows))
215
+ unavoidable: int | None = None
216
+ if config.max_units_per_h is not None:
217
+ max_pace = config.max_units_per_h / config.units_per_week * 100
218
+ unavoidable = round(sum(r["lost_units"] for r in project(accounts, max_pace, now, config)))
219
+ raw = _walk(accounts, pace, now)
220
+ drain_i = next((i for i, w in enumerate(raw) if w[1] > 0), None)
221
+ drain_first = rows[drain_i]["name"] if drain_i is not None else None
222
+
223
+ secondary_first = None
224
+ # the unrounded loss: a loss that rounds to 0.0 point is still a loss
225
+ if drain_i is not None and raw[drain_i][2] == 0:
226
+ cands = [
227
+ r
228
+ for r in rows
229
+ if r["room_pct"] >= config.secondary_min_room_pct
230
+ and (
231
+ _secondary_carried(r["name"], now, previous, config)
232
+ or _secondary_qualifies(extra[r["name"]], now, previous, config)
233
+ )
234
+ ]
235
+ if cands:
236
+ secondary_first = max(cands, key=lambda r: r["room_pct"])["name"]
237
+ secondary_since = None
238
+ if secondary_first:
239
+ secondary_since = _secondary_carried(secondary_first, now, previous, config) or _iso(now)
240
+
241
+ state = "burn" if lost_units >= config.burn_floor_units else "normal"
242
+ tail = f", drain {drain_first} first." if drain_first else "."
243
+ if state == "burn":
244
+ losing = [r for r in rows if r["lost_units"] > 0]
245
+ names = ", ".join(r["name"] for r in losing)
246
+ at = _clock(datetime.fromisoformat(losing[0]["reset"]))
247
+ summary = (
248
+ f"Burn: {lost_units} units expire on {names} at the {at} UTC reset "
249
+ f"at {pace:.1f} pts/h{tail}"
250
+ )
251
+ else:
252
+ summary = f"Normal: nothing expires at {pace:.1f} pts/h{tail}"
253
+ return {
254
+ "state": state,
255
+ "drain_first": drain_first,
256
+ "secondary_first": secondary_first,
257
+ "secondary_since": secondary_since,
258
+ "pace_pct_h": round(pace, 2),
259
+ "pace_source": "measured" if measured is not None else "average",
260
+ "lost_units": lost_units,
261
+ "unavoidable_units": unavoidable,
262
+ "accounts": rows,
263
+ "summary": summary,
264
+ }
File without changes
@@ -0,0 +1,9 @@
1
+ line-length = 100
2
+ target-version = "py39"
3
+
4
+ [lint]
5
+ select = ["E", "F", "W", "I", "B", "UP", "N", "SIM", "RUF"]
6
+ ignore = ["UP006", "UP007", "UP035", "UP045", "RUF022", "UP017"]
7
+
8
+ [lint.isort]
9
+ known-first-party = ["quotapilot"]
@@ -0,0 +1,135 @@
1
+ """The claude-swap adapter: `cswap list --json` into accounts."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from datetime import datetime, timezone
7
+ from types import SimpleNamespace
8
+ from typing import Any
9
+
10
+ import pytest
11
+
12
+ from quotapilot import decide
13
+ from quotapilot.adapters import claude_swap
14
+
15
+ NOW = datetime(2026, 11, 18, 13, 27, tzinfo=timezone.utc)
16
+
17
+ PAYLOAD: dict[str, Any] = {
18
+ "activeAccountNumber": 1,
19
+ "accounts": [
20
+ {
21
+ "number": 1,
22
+ "email": "work@example.com",
23
+ "active": True,
24
+ "usageStatus": "ok",
25
+ "usage": {
26
+ "fiveHour": {"pct": 12, "resetsAt": "2026-11-18T17:00:00Z"},
27
+ "sevenDay": {"pct": 62.5, "resetsAt": "2026-11-22T17:00:00Z"},
28
+ "scoped": [
29
+ {"name": "Opus", "pct": 30, "resetsAt": "2026-11-24T17:00:00Z"},
30
+ {"name": "Sonnet", "pct": 26, "resetsAt": "2026-11-24T17:00:00+00:00"},
31
+ ],
32
+ },
33
+ },
34
+ {
35
+ "number": 2,
36
+ "email": "personal@example.com",
37
+ "usageStatus": "ok",
38
+ "usage": {"sevenDay": {"pct": 8, "resetsAt": "2026-11-23T23:00:00Z"}},
39
+ },
40
+ {"number": 3, "usageStatus": "error", "usage": None},
41
+ {"number": 4, "usageStatus": "ok", "usage": {"fiveHour": {"pct": 1}}},
42
+ ],
43
+ }
44
+
45
+
46
+ def test_parse_list_reads_the_weekly_window():
47
+ accs = claude_swap.parse_list(PAYLOAD, NOW)
48
+ assert [a.name for a in accs] == ["1", "2", "3", "4"]
49
+ one = accs[0]
50
+ assert one.used_pct == 62.5 and one.reset == datetime(2026, 11, 22, 17, tzinfo=timezone.utc)
51
+ assert one.usable and one.secondary_pct == 30
52
+ assert accs[1].used_pct == 8 and accs[1].usable
53
+
54
+
55
+ def test_unreadable_usage_is_not_usable():
56
+ accs = claude_swap.parse_list(PAYLOAD, NOW)
57
+ for a in accs[2:]:
58
+ assert not a.usable and a.used_pct is None and a.reset is None
59
+
60
+
61
+ def test_secondary_window_by_name_or_first():
62
+ named = claude_swap.parse_list(PAYLOAD, NOW, secondary_name="Sonnet")[0]
63
+ assert named.secondary_pct == 26
64
+ assert named.secondary_reset == datetime(2026, 11, 24, 17, tzinfo=timezone.utc)
65
+ first = claude_swap.parse_list(PAYLOAD, NOW)[0]
66
+ assert first.secondary_pct == 30
67
+ missing = claude_swap.parse_list(PAYLOAD, NOW, secondary_name="Haiku")[0]
68
+ assert missing.secondary_pct is None and missing.secondary_reset is None
69
+
70
+
71
+ def test_a_bare_list_of_rows_is_accepted():
72
+ assert [a.name for a in claude_swap.parse_list(PAYLOAD["accounts"], NOW)] == [
73
+ "1",
74
+ "2",
75
+ "3",
76
+ "4",
77
+ ]
78
+
79
+
80
+ def test_naive_stamp_is_read_as_local_time():
81
+ at = claude_swap.parse_at("2026-11-22 17:00:00")
82
+ assert at is not None and at.tzinfo is not None
83
+ assert claude_swap.parse_at("nope") is None and claude_swap.parse_at(None) is None
84
+
85
+
86
+ def test_malformed_rows_raise():
87
+ with pytest.raises(KeyError):
88
+ claude_swap.parse_list({"accounts": [{"usage": {}}]}, NOW)
89
+ bad = {"accounts": [{"number": 1, "usageStatus": "ok", "usage": [1]}]}
90
+ with pytest.raises(TypeError):
91
+ claude_swap.parse_list(bad, NOW)
92
+
93
+
94
+ def test_parsed_accounts_feed_decide():
95
+ out = decide(claude_swap.parse_list(PAYLOAD, NOW), [], NOW)
96
+ assert out["drain_first"] == "1"
97
+ assert [r["name"] for r in out["accounts"]] == ["1", "2"]
98
+
99
+
100
+ def _runner(stdout: str, returncode: int = 0, stderr: str = ""):
101
+ calls: list[list[str]] = []
102
+
103
+ def run(cmd: list[str], **kwargs: Any) -> Any:
104
+ calls.append(cmd)
105
+ return SimpleNamespace(returncode=returncode, stdout=stdout, stderr=stderr)
106
+
107
+ return run, calls
108
+
109
+
110
+ def test_read_runs_cswap_list_json():
111
+ run, calls = _runner(json.dumps(PAYLOAD))
112
+ accs = claude_swap.read(run=run)
113
+ assert calls == [["cswap", "list", "--json"]]
114
+ assert len(accs) == 4
115
+ run, calls = _runner(json.dumps(PAYLOAD))
116
+ claude_swap.read(run=run, binary="/opt/bin/cswap")
117
+ assert calls[0][0] == "/opt/bin/cswap"
118
+
119
+
120
+ def test_read_failures_are_runtime_errors():
121
+ run, _ = _runner("", returncode=2, stderr="boom")
122
+ with pytest.raises(RuntimeError, match="exit 2: boom"):
123
+ claude_swap.read(run=run)
124
+ run, _ = _runner("not json")
125
+ with pytest.raises(RuntimeError, match="bad json"):
126
+ claude_swap.read(run=run)
127
+ run, _ = _runner("{}")
128
+ with pytest.raises(RuntimeError, match="bad json"):
129
+ claude_swap.read(run=run)
130
+
131
+ def broken(cmd: list[str], **kwargs: Any) -> Any:
132
+ raise FileNotFoundError("cswap")
133
+
134
+ with pytest.raises(RuntimeError, match="cswap list failed"):
135
+ claude_swap.read(run=broken)
@@ -0,0 +1,255 @@
1
+ """quotapilot core: projection of what each account-week loses, drain first, burn or normal."""
2
+
3
+ from datetime import datetime, timedelta, timezone
4
+
5
+ import pytest
6
+
7
+ from quotapilot import Account, Config, average_pace, decide, pace_from_history, project
8
+
9
+ UTC = timezone.utc
10
+ NOW = datetime(2026, 11, 18, 13, 27, tzinfo=UTC)
11
+ EM, EN = chr(0x2014), chr(0x2013)
12
+ REF = Config(units_per_week=3600, max_units_per_h=140, burn_floor_units=36)
13
+
14
+
15
+ def _d(s):
16
+ return datetime.fromisoformat(s.replace("Z", "+00:00"))
17
+
18
+
19
+ def snapshot(tz=UTC):
20
+ def z(s):
21
+ return _d(s).astimezone(tz)
22
+
23
+ return [
24
+ Account("1", 99, None, usable=False),
25
+ Account("2", 8, z("2026-11-23T23:00:00Z"), 7, z("2026-11-23T23:00:00Z")),
26
+ Account("3", 99, z("2026-11-18T23:00:00Z"), 36, z("2026-11-18T23:00:00Z")),
27
+ Account("4", 62, z("2026-11-22T17:00:00Z"), 26, z("2026-11-22T17:00:00Z")),
28
+ ]
29
+
30
+
31
+ def flat_history(name, pct_a, pct_b, now=NOW):
32
+ return [(now - timedelta(hours=7), name, pct_a), (now, name, pct_b)]
33
+
34
+
35
+ def test_snapshot_without_history_uses_average():
36
+ out = decide(snapshot(), [], NOW, config=REF)
37
+ assert out["pace_source"] == "average"
38
+ assert out["drain_first"] == "3"
39
+ assert [a["name"] for a in out["accounts"]] == ["3", "4", "2"]
40
+ assert out["secondary_first"] is None
41
+ assert out["state"] in ("burn", "normal")
42
+
43
+
44
+ def test_project_at_pace_one_by_hand():
45
+ rows = {r["name"]: r for r in project(snapshot(), 1.0, NOW, REF)}
46
+ assert rows["3"]["lost_pct"] == 0 and rows["3"]["empty_at"] is not None
47
+ assert rows["4"]["room_pct"] == 38 and rows["4"]["lost_pct"] == 0
48
+ t = NOW + timedelta(hours=1) + timedelta(hours=38)
49
+ avail = (_d("2026-11-23T23:00:00Z") - t).total_seconds() / 3600
50
+ expect = 92 - avail
51
+ assert rows["2"]["room_pct"] == 92
52
+ assert rows["2"]["lost_pct"] == pytest.approx(expect, abs=0.06)
53
+ assert rows["2"]["lost_units"] == pytest.approx(expect / 100 * 3600, abs=2.5)
54
+ assert rows["2"]["empty_at"] is None
55
+
56
+
57
+ def test_pace_zero_loses_every_room_and_burns():
58
+ hist = flat_history("2", 8, 8)
59
+ out = decide(snapshot(), hist, NOW, config=REF)
60
+ assert out["pace_source"] == "measured" and out["pace_pct_h"] == 0
61
+ assert out["state"] == "burn"
62
+ for a in out["accounts"]:
63
+ assert a["lost_pct"] == a["room_pct"] and a["empty_at"] is None
64
+ assert out["lost_units"] == round((1 + 38 + 92) / 100 * 3600)
65
+
66
+
67
+ def test_reset_in_the_past_loses_nothing():
68
+ acc = [Account("9", 80, NOW - timedelta(hours=2))]
69
+ row = project(acc, 0.0, NOW, REF)[0]
70
+ assert row["room_pct"] == 0 and row["lost_pct"] == 0 and row["lost_units"] == 0
71
+
72
+
73
+ def test_pace_from_history():
74
+ now = NOW
75
+ h = timedelta(hours=1)
76
+ assert pace_from_history([(now - 5 * h, "a", 1), (now, "a", 9)], now) is None
77
+ ex = [
78
+ (now - 10 * h, "a", 10),
79
+ (now - 5 * h, "a", 14),
80
+ (now, "a", 20),
81
+ (now - 10 * h, "b", 50),
82
+ (now - 4 * h, "b", 53),
83
+ ]
84
+ assert pace_from_history(ex, now) == pytest.approx(1.3)
85
+ rs = [(now - 8 * h, "a", 99), (now - 4 * h, "a", 3), (now, "a", 5)]
86
+ assert pace_from_history(rs, now) == pytest.approx(0.25)
87
+ old = [(now - 30 * h, "a", 0), (now - 7 * h, "a", 10), (now, "a", 17)]
88
+ assert pace_from_history(old, now) == pytest.approx(1.0)
89
+ assert pace_from_history([], now) is None
90
+
91
+
92
+ def test_average_pace():
93
+ acc = [Account("a", 50, NOW + timedelta(hours=84)), Account("x", 9, None)]
94
+ assert average_pace(acc, NOW) == pytest.approx(50 / 84)
95
+
96
+
97
+ def _secondary_setup(pace_delta):
98
+ a = Account("A", 95, NOW + timedelta(hours=10))
99
+ five = Account("5", 40, NOW + timedelta(hours=100), 2, NOW + timedelta(hours=165))
100
+ hist = [(NOW - timedelta(hours=7), "A", 90), (NOW, "A", 90 + pace_delta)]
101
+ return [a, five], hist
102
+
103
+
104
+ def test_secondary_only_reset_picks_account():
105
+ accs, hist = _secondary_setup(7)
106
+ out = decide(accs, hist, NOW)
107
+ assert out["drain_first"] == "A"
108
+ assert out["accounts"][0]["lost_pct"] == 0
109
+ assert out["secondary_first"] == "5"
110
+
111
+
112
+ def test_secondary_blocked_when_drain_first_loses():
113
+ accs, hist = _secondary_setup(0.07)
114
+ out = decide(accs, hist, NOW)
115
+ assert out["accounts"][0]["lost_pct"] > 0
116
+ assert out["secondary_first"] is None
117
+
118
+
119
+ def test_secondary_drop_via_previous():
120
+ reset = NOW + timedelta(hours=100)
121
+ acc = [Account("5", 52, reset, 10, reset)]
122
+ prev = {"accounts": [{"name": "5", "used_pct": 50, "secondary_pct": 80}]}
123
+ hist = flat_history("5", 50, 57)
124
+ assert decide(acc, hist, NOW, prev)["secondary_first"] == "5"
125
+ assert decide(acc, hist, NOW, None)["secondary_first"] is None
126
+ prev_dropped = {"accounts": [{"name": "5", "used_pct": 70, "secondary_pct": 80}]}
127
+ assert decide(acc, hist, NOW, prev_dropped)["secondary_first"] is None
128
+
129
+
130
+ def test_mixed_timezones_give_the_same_result():
131
+ plus1 = timezone(timedelta(hours=1))
132
+ a = decide(snapshot(UTC), [], NOW, config=REF)
133
+ b = decide(snapshot(plus1), [], NOW.astimezone(plus1), config=REF)
134
+ assert a == b
135
+
136
+
137
+ def test_summary_is_english_utc():
138
+ s = decide(snapshot(), flat_history("2", 8, 12), NOW, config=REF)["summary"]
139
+ assert s == "Burn: 2051 units expire on 2 at the 23:00 UTC reset at 0.6 pts/h, drain 3 first."
140
+ n = decide(snapshot(), [], NOW, config=REF)["summary"]
141
+ assert n == "Normal: nothing expires at 1.7 pts/h, drain 3 first."
142
+
143
+
144
+ def test_summary_is_clean_and_short():
145
+ for hist in ([], flat_history("2", 8, 8), flat_history("2", 8, 30)):
146
+ s = decide(snapshot(), hist, NOW, config=REF)["summary"]
147
+ assert EM not in s and EN not in s and len(s) < 160
148
+ assert s.isascii()
149
+ assert decide(snapshot(), flat_history("2", 8, 8), NOW, config=REF)["summary"].startswith(
150
+ "Burn:"
151
+ )
152
+
153
+
154
+ def test_defaults():
155
+ c = Config()
156
+ assert (c.week_hours, c.units_per_week, c.max_units_per_h, c.burn_floor_units) == (
157
+ 168,
158
+ 100.0,
159
+ None,
160
+ 1.0,
161
+ )
162
+ assert (c.secondary_min_room_pct, c.secondary_drop_pct) == (10, 20)
163
+ assert (c.min_span_h, c.history_h, c.secondary_hold_h) == (6, 24, 24)
164
+ out = decide(snapshot(), flat_history("2", 8, 8), NOW)
165
+ assert out["unavoidable_units"] is None
166
+ assert out["lost_units"] == 131 # one unit is one percent point: 1 + 38 + 92
167
+
168
+
169
+ def test_matches_the_reference_config():
170
+ # numbers computed with the original implementation on these same inputs
171
+ out = decide(snapshot(), [], NOW, config=REF)
172
+ assert (out["state"], out["drain_first"], out["pace_pct_h"], out["pace_source"]) == (
173
+ "normal",
174
+ "3",
175
+ 1.74,
176
+ "average",
177
+ )
178
+ assert (out["lost_units"], out["unavoidable_units"]) == (0, 0)
179
+ assert out["accounts"][0]["empty_at"] == "2026-11-18T14:01:30.588869+00:00"
180
+ assert out["accounts"][2]["empty_at"] == "2026-11-21T16:47:47.141901+00:00"
181
+
182
+ out = decide(snapshot(), flat_history("2", 8, 12), NOW, config=REF)
183
+ assert (out["state"], out["pace_pct_h"], out["pace_source"]) == ("burn", 0.57, "measured")
184
+ assert (out["lost_units"], out["unavoidable_units"]) == (2051, 0)
185
+ assert out["accounts"][2]["lost_pct"] == 57.0 and out["accounts"][2]["lost_units"] == 2051.0
186
+
187
+ one = [Account("x", 8, NOW + timedelta(hours=5))]
188
+ out = decide(one, [], NOW, config=REF)
189
+ assert (out["pace_pct_h"], out["lost_units"], out["unavoidable_units"]) == (0.05, 3303, 2612)
190
+ assert out["accounts"][0]["lost_pct"] == 91.8
191
+ out = decide(one, flat_history("x", 8, 15), NOW, config=REF)
192
+ assert (out["pace_pct_h"], out["lost_units"], out["unavoidable_units"]) == (1.0, 3132, 2612)
193
+
194
+ a = Account("A", 95, NOW + timedelta(hours=10))
195
+ five = Account("5", 40, NOW + timedelta(hours=100), 2, NOW + timedelta(hours=165))
196
+ hist = [(NOW - timedelta(hours=7), "A", 90), (NOW, "A", 97)]
197
+ out = decide([a, five], hist, NOW, config=REF)
198
+ assert (out["secondary_first"], out["secondary_since"]) == ("5", NOW.isoformat())
199
+ assert (out["pace_pct_h"], out["lost_units"]) == (1.0, 0)
200
+
201
+
202
+ def test_average_pace_ignores_a_past_reset():
203
+ acc = [
204
+ Account("a", 50, NOW + timedelta(hours=84)),
205
+ Account("stale", 99, NOW - timedelta(hours=2)),
206
+ ]
207
+ assert average_pace(acc, NOW) == pytest.approx(50 / 84)
208
+
209
+
210
+ def test_secondary_blocked_by_a_loss_that_rounds_to_zero():
211
+ a = Account("A", 95, NOW + timedelta(hours=10))
212
+ five = Account("5", 40, NOW + timedelta(hours=100), 2, NOW + timedelta(hours=165))
213
+ # 7 h of history at 0.4955 pts/h: A needs 5 points in 10 h, loses about 0.045 point
214
+ hist = [(NOW - timedelta(hours=7), "A", 90), (NOW, "A", 90 + 0.4955 * 7)]
215
+ out = decide([a, five], hist, NOW)
216
+ assert out["drain_first"] == "A"
217
+ assert out["secondary_first"] is None
218
+
219
+
220
+ def _drop_scene(now):
221
+ a = Account("A", 40, now + timedelta(hours=100), 5, now + timedelta(hours=100))
222
+ b = Account("B", 99, now + timedelta(hours=10), 5, now + timedelta(hours=10))
223
+ prev = {"accounts": [{"name": "A", "used_pct": 40, "secondary_pct": 60}]}
224
+ return [a, b], prev
225
+
226
+
227
+ def test_secondary_drop_persists_across_ticks_then_expires():
228
+ accs, prev = _drop_scene(NOW)
229
+ hist = [(NOW - timedelta(hours=7), "B", 90), (NOW, "B", 99)]
230
+ t1 = decide(accs, hist, NOW, previous=prev)
231
+ assert t1["secondary_first"] == "A" and t1["secondary_since"] == NOW.isoformat()
232
+ t1["accounts"] = [{"name": "A", "used_pct": 40, "secondary_pct": 5}]
233
+ later = NOW + timedelta(hours=1)
234
+ accs2, _ = _drop_scene(later)
235
+ t2 = decide(
236
+ accs2, [(later - timedelta(hours=7), "B", 90), (later, "B", 99)], later, previous=t1
237
+ )
238
+ assert t2["secondary_first"] == "A" and t2["secondary_since"] == t1["secondary_since"]
239
+ t3t = NOW + timedelta(hours=25)
240
+ accs3, _ = _drop_scene(t3t)
241
+ t3 = decide(accs3, [(t3t - timedelta(hours=7), "B", 90), (t3t, "B", 99)], t3t, previous=t1)
242
+ assert t3["secondary_first"] is None and t3["secondary_since"] is None
243
+
244
+
245
+ def test_secondary_persistence_still_checks_room():
246
+ accs, prev = _drop_scene(NOW)
247
+ hist = [(NOW - timedelta(hours=7), "B", 90), (NOW, "B", 99)]
248
+ t1 = decide(accs, hist, NOW, previous=prev)
249
+ accs[0].used_pct = 95
250
+ t2 = decide(accs, hist, NOW + timedelta(hours=1), previous=t1)
251
+ assert t2["secondary_first"] is None
252
+
253
+
254
+ if __name__ == "__main__":
255
+ raise SystemExit(pytest.main([__file__, "-q"]))