claude-dev-env 8.111.5 → 8.112.1
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.
- package/.agents/skills/build-eval/evals/review/README.md +2 -2
- package/.agents/skills/build-eval/evals/review/review_eval_support/account.py +166 -0
- package/.agents/skills/build-eval/evals/review/review_eval_support/config/constants.py +26 -0
- package/.agents/skills/build-eval/evals/review/review_eval_support/execution.py +8 -0
- package/.agents/skills/build-eval/evals/review/test_run.py +261 -0
- package/_shared/advisor/reference/astra-rung.md +13 -5
- package/_shared/advisor/scripts/codex_astra_advisor.py +31 -8
- package/_shared/advisor/scripts/codex_astra_preflight.py +70 -14
- package/_shared/advisor/scripts/config/advisor_scripts_constants/astra_advisor_constants.py +7 -0
- package/_shared/advisor/scripts/tests/test_codex_astra_advisor.py +266 -2
- package/_shared/advisor/scripts/tests/test_codex_astra_preflight.py +114 -8
- package/_shared/pr-loop/scripts/check_convergence.py +5 -1
- package/_shared/pr-loop/scripts/codex_review_account.py +180 -0
- package/_shared/pr-loop/scripts/codex_review_scripts_constants/account_constants.py +28 -0
- package/_shared/pr-loop/scripts/codex_review_scripts_constants/run_constants.py +3 -1
- package/_shared/pr-loop/scripts/run_codex_review.py +144 -15
- package/_shared/pr-loop/scripts/test_check_convergence_codex.py +3 -3
- package/_shared/pr-loop/scripts/test_codex_review_account.py +355 -0
- package/_shared/pr-loop/scripts/test_run_codex_review.py +507 -6
- package/docs/account-broker.md +5 -3
- package/docs/codex-accounts.md +57 -16
- package/docs/rule-guides/question-presentation.md +4 -0
- package/hooks/blocking/final_reply_gate.py +59 -3
- package/hooks/blocking/open_tasks_transcript.py +18 -0
- package/hooks/blocking/test_final_reply_gate.py +160 -0
- package/hooks/features/conduct-gates.md +1 -4
- package/hooks/hooks.json +0 -10
- package/hooks/hooks_constants/final_reply_gate_constants.py +16 -0
- package/hooks/hooks_constants/open_tasks_stop_gate_constants.py +9 -0
- package/package.json +1 -1
- package/rules/question-presentation.md +1 -1
- package/scripts/Sync-RepoMain.ps1 +86 -3
- package/scripts/account_broker.py +50 -25
- package/scripts/account_broker_support.py +54 -3
- package/scripts/codex_account_choice.py +12 -8
- package/scripts/codex_account_chooser.py +110 -0
- package/scripts/codex_account_meters.py +43 -4
- package/scripts/codex_plan_rules.py +156 -0
- package/scripts/dev_env_scripts_constants/account_broker_constants.py +29 -42
- package/scripts/dev_env_scripts_constants/codex_account_constants.py +62 -2
- package/scripts/dev_env_scripts_constants/test_account_broker_constants.py +359 -2
- package/scripts/dev_env_scripts_constants/test_codex_account_constants.py +213 -14
- package/scripts/policy_lint/adapter_configuration.py +0 -5
- package/scripts/policy_lint/config/constants.py +0 -1
- package/scripts/test_account_broker.py +1756 -523
- package/scripts/test_account_broker_support.py +77 -0
- package/scripts/test_codex_account_meters.py +95 -0
- package/scripts/tests/Sync-RepoMain.Tests.ps1 +55 -0
- package/scripts/tests/test_adapter_configuration.py +0 -8
- package/scripts/tests/test_sync_repo_main_mirror.py +60 -0
- package/hooks/blocking/merge_over_review_offer_gate.py +0 -114
- package/hooks/blocking/test_merge_over_review_offer_gate.py +0 -138
- package/hooks/hooks_constants/merge_over_review_offer_gate_constants.py +0 -34
|
@@ -17,11 +17,15 @@
|
|
|
17
17
|
- When the fast-forward fails because the files were already copied in,
|
|
18
18
|
moves HEAD with a mixed reset, which writes no files. It keeps that move
|
|
19
19
|
only when every file the remote changed now matches the remote
|
|
20
|
+
- When a -Mirror tree diverged from the remote, keeps the old tip under
|
|
21
|
+
refs/mirror-backup/, moves HEAD with a mixed reset, and stashes every
|
|
22
|
+
tracked file that still differs from the remote
|
|
20
23
|
- Logs and exits non-zero on skip, diverge, or failure so a Task Scheduler
|
|
21
24
|
history row can surface a problem instead of a silent no-op
|
|
22
25
|
|
|
23
26
|
Exit codes: 0 success, 1 git operation failed, 2 configuration or repo
|
|
24
|
-
problem, 3 skipped by a safety rule, 4 diverged from the remote
|
|
27
|
+
problem, 3 skipped by a safety rule, 4 diverged from the remote (a -Mirror
|
|
28
|
+
tree realigns instead).
|
|
25
29
|
|
|
26
30
|
.PARAMETER RepoPath
|
|
27
31
|
Absolute path to the git working tree. Required.
|
|
@@ -58,6 +62,15 @@
|
|
|
58
62
|
back to the old checkout and the run exits 1. Without the switch, any
|
|
59
63
|
other checkout is skipped.
|
|
60
64
|
|
|
65
|
+
A mirror whose history diverged from the remote, as after a rewrite of the
|
|
66
|
+
remote history, realigns instead of exiting 4. The old tip stays reachable
|
|
67
|
+
as refs/mirror-backup/<yyyy-MM-dd>-<tip>, HEAD and the index move to the
|
|
68
|
+
remote tip with a mixed reset, and every tracked file that still differs is
|
|
69
|
+
stashed as "mirror realign <yyyy-MM-dd>: tree before moving <tip> to
|
|
70
|
+
<remote>/<branch>". Untracked files are never touched. A staged index skips
|
|
71
|
+
the realign. When a step fails, HEAD goes back to the old tip and the run
|
|
72
|
+
exits 1.
|
|
73
|
+
|
|
61
74
|
.PARAMETER LogPath
|
|
62
75
|
Absolute path to the run log (default: $HOME\.claude\logs\sync-repo-main.log).
|
|
63
76
|
#>
|
|
@@ -284,6 +297,67 @@ function Invoke-AdoptCopiedTree {
|
|
|
284
297
|
return $false
|
|
285
298
|
}
|
|
286
299
|
|
|
300
|
+
function Invoke-MirrorRealign {
|
|
301
|
+
<#
|
|
302
|
+
Moves a mirror whose history diverged from the remote onto the remote
|
|
303
|
+
tip. A rewritten remote history leaves a mirror with commits the remote
|
|
304
|
+
no longer holds, and a fast-forward can never reach it again.
|
|
305
|
+
|
|
306
|
+
The old tip is kept under refs/mirror-backup/ first. A mixed reset then
|
|
307
|
+
moves HEAD and the index to the remote tip and writes no files. Every
|
|
308
|
+
tracked file that still differs from the remote is stashed, which puts the
|
|
309
|
+
remote content in its place and keeps the old content in the stash list.
|
|
310
|
+
Untracked files stay. A failure after the reset puts HEAD back on the old
|
|
311
|
+
tip, so the next run meets the same state and tries again.
|
|
312
|
+
#>
|
|
313
|
+
param(
|
|
314
|
+
[Parameter(Mandatory)]
|
|
315
|
+
[string]$LocalTip,
|
|
316
|
+
[Parameter(Mandatory)]
|
|
317
|
+
[string]$RemoteRef
|
|
318
|
+
)
|
|
319
|
+
$stagedResult = Invoke-Git -Arguments @('diff', '--cached', '--quiet')
|
|
320
|
+
if ($stagedResult.ExitCode -ne 0) {
|
|
321
|
+
Write-SyncLog -Level 'ERROR' -Message 'realign skipped: the index holds staged changes'
|
|
322
|
+
return $false
|
|
323
|
+
}
|
|
324
|
+
$backupRef = 'refs/mirror-backup/{0}-{1}' -f (Get-Date -Format 'yyyy-MM-dd'), $LocalTip.Substring(0, 12)
|
|
325
|
+
$backupResult = Invoke-Git -Arguments @('update-ref', $backupRef, $LocalTip)
|
|
326
|
+
if ($backupResult.ExitCode -ne 0) {
|
|
327
|
+
Write-SyncLog -Level 'ERROR' -Message "realign skipped: cannot keep the old tip under ${backupRef}: $($backupResult.Output)"
|
|
328
|
+
return $false
|
|
329
|
+
}
|
|
330
|
+
$resetResult = Invoke-Git -Arguments @('reset', '-q', $RemoteRef)
|
|
331
|
+
if ($resetResult.ExitCode -ne 0) {
|
|
332
|
+
Write-SyncLog -Level 'ERROR' -Message "realign skipped: mixed reset failed: $($resetResult.Output)"
|
|
333
|
+
return $false
|
|
334
|
+
}
|
|
335
|
+
$differResult = Invoke-Git -Arguments @('diff', '--name-only', '--no-renames', '-z')
|
|
336
|
+
$stashNote = 'every tracked file already matched'
|
|
337
|
+
$failure = if ($differResult.ExitCode -ne 0) { "cannot list the files that differ: $($differResult.Output)" }
|
|
338
|
+
if (-not $failure) {
|
|
339
|
+
$allDifferingPaths = @(Get-NulSeparatedPaths -Output $differResult.Output)
|
|
340
|
+
if ($allDifferingPaths.Count -gt 0) {
|
|
341
|
+
$realignStashMessage = 'mirror realign {0}: tree before moving {1} to {2}' -f (Get-Date -Format 'yyyy-MM-dd'), $LocalTip, $RemoteRef
|
|
342
|
+
$stashResult = Invoke-Git -Arguments @('stash', 'push', '-m', $realignStashMessage)
|
|
343
|
+
if ($stashResult.ExitCode -ne 0) {
|
|
344
|
+
$failure = "stashing $($allDifferingPaths.Count) differing file(s) failed: $($stashResult.Output)"
|
|
345
|
+
}
|
|
346
|
+
else {
|
|
347
|
+
$stashNote = "$($allDifferingPaths.Count) differing file(s) are stashed as '$realignStashMessage'"
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
if ($failure) {
|
|
352
|
+
$revertResult = Invoke-Git -Arguments @('reset', '-q', $LocalTip)
|
|
353
|
+
$revertNote = if ($revertResult.ExitCode -eq 0) { "HEAD is back at $LocalTip" } else { "putting HEAD back at $LocalTip also failed: $($revertResult.Output)" }
|
|
354
|
+
Write-SyncLog -Level 'ERROR' -Message "realign failed, $failure; $revertNote"
|
|
355
|
+
return $false
|
|
356
|
+
}
|
|
357
|
+
Write-SyncLog -Level 'MIRROR' -Message "realigned onto ${RemoteRef}: old tip $LocalTip is kept as $backupRef; $stashNote"
|
|
358
|
+
return $true
|
|
359
|
+
}
|
|
360
|
+
|
|
287
361
|
function Get-RunLockName {
|
|
288
362
|
$lockPath = [System.IO.Path]::TrimEndingDirectorySeparator([System.IO.Path]::GetFullPath($RepoPath))
|
|
289
363
|
$resolveLinkTarget = [System.IO.Directory].GetMethod('ResolveLinkTarget', [type[]]([string], [bool]))
|
|
@@ -361,8 +435,17 @@ try {
|
|
|
361
435
|
$ancestorResult = Invoke-Git -Arguments @('merge-base', '--is-ancestor', $Branch, "$Remote/$Branch")
|
|
362
436
|
if ($ancestorResult.ExitCode -ne 0) {
|
|
363
437
|
$countResult = Invoke-Git -Arguments @('rev-list', '--left-right', '--count', "${Branch}...${Remote}/${Branch}")
|
|
364
|
-
|
|
365
|
-
|
|
438
|
+
if (-not $Mirror) {
|
|
439
|
+
Write-SyncLog -Level 'ERROR' -Message "diverged from $Remote/$Branch (counts=$($countResult.Output)); fast-forward refused. local=$localTip remote=$remoteTip"
|
|
440
|
+
exit 4
|
|
441
|
+
}
|
|
442
|
+
Write-SyncLog -Level 'MIRROR' -Message "diverged from $Remote/$Branch (counts=$($countResult.Output)); realigning the mirror. local=$localTip remote=$remoteTip"
|
|
443
|
+
if (-not (Invoke-MirrorRealign -LocalTip $localTip -RemoteRef "$Remote/$Branch")) {
|
|
444
|
+
exit 1
|
|
445
|
+
}
|
|
446
|
+
$subject = Get-GitDecoration -Arguments @('log', '-1', '--format=%h %s') -Placeholder '<subject unavailable>'
|
|
447
|
+
Write-SyncLog -Level 'OK' -Message "$Branch $localTip -> $remoteTip realigned | $subject"
|
|
448
|
+
exit 0
|
|
366
449
|
}
|
|
367
450
|
|
|
368
451
|
$didStash = $false
|
|
@@ -15,6 +15,7 @@ from typing import Mapping, Sequence
|
|
|
15
15
|
|
|
16
16
|
import account_broker_support as support
|
|
17
17
|
import codex_account_meters
|
|
18
|
+
from codex_account_chooser import choose_codex
|
|
18
19
|
from account_broker_support import (
|
|
19
20
|
all_product_adapters,
|
|
20
21
|
Account,
|
|
@@ -43,10 +44,10 @@ from account_broker_support import (
|
|
|
43
44
|
from dev_env_scripts_constants.account_broker_constants import (
|
|
44
45
|
_account_reset,
|
|
45
46
|
_choose_claude,
|
|
46
|
-
_choose_codex,
|
|
47
47
|
_wait_decision,
|
|
48
48
|
ALL_PARENT_CLAUDE_SESSION_VARIABLES,
|
|
49
49
|
ALL_SIGN_IN_FAILURE_SIGNATURES,
|
|
50
|
+
ALL_CHOOSE_AND_CHECK_ACTIONS,
|
|
50
51
|
COMMAND_MISSING_EXIT_CODE,
|
|
51
52
|
NO_USABLE_ACCOUNT_EXIT_CODE,
|
|
52
53
|
NO_USABLE_REASON_SEPARATOR,
|
|
@@ -60,39 +61,55 @@ from dev_env_scripts_constants.account_broker_constants import (
|
|
|
60
61
|
utc_time_text as _time_text,
|
|
61
62
|
)
|
|
62
63
|
from dev_env_scripts_constants.codex_account_constants import (
|
|
63
|
-
|
|
64
|
-
|
|
64
|
+
ALL_TIERS_BEST_FIRST,
|
|
65
|
+
HOME_CODEX_ONLY_MESSAGE,
|
|
66
|
+
HOME_WITH_SPENT_MESSAGE,
|
|
65
67
|
NO_ROSTER_ACCOUNT_NAME,
|
|
66
|
-
|
|
68
|
+
REQUIRE_TIER_ARGUMENT,
|
|
67
69
|
)
|
|
68
70
|
|
|
69
71
|
|
|
72
|
+
def _holds_codex_credits(product: Product, reading: Reading) -> bool:
|
|
73
|
+
return product is Product.CODEX and reading.meters is not None and reading.meters.has_spendable_credits
|
|
74
|
+
|
|
75
|
+
|
|
70
76
|
def choose_from_readings(
|
|
71
77
|
product: Product,
|
|
72
78
|
all_readings: Sequence[Reading],
|
|
73
79
|
*,
|
|
74
80
|
now: datetime,
|
|
75
81
|
all_spent_accounts: frozenset[Account] = frozenset(),
|
|
82
|
+
all_attempted_accounts: frozenset[Account] = frozenset(),
|
|
76
83
|
preferred_command: str | None = None,
|
|
77
84
|
all_spent_resets: Mapping[Account, datetime] | None = None,
|
|
85
|
+
required_tier: str | None = None,
|
|
86
|
+
is_home_named: bool = False,
|
|
78
87
|
) -> Decision:
|
|
79
88
|
"""Choose an account or a wait.
|
|
80
89
|
|
|
81
90
|
Args:
|
|
82
91
|
product: Account product.
|
|
83
92
|
all_readings: Roster and meter readings.
|
|
93
|
+
all_spent_accounts: Accounts a saved mark holds, or that spent an attempt in this run. A Codex account with spendable credits is still chosen unless it spent an attempt in this run.
|
|
94
|
+
all_attempted_accounts: Accounts that spent an attempt in this run. Credits do not keep them.
|
|
95
|
+
required_tier: Codex tier the job needs, or None for any tier. Claude choices ignore it.
|
|
96
|
+
is_home_named: True when the caller named one Codex home, which runs on a paid plan
|
|
97
|
+
whatever its room, unless ``required_tier`` is above the tier it reaches.
|
|
98
|
+
Claude choices ignore it.
|
|
84
99
|
|
|
85
100
|
Returns:
|
|
86
101
|
A run or wait decision.
|
|
87
102
|
"""
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
103
|
+
all_available = [
|
|
104
|
+
each_reading
|
|
105
|
+
for each_reading in all_readings
|
|
106
|
+
if each_reading.account not in all_attempted_accounts
|
|
107
|
+
and (each_reading.account not in all_spent_accounts or _holds_codex_credits(product, each_reading))
|
|
108
|
+
]
|
|
92
109
|
selected = (
|
|
93
110
|
_choose_claude(all_available, preferred_command)
|
|
94
111
|
if product is Product.CLAUDE
|
|
95
|
-
else
|
|
112
|
+
else choose_codex(all_available, required_tier, is_home_named=is_home_named)
|
|
96
113
|
)
|
|
97
114
|
return selected or _wait_decision(all_readings, now, all_spent_accounts, all_spent_resets or {})
|
|
98
115
|
|
|
@@ -237,6 +254,7 @@ class _RunContext:
|
|
|
237
254
|
start_failure_text: str = ""
|
|
238
255
|
live_log: Path | None = None
|
|
239
256
|
all_sign_in_failures: dict[str, str] = field(default_factory=dict)
|
|
257
|
+
all_attempted_accounts: set[Account] = field(default_factory=set)
|
|
240
258
|
|
|
241
259
|
|
|
242
260
|
def _prepare_run(
|
|
@@ -328,11 +346,11 @@ def _wait_outcome(context: _RunContext, decision: Decision) -> JobOutcome:
|
|
|
328
346
|
def _record_spent_attempt(context: _RunContext, account: Account, status: str, returncode: int | None) -> None:
|
|
329
347
|
context.all_attempts.append((account.name, status))
|
|
330
348
|
context.report.events.append({"type": "attempt", "account": account.name, "status": status, "exit_code": returncode})
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
349
|
+
reading = next(each_reading for each_reading in context.all_readings if each_reading.account == account)
|
|
350
|
+
context.all_spent_accounts.add(account)
|
|
351
|
+
context.all_attempted_accounts.add(account)
|
|
352
|
+
if status == "usage_limited":
|
|
353
|
+
context.all_spent_resets[account] = _mark_spent(context.all_state, reading, context.now)
|
|
336
354
|
|
|
337
355
|
|
|
338
356
|
def _invoke(context: _RunContext, account: Account) -> subprocess.CompletedProcess[str]:
|
|
@@ -378,10 +396,6 @@ def _attempt_once(context: _RunContext, decision: Decision) -> JobOutcome | None
|
|
|
378
396
|
except OSError as error:
|
|
379
397
|
_record_spent_attempt(context, account, "start_failed", COMMAND_MISSING_EXIT_CODE)
|
|
380
398
|
context.start_failure_text = str(error)
|
|
381
|
-
if not context.all_readings:
|
|
382
|
-
context.report.final_decision = decision
|
|
383
|
-
final_status = "advisor_blocked" if context.product is Product.CLAUDE else "start_failed"
|
|
384
|
-
return JobOutcome(COMMAND_MISSING_EXIT_CODE, "", str(error), account.name, tuple(context.all_attempts), final_status, None, None)
|
|
385
399
|
return None
|
|
386
400
|
combined = f"{completion.stdout}{completion.stderr}".casefold()
|
|
387
401
|
is_limited = completion.returncode != 0 and any(
|
|
@@ -389,9 +403,6 @@ def _attempt_once(context: _RunContext, decision: Decision) -> JobOutcome | None
|
|
|
389
403
|
)
|
|
390
404
|
if is_limited:
|
|
391
405
|
_record_spent_attempt(context, account, "usage_limited", completion.returncode)
|
|
392
|
-
if not context.all_readings:
|
|
393
|
-
waiting = Decision("wait", None, context.now + timedelta(hours=1), "no account has room", "wait")
|
|
394
|
-
return _wait_outcome(context, waiting)
|
|
395
406
|
return None
|
|
396
407
|
if context.product is Product.CLAUDE and _is_sign_in_failure(completion):
|
|
397
408
|
_record_sign_in_failure(context, account, completion)
|
|
@@ -408,7 +419,7 @@ def _execute(
|
|
|
408
419
|
context = _prepare_run(product, all_argv, now, timeout_seconds, stdin_text, cwd, encoding, errors)
|
|
409
420
|
context.live_log = live_log
|
|
410
421
|
while True:
|
|
411
|
-
picked = choose_from_readings(product, context.all_readings, now=now, all_spent_accounts=frozenset(context.all_spent_accounts), preferred_command=context.preferred_command, all_spent_resets=context.all_spent_resets)
|
|
422
|
+
picked = choose_from_readings(product, context.all_readings, now=now, all_spent_accounts=frozenset(context.all_spent_accounts), all_attempted_accounts=frozenset(context.all_attempted_accounts), preferred_command=context.preferred_command, all_spent_resets=context.all_spent_resets)
|
|
412
423
|
decision = _with_outside_spent_marks(picked, _outside_roster_resets(product, context.all_readings, context.all_state, now))
|
|
413
424
|
context.report.events.append({"type": "pick", "decision": decision_payload(decision)})
|
|
414
425
|
if decision.account is None:
|
|
@@ -439,6 +450,9 @@ def _parser() -> argparse.ArgumentParser:
|
|
|
439
450
|
command = commands.add_parser(each_action)
|
|
440
451
|
all_product_choices = [Product.CODEX.value] if each_action == "limits" else [each_product.value for each_product in Product]
|
|
441
452
|
command.add_argument("--product", choices=all_product_choices, required=True)
|
|
453
|
+
if each_action in ALL_CHOOSE_AND_CHECK_ACTIONS:
|
|
454
|
+
command.add_argument(REQUIRE_TIER_ARGUMENT, choices=ALL_TIERS_BEST_FIRST, default=None)
|
|
455
|
+
command.add_argument("--home", type=Path, default=None)
|
|
442
456
|
if each_action == "choose":
|
|
443
457
|
command.add_argument("--spent", action="append", default=[])
|
|
444
458
|
if each_action == "limits":
|
|
@@ -514,15 +528,26 @@ def _run_cli(product: Product, parsed: argparse.Namespace, parser: argparse.Argu
|
|
|
514
528
|
return 4 if outcome.status == "advisor_blocked" else outcome.returncode
|
|
515
529
|
|
|
516
530
|
|
|
531
|
+
def _refuse_home_misuse(product: Product, parsed: argparse.Namespace) -> None:
|
|
532
|
+
if parsed.home is None:
|
|
533
|
+
return
|
|
534
|
+
if product is not Product.CODEX:
|
|
535
|
+
raise BrokerConfigurationError(HOME_CODEX_ONLY_MESSAGE)
|
|
536
|
+
if getattr(parsed, "spent", None):
|
|
537
|
+
raise BrokerConfigurationError(HOME_WITH_SPENT_MESSAGE)
|
|
538
|
+
|
|
539
|
+
|
|
517
540
|
def _choose_cli(product: Product, parsed: argparse.Namespace) -> int:
|
|
541
|
+
_refuse_home_misuse(product, parsed)
|
|
518
542
|
now = datetime.now(timezone.utc)
|
|
519
543
|
all_state = _load_state(broker_state_path())
|
|
520
|
-
all_readings = read_accounts(product, all_state=all_state, now=now)
|
|
544
|
+
all_readings = read_accounts(product, all_state=all_state, now=now, home=parsed.home)
|
|
521
545
|
if parsed.action == "choose" and parsed.spent:
|
|
522
546
|
_save_spent_arguments(parsed.spent, all_readings, all_state, now, product)
|
|
523
547
|
spent, resets = _spent_for_readings(all_readings, all_state, now)
|
|
524
|
-
decision = choose_from_readings(product, all_readings, now=now, all_spent_accounts=spent, all_spent_resets=resets)
|
|
525
|
-
|
|
548
|
+
decision = choose_from_readings(product, all_readings, now=now, all_spent_accounts=spent, all_spent_resets=resets, required_tier=parsed.require_tier, is_home_named=parsed.home is not None)
|
|
549
|
+
if parsed.home is None:
|
|
550
|
+
decision = _with_outside_spent_marks(decision, _outside_roster_resets(product, all_readings, all_state, now))
|
|
526
551
|
if parsed.action == "choose":
|
|
527
552
|
print(json.dumps({"decision": decision_payload(decision), "accounts": readings_payload(all_readings), "state_path": str(broker_state_path())}))
|
|
528
553
|
return WAIT_EXIT_CODE if decision.action == "wait" else 0
|
|
@@ -72,6 +72,8 @@ from dev_env_scripts_constants.codex_account_constants import (
|
|
|
72
72
|
CODEX_ACCOUNT_LAUNCHERS_FILE_NAME,
|
|
73
73
|
CODEX_ACCOUNT_PROFILES_ENVIRONMENT_VARIABLE,
|
|
74
74
|
CODEX_HOME_ENVIRONMENT_VARIABLE,
|
|
75
|
+
MAIN_CODEX_HOME_DIRECTORY_NAME,
|
|
76
|
+
NO_ROSTER_ACCOUNT_NAME,
|
|
75
77
|
)
|
|
76
78
|
from dev_env_scripts_constants.shared_tree_constants import CLAUDE_CONFIG_DIR_ENV_VAR
|
|
77
79
|
from shared_tree_paths import resolve_shared_process_tree_scripts_directory
|
|
@@ -325,6 +327,9 @@ def read_codex_account_meters(account: Account) -> Meters:
|
|
|
325
327
|
FULL_PERCENT - weekly_window.used_percent if weekly_window else None,
|
|
326
328
|
weekly_window.resets_at if weekly_window else None,
|
|
327
329
|
usage.plan_type,
|
|
330
|
+
usage.has_credits,
|
|
331
|
+
usage.is_credits_unlimited,
|
|
332
|
+
usage.credit_balance,
|
|
328
333
|
)
|
|
329
334
|
|
|
330
335
|
|
|
@@ -511,6 +516,9 @@ def _meter_payload(meters: Meters | None) -> dict[str, object] | None:
|
|
|
511
516
|
"weekly_percent_left": meters.weekly_percent_left,
|
|
512
517
|
"weekly_resets_at": utc_time_text(meters.weekly_resets_at),
|
|
513
518
|
"plan_type": meters.plan_type,
|
|
519
|
+
"has_credits": meters.has_credits,
|
|
520
|
+
"is_credits_unlimited": meters.is_credits_unlimited,
|
|
521
|
+
"credit_balance": meters.credit_balance,
|
|
514
522
|
}
|
|
515
523
|
|
|
516
524
|
|
|
@@ -521,12 +529,17 @@ def _meters_from_payload(raw_meters: object) -> Meters | None:
|
|
|
521
529
|
if any(each_percent is not None and not isinstance(each_percent, (int, float)) for each_percent in all_percentages):
|
|
522
530
|
return None
|
|
523
531
|
plan_type = raw_meters.get("plan_type")
|
|
532
|
+
credit_balance = raw_meters.get("credit_balance")
|
|
533
|
+
is_balance_number = isinstance(credit_balance, (int, float)) and not isinstance(credit_balance, bool)
|
|
524
534
|
return Meters(
|
|
525
535
|
all_percentages[0],
|
|
526
536
|
parse_utc_time(raw_meters.get("session_resets_at")),
|
|
527
537
|
all_percentages[1],
|
|
528
538
|
parse_utc_time(raw_meters.get("weekly_resets_at")),
|
|
529
539
|
plan_type if isinstance(plan_type, str) else None,
|
|
540
|
+
raw_meters.get("has_credits") is True,
|
|
541
|
+
raw_meters.get("is_credits_unlimited") is True,
|
|
542
|
+
float(credit_balance) if is_balance_number else None,
|
|
530
543
|
)
|
|
531
544
|
|
|
532
545
|
|
|
@@ -573,7 +586,42 @@ def _last_good_meters(all_cached_fields: dict[str, object], now: datetime) -> tu
|
|
|
573
586
|
return meters, measured_at
|
|
574
587
|
|
|
575
588
|
|
|
576
|
-
def
|
|
589
|
+
def codex_default_account() -> Account:
|
|
590
|
+
"""Return the account for the default Codex home, read when no roster is configured.
|
|
591
|
+
|
|
592
|
+
::
|
|
593
|
+
|
|
594
|
+
CODEX_HOME "C:/work/codex-a" -> the home C:/work/codex-a
|
|
595
|
+
CODEX_HOME unset, "" or " " -> the home ~/.codex
|
|
596
|
+
|
|
597
|
+
Returns:
|
|
598
|
+
The account named ``default``. Its home is ``CODEX_HOME`` without its
|
|
599
|
+
padding, or ``~/.codex`` when the variable is unset or blank.
|
|
600
|
+
"""
|
|
601
|
+
exported_home = os.environ.get(CODEX_HOME_ENVIRONMENT_VARIABLE, "").strip()
|
|
602
|
+
home = Path(exported_home or Path.home() / MAIN_CODEX_HOME_DIRECTORY_NAME).resolve()
|
|
603
|
+
return Account(Product.CODEX, NO_ROSTER_ACCOUNT_NAME, home, True)
|
|
604
|
+
|
|
605
|
+
|
|
606
|
+
def _account_for_home(all_roster: Sequence[Account], home: Path) -> Account:
|
|
607
|
+
resolved_home = home.expanduser().resolve()
|
|
608
|
+
roster_account = next(
|
|
609
|
+
(each_account for each_account in all_roster if os.path.normcase(each_account.home) == os.path.normcase(resolved_home)),
|
|
610
|
+
None,
|
|
611
|
+
)
|
|
612
|
+
return roster_account or Account(Product.CODEX, resolved_home.name or NO_ROSTER_ACCOUNT_NAME, resolved_home)
|
|
613
|
+
|
|
614
|
+
|
|
615
|
+
def _accounts_to_read(product: Product, adapter: ProductAdapter, home: Path | None) -> Sequence[Account]:
|
|
616
|
+
all_roster = adapter.load_accounts()
|
|
617
|
+
if home is not None:
|
|
618
|
+
return (_account_for_home(all_roster, home),)
|
|
619
|
+
if product is Product.CODEX and not all_roster:
|
|
620
|
+
return (codex_default_account(),)
|
|
621
|
+
return all_roster
|
|
622
|
+
|
|
623
|
+
|
|
624
|
+
def read_accounts(product: Product, adapter: ProductAdapter | None = None, *, all_state: dict[str, object] | None = None, now: datetime | None = None, home: Path | None = None) -> tuple[Reading, ...]:
|
|
577
625
|
"""Read account meters with a 60-second cache.
|
|
578
626
|
|
|
579
627
|
Args:
|
|
@@ -581,16 +629,19 @@ def read_accounts(product: Product, adapter: ProductAdapter | None = None, *, al
|
|
|
581
629
|
adapter: Injected account and meter readers.
|
|
582
630
|
all_state: Mutable broker state document.
|
|
583
631
|
now: Clock instant used for cache age.
|
|
632
|
+
home: Codex home to read alone, not the roster. A roster account
|
|
633
|
+
with that home keeps its name; any other home reads as one extra account.
|
|
584
634
|
|
|
585
635
|
Returns:
|
|
586
|
-
Account readings in roster order.
|
|
636
|
+
Account readings in roster order. A Codex product with no roster reads
|
|
637
|
+
its default home as the one account.
|
|
587
638
|
"""
|
|
588
639
|
active = adapter or all_product_adapters[product]
|
|
589
640
|
current = now or datetime.now(timezone.utc)
|
|
590
641
|
all_cache = all_state.get("meters", {}) if all_state is not None else {}
|
|
591
642
|
all_readings: list[Reading] = []
|
|
592
643
|
is_updated = False
|
|
593
|
-
for each_account in active
|
|
644
|
+
for each_account in _accounts_to_read(product, active, home):
|
|
594
645
|
reading, did_read = _read_one_account(each_account, active, all_cache, current)
|
|
595
646
|
all_readings.append(reading)
|
|
596
647
|
is_updated = is_updated or did_read
|
|
@@ -2,12 +2,16 @@
|
|
|
2
2
|
"""Keep each Codex account's home and launcher ready.
|
|
3
3
|
|
|
4
4
|
Each Codex account signs in under its own Codex home in
|
|
5
|
-
``~/.codex-profiles/<name>``. The account list names them
|
|
5
|
+
``~/.codex-profiles/<name>``. The account list names them. The broker ranks
|
|
6
|
+
them by plan and room, and list order breaks only an exact tie. The list is the
|
|
6
7
|
``CODEX_ACCOUNT_PROFILES`` environment variable, comma-separated, else the saved
|
|
7
|
-
``account-launchers.json`` list under the profiles root. With neither,
|
|
8
|
-
``codex-1`` through ``codex-4``
|
|
9
|
-
|
|
10
|
-
|
|
8
|
+
``account-launchers.json`` list under the profiles root. With neither, ``sync``
|
|
9
|
+
falls back to ``codex-1`` through ``codex-4`` and ``install`` has no accounts.
|
|
10
|
+
The broker's ``choose`` and ``check`` fall back to those four only when
|
|
11
|
+
``CODEX_ACCOUNT_PROFILES`` holds only separators and no saved list names an
|
|
12
|
+
account; with the variable unset or blank they read the default Codex home as
|
|
13
|
+
the account ``default``. An environment roster that differs from the saved file
|
|
14
|
+
is saved to it, so a process without the variable reads the same roster.
|
|
11
15
|
|
|
12
16
|
Three commands::
|
|
13
17
|
|
|
@@ -196,7 +200,7 @@ def _save_environment_roster(
|
|
|
196
200
|
|
|
197
201
|
|
|
198
202
|
def saved_codex_account_names(profiles_root: Path) -> tuple[str, ...]:
|
|
199
|
-
"""Name the account list, in
|
|
203
|
+
"""Name the account list, in roster order, without duplicates.
|
|
200
204
|
|
|
201
205
|
::
|
|
202
206
|
|
|
@@ -222,7 +226,7 @@ def saved_codex_account_names(profiles_root: Path) -> tuple[str, ...]:
|
|
|
222
226
|
|
|
223
227
|
|
|
224
228
|
def codex_account_names(profiles_root: Path) -> tuple[str, ...]:
|
|
225
|
-
"""Name the accounts the broker and setup commands use, in
|
|
229
|
+
"""Name the accounts the broker and setup commands use, in roster order.
|
|
226
230
|
|
|
227
231
|
Args:
|
|
228
232
|
profiles_root: The directory that holds every account's Codex home.
|
|
@@ -241,7 +245,7 @@ def save_codex_account_names(profiles_root: Path, all_names: Sequence[str]) -> N
|
|
|
241
245
|
|
|
242
246
|
Args:
|
|
243
247
|
profiles_root: The directory that holds every account's Codex home.
|
|
244
|
-
all_names: The account names in
|
|
248
|
+
all_names: The account names in roster order.
|
|
245
249
|
"""
|
|
246
250
|
profiles_root.mkdir(parents=True, exist_ok=True)
|
|
247
251
|
roster_text = json.dumps(list(all_names), indent=ROSTER_JSON_INDENT) + "\n"
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"""Choose the Codex account a job runs on from the readings of the roster.
|
|
2
|
+
|
|
3
|
+
::
|
|
4
|
+
|
|
5
|
+
pro 5% left, team 90% left, no tier required -> pro, tier luna
|
|
6
|
+
the same roster, normal tier required -> team, tier normal
|
|
7
|
+
named team home, 0.5% of its week left -> that home, tier luna
|
|
8
|
+
|
|
9
|
+
A Pro plan account that can run comes before every account on another plan. A
|
|
10
|
+
named home on a paid plan runs whatever its room, credits or floors. It takes
|
|
11
|
+
the tier its meters allow, or the lowest tier when none allows it. A required
|
|
12
|
+
tier still applies, so a named home below it does not run.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
from collections.abc import Sequence
|
|
18
|
+
|
|
19
|
+
from codex_plan_rules import codex_tier, is_pro_plan, is_refused_plan
|
|
20
|
+
from dev_env_scripts_constants.account_broker_constants import (
|
|
21
|
+
Decision,
|
|
22
|
+
Reading,
|
|
23
|
+
_rank_key,
|
|
24
|
+
)
|
|
25
|
+
from dev_env_scripts_constants.codex_account_constants import (
|
|
26
|
+
ALL_TIERS_BEST_FIRST,
|
|
27
|
+
CREDITS_REASON_TEMPLATE,
|
|
28
|
+
NAMED_HOME_REASON_TEMPLATE,
|
|
29
|
+
NORMAL_TIER_MINIMUM_PERCENT_LEFT,
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _run_reason(reading: Reading) -> str:
|
|
34
|
+
name = reading.account.name
|
|
35
|
+
percent_left = reading.meters.tightest_percent_left
|
|
36
|
+
if (
|
|
37
|
+
reading.meters.has_spendable_credits
|
|
38
|
+
and percent_left <= NORMAL_TIER_MINIMUM_PERCENT_LEFT
|
|
39
|
+
):
|
|
40
|
+
return CREDITS_REASON_TEMPLATE.format(name=name, percent=percent_left)
|
|
41
|
+
return f"{name} has {percent_left:g}% left"
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _choose_tier(all_candidates: Sequence[Reading], tier: str) -> Decision | None:
|
|
45
|
+
for each_reading in all_candidates:
|
|
46
|
+
if codex_tier(each_reading.meters) == tier:
|
|
47
|
+
return Decision(
|
|
48
|
+
"run", each_reading.account, None, _run_reason(each_reading), tier
|
|
49
|
+
)
|
|
50
|
+
return None
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _accepted_tiers(required_tier: str | None) -> tuple[str, ...]:
|
|
54
|
+
if required_tier is None:
|
|
55
|
+
return ALL_TIERS_BEST_FIRST
|
|
56
|
+
return ALL_TIERS_BEST_FIRST[: ALL_TIERS_BEST_FIRST.index(required_tier) + 1]
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _choose_named_home(all_available: Sequence[Reading], required_tier: str | None) -> Decision | None:
|
|
60
|
+
for each_reading in all_available:
|
|
61
|
+
if each_reading.meters is None or is_refused_plan(each_reading.meters):
|
|
62
|
+
continue
|
|
63
|
+
allowed_tier = codex_tier(each_reading.meters)
|
|
64
|
+
tier = allowed_tier or ALL_TIERS_BEST_FIRST[-1]
|
|
65
|
+
if tier not in _accepted_tiers(required_tier):
|
|
66
|
+
continue
|
|
67
|
+
reason = (
|
|
68
|
+
_run_reason(each_reading)
|
|
69
|
+
if allowed_tier
|
|
70
|
+
else NAMED_HOME_REASON_TEMPLATE.format(name=each_reading.account.name)
|
|
71
|
+
)
|
|
72
|
+
return Decision("run", each_reading.account, None, reason, tier)
|
|
73
|
+
return None
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def choose_codex(
|
|
77
|
+
all_available: Sequence[Reading],
|
|
78
|
+
required_tier: str | None = None,
|
|
79
|
+
*,
|
|
80
|
+
is_home_named: bool = False,
|
|
81
|
+
) -> Decision | None:
|
|
82
|
+
"""Choose the Codex account for a new job, Pro plan accounts first.
|
|
83
|
+
|
|
84
|
+
::
|
|
85
|
+
|
|
86
|
+
roster, team 0.5% of its week left -> None, the job waits
|
|
87
|
+
named home, team 0.5% of its week left -> run on that home, tier luna
|
|
88
|
+
named home, free plan or unread meters, any room -> None
|
|
89
|
+
|
|
90
|
+
Args:
|
|
91
|
+
all_available: Readings the caller left available: accounts not spent, or spent Codex accounts with spendable credits, and not already tried in this run.
|
|
92
|
+
required_tier: The lowest tier the caller accepts, or None for any tier.
|
|
93
|
+
is_home_named: True when the caller named one Codex home, so its reading
|
|
94
|
+
runs on any paid plan whatever its room, credits or floors, unless
|
|
95
|
+
``required_tier`` is above the tier it reaches.
|
|
96
|
+
|
|
97
|
+
Returns:
|
|
98
|
+
A run decision, or None when no account reaches an accepted tier.
|
|
99
|
+
"""
|
|
100
|
+
if is_home_named:
|
|
101
|
+
return _choose_named_home(all_available, required_tier)
|
|
102
|
+
all_candidates = sorted(all_available, key=_rank_key)
|
|
103
|
+
all_pro_candidates = [each_reading for each_reading in all_candidates if is_pro_plan(each_reading.meters)]
|
|
104
|
+
all_other_candidates = [each_reading for each_reading in all_candidates if not is_pro_plan(each_reading.meters)]
|
|
105
|
+
for each_group in (all_pro_candidates, all_other_candidates):
|
|
106
|
+
for each_tier in _accepted_tiers(required_tier):
|
|
107
|
+
chosen = _choose_tier(each_group, each_tier)
|
|
108
|
+
if chosen is not None:
|
|
109
|
+
return chosen
|
|
110
|
+
return None
|