claude-dev-env 8.111.4 → 8.112.0

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.
Files changed (51) hide show
  1. package/.agents/skills/build-eval/evals/review/README.md +2 -2
  2. package/.agents/skills/build-eval/evals/review/review_eval_support/account.py +166 -0
  3. package/.agents/skills/build-eval/evals/review/review_eval_support/config/constants.py +26 -0
  4. package/.agents/skills/build-eval/evals/review/review_eval_support/execution.py +8 -0
  5. package/.agents/skills/build-eval/evals/review/test_run.py +261 -0
  6. package/_shared/advisor/reference/astra-rung.md +13 -5
  7. package/_shared/advisor/scripts/codex_astra_advisor.py +31 -8
  8. package/_shared/advisor/scripts/codex_astra_preflight.py +70 -14
  9. package/_shared/advisor/scripts/config/advisor_scripts_constants/astra_advisor_constants.py +7 -0
  10. package/_shared/advisor/scripts/tests/test_codex_astra_advisor.py +266 -2
  11. package/_shared/advisor/scripts/tests/test_codex_astra_preflight.py +114 -8
  12. package/_shared/pr-loop/scripts/check_convergence.py +5 -1
  13. package/_shared/pr-loop/scripts/codex_review_account.py +180 -0
  14. package/_shared/pr-loop/scripts/codex_review_scripts_constants/account_constants.py +28 -0
  15. package/_shared/pr-loop/scripts/codex_review_scripts_constants/run_constants.py +3 -1
  16. package/_shared/pr-loop/scripts/run_codex_review.py +144 -15
  17. package/_shared/pr-loop/scripts/test_check_convergence_codex.py +3 -3
  18. package/_shared/pr-loop/scripts/test_codex_review_account.py +355 -0
  19. package/_shared/pr-loop/scripts/test_run_codex_review.py +507 -6
  20. package/docs/account-broker.md +6 -4
  21. package/docs/codex-accounts.md +57 -16
  22. package/docs/rule-guides/question-presentation.md +4 -0
  23. package/docs/second-claude-account.md +1 -1
  24. package/hooks/blocking/final_reply_gate.py +59 -3
  25. package/hooks/blocking/open_tasks_transcript.py +18 -0
  26. package/hooks/blocking/test_final_reply_gate.py +160 -0
  27. package/hooks/features/conduct-gates.md +1 -4
  28. package/hooks/hooks.json +0 -10
  29. package/hooks/hooks_constants/final_reply_gate_constants.py +16 -0
  30. package/hooks/hooks_constants/open_tasks_stop_gate_constants.py +9 -0
  31. package/package.json +1 -1
  32. package/rules/question-presentation.md +1 -1
  33. package/scripts/account_broker.py +122 -27
  34. package/scripts/account_broker_support.py +54 -3
  35. package/scripts/codex_account_choice.py +12 -8
  36. package/scripts/codex_account_chooser.py +110 -0
  37. package/scripts/codex_account_meters.py +43 -4
  38. package/scripts/codex_plan_rules.py +156 -0
  39. package/scripts/dev_env_scripts_constants/account_broker_constants.py +41 -42
  40. package/scripts/dev_env_scripts_constants/codex_account_constants.py +62 -2
  41. package/scripts/dev_env_scripts_constants/test_account_broker_constants.py +359 -2
  42. package/scripts/dev_env_scripts_constants/test_codex_account_constants.py +213 -14
  43. package/scripts/policy_lint/adapter_configuration.py +0 -5
  44. package/scripts/policy_lint/config/constants.py +0 -1
  45. package/scripts/test_account_broker.py +1913 -526
  46. package/scripts/test_account_broker_support.py +77 -0
  47. package/scripts/test_codex_account_meters.py +95 -0
  48. package/scripts/tests/test_adapter_configuration.py +0 -8
  49. package/hooks/blocking/merge_over_review_offer_gate.py +0 -114
  50. package/hooks/blocking/test_merge_over_review_offer_gate.py +0 -138
  51. package/hooks/hooks_constants/merge_over_review_offer_gate_constants.py +0 -34
@@ -4,6 +4,7 @@ import json
4
4
  import io
5
5
  import shutil
6
6
  import subprocess
7
+ from collections.abc import Callable
7
8
  from datetime import datetime, timedelta, timezone
8
9
  from pathlib import Path
9
10
 
@@ -21,10 +22,13 @@ from account_broker import (
21
22
  choose_from_readings,
22
23
  run_job,
23
24
  )
25
+ from dev_env_scripts_constants import codex_account_constants
24
26
  from dev_env_scripts_constants.account_broker_constants import WAIT_EXIT_CODE
27
+ from dev_env_scripts_constants.claude_chain_usage_constants import NO_ACCESS_TOKEN_ERROR_TEMPLATE
25
28
 
26
29
 
27
30
  NOW = datetime(2026, 10, 3, tzinfo=timezone.utc)
31
+ DEFAULT_PLAN = "team"
28
32
 
29
33
 
30
34
  class _FrozenClock(datetime):
@@ -52,7 +56,9 @@ def _meters(
52
56
  *,
53
57
  short_reset: datetime | None = None,
54
58
  weekly_reset: datetime | None = None,
55
- plan_type: str | None = None,
59
+ plan_type: str | None = DEFAULT_PLAN,
60
+ credit_balance: float | None = None,
61
+ is_credits_unlimited: bool = False,
56
62
  ) -> Meters:
57
63
  return Meters(
58
64
  short_left,
@@ -60,6 +66,9 @@ def _meters(
60
66
  weekly_left,
61
67
  weekly_reset or NOW + timedelta(days=3),
62
68
  plan_type,
69
+ credit_balance is not None,
70
+ is_credits_unlimited,
71
+ credit_balance,
63
72
  )
64
73
 
65
74
 
@@ -133,7 +142,7 @@ def test_should_pick_a_pro_plan_account_over_a_roomier_team_account() -> None:
133
142
  assert decision.tier == "normal"
134
143
 
135
144
 
136
- def test_should_pick_a_team_account_in_the_normal_tier_over_a_pro_plan_account_below_the_floor() -> None:
145
+ def test_should_pick_a_pro_plan_account_below_the_floor_over_a_team_account_in_the_normal_tier() -> None:
137
146
  readings = (
138
147
  Reading(_account("personal"), _meters(50, 8, plan_type="pro")),
139
148
  Reading(_account("team-jon"), _meters(40, 30, plan_type="team")),
@@ -141,740 +150,1966 @@ def test_should_pick_a_team_account_in_the_normal_tier_over_a_pro_plan_account_b
141
150
 
142
151
  decision = choose_from_readings(Product.CODEX, readings, now=NOW)
143
152
 
144
- assert decision.account == readings[1].account
145
- assert decision.tier == "normal"
146
-
147
-
148
- def test_should_keep_list_order_when_tighter_windows_tie() -> None:
149
- readings = (
150
- Reading(_account("first"), _meters(40, 60)),
151
- Reading(_account("second"), _meters(70, 40)),
152
- )
153
-
154
- decision = choose_from_readings(Product.CODEX, readings, now=NOW)
155
-
156
153
  assert decision.account == readings[0].account
154
+ assert decision.tier == "luna"
157
155
 
158
156
 
159
- @pytest.mark.parametrize(
160
- ("weekly_reset", "weekly_left", "short_left"),
161
- (
162
- (NOW + timedelta(hours=4), 1, 80),
163
- (NOW + timedelta(hours=4), 20, 5),
164
- ),
165
- )
166
- def test_should_guard_main_at_each_limit(
167
- weekly_reset: datetime, weekly_left: float, short_left: float
168
- ) -> None:
169
- main = Reading(
170
- _account("main", Product.CLAUDE, main=True),
171
- _meters(short_left, weekly_left, weekly_reset=weekly_reset),
172
- )
173
- extra = Reading(_account("extra", Product.CLAUDE), _meters(20, 20))
174
-
175
- decision = choose_from_readings(Product.CLAUDE, (main, extra), now=NOW)
176
-
177
- assert decision.account == extra.account
157
+ FREE_PLAN = "free"
158
+ TEAM_PLAN = "team"
159
+ PRO_PLAN = "prolite"
160
+ CREDIT_BALANCE = 83600.8856485
178
161
 
179
162
 
180
- def test_should_pick_main_when_it_has_more_room_than_every_extra() -> None:
181
- main = Reading(
182
- _account("main", Product.CLAUDE, main=True),
183
- _meters(80, 80, weekly_reset=NOW + timedelta(days=5)),
184
- )
185
- extras = (
186
- Reading(_account("second", Product.CLAUDE), _meters(60, 60)),
187
- Reading(_account("third", Product.CLAUDE), _meters(40, 40)),
163
+ def _current_roster() -> tuple[Reading, ...]:
164
+ return (
165
+ Reading(_account("editor"), _meters(None, 100, plan_type=FREE_PLAN)),
166
+ Reading(_account("team-mel"), _meters(None, 81, plan_type=TEAM_PLAN)),
167
+ Reading(_account("team-jon"), _meters(None, 81, plan_type=TEAM_PLAN)),
168
+ Reading(_account("personal"), _meters(None, 1, plan_type=PRO_PLAN, credit_balance=CREDIT_BALANCE)),
188
169
  )
189
170
 
190
- decision = choose_from_readings(Product.CLAUDE, (*extras, main), now=NOW)
191
-
192
- assert decision.action == "run"
193
- assert decision.account == main.account
194
171
 
172
+ def test_should_choose_the_pro_account_with_credits_over_free_and_team_accounts_with_more_room() -> None:
173
+ readings = _current_roster()
195
174
 
196
- def test_should_pick_an_extra_with_more_room_than_main() -> None:
197
- main = Reading(
198
- _account("main", Product.CLAUDE, main=True),
199
- _meters(60, 60, weekly_reset=NOW + timedelta(hours=4)),
200
- )
201
- extra = Reading(_account("extra", Product.CLAUDE), _meters(90, 90))
202
-
203
- decision = choose_from_readings(Product.CLAUDE, (main, extra), now=NOW)
175
+ decision = choose_from_readings(Product.CODEX, readings, now=NOW)
204
176
 
205
- assert decision.account == extra.account
177
+ assert decision.action == "run"
178
+ assert decision.account == readings[3].account
179
+ assert decision.tier == "normal"
180
+ assert decision.reason == "personal has 1% left and credits"
206
181
 
207
182
 
208
- @pytest.mark.parametrize(("main_short_left", "expected_name"), ((6, "main"), (5, "extra")))
209
- def test_should_pick_main_only_while_under_its_5_hour_ceiling(
210
- main_short_left: float, expected_name: str
211
- ) -> None:
212
- main = Reading(
213
- _account("main", Product.CLAUDE, main=True),
214
- _meters(main_short_left, 95, weekly_reset=NOW + timedelta(days=5)),
183
+ def test_should_pick_a_pro_account_with_credits_even_when_a_spent_mark_names_it() -> None:
184
+ pro_account = _account("pro-with-credits")
185
+ readings = (
186
+ Reading(_account("team"), _meters(None, 81, plan_type=TEAM_PLAN)),
187
+ Reading(pro_account, _meters(0, 0, plan_type=PRO_PLAN, credit_balance=CREDIT_BALANCE)),
215
188
  )
216
- extra = Reading(_account("extra", Product.CLAUDE), _meters(20, 2))
217
-
218
- decision = choose_from_readings(Product.CLAUDE, (main, extra), now=NOW)
219
-
220
- assert decision.account.name == expected_name
221
-
222
189
 
223
- def test_should_pick_main_when_it_is_the_only_readable_account() -> None:
224
- main = Reading(
225
- _account("main", Product.CLAUDE, main=True),
226
- _meters(80, 80, weekly_reset=NOW + timedelta(days=5)),
190
+ decision = choose_from_readings(
191
+ Product.CODEX,
192
+ readings,
193
+ now=NOW,
194
+ all_spent_accounts=frozenset({pro_account}),
195
+ all_spent_resets={pro_account: NOW + timedelta(hours=1)},
227
196
  )
228
- unread = Reading(_account("extra", Product.CLAUDE), None)
229
-
230
- decision = choose_from_readings(Product.CLAUDE, (unread, main), now=NOW)
231
197
 
232
198
  assert decision.action == "run"
233
- assert decision.account == main.account
199
+ assert decision.account == pro_account
200
+ assert decision.tier == "normal"
234
201
 
235
202
 
236
- def test_should_pick_main_when_its_5_hour_meter_is_null_and_its_week_has_room() -> None:
237
- main = Reading(
238
- _account("main", Product.CLAUDE, main=True),
239
- Meters(None, None, 96.0, NOW + timedelta(days=5)),
203
+ def test_should_keep_a_spent_mark_on_a_pro_account_without_credits() -> None:
204
+ pro_account = _account("pro-without-credits")
205
+ readings = (
206
+ Reading(_account("team"), _meters(None, 81, plan_type=TEAM_PLAN)),
207
+ Reading(pro_account, _meters(0, 0, plan_type=PRO_PLAN)),
240
208
  )
241
209
 
242
- decision = choose_from_readings(Product.CLAUDE, (main,), now=NOW)
210
+ decision = choose_from_readings(
211
+ Product.CODEX,
212
+ readings,
213
+ now=NOW,
214
+ all_spent_accounts=frozenset({pro_account}),
215
+ all_spent_resets={pro_account: NOW + timedelta(hours=1)},
216
+ )
243
217
 
244
218
  assert decision.action == "run"
245
- assert decision.account == main.account
246
- assert decision.reason == "main has 96% left"
219
+ assert decision.account == readings[0].account
247
220
 
248
221
 
249
- def test_should_wait_for_main_5_hour_reset_while_its_week_resets_days_away() -> None:
250
- short_reset = NOW + timedelta(hours=2)
251
- main = Reading(
252
- _account("main", Product.CLAUDE, main=True),
253
- _meters(5, 50, short_reset=short_reset, weekly_reset=NOW + timedelta(days=3)),
222
+ def test_should_choose_the_current_roster_through_the_choose_command(
223
+ monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
224
+ ) -> None:
225
+ readings = _current_roster()
226
+ all_meters = {each_reading.account.name: each_reading.meters for each_reading in readings}
227
+ monkeypatch.setitem(
228
+ account_broker.all_product_adapters,
229
+ Product.CODEX,
230
+ _adapter(tuple(each_reading.account for each_reading in readings), all_meters),
254
231
  )
255
232
 
256
- decision = choose_from_readings(Product.CLAUDE, (main,), now=NOW)
233
+ exit_code = account_broker.main(("choose", "--product", "codex"))
257
234
 
258
- assert decision.action == "wait"
259
- assert decision.resets_at == short_reset
235
+ payload = json.loads(capsys.readouterr().out)
236
+ personal_entry = next(each_entry for each_entry in payload["accounts"] if each_entry["name"] == "personal")
237
+ assert exit_code == 0
238
+ assert payload["decision"]["account"] == "personal"
239
+ assert payload["decision"]["tier"] == "normal"
240
+ assert personal_entry["meters"]["plan_type"] == PRO_PLAN
241
+ assert personal_entry["meters"]["has_credits"] is True
242
+ assert personal_entry["meters"]["credit_balance"] == CREDIT_BALANCE
260
243
 
261
244
 
262
- def test_should_check_main_again_in_an_hour_when_a_blocking_window_has_no_reset() -> None:
263
- main = Reading(
264
- _account("main", Product.CLAUDE, main=True),
265
- Meters(5, None, 1, NOW + timedelta(hours=4)),
245
+ def test_should_never_choose_a_free_account_even_when_it_has_the_most_room() -> None:
246
+ readings = (
247
+ Reading(_account("editor"), _meters(100, 100, plan_type=FREE_PLAN)),
248
+ Reading(_account("team"), _meters(40, 5, plan_type=TEAM_PLAN)),
266
249
  )
267
250
 
268
- decision = choose_from_readings(Product.CLAUDE, (main,), now=NOW)
251
+ decision = choose_from_readings(Product.CODEX, readings, now=NOW)
269
252
 
270
- assert decision.action == "wait"
271
- assert decision.resets_at == NOW + timedelta(hours=1)
253
+ assert decision.account == readings[1].account
254
+ assert decision.tier == "luna"
272
255
 
273
256
 
274
257
  @pytest.mark.parametrize(
275
- ("short_left", "weekly_left", "weekly_reset", "expected_reset"),
276
- (
277
- (5, 20, NOW + timedelta(hours=4), NOW + timedelta(hours=2)),
278
- (80, 1, NOW + timedelta(hours=4), NOW + timedelta(hours=4)),
279
- ),
258
+ ("credit_balance", "is_credits_unlimited"), ((None, False), (CREDIT_BALANCE, False), (None, True))
280
259
  )
281
- def test_should_wait_for_the_meter_or_window_that_blocks_main(
282
- short_left: float, weekly_left: float, weekly_reset: datetime, expected_reset: datetime
260
+ def test_should_wait_and_name_the_free_plan_when_the_only_account_is_free(
261
+ credit_balance: float | None, is_credits_unlimited: bool
283
262
  ) -> None:
284
- main = Reading(
285
- _account("main", Product.CLAUDE, main=True),
286
- _meters(short_left, weekly_left, short_reset=NOW + timedelta(hours=2), weekly_reset=weekly_reset),
263
+ reading = Reading(
264
+ _account("editor"),
265
+ _meters(100, 100, plan_type=FREE_PLAN, credit_balance=credit_balance, is_credits_unlimited=is_credits_unlimited),
287
266
  )
288
267
 
289
- decision = choose_from_readings(Product.CLAUDE, (main,), now=NOW)
268
+ decision = choose_from_readings(Product.CODEX, (reading,), now=NOW)
290
269
 
291
270
  assert decision.action == "wait"
292
- assert decision.resets_at == expected_reset
293
-
294
-
295
- def test_should_try_next_account_after_usage_limit(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
296
- accounts = (_account("first"), _account("second"))
297
- adapter = _adapter(accounts, {"first": _meters(80, 80), "second": _meters(70, 70)})
298
- attempted: list[str] = []
271
+ assert decision.account is None
272
+ assert decision.reason == (
273
+ "no account has room (editor is on a free plan and is never chosen); next check at 2026-10-03T01:00:00+00:00"
274
+ )
299
275
 
300
- def runner(command: object, **options: object) -> subprocess.CompletedProcess[str]:
301
- selected = Path(options["env"]["CODEX_HOME"]).name
302
- attempted.append(selected)
303
- if selected == "first":
304
- return subprocess.CompletedProcess(command, 1, "", "rate limit")
305
- return subprocess.CompletedProcess(command, 0, "served", "")
306
276
 
307
- report_path = tmp_path / "report.json"
308
- monkeypatch.setitem(account_broker.all_product_adapters, Product.CODEX, adapter)
309
- with account_broker.override_subprocess_runner(runner):
310
- outcome, report = account_broker._execute(
277
+ def test_should_exit_three_for_check_when_the_only_account_is_free(monkeypatch: pytest.MonkeyPatch) -> None:
278
+ account = _account("editor")
279
+ monkeypatch.setitem(
280
+ account_broker.all_product_adapters,
311
281
  Product.CODEX,
312
- ("job",),
313
- now=NOW,
314
- )
315
- account_broker._write_report(report_path, report)
282
+ _adapter((account,), {"editor": _meters(100, 100, plan_type=FREE_PLAN)}),
283
+ )
316
284
 
317
- report = json.loads(report_path.read_text(encoding="utf-8"))
318
- assert outcome.returncode == 0
319
- assert attempted == ["first", "second"]
320
- assert [event["type"] for event in report["events"]] == ["pick", "attempt", "pick", "attempt"]
321
- assert report["final_decision"]["account"] == "second"
285
+ assert account_broker.main(("check", "--product", "codex")) == WAIT_EXIT_CODE
322
286
 
323
287
 
324
- def test_should_wait_for_soonest_reset_and_exit_three(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
325
- accounts = (_account("first"), _account("second"))
326
- first_reset = NOW + timedelta(hours=5)
327
- second_reset = NOW + timedelta(hours=3)
328
- adapter = _adapter(
329
- accounts,
330
- {
331
- "first": _meters(0, 0, short_reset=first_reset, weekly_reset=first_reset),
332
- "second": _meters(0, 0, short_reset=second_reset, weekly_reset=second_reset),
333
- },
288
+ def test_should_not_run_a_job_on_a_free_account(monkeypatch: pytest.MonkeyPatch) -> None:
289
+ account = _account("editor")
290
+ monkeypatch.setitem(
291
+ account_broker.all_product_adapters,
292
+ Product.CODEX,
293
+ _adapter((account,), {"editor": _meters(100, 100, plan_type=FREE_PLAN)}),
334
294
  )
295
+ all_invoked_homes: list[str] = []
335
296
 
336
- report_path = tmp_path / "report.json"
337
- monkeypatch.setitem(account_broker.all_product_adapters, Product.CODEX, adapter)
338
- with account_broker.override_subprocess_runner(lambda command, **options: pytest.fail("a waiting job ran")):
339
- outcome, report = account_broker._execute(
340
- Product.CODEX,
341
- ("job",),
342
- now=NOW,
343
- )
344
- account_broker._write_report(report_path, report)
297
+ def runner(argv: object, **options: object) -> subprocess.CompletedProcess[str]:
298
+ all_invoked_homes.append(Path(options["env"]["CODEX_HOME"]).name)
299
+ return subprocess.CompletedProcess(argv, 0, "served", "")
345
300
 
346
- report = json.loads(report_path.read_text(encoding="utf-8"))
301
+ with account_broker.override_subprocess_runner(runner):
302
+ outcome, _ = account_broker._execute(Product.CODEX, ("job",), now=NOW)
303
+
304
+ assert all_invoked_homes == []
305
+ assert outcome.status == "wait"
347
306
  assert outcome.returncode == WAIT_EXIT_CODE
348
- assert report["final_decision"]["action"] == "wait"
349
- assert report["final_decision"]["resets_at"] == second_reset.isoformat()
350
307
 
351
308
 
352
- def test_should_wait_until_both_blocking_windows_reset() -> None:
353
- short_reset = NOW + timedelta(hours=2)
354
- weekly_reset = NOW + timedelta(days=2)
355
- reading = Reading(
356
- _account("spent"),
357
- _meters(0, 0, short_reset=short_reset, weekly_reset=weekly_reset),
309
+ def _pro_below_the_normal_bar_beside_a_roomy_team() -> tuple[Reading, ...]:
310
+ return (
311
+ Reading(_account("team"), _meters(None, 90, plan_type=TEAM_PLAN)),
312
+ Reading(_account("personal"), _meters(None, 5, plan_type="pro")),
358
313
  )
359
314
 
360
- decision = choose_from_readings(Product.CODEX, (reading,), now=NOW)
361
315
 
362
- assert decision.resets_at == weekly_reset
316
+ def test_should_give_a_caller_with_no_tier_requirement_the_pro_account_in_the_luna_tier() -> None:
317
+ readings = _pro_below_the_normal_bar_beside_a_roomy_team()
363
318
 
319
+ decision = choose_from_readings(Product.CODEX, readings, now=NOW)
364
320
 
365
- def test_should_use_claude_extra_floors_and_wait_for_unread() -> None:
366
- blocked = Reading(
367
- _account("blocked", Product.CLAUDE), _meters(5, 1)
368
- )
369
- unread = Reading(_account("unread", Product.CLAUDE), None)
321
+ assert decision.account == readings[1].account
322
+ assert decision.tier == "luna"
370
323
 
371
- decision = choose_from_readings(Product.CLAUDE, (blocked, unread), now=NOW)
372
324
 
373
- assert decision.action == "wait"
374
- assert decision.account is None
325
+ def test_should_give_a_caller_that_requires_the_normal_tier_the_team_account_over_a_pro_account_in_luna() -> None:
326
+ readings = _pro_below_the_normal_bar_beside_a_roomy_team()
375
327
 
328
+ decision = choose_from_readings(Product.CODEX, readings, now=NOW, required_tier="normal")
376
329
 
377
- def _ranked_claude_account(name: str, priority: int | None) -> Account:
378
- return Account(Product.CLAUDE, name, Path("/profiles") / name, False, name, priority)
330
+ assert decision.action == "run"
331
+ assert decision.account == readings[0].account
332
+ assert decision.tier == "normal"
379
333
 
380
334
 
381
- def test_should_pick_the_first_claude_account_in_priority_order_with_room() -> None:
335
+ def test_should_give_a_caller_that_requires_the_normal_tier_the_pro_account_when_it_qualifies() -> None:
382
336
  readings = (
383
- Reading(_ranked_claude_account("roomy", 2), _meters(90, 90)),
384
- Reading(_ranked_claude_account("spent", 0), _meters(5, 90)),
385
- Reading(_ranked_claude_account("preferred", 1), _meters(20, 20)),
386
- Reading(_ranked_claude_account("unranked", None), _meters(99, 99)),
337
+ Reading(_account("team"), _meters(None, 90, plan_type=TEAM_PLAN)),
338
+ Reading(_account("personal"), _meters(None, 30, plan_type="pro")),
387
339
  )
388
340
 
389
- decision = choose_from_readings(Product.CLAUDE, readings, now=NOW)
341
+ decision = choose_from_readings(Product.CODEX, readings, now=NOW, required_tier="normal")
390
342
 
391
- assert decision.account.name == "preferred"
392
- assert "priority 2" in decision.reason
343
+ assert decision.account == readings[1].account
344
+ assert decision.tier == "normal"
393
345
 
394
346
 
395
- def test_should_fall_back_to_the_roomiest_unranked_claude_account() -> None:
347
+ def test_should_give_a_caller_that_requires_the_normal_tier_a_pro_account_that_runs_on_credits() -> None:
396
348
  readings = (
397
- Reading(_ranked_claude_account("ranked_spent", 0), _meters(5, 5)),
398
- Reading(_ranked_claude_account("tight", None), _meters(30, 30)),
399
- Reading(_ranked_claude_account("roomy", None), _meters(60, 60)),
349
+ Reading(_account("team"), _meters(None, 90, plan_type=TEAM_PLAN)),
350
+ Reading(_account("personal"), _meters(None, 0.5, plan_type="pro", credit_balance=CREDIT_BALANCE)),
400
351
  )
401
352
 
402
- decision = choose_from_readings(Product.CLAUDE, readings, now=NOW)
353
+ decision = choose_from_readings(Product.CODEX, readings, now=NOW, required_tier="normal")
403
354
 
404
- assert decision.account.name == "roomy"
355
+ assert decision.account == readings[1].account
356
+ assert decision.tier == "normal"
405
357
 
406
358
 
407
- def test_should_keep_resume_affinity_ahead_of_priority() -> None:
359
+ def test_should_wait_for_a_caller_that_requires_the_normal_tier_when_every_account_is_in_luna() -> None:
408
360
  readings = (
409
- Reading(_ranked_claude_account("first", 0), _meters(90, 90)),
410
- Reading(_ranked_claude_account("bound", 1), _meters(40, 40)),
361
+ Reading(_account("team"), _meters(None, 5, plan_type=TEAM_PLAN)),
362
+ Reading(_account("personal"), _meters(None, 5, plan_type="pro")),
411
363
  )
412
364
 
413
- decision = choose_from_readings(Product.CLAUDE, readings, now=NOW, preferred_command="bound")
365
+ decision = choose_from_readings(Product.CODEX, readings, now=NOW, required_tier="normal")
414
366
 
415
- assert decision.account.name == "bound"
416
- assert decision.reason == "resume affinity"
367
+ assert decision.action == "wait"
368
+ assert decision.account is None
369
+ assert decision.tier == "wait"
417
370
 
418
371
 
419
- def test_should_wait_when_every_ranked_claude_account_is_spent() -> None:
372
+ def test_should_never_give_a_caller_that_requires_the_normal_tier_a_free_account_with_more_room() -> None:
420
373
  readings = (
421
- Reading(_ranked_claude_account("first", 0), _meters(5, 5)),
422
- Reading(_ranked_claude_account("second", 1), _meters(0, 50)),
374
+ Reading(_account("editor"), _meters(100, 100, plan_type=FREE_PLAN)),
375
+ Reading(_account("team"), _meters(None, 5, plan_type=TEAM_PLAN)),
423
376
  )
424
377
 
425
- decision = choose_from_readings(Product.CLAUDE, readings, now=NOW)
378
+ decision = choose_from_readings(Product.CODEX, readings, now=NOW, required_tier="normal")
426
379
 
427
380
  assert decision.action == "wait"
428
381
 
429
382
 
430
- @pytest.mark.parametrize("count", (1, 5))
431
- def test_should_consider_every_account_in_the_roster(count: int) -> None:
432
- readings = tuple(
433
- Reading(_account(f"account_{index}"), _meters(30 + index, 30 + index))
434
- for index in range(count)
435
- )
436
-
437
- decision = choose_from_readings(Product.CODEX, readings, now=NOW)
438
-
439
- assert decision.account == readings[-1].account
440
-
441
-
442
- def test_should_use_luna_floor_without_choosing_a_model() -> None:
443
- reading = Reading(_account("low"), _meters(30, 8))
444
-
445
- decision = choose_from_readings(Product.CODEX, (reading,), now=NOW)
446
-
447
- assert decision.account == reading.account
448
- assert decision.tier == "luna"
449
- assert not hasattr(decision, "model")
450
-
451
-
452
- def test_should_keep_resume_affinity_when_account_has_room() -> None:
383
+ def test_should_leave_a_claude_choice_unchanged_for_a_caller_that_requires_the_normal_tier() -> None:
453
384
  readings = (
454
- Reading(_account("roomy", Product.CLAUDE), _meters(80, 80)),
455
- Reading(_account("origin", Product.CLAUDE), _meters(20, 20)),
385
+ Reading(_account("first", Product.CLAUDE), _meters(12, 80)),
386
+ Reading(_account("second", Product.CLAUDE), _meters(70, 40)),
456
387
  )
457
388
 
458
- decision = choose_from_readings(
459
- Product.CLAUDE, readings, now=NOW, preferred_command="origin"
460
- )
389
+ without_requirement = choose_from_readings(Product.CLAUDE, readings, now=NOW)
390
+ with_requirement = choose_from_readings(Product.CLAUDE, readings, now=NOW, required_tier="normal")
461
391
 
462
- assert decision.account == readings[1].account
392
+ assert with_requirement == without_requirement
463
393
 
464
394
 
465
- def test_should_exit_three_for_check_while_all_accounts_wait(monkeypatch: pytest.MonkeyPatch) -> None:
466
- account = _account("spent")
395
+ def test_should_pass_the_required_tier_through_the_choose_command(
396
+ monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
397
+ ) -> None:
398
+ readings = _pro_below_the_normal_bar_beside_a_roomy_team()
399
+ all_meters = {each_reading.account.name: each_reading.meters for each_reading in readings}
467
400
  monkeypatch.setitem(
468
401
  account_broker.all_product_adapters,
469
402
  Product.CODEX,
470
- _adapter((account,), {"spent": _meters(0, 0)}),
403
+ _adapter(tuple(each_reading.account for each_reading in readings), all_meters),
471
404
  )
472
405
 
473
- assert account_broker.main(("check", "--product", "codex")) == WAIT_EXIT_CODE
406
+ without_requirement_code = account_broker.main(("choose", "--product", "codex"))
407
+ without_requirement = json.loads(capsys.readouterr().out)["decision"]
408
+ with_requirement_code = account_broker.main(("choose", "--product", "codex", "--require-tier", "normal"))
409
+ with_requirement = json.loads(capsys.readouterr().out)["decision"]
474
410
 
411
+ assert (without_requirement_code, without_requirement["account"], without_requirement["tier"]) == (0, "personal", "luna")
412
+ assert (with_requirement_code, with_requirement["account"], with_requirement["tier"]) == (0, "team", "normal")
475
413
 
476
- def test_should_print_decision_and_meters_for_choose(
414
+
415
+ def test_should_exit_three_with_a_wait_answer_when_the_required_tier_has_no_account(
477
416
  monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
478
417
  ) -> None:
479
- account = _account("roomy")
418
+ account = _account("personal")
480
419
  monkeypatch.setitem(
481
420
  account_broker.all_product_adapters,
482
421
  Product.CODEX,
483
- _adapter((account,), {"roomy": _meters(80, 70)}),
422
+ _adapter((account,), {"personal": _meters(None, 5, plan_type="pro")}),
484
423
  )
485
424
 
486
- assert account_broker.main(("choose", "--product", "codex")) == 0
487
- payload = json.loads(capsys.readouterr().out)
488
- assert payload["decision"]["account"] == "roomy"
489
- assert payload["decision"]["profile"] is None
490
- assert payload["accounts"][0]["meters"]["session_percent_left"] == 80
491
- assert payload["state_path"].endswith("state.json")
425
+ exit_code = account_broker.main(("choose", "--product", "codex", "--require-tier", "normal"))
426
+
427
+ decision = json.loads(capsys.readouterr().out)["decision"]
428
+ assert exit_code == WAIT_EXIT_CODE
429
+ assert decision["action"] == "wait"
430
+ assert decision["tier"] == "wait"
492
431
 
493
432
 
494
- def test_should_count_failed_meter_read_as_spent() -> None:
433
+ def test_should_refuse_a_required_tier_the_broker_does_not_name(capsys: pytest.CaptureFixture[str]) -> None:
434
+ with pytest.raises(SystemExit) as raised:
435
+ account_broker.main(("choose", "--product", "codex", "--require-tier", "turbo"))
436
+
437
+ assert raised.value.code == 2
438
+ assert "invalid choice: 'turbo'" in capsys.readouterr().err
439
+
440
+
441
+ UNKNOWN_PLAN = "unknown"
442
+ NO_PLAN_VALUES = (None, UNKNOWN_PLAN, "Unknown", " UNKNOWN ", "")
443
+
444
+
445
+ @pytest.mark.parametrize("plan_type", NO_PLAN_VALUES)
446
+ def test_should_never_choose_an_account_with_no_known_plan_even_when_it_has_the_most_room(plan_type: str | None) -> None:
495
447
  readings = (
496
- Reading(_account("unread"), None),
497
- Reading(_account("roomy"), _meters(70, 70)),
448
+ Reading(_account("unlabelled"), _meters(100, 100, plan_type=plan_type)),
449
+ Reading(_account("team"), _meters(40, 5, plan_type=TEAM_PLAN)),
498
450
  )
499
451
 
500
452
  decision = choose_from_readings(Product.CODEX, readings, now=NOW)
501
453
 
502
454
  assert decision.account == readings[1].account
455
+ assert decision.tier == "luna"
503
456
 
504
457
 
505
- def test_should_serialize_readings_with_named_fields() -> None:
506
- reading = Reading(_account("one"), _meters(80, 70), measured_at=NOW)
458
+ @pytest.mark.parametrize(
459
+ ("credit_balance", "is_credits_unlimited"), ((None, False), (CREDIT_BALANCE, False), (None, True))
460
+ )
461
+ def test_should_wait_and_name_the_missing_plan_when_the_only_account_has_no_known_plan(
462
+ credit_balance: float | None, is_credits_unlimited: bool
463
+ ) -> None:
464
+ reading = Reading(
465
+ _account("unlabelled"),
466
+ _meters(100, 100, plan_type=UNKNOWN_PLAN, credit_balance=credit_balance, is_credits_unlimited=is_credits_unlimited),
467
+ )
507
468
 
508
- payload = account_broker.readings_payload((reading,))
469
+ decision = choose_from_readings(Product.CODEX, (reading,), now=NOW)
509
470
 
510
- assert payload[0]["name"] == "one"
511
- assert payload[0]["meters"]["weekly_percent_left"] == 70
512
- assert payload[0]["measured_at"] == NOW.isoformat()
471
+ assert decision.action == "wait"
472
+ assert decision.account is None
473
+ assert decision.reason == (
474
+ "no account has room (unlabelled reports no known plan and is never chosen); "
475
+ "next check at 2026-10-03T01:00:00+00:00"
476
+ )
513
477
 
514
478
 
515
- def test_should_wait_until_the_rate_limit_probe_after_stale_meters_expire() -> None:
516
- reading = Reading(
517
- _account("one", Product.CLAUDE), None,
518
- "usage probe failed: HTTP Error 429", NOW - timedelta(minutes=25),
519
- NOW + timedelta(minutes=5),
479
+ def test_should_name_each_refusal_apart_when_a_free_account_and_an_account_with_no_plan_are_the_only_accounts() -> None:
480
+ readings = (
481
+ Reading(_account("editor"), _meters(100, 100, plan_type=FREE_PLAN)),
482
+ Reading(_account("unlabelled"), _meters(100, 100, plan_type=None)),
520
483
  )
521
484
 
522
- decision = choose_from_readings(Product.CLAUDE, (reading,), now=NOW)
485
+ decision = choose_from_readings(Product.CODEX, readings, now=NOW)
523
486
 
524
487
  assert decision.action == "wait"
525
- assert decision.resets_at == NOW + timedelta(minutes=5)
526
488
  assert decision.reason == (
527
- "no account meter could be read (one (usage probe failed: HTTP Error 429)); "
528
- "next check at 2026-10-03T00:05:00+00:00"
489
+ "no account has room (editor is on a free plan and is never chosen, "
490
+ "unlabelled reports no known plan and is never chosen); next check at 2026-10-03T01:00:00+00:00"
529
491
  )
530
492
 
531
493
 
532
- def test_should_wait_when_all_meter_reads_fail() -> None:
533
- readings = (Reading(_account("first"), None), Reading(_account("second"), None))
494
+ def test_should_exit_three_for_check_when_the_only_account_has_no_known_plan(monkeypatch: pytest.MonkeyPatch) -> None:
495
+ account = _account("unlabelled")
496
+ monkeypatch.setitem(
497
+ account_broker.all_product_adapters,
498
+ Product.CODEX,
499
+ _adapter((account,), {"unlabelled": _meters(100, 100, plan_type=UNKNOWN_PLAN)}),
500
+ )
501
+
502
+ assert account_broker.main(("check", "--product", "codex")) == WAIT_EXIT_CODE
503
+
504
+
505
+ def test_should_keep_the_unread_handling_for_an_account_whose_meters_could_not_be_read() -> None:
506
+ readings = (
507
+ Reading(_account("unread"), None, "codex app-server failed: timed out"),
508
+ Reading(_account("unlabelled"), _meters(100, 100, plan_type=None)),
509
+ )
534
510
 
535
511
  decision = choose_from_readings(Product.CODEX, readings, now=NOW)
536
512
 
537
513
  assert decision.action == "wait"
538
- assert decision.resets_at == NOW + timedelta(hours=1)
514
+ assert decision.reason == (
515
+ "no readable account has room (unlabelled reports no known plan and is never chosen); "
516
+ "meter unreadable for unread (codex app-server failed: timed out); next check at 2026-10-03T01:00:00+00:00"
517
+ )
539
518
 
540
519
 
541
- _MAIN_CLAUDE = _account("main", Product.CLAUDE, main=True)
542
- _EV_CLAUDE = _account("ev", Product.CLAUDE)
520
+ UNRECOGNISED_PLANS = ("free_works", "free trial", "pro_trial", "teams", "freemium")
521
+ PAID_PLANS = ("pro", "prolite", "promax", "team", "plus", "business", "enterprise", "edu")
522
+
523
+
524
+ @pytest.mark.parametrize("plan_type", UNRECOGNISED_PLANS)
525
+ def test_should_never_choose_an_account_on_an_unrecognised_plan_even_when_it_has_the_most_room(plan_type: str) -> None:
526
+ readings = (
527
+ Reading(_account("unrecognised"), _meters(100, 100, plan_type=plan_type)),
528
+ Reading(_account("team"), _meters(40, 5, plan_type=TEAM_PLAN)),
529
+ )
530
+
531
+ decision = choose_from_readings(Product.CODEX, readings, now=NOW)
532
+
533
+ assert decision.account == readings[1].account
534
+ assert decision.tier == "luna"
543
535
 
544
536
 
537
+ @pytest.mark.parametrize("plan_type", UNRECOGNISED_PLANS)
545
538
  @pytest.mark.parametrize(
546
- ("readings", "spent_resets", "expected_reason", "expected_resets_at"),
547
- (
548
- pytest.param(
549
- (Reading(_MAIN_CLAUDE, None), Reading(_EV_CLAUDE, None)),
550
- {},
551
- "no account meter could be read (main, ev); next check at 2026-10-03T01:00:00+00:00",
552
- NOW + timedelta(hours=1),
553
- id="every-meter-unreadable",
554
- ),
555
- pytest.param(
556
- (Reading(_MAIN_CLAUDE, _meters(5, 50, short_reset=NOW + timedelta(minutes=30))), Reading(_EV_CLAUDE, None)),
557
- {},
558
- "no readable account has room (main 5% left); meter unreadable for ev; next reset at 2026-10-03T00:30:00+00:00",
559
- NOW + timedelta(minutes=30),
560
- id="unreadable-beside-a-reset-before-the-check",
561
- ),
562
- pytest.param(
563
- (Reading(_MAIN_CLAUDE, _meters(5, 50, short_reset=NOW + timedelta(hours=2))), Reading(_EV_CLAUDE, None)),
564
- {},
565
- "no readable account has room (main 5% left); meter unreadable for ev; next check at 2026-10-03T01:00:00+00:00",
566
- NOW + timedelta(hours=1),
567
- id="unreadable-beside-a-reset-after-the-check",
568
- ),
569
- pytest.param(
570
- (Reading(_MAIN_CLAUDE, _meters(80, 80)), Reading(_EV_CLAUDE, None)),
571
- {_MAIN_CLAUDE: NOW + timedelta(minutes=30)},
572
- "no readable account has room (main spent); meter unreadable for ev; next reset at 2026-10-03T00:30:00+00:00",
573
- NOW + timedelta(minutes=30),
574
- id="unreadable-beside-a-spent-account",
575
- ),
576
- pytest.param(
577
- (
578
- Reading(_MAIN_CLAUDE, _meters(5, 50, short_reset=NOW + timedelta(hours=2))),
579
- Reading(_EV_CLAUDE, _meters(5, 80, short_reset=NOW + timedelta(hours=3))),
580
- ),
581
- {},
582
- "no account has room (main 5% left, ev 5% left); next reset at 2026-10-03T02:00:00+00:00",
583
- NOW + timedelta(hours=2),
584
- id="every-meter-read-with-known-resets",
585
- ),
586
- pytest.param(
587
- (Reading(_MAIN_CLAUDE, Meters(5, None, 50, None)),),
588
- {},
589
- "no account has room (main 5% left); next check at 2026-10-03T01:00:00+00:00",
590
- NOW + timedelta(hours=1),
591
- id="every-meter-read-without-a-known-reset",
592
- ),
593
- pytest.param(
594
- (),
595
- {},
596
- "no account has room; next check at 2026-10-03T01:00:00+00:00",
597
- NOW + timedelta(hours=1),
598
- id="no-account-in-the-roster",
599
- ),
600
- pytest.param(
601
- (Reading(_MAIN_CLAUDE, Meters(None, None, None, None)),),
602
- {},
603
- "no account has room (main percent left unread); next check at 2026-10-03T01:00:00+00:00",
604
- NOW + timedelta(hours=1),
605
- id="meter-read-without-a-percent",
606
- ),
607
- ),
539
+ ("credit_balance", "is_credits_unlimited"), ((None, False), (CREDIT_BALANCE, False), (None, True))
608
540
  )
609
- def test_should_name_what_the_broker_knows_in_the_wait_reason(
610
- readings: tuple[Reading, ...],
611
- spent_resets: dict[Account, datetime],
612
- expected_reason: str,
613
- expected_resets_at: datetime,
541
+ def test_should_wait_and_name_the_missing_plan_when_the_only_account_is_on_an_unrecognised_plan(
542
+ plan_type: str, credit_balance: float | None, is_credits_unlimited: bool
614
543
  ) -> None:
615
- decision = choose_from_readings(
616
- Product.CLAUDE,
617
- readings,
618
- now=NOW,
619
- all_spent_accounts=frozenset(spent_resets),
620
- all_spent_resets=spent_resets,
544
+ reading = Reading(
545
+ _account("unrecognised"),
546
+ _meters(100, 100, plan_type=plan_type, credit_balance=credit_balance, is_credits_unlimited=is_credits_unlimited),
621
547
  )
622
548
 
549
+ decision = choose_from_readings(Product.CODEX, (reading,), now=NOW)
550
+
623
551
  assert decision.action == "wait"
624
- assert decision.reason == expected_reason
625
- assert decision.resets_at == expected_resets_at
552
+ assert decision.account is None
553
+ assert decision.reason == (
554
+ "no account has room (unrecognised reports no known plan and is never chosen); "
555
+ "next check at 2026-10-03T01:00:00+00:00"
556
+ )
626
557
 
627
558
 
628
- def test_should_carry_the_unreadable_meter_reason_into_the_worker_report(
629
- monkeypatch: pytest.MonkeyPatch, tmp_path: Path
559
+ @pytest.mark.parametrize("plan_type", UNRECOGNISED_PLANS)
560
+ def test_should_never_choose_an_account_on_an_unrecognised_plan_when_the_floor_switch_is_on(
561
+ monkeypatch: pytest.MonkeyPatch, plan_type: str
630
562
  ) -> None:
631
- adapter = _adapter((_MAIN_CLAUDE, _EV_CLAUDE), {"main": None, "ev": None})
632
- monkeypatch.setitem(account_broker.all_product_adapters, Product.CLAUDE, adapter)
633
- prompt_file = tmp_path / "brief.md"
634
- prompt_file.write_text("standalone brief", encoding="utf-8")
635
- report_file = tmp_path / "report.json"
563
+ _disable_codex_weekly_floor(monkeypatch)
564
+ reading = Reading(_account("unrecognised"), _meters(30, 0.5, plan_type=plan_type))
636
565
 
637
- with account_broker.override_subprocess_runner(lambda command, **options: pytest.fail("a waiting job ran")):
638
- exit_code = claude_account_worker.run_worker(
639
- prompt_file=prompt_file,
640
- cwd=tmp_path,
641
- report_file=report_file,
642
- model=None,
643
- permission_mode="auto",
644
- timeout_minutes=60,
645
- )
566
+ decision = choose_from_readings(Product.CODEX, (reading,), now=NOW)
646
567
 
647
- report = json.loads(report_file.read_text(encoding="utf-8"))
648
- assert exit_code == WAIT_EXIT_CODE
649
- assert report["account"] == "wait"
650
- assert report["reason"].startswith("no account meter could be read")
568
+ assert decision.action == "wait"
569
+ assert decision.account is None
651
570
 
652
571
 
653
- def test_should_replay_stdin_bytes_and_only_print_served_stdout(
654
- monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str]
572
+ @pytest.mark.parametrize("plan_type", UNRECOGNISED_PLANS)
573
+ def test_should_exit_three_for_check_when_the_only_account_is_on_an_unrecognised_plan(
574
+ monkeypatch: pytest.MonkeyPatch, plan_type: str
655
575
  ) -> None:
656
- accounts = (_account("first"), _account("second"))
657
- monkeypatch.setitem(account_broker.all_product_adapters, Product.CODEX, _adapter(accounts, {
658
- "first": _meters(80, 80), "second": _meters(70, 70)
659
- }))
660
- original = b"first\r\nsecond\x00\xff"
661
- received: list[bytes] = []
576
+ account = _account("unrecognised")
577
+ monkeypatch.setitem(
578
+ account_broker.all_product_adapters,
579
+ Product.CODEX,
580
+ _adapter((account,), {"unrecognised": _meters(100, 100, plan_type=plan_type)}),
581
+ )
582
+
583
+ assert account_broker.main(("check", "--product", "codex")) == WAIT_EXIT_CODE
584
+
585
+
586
+ @pytest.mark.parametrize("plan_type", UNRECOGNISED_PLANS)
587
+ def test_should_not_run_a_job_on_an_account_on_an_unrecognised_plan(
588
+ monkeypatch: pytest.MonkeyPatch, plan_type: str
589
+ ) -> None:
590
+ account = _account("unrecognised")
591
+ monkeypatch.setitem(
592
+ account_broker.all_product_adapters,
593
+ Product.CODEX,
594
+ _adapter((account,), {"unrecognised": _meters(100, 100, plan_type=plan_type)}),
595
+ )
596
+ all_invoked_homes: list[str] = []
662
597
 
663
598
  def runner(argv: object, **options: object) -> subprocess.CompletedProcess[str]:
664
- received.append(options["input"])
665
- if len(received) == 1:
666
- return subprocess.CompletedProcess(argv, 1, "discard this", "rate limit")
667
- return subprocess.CompletedProcess(argv, 0, "command output", "")
599
+ all_invoked_homes.append(Path(options["env"]["CODEX_HOME"]).name)
600
+ return subprocess.CompletedProcess(argv, 0, "served", "")
668
601
 
669
- monkeypatch.setattr(account_broker.sys, "stdin", io.TextIOWrapper(io.BytesIO(original), encoding="utf-8"))
670
- report_path = tmp_path / "report.json"
671
602
  with account_broker.override_subprocess_runner(runner):
672
- code = account_broker.main(("run", "--product", "codex", "--report", str(report_path), "--", "job"))
603
+ outcome, _ = account_broker._execute(Product.CODEX, ("job",), now=NOW)
673
604
 
674
- captured_streams = capsys.readouterr()
675
- assert code == 0
676
- assert received == [original, original]
677
- assert captured_streams.out == "command output"
678
- assert json.loads(report_path.read_text(encoding="utf-8"))["final_decision"]["account"] == "second"
605
+ assert all_invoked_homes == []
606
+ assert outcome.status == "wait"
607
+ assert outcome.returncode == WAIT_EXIT_CODE
679
608
 
680
609
 
681
- def test_should_write_wait_report_without_stdout(
682
- monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str]
683
- ) -> None:
684
- account = _account("spent")
685
- monkeypatch.setitem(account_broker.all_product_adapters, Product.CODEX, _adapter((account,), {"spent": _meters(0, 0)}))
686
- monkeypatch.setattr(account_broker.sys, "stdin", io.TextIOWrapper(io.BytesIO(b""), encoding="utf-8"))
687
- report_path = tmp_path / "report.json"
610
+ @pytest.mark.parametrize("plan_type", PAID_PLANS)
611
+ def test_should_choose_an_account_on_every_listed_paid_plan(plan_type: str) -> None:
612
+ reading = Reading(_account("paid"), _meters(100, 100, plan_type=plan_type))
688
613
 
689
- code = account_broker.main(("run", "--product", "codex", "--report", str(report_path), "--", "job"))
614
+ decision = choose_from_readings(Product.CODEX, (reading,), now=NOW)
615
+
616
+ assert decision.action == "run"
617
+ assert decision.account == reading.account
618
+ assert decision.tier == "normal"
619
+
620
+
621
+ @pytest.mark.parametrize("plan_type", [each_plan.upper() for each_plan in PAID_PLANS] + [f" {PAID_PLANS[0]} "])
622
+ def test_should_choose_an_account_on_a_listed_paid_plan_whatever_its_case_or_padding(plan_type: str) -> None:
623
+ reading = Reading(_account("paid"), _meters(100, 100, plan_type=plan_type))
624
+
625
+ decision = choose_from_readings(Product.CODEX, (reading,), now=NOW)
626
+
627
+ assert decision.action == "run"
628
+ assert decision.account == reading.account
629
+
630
+
631
+ def test_should_still_choose_a_claude_account_whose_meters_carry_no_plan_type() -> None:
632
+ readings = (Reading(_account("main", Product.CLAUDE), _meters(80, 80, plan_type=None)),)
633
+
634
+ decision = choose_from_readings(Product.CLAUDE, readings, now=NOW)
635
+
636
+ assert decision.action == "run"
637
+ assert decision.account == readings[0].account
638
+ assert decision.tier == "normal"
639
+
640
+
641
+ def test_should_keep_the_reset_time_of_a_claude_account_with_no_plan_type_when_it_has_no_room() -> None:
642
+ reading = Reading(_account("main", Product.CLAUDE), _meters(0, 80, plan_type=None))
643
+
644
+ decision = choose_from_readings(Product.CLAUDE, (reading,), now=NOW)
645
+
646
+ assert decision.action == "wait"
647
+ assert decision.resets_at == reading.meters.session_resets_at
648
+ assert decision.reason == f"no account has room (main 0% left); next reset at {reading.meters.session_resets_at.isoformat()}"
649
+
650
+
651
+ def test_should_choose_a_team_account_with_credits_at_both_floors() -> None:
652
+ reading = Reading(_account("team"), _meters(0, 0.5, plan_type=TEAM_PLAN, credit_balance=CREDIT_BALANCE))
653
+
654
+ decision = choose_from_readings(Product.CODEX, (reading,), now=NOW)
655
+
656
+ assert decision.action == "run"
657
+ assert decision.account == reading.account
658
+
659
+
660
+ def test_should_exit_zero_for_check_on_an_account_with_credits_at_both_floors(monkeypatch: pytest.MonkeyPatch) -> None:
661
+ account = _account("personal")
662
+ monkeypatch.setitem(
663
+ account_broker.all_product_adapters,
664
+ Product.CODEX,
665
+ _adapter((account,), {"personal": _meters(0, 0.5, plan_type=PRO_PLAN, credit_balance=CREDIT_BALANCE)}),
666
+ )
667
+
668
+ assert account_broker.main(("check", "--product", "codex")) == 0
669
+
670
+
671
+ def test_should_wait_on_an_account_at_both_floors_with_a_zero_credit_balance() -> None:
672
+ reading = Reading(_account("team"), _meters(0, 0.5, plan_type=TEAM_PLAN, credit_balance=0.0))
673
+
674
+ decision = choose_from_readings(Product.CODEX, (reading,), now=NOW)
675
+
676
+ assert decision.action == "wait"
677
+ assert decision.resets_at == reading.meters.weekly_resets_at
678
+
679
+
680
+ def test_should_wait_for_the_session_reset_of_a_pro_account_at_zero_with_a_zero_credit_balance() -> None:
681
+ reading = Reading(_account("personal"), _meters(0, 0.5, plan_type=PRO_PLAN, credit_balance=0.0))
682
+
683
+ decision = choose_from_readings(Product.CODEX, (reading,), now=NOW)
684
+
685
+ assert decision.action == "wait"
686
+ assert decision.resets_at == reading.meters.session_resets_at
687
+
688
+
689
+ def test_should_choose_an_unlimited_credits_account_at_both_floors() -> None:
690
+ reading = Reading(_account("personal"), _meters(0, 0.5, plan_type="pro", is_credits_unlimited=True))
691
+
692
+ decision = choose_from_readings(Product.CODEX, (reading,), now=NOW)
693
+
694
+ assert decision.action == "run"
695
+ assert decision.account == reading.account
696
+
697
+
698
+ def test_should_prefer_a_pro_account_with_plan_usage_over_a_pro_account_with_only_credits() -> None:
699
+ readings = (
700
+ Reading(_account("credits-only"), _meters(None, 0.5, plan_type=PRO_PLAN, credit_balance=CREDIT_BALANCE)),
701
+ Reading(_account("with-usage"), _meters(40, 30, plan_type="pro")),
702
+ )
703
+
704
+ decision = choose_from_readings(Product.CODEX, readings, now=NOW)
705
+
706
+ assert decision.account == readings[1].account
707
+ assert decision.reason == "with-usage has 30% left"
708
+
709
+
710
+ def test_should_prefer_a_team_account_with_plan_usage_over_a_team_account_with_only_credits() -> None:
711
+ readings = (
712
+ Reading(_account("credits-only"), _meters(None, 0.5, plan_type=TEAM_PLAN, credit_balance=CREDIT_BALANCE)),
713
+ Reading(_account("with-usage"), _meters(40, 30, plan_type=TEAM_PLAN)),
714
+ )
715
+
716
+ decision = choose_from_readings(Product.CODEX, readings, now=NOW)
717
+
718
+ assert decision.account == readings[1].account
719
+
720
+
721
+ def test_should_prefer_a_pro_account_with_only_credits_over_a_team_account_with_more_room() -> None:
722
+ readings = (
723
+ Reading(_account("team"), _meters(90, 85, plan_type=TEAM_PLAN)),
724
+ Reading(_account("personal"), _meters(None, 0.5, plan_type="promax", credit_balance=CREDIT_BALANCE)),
725
+ )
726
+
727
+ decision = choose_from_readings(Product.CODEX, readings, now=NOW)
728
+
729
+ assert decision.account == readings[1].account
730
+
731
+
732
+ @pytest.mark.parametrize("weekly_left", (5, 9))
733
+ def test_should_choose_a_pro_account_below_the_normal_floor_over_a_team_account_with_more_room(weekly_left: float) -> None:
734
+ readings = (
735
+ Reading(_account("team"), _meters(None, 90, plan_type=TEAM_PLAN)),
736
+ Reading(_account("personal"), _meters(None, weekly_left, plan_type="pro")),
737
+ )
738
+
739
+ decision = choose_from_readings(Product.CODEX, readings, now=NOW)
740
+
741
+ assert decision.account == readings[1].account
742
+ assert decision.tier == "luna"
743
+
744
+
745
+ @pytest.mark.parametrize(("short_left", "weekly_left"), ((5, 80), (0.5, 80), (None, 1), (None, 0.5), (19, 1)))
746
+ def test_should_choose_a_pro_account_with_plan_usage_left_in_both_windows_over_a_team_account(
747
+ short_left: float | None, weekly_left: float
748
+ ) -> None:
749
+ readings = (
750
+ Reading(_account("team"), _meters(None, 90, plan_type=TEAM_PLAN)),
751
+ Reading(_account("personal"), _meters(short_left, weekly_left, plan_type="pro")),
752
+ )
753
+
754
+ decision = choose_from_readings(Product.CODEX, readings, now=NOW)
755
+
756
+ assert decision.account == readings[1].account
757
+ assert decision.tier == "luna"
758
+
759
+
760
+ @pytest.mark.parametrize(("short_left", "weekly_left"), ((0, 80), (80, 0), (0, 0), (None, 0)))
761
+ def test_should_skip_a_pro_account_with_a_window_at_zero_and_no_credits(
762
+ short_left: float | None, weekly_left: float
763
+ ) -> None:
764
+ readings = (
765
+ Reading(_account("team"), _meters(None, 90, plan_type=TEAM_PLAN)),
766
+ Reading(_account("personal"), _meters(short_left, weekly_left, plan_type="pro")),
767
+ )
768
+
769
+ decision = choose_from_readings(Product.CODEX, readings, now=NOW)
770
+
771
+ assert decision.account == readings[0].account
772
+ assert decision.tier == "normal"
773
+
774
+
775
+ def test_should_wait_for_the_reset_of_a_pro_account_at_zero_when_it_is_the_only_account() -> None:
776
+ reading = Reading(_account("personal"), _meters(0, 80, plan_type="pro"))
777
+
778
+ decision = choose_from_readings(Product.CODEX, (reading,), now=NOW)
779
+
780
+ assert decision.action == "wait"
781
+ assert decision.resets_at == reading.meters.session_resets_at
782
+
783
+
784
+ @pytest.mark.parametrize("weekly_left", (0, 1))
785
+ def test_should_choose_a_pro_account_with_credits_at_the_stop_floor_over_a_team_account(weekly_left: float) -> None:
786
+ readings = (
787
+ Reading(_account("team"), _meters(None, 90, plan_type=TEAM_PLAN)),
788
+ Reading(_account("personal"), _meters(None, weekly_left, plan_type="pro", credit_balance=CREDIT_BALANCE)),
789
+ )
790
+
791
+ decision = choose_from_readings(Product.CODEX, readings, now=NOW)
792
+
793
+ assert decision.account == readings[1].account
794
+ assert decision.tier == "normal"
795
+
796
+
797
+ def test_should_keep_plan_and_credits_through_the_meter_cache() -> None:
798
+ account = _account("personal")
799
+ all_reads: list[str] = []
800
+
801
+ def read_meters(each_account: Account) -> Meters:
802
+ all_reads.append(each_account.name)
803
+ return _meters(None, 1, plan_type=PRO_PLAN, credit_balance=CREDIT_BALANCE)
804
+
805
+ adapter = ProductAdapter(lambda: (account,), read_meters, "CODEX_HOME", ())
806
+ state = account_broker._load_state(account_broker.broker_state_path())
807
+
808
+ fresh = account_broker.read_accounts(Product.CODEX, adapter, all_state=state, now=NOW)
809
+ cached = account_broker.read_accounts(Product.CODEX, adapter, all_state=state, now=NOW + timedelta(seconds=10))
810
+
811
+ assert all_reads == ["personal"]
812
+ assert cached[0].meters == fresh[0].meters
813
+ assert cached[0].meters.has_spendable_credits is True
814
+ assert cached[0].meters.plan_type == PRO_PLAN
815
+
816
+
817
+ def test_should_keep_list_order_when_tighter_windows_tie() -> None:
818
+ readings = (
819
+ Reading(_account("first"), _meters(40, 60)),
820
+ Reading(_account("second"), _meters(70, 40)),
821
+ )
822
+
823
+ decision = choose_from_readings(Product.CODEX, readings, now=NOW)
824
+
825
+ assert decision.account == readings[0].account
826
+
827
+
828
+ @pytest.mark.parametrize(
829
+ ("weekly_reset", "weekly_left", "short_left"),
830
+ (
831
+ (NOW + timedelta(hours=4), 1, 80),
832
+ (NOW + timedelta(hours=4), 20, 5),
833
+ ),
834
+ )
835
+ def test_should_guard_main_at_each_limit(
836
+ weekly_reset: datetime, weekly_left: float, short_left: float
837
+ ) -> None:
838
+ main = Reading(
839
+ _account("main", Product.CLAUDE, main=True),
840
+ _meters(short_left, weekly_left, weekly_reset=weekly_reset),
841
+ )
842
+ extra = Reading(_account("extra", Product.CLAUDE), _meters(20, 20))
843
+
844
+ decision = choose_from_readings(Product.CLAUDE, (main, extra), now=NOW)
845
+
846
+ assert decision.account == extra.account
847
+
848
+
849
+ def test_should_pick_main_when_it_has_more_room_than_every_extra() -> None:
850
+ main = Reading(
851
+ _account("main", Product.CLAUDE, main=True),
852
+ _meters(80, 80, weekly_reset=NOW + timedelta(days=5)),
853
+ )
854
+ extras = (
855
+ Reading(_account("second", Product.CLAUDE), _meters(60, 60)),
856
+ Reading(_account("third", Product.CLAUDE), _meters(40, 40)),
857
+ )
858
+
859
+ decision = choose_from_readings(Product.CLAUDE, (*extras, main), now=NOW)
860
+
861
+ assert decision.action == "run"
862
+ assert decision.account == main.account
863
+
864
+
865
+ def test_should_pick_an_extra_with_more_room_than_main() -> None:
866
+ main = Reading(
867
+ _account("main", Product.CLAUDE, main=True),
868
+ _meters(60, 60, weekly_reset=NOW + timedelta(hours=4)),
869
+ )
870
+ extra = Reading(_account("extra", Product.CLAUDE), _meters(90, 90))
871
+
872
+ decision = choose_from_readings(Product.CLAUDE, (main, extra), now=NOW)
873
+
874
+ assert decision.account == extra.account
875
+
876
+
877
+ @pytest.mark.parametrize(("main_short_left", "expected_name"), ((6, "main"), (5, "extra")))
878
+ def test_should_pick_main_only_while_under_its_5_hour_ceiling(
879
+ main_short_left: float, expected_name: str
880
+ ) -> None:
881
+ main = Reading(
882
+ _account("main", Product.CLAUDE, main=True),
883
+ _meters(main_short_left, 95, weekly_reset=NOW + timedelta(days=5)),
884
+ )
885
+ extra = Reading(_account("extra", Product.CLAUDE), _meters(20, 2))
886
+
887
+ decision = choose_from_readings(Product.CLAUDE, (main, extra), now=NOW)
888
+
889
+ assert decision.account.name == expected_name
890
+
891
+
892
+ def test_should_pick_main_when_it_is_the_only_readable_account() -> None:
893
+ main = Reading(
894
+ _account("main", Product.CLAUDE, main=True),
895
+ _meters(80, 80, weekly_reset=NOW + timedelta(days=5)),
896
+ )
897
+ unread = Reading(_account("extra", Product.CLAUDE), None)
898
+
899
+ decision = choose_from_readings(Product.CLAUDE, (unread, main), now=NOW)
900
+
901
+ assert decision.action == "run"
902
+ assert decision.account == main.account
903
+
904
+
905
+ def test_should_pick_main_when_its_5_hour_meter_is_null_and_its_week_has_room() -> None:
906
+ main = Reading(
907
+ _account("main", Product.CLAUDE, main=True),
908
+ Meters(None, None, 96.0, NOW + timedelta(days=5)),
909
+ )
910
+
911
+ decision = choose_from_readings(Product.CLAUDE, (main,), now=NOW)
912
+
913
+ assert decision.action == "run"
914
+ assert decision.account == main.account
915
+ assert decision.reason == "main has 96% left"
916
+
917
+
918
+ def test_should_wait_for_main_5_hour_reset_while_its_week_resets_days_away() -> None:
919
+ short_reset = NOW + timedelta(hours=2)
920
+ main = Reading(
921
+ _account("main", Product.CLAUDE, main=True),
922
+ _meters(5, 50, short_reset=short_reset, weekly_reset=NOW + timedelta(days=3)),
923
+ )
924
+
925
+ decision = choose_from_readings(Product.CLAUDE, (main,), now=NOW)
926
+
927
+ assert decision.action == "wait"
928
+ assert decision.resets_at == short_reset
929
+
930
+
931
+ def test_should_check_main_again_in_an_hour_when_a_blocking_window_has_no_reset() -> None:
932
+ main = Reading(
933
+ _account("main", Product.CLAUDE, main=True),
934
+ Meters(5, None, 1, NOW + timedelta(hours=4)),
935
+ )
936
+
937
+ decision = choose_from_readings(Product.CLAUDE, (main,), now=NOW)
938
+
939
+ assert decision.action == "wait"
940
+ assert decision.resets_at == NOW + timedelta(hours=1)
941
+
942
+
943
+ @pytest.mark.parametrize(
944
+ ("short_left", "weekly_left", "weekly_reset", "expected_reset"),
945
+ (
946
+ (5, 20, NOW + timedelta(hours=4), NOW + timedelta(hours=2)),
947
+ (80, 1, NOW + timedelta(hours=4), NOW + timedelta(hours=4)),
948
+ ),
949
+ )
950
+ def test_should_wait_for_the_meter_or_window_that_blocks_main(
951
+ short_left: float, weekly_left: float, weekly_reset: datetime, expected_reset: datetime
952
+ ) -> None:
953
+ main = Reading(
954
+ _account("main", Product.CLAUDE, main=True),
955
+ _meters(short_left, weekly_left, short_reset=NOW + timedelta(hours=2), weekly_reset=weekly_reset),
956
+ )
957
+
958
+ decision = choose_from_readings(Product.CLAUDE, (main,), now=NOW)
959
+
960
+ assert decision.action == "wait"
961
+ assert decision.resets_at == expected_reset
962
+
963
+
964
+ def test_should_try_next_account_after_usage_limit(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
965
+ accounts = (_account("first"), _account("second"))
966
+ adapter = _adapter(accounts, {"first": _meters(80, 80), "second": _meters(70, 70)})
967
+ attempted: list[str] = []
968
+
969
+ def runner(command: object, **options: object) -> subprocess.CompletedProcess[str]:
970
+ selected = Path(options["env"]["CODEX_HOME"]).name
971
+ attempted.append(selected)
972
+ if selected == "first":
973
+ return subprocess.CompletedProcess(command, 1, "", "rate limit")
974
+ return subprocess.CompletedProcess(command, 0, "served", "")
975
+
976
+ report_path = tmp_path / "report.json"
977
+ monkeypatch.setitem(account_broker.all_product_adapters, Product.CODEX, adapter)
978
+ with account_broker.override_subprocess_runner(runner):
979
+ outcome, report = account_broker._execute(
980
+ Product.CODEX,
981
+ ("job",),
982
+ now=NOW,
983
+ )
984
+ account_broker._write_report(report_path, report)
985
+
986
+ report = json.loads(report_path.read_text(encoding="utf-8"))
987
+ assert outcome.returncode == 0
988
+ assert attempted == ["first", "second"]
989
+ assert [event["type"] for event in report["events"]] == ["pick", "attempt", "pick", "attempt"]
990
+ assert report["final_decision"]["account"] == "second"
991
+
992
+
993
+ def test_should_wait_for_soonest_reset_and_exit_three(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
994
+ accounts = (_account("first"), _account("second"))
995
+ first_reset = NOW + timedelta(hours=5)
996
+ second_reset = NOW + timedelta(hours=3)
997
+ adapter = _adapter(
998
+ accounts,
999
+ {
1000
+ "first": _meters(0, 0, short_reset=first_reset, weekly_reset=first_reset),
1001
+ "second": _meters(0, 0, short_reset=second_reset, weekly_reset=second_reset),
1002
+ },
1003
+ )
1004
+
1005
+ report_path = tmp_path / "report.json"
1006
+ monkeypatch.setitem(account_broker.all_product_adapters, Product.CODEX, adapter)
1007
+ with account_broker.override_subprocess_runner(lambda command, **options: pytest.fail("a waiting job ran")):
1008
+ outcome, report = account_broker._execute(
1009
+ Product.CODEX,
1010
+ ("job",),
1011
+ now=NOW,
1012
+ )
1013
+ account_broker._write_report(report_path, report)
1014
+
1015
+ report = json.loads(report_path.read_text(encoding="utf-8"))
1016
+ assert outcome.returncode == WAIT_EXIT_CODE
1017
+ assert report["final_decision"]["action"] == "wait"
1018
+ assert report["final_decision"]["resets_at"] == second_reset.isoformat()
1019
+
1020
+
1021
+ def test_should_wait_until_both_blocking_windows_reset() -> None:
1022
+ short_reset = NOW + timedelta(hours=2)
1023
+ weekly_reset = NOW + timedelta(days=2)
1024
+ reading = Reading(
1025
+ _account("spent"),
1026
+ _meters(0, 0, short_reset=short_reset, weekly_reset=weekly_reset),
1027
+ )
1028
+
1029
+ decision = choose_from_readings(Product.CODEX, (reading,), now=NOW)
1030
+
1031
+ assert decision.resets_at == weekly_reset
1032
+
1033
+
1034
+ def test_should_use_claude_extra_floors_and_wait_for_unread() -> None:
1035
+ blocked = Reading(
1036
+ _account("blocked", Product.CLAUDE), _meters(5, 1)
1037
+ )
1038
+ unread = Reading(_account("unread", Product.CLAUDE), None)
1039
+
1040
+ decision = choose_from_readings(Product.CLAUDE, (blocked, unread), now=NOW)
1041
+
1042
+ assert decision.action == "wait"
1043
+ assert decision.account is None
1044
+
1045
+
1046
+ def _ranked_claude_account(name: str, priority: int | None) -> Account:
1047
+ return Account(Product.CLAUDE, name, Path("/profiles") / name, False, name, priority)
1048
+
1049
+
1050
+ def test_should_pick_the_first_claude_account_in_priority_order_with_room() -> None:
1051
+ readings = (
1052
+ Reading(_ranked_claude_account("roomy", 2), _meters(90, 90)),
1053
+ Reading(_ranked_claude_account("spent", 0), _meters(5, 90)),
1054
+ Reading(_ranked_claude_account("preferred", 1), _meters(20, 20)),
1055
+ Reading(_ranked_claude_account("unranked", None), _meters(99, 99)),
1056
+ )
1057
+
1058
+ decision = choose_from_readings(Product.CLAUDE, readings, now=NOW)
1059
+
1060
+ assert decision.account.name == "preferred"
1061
+ assert "priority 2" in decision.reason
1062
+
1063
+
1064
+ def test_should_fall_back_to_the_roomiest_unranked_claude_account() -> None:
1065
+ readings = (
1066
+ Reading(_ranked_claude_account("ranked_spent", 0), _meters(5, 5)),
1067
+ Reading(_ranked_claude_account("tight", None), _meters(30, 30)),
1068
+ Reading(_ranked_claude_account("roomy", None), _meters(60, 60)),
1069
+ )
1070
+
1071
+ decision = choose_from_readings(Product.CLAUDE, readings, now=NOW)
1072
+
1073
+ assert decision.account.name == "roomy"
1074
+
1075
+
1076
+ def test_should_keep_resume_affinity_ahead_of_priority() -> None:
1077
+ readings = (
1078
+ Reading(_ranked_claude_account("first", 0), _meters(90, 90)),
1079
+ Reading(_ranked_claude_account("bound", 1), _meters(40, 40)),
1080
+ )
1081
+
1082
+ decision = choose_from_readings(Product.CLAUDE, readings, now=NOW, preferred_command="bound")
1083
+
1084
+ assert decision.account.name == "bound"
1085
+ assert decision.reason == "resume affinity"
1086
+
1087
+
1088
+ def test_should_wait_when_every_ranked_claude_account_is_spent() -> None:
1089
+ readings = (
1090
+ Reading(_ranked_claude_account("first", 0), _meters(5, 5)),
1091
+ Reading(_ranked_claude_account("second", 1), _meters(0, 50)),
1092
+ )
1093
+
1094
+ decision = choose_from_readings(Product.CLAUDE, readings, now=NOW)
1095
+
1096
+ assert decision.action == "wait"
1097
+
1098
+
1099
+ @pytest.mark.parametrize("count", (1, 5))
1100
+ def test_should_consider_every_account_in_the_roster(count: int) -> None:
1101
+ readings = tuple(
1102
+ Reading(_account(f"account_{index}"), _meters(30 + index, 30 + index))
1103
+ for index in range(count)
1104
+ )
1105
+
1106
+ decision = choose_from_readings(Product.CODEX, readings, now=NOW)
1107
+
1108
+ assert decision.account == readings[-1].account
1109
+
1110
+
1111
+ def test_should_use_luna_floor_without_choosing_a_model() -> None:
1112
+ reading = Reading(_account("low"), _meters(30, 8))
1113
+
1114
+ decision = choose_from_readings(Product.CODEX, (reading,), now=NOW)
1115
+
1116
+ assert decision.account == reading.account
1117
+ assert decision.tier == "luna"
1118
+ assert not hasattr(decision, "model")
1119
+
1120
+
1121
+ def _disable_codex_weekly_floor(monkeypatch: pytest.MonkeyPatch) -> None:
1122
+ monkeypatch.setenv(codex_account_constants.CODEX_WEEKLY_FLOOR_DISABLED_ENVIRONMENT_VARIABLE, "1")
1123
+
1124
+
1125
+ def test_should_wait_when_the_only_account_is_at_the_weekly_floor() -> None:
1126
+ reading = Reading(_account("credits"), _meters(30, 0.5))
1127
+
1128
+ decision = choose_from_readings(Product.CODEX, (reading,), now=NOW)
1129
+
1130
+ assert decision.action == "wait"
1131
+ assert decision.resets_at == reading.meters.weekly_resets_at
1132
+
1133
+
1134
+ def test_should_choose_an_account_at_the_weekly_floor_when_the_floor_is_disabled(
1135
+ monkeypatch: pytest.MonkeyPatch,
1136
+ ) -> None:
1137
+ _disable_codex_weekly_floor(monkeypatch)
1138
+ reading = Reading(_account("credits"), _meters(30, 0.5))
1139
+
1140
+ decision = choose_from_readings(Product.CODEX, (reading,), now=NOW)
1141
+
1142
+ assert decision.action == "run"
1143
+ assert decision.account == reading.account
1144
+ assert decision.tier == "luna"
1145
+
1146
+
1147
+ def test_should_prefer_an_account_with_room_over_one_at_the_weekly_floor_when_the_floor_is_disabled(
1148
+ monkeypatch: pytest.MonkeyPatch,
1149
+ ) -> None:
1150
+ _disable_codex_weekly_floor(monkeypatch)
1151
+ readings = (
1152
+ Reading(_account("credits"), _meters(30, 0.5)),
1153
+ Reading(_account("roomy"), _meters(30, 8)),
1154
+ )
1155
+
1156
+ decision = choose_from_readings(Product.CODEX, readings, now=NOW)
1157
+
1158
+ assert decision.account == readings[1].account
1159
+ assert decision.tier == "luna"
1160
+
1161
+
1162
+ def test_should_still_wait_on_a_spent_session_when_the_weekly_floor_is_disabled(
1163
+ monkeypatch: pytest.MonkeyPatch,
1164
+ ) -> None:
1165
+ _disable_codex_weekly_floor(monkeypatch)
1166
+ reading = Reading(_account("credits"), _meters(0, 0.5))
1167
+
1168
+ decision = choose_from_readings(Product.CODEX, (reading,), now=NOW)
1169
+
1170
+ assert decision.action == "wait"
1171
+ assert decision.resets_at == reading.meters.session_resets_at
1172
+
1173
+
1174
+ def test_should_exit_zero_for_check_on_an_account_at_the_weekly_floor_when_the_floor_is_disabled(
1175
+ monkeypatch: pytest.MonkeyPatch,
1176
+ ) -> None:
1177
+ _disable_codex_weekly_floor(monkeypatch)
1178
+ account = _account("credits")
1179
+ monkeypatch.setitem(
1180
+ account_broker.all_product_adapters,
1181
+ Product.CODEX,
1182
+ _adapter((account,), {"credits": _meters(30, 0.5)}),
1183
+ )
1184
+
1185
+ assert account_broker.main(("check", "--product", "codex")) == 0
1186
+
1187
+
1188
+ def test_should_keep_resume_affinity_when_account_has_room() -> None:
1189
+ readings = (
1190
+ Reading(_account("roomy", Product.CLAUDE), _meters(80, 80)),
1191
+ Reading(_account("origin", Product.CLAUDE), _meters(20, 20)),
1192
+ )
1193
+
1194
+ decision = choose_from_readings(
1195
+ Product.CLAUDE, readings, now=NOW, preferred_command="origin"
1196
+ )
1197
+
1198
+ assert decision.account == readings[1].account
1199
+
1200
+
1201
+ def test_should_exit_three_for_check_while_all_accounts_wait(monkeypatch: pytest.MonkeyPatch) -> None:
1202
+ account = _account("spent")
1203
+ monkeypatch.setitem(
1204
+ account_broker.all_product_adapters,
1205
+ Product.CODEX,
1206
+ _adapter((account,), {"spent": _meters(0, 0)}),
1207
+ )
1208
+
1209
+ assert account_broker.main(("check", "--product", "codex")) == WAIT_EXIT_CODE
1210
+
1211
+
1212
+ def test_should_print_decision_and_meters_for_choose(
1213
+ monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
1214
+ ) -> None:
1215
+ account = _account("roomy")
1216
+ monkeypatch.setitem(
1217
+ account_broker.all_product_adapters,
1218
+ Product.CODEX,
1219
+ _adapter((account,), {"roomy": _meters(80, 70)}),
1220
+ )
1221
+
1222
+ assert account_broker.main(("choose", "--product", "codex")) == 0
1223
+ payload = json.loads(capsys.readouterr().out)
1224
+ assert payload["decision"]["account"] == "roomy"
1225
+ assert payload["decision"]["profile"] is None
1226
+ assert payload["accounts"][0]["meters"]["session_percent_left"] == 80
1227
+ assert payload["state_path"].endswith("state.json")
1228
+
1229
+
1230
+ def test_should_count_failed_meter_read_as_spent() -> None:
1231
+ readings = (
1232
+ Reading(_account("unread"), None),
1233
+ Reading(_account("roomy"), _meters(70, 70)),
1234
+ )
1235
+
1236
+ decision = choose_from_readings(Product.CODEX, readings, now=NOW)
1237
+
1238
+ assert decision.account == readings[1].account
1239
+
1240
+
1241
+ def test_should_serialize_readings_with_named_fields() -> None:
1242
+ reading = Reading(_account("one"), _meters(80, 70), measured_at=NOW)
1243
+
1244
+ payload = account_broker.readings_payload((reading,))
1245
+
1246
+ assert payload[0]["name"] == "one"
1247
+ assert payload[0]["meters"]["weekly_percent_left"] == 70
1248
+ assert payload[0]["measured_at"] == NOW.isoformat()
1249
+
1250
+
1251
+ def test_should_wait_until_the_rate_limit_probe_after_stale_meters_expire() -> None:
1252
+ reading = Reading(
1253
+ _account("one", Product.CLAUDE), None,
1254
+ "usage probe failed: HTTP Error 429", NOW - timedelta(minutes=25),
1255
+ NOW + timedelta(minutes=5),
1256
+ )
1257
+
1258
+ decision = choose_from_readings(Product.CLAUDE, (reading,), now=NOW)
1259
+
1260
+ assert decision.action == "wait"
1261
+ assert decision.resets_at == NOW + timedelta(minutes=5)
1262
+ assert decision.reason == (
1263
+ "no account meter could be read (one (usage probe failed: HTTP Error 429)); "
1264
+ "next check at 2026-10-03T00:05:00+00:00"
1265
+ )
1266
+
1267
+
1268
+ def test_should_wait_when_all_meter_reads_fail() -> None:
1269
+ readings = (Reading(_account("first"), None), Reading(_account("second"), None))
1270
+
1271
+ decision = choose_from_readings(Product.CODEX, readings, now=NOW)
1272
+
1273
+ assert decision.action == "wait"
1274
+ assert decision.resets_at == NOW + timedelta(hours=1)
1275
+
1276
+
1277
+ _MAIN_CLAUDE = _account("main", Product.CLAUDE, main=True)
1278
+ _EV_CLAUDE = _account("ev", Product.CLAUDE)
1279
+
1280
+
1281
+ @pytest.mark.parametrize(
1282
+ ("readings", "spent_resets", "expected_reason", "expected_resets_at"),
1283
+ (
1284
+ pytest.param(
1285
+ (Reading(_MAIN_CLAUDE, None), Reading(_EV_CLAUDE, None)),
1286
+ {},
1287
+ "no account meter could be read (main, ev); next check at 2026-10-03T01:00:00+00:00",
1288
+ NOW + timedelta(hours=1),
1289
+ id="every-meter-unreadable",
1290
+ ),
1291
+ pytest.param(
1292
+ (Reading(_MAIN_CLAUDE, _meters(5, 50, short_reset=NOW + timedelta(minutes=30))), Reading(_EV_CLAUDE, None)),
1293
+ {},
1294
+ "no readable account has room (main 5% left); meter unreadable for ev; next reset at 2026-10-03T00:30:00+00:00",
1295
+ NOW + timedelta(minutes=30),
1296
+ id="unreadable-beside-a-reset-before-the-check",
1297
+ ),
1298
+ pytest.param(
1299
+ (Reading(_MAIN_CLAUDE, _meters(5, 50, short_reset=NOW + timedelta(hours=2))), Reading(_EV_CLAUDE, None)),
1300
+ {},
1301
+ "no readable account has room (main 5% left); meter unreadable for ev; next check at 2026-10-03T01:00:00+00:00",
1302
+ NOW + timedelta(hours=1),
1303
+ id="unreadable-beside-a-reset-after-the-check",
1304
+ ),
1305
+ pytest.param(
1306
+ (Reading(_MAIN_CLAUDE, _meters(80, 80)), Reading(_EV_CLAUDE, None)),
1307
+ {_MAIN_CLAUDE: NOW + timedelta(minutes=30)},
1308
+ "no readable account has room (main spent); meter unreadable for ev; next reset at 2026-10-03T00:30:00+00:00",
1309
+ NOW + timedelta(minutes=30),
1310
+ id="unreadable-beside-a-spent-account",
1311
+ ),
1312
+ pytest.param(
1313
+ (
1314
+ Reading(_MAIN_CLAUDE, _meters(5, 50, short_reset=NOW + timedelta(hours=2))),
1315
+ Reading(_EV_CLAUDE, _meters(5, 80, short_reset=NOW + timedelta(hours=3))),
1316
+ ),
1317
+ {},
1318
+ "no account has room (main 5% left, ev 5% left); next reset at 2026-10-03T02:00:00+00:00",
1319
+ NOW + timedelta(hours=2),
1320
+ id="every-meter-read-with-known-resets",
1321
+ ),
1322
+ pytest.param(
1323
+ (Reading(_MAIN_CLAUDE, Meters(5, None, 50, None)),),
1324
+ {},
1325
+ "no account has room (main 5% left); next check at 2026-10-03T01:00:00+00:00",
1326
+ NOW + timedelta(hours=1),
1327
+ id="every-meter-read-without-a-known-reset",
1328
+ ),
1329
+ pytest.param(
1330
+ (),
1331
+ {},
1332
+ "no account has room; next check at 2026-10-03T01:00:00+00:00",
1333
+ NOW + timedelta(hours=1),
1334
+ id="no-account-in-the-roster",
1335
+ ),
1336
+ pytest.param(
1337
+ (Reading(_MAIN_CLAUDE, Meters(None, None, None, None)),),
1338
+ {},
1339
+ "no account has room (main percent left unread); next check at 2026-10-03T01:00:00+00:00",
1340
+ NOW + timedelta(hours=1),
1341
+ id="meter-read-without-a-percent",
1342
+ ),
1343
+ ),
1344
+ )
1345
+ def test_should_name_what_the_broker_knows_in_the_wait_reason(
1346
+ readings: tuple[Reading, ...],
1347
+ spent_resets: dict[Account, datetime],
1348
+ expected_reason: str,
1349
+ expected_resets_at: datetime,
1350
+ ) -> None:
1351
+ decision = choose_from_readings(
1352
+ Product.CLAUDE,
1353
+ readings,
1354
+ now=NOW,
1355
+ all_spent_accounts=frozenset(spent_resets),
1356
+ all_spent_resets=spent_resets,
1357
+ )
1358
+
1359
+ assert decision.action == "wait"
1360
+ assert decision.reason == expected_reason
1361
+ assert decision.resets_at == expected_resets_at
1362
+
1363
+
1364
+ def test_should_carry_the_unreadable_meter_reason_into_the_worker_report(
1365
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
1366
+ ) -> None:
1367
+ adapter = _adapter((_MAIN_CLAUDE, _EV_CLAUDE), {"main": None, "ev": None})
1368
+ monkeypatch.setitem(account_broker.all_product_adapters, Product.CLAUDE, adapter)
1369
+ prompt_file = tmp_path / "brief.md"
1370
+ prompt_file.write_text("standalone brief", encoding="utf-8")
1371
+ report_file = tmp_path / "report.json"
1372
+
1373
+ with account_broker.override_subprocess_runner(lambda command, **options: pytest.fail("a waiting job ran")):
1374
+ exit_code = claude_account_worker.run_worker(
1375
+ prompt_file=prompt_file,
1376
+ cwd=tmp_path,
1377
+ report_file=report_file,
1378
+ model=None,
1379
+ permission_mode="auto",
1380
+ timeout_minutes=60,
1381
+ )
1382
+
1383
+ report = json.loads(report_file.read_text(encoding="utf-8"))
1384
+ assert exit_code == WAIT_EXIT_CODE
1385
+ assert report["account"] == "wait"
1386
+ assert report["reason"].startswith("no account meter could be read")
1387
+
1388
+
1389
+ def test_should_replay_stdin_bytes_and_only_print_served_stdout(
1390
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str]
1391
+ ) -> None:
1392
+ accounts = (_account("first"), _account("second"))
1393
+ monkeypatch.setitem(account_broker.all_product_adapters, Product.CODEX, _adapter(accounts, {
1394
+ "first": _meters(80, 80), "second": _meters(70, 70)
1395
+ }))
1396
+ original = b"first\r\nsecond\x00\xff"
1397
+ received: list[bytes] = []
1398
+
1399
+ def runner(argv: object, **options: object) -> subprocess.CompletedProcess[str]:
1400
+ received.append(options["input"])
1401
+ if len(received) == 1:
1402
+ return subprocess.CompletedProcess(argv, 1, "discard this", "rate limit")
1403
+ return subprocess.CompletedProcess(argv, 0, "command output", "")
1404
+
1405
+ monkeypatch.setattr(account_broker.sys, "stdin", io.TextIOWrapper(io.BytesIO(original), encoding="utf-8"))
1406
+ report_path = tmp_path / "report.json"
1407
+ with account_broker.override_subprocess_runner(runner):
1408
+ code = account_broker.main(("run", "--product", "codex", "--report", str(report_path), "--", "job"))
1409
+
1410
+ captured_streams = capsys.readouterr()
1411
+ assert code == 0
1412
+ assert received == [original, original]
1413
+ assert captured_streams.out == "command output"
1414
+ assert json.loads(report_path.read_text(encoding="utf-8"))["final_decision"]["account"] == "second"
1415
+
1416
+
1417
+ def test_should_write_wait_report_without_stdout(
1418
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str]
1419
+ ) -> None:
1420
+ account = _account("spent")
1421
+ monkeypatch.setitem(account_broker.all_product_adapters, Product.CODEX, _adapter((account,), {"spent": _meters(0, 0)}))
1422
+ monkeypatch.setattr(account_broker.sys, "stdin", io.TextIOWrapper(io.BytesIO(b""), encoding="utf-8"))
1423
+ report_path = tmp_path / "report.json"
1424
+
1425
+ code = account_broker.main(("run", "--product", "codex", "--report", str(report_path), "--", "job"))
1426
+
1427
+ assert code == WAIT_EXIT_CODE
1428
+ assert capsys.readouterr().out == ""
1429
+ final = json.loads(report_path.read_text(encoding="utf-8"))["final_decision"]
1430
+ assert final["action"] == "wait"
1431
+ assert final["resets_at"] is not None
1432
+
1433
+
1434
+ def test_should_keep_spent_mark_until_reset(
1435
+ monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
1436
+ ) -> None:
1437
+ accounts = (_account("first"), _account("second"))
1438
+ monkeypatch.setitem(account_broker.all_product_adapters, Product.CODEX, _adapter(accounts, {
1439
+ "first": _meters(80, 80), "second": _meters(70, 70)
1440
+ }))
1441
+ reset = int((datetime.now(timezone.utc) + timedelta(hours=2)).timestamp())
1442
+
1443
+ assert account_broker.main(("choose", "--product", "codex", "--spent", f"first:{reset}")) == 0
1444
+ assert json.loads(capsys.readouterr().out)["decision"]["account"] == "second"
1445
+ assert account_broker.main(("choose", "--product", "codex")) == 0
1446
+ assert json.loads(capsys.readouterr().out)["decision"]["account"] == "second"
1447
+
1448
+
1449
+ def test_should_leave_later_choices_open_after_start_failure(
1450
+ monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
1451
+ ) -> None:
1452
+ accounts = (_account("first"), _account("second"))
1453
+ monkeypatch.setitem(account_broker.all_product_adapters, Product.CODEX, _adapter(accounts, {
1454
+ "first": _meters(80, 80), "second": _meters(70, 70)
1455
+ }))
1456
+
1457
+ def runner(argv: object, **options: object) -> subprocess.CompletedProcess[str]:
1458
+ raise OSError("missing command")
1459
+
1460
+ with account_broker.override_subprocess_runner(runner):
1461
+ outcome, _ = account_broker._execute(Product.CODEX, ("job",), now=datetime.now(timezone.utc))
1462
+
1463
+ assert outcome.attempts == (("first", "start_failed"), ("second", "start_failed"))
1464
+ assert account_broker.main(("choose", "--product", "codex")) == 0
1465
+ assert json.loads(capsys.readouterr().out)["decision"]["account"] == "first"
1466
+
1467
+
1468
+ @pytest.mark.parametrize("product", (Product.CLAUDE, Product.CODEX))
1469
+ def test_should_exit_127_when_every_account_fails_to_start(
1470
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, product: Product
1471
+ ) -> None:
1472
+ accounts = (_account("first", product), _account("second", product))
1473
+ monkeypatch.setitem(account_broker.all_product_adapters, product, _adapter(accounts, {
1474
+ "first": _meters(80, 80), "second": _meters(70, 70)
1475
+ }))
1476
+ monkeypatch.setattr(account_broker.sys, "stdin", io.TextIOWrapper(io.BytesIO(b""), encoding="utf-8"))
1477
+
1478
+ def runner(argv: object, **options: object) -> subprocess.CompletedProcess[str]:
1479
+ raise OSError("missing command")
1480
+
1481
+ with account_broker.override_subprocess_runner(runner):
1482
+ outcome, _ = account_broker._execute(product, ("job",), now=datetime.now(timezone.utc))
1483
+ code = account_broker.main(("run", "--product", product.value, "--report", str(tmp_path / "report.json"), "--", "job"))
1484
+
1485
+ assert outcome.status == "start_failed"
1486
+ assert outcome.returncode == 127
1487
+ assert outcome.wait_reset_at is None
1488
+ assert code == 127
1489
+
1490
+
1491
+ def test_should_report_exhausted_when_start_failure_meets_usage_limit(
1492
+ monkeypatch: pytest.MonkeyPatch,
1493
+ ) -> None:
1494
+ accounts = (_account("first"), _account("second"))
1495
+ monkeypatch.setitem(account_broker.all_product_adapters, Product.CODEX, _adapter(accounts, {
1496
+ "first": _meters(80, 80), "second": _meters(70, 70)
1497
+ }))
1498
+
1499
+ def runner(argv: object, **options: object) -> subprocess.CompletedProcess[str]:
1500
+ if Path(options["env"]["CODEX_HOME"]).name == "first":
1501
+ raise OSError("missing command")
1502
+ return subprocess.CompletedProcess(argv, 1, "", "rate limit")
1503
+
1504
+ with account_broker.override_subprocess_runner(runner):
1505
+ outcome, _ = account_broker._execute(Product.CODEX, ("job",), now=datetime.now(timezone.utc))
1506
+
1507
+ assert outcome.attempts == (("first", "start_failed"), ("second", "usage_limited"))
1508
+ assert outcome.status == "exhausted"
1509
+ assert outcome.returncode == 3
1510
+
1511
+
1512
+ def test_should_stop_after_timeout_without_running_job_again(
1513
+ monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
1514
+ ) -> None:
1515
+ accounts = (_account("first"), _account("second"))
1516
+ monkeypatch.setitem(account_broker.all_product_adapters, Product.CODEX, _adapter(accounts, {
1517
+ "first": _meters(80, 80), "second": _meters(70, 70)
1518
+ }))
1519
+ invoked_homes: list[str] = []
1520
+
1521
+ def runner(argv: object, **options: object) -> subprocess.CompletedProcess[str]:
1522
+ invoked_homes.append(Path(options["env"]["CODEX_HOME"]).name)
1523
+ raise subprocess.TimeoutExpired("job", 1)
1524
+
1525
+ with account_broker.override_subprocess_runner(runner):
1526
+ outcome, report = account_broker._execute(Product.CODEX, ("job",), now=datetime.now(timezone.utc))
1527
+
1528
+ assert invoked_homes == ["first"]
1529
+ assert outcome.attempts == (("first", "timeout"),)
1530
+ assert outcome.status == "timeout"
1531
+ assert outcome.returncode == 124
1532
+ assert outcome.account_name == "first"
1533
+ assert report.final_decision.account.name == "first"
1534
+ assert account_broker.main(("choose", "--product", "codex")) == 0
1535
+ assert json.loads(capsys.readouterr().out)["decision"]["account"] == "first"
1536
+
1537
+
1538
+ @pytest.mark.parametrize(
1539
+ ("product", "roster_names", "start_error", "expected_code"),
1540
+ (
1541
+ (Product.CLAUDE, ("first",), subprocess.TimeoutExpired("job", 1), 124),
1542
+ (Product.CODEX, ("first",), subprocess.TimeoutExpired("job", 1), 124),
1543
+ (Product.CODEX, (), OSError("missing command"), 127),
1544
+ ),
1545
+ )
1546
+ def test_should_exit_with_job_failure_code(
1547
+ monkeypatch: pytest.MonkeyPatch,
1548
+ tmp_path: Path,
1549
+ product: Product,
1550
+ roster_names: tuple[str, ...],
1551
+ start_error: Exception,
1552
+ expected_code: int,
1553
+ ) -> None:
1554
+ accounts = tuple(_account(each_name, product) for each_name in roster_names)
1555
+ monkeypatch.setitem(account_broker.all_product_adapters, product, _adapter(accounts, {
1556
+ each_name: _meters(80, 80) for each_name in (*roster_names, "default")
1557
+ }))
1558
+ monkeypatch.setattr(account_broker.sys, "stdin", io.TextIOWrapper(io.BytesIO(b""), encoding="utf-8"))
690
1559
 
691
- assert code == WAIT_EXIT_CODE
692
- assert capsys.readouterr().out == ""
693
- final = json.loads(report_path.read_text(encoding="utf-8"))["final_decision"]
694
- assert final["action"] == "wait"
695
- assert final["resets_at"] is not None
1560
+ def runner(argv: object, **options: object) -> subprocess.CompletedProcess[str]:
1561
+ raise start_error
1562
+
1563
+ with account_broker.override_subprocess_runner(runner):
1564
+ code = account_broker.main(("run", "--product", product.value, "--report", str(tmp_path / "report.json"), "--", "job"))
696
1565
 
1566
+ assert code == expected_code
697
1567
 
698
- def test_should_keep_spent_mark_until_reset(
1568
+
1569
+ def test_should_keep_usage_limited_account_spent_for_later_choices(
699
1570
  monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
700
1571
  ) -> None:
701
1572
  accounts = (_account("first"), _account("second"))
702
1573
  monkeypatch.setitem(account_broker.all_product_adapters, Product.CODEX, _adapter(accounts, {
703
1574
  "first": _meters(80, 80), "second": _meters(70, 70)
704
1575
  }))
705
- reset = int((datetime.now(timezone.utc) + timedelta(hours=2)).timestamp())
706
1576
 
707
- assert account_broker.main(("choose", "--product", "codex", "--spent", f"first:{reset}")) == 0
708
- assert json.loads(capsys.readouterr().out)["decision"]["account"] == "second"
709
- assert account_broker.main(("choose", "--product", "codex")) == 0
710
- assert json.loads(capsys.readouterr().out)["decision"]["account"] == "second"
1577
+ def runner(argv: object, **options: object) -> subprocess.CompletedProcess[str]:
1578
+ if Path(options["env"]["CODEX_HOME"]).name == "first":
1579
+ return subprocess.CompletedProcess(argv, 1, "", "rate limit")
1580
+ return subprocess.CompletedProcess(argv, 0, "served", "")
1581
+
1582
+ with account_broker.override_subprocess_runner(runner):
1583
+ account_broker._execute(Product.CODEX, ("job",), now=datetime.now(timezone.utc))
1584
+
1585
+ assert account_broker.main(("choose", "--product", "codex")) == 0
1586
+ assert json.loads(capsys.readouterr().out)["decision"]["account"] == "second"
1587
+
1588
+
1589
+ def test_should_not_retry_a_credit_account_that_reports_a_usage_limit_in_the_same_run(
1590
+ monkeypatch: pytest.MonkeyPatch,
1591
+ ) -> None:
1592
+ accounts = (_account("pro"), _account("team"))
1593
+ monkeypatch.setitem(account_broker.all_product_adapters, Product.CODEX, _adapter(accounts, {
1594
+ "pro": _meters(0, 0, plan_type=PRO_PLAN, credit_balance=CREDIT_BALANCE),
1595
+ "team": _meters(80, 80, plan_type=TEAM_PLAN),
1596
+ }))
1597
+ all_invoked_homes: list[str] = []
1598
+
1599
+ def runner(argv: object, **options: object) -> subprocess.CompletedProcess[str]:
1600
+ home_name = Path(options["env"]["CODEX_HOME"]).name
1601
+ all_invoked_homes.append(home_name)
1602
+ if len(all_invoked_homes) > 3:
1603
+ pytest.fail("the same run kept retrying a usage-limited account")
1604
+ if home_name == "pro":
1605
+ return subprocess.CompletedProcess(argv, 1, "", "rate limit")
1606
+ return subprocess.CompletedProcess(argv, 0, "served", "")
1607
+
1608
+ with account_broker.override_subprocess_runner(runner):
1609
+ outcome, _ = account_broker._execute(Product.CODEX, ("job",), now=NOW)
1610
+
1611
+ assert [each_name for each_name, _ in outcome.attempts] == ["pro", "team"]
1612
+ assert outcome.returncode == 0
1613
+
1614
+
1615
+ def test_should_list_accounts_without_reading_meters(
1616
+ monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
1617
+ ) -> None:
1618
+ account = _account("listed")
1619
+ adapter = ProductAdapter(lambda: (account,), lambda _: pytest.fail("meter read"), "CODEX_HOME", ())
1620
+ monkeypatch.setitem(account_broker.all_product_adapters, Product.CODEX, adapter)
1621
+
1622
+ assert account_broker.main(("accounts", "--product", "codex")) == 0
1623
+ assert json.loads(capsys.readouterr().out) == {
1624
+ "accounts": [{"name": "listed", "profile": None, "home": str(account.home), "is_main": False}]
1625
+ }
1626
+
1627
+
1628
+ def test_should_use_default_codex_home_without_roster(
1629
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
1630
+ ) -> None:
1631
+ monkeypatch.delenv("CODEX_ACCOUNT_PROFILES", raising=False)
1632
+ monkeypatch.setattr(account_broker.support.codex_account_choice, "default_profiles_root", lambda: tmp_path / "profiles")
1633
+ monkeypatch.setenv("CODEX_HOME", str(tmp_path / "default"))
1634
+
1635
+ assert account_broker.load_codex_accounts() == ()
1636
+ all_meters = {"default": _meters(40, 60, plan_type="pro")}
1637
+ monkeypatch.setitem(account_broker.all_product_adapters, Product.CODEX, _adapter((), all_meters))
1638
+ state = account_broker._load_state(account_broker.broker_state_path())
1639
+
1640
+ readings = account_broker.read_accounts(Product.CODEX, all_state=state, now=NOW)
1641
+
1642
+ decision = choose_from_readings(Product.CODEX, readings, now=NOW)
1643
+ assert decision.account.name == "default"
1644
+ assert decision.account.home == (tmp_path / "default").resolve()
1645
+ assert decision.reason == "default has 40% left"
1646
+
1647
+
1648
+ def _use_default_home_without_roster(
1649
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, default_meters: Meters | Exception
1650
+ ) -> tuple[Path, list[str]]:
1651
+ home = tmp_path / "default-home"
1652
+ monkeypatch.setenv("CODEX_HOME", str(home))
1653
+ monkeypatch.setattr(account_broker_support.time, "sleep", lambda _: None)
1654
+ all_read_names: list[str] = []
1655
+
1656
+ def read_meters(account: Account) -> Meters:
1657
+ all_read_names.append(account.name)
1658
+ if isinstance(default_meters, Exception):
1659
+ raise default_meters
1660
+ return default_meters
1661
+
1662
+ adapter = ProductAdapter(lambda: (), read_meters, "CODEX_HOME", ("rate limit",))
1663
+ monkeypatch.setitem(account_broker.all_product_adapters, Product.CODEX, adapter)
1664
+ _freeze_clock(monkeypatch, NOW)
1665
+ return home.resolve(), all_read_names
1666
+
1667
+
1668
+ def test_should_read_the_meters_of_the_default_home_when_no_roster_is_configured(
1669
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str]
1670
+ ) -> None:
1671
+ home, all_read_names = _use_default_home_without_roster(monkeypatch, tmp_path, _meters(40, 60, plan_type="pro"))
1672
+
1673
+ code = account_broker.main(("choose", "--product", "codex"))
1674
+
1675
+ payload = json.loads(capsys.readouterr().out)
1676
+ assert code == 0
1677
+ assert all_read_names == ["default"]
1678
+ assert payload["decision"]["account"] == "default"
1679
+ assert payload["decision"]["home"] == str(home)
1680
+ assert payload["decision"]["reason"] == "default has 40% left"
1681
+ assert payload["accounts"][0]["meters"]["plan_type"] == "pro"
1682
+
1683
+
1684
+ @pytest.mark.parametrize("blank_home", ("", " ", "\t"))
1685
+ def test_should_choose_the_home_directory_default_when_codex_home_is_blank_and_no_roster_is_configured(
1686
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str], blank_home: str
1687
+ ) -> None:
1688
+ _use_default_home_without_roster(monkeypatch, tmp_path, _meters(40, 60, plan_type="pro"))
1689
+ monkeypatch.setenv("CODEX_HOME", blank_home)
1690
+
1691
+ code = account_broker.main(("choose", "--product", "codex"))
1692
+
1693
+ decision = json.loads(capsys.readouterr().out)["decision"]
1694
+ assert code == 0
1695
+ assert decision["action"] == "run"
1696
+ assert decision["home"] == str((Path.home() / ".codex").resolve())
1697
+
1698
+
1699
+ @pytest.mark.parametrize(
1700
+ ("plan_type", "refusal"),
1701
+ (
1702
+ ("free", "default is on a free plan and is never chosen"),
1703
+ (None, "default reports no known plan and is never chosen"),
1704
+ ("unknown", "default reports no known plan and is never chosen"),
1705
+ ("free_works", "default reports no known plan and is never chosen"),
1706
+ ),
1707
+ )
1708
+ def test_should_wait_when_the_default_home_is_free_or_has_no_known_plan(
1709
+ monkeypatch: pytest.MonkeyPatch,
1710
+ tmp_path: Path,
1711
+ capsys: pytest.CaptureFixture[str],
1712
+ plan_type: str | None,
1713
+ refusal: str,
1714
+ ) -> None:
1715
+ _use_default_home_without_roster(monkeypatch, tmp_path, _meters(100, 100, plan_type=plan_type))
1716
+
1717
+ code = account_broker.main(("choose", "--product", "codex"))
1718
+
1719
+ decision = json.loads(capsys.readouterr().out)["decision"]
1720
+ assert code == WAIT_EXIT_CODE
1721
+ assert decision["action"] == "wait"
1722
+ assert decision["account"] is None
1723
+ assert decision["reason"] == f"no account has room ({refusal}); next check at 2026-10-03T01:00:00+00:00"
1724
+
1725
+
1726
+ def test_should_wait_and_name_the_failed_read_when_the_default_home_meters_cannot_be_read(
1727
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str]
1728
+ ) -> None:
1729
+ _use_default_home_without_roster(monkeypatch, tmp_path, OSError("codex app-server failed: timed out"))
1730
+
1731
+ code = account_broker.main(("choose", "--product", "codex"))
1732
+
1733
+ decision = json.loads(capsys.readouterr().out)["decision"]
1734
+ assert code == WAIT_EXIT_CODE
1735
+ assert decision["action"] == "wait"
1736
+ assert decision["reason"] == (
1737
+ "no account meter could be read (default (codex app-server failed: timed out)); "
1738
+ "next check at 2026-10-03T01:00:00+00:00"
1739
+ )
1740
+
1741
+
1742
+ def test_should_wait_when_the_default_home_has_no_reading() -> None:
1743
+ decision = choose_from_readings(Product.CODEX, (), now=NOW)
1744
+
1745
+ assert decision.action == "wait"
1746
+ assert decision.account is None
1747
+
1748
+
1749
+ def test_should_not_start_a_job_on_a_free_default_home(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
1750
+ _use_default_home_without_roster(monkeypatch, tmp_path, _meters(100, 100, plan_type=FREE_PLAN))
1751
+ all_invoked_homes: list[str] = []
1752
+
1753
+ def runner(argv: object, **options: object) -> subprocess.CompletedProcess[str]:
1754
+ all_invoked_homes.append(options["env"]["CODEX_HOME"])
1755
+ return subprocess.CompletedProcess(argv, 0, "served", "")
1756
+
1757
+ with account_broker.override_subprocess_runner(runner):
1758
+ outcome, _ = account_broker._execute(Product.CODEX, ("job",), now=NOW)
1759
+
1760
+ assert all_invoked_homes == []
1761
+ assert outcome.status == "wait"
1762
+ assert outcome.returncode == WAIT_EXIT_CODE
1763
+
1764
+
1765
+ @pytest.mark.parametrize("plan_type", UNRECOGNISED_PLANS)
1766
+ def test_should_not_start_a_job_on_a_default_home_on_an_unrecognised_plan(
1767
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, plan_type: str
1768
+ ) -> None:
1769
+ _use_default_home_without_roster(monkeypatch, tmp_path, _meters(100, 100, plan_type=plan_type))
1770
+ all_invoked_homes: list[str] = []
1771
+
1772
+ def runner(argv: object, **options: object) -> subprocess.CompletedProcess[str]:
1773
+ all_invoked_homes.append(options["env"]["CODEX_HOME"])
1774
+ return subprocess.CompletedProcess(argv, 0, "served", "")
1775
+
1776
+ with account_broker.override_subprocess_runner(runner):
1777
+ outcome, _ = account_broker._execute(Product.CODEX, ("job",), now=NOW)
1778
+
1779
+ assert all_invoked_homes == []
1780
+ assert outcome.status == "wait"
1781
+ assert outcome.returncode == WAIT_EXIT_CODE
1782
+
1783
+
1784
+ def _use_roster_beside_an_outside_home(
1785
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, outside_meters: Meters | Exception
1786
+ ) -> tuple[Path, list[str]]:
1787
+ outside_home = (tmp_path / "exported-home").resolve()
1788
+ roster = (_account("team"),)
1789
+ all_read_names: list[str] = []
1790
+
1791
+ def read_meters(account: Account) -> Meters:
1792
+ all_read_names.append(account.name)
1793
+ if account.name == "team":
1794
+ return _meters(90, 90, plan_type=TEAM_PLAN)
1795
+ if isinstance(outside_meters, Exception):
1796
+ raise outside_meters
1797
+ return outside_meters
1798
+
1799
+ monkeypatch.setattr(account_broker_support.time, "sleep", lambda _: None)
1800
+ monkeypatch.setitem(
1801
+ account_broker.all_product_adapters, Product.CODEX, ProductAdapter(lambda: roster, read_meters, "CODEX_HOME", ())
1802
+ )
1803
+ _freeze_clock(monkeypatch, NOW)
1804
+ return outside_home, all_read_names
1805
+
1806
+
1807
+ def test_should_judge_only_the_named_home_when_choose_gets_a_home(
1808
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str]
1809
+ ) -> None:
1810
+ outside_home, all_read_names = _use_roster_beside_an_outside_home(
1811
+ monkeypatch, tmp_path, _meters(None, 5, plan_type="pro")
1812
+ )
1813
+
1814
+ code = account_broker.main(("choose", "--product", "codex", "--home", str(outside_home)))
1815
+
1816
+ payload = json.loads(capsys.readouterr().out)
1817
+ assert code == 0
1818
+ assert all_read_names == ["exported-home"]
1819
+ assert payload["decision"]["action"] == "run"
1820
+ assert payload["decision"]["home"] == str(outside_home)
1821
+ assert payload["decision"]["tier"] == "luna"
1822
+ assert [each_entry["home"] for each_entry in payload["accounts"]] == [str(outside_home)]
1823
+
1824
+
1825
+ @pytest.mark.parametrize(
1826
+ ("plan_type", "refusal"),
1827
+ (
1828
+ ("free", "exported-home is on a free plan and is never chosen"),
1829
+ (None, "exported-home reports no known plan and is never chosen"),
1830
+ ("unknown", "exported-home reports no known plan and is never chosen"),
1831
+ ("free_works", "exported-home reports no known plan and is never chosen"),
1832
+ ),
1833
+ )
1834
+ def test_should_wait_when_the_named_home_is_free_or_has_no_known_plan(
1835
+ monkeypatch: pytest.MonkeyPatch,
1836
+ tmp_path: Path,
1837
+ capsys: pytest.CaptureFixture[str],
1838
+ plan_type: str | None,
1839
+ refusal: str,
1840
+ ) -> None:
1841
+ outside_home, _ = _use_roster_beside_an_outside_home(monkeypatch, tmp_path, _meters(100, 100, plan_type=plan_type))
1842
+
1843
+ code = account_broker.main(("choose", "--product", "codex", "--home", str(outside_home)))
1844
+
1845
+ decision = json.loads(capsys.readouterr().out)["decision"]
1846
+ assert code == WAIT_EXIT_CODE
1847
+ assert decision["action"] == "wait"
1848
+ assert decision["reason"] == f"no account has room ({refusal}); next check at 2026-10-03T01:00:00+00:00"
1849
+
1850
+
1851
+ def test_should_wait_when_the_meters_of_the_named_home_cannot_be_read(
1852
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str]
1853
+ ) -> None:
1854
+ outside_home, _ = _use_roster_beside_an_outside_home(monkeypatch, tmp_path, OSError("codex app-server failed: timed out"))
1855
+
1856
+ code = account_broker.main(("choose", "--product", "codex", "--home", str(outside_home)))
1857
+
1858
+ decision = json.loads(capsys.readouterr().out)["decision"]
1859
+ assert code == WAIT_EXIT_CODE
1860
+ assert decision["reason"] == (
1861
+ "no account meter could be read (exported-home (codex app-server failed: timed out)); "
1862
+ "next check at 2026-10-03T01:00:00+00:00"
1863
+ )
1864
+
1865
+
1866
+ def test_should_exit_three_for_check_when_the_named_home_is_free(
1867
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
1868
+ ) -> None:
1869
+ outside_home, _ = _use_roster_beside_an_outside_home(monkeypatch, tmp_path, _meters(100, 100, plan_type=FREE_PLAN))
1870
+
1871
+ assert account_broker.main(("check", "--product", "codex", "--home", str(outside_home))) == WAIT_EXIT_CODE
1872
+
1873
+
1874
+ @pytest.mark.parametrize("plan_type", UNRECOGNISED_PLANS)
1875
+ def test_should_exit_three_for_check_when_the_named_home_is_on_an_unrecognised_plan(
1876
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, plan_type: str
1877
+ ) -> None:
1878
+ outside_home, _ = _use_roster_beside_an_outside_home(monkeypatch, tmp_path, _meters(100, 100, plan_type=plan_type))
1879
+
1880
+ assert account_broker.main(("check", "--product", "codex", "--home", str(outside_home))) == WAIT_EXIT_CODE
1881
+
1882
+
1883
+ def test_should_not_let_the_floor_switch_or_credits_unlock_a_named_home_on_an_unrecognised_plan(
1884
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str]
1885
+ ) -> None:
1886
+ _disable_codex_weekly_floor(monkeypatch)
1887
+ outside_home, _ = _use_roster_beside_an_outside_home(
1888
+ monkeypatch, tmp_path, _meters(30, 0.5, plan_type="free_works", credit_balance=CREDIT_BALANCE, is_credits_unlimited=True)
1889
+ )
1890
+
1891
+ code = account_broker.main(("choose", "--product", "codex", "--home", str(outside_home)))
1892
+
1893
+ decision = json.loads(capsys.readouterr().out)["decision"]
1894
+ assert code == WAIT_EXIT_CODE
1895
+ assert decision["action"] == "wait"
1896
+ assert decision["account"] is None
1897
+
1898
+
1899
+ def test_should_run_a_named_team_home_at_half_a_percent_weekly_without_credits(
1900
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str]
1901
+ ) -> None:
1902
+ outside_home, _ = _use_roster_beside_an_outside_home(monkeypatch, tmp_path, _meters(80, 0.5, plan_type=TEAM_PLAN))
1903
+
1904
+ code = account_broker.main(("choose", "--product", "codex", "--home", str(outside_home)))
1905
+
1906
+ decision = json.loads(capsys.readouterr().out)["decision"]
1907
+ assert code == 0
1908
+ assert decision["action"] == "run"
1909
+ assert decision["home"] == str(outside_home)
1910
+ assert decision["tier"] == "luna"
1911
+ assert decision["reason"] == "exported-home is the named home and runs whatever room it has left"
1912
+
1913
+
1914
+ def test_should_run_a_named_pro_home_with_no_session_room(
1915
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str]
1916
+ ) -> None:
1917
+ outside_home, _ = _use_roster_beside_an_outside_home(monkeypatch, tmp_path, _meters(0, 70, plan_type="pro"))
1918
+
1919
+ code = account_broker.main(("choose", "--product", "codex", "--home", str(outside_home)))
1920
+
1921
+ decision = json.loads(capsys.readouterr().out)["decision"]
1922
+ assert code == 0
1923
+ assert decision["action"] == "run"
1924
+ assert decision["home"] == str(outside_home)
1925
+ assert decision["tier"] == "luna"
1926
+
1927
+
1928
+ @pytest.mark.parametrize("is_floor_switch_on", (False, True))
1929
+ def test_should_run_a_named_home_at_the_weekly_floor_whether_the_floor_switch_is_on_or_off(
1930
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str], is_floor_switch_on: bool
1931
+ ) -> None:
1932
+ if is_floor_switch_on:
1933
+ _disable_codex_weekly_floor(monkeypatch)
1934
+ outside_home, _ = _use_roster_beside_an_outside_home(monkeypatch, tmp_path, _meters(80, 0.5, plan_type=TEAM_PLAN))
1935
+
1936
+ code = account_broker.main(("choose", "--product", "codex", "--home", str(outside_home)))
1937
+
1938
+ decision = json.loads(capsys.readouterr().out)["decision"]
1939
+ assert code == 0
1940
+ assert decision["action"] == "run"
1941
+ assert decision["tier"] == "luna"
1942
+
1943
+
1944
+ @pytest.mark.parametrize(
1945
+ ("meters", "tier"),
1946
+ (
1947
+ (_meters(80, 50, plan_type=TEAM_PLAN), "normal"),
1948
+ (_meters(30, 8, plan_type=TEAM_PLAN), "luna"),
1949
+ (_meters(80, 0.5, plan_type=TEAM_PLAN, credit_balance=CREDIT_BALANCE), "normal"),
1950
+ (_meters(80, 0.5, plan_type=TEAM_PLAN), "luna"),
1951
+ (_meters(0, 0, plan_type="promax"), "luna"),
1952
+ ),
1953
+ )
1954
+ def test_should_name_the_tier_a_named_home_would_have_and_luna_when_none_fits(
1955
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str], meters: Meters, tier: str
1956
+ ) -> None:
1957
+ outside_home, _ = _use_roster_beside_an_outside_home(monkeypatch, tmp_path, meters)
1958
+
1959
+ code = account_broker.main(("choose", "--product", "codex", "--home", str(outside_home)))
1960
+
1961
+ decision = json.loads(capsys.readouterr().out)["decision"]
1962
+ assert code == 0
1963
+ assert decision["action"] == "run"
1964
+ assert decision["tier"] == tier
1965
+
1966
+
1967
+ def test_should_exit_zero_for_check_when_the_named_home_is_at_half_a_percent_weekly(
1968
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
1969
+ ) -> None:
1970
+ outside_home, _ = _use_roster_beside_an_outside_home(monkeypatch, tmp_path, _meters(80, 0.5, plan_type=TEAM_PLAN))
1971
+
1972
+ assert account_broker.main(("check", "--product", "codex", "--home", str(outside_home))) == 0
711
1973
 
712
1974
 
713
- def test_should_leave_later_choices_open_after_start_failure(
1975
+ def test_should_still_wait_on_a_roster_account_at_half_a_percent_weekly_when_no_home_is_named(
714
1976
  monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
715
1977
  ) -> None:
716
- accounts = (_account("first"), _account("second"))
717
- monkeypatch.setitem(account_broker.all_product_adapters, Product.CODEX, _adapter(accounts, {
718
- "first": _meters(80, 80), "second": _meters(70, 70)
719
- }))
720
-
721
- def runner(argv: object, **options: object) -> subprocess.CompletedProcess[str]:
722
- raise OSError("missing command")
1978
+ monkeypatch.setitem(
1979
+ account_broker.all_product_adapters,
1980
+ Product.CODEX,
1981
+ _adapter((_account("team"),), {"team": _meters(80, 0.5, plan_type=TEAM_PLAN)}),
1982
+ )
1983
+ _freeze_clock(monkeypatch, NOW)
723
1984
 
724
- with account_broker.override_subprocess_runner(runner):
725
- outcome, _ = account_broker._execute(Product.CODEX, ("job",), now=datetime.now(timezone.utc))
1985
+ code = account_broker.main(("choose", "--product", "codex"))
726
1986
 
727
- assert outcome.attempts == (("first", "start_failed"), ("second", "start_failed"))
728
- assert account_broker.main(("choose", "--product", "codex")) == 0
729
- assert json.loads(capsys.readouterr().out)["decision"]["account"] == "first"
1987
+ decision = json.loads(capsys.readouterr().out)["decision"]
1988
+ assert code == WAIT_EXIT_CODE
1989
+ assert decision["action"] == "wait"
1990
+ assert decision["account"] is None
730
1991
 
731
1992
 
732
- @pytest.mark.parametrize("product", (Product.CLAUDE, Product.CODEX))
733
- def test_should_exit_127_when_every_account_fails_to_start(
734
- monkeypatch: pytest.MonkeyPatch, tmp_path: Path, product: Product
1993
+ def test_should_exit_three_for_check_on_a_roster_account_at_half_a_percent_weekly_when_no_home_is_named(
1994
+ monkeypatch: pytest.MonkeyPatch,
735
1995
  ) -> None:
736
- accounts = (_account("first", product), _account("second", product))
737
- monkeypatch.setitem(account_broker.all_product_adapters, product, _adapter(accounts, {
738
- "first": _meters(80, 80), "second": _meters(70, 70)
739
- }))
740
- monkeypatch.setattr(account_broker.sys, "stdin", io.TextIOWrapper(io.BytesIO(b""), encoding="utf-8"))
1996
+ monkeypatch.setitem(
1997
+ account_broker.all_product_adapters,
1998
+ Product.CODEX,
1999
+ _adapter((_account("team"),), {"team": _meters(80, 0.5, plan_type=TEAM_PLAN)}),
2000
+ )
2001
+ _freeze_clock(monkeypatch, NOW)
741
2002
 
742
- def runner(argv: object, **options: object) -> subprocess.CompletedProcess[str]:
743
- raise OSError("missing command")
2003
+ assert account_broker.main(("check", "--product", "codex")) == WAIT_EXIT_CODE
744
2004
 
745
- with account_broker.override_subprocess_runner(runner):
746
- outcome, _ = account_broker._execute(product, ("job",), now=datetime.now(timezone.utc))
747
- code = account_broker.main(("run", "--product", product.value, "--report", str(tmp_path / "report.json"), "--", "job"))
748
2005
 
749
- assert outcome.status == "start_failed"
750
- assert outcome.returncode == 127
751
- assert outcome.wait_reset_at is None
752
- assert code == 127
2006
+ def test_should_wait_when_a_named_home_below_normal_meets_a_normal_requirement(
2007
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str]
2008
+ ) -> None:
2009
+ outside_home, _ = _use_roster_beside_an_outside_home(monkeypatch, tmp_path, _meters(80, 0.5, plan_type=TEAM_PLAN))
753
2010
 
2011
+ code = account_broker.main(("choose", "--product", "codex", "--home", str(outside_home), "--require-tier", "normal"))
754
2012
 
755
- def test_should_report_exhausted_when_start_failure_meets_usage_limit(
756
- monkeypatch: pytest.MonkeyPatch,
757
- ) -> None:
758
- accounts = (_account("first"), _account("second"))
759
- monkeypatch.setitem(account_broker.all_product_adapters, Product.CODEX, _adapter(accounts, {
760
- "first": _meters(80, 80), "second": _meters(70, 70)
761
- }))
2013
+ decision = json.loads(capsys.readouterr().out)["decision"]
2014
+ assert code == WAIT_EXIT_CODE
2015
+ assert decision["action"] == "wait"
762
2016
 
763
- def runner(argv: object, **options: object) -> subprocess.CompletedProcess[str]:
764
- if Path(options["env"]["CODEX_HOME"]).name == "first":
765
- raise OSError("missing command")
766
- return subprocess.CompletedProcess(argv, 1, "", "rate limit")
767
2017
 
768
- with account_broker.override_subprocess_runner(runner):
769
- outcome, _ = account_broker._execute(Product.CODEX, ("job",), now=datetime.now(timezone.utc))
2018
+ def test_should_wait_on_a_named_home_that_a_saved_spent_mark_still_covers(
2019
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str]
2020
+ ) -> None:
2021
+ outside_home, _ = _use_roster_beside_an_outside_home(monkeypatch, tmp_path, _meters(80, 80, plan_type="pro"))
2022
+ account_broker._save_state(
2023
+ account_broker.broker_state_path(),
2024
+ {
2025
+ "meters": {},
2026
+ "spent": {
2027
+ account_broker._state_key(Account(Product.CODEX, "exported-home", outside_home)): (NOW + timedelta(hours=3)).timestamp()
2028
+ },
2029
+ "affinity": {},
2030
+ },
2031
+ )
770
2032
 
771
- assert outcome.attempts == (("first", "start_failed"), ("second", "usage_limited"))
772
- assert outcome.status == "exhausted"
773
- assert outcome.returncode == 3
2033
+ code = account_broker.main(("choose", "--product", "codex", "--home", str(outside_home)))
2034
+
2035
+ decision = json.loads(capsys.readouterr().out)["decision"]
2036
+ assert code == WAIT_EXIT_CODE
2037
+ assert decision["action"] == "wait"
2038
+ assert decision["account"] is None
774
2039
 
775
2040
 
776
- def test_should_stop_after_timeout_without_running_job_again(
2041
+ def test_should_use_the_roster_account_when_the_named_home_is_a_roster_home(
777
2042
  monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
778
2043
  ) -> None:
779
- accounts = (_account("first"), _account("second"))
780
- monkeypatch.setitem(account_broker.all_product_adapters, Product.CODEX, _adapter(accounts, {
781
- "first": _meters(80, 80), "second": _meters(70, 70)
782
- }))
783
- invoked_homes: list[str] = []
2044
+ roster_account = _account("team")
2045
+ roster = (roster_account, _account("personal"))
2046
+ all_read_names: list[str] = []
784
2047
 
785
- def runner(argv: object, **options: object) -> subprocess.CompletedProcess[str]:
786
- invoked_homes.append(Path(options["env"]["CODEX_HOME"]).name)
787
- raise subprocess.TimeoutExpired("job", 1)
2048
+ def read_meters(account: Account) -> Meters:
2049
+ all_read_names.append(account.name)
2050
+ return _meters(80, 80, plan_type=TEAM_PLAN)
788
2051
 
789
- with account_broker.override_subprocess_runner(runner):
790
- outcome, report = account_broker._execute(Product.CODEX, ("job",), now=datetime.now(timezone.utc))
2052
+ monkeypatch.setitem(
2053
+ account_broker.all_product_adapters, Product.CODEX, ProductAdapter(lambda: roster, read_meters, "CODEX_HOME", ())
2054
+ )
791
2055
 
792
- assert invoked_homes == ["first"]
793
- assert outcome.attempts == (("first", "timeout"),)
794
- assert outcome.status == "timeout"
795
- assert outcome.returncode == 124
796
- assert outcome.account_name == "first"
797
- assert report.final_decision.account.name == "first"
798
- assert account_broker.main(("choose", "--product", "codex")) == 0
799
- assert json.loads(capsys.readouterr().out)["decision"]["account"] == "first"
2056
+ code = account_broker.main(("choose", "--product", "codex", "--home", str(roster_account.home)))
800
2057
 
2058
+ decision = json.loads(capsys.readouterr().out)["decision"]
2059
+ assert code == 0
2060
+ assert all_read_names == ["team"]
2061
+ assert decision["account"] == "team"
801
2062
 
802
- @pytest.mark.parametrize(
803
- ("product", "roster_names", "start_error", "expected_code"),
804
- (
805
- (Product.CLAUDE, ("first",), subprocess.TimeoutExpired("job", 1), 124),
806
- (Product.CODEX, ("first",), subprocess.TimeoutExpired("job", 1), 124),
807
- (Product.CODEX, (), OSError("missing command"), 127),
808
- ),
809
- )
810
- def test_should_exit_with_job_failure_code(
811
- monkeypatch: pytest.MonkeyPatch,
812
- tmp_path: Path,
813
- product: Product,
814
- roster_names: tuple[str, ...],
815
- start_error: Exception,
816
- expected_code: int,
817
- ) -> None:
818
- accounts = tuple(_account(each_name, product) for each_name in roster_names)
819
- monkeypatch.setitem(account_broker.all_product_adapters, product, _adapter(accounts, {
820
- each_name: _meters(80, 80) for each_name in roster_names
821
- }))
822
- monkeypatch.setattr(account_broker.sys, "stdin", io.TextIOWrapper(io.BytesIO(b""), encoding="utf-8"))
823
2063
 
824
- def runner(argv: object, **options: object) -> subprocess.CompletedProcess[str]:
825
- raise start_error
2064
+ def test_should_not_let_a_spent_roster_account_stop_the_named_home(
2065
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str]
2066
+ ) -> None:
2067
+ outside_home, _ = _use_roster_beside_an_outside_home(monkeypatch, tmp_path, _meters(80, 80, plan_type="pro"))
2068
+ account_broker._save_state(
2069
+ account_broker.broker_state_path(),
2070
+ {"meters": {}, "spent": {account_broker._state_key(_account("team")): (NOW + timedelta(hours=3)).timestamp()}, "affinity": {}},
2071
+ )
826
2072
 
827
- with account_broker.override_subprocess_runner(runner):
828
- code = account_broker.main(("run", "--product", product.value, "--report", str(tmp_path / "report.json"), "--", "job"))
2073
+ code = account_broker.main(("choose", "--product", "codex", "--home", str(outside_home)))
829
2074
 
830
- assert code == expected_code
2075
+ decision = json.loads(capsys.readouterr().out)["decision"]
2076
+ assert code == 0
2077
+ assert decision["action"] == "run"
2078
+ assert decision["tier"] == "normal"
831
2079
 
832
2080
 
833
- def test_should_keep_usage_limited_account_spent_for_later_choices(
834
- monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
2081
+ def test_should_refuse_a_home_beside_spent_marks(
2082
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str]
835
2083
  ) -> None:
836
- accounts = (_account("first"), _account("second"))
837
- monkeypatch.setitem(account_broker.all_product_adapters, Product.CODEX, _adapter(accounts, {
838
- "first": _meters(80, 80), "second": _meters(70, 70)
839
- }))
2084
+ outside_home, all_read_names = _use_roster_beside_an_outside_home(monkeypatch, tmp_path, _meters(80, 80, plan_type="pro"))
840
2085
 
841
- def runner(argv: object, **options: object) -> subprocess.CompletedProcess[str]:
842
- if Path(options["env"]["CODEX_HOME"]).name == "first":
843
- return subprocess.CompletedProcess(argv, 1, "", "rate limit")
844
- return subprocess.CompletedProcess(argv, 0, "served", "")
2086
+ code = account_broker.main(("choose", "--product", "codex", "--home", str(outside_home), "--spent", "team"))
845
2087
 
846
- with account_broker.override_subprocess_runner(runner):
847
- account_broker._execute(Product.CODEX, ("job",), now=datetime.now(timezone.utc))
2088
+ assert code == 2
2089
+ assert all_read_names == []
2090
+ assert "--home cannot be used with --spent" in capsys.readouterr().err
848
2091
 
849
- assert account_broker.main(("choose", "--product", "codex")) == 0
850
- assert json.loads(capsys.readouterr().out)["decision"]["account"] == "second"
851
2092
 
2093
+ def test_should_refuse_a_home_for_the_claude_product(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
2094
+ code = account_broker.main(("choose", "--product", "claude", "--home", str(tmp_path)))
852
2095
 
853
- def test_should_list_accounts_without_reading_meters(
854
- monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
855
- ) -> None:
856
- account = _account("listed")
857
- adapter = ProductAdapter(lambda: (account,), lambda _: pytest.fail("meter read"), "CODEX_HOME", ())
858
- monkeypatch.setitem(account_broker.all_product_adapters, Product.CODEX, adapter)
2096
+ assert code == 2
2097
+ assert "--home applies to the codex product only" in capsys.readouterr().err
859
2098
 
860
- assert account_broker.main(("accounts", "--product", "codex")) == 0
861
- assert json.loads(capsys.readouterr().out) == {
862
- "accounts": [{"name": "listed", "profile": None, "home": str(account.home), "is_main": False}]
863
- }
864
2099
 
2100
+ def test_should_start_a_job_on_a_paid_default_home_with_its_home_set(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
2101
+ home, _ = _use_default_home_without_roster(monkeypatch, tmp_path, _meters(40, 60, plan_type="pro"))
2102
+ all_invoked_homes: list[str] = []
865
2103
 
866
- def test_should_use_default_codex_home_without_roster(
867
- monkeypatch: pytest.MonkeyPatch, tmp_path: Path
868
- ) -> None:
869
- monkeypatch.delenv("CODEX_ACCOUNT_PROFILES", raising=False)
870
- monkeypatch.setattr(account_broker.support.codex_account_choice, "default_profiles_root", lambda: tmp_path / "profiles")
871
- monkeypatch.setenv("CODEX_HOME", str(tmp_path / "default"))
2104
+ def runner(argv: object, **options: object) -> subprocess.CompletedProcess[str]:
2105
+ all_invoked_homes.append(options["env"]["CODEX_HOME"])
2106
+ return subprocess.CompletedProcess(argv, 0, "served", "")
872
2107
 
873
- assert account_broker.load_codex_accounts() == ()
874
- decision = choose_from_readings(Product.CODEX, (), now=NOW)
875
- assert decision.account.name == "default"
876
- assert decision.account.home == (tmp_path / "default").resolve()
877
- assert "no roster" in decision.reason
2108
+ with account_broker.override_subprocess_runner(runner):
2109
+ outcome, _ = account_broker._execute(Product.CODEX, ("job",), now=NOW)
2110
+
2111
+ assert all_invoked_homes == [str(home)]
2112
+ assert outcome.status == "served"
878
2113
 
879
2114
 
880
2115
  def test_should_keep_the_codex_roster_for_a_process_without_the_roster_variable(
@@ -966,7 +2201,7 @@ def test_should_wait_for_spent_default_home_until_the_mark_passes(
966
2201
  monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str]
967
2202
  ) -> None:
968
2203
  home = tmp_path / "default-home"
969
- monkeypatch.setitem(account_broker.all_product_adapters, Product.CODEX, _adapter((), {}))
2204
+ monkeypatch.setitem(account_broker.all_product_adapters, Product.CODEX, _adapter((), {"default": _meters(80, 80)}))
970
2205
  monkeypatch.setenv("CODEX_HOME", str(home))
971
2206
  _freeze_clock(monkeypatch, NOW)
972
2207
  reset = NOW + timedelta(hours=2)
@@ -1271,7 +2506,7 @@ def test_should_warn_when_a_spent_mark_names_an_account_outside_the_roster(
1271
2506
  def test_should_not_warn_when_the_default_account_is_marked_without_a_roster(
1272
2507
  monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
1273
2508
  ) -> None:
1274
- monkeypatch.setitem(account_broker.all_product_adapters, Product.CODEX, _adapter((), {}))
2509
+ monkeypatch.setitem(account_broker.all_product_adapters, Product.CODEX, _adapter((), {"default": _meters(80, 80)}))
1275
2510
  _freeze_clock(monkeypatch, NOW)
1276
2511
  reset = NOW + timedelta(hours=2)
1277
2512
 
@@ -1288,7 +2523,7 @@ def test_should_warn_when_a_spent_mark_names_an_account_the_roster_lacks(
1288
2523
  monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], all_roster_names: tuple[str, ...], marked_name: str
1289
2524
  ) -> None:
1290
2525
  all_accounts = tuple(_account(each_name) for each_name in all_roster_names)
1291
- monkeypatch.setitem(account_broker.all_product_adapters, Product.CODEX, _adapter(all_accounts, {each_name: _meters(80, 80) for each_name in all_roster_names}))
2526
+ monkeypatch.setitem(account_broker.all_product_adapters, Product.CODEX, _adapter(all_accounts, {each_name: _meters(80, 80) for each_name in (*all_roster_names, "default")}))
1292
2527
  _freeze_clock(monkeypatch, NOW)
1293
2528
  reset = NOW + timedelta(hours=2)
1294
2529
 
@@ -1513,3 +2748,155 @@ def test_should_save_every_spent_mark_in_one_write(
1513
2748
 
1514
2749
  assert len(all_saved_marks) == 1
1515
2750
  assert len(all_saved_marks[0]) == 2
2751
+
2752
+
2753
+ def _claude_adapter(accounts: tuple[Account, ...], read_meters: Callable[[Account], Meters | None]) -> ProductAdapter:
2754
+ return ProductAdapter(
2755
+ load_accounts=lambda: accounts,
2756
+ read_meters=read_meters,
2757
+ environment_variable="CLAUDE_CONFIG_DIR",
2758
+ usage_limit_signatures=("rate limit",),
2759
+ )
2760
+
2761
+
2762
+ def _execute_claude(
2763
+ monkeypatch: pytest.MonkeyPatch,
2764
+ accounts: tuple[Account, ...],
2765
+ read_meters: Callable[[Account], Meters | None],
2766
+ completions_by_name: dict[str, tuple[int, str, str]],
2767
+ attempted: list[str],
2768
+ ) -> tuple[account_broker.JobOutcome, account_broker.Report]:
2769
+ def runner(command: object, **options: object) -> subprocess.CompletedProcess[str]:
2770
+ selected = Path(options["env"]["CLAUDE_CONFIG_DIR"]).name
2771
+ attempted.append(selected)
2772
+ returncode, stdout, stderr = completions_by_name[selected]
2773
+ return subprocess.CompletedProcess(command, returncode, stdout, stderr)
2774
+
2775
+ monkeypatch.setitem(account_broker.all_product_adapters, Product.CLAUDE, _claude_adapter(accounts, read_meters))
2776
+ with account_broker.override_subprocess_runner(runner):
2777
+ return account_broker._execute(Product.CLAUDE, ("job",), now=NOW)
2778
+
2779
+
2780
+ def test_should_skip_an_account_whose_sign_in_fails_and_run_the_next_account(monkeypatch: pytest.MonkeyPatch) -> None:
2781
+ accounts = (_account("first", Product.CLAUDE), _account("second", Product.CLAUDE))
2782
+ meters_by_name = {"first": _meters(90, 90), "second": _meters(70, 70)}
2783
+ attempted: list[str] = []
2784
+
2785
+ outcome, report = _execute_claude(
2786
+ monkeypatch,
2787
+ accounts,
2788
+ lambda account: meters_by_name[account.name],
2789
+ {"first": (1, "", "Stored token expired"), "second": (0, "served", "")},
2790
+ attempted,
2791
+ )
2792
+
2793
+ assert outcome.returncode == 0
2794
+ assert attempted == ["first", "second"]
2795
+ assert "skipped first: Stored token expired" in outcome.stderr
2796
+ assert any(
2797
+ each_event.get("type") == "sign_in_failure" and each_event.get("account") == "first"
2798
+ for each_event in report.events
2799
+ )
2800
+
2801
+
2802
+ def test_should_exit_four_and_name_each_account_when_every_sign_in_fails(monkeypatch: pytest.MonkeyPatch) -> None:
2803
+ accounts = (_account("first", Product.CLAUDE), _account("second", Product.CLAUDE))
2804
+ meters_by_name = {"first": _meters(90, 90), "second": _meters(70, 70)}
2805
+ attempted: list[str] = []
2806
+
2807
+ outcome, _ = _execute_claude(
2808
+ monkeypatch,
2809
+ accounts,
2810
+ lambda account: meters_by_name[account.name],
2811
+ {
2812
+ "first": (1, "", "Organization has status: canceled"),
2813
+ "second": (1, "", "Stored token expired"),
2814
+ },
2815
+ attempted,
2816
+ )
2817
+
2818
+ assert outcome.returncode == 4
2819
+ assert outcome.status == "no_usable_account"
2820
+ assert attempted == ["first", "second"]
2821
+ assert "first: Organization has status: canceled" in outcome.stderr
2822
+ assert "second: Stored token expired" in outcome.stderr
2823
+
2824
+
2825
+ def test_should_exit_four_when_a_signed_out_account_and_a_failed_sign_in_leave_no_usable_account(
2826
+ monkeypatch: pytest.MonkeyPatch,
2827
+ ) -> None:
2828
+ accounts = (_account("first", Product.CLAUDE), _account("second", Product.CLAUDE))
2829
+ signed_out_path = Path("/profiles/second/.credentials.json")
2830
+ attempted: list[str] = []
2831
+
2832
+ def read_meters(account: Account) -> Meters | None:
2833
+ if account.name == "second":
2834
+ raise account_broker_support.ClaudeSignedOutError(
2835
+ NO_ACCESS_TOKEN_ERROR_TEMPLATE.format(credentials_path=signed_out_path)
2836
+ )
2837
+ return _meters(90, 90)
2838
+
2839
+ outcome, _ = _execute_claude(
2840
+ monkeypatch,
2841
+ accounts,
2842
+ read_meters,
2843
+ {"first": (1, "", "stored token expired")},
2844
+ attempted,
2845
+ )
2846
+
2847
+ assert outcome.returncode == 4
2848
+ assert attempted == ["first"]
2849
+ assert "second: " + NO_ACCESS_TOKEN_ERROR_TEMPLATE.format(credentials_path=signed_out_path) in outcome.stderr
2850
+
2851
+
2852
+ def test_should_wait_with_exit_three_when_a_failed_sign_in_leaves_a_usage_limited_account(
2853
+ monkeypatch: pytest.MonkeyPatch,
2854
+ ) -> None:
2855
+ accounts = (_account("first", Product.CLAUDE), _account("second", Product.CLAUDE))
2856
+ meters_by_name = {"first": _meters(90, 90), "second": _meters(70, 70)}
2857
+ attempted: list[str] = []
2858
+
2859
+ outcome, _ = _execute_claude(
2860
+ monkeypatch,
2861
+ accounts,
2862
+ lambda account: meters_by_name[account.name],
2863
+ {"first": (1, "", "Stored token expired"), "second": (1, "", "rate limit")},
2864
+ attempted,
2865
+ )
2866
+
2867
+ assert outcome.returncode == WAIT_EXIT_CODE
2868
+ assert attempted == ["first", "second"]
2869
+
2870
+
2871
+ def test_should_not_skip_an_account_when_only_stdout_quotes_a_sign_in_message(monkeypatch: pytest.MonkeyPatch) -> None:
2872
+ accounts = (_account("first", Product.CLAUDE), _account("second", Product.CLAUDE))
2873
+ meters_by_name = {"first": _meters(90, 90), "second": _meters(70, 70)}
2874
+ attempted: list[str] = []
2875
+
2876
+ outcome, _ = _execute_claude(
2877
+ monkeypatch,
2878
+ accounts,
2879
+ lambda account: meters_by_name[account.name],
2880
+ {"first": (1, "stored token expired", ""), "second": (0, "served", "")},
2881
+ attempted,
2882
+ )
2883
+
2884
+ assert outcome.returncode == 1
2885
+ assert attempted == ["first"]
2886
+
2887
+
2888
+ def test_should_stop_on_a_failure_that_is_not_a_sign_in(monkeypatch: pytest.MonkeyPatch) -> None:
2889
+ accounts = (_account("first", Product.CLAUDE), _account("second", Product.CLAUDE))
2890
+ meters_by_name = {"first": _meters(90, 90), "second": _meters(70, 70)}
2891
+ attempted: list[str] = []
2892
+
2893
+ outcome, _ = _execute_claude(
2894
+ monkeypatch,
2895
+ accounts,
2896
+ lambda account: meters_by_name[account.name],
2897
+ {"first": (1, "", "boom"), "second": (0, "served", "")},
2898
+ attempted,
2899
+ )
2900
+
2901
+ assert outcome.returncode == 1
2902
+ assert attempted == ["first"]