claude-dev-env 8.111.5 → 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 (50) 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 +5 -3
  21. package/docs/codex-accounts.md +57 -16
  22. package/docs/rule-guides/question-presentation.md +4 -0
  23. package/hooks/blocking/final_reply_gate.py +59 -3
  24. package/hooks/blocking/open_tasks_transcript.py +18 -0
  25. package/hooks/blocking/test_final_reply_gate.py +160 -0
  26. package/hooks/features/conduct-gates.md +1 -4
  27. package/hooks/hooks.json +0 -10
  28. package/hooks/hooks_constants/final_reply_gate_constants.py +16 -0
  29. package/hooks/hooks_constants/open_tasks_stop_gate_constants.py +9 -0
  30. package/package.json +1 -1
  31. package/rules/question-presentation.md +1 -1
  32. package/scripts/account_broker.py +50 -25
  33. package/scripts/account_broker_support.py +54 -3
  34. package/scripts/codex_account_choice.py +12 -8
  35. package/scripts/codex_account_chooser.py +110 -0
  36. package/scripts/codex_account_meters.py +43 -4
  37. package/scripts/codex_plan_rules.py +156 -0
  38. package/scripts/dev_env_scripts_constants/account_broker_constants.py +29 -42
  39. package/scripts/dev_env_scripts_constants/codex_account_constants.py +62 -2
  40. package/scripts/dev_env_scripts_constants/test_account_broker_constants.py +359 -2
  41. package/scripts/dev_env_scripts_constants/test_codex_account_constants.py +213 -14
  42. package/scripts/policy_lint/adapter_configuration.py +0 -5
  43. package/scripts/policy_lint/config/constants.py +0 -1
  44. package/scripts/test_account_broker.py +1756 -523
  45. package/scripts/test_account_broker_support.py +77 -0
  46. package/scripts/test_codex_account_meters.py +95 -0
  47. package/scripts/tests/test_adapter_configuration.py +0 -8
  48. package/hooks/blocking/merge_over_review_offer_gate.py +0 -114
  49. package/hooks/blocking/test_merge_over_review_offer_gate.py +0 -138
  50. package/hooks/hooks_constants/merge_over_review_offer_gate_constants.py +0 -34
@@ -22,11 +22,13 @@ from account_broker import (
22
22
  choose_from_readings,
23
23
  run_job,
24
24
  )
25
+ from dev_env_scripts_constants import codex_account_constants
25
26
  from dev_env_scripts_constants.account_broker_constants import WAIT_EXIT_CODE
26
27
  from dev_env_scripts_constants.claude_chain_usage_constants import NO_ACCESS_TOKEN_ERROR_TEMPLATE
27
28
 
28
29
 
29
30
  NOW = datetime(2026, 10, 3, tzinfo=timezone.utc)
31
+ DEFAULT_PLAN = "team"
30
32
 
31
33
 
32
34
  class _FrozenClock(datetime):
@@ -54,7 +56,9 @@ def _meters(
54
56
  *,
55
57
  short_reset: datetime | None = None,
56
58
  weekly_reset: datetime | None = None,
57
- plan_type: str | None = None,
59
+ plan_type: str | None = DEFAULT_PLAN,
60
+ credit_balance: float | None = None,
61
+ is_credits_unlimited: bool = False,
58
62
  ) -> Meters:
59
63
  return Meters(
60
64
  short_left,
@@ -62,6 +66,9 @@ def _meters(
62
66
  weekly_left,
63
67
  weekly_reset or NOW + timedelta(days=3),
64
68
  plan_type,
69
+ credit_balance is not None,
70
+ is_credits_unlimited,
71
+ credit_balance,
65
72
  )
66
73
 
67
74
 
@@ -135,7 +142,7 @@ def test_should_pick_a_pro_plan_account_over_a_roomier_team_account() -> None:
135
142
  assert decision.tier == "normal"
136
143
 
137
144
 
138
- 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:
139
146
  readings = (
140
147
  Reading(_account("personal"), _meters(50, 8, plan_type="pro")),
141
148
  Reading(_account("team-jon"), _meters(40, 30, plan_type="team")),
@@ -143,740 +150,1966 @@ def test_should_pick_a_team_account_in_the_normal_tier_over_a_pro_plan_account_b
143
150
 
144
151
  decision = choose_from_readings(Product.CODEX, readings, now=NOW)
145
152
 
146
- assert decision.account == readings[1].account
147
- assert decision.tier == "normal"
148
-
149
-
150
- def test_should_keep_list_order_when_tighter_windows_tie() -> None:
151
- readings = (
152
- Reading(_account("first"), _meters(40, 60)),
153
- Reading(_account("second"), _meters(70, 40)),
154
- )
155
-
156
- decision = choose_from_readings(Product.CODEX, readings, now=NOW)
157
-
158
153
  assert decision.account == readings[0].account
154
+ assert decision.tier == "luna"
159
155
 
160
156
 
161
- @pytest.mark.parametrize(
162
- ("weekly_reset", "weekly_left", "short_left"),
163
- (
164
- (NOW + timedelta(hours=4), 1, 80),
165
- (NOW + timedelta(hours=4), 20, 5),
166
- ),
167
- )
168
- def test_should_guard_main_at_each_limit(
169
- weekly_reset: datetime, weekly_left: float, short_left: float
170
- ) -> None:
171
- main = Reading(
172
- _account("main", Product.CLAUDE, main=True),
173
- _meters(short_left, weekly_left, weekly_reset=weekly_reset),
174
- )
175
- extra = Reading(_account("extra", Product.CLAUDE), _meters(20, 20))
176
-
177
- decision = choose_from_readings(Product.CLAUDE, (main, extra), now=NOW)
178
-
179
- assert decision.account == extra.account
157
+ FREE_PLAN = "free"
158
+ TEAM_PLAN = "team"
159
+ PRO_PLAN = "prolite"
160
+ CREDIT_BALANCE = 83600.8856485
180
161
 
181
162
 
182
- def test_should_pick_main_when_it_has_more_room_than_every_extra() -> None:
183
- main = Reading(
184
- _account("main", Product.CLAUDE, main=True),
185
- _meters(80, 80, weekly_reset=NOW + timedelta(days=5)),
186
- )
187
- extras = (
188
- Reading(_account("second", Product.CLAUDE), _meters(60, 60)),
189
- 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)),
190
169
  )
191
170
 
192
- decision = choose_from_readings(Product.CLAUDE, (*extras, main), now=NOW)
193
-
194
- assert decision.action == "run"
195
- assert decision.account == main.account
196
171
 
172
+ def test_should_choose_the_pro_account_with_credits_over_free_and_team_accounts_with_more_room() -> None:
173
+ readings = _current_roster()
197
174
 
198
- def test_should_pick_an_extra_with_more_room_than_main() -> None:
199
- main = Reading(
200
- _account("main", Product.CLAUDE, main=True),
201
- _meters(60, 60, weekly_reset=NOW + timedelta(hours=4)),
202
- )
203
- extra = Reading(_account("extra", Product.CLAUDE), _meters(90, 90))
204
-
205
- decision = choose_from_readings(Product.CLAUDE, (main, extra), now=NOW)
175
+ decision = choose_from_readings(Product.CODEX, readings, now=NOW)
206
176
 
207
- 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"
208
181
 
209
182
 
210
- @pytest.mark.parametrize(("main_short_left", "expected_name"), ((6, "main"), (5, "extra")))
211
- def test_should_pick_main_only_while_under_its_5_hour_ceiling(
212
- main_short_left: float, expected_name: str
213
- ) -> None:
214
- main = Reading(
215
- _account("main", Product.CLAUDE, main=True),
216
- _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)),
217
188
  )
218
- extra = Reading(_account("extra", Product.CLAUDE), _meters(20, 2))
219
-
220
- decision = choose_from_readings(Product.CLAUDE, (main, extra), now=NOW)
221
-
222
- assert decision.account.name == expected_name
223
-
224
189
 
225
- def test_should_pick_main_when_it_is_the_only_readable_account() -> None:
226
- main = Reading(
227
- _account("main", Product.CLAUDE, main=True),
228
- _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)},
229
196
  )
230
- unread = Reading(_account("extra", Product.CLAUDE), None)
231
-
232
- decision = choose_from_readings(Product.CLAUDE, (unread, main), now=NOW)
233
197
 
234
198
  assert decision.action == "run"
235
- assert decision.account == main.account
199
+ assert decision.account == pro_account
200
+ assert decision.tier == "normal"
236
201
 
237
202
 
238
- def test_should_pick_main_when_its_5_hour_meter_is_null_and_its_week_has_room() -> None:
239
- main = Reading(
240
- _account("main", Product.CLAUDE, main=True),
241
- 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)),
242
208
  )
243
209
 
244
- 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
+ )
245
217
 
246
218
  assert decision.action == "run"
247
- assert decision.account == main.account
248
- assert decision.reason == "main has 96% left"
219
+ assert decision.account == readings[0].account
249
220
 
250
221
 
251
- def test_should_wait_for_main_5_hour_reset_while_its_week_resets_days_away() -> None:
252
- short_reset = NOW + timedelta(hours=2)
253
- main = Reading(
254
- _account("main", Product.CLAUDE, main=True),
255
- _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),
256
231
  )
257
232
 
258
- decision = choose_from_readings(Product.CLAUDE, (main,), now=NOW)
233
+ exit_code = account_broker.main(("choose", "--product", "codex"))
259
234
 
260
- assert decision.action == "wait"
261
- 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
262
243
 
263
244
 
264
- def test_should_check_main_again_in_an_hour_when_a_blocking_window_has_no_reset() -> None:
265
- main = Reading(
266
- _account("main", Product.CLAUDE, main=True),
267
- 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)),
268
249
  )
269
250
 
270
- decision = choose_from_readings(Product.CLAUDE, (main,), now=NOW)
251
+ decision = choose_from_readings(Product.CODEX, readings, now=NOW)
271
252
 
272
- assert decision.action == "wait"
273
- assert decision.resets_at == NOW + timedelta(hours=1)
253
+ assert decision.account == readings[1].account
254
+ assert decision.tier == "luna"
274
255
 
275
256
 
276
257
  @pytest.mark.parametrize(
277
- ("short_left", "weekly_left", "weekly_reset", "expected_reset"),
278
- (
279
- (5, 20, NOW + timedelta(hours=4), NOW + timedelta(hours=2)),
280
- (80, 1, NOW + timedelta(hours=4), NOW + timedelta(hours=4)),
281
- ),
258
+ ("credit_balance", "is_credits_unlimited"), ((None, False), (CREDIT_BALANCE, False), (None, True))
282
259
  )
283
- def test_should_wait_for_the_meter_or_window_that_blocks_main(
284
- 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
285
262
  ) -> None:
286
- main = Reading(
287
- _account("main", Product.CLAUDE, main=True),
288
- _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),
289
266
  )
290
267
 
291
- decision = choose_from_readings(Product.CLAUDE, (main,), now=NOW)
268
+ decision = choose_from_readings(Product.CODEX, (reading,), now=NOW)
292
269
 
293
270
  assert decision.action == "wait"
294
- assert decision.resets_at == expected_reset
295
-
296
-
297
- def test_should_try_next_account_after_usage_limit(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
298
- accounts = (_account("first"), _account("second"))
299
- adapter = _adapter(accounts, {"first": _meters(80, 80), "second": _meters(70, 70)})
300
- 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
+ )
301
275
 
302
- def runner(command: object, **options: object) -> subprocess.CompletedProcess[str]:
303
- selected = Path(options["env"]["CODEX_HOME"]).name
304
- attempted.append(selected)
305
- if selected == "first":
306
- return subprocess.CompletedProcess(command, 1, "", "rate limit")
307
- return subprocess.CompletedProcess(command, 0, "served", "")
308
276
 
309
- report_path = tmp_path / "report.json"
310
- monkeypatch.setitem(account_broker.all_product_adapters, Product.CODEX, adapter)
311
- with account_broker.override_subprocess_runner(runner):
312
- 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,
313
281
  Product.CODEX,
314
- ("job",),
315
- now=NOW,
316
- )
317
- account_broker._write_report(report_path, report)
282
+ _adapter((account,), {"editor": _meters(100, 100, plan_type=FREE_PLAN)}),
283
+ )
318
284
 
319
- report = json.loads(report_path.read_text(encoding="utf-8"))
320
- assert outcome.returncode == 0
321
- assert attempted == ["first", "second"]
322
- assert [event["type"] for event in report["events"]] == ["pick", "attempt", "pick", "attempt"]
323
- assert report["final_decision"]["account"] == "second"
285
+ assert account_broker.main(("check", "--product", "codex")) == WAIT_EXIT_CODE
324
286
 
325
287
 
326
- def test_should_wait_for_soonest_reset_and_exit_three(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
327
- accounts = (_account("first"), _account("second"))
328
- first_reset = NOW + timedelta(hours=5)
329
- second_reset = NOW + timedelta(hours=3)
330
- adapter = _adapter(
331
- accounts,
332
- {
333
- "first": _meters(0, 0, short_reset=first_reset, weekly_reset=first_reset),
334
- "second": _meters(0, 0, short_reset=second_reset, weekly_reset=second_reset),
335
- },
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)}),
336
294
  )
295
+ all_invoked_homes: list[str] = []
337
296
 
338
- report_path = tmp_path / "report.json"
339
- monkeypatch.setitem(account_broker.all_product_adapters, Product.CODEX, adapter)
340
- with account_broker.override_subprocess_runner(lambda command, **options: pytest.fail("a waiting job ran")):
341
- outcome, report = account_broker._execute(
342
- Product.CODEX,
343
- ("job",),
344
- now=NOW,
345
- )
346
- 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", "")
347
300
 
348
- 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"
349
306
  assert outcome.returncode == WAIT_EXIT_CODE
350
- assert report["final_decision"]["action"] == "wait"
351
- assert report["final_decision"]["resets_at"] == second_reset.isoformat()
352
307
 
353
308
 
354
- def test_should_wait_until_both_blocking_windows_reset() -> None:
355
- short_reset = NOW + timedelta(hours=2)
356
- weekly_reset = NOW + timedelta(days=2)
357
- reading = Reading(
358
- _account("spent"),
359
- _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")),
360
313
  )
361
314
 
362
- decision = choose_from_readings(Product.CODEX, (reading,), now=NOW)
363
315
 
364
- 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()
365
318
 
319
+ decision = choose_from_readings(Product.CODEX, readings, now=NOW)
366
320
 
367
- def test_should_use_claude_extra_floors_and_wait_for_unread() -> None:
368
- blocked = Reading(
369
- _account("blocked", Product.CLAUDE), _meters(5, 1)
370
- )
371
- unread = Reading(_account("unread", Product.CLAUDE), None)
321
+ assert decision.account == readings[1].account
322
+ assert decision.tier == "luna"
372
323
 
373
- decision = choose_from_readings(Product.CLAUDE, (blocked, unread), now=NOW)
374
324
 
375
- assert decision.action == "wait"
376
- 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()
377
327
 
328
+ decision = choose_from_readings(Product.CODEX, readings, now=NOW, required_tier="normal")
378
329
 
379
- def _ranked_claude_account(name: str, priority: int | None) -> Account:
380
- 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"
381
333
 
382
334
 
383
- 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:
384
336
  readings = (
385
- Reading(_ranked_claude_account("roomy", 2), _meters(90, 90)),
386
- Reading(_ranked_claude_account("spent", 0), _meters(5, 90)),
387
- Reading(_ranked_claude_account("preferred", 1), _meters(20, 20)),
388
- 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")),
389
339
  )
390
340
 
391
- decision = choose_from_readings(Product.CLAUDE, readings, now=NOW)
341
+ decision = choose_from_readings(Product.CODEX, readings, now=NOW, required_tier="normal")
392
342
 
393
- assert decision.account.name == "preferred"
394
- assert "priority 2" in decision.reason
343
+ assert decision.account == readings[1].account
344
+ assert decision.tier == "normal"
395
345
 
396
346
 
397
- 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:
398
348
  readings = (
399
- Reading(_ranked_claude_account("ranked_spent", 0), _meters(5, 5)),
400
- Reading(_ranked_claude_account("tight", None), _meters(30, 30)),
401
- 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)),
402
351
  )
403
352
 
404
- decision = choose_from_readings(Product.CLAUDE, readings, now=NOW)
353
+ decision = choose_from_readings(Product.CODEX, readings, now=NOW, required_tier="normal")
405
354
 
406
- assert decision.account.name == "roomy"
355
+ assert decision.account == readings[1].account
356
+ assert decision.tier == "normal"
407
357
 
408
358
 
409
- 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:
410
360
  readings = (
411
- Reading(_ranked_claude_account("first", 0), _meters(90, 90)),
412
- 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")),
413
363
  )
414
364
 
415
- 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")
416
366
 
417
- assert decision.account.name == "bound"
418
- assert decision.reason == "resume affinity"
367
+ assert decision.action == "wait"
368
+ assert decision.account is None
369
+ assert decision.tier == "wait"
419
370
 
420
371
 
421
- 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:
422
373
  readings = (
423
- Reading(_ranked_claude_account("first", 0), _meters(5, 5)),
424
- 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)),
425
376
  )
426
377
 
427
- decision = choose_from_readings(Product.CLAUDE, readings, now=NOW)
378
+ decision = choose_from_readings(Product.CODEX, readings, now=NOW, required_tier="normal")
428
379
 
