claude-dev-env 8.111.4 → 8.112.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/.agents/skills/build-eval/evals/review/README.md +2 -2
  2. package/.agents/skills/build-eval/evals/review/review_eval_support/account.py +166 -0
  3. package/.agents/skills/build-eval/evals/review/review_eval_support/config/constants.py +26 -0
  4. package/.agents/skills/build-eval/evals/review/review_eval_support/execution.py +8 -0
  5. package/.agents/skills/build-eval/evals/review/test_run.py +261 -0
  6. package/_shared/advisor/reference/astra-rung.md +13 -5
  7. package/_shared/advisor/scripts/codex_astra_advisor.py +31 -8
  8. package/_shared/advisor/scripts/codex_astra_preflight.py +70 -14
  9. package/_shared/advisor/scripts/config/advisor_scripts_constants/astra_advisor_constants.py +7 -0
  10. package/_shared/advisor/scripts/tests/test_codex_astra_advisor.py +266 -2
  11. package/_shared/advisor/scripts/tests/test_codex_astra_preflight.py +114 -8
  12. package/_shared/pr-loop/scripts/check_convergence.py +5 -1
  13. package/_shared/pr-loop/scripts/codex_review_account.py +180 -0
  14. package/_shared/pr-loop/scripts/codex_review_scripts_constants/account_constants.py +28 -0
  15. package/_shared/pr-loop/scripts/codex_review_scripts_constants/run_constants.py +3 -1
  16. package/_shared/pr-loop/scripts/run_codex_review.py +144 -15
  17. package/_shared/pr-loop/scripts/test_check_convergence_codex.py +3 -3
  18. package/_shared/pr-loop/scripts/test_codex_review_account.py +355 -0
  19. package/_shared/pr-loop/scripts/test_run_codex_review.py +507 -6
  20. package/docs/account-broker.md +6 -4
  21. package/docs/codex-accounts.md +57 -16
  22. package/docs/rule-guides/question-presentation.md +4 -0
  23. package/docs/second-claude-account.md +1 -1
  24. package/hooks/blocking/final_reply_gate.py +59 -3
  25. package/hooks/blocking/open_tasks_transcript.py +18 -0
  26. package/hooks/blocking/test_final_reply_gate.py +160 -0
  27. package/hooks/features/conduct-gates.md +1 -4
  28. package/hooks/hooks.json +0 -10
  29. package/hooks/hooks_constants/final_reply_gate_constants.py +16 -0
  30. package/hooks/hooks_constants/open_tasks_stop_gate_constants.py +9 -0
  31. package/package.json +1 -1
  32. package/rules/question-presentation.md +1 -1
  33. package/scripts/account_broker.py +122 -27
  34. package/scripts/account_broker_support.py +54 -3
  35. package/scripts/codex_account_choice.py +12 -8
  36. package/scripts/codex_account_chooser.py +110 -0
  37. package/scripts/codex_account_meters.py +43 -4
  38. package/scripts/codex_plan_rules.py +156 -0
  39. package/scripts/dev_env_scripts_constants/account_broker_constants.py +41 -42
  40. package/scripts/dev_env_scripts_constants/codex_account_constants.py +62 -2
  41. package/scripts/dev_env_scripts_constants/test_account_broker_constants.py +359 -2
  42. package/scripts/dev_env_scripts_constants/test_codex_account_constants.py +213 -14
  43. package/scripts/policy_lint/adapter_configuration.py +0 -5
  44. package/scripts/policy_lint/config/constants.py +0 -1
  45. package/scripts/test_account_broker.py +1913 -526
  46. package/scripts/test_account_broker_support.py +77 -0
  47. package/scripts/test_codex_account_meters.py +95 -0
  48. package/scripts/tests/test_adapter_configuration.py +0 -8
  49. package/hooks/blocking/merge_over_review_offer_gate.py +0 -114
  50. package/hooks/blocking/test_merge_over_review_offer_gate.py +0 -138
  51. package/hooks/hooks_constants/merge_over_review_offer_gate_constants.py +0 -34
@@ -15,14 +15,22 @@ SCRIPTS_DIRECTORY = Path(__file__).resolve().parent
15
15
  if str(SCRIPTS_DIRECTORY) not in sys.path:
16
16
  sys.path.insert(0, str(SCRIPTS_DIRECTORY))
17
17
 
18
+ import codex_review_account as account
18
19
  import run_codex_review as wrapper # noqa: E402
19
- from codex_review_scripts_constants.run_constants import ( # noqa: E402
20
+ from codex_review_scripts_constants.account_constants import (
21
+ ACCOUNT_BROKER_HOME_FLAG,
22
+ BROKER_WAIT_EXIT_CODE,
23
+ NO_ACCOUNT_EXIT_CODE,
24
+ )
25
+ from codex_review_scripts_constants.run_constants import (
20
26
  ALL_SHAPE_PROBE_REQUIRED_FLAGS,
21
27
  BASE_TARGET_FLAG,
28
+ CANNOT_EXECUTE_EXIT_CODE,
22
29
  CODEX_BINARY_NAME,
23
30
  CODEX_HOME_ENV_VAR,
24
31
  COMMIT_TARGET_FLAG,
25
32
  CUSTOM_INSTRUCTIONS_PROMPT,
33
+ DECODE_ERRORS_REPLACE,
26
34
  DEFAULT_TIMEOUT_SECONDS,
27
35
  EXEC_SUBCOMMAND,
28
36
  HELP_FLAG,
@@ -33,7 +41,6 @@ from codex_review_scripts_constants.run_constants import ( # noqa: E402
33
41
  OUTCOME_CLASS_CODEX_DOWN,
34
42
  OUTCOME_CLASS_COMPLETED,
35
43
  REVIEW_SUBCOMMAND,
36
- SUBPROCESS_DECODE_EXIT_CODE,
37
44
  TIMEOUT_EXIT_CODE,
38
45
  UNCOMMITTED_TARGET_FLAG,
39
46
  UTF8_ENCODING,
@@ -47,10 +54,17 @@ HELP_TEXT_WITH_TARGETS = (
47
54
  " --commit <SHA>\n"
48
55
  " --json\n"
49
56
  )
57
+ BROKER_ACCOUNT_HOME = str(Path("profiles-root") / "codex-1")
58
+ SPAWN_PERMISSION_MESSAGE = "access denied"
59
+ WINDOWS_NOT_EXECUTABLE_MESSAGE = "[WinError 193] not a valid Win32 application"
50
60
  VERSION_STDOUT = "codex-cli 0.144.3\n"
51
61
  EXPECTED_BINARY_VERSION = "0.144.3"
52
62
  AGENT_MESSAGE_BODY = "No issues found.\n\n```json\n[]\n```"
53
63
  CARRIAGE_RETURN_LINE_ENDING = b"\r\n"
64
+ INVALID_UTF8_STDOUT_BYTES = b"ok\xff\xfe"
65
+ INVALID_UTF8_STDERR_BYTES = b"\x80err"
66
+ INVALID_UTF8_COMMAND_TIMEOUT_SECONDS = 60
67
+ REPLACEMENT_CHARACTER = "�"
54
68
  SUCCESS_JSONL = "\n".join(
55
69
  [
56
70
  json.dumps({"type": "thread.started", "thread_id": "thread-1"}),
@@ -154,13 +168,74 @@ def _is_review_run(all_arguments: list[str]) -> bool:
154
168
  )
155
169
 
156
170
 
171
+ def _broker_answer_text(tier: str, action: str, home: str | None, reason: str) -> str:
172
+ return json.dumps(
173
+ {
174
+ "decision": {
175
+ "action": action,
176
+ "account": "codex-1",
177
+ "profile": "codex-1",
178
+ "home": home,
179
+ "reason": reason,
180
+ "tier": tier,
181
+ "resets_at": None,
182
+ },
183
+ "accounts": [],
184
+ "state_path": "state.json",
185
+ }
186
+ )
187
+
188
+
189
+ def _normal_broker_reply(
190
+ all_arguments: list[str],
191
+ ) -> subprocess.CompletedProcess[str]:
192
+ answered_home = BROKER_ACCOUNT_HOME
193
+ if ACCOUNT_BROKER_HOME_FLAG in all_arguments:
194
+ judged_home = all_arguments[all_arguments.index(ACCOUNT_BROKER_HOME_FLAG) + 1]
195
+ answered_home = str(Path(judged_home).expanduser().resolve())
196
+ return _completed(
197
+ all_arguments,
198
+ 0,
199
+ stdout=_broker_answer_text(
200
+ "normal", "run", answered_home, "codex-1 has 62% left"
201
+ ),
202
+ )
203
+
204
+
205
+ def _is_broker_choose(all_arguments: list[str]) -> bool:
206
+ return all_arguments == account.broker_choose_command()
207
+
208
+
209
+ def _is_broker_home_check(all_arguments: list[str], codex_home: str) -> bool:
210
+ return all_arguments == account.broker_home_check_command(codex_home)
211
+
212
+
213
+ def _is_any_broker_command(all_arguments: list[str]) -> bool:
214
+ return all_arguments[:2] == [sys.executable, str(account.account_broker_path())]
215
+
216
+
217
+ @pytest.fixture(autouse=True)
218
+ def no_codex_home_in_environment(monkeypatch: pytest.MonkeyPatch) -> None:
219
+ monkeypatch.delenv(CODEX_HOME_ENV_VAR, raising=False)
220
+
221
+
157
222
  def _install_recorder(
158
223
  monkeypatch: pytest.MonkeyPatch,
159
224
  behavior_for_invocation: Callable[
160
225
  [list[str]], subprocess.CompletedProcess[str] | BaseException
161
226
  ],
227
+ broker_behavior: Callable[
228
+ [list[str]], subprocess.CompletedProcess[str] | BaseException
229
+ ] = _normal_broker_reply,
162
230
  ) -> _SubprocessRecorder:
163
- recorder = _SubprocessRecorder(behavior_for_invocation)
231
+ def behavior_with_broker(
232
+ all_arguments: list[str],
233
+ ) -> subprocess.CompletedProcess[str] | BaseException:
234
+ if _is_any_broker_command(all_arguments):
235
+ return broker_behavior(all_arguments)
236
+ return behavior_for_invocation(all_arguments)
237
+
238
+ recorder = _SubprocessRecorder(behavior_with_broker)
164
239
  monkeypatch.setattr(wrapper, "codex_subprocess_runner", recorder)
165
240
  monkeypatch.setattr(
166
241
  wrapper, "_resolve_codex_command_prefix", lambda: [CODEX_BINARY_NAME]
@@ -465,6 +540,7 @@ def test_jsonl_capture_and_agent_message_extraction(
465
540
  assert review_keyword_arguments["capture_output"] is True
466
541
  assert review_keyword_arguments["text"] is True
467
542
  assert review_keyword_arguments["encoding"] == UTF8_ENCODING
543
+ assert review_keyword_arguments["errors"] == DECODE_ERRORS_REPLACE
468
544
  assert review_keyword_arguments["check"] is False
469
545
 
470
546
 
@@ -487,15 +563,23 @@ def test_jsonl_capture_preserves_stream_line_endings(
487
563
  assert captured_bytes == SUCCESS_JSONL.encode(UTF8_ENCODING)
488
564
 
489
565
 
490
- def test_unicode_decode_error_returns_codex_down(
566
+ @pytest.mark.parametrize(
567
+ "spawn_error",
568
+ [
569
+ PermissionError(SPAWN_PERMISSION_MESSAGE),
570
+ OSError(WINDOWS_NOT_EXECUTABLE_MESSAGE),
571
+ ],
572
+ )
573
+ def test_codex_binary_that_cannot_start_returns_codex_down(
491
574
  monkeypatch: pytest.MonkeyPatch,
492
575
  repository_directory: Path,
493
576
  run_state_directory: Path,
577
+ spawn_error: OSError,
494
578
  ) -> None:
495
579
  def behavior(
496
580
  all_arguments: list[str],
497
581
  ) -> subprocess.CompletedProcess[str] | BaseException:
498
- raise UnicodeDecodeError("utf-8", b"\xff", 0, 1, "invalid start byte")
582
+ return spawn_error
499
583
 
500
584
  _install_recorder(monkeypatch, behavior)
501
585
 
@@ -506,10 +590,44 @@ def test_unicode_decode_error_returns_codex_down(
506
590
  )
507
591
 
508
592
  assert review_outcome.outcome_class == OUTCOME_CLASS_CODEX_DOWN
509
- assert review_outcome.exit_code == SUBPROCESS_DECODE_EXIT_CODE
593
+ assert review_outcome.exit_code == CANNOT_EXECUTE_EXIT_CODE
510
594
  assert review_outcome.jsonl_path is None
511
595
 
512
596
 
597
+ def test_command_output_with_invalid_utf8_is_decoded_with_replacement() -> None:
598
+ emit_invalid_bytes_program = (
599
+ "import sys;"
600
+ f"sys.stdout.buffer.write({INVALID_UTF8_STDOUT_BYTES!r});"
601
+ f"sys.stderr.buffer.write({INVALID_UTF8_STDERR_BYTES!r})"
602
+ )
603
+
604
+ command_completion = wrapper._run_command(
605
+ [sys.executable, "-c", emit_invalid_bytes_program],
606
+ working_directory=None,
607
+ timeout_seconds=INVALID_UTF8_COMMAND_TIMEOUT_SECONDS,
608
+ )
609
+
610
+ assert command_completion.returncode == 0
611
+ assert command_completion.stdout == f"ok{REPLACEMENT_CHARACTER}{REPLACEMENT_CHARACTER}"
612
+ assert command_completion.stderr == f"{REPLACEMENT_CHARACTER}err"
613
+
614
+
615
+ def test_safe_run_returns_the_completion_for_invalid_utf8_output() -> None:
616
+ emit_invalid_bytes_program = (
617
+ "import sys;"
618
+ f"sys.stdout.buffer.write({INVALID_UTF8_STDOUT_BYTES!r})"
619
+ )
620
+
621
+ command_completion = wrapper._safe_run(
622
+ [sys.executable, "-c", emit_invalid_bytes_program],
623
+ working_directory=None,
624
+ timeout_seconds=INVALID_UTF8_COMMAND_TIMEOUT_SECONDS,
625
+ )
626
+
627
+ assert isinstance(command_completion, subprocess.CompletedProcess)
628
+ assert command_completion.stdout == f"ok{REPLACEMENT_CHARACTER}{REPLACEMENT_CHARACTER}"
629
+
630
+
513
631
  def test_timeout_returns_codex_down(
514
632
  monkeypatch: pytest.MonkeyPatch,
515
633
  repository_directory: Path,
@@ -563,6 +681,389 @@ def test_codex_home_env_is_passed_through_when_set(
563
681
  assert process_environment[CODEX_HOME_ENV_VAR] == str(codex_home_directory)
564
682
 
565
683
 
684
+ def _run_uncommitted_review(
685
+ repository_directory: Path, run_state_directory: Path
686
+ ) -> wrapper.CodexReviewOutcome:
687
+ return wrapper.run_codex_review(
688
+ repository_directory=repository_directory,
689
+ run_state_directory=run_state_directory,
690
+ is_uncommitted=True,
691
+ )
692
+
693
+
694
+ def _environment_of(
695
+ recorder: _SubprocessRecorder, invocation: list[str]
696
+ ) -> dict[str, str]:
697
+ invocation_index = recorder.all_invocations.index(invocation)
698
+ environment = recorder.all_keyword_arguments[invocation_index]["env"]
699
+ assert isinstance(environment, dict)
700
+ return environment
701
+
702
+
703
+ def test_review_runs_on_the_home_the_broker_names(
704
+ monkeypatch: pytest.MonkeyPatch,
705
+ repository_directory: Path,
706
+ run_state_directory: Path,
707
+ ) -> None:
708
+ recorder = _install_recorder(monkeypatch, _healthy_probe_then_review())
709
+
710
+ review_outcome = _run_uncommitted_review(repository_directory, run_state_directory)
711
+
712
+ assert review_outcome.outcome_class == OUTCOME_CLASS_COMPLETED
713
+ review_environment = _environment_of(recorder, _only_review_invocation(recorder))
714
+ assert review_environment[CODEX_HOME_ENV_VAR] == BROKER_ACCOUNT_HOME
715
+
716
+
717
+ def test_broker_is_asked_after_the_probes_and_before_the_review(
718
+ monkeypatch: pytest.MonkeyPatch,
719
+ repository_directory: Path,
720
+ run_state_directory: Path,
721
+ ) -> None:
722
+ recorder = _install_recorder(monkeypatch, _healthy_probe_then_review())
723
+
724
+ _run_uncommitted_review(repository_directory, run_state_directory)
725
+
726
+ all_stage_names = [
727
+ "version"
728
+ if _is_version_probe(each_invocation)
729
+ else "shape"
730
+ if _is_shape_probe(each_invocation)
731
+ else "broker"
732
+ if _is_broker_choose(each_invocation)
733
+ else "review"
734
+ for each_invocation in recorder.all_invocations
735
+ ]
736
+ assert all_stage_names == ["version", "shape", "broker", "review"]
737
+
738
+
739
+ def test_broker_wait_returns_codex_down_without_running_the_review(
740
+ monkeypatch: pytest.MonkeyPatch,
741
+ repository_directory: Path,
742
+ run_state_directory: Path,
743
+ ) -> None:
744
+ wait_reason = "no account has room; next reset at 2026-11-10T00:00:00Z"
745
+
746
+ def broker_waits(
747
+ all_arguments: list[str],
748
+ ) -> subprocess.CompletedProcess[str]:
749
+ return _completed(
750
+ all_arguments,
751
+ BROKER_WAIT_EXIT_CODE,
752
+ stdout=_broker_answer_text("wait", "wait", None, wait_reason),
753
+ )
754
+
755
+ recorder = _install_recorder(
756
+ monkeypatch, _healthy_probe_then_review(), broker_waits
757
+ )
758
+
759
+ review_outcome = _run_uncommitted_review(repository_directory, run_state_directory)
760
+
761
+ assert review_outcome.outcome_class == OUTCOME_CLASS_CODEX_DOWN
762
+ assert review_outcome.exit_code == NO_ACCOUNT_EXIT_CODE
763
+ assert review_outcome.binary_version == EXPECTED_BINARY_VERSION
764
+ assert review_outcome.jsonl_path is None
765
+ assert wait_reason in review_outcome.agent_message
766
+ assert not any(
767
+ _is_review_run(each_invocation)
768
+ for each_invocation in recorder.all_invocations
769
+ )
770
+ assert list(run_state_directory.iterdir()) == []
771
+
772
+
773
+ def test_luna_tier_answer_returns_codex_down_without_running_the_review(
774
+ monkeypatch: pytest.MonkeyPatch,
775
+ repository_directory: Path,
776
+ run_state_directory: Path,
777
+ ) -> None:
778
+ def broker_answers_luna(
779
+ all_arguments: list[str],
780
+ ) -> subprocess.CompletedProcess[str]:
781
+ return _completed(
782
+ all_arguments,
783
+ 0,
784
+ stdout=_broker_answer_text(
785
+ "luna", "run", BROKER_ACCOUNT_HOME, "codex-1 has 4% left"
786
+ ),
787
+ )
788
+
789
+ recorder = _install_recorder(
790
+ monkeypatch, _healthy_probe_then_review(), broker_answers_luna
791
+ )
792
+
793
+ review_outcome = _run_uncommitted_review(repository_directory, run_state_directory)
794
+
795
+ assert review_outcome.outcome_class == OUTCOME_CLASS_CODEX_DOWN
796
+ assert review_outcome.exit_code == NO_ACCOUNT_EXIT_CODE
797
+ assert "codex-1 has 4% left" in review_outcome.agent_message
798
+ assert not any(
799
+ _is_review_run(each_invocation)
800
+ for each_invocation in recorder.all_invocations
801
+ )
802
+
803
+
804
+ @pytest.mark.parametrize(
805
+ ("broker_behavior", "expected_exit_code"),
806
+ [
807
+ (lambda all_arguments: _completed(all_arguments, 2, stderr="bad roster"), 2),
808
+ (
809
+ lambda all_arguments: _completed(all_arguments, 0, stdout="not json"),
810
+ NO_ACCOUNT_EXIT_CODE,
811
+ ),
812
+ (
813
+ lambda all_arguments: _completed(
814
+ all_arguments,
815
+ 0,
816
+ stdout=_broker_answer_text("normal", "run", None, "no home"),
817
+ ),
818
+ NO_ACCOUNT_EXIT_CODE,
819
+ ),
820
+ (
821
+ lambda all_arguments: subprocess.TimeoutExpired(
822
+ cmd=all_arguments, timeout=1
823
+ ),
824
+ TIMEOUT_EXIT_CODE,
825
+ ),
826
+ (
827
+ lambda all_arguments: FileNotFoundError(all_arguments[0]),
828
+ MISSING_BINARY_EXIT_CODE,
829
+ ),
830
+ (
831
+ lambda all_arguments: PermissionError(SPAWN_PERMISSION_MESSAGE),
832
+ CANNOT_EXECUTE_EXIT_CODE,
833
+ ),
834
+ (
835
+ lambda all_arguments: OSError(WINDOWS_NOT_EXECUTABLE_MESSAGE),
836
+ CANNOT_EXECUTE_EXIT_CODE,
837
+ ),
838
+ ],
839
+ )
840
+ def test_broker_failure_returns_codex_down_without_running_the_review(
841
+ monkeypatch: pytest.MonkeyPatch,
842
+ repository_directory: Path,
843
+ run_state_directory: Path,
844
+ broker_behavior: Callable[
845
+ [list[str]], subprocess.CompletedProcess[str] | BaseException
846
+ ],
847
+ expected_exit_code: int,
848
+ ) -> None:
849
+ recorder = _install_recorder(
850
+ monkeypatch, _healthy_probe_then_review(), broker_behavior
851
+ )
852
+
853
+ review_outcome = _run_uncommitted_review(repository_directory, run_state_directory)
854
+
855
+ assert review_outcome.outcome_class == OUTCOME_CLASS_CODEX_DOWN
856
+ assert review_outcome.exit_code == expected_exit_code
857
+ assert review_outcome.jsonl_path is None
858
+ assert not any(
859
+ _is_review_run(each_invocation)
860
+ for each_invocation in recorder.all_invocations
861
+ )
862
+
863
+
864
+ def test_codex_home_already_set_keeps_its_account_after_the_broker_checks_it(
865
+ monkeypatch: pytest.MonkeyPatch,
866
+ tmp_path: Path,
867
+ repository_directory: Path,
868
+ run_state_directory: Path,
869
+ ) -> None:
870
+ pinned_home = str(tmp_path / "pinned-codex-home")
871
+ monkeypatch.setenv(CODEX_HOME_ENV_VAR, pinned_home)
872
+ recorder = _install_recorder(monkeypatch, _healthy_probe_then_review())
873
+
874
+ review_outcome = _run_uncommitted_review(repository_directory, run_state_directory)
875
+
876
+ assert review_outcome.outcome_class == OUTCOME_CLASS_COMPLETED
877
+ assert not any(
878
+ _is_broker_choose(each_invocation)
879
+ for each_invocation in recorder.all_invocations
880
+ )
881
+ assert any(
882
+ _is_broker_home_check(each_invocation, pinned_home)
883
+ for each_invocation in recorder.all_invocations
884
+ )
885
+ review_environment = _environment_of(recorder, _only_review_invocation(recorder))
886
+ assert review_environment[CODEX_HOME_ENV_VAR] == pinned_home
887
+
888
+
889
+ def test_padded_paid_export_launches_on_the_trimmed_absolute_folder(
890
+ monkeypatch: pytest.MonkeyPatch,
891
+ tmp_path: Path,
892
+ repository_directory: Path,
893
+ run_state_directory: Path,
894
+ ) -> None:
895
+ paid_home = tmp_path / "paid-codex-home"
896
+ paid_home.mkdir()
897
+ monkeypatch.setenv(CODEX_HOME_ENV_VAR, f" {paid_home} ")
898
+ recorder = _install_recorder(monkeypatch, _healthy_probe_then_review())
899
+
900
+ review_outcome = _run_uncommitted_review(repository_directory, run_state_directory)
901
+
902
+ assert review_outcome.outcome_class == OUTCOME_CLASS_COMPLETED
903
+ assert any(
904
+ _is_broker_home_check(each_invocation, str(paid_home))
905
+ for each_invocation in recorder.all_invocations
906
+ )
907
+ review_environment = _environment_of(recorder, _only_review_invocation(recorder))
908
+ assert review_environment[CODEX_HOME_ENV_VAR] == str(paid_home.resolve())
909
+
910
+
911
+ def test_pinned_home_review_launches_on_the_home_the_broker_answers(
912
+ monkeypatch: pytest.MonkeyPatch,
913
+ tmp_path: Path,
914
+ repository_directory: Path,
915
+ run_state_directory: Path,
916
+ ) -> None:
917
+ monkeypatch.setenv(CODEX_HOME_ENV_VAR, str(tmp_path / "exported-codex-home"))
918
+
919
+ def broker_names_its_own_spelling(
920
+ all_arguments: list[str],
921
+ ) -> subprocess.CompletedProcess[str]:
922
+ return _completed(
923
+ all_arguments,
924
+ 0,
925
+ stdout=_broker_answer_text(
926
+ "luna", "run", BROKER_ACCOUNT_HOME, "codex-1 has 4% left"
927
+ ),
928
+ )
929
+
930
+ recorder = _install_recorder(
931
+ monkeypatch, _healthy_probe_then_review(), broker_names_its_own_spelling
932
+ )
933
+
934
+ review_outcome = _run_uncommitted_review(repository_directory, run_state_directory)
935
+
936
+ assert review_outcome.outcome_class == OUTCOME_CLASS_COMPLETED
937
+ review_environment = _environment_of(recorder, _only_review_invocation(recorder))
938
+ assert review_environment[CODEX_HOME_ENV_VAR] == BROKER_ACCOUNT_HOME
939
+
940
+
941
+ def test_codex_home_already_set_on_a_refused_account_returns_codex_down(
942
+ monkeypatch: pytest.MonkeyPatch,
943
+ tmp_path: Path,
944
+ repository_directory: Path,
945
+ run_state_directory: Path,
946
+ ) -> None:
947
+ monkeypatch.setenv(CODEX_HOME_ENV_VAR, str(tmp_path / "free-codex-home"))
948
+ refusal_reason = "default is on a free plan; the broker never picks it"
949
+
950
+ def broker_refuses(
951
+ all_arguments: list[str],
952
+ ) -> subprocess.CompletedProcess[str]:
953
+ return _completed(
954
+ all_arguments,
955
+ BROKER_WAIT_EXIT_CODE,
956
+ stdout=_broker_answer_text("wait", "wait", None, refusal_reason),
957
+ )
958
+
959
+ recorder = _install_recorder(
960
+ monkeypatch, _healthy_probe_then_review(), broker_refuses
961
+ )
962
+
963
+ review_outcome = _run_uncommitted_review(repository_directory, run_state_directory)
964
+
965
+ assert review_outcome.outcome_class == OUTCOME_CLASS_CODEX_DOWN
966
+ assert review_outcome.exit_code == NO_ACCOUNT_EXIT_CODE
967
+ assert refusal_reason in review_outcome.agent_message
968
+ assert not any(
969
+ _is_review_run(each_invocation)
970
+ for each_invocation in recorder.all_invocations
971
+ )
972
+
973
+
974
+ @pytest.mark.parametrize(
975
+ "broker_behavior",
976
+ [
977
+ lambda all_arguments: _completed(all_arguments, 2, stderr="bad roster"),
978
+ lambda all_arguments: _completed(all_arguments, 0, stdout="not json"),
979
+ lambda all_arguments: FileNotFoundError(all_arguments[0]),
980
+ lambda all_arguments: PermissionError(SPAWN_PERMISSION_MESSAGE),
981
+ lambda all_arguments: OSError(WINDOWS_NOT_EXECUTABLE_MESSAGE),
982
+ ],
983
+ )
984
+ def test_codex_home_already_set_fails_closed_when_the_broker_cannot_check_it(
985
+ monkeypatch: pytest.MonkeyPatch,
986
+ tmp_path: Path,
987
+ repository_directory: Path,
988
+ run_state_directory: Path,
989
+ broker_behavior: Callable[
990
+ [list[str]], subprocess.CompletedProcess[str] | BaseException
991
+ ],
992
+ ) -> None:
993
+ monkeypatch.setenv(CODEX_HOME_ENV_VAR, str(tmp_path / "unchecked-codex-home"))
994
+ recorder = _install_recorder(
995
+ monkeypatch, _healthy_probe_then_review(), broker_behavior
996
+ )
997
+
998
+ review_outcome = _run_uncommitted_review(repository_directory, run_state_directory)
999
+
1000
+ assert review_outcome.outcome_class == OUTCOME_CLASS_CODEX_DOWN
1001
+ assert not any(
1002
+ _is_review_run(each_invocation)
1003
+ for each_invocation in recorder.all_invocations
1004
+ )
1005
+
1006
+
1007
+ def test_codex_home_already_set_on_a_low_room_paid_account_still_runs(
1008
+ monkeypatch: pytest.MonkeyPatch,
1009
+ tmp_path: Path,
1010
+ repository_directory: Path,
1011
+ run_state_directory: Path,
1012
+ ) -> None:
1013
+ pinned_home = str(tmp_path / "pinned-codex-home")
1014
+ monkeypatch.setenv(CODEX_HOME_ENV_VAR, pinned_home)
1015
+
1016
+ def broker_answers_luna(
1017
+ all_arguments: list[str],
1018
+ ) -> subprocess.CompletedProcess[str]:
1019
+ return _completed(
1020
+ all_arguments,
1021
+ 0,
1022
+ stdout=_broker_answer_text("luna", "run", pinned_home, "default has 4% left"),
1023
+ )
1024
+
1025
+ _install_recorder(monkeypatch, _healthy_probe_then_review(), broker_answers_luna)
1026
+
1027
+ review_outcome = _run_uncommitted_review(repository_directory, run_state_directory)
1028
+
1029
+ assert review_outcome.outcome_class == OUTCOME_CLASS_COMPLETED
1030
+
1031
+
1032
+ def test_blank_codex_home_does_not_pin_an_account(
1033
+ monkeypatch: pytest.MonkeyPatch,
1034
+ repository_directory: Path,
1035
+ run_state_directory: Path,
1036
+ ) -> None:
1037
+ monkeypatch.setenv(CODEX_HOME_ENV_VAR, " ")
1038
+ recorder = _install_recorder(monkeypatch, _healthy_probe_then_review())
1039
+
1040
+ _run_uncommitted_review(repository_directory, run_state_directory)
1041
+
1042
+ review_environment = _environment_of(recorder, _only_review_invocation(recorder))
1043
+ assert review_environment[CODEX_HOME_ENV_VAR] == BROKER_ACCOUNT_HOME
1044
+
1045
+
1046
+ def test_broker_is_not_asked_when_the_probe_already_failed(
1047
+ monkeypatch: pytest.MonkeyPatch,
1048
+ repository_directory: Path,
1049
+ run_state_directory: Path,
1050
+ ) -> None:
1051
+ def behavior(
1052
+ all_arguments: list[str],
1053
+ ) -> subprocess.CompletedProcess[str] | BaseException:
1054
+ raise FileNotFoundError(all_arguments[0])
1055
+
1056
+ recorder = _install_recorder(monkeypatch, behavior)
1057
+
1058
+ review_outcome = _run_uncommitted_review(repository_directory, run_state_directory)
1059
+
1060
+ assert review_outcome.outcome_class == OUTCOME_CLASS_CODEX_DOWN
1061
+ assert not any(
1062
+ _is_broker_choose(each_invocation)
1063
+ for each_invocation in recorder.all_invocations
1064
+ )
1065
+
1066
+
566
1067
  def test_rejects_multiple_targets(
567
1068
  monkeypatch: pytest.MonkeyPatch,
568
1069
  repository_directory: Path,
@@ -6,7 +6,7 @@ Claude's main home is `~/.claude`. Its `claude-chain.json` file contains a `chai
6
6
 
7
7
  The optional `claude-account-order.json` file in the main home sets the Claude pick priority. It is a JSON list of account names, first choice first, such as `["claude-second", "claude"]`. An entry matches an account's name, its command, or its `claude-<name>` launcher, and `claude` names the main account. A new job goes to the first listed account with room. When no listed account has room, the broker picks the unlisted account with the most room, and it waits when no account has room. A resumed session stays on its bound account while that account has room. A listed name absent from the roster is skipped. Without the file, every job goes to the account with the most room. Edit the file to change the order; the next pick reads it.
8
8
 
9
- Codex uses its configured account list. A broker run that reads `CODEX_ACCOUNT_PROFILES` saves that list to `account-launchers.json`, so a later run without the variable reads the same roster; [Codex accounts](codex-accounts.md) has the details. When no Codex roster is configured, the broker chooses the default Codex home. A new Codex job goes to an account on a Pro plan before any other account in the same tier. The plan comes from the account's meter reply, and `ALL_PRO_PLAN_TYPES` lists the Pro plans: `pro`, `prolite`, and `promax`. Among accounts of the same kind, the one with the most room wins. A Pro account below the `normal` floor still loses to any account with room in the `normal` tier.
9
+ Codex uses its configured account list. A broker run that reads `CODEX_ACCOUNT_PROFILES` saves that list to `account-launchers.json`, so a later run without the variable reads the same roster; [Codex accounts](codex-accounts.md) has the details. When no Codex roster is configured, `choose` and `check` read the default Codex home, `CODEX_HOME` or `~/.codex` when it is unset or blank, as the account `default` and apply the same plan rule, so a free, missing, unknown or unlisted plan there gives `wait`. A failed read of that home also gives `wait` with exit 3, and the reason names the failure. A new Codex job goes to an account on a Pro plan before any account on another plan, in any tier, whenever a Pro account can run. The plan comes from the account's meter reply, and `ALL_PRO_PLAN_TYPES` lists the Pro plans: `pro`, `prolite`, and `promax`. Among accounts of the same kind, `normal` comes before `luna`, and the one with the most room wins. A Pro account with no credits and more than 0% and at most 10% of its room left takes `luna`, and it still comes before an account on another plan with room in the `normal` tier. A Pro account with no credits cannot run when one of its windows has no room left, when its meters are unread, when a spent mark on it is still in the future, or, for a caller that passes `--require-tier normal`, when it has 10% or less of its room left; the broker then moves to the next account. The 1% weekly stop and the 20% short-window floor apply to accounts on other plans. A caller that passes `--require-tier normal` takes a Pro account only when it reaches `normal`, and otherwise the account on another paid plan with the most room that does. An account on a free plan (`ALL_FREE_PLAN_TYPES`, `free`) is never chosen, and a `wait` reason names it. Only a plan on the paid list (`ALL_PAID_PLAN_TYPES`: `business`, `edu`, `enterprise`, `plus`, `pro`, `prolite`, `promax`, and `team`) is chosen. An account whose meter reply names no plan, a blank plan, `unknown`, or any other name outside that list is never chosen either, and its `wait` reason says so. An account whose meters could not be read keeps the unread handling below and is not judged by plan. An account with credits, which the meter reply reports as `hasCredits` is `true` with a balance above zero, or `unlimited` is `true`, takes the `normal` tier at any plan room, so a Pro account with credits comes before every account on another plan.
10
10
 
11
11
  ## Commands
12
12
 
@@ -14,13 +14,15 @@ Codex uses its configured account list. A broker run that reads `CODEX_ACCOUNT_P
14
14
  python scripts/account_broker.py accounts --product claude
15
15
  python scripts/account_broker.py choose --product codex
16
16
  python scripts/account_broker.py choose --product codex --spent account-name:1790000000
17
+ python scripts/account_broker.py choose --product codex --require-tier normal
18
+ python scripts/account_broker.py choose --product codex --home ~/.codex-profiles/codex-1
17
19
  python scripts/account_broker.py check --product codex
18
20
  printf "%s" "prompt" | python scripts/account_broker.py run --product claude --report report.json -- claude --output-format json -p
19
21
  ```
20
22
 
21
- `accounts` prints the roster without reading meters. `choose` prints `decision`, `accounts`, and `state_path`. Each decision contains `action`, `account`, `profile`, `home`, `reason`, `tier`, and `resets_at`. `profile` is the name of the profile whose home the account uses, such as `editor` for a home at `~/.claude-profiles/editor`. It is null for the main account, a Codex account, a home outside the profiles root, a home whose folder name is not a valid profile name such as `main`, and a wait decision. `--spent` takes an account's name or its profile. The account order file matches the name, command, or launcher, and resume affinity stores the command, or the name for an account without one. When a mark is one account's name and another account's profile, the name wins. Every mark is read before the first one is saved, so an unreadable mark saves none. `accounts` and the `choose` account list carry the same `profile` field. A wait decision has no account or home and includes the soonest reset in UTC. An account counts as free at the latest reset of the windows that hold it, and one hour out when one of those windows has no reset time. A failed meter read reuses the account's last good reading when that reading is 30 minutes old or less, and otherwise excludes the account for that choice. `--spent` saves an exclusion until the supplied Unix reset, the account's soonest known meter reset, or one hour when neither is available. A `--spent` name absent from the roster is saved until the supplied Unix reset, or for one hour when no reset is given. A mark splits at its last colon, so an absent name that contains a colon, such as `C:\bin\old.cmd`, takes an explicit reset, such as `C:\bin\old.cmd:1800000000`. While any such mark is still in the future, `choose` waits until the soonest mark and exits 3, and with no Codex roster `--spent default` waits until that mark passes. `default` is the name `choose` gives the Codex home when no roster is configured, so while a Codex roster exists `choose` neither saves a `--spent default` mark nor waits on a stored one. Meter reads younger than 60 seconds are reused.
23
+ `accounts` prints the roster without reading meters. `choose` prints `decision`, `accounts`, and `state_path`. Each decision contains `action`, `account`, `profile`, `home`, `reason`, `tier`, and `resets_at`. `profile` is the name of the profile whose home the account uses, such as `editor` for a home at `~/.claude-profiles/editor`. It is null for the main account, a Codex account, a home outside the profiles root, a home whose folder name is not a valid profile name such as `main`, and a wait decision. `--spent` takes an account's name or its profile. The account order file matches the name, command, or launcher, and resume affinity stores the command, or the name for an account without one. When a mark is one account's name and another account's profile, the name wins. Every mark is read before the first one is saved, so an unreadable mark saves none. `accounts` and the `choose` account list carry the same `profile` field. A wait decision has no account or home and includes the soonest reset in UTC. An account counts as free at the latest reset of the windows that hold it, and one hour out when one of those windows has no reset time. A failed meter read reuses the account's last good reading when that reading is 30 minutes old or less, and otherwise excludes the account for that choice. `--spent` saves an exclusion until the supplied Unix reset, the account's soonest known meter reset, or one hour when neither is available. A Codex account with spendable credits is not excluded by a mark saved for it, so `choose` still runs it when its meters give it a tier. A mark saved for a roster account excludes only that account, so `choose` runs another account that has room. A `--spent` name absent from the roster is saved until the supplied Unix reset, or for one hour when no reset is given. A mark splits at its last colon, so an absent name that contains a colon, such as `C:\bin\old.cmd`, takes an explicit reset, such as `C:\bin\old.cmd:1800000000`. While a mark for a name outside the roster is still in the future, `choose` waits and exits 3, even when the roster has room. With no Codex roster, a paid default home without spendable credits waits until its `--spent default` mark passes. `default` is the name `choose` gives the Codex home when no roster is configured, so while a Codex roster exists `choose` neither saves a `--spent default` mark nor waits on a stored one. Meter reads younger than 60 seconds are reused.
22
24
 
23
- `check` prints nothing and exits 3 while every account is below its floor. `run` sets `CLAUDE_CONFIG_DIR` or `CODEX_HOME` for each attempt. A Claude job also starts without the parent session's variables, such as `CLAUDE_CODE_SESSION_ID` and `CLAUDECODE`, so a child started from inside a Claude Code session runs as its own session. `ALL_PARENT_CLAUDE_SESSION_VARIABLES` lists them. It replays the same stdin bytes when a usage limit or start failure leads to another account. Send the prompt on stdin. When the command resolves to a `.cmd` or `.bat` file, the broker refuses an argument that holds a cmd.exe metacharacter and records `start_failed`. It writes the command's stdout to stdout and diagnostics to stderr. A resumed Claude session uses the account bound to its session when that account has room.
25
+ `--require-tier normal` makes a Codex `choose` or `check` wait unless an account reaches the `normal` tier. `--home <path>` makes either command judge that one Codex home alone. A home on a paid plan with readable meters runs, whatever its room, credits or `CODEX_WEEKLY_FLOOR_DISABLED` setting, and reports the tier its meters allow, or `luna` when none does. A home still gives `wait` when its plan is free, missing, blank, unknown or unlisted, when its meters are unread, when it does not reach a required tier such as the one `--require-tier normal` sets, and when a spent mark saved for the roster account with that home, by `run` or `choose --spent`, is still in the future, until that mark's reset, unless the Codex account has spendable credits. A roster account with that home keeps its name, so its mark holds the home unless that account has spendable credits. Any other home reads as an account named for its folder, and a mark is keyed by product, account name and home. So a mark saved for the no-roster default account, named `default`, does not hold `--home <that home>` unless the folder of that home is also named `default`, and a mark saved for an account outside the roster never holds a `--home` answer. After an account leaves the roster, a mark saved while it was in the roster still holds `--home <its home>` only when the account's name equals the name of its resolved home folder. A roster account `Alpha` whose home folder is `alpha`, or whose home folder is a junction to a folder with another name, stops holding `--home <its home>` once it leaves the roster. The broker refuses `--home` for the Claude product and with `--spent`. `check` prints nothing and exits 3 while every account is below its floor. `run` sets `CLAUDE_CONFIG_DIR` or `CODEX_HOME` for each attempt. A Claude job also starts without the parent session's variables, such as `CLAUDE_CODE_SESSION_ID` and `CLAUDECODE`, so a child started from inside a Claude Code session runs as its own session. `ALL_PARENT_CLAUDE_SESSION_VARIABLES` lists them. It replays the same stdin bytes when a usage limit, start failure, or sign-in failure leads to another account. Send the prompt on stdin. When the command resolves to a `.cmd` or `.bat` file, the broker refuses an argument that holds a cmd.exe metacharacter and records `start_failed`. It writes the command's stdout to stdout and diagnostics to stderr. A resumed Claude session uses the account bound to its session when that account has room.
24
26
 
25
27
  The broker stores cached meters, spent marks, and Claude session bindings in one JSON file under `~/.claude/account-broker`. Every broker process for the same user reads that file, so a spent mark pauses that account for every job. A write holds an exclusive lock on the sibling `state.json.lock`, re-reads the file, merges, and swaps in a sibling temporary file with `os.replace`. The merge keeps the latest reset for each spent mark and the newest meter read for each account.
26
28
 
@@ -30,7 +32,7 @@ The broker stores cached meters, spent marks, and Claude session bindings in one
30
32
  | --- | --- |
31
33
  | `0` | `choose` or `check` found an account, or the job exited successfully. |
32
34
  | `3` | No account clears its floor. The decision includes `resets_at`. |
33
- | `4` | A Claude job stopped with `advisor_blocked`. |
35
+ | `4` | A Claude job stopped with `advisor_blocked`, or every Claude account was unusable: each had no token or was signed out. |
34
36
  | `127` | A Codex job timed out, its command could not start while no Codex roster is configured, or the command could not start on any account in the roster. |
35
37
  | Other command code | `run` returns the command's exit code after a served response. |
36
38