429
380
  assert decision.action == "wait"
430
381
 
431
382
 
432
- @pytest.mark.parametrize("count", (1, 5))
433
- def test_should_consider_every_account_in_the_roster(count: int) -> None:
434
- readings = tuple(
435
- Reading(_account(f"account_{index}"), _meters(30 + index, 30 + index))
436
- for index in range(count)
437
- )
438
-
439
- decision = choose_from_readings(Product.CODEX, readings, now=NOW)
440
-
441
- assert decision.account == readings[-1].account
442
-
443
-
444
- def test_should_use_luna_floor_without_choosing_a_model() -> None:
445
- reading = Reading(_account("low"), _meters(30, 8))
446
-
447
- decision = choose_from_readings(Product.CODEX, (reading,), now=NOW)
448
-
449
- assert decision.account == reading.account
450
- assert decision.tier == "luna"
451
- assert not hasattr(decision, "model")
452
-
453
-
454
- 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:
455
384
  readings = (
456
- Reading(_account("roomy", Product.CLAUDE), _meters(80, 80)),
457
- 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)),
458
387
  )
459
388
 
460
- decision = choose_from_readings(
461
- Product.CLAUDE, readings, now=NOW, preferred_command="origin"
462
- )
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")
463
391
 
464
- assert decision.account == readings[1].account
392
+ assert with_requirement == without_requirement
465
393
 
466
394
 
467
- def test_should_exit_three_for_check_while_all_accounts_wait(monkeypatch: pytest.MonkeyPatch) -> None:
468
- 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}
469
400
  monkeypatch.setitem(
470
401
  account_broker.all_product_adapters,
471
402
  Product.CODEX,
472
- _adapter((account,), {"spent": _meters(0, 0)}),
403
+ _adapter(tuple(each_reading.account for each_reading in readings), all_meters),
473
404
  )
474
405
 
475
- 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"]
476
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")
477
413
 
478
- 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(
479
416
  monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
480
417
  ) -> None:
481
- account = _account("roomy")
418
+ account = _account("personal")
482
419
  monkeypatch.setitem(
483
420
  account_broker.all_product_adapters,
484
421
  Product.CODEX,
485
- _adapter((account,), {"roomy": _meters(80, 70)}),
422
+ _adapter((account,), {"personal": _meters(None, 5, plan_type="pro")}),
486
423
  )
487
424
 
488
- assert account_broker.main(("choose", "--product", "codex")) == 0
489
- payload = json.loads(capsys.readouterr().out)
490
- assert payload["decision"]["account"] == "roomy"
491
- assert payload["decision"]["profile"] is None
492
- assert payload["accounts"][0]["meters"]["session_percent_left"] == 80
493
- 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"
494
431
 
495
432
 
496
- 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:
497
447
  readings = (
498
- Reading(_account("unread"), None),
499
- 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)),
500
450
  )
501
451
 
502
452
  decision = choose_from_readings(Product.CODEX, readings, now=NOW)
503
453
 
504
454
  assert decision.account == readings[1].account
455
+ assert decision.tier == "luna"
505
456
 
506
457
 
507
- def test_should_serialize_readings_with_named_fields() -> None:
508
- 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
+ )
509
468
 
510
- payload = account_broker.readings_payload((reading,))
469
+ decision = choose_from_readings(Product.CODEX, (reading,), now=NOW)
511
470
 
512
- assert payload[0]["name"] == "one"
513
- assert payload[0]["meters"]["weekly_percent_left"] == 70
514
- 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
+ )
515
477
 
516
478
 
517
- def test_should_wait_until_the_rate_limit_probe_after_stale_meters_expire() -> None:
518
- reading = Reading(
519
- _account("one", Product.CLAUDE), None,
520
- "usage probe failed: HTTP Error 429", NOW - timedelta(minutes=25),
521
- 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)),
522
483
  )
523
484
 
524
- decision = choose_from_readings(Product.CLAUDE, (reading,), now=NOW)
485
+ decision = choose_from_readings(Product.CODEX, readings, now=NOW)
525
486
 
526
487
  assert decision.action == "wait"
527
- assert decision.resets_at == NOW + timedelta(minutes=5)
528
488
  assert decision.reason == (
529
- "no account meter could be read (one (usage probe failed: HTTP Error 429)); "
530
- "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"
531
491
  )
532
492
 
533
493
 
534
- def test_should_wait_when_all_meter_reads_fail() -> None:
535
- 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
+ )
536
510
 
537
511
  decision = choose_from_readings(Product.CODEX, readings, now=NOW)
538
512
 
539
513
  assert decision.action == "wait"
540
- 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
+ )
541
518
 
542
519
 
543
- _MAIN_CLAUDE = _account("main", Product.CLAUDE, main=True)
544
- _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"
545
535
 
546
536
 
537
+ @pytest.mark.parametrize("plan_type", UNRECOGNISED_PLANS)
547
538
  @pytest.mark.parametrize(
548
- ("readings", "spent_resets", "expected_reason", "expected_resets_at"),
549
- (
550
- pytest.param(
551
- (Reading(_MAIN_CLAUDE, None), Reading(_EV_CLAUDE, None)),
552
- {},
553
- "no account meter could be read (main, ev); next check at 2026-10-03T01:00:00+00:00",
554
- NOW + timedelta(hours=1),
555
- id="every-meter-unreadable",
556
- ),
557
- pytest.param(
558
- (Reading(_MAIN_CLAUDE, _meters(5, 50, short_reset=NOW + timedelta(minutes=30))), Reading(_EV_CLAUDE, None)),
559
- {},
560
- "no readable account has room (main 5% left); meter unreadable for ev; next reset at 2026-10-03T00:30:00+00:00",
561
- NOW + timedelta(minutes=30),
562
- id="unreadable-beside-a-reset-before-the-check",
563
- ),
564
- pytest.param(
565
- (Reading(_MAIN_CLAUDE, _meters(5, 50, short_reset=NOW + timedelta(hours=2))), Reading(_EV_CLAUDE, None)),
566
- {},
567
- "no readable account has room (main 5% left); meter unreadable for ev; next check at 2026-10-03T01:00:00+00:00",
568
- NOW + timedelta(hours=1),
569
- id="unreadable-beside-a-reset-after-the-check",
570
- ),
571
- pytest.param(
572
- (Reading(_MAIN_CLAUDE, _meters(80, 80)), Reading(_EV_CLAUDE, None)),
573
- {_MAIN_CLAUDE: NOW + timedelta(minutes=30)},
574
- "no readable account has room (main spent); meter unreadable for ev; next reset at 2026-10-03T00:30:00+00:00",
575
- NOW + timedelta(minutes=30),
576
- id="unreadable-beside-a-spent-account",
577
- ),
578
- pytest.param(
579
- (
580
- Reading(_MAIN_CLAUDE, _meters(5, 50, short_reset=NOW + timedelta(hours=2))),
581
- Reading(_EV_CLAUDE, _meters(5, 80, short_reset=NOW + timedelta(hours=3))),
582
- ),
583
- {},
584
- "no account has room (main 5% left, ev 5% left); next reset at 2026-10-03T02:00:00+00:00",
585
- NOW + timedelta(hours=2),
586
- id="every-meter-read-with-known-resets",
587
- ),
588
- pytest.param(
589
- (Reading(_MAIN_CLAUDE, Meters(5, None, 50, None)),),
590
- {},
591
- "no account has room (main 5% left); next check at 2026-10-03T01:00:00+00:00",
592
- NOW + timedelta(hours=1),
593
- id="every-meter-read-without-a-known-reset",
594
- ),
595
- pytest.param(
596
- (),
597
- {},
598
- "no account has room; next check at 2026-10-03T01:00:00+00:00",
599
- NOW + timedelta(hours=1),
600
- id="no-account-in-the-roster",
601
- ),
602
- pytest.param(
603
- (Reading(_MAIN_CLAUDE, Meters(None, None, None, None)),),
604
- {},
605
- "no account has room (main percent left unread); next check at 2026-10-03T01:00:00+00:00",
606
- NOW + timedelta(hours=1),
607
- id="meter-read-without-a-percent",
608
- ),
609
- ),
539
+ ("credit_balance", "is_credits_unlimited"), ((None, False), (CREDIT_BALANCE, False), (None, True))
610
540
  )
611
- def test_should_name_what_the_broker_knows_in_the_wait_reason(
612
- readings: tuple[Reading, ...],
613
- spent_resets: dict[Account, datetime],
614
- expected_reason: str,
615
- 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
616
543
  ) -> None:
617
- decision = choose_from_readings(
618
- Product.CLAUDE,
619
- readings,
620
- now=NOW,
621
- all_spent_accounts=frozenset(spent_resets),
622
- 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),
623
547
  )
624
548
 
549
+ decision = choose_from_readings(Product.CODEX, (reading,), now=NOW)
550
+
625
551
  assert decision.action == "wait"
626
- assert decision.reason == expected_reason
627
- 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
+ )
628
557
 
629
558
 
630
- def test_should_carry_the_unreadable_meter_reason_into_the_worker_report(
631
- 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
632
562
  ) -> None:
633
- adapter = _adapter((_MAIN_CLAUDE, _EV_CLAUDE), {"main": None, "ev": None})
634
- monkeypatch.setitem(account_broker.all_product_adapters, Product.CLAUDE, adapter)
635
- prompt_file = tmp_path / "brief.md"
636
- prompt_file.write_text("standalone brief", encoding="utf-8")
637
- 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))
638
565
 
639
- with account_broker.override_subprocess_runner(lambda command, **options: pytest.fail("a waiting job ran")):
640
- exit_code = claude_account_worker.run_worker(
641
- prompt_file=prompt_file,
642
- cwd=tmp_path,
643
- report_file=report_file,
644
- model=None,
645
- permission_mode="auto",
646
- timeout_minutes=60,
647
- )
566
+ decision = choose_from_readings(Product.CODEX, (reading,), now=NOW)
648
567
 
649
- report = json.loads(report_file.read_text(encoding="utf-8"))
650
- assert exit_code == WAIT_EXIT_CODE
651
- assert report["account"] == "wait"
652
- assert report["reason"].startswith("no account meter could be read")
568
+ assert decision.action == "wait"
569
+ assert decision.account is None
653
570
 
654
571
 
655
- def test_should_replay_stdin_bytes_and_only_print_served_stdout(
656
- 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
657
575
  ) -> None:
658
- accounts = (_account("first"), _account("second"))
659
- monkeypatch.setitem(account_broker.all_product_adapters, Product.CODEX, _adapter(accounts, {
660
- "first": _meters(80, 80), "second": _meters(70, 70)
661
- }))
662
- original = b"first\r\nsecond\x00\xff"
663
- 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] = []
664
597
 
665
598
  def runner(argv: object, **options: object) -> subprocess.CompletedProcess[str]:
666
- received.append(options["input"])
667
- if len(received) == 1:
668
- return subprocess.CompletedProcess(argv, 1, "discard this", "rate limit")
669
- 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", "")
670
601
 
671
- monkeypatch.setattr(account_broker.sys, "stdin", io.TextIOWrapper(io.BytesIO(original), encoding="utf-8"))
672
- report_path = tmp_path / "report.json"
673
602
  with account_broker.override_subprocess_runner(runner):
674
- code = account_broker.main(("run", "--product", "codex", "--report", str(report_path), "--", "job"))
603
+ outcome, _ = account_broker._execute(Product.CODEX, ("job",), now=NOW)
675
604
 
676
- captured_streams = capsys.readouterr()
677
- assert code == 0
678
- assert received == [original, original]
679
- assert captured_streams.out == "command output"
680
- 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
681
608
 
682
609
 
683
- def test_should_write_wait_report_without_stdout(
684
- monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str]
685
- ) -> None:
686
- account = _account("spent")
687
- monkeypatch.setitem(account_broker.all_product_adapters, Product.CODEX, _adapter((account,), {"spent": _meters(0, 0)}))
688
- monkeypatch.setattr(account_broker.sys, "stdin", io.TextIOWrapper(io.BytesIO(b""), encoding="utf-8"))
689
- 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))
690
613
 
691
- 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"))
1559
+
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"))
1565
+
1566
+ assert code == expected_code
1567
+
1568
+
1569
+ def test_should_keep_usage_limited_account_spent_for_later_choices(
1570
+ monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
1571
+ ) -> None:
1572
+ accounts = (_account("first"), _account("second"))
1573
+ monkeypatch.setitem(account_broker.all_product_adapters, Product.CODEX, _adapter(accounts, {
1574
+ "first": _meters(80, 80), "second": _meters(70, 70)
1575
+ }))
1576
+
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)))
692
1844
 
1845
+ decision = json.loads(capsys.readouterr().out)["decision"]
693
1846
  assert code == WAIT_EXIT_CODE
694
- assert capsys.readouterr().out == ""
695
- final = json.loads(report_path.read_text(encoding="utf-8"))["final_decision"]
696
- assert final["action"] == "wait"
697
- assert final["resets_at"] is not None
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"
698
1849
 
699
1850
 
700
- def test_should_keep_spent_mark_until_reset(
701
- monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
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]
702
1853
  ) -> None:
703
- accounts = (_account("first"), _account("second"))
704
- monkeypatch.setitem(account_broker.all_product_adapters, Product.CODEX, _adapter(accounts, {
705
- "first": _meters(80, 80), "second": _meters(70, 70)
706
- }))
707
- reset = int((datetime.now(timezone.utc) + timedelta(hours=2)).timestamp())
1854
+ outside_home, _ = _use_roster_beside_an_outside_home(monkeypatch, tmp_path, OSError("codex app-server failed: timed out"))
708
1855
 
709
- assert account_broker.main(("choose", "--product", "codex", "--spent", f"first:{reset}")) == 0
710
- assert json.loads(capsys.readouterr().out)["decision"]["account"] == "second"
711
- assert account_broker.main(("choose", "--product", "codex")) == 0
712
- assert json.loads(capsys.readouterr().out)["decision"]["account"] == "second"
1856
+ code = account_broker.main(("choose", "--product", "codex", "--home", str(outside_home)))
713
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
+ )
714
1864
 
715
- def test_should_leave_later_choices_open_after_start_failure(
716
- monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
1865
+
1866
+ def test_should_exit_three_for_check_when_the_named_home_is_free(
1867
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
717
1868
  ) -> None:
718
- accounts = (_account("first"), _account("second"))
719
- monkeypatch.setitem(account_broker.all_product_adapters, Product.CODEX, _adapter(accounts, {
720
- "first": _meters(80, 80), "second": _meters(70, 70)
721
- }))
1869
+ outside_home, _ = _use_roster_beside_an_outside_home(monkeypatch, tmp_path, _meters(100, 100, plan_type=FREE_PLAN))
722
1870
 
723
- def runner(argv: object, **options: object) -> subprocess.CompletedProcess[str]:
724
- raise OSError("missing command")
1871
+ assert account_broker.main(("check", "--product", "codex", "--home", str(outside_home))) == WAIT_EXIT_CODE
725
1872
 
726
- with account_broker.override_subprocess_runner(runner):
727
- outcome, _ = account_broker._execute(Product.CODEX, ("job",), now=datetime.now(timezone.utc))
728
1873
 
729
- assert outcome.attempts == (("first", "start_failed"), ("second", "start_failed"))
730
- assert account_broker.main(("choose", "--product", "codex")) == 0
731
- assert json.loads(capsys.readouterr().out)["decision"]["account"] == "first"
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))
732
1879
 
1880
+ assert account_broker.main(("check", "--product", "codex", "--home", str(outside_home))) == WAIT_EXIT_CODE
733
1881
 
734
- @pytest.mark.parametrize("product", (Product.CLAUDE, Product.CODEX))
735
- def test_should_exit_127_when_every_account_fails_to_start(
736
- monkeypatch: pytest.MonkeyPatch, tmp_path: Path, product: Product
737
- ) -> None:
738
- accounts = (_account("first", product), _account("second", product))
739
- monkeypatch.setitem(account_broker.all_product_adapters, product, _adapter(accounts, {
740
- "first": _meters(80, 80), "second": _meters(70, 70)
741
- }))
742
- monkeypatch.setattr(account_broker.sys, "stdin", io.TextIOWrapper(io.BytesIO(b""), encoding="utf-8"))
743
1882
 
744
- def runner(argv: object, **options: object) -> subprocess.CompletedProcess[str]:
745
- raise OSError("missing command")
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
+ )
746
1890
 
747
- with account_broker.override_subprocess_runner(runner):
748
- outcome, _ = account_broker._execute(product, ("job",), now=datetime.now(timezone.utc))
749
- code = account_broker.main(("run", "--product", product.value, "--report", str(tmp_path / "report.json"), "--", "job"))
1891
+ code = account_broker.main(("choose", "--product", "codex", "--home", str(outside_home)))
750
1892
 
751
- assert outcome.status == "start_failed"
752
- assert outcome.returncode == 127
753
- assert outcome.wait_reset_at is None
754
- assert code == 127
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
755
1897
 
756
1898
 
757
- def test_should_report_exhausted_when_start_failure_meets_usage_limit(
758
- monkeypatch: pytest.MonkeyPatch,
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]
759
1901
  ) -> None:
760
- accounts = (_account("first"), _account("second"))
761
- monkeypatch.setitem(account_broker.all_product_adapters, Product.CODEX, _adapter(accounts, {
762
- "first": _meters(80, 80), "second": _meters(70, 70)
763
- }))
764
-
765
- def runner(argv: object, **options: object) -> subprocess.CompletedProcess[str]:
766
- if Path(options["env"]["CODEX_HOME"]).name == "first":
767
- raise OSError("missing command")
768
- return subprocess.CompletedProcess(argv, 1, "", "rate limit")
1902
+ outside_home, _ = _use_roster_beside_an_outside_home(monkeypatch, tmp_path, _meters(80, 0.5, plan_type=TEAM_PLAN))
769
1903
 
770
- with account_broker.override_subprocess_runner(runner):
771
- outcome, _ = account_broker._execute(Product.CODEX, ("job",), now=datetime.now(timezone.utc))
1904
+ code = account_broker.main(("choose", "--product", "codex", "--home", str(outside_home)))
772
1905
 
773
- assert outcome.attempts == (("first", "start_failed"), ("second", "usage_limited"))
774
- assert outcome.status == "exhausted"
775
- assert outcome.returncode == 3
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"
776
1912
 
777
1913
 
778
- def test_should_stop_after_timeout_without_running_job_again(
779
- monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
1914
+ def test_should_run_a_named_pro_home_with_no_session_room(
1915
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str]
780
1916
  ) -> None:
781
- accounts = (_account("first"), _account("second"))
782
- monkeypatch.setitem(account_broker.all_product_adapters, Product.CODEX, _adapter(accounts, {
783
- "first": _meters(80, 80), "second": _meters(70, 70)
784
- }))
785
- invoked_homes: list[str] = []
1917
+ outside_home, _ = _use_roster_beside_an_outside_home(monkeypatch, tmp_path, _meters(0, 70, plan_type="pro"))
786
1918
 
787
- def runner(argv: object, **options: object) -> subprocess.CompletedProcess[str]:
788
- invoked_homes.append(Path(options["env"]["CODEX_HOME"]).name)
789
- raise subprocess.TimeoutExpired("job", 1)
1919
+ code = account_broker.main(("choose", "--product", "codex", "--home", str(outside_home)))
790
1920
 
791
- with account_broker.override_subprocess_runner(runner):
792
- outcome, report = account_broker._execute(Product.CODEX, ("job",), now=datetime.now(timezone.utc))
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"
793
1926
 
794
- assert invoked_homes == ["first"]
795
- assert outcome.attempts == (("first", "timeout"),)
796
- assert outcome.status == "timeout"
797
- assert outcome.returncode == 124
798
- assert outcome.account_name == "first"
799
- assert report.final_decision.account.name == "first"
800
- assert account_broker.main(("choose", "--product", "codex")) == 0
801
- assert json.loads(capsys.readouterr().out)["decision"]["account"] == "first"
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"
802
1942
 
803
1943
 
804
1944
  @pytest.mark.parametrize(
805
- ("product", "roster_names", "start_error", "expected_code"),
1945
+ ("meters", "tier"),
806
1946
  (
807
- (Product.CLAUDE, ("first",), subprocess.TimeoutExpired("job", 1), 124),
808
- (Product.CODEX, ("first",), subprocess.TimeoutExpired("job", 1), 124),
809
- (Product.CODEX, (), OSError("missing command"), 127),
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"),
810
1952
  ),
811
1953
  )
812
- def test_should_exit_with_job_failure_code(
813
- monkeypatch: pytest.MonkeyPatch,
814
- tmp_path: Path,
815
- product: Product,
816
- roster_names: tuple[str, ...],
817
- start_error: Exception,
818
- expected_code: int,
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
819
1956
  ) -> None:
820
- accounts = tuple(_account(each_name, product) for each_name in roster_names)
821
- monkeypatch.setitem(account_broker.all_product_adapters, product, _adapter(accounts, {
822
- each_name: _meters(80, 80) for each_name in roster_names
823
- }))
824
- monkeypatch.setattr(account_broker.sys, "stdin", io.TextIOWrapper(io.BytesIO(b""), encoding="utf-8"))
1957
+ outside_home, _ = _use_roster_beside_an_outside_home(monkeypatch, tmp_path, meters)
825
1958
 
826
- def runner(argv: object, **options: object) -> subprocess.CompletedProcess[str]:
827
- raise start_error
1959
+ code = account_broker.main(("choose", "--product", "codex", "--home", str(outside_home)))
828
1960
 
829
- with account_broker.override_subprocess_runner(runner):
830
- code = account_broker.main(("run", "--product", product.value, "--report", str(tmp_path / "report.json"), "--", "job"))
1961
+ decision = json.loads(capsys.readouterr().out)["decision"]
1962
+ assert code == 0
1963
+ assert decision["action"] == "run"
1964
+ assert decision["tier"] == tier
831
1965
 
832
- assert code == expected_code
833
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
834
1973
 
835
- def test_should_keep_usage_limited_account_spent_for_later_choices(
1974
+
1975
+ def test_should_still_wait_on_a_roster_account_at_half_a_percent_weekly_when_no_home_is_named(
836
1976
  monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
837
1977
  ) -> None:
838
- accounts = (_account("first"), _account("second"))
839
- monkeypatch.setitem(account_broker.all_product_adapters, Product.CODEX, _adapter(accounts, {
840
- "first": _meters(80, 80), "second": _meters(70, 70)
841
- }))
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)
842
1984
 
843
- def runner(argv: object, **options: object) -> subprocess.CompletedProcess[str]:
844
- if Path(options["env"]["CODEX_HOME"]).name == "first":
845
- return subprocess.CompletedProcess(argv, 1, "", "rate limit")
846
- return subprocess.CompletedProcess(argv, 0, "served", "")
1985
+ code = account_broker.main(("choose", "--product", "codex"))
847
1986
 
848
- with account_broker.override_subprocess_runner(runner):
849
- account_broker._execute(Product.CODEX, ("job",), now=datetime.now(timezone.utc))
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
850
1991
 
851
- assert account_broker.main(("choose", "--product", "codex")) == 0
852
- assert json.loads(capsys.readouterr().out)["decision"]["account"] == "second"
853
1992
 
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,
1995
+ ) -> None:
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)
2002
+
2003
+ assert account_broker.main(("check", "--product", "codex")) == WAIT_EXIT_CODE
854
2004
 
855
- def test_should_list_accounts_without_reading_meters(
2005
+
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))
2010
+
2011
+ code = account_broker.main(("choose", "--product", "codex", "--home", str(outside_home), "--require-tier", "normal"))
2012
+
2013
+ decision = json.loads(capsys.readouterr().out)["decision"]
2014
+ assert code == WAIT_EXIT_CODE
2015
+ assert decision["action"] == "wait"
2016
+
2017
+
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
+ )
2032
+
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
2039
+
2040
+
2041
+ def test_should_use_the_roster_account_when_the_named_home_is_a_roster_home(
856
2042
  monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
857
2043
  ) -> None:
858
- account = _account("listed")
859
- adapter = ProductAdapter(lambda: (account,), lambda _: pytest.fail("meter read"), "CODEX_HOME", ())
860
- monkeypatch.setitem(account_broker.all_product_adapters, Product.CODEX, adapter)
2044
+ roster_account = _account("team")
2045
+ roster = (roster_account, _account("personal"))
2046
+ all_read_names: list[str] = []
861
2047
 
862
- assert account_broker.main(("accounts", "--product", "codex")) == 0
863
- assert json.loads(capsys.readouterr().out) == {
864
- "accounts": [{"name": "listed", "profile": None, "home": str(account.home), "is_main": False}]
865
- }
2048
+ def read_meters(account: Account) -> Meters:
2049
+ all_read_names.append(account.name)
2050
+ return _meters(80, 80, plan_type=TEAM_PLAN)
866
2051
 
2052
+ monkeypatch.setitem(
2053
+ account_broker.all_product_adapters, Product.CODEX, ProductAdapter(lambda: roster, read_meters, "CODEX_HOME", ())
2054
+ )
867
2055
 
868
- def test_should_use_default_codex_home_without_roster(
869
- monkeypatch: pytest.MonkeyPatch, tmp_path: Path
2056
+ code = account_broker.main(("choose", "--product", "codex", "--home", str(roster_account.home)))
2057
+
2058
+ decision = json.loads(capsys.readouterr().out)["decision"]
2059
+ assert code == 0
2060
+ assert all_read_names == ["team"]
2061
+ assert decision["account"] == "team"
2062
+
2063
+
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]
870
2066
  ) -> None:
871
- monkeypatch.delenv("CODEX_ACCOUNT_PROFILES", raising=False)
872
- monkeypatch.setattr(account_broker.support.codex_account_choice, "default_profiles_root", lambda: tmp_path / "profiles")
873
- monkeypatch.setenv("CODEX_HOME", str(tmp_path / "default"))
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
+ )
874
2072
 
875
- assert account_broker.load_codex_accounts() == ()
876
- decision = choose_from_readings(Product.CODEX, (), now=NOW)
877
- assert decision.account.name == "default"
878
- assert decision.account.home == (tmp_path / "default").resolve()
879
- assert "no roster" in decision.reason
2073
+ code = account_broker.main(("choose", "--product", "codex", "--home", str(outside_home)))
2074
+
2075
+ decision = json.loads(capsys.readouterr().out)["decision"]
2076
+ assert code == 0
2077
+ assert decision["action"] == "run"
2078
+ assert decision["tier"] == "normal"
2079
+
2080
+
2081
+ def test_should_refuse_a_home_beside_spent_marks(
2082
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str]
2083
+ ) -> None:
2084
+ outside_home, all_read_names = _use_roster_beside_an_outside_home(monkeypatch, tmp_path, _meters(80, 80, plan_type="pro"))
2085
+
2086
+ code = account_broker.main(("choose", "--product", "codex", "--home", str(outside_home), "--spent", "team"))
2087
+
2088
+ assert code == 2
2089
+ assert all_read_names == []
2090
+ assert "--home cannot be used with --spent" in capsys.readouterr().err
2091
+
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)))
2095
+
2096
+ assert code == 2
2097
+ assert "--home applies to the codex product only" in capsys.readouterr().err
2098
+
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] = []
2103
+
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", "")
2107
+
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"
880
2113
 
881
2114
 
882
2115
  def test_should_keep_the_codex_roster_for_a_process_without_the_roster_variable(
@@ -968,7 +2201,7 @@ def test_should_wait_for_spent_default_home_until_the_mark_passes(
968
2201
  monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str]
969
2202
  ) -> None:
970
2203
  home = tmp_path / "default-home"
971
- 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)}))
972
2205
  monkeypatch.setenv("CODEX_HOME", str(home))
973
2206
  _freeze_clock(monkeypatch, NOW)
974
2207
  reset = NOW + timedelta(hours=2)
@@ -1273,7 +2506,7 @@ def test_should_warn_when_a_spent_mark_names_an_account_outside_the_roster(
1273
2506
  def test_should_not_warn_when_the_default_account_is_marked_without_a_roster(
1274
2507
  monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
1275
2508
  ) -> None:
1276
- 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)}))
1277
2510
  _freeze_clock(monkeypatch, NOW)
1278
2511
  reset = NOW + timedelta(hours=2)
1279
2512
 
@@ -1290,7 +2523,7 @@ def test_should_warn_when_a_spent_mark_names_an_account_the_roster_lacks(
1290
2523
  monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], all_roster_names: tuple[str, ...], marked_name: str
1291
2524
  ) -> None:
1292
2525
  all_accounts = tuple(_account(each_name) for each_name in all_roster_names)
1293
- 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")}))
1294
2527
  _freeze_clock(monkeypatch, NOW)
1295
2528
  reset = NOW + timedelta(hours=2)
1296
2529