claude-dev-env 8.126.2 → 8.126.4

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.
@@ -11,7 +11,7 @@ User-level rule: applies to **every** git repo that uses GitHub with `gh`. Small
11
11
 
12
12
  ### Workflow decision tree
13
13
 
14
- **When to use stacked PRs:** Feature B depends on Feature A's implementation. See the Delivery section of `~/.claude/docs/rule-guides/verified-work.md`.
14
+ **When to use stacked PRs:** Feature B depends on Feature A's implementation. See the Delivery section of `~/.claude/docs/rule-guides/verified-work.md`. To decide where to cut, or to split an open PR, read [the slice test](reference/split-a-pull-request.md).
15
15
 
16
16
  **When to extract shared infrastructure first:** Multiple features need same utilities/helpers
17
17
 
@@ -0,0 +1,26 @@
1
+ # Split a pull request into slices
2
+
3
+ A slice is worth its own pull request when all four tests hold:
4
+
5
+ 1. It merges alone and leaves the trunk working.
6
+ 2. It has its own proof: a test or command that fails without the slice and passes with it.
7
+ 3. It reverts alone.
8
+ 4. One sentence states its purpose, and a reviewer can judge it without reading later levels. A slice that needs two sentences is usually two slices.
9
+
10
+ A cut by folder, file count, or line cap that fails these tests is cosmetic. Merge it back. Fewer slices is a valid answer, and so is one pull request with a stated reason.
11
+
12
+ Split when the change carries more than one purpose, or when one small part carries the behaviour change and its risk while the rest is library, data, or docs. Isolate the part that switches the behaviour on, so its revert is small.
13
+
14
+ Try the cheaper move first. Mark generated or data files that swell the diff with a `linguist-generated` line in `.gitattributes`, then judge the size again.
15
+
16
+ Decide the slices when you write the plan. The Delivery section of `~/.claude/docs/rule-guides/verified-work.md` already commits each verified piece as its own level. The steps below repair a pull request where that did not happen.
17
+
18
+ ## Split a pull request that is already open
19
+
20
+ 1. Pin the head SHA, and stop if it moves. Build the new branches from it. Never rewrite or push to a branch another session or person owns. The owner closes the original.
21
+ 2. Read the body, the open review threads, and the latest review findings, and map each open finding to the slice it lands in.
22
+ 3. Sort hunks by purpose. One file can hold hunks for two slices. Check imports across each seam before you fix the order, and put foundational work at the bottom.
23
+ 4. Post the plan: the slices in order, the purpose sentence and proof command for each, and the cuts that failed the tests. Then get the owner's go before you build.
24
+ 5. Change no code during the split. The tree at the top of the stack equals the tree at the pinned head, so `git diff <pinned-sha> <tip> --stat` prints nothing.
25
+ 6. Prove each level alone, as [each stack level stands on its own](../SKILL.md#each-stack-level-stands-on-its-own) describes. Where CI runs only on the stack tip, a lower level has no verdict until you run its checks.
26
+ 7. Each new pull request links the original pull request and carries its own proof. Approvals do not carry over, so name the approvals each one still needs.
@@ -505,7 +505,7 @@ def _broker_completion(
505
505
  Product.CODEX, all_readings, now=BROKER_CLOCK, required_tier=required_tier
506
506
  )
507
507
  answer = {
508
- "decision": decision_payload(decision),
508
+ "decision": decision_payload(decision, all_readings),
509
509
  "accounts": readings_payload(all_readings),
510
510
  }
511
511
  exit_code = BROKER_WAIT_EXIT_CODE if decision.action == "wait" else 0
@@ -116,7 +116,7 @@ def test_should_accept_the_answer_the_broker_serializes(tmp_path: Path) -> None:
116
116
  account = Account(Product.CODEX, "codex-2", tmp_path / "codex-2")
117
117
  reading = Reading(account, Meters(72.0, None, 42.0, None))
118
118
  decision = Decision("run", account, None, "codex-2 has 42% left", "normal")
119
- answer = {"decision": decision_payload(decision), "accounts": readings_payload([reading])}
119
+ answer = {"decision": decision_payload(decision, [reading]), "accounts": readings_payload([reading])}
120
120
 
121
121
  def process_runner(arguments: list[str], **kwargs: object) -> subprocess.CompletedProcess[str]:
122
122
  return subprocess.CompletedProcess(arguments, 0, json.dumps(answer), "")
@@ -140,7 +140,7 @@ def _answer_for_the_default_home(
140
140
  required_tier="normal",
141
141
  )
142
142
  return {
143
- "decision": decision_payload(decision),
143
+ "decision": decision_payload(decision, [reading]),
144
144
  "accounts": readings_payload([reading]),
145
145
  }
146
146
 
@@ -205,7 +205,7 @@ def _broker_reply_for_an_exported_home(
205
205
  Product.CODEX, [reading], now=datetime.now(timezone.utc)
206
206
  )
207
207
  answer = {
208
- "decision": decision_payload(decision),
208
+ "decision": decision_payload(decision, [reading]),
209
209
  "accounts": readings_payload([reading]),
210
210
  }
211
211
  return (3 if decision.action == "wait" else 0), answer, decision.tier
@@ -285,12 +285,12 @@ test('sandbox uninstall removes only package-owned permission entries and keeps
285
285
  }
286
286
  });
287
287
 
288
- test('package settings.json publishes the session agent, advisor model, auto-compact, auto mode, idle compaction, Python UTF-8 and reminder-off defaults', () => {
288
+ test('package settings.json publishes the session agent, auto-compact, auto mode, idle compaction, Python UTF-8 and reminder-off defaults', () => {
289
289
  const packageSettings = JSON.parse(readFileSync(PACKAGE_SETTINGS_PATH, 'utf8'));
290
290
  const settingsDefaults = settingsDefaultsFromPackageSettings(packageSettings);
291
291
  assert.deepEqual(
292
292
  Object.keys(settingsDefaults).sort(),
293
- ['advisorModel', 'agent', 'autoCompactWindow', 'autoMode', 'env', 'modelSettings'],
293
+ ['agent', 'autoCompactWindow', 'autoMode', 'env', 'modelSettings'],
294
294
  );
295
295
  assert.equal(settingsDefaults.autoCompactWindow, 350000);
296
296
  assert.deepEqual(settingsDefaults.env, PACKAGE_ENV_DEFAULTS);
@@ -303,7 +303,6 @@ test('package settings.json publishes the session agent, advisor model, auto-com
303
303
  existsSync(join(PACKAGE_ROOT, '.agents', 'agents', `${settingsDefaults.agent}.md`)),
304
304
  'the session agent named by the agent default ships with the package',
305
305
  );
306
- assert.equal(settingsDefaults.advisorModel, 'fable');
307
306
  const [firstAllowRule, ...allCustomAllowRules] = settingsDefaults.autoMode.allow;
308
307
  assert.equal(firstAllowRule, '$defaults');
309
308
  assert.equal(allCustomAllowRules.length, 2);
@@ -384,13 +383,13 @@ test('install leaves reminder-off variables the user already set in place and ad
384
383
  }
385
384
  });
386
385
 
387
- test('install adds advisorModel when missing and keeps a user choice on rerun', () => {
386
+ test('install does not add advisorModel and keeps a user choice on rerun', () => {
388
387
  const sandboxHome = mkdtempSync(join(tmpdir(), 'cde-settings-defaults-'));
389
388
  try {
390
389
  const firstRun = runInstallerInSandbox(sandboxHome);
391
390
  assert.equal(firstRun.status, 0, firstRun.stderr);
392
391
  const settingsPath = join(sandboxHome, '.claude', 'settings.json');
393
- assert.equal(JSON.parse(readFileSync(settingsPath, 'utf8')).advisorModel, 'fable');
392
+ assert.equal(Object.hasOwn(JSON.parse(readFileSync(settingsPath, 'utf8')), 'advisorModel'), false);
394
393
  const userChoice = JSON.parse(readFileSync(settingsPath, 'utf8'));
395
394
  userChoice.advisorModel = 'sonnet';
396
395
  writeFileSync(settingsPath, JSON.stringify(userChoice, null, 4) + '\n');
@@ -20,7 +20,7 @@ python scripts/account_broker.py check --product codex
20
20
  printf "%s" "prompt" | python scripts/account_broker.py run --product claude --report report.json -- claude --output-format json -p
21
21
  ```
22
22
 
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.
23
+ `accounts` prints the roster without reading meters. `choose` prints `decision`, `accounts`, and `state_path`. Each decision contains `action`, `account`, `profile`, `home`, `reason`, `tier`, `resets_at`, and `meter_unread`. `meter_unread` lists, in roster order, the name of each account whose meter could not be read for this choice; it is `[]` when every meter was read. The `run` report carries it in `final_decision` and in each `pick` event. `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. An HTTP 429 from the Claude usage endpoint holds that account's next probe for the reply's `Retry-After`, in seconds or as a date, bounded to 5 through 20 minutes, and for 5 minutes when the reply has none. A 429 keeps the earlier good reading in the state file, even once that reading is too old to choose on. `--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.
24
24
 
25
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.
26
26
 
@@ -31,7 +31,7 @@ The broker stores cached meters, spent marks, and Claude session bindings in one
31
31
  | Code | Meaning |
32
32
  | --- | --- |
33
33
  | `0` | `choose` or `check` found an account, or the job exited successfully. |
34
- | `3` | Wait. No account clears its floor, no read account clears its floor while other meters went unread, or no account meter could be read. The reason says which. The decision includes `resets_at`. |
34
+ | `3` | Wait. No account clears its floor, no read account clears its floor while other meters went unread, or no account meter could be read. The reason says which, and `meter_unread` lists the accounts whose meter went unread; an empty list means every meter was read and no account has room. The decision includes `resets_at`. |
35
35
  | `4` | A Claude job stopped with `advisor_blocked`, or every Claude account was unusable: each had no token or was signed out. |
36
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. |
37
37
  | Other command code | `run` returns the command's exit code after a served response. |
@@ -52,8 +52,10 @@ usage endpoint returns as `null` holds no account back, but an account needs at
52
52
  least one window with a percent to have room.
53
53
 
54
54
  A wait whose reason starts "no account meter could be read" is a failed read,
55
- and the account may have usage left. An HTTP 429 from the usage endpoint holds
56
- that account's probe for 5 minutes.
55
+ and the account may have usage left. The decision's `meter_unread` list names
56
+ those accounts. An HTTP 429 from the usage endpoint holds that account's probe
57
+ for the reply's `Retry-After`, at least 5 and at most 20 minutes, and 5 minutes
58
+ when the reply has none.
57
59
  [Proof before a pull request](rule-guides/proof-before-pull-request.md) says
58
60
  what a session does next.
59
61
 
package/hooks/hooks.json CHANGED
@@ -108,7 +108,7 @@
108
108
  {
109
109
  "type": "command",
110
110
  "command": "python3 ${CLAUDE_PLUGIN_ROOT}/hooks/blocking/resolve_thread_reply_gate.py",
111
- "timeout": 10
111
+ "timeout": 30
112
112
  }
113
113
  ]
114
114
  },
@@ -123,7 +123,7 @@
123
123
  {
124
124
  "type": "command",
125
125
  "command": "python3 ${CLAUDE_PLUGIN_ROOT}/hooks/session/npx_pele_guidance.py",
126
- "timeout": 10
126
+ "timeout": 30
127
127
  }
128
128
  ]
129
129
  },
@@ -133,7 +133,7 @@
133
133
  {
134
134
  "type": "command",
135
135
  "command": "python3 ${CLAUDE_PLUGIN_ROOT}/hooks/advisory/pieces_per_level_note.py",
136
- "timeout": 10
136
+ "timeout": 30
137
137
  }
138
138
  ]
139
139
  },
@@ -355,7 +355,7 @@
355
355
  {
356
356
  "type": "command",
357
357
  "command": "python3 ${CLAUDE_PLUGIN_ROOT}/hooks/blocking/step_note_gate.py",
358
- "timeout": 15
358
+ "timeout": 30
359
359
  }
360
360
  ]
361
361
  }
@@ -30,6 +30,8 @@ BROKER_COMMAND_DENY_REASON: str = (
30
30
  "--report <report.json> -- <the same claude -p command>. "
31
31
  "The broker picks an account with room, sends a --resume turn to the account that owns the session, "
32
32
  "and starts the child without this session's variables. "
33
- "Exit 3 means no account has room: report the reset time from the report file. "
33
+ "Exit 3 means a wait: no account has room, or a meter could not be read. "
34
+ "The report's final_decision lists unread accounts in meter_unread; an empty list means every meter was read and no account has room. "
35
+ "Report the reason and resets_at from the report file. "
34
36
  "For a worker that edits code, use claude_account_worker.py from the second-account-workers skill."
35
37
  )
@@ -4,6 +4,7 @@ from __future__ import annotations
4
4
 
5
5
  import json
6
6
  import math
7
+ import re
7
8
  import time
8
9
  from pathlib import Path
9
10
 
@@ -17,6 +18,9 @@ from hooks_constants.hook_time_budget import call_timeout, remaining_seconds, ti
17
18
  HOOKS_JSON_PATH = Path(__file__).resolve().parent.parent / "hooks.json"
18
19
  MINIMUM_MARGIN_SECONDS = 5
19
20
  EXIT_MARGIN_SECONDS = 2
21
+ MINIMUM_SHELL_HOOK_TIMEOUT_SECONDS = 30
22
+ SHELL_TOOL_NAME = "Bash"
23
+ ALL_MATCH_EVERY_TOOL_MATCHERS = ("", "*")
20
24
 
21
25
 
22
26
  def registered_timeout(event_name: str, script_relative_path: str) -> int:
@@ -109,3 +113,17 @@ def test_should_register_the_open_tasks_gate_with_a_45_second_timeout() -> None:
109
113
  gate_timeout = registered_timeout("Stop", "blocking/open_tasks_stop_gate.py")
110
114
  assert gate_timeout == 45
111
115
  assert gate_timeout - closing_reply_judge_constants.JUDGE_TIMEOUT_SECONDS >= MINIMUM_MARGIN_SECONDS
116
+
117
+
118
+ def test_should_give_every_shell_pre_tool_hook_at_least_30_seconds() -> None:
119
+ all_groups = json.loads(HOOKS_JSON_PATH.read_text(encoding="utf-8"))["hooks"]["PreToolUse"]
120
+ all_short_hooks = [
121
+ (each_hook["command"], each_hook["timeout"])
122
+ for each_group in all_groups
123
+ if each_group.get("matcher", "") in ALL_MATCH_EVERY_TOOL_MATCHERS
124
+ or re.fullmatch(each_group["matcher"], SHELL_TOOL_NAME)
125
+ for each_hook in each_group["hooks"]
126
+ if each_hook.get("type") == "command"
127
+ and each_hook["timeout"] < MINIMUM_SHELL_HOOK_TIMEOUT_SECONDS
128
+ ]
129
+ assert all_short_hooks == []
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-dev-env",
3
- "version": "8.126.2",
3
+ "version": "8.126.4",
4
4
  "description": "Claude Code development standards — rules, hooks, agents, commands, and skills",
5
5
  "type": "module",
6
6
  "bin": {
@@ -114,11 +114,20 @@ def choose_from_readings(
114
114
  return selected or _wait_decision(all_readings, now, all_spent_accounts, all_spent_resets or {})
115
115
 
116
116
 
117
- def decision_payload(decision: Decision) -> dict[str, object]:
118
- """Serialize a choice.
117
+ def decision_payload(decision: Decision, all_readings: Sequence[Reading]) -> dict[str, object]:
118
+ """Serialize a choice, with the accounts whose meter went unread.
119
+
120
+ ::
121
+
122
+ wait, main unread (HTTP 429), ev unread -> {..., "meter_unread": ["main", "ev"]}
123
+ wait, every meter read, none has room -> {..., "meter_unread": []}
124
+
125
+ ``meter_unread`` tells a wait on unread meters from a wait on spent usage
126
+ without parsing the reason text.
119
127
 
120
128
  Args:
121
129
  decision: Account choice.
130
+ all_readings: The readings the choice was made from.
122
131
 
123
132
  Returns:
124
133
  JSON-compatible decision fields.
@@ -131,6 +140,7 @@ def decision_payload(decision: Decision) -> dict[str, object]:
131
140
  "reason": decision.reason,
132
141
  "tier": decision.tier,
133
142
  "resets_at": _time_text(decision.resets_at),
143
+ "meter_unread": [each_reading.account.name for each_reading in all_readings if each_reading.meters is None],
134
144
  }
135
145
 
136
146
 
@@ -227,7 +237,7 @@ def _write_report(path: Path, report: Report) -> None:
227
237
  "product": report.product.value,
228
238
  "command": report.command,
229
239
  "events": report.events,
230
- "final_decision": decision_payload(report.final_decision) if report.final_decision else None,
240
+ "final_decision": decision_payload(report.final_decision, report.all_readings) if report.final_decision else None,
231
241
  }
232
242
  path.parent.mkdir(parents=True, exist_ok=True)
233
243
  path.write_text(json.dumps(payload, indent=REPORT_INDENT_SPACES) + "\n", encoding="utf-8", newline="\n")
@@ -269,7 +279,7 @@ def _prepare_run(
269
279
  spent, all_spent_resets = _spent_for_readings(all_readings, all_state, now)
270
280
  stdin_bytes = stdin_text.encode(encoding, errors) if isinstance(stdin_text, str) else stdin_text
271
281
  return _RunContext(
272
- product, list(all_argv), active, now, all_state, all_readings, Report(product, list(all_argv)),
282
+ product, list(all_argv), active, now, all_state, all_readings, Report(product, list(all_argv), all_readings=all_readings),
273
283
  stdin_bytes, timeout_seconds, cwd, encoding, errors, preferred, [], set(spent), all_spent_resets
274
284
  )
275
285
 
@@ -421,7 +431,7 @@ def _execute(
421
431
  while True:
422
432
  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)
423
433
  decision = _with_outside_spent_marks(picked, _outside_roster_resets(product, context.all_readings, context.all_state, now))
424
- context.report.events.append({"type": "pick", "decision": decision_payload(decision)})
434
+ context.report.events.append({"type": "pick", "decision": decision_payload(decision, context.all_readings)})
425
435
  if decision.account is None:
426
436
  return _wait_outcome(context, decision), context.report
427
437
  outcome = _attempt_once(context, decision)
@@ -549,7 +559,7 @@ def _choose_cli(product: Product, parsed: argparse.Namespace) -> int:
549
559
  if parsed.home is None:
550
560
  decision = _with_outside_spent_marks(decision, _outside_roster_resets(product, all_readings, all_state, now))
551
561
  if parsed.action == "choose":
552
- print(json.dumps({"decision": decision_payload(decision), "accounts": readings_payload(all_readings), "state_path": str(broker_state_path())}))
562
+ print(json.dumps({"decision": decision_payload(decision, all_readings), "accounts": readings_payload(all_readings), "state_path": str(broker_state_path())}))
553
563
  return WAIT_EXIT_CODE if decision.action == "wait" else 0
554
564
 
555
565
 
@@ -13,8 +13,11 @@ import sys
13
13
  import tempfile
14
14
  import threading
15
15
  import time
16
+ import urllib.error
16
17
  from contextlib import contextmanager
17
18
  from datetime import datetime, timezone
19
+ from email.utils import parsedate_to_datetime
20
+ from http import HTTPStatus
18
21
  from pathlib import Path, PureWindowsPath
19
22
  from typing import Callable, Iterator, Sequence
20
23
 
@@ -46,6 +49,7 @@ from dev_env_scripts_constants.account_broker_constants import (
46
49
  LOGIN_REFRESH_TIMEOUT_SECONDS,
47
50
  METER_READ_ATTEMPTS,
48
51
  METER_RATE_LIMIT_COOLDOWN_SECONDS,
52
+ METER_RATE_LIMIT_MAX_COOLDOWN_SECONDS,
49
53
  Meters,
50
54
  Product,
51
55
  ProductAdapter,
@@ -56,6 +60,7 @@ from dev_env_scripts_constants.account_broker_constants import (
56
60
  Reading,
57
61
  Report,
58
62
  REPORT_INDENT_SPACES,
63
+ RETRY_AFTER_HEADER_NAME,
59
64
  SubprocessRunner,
60
65
  codex_usage_limit_signatures,
61
66
  meter_read_delay_seconds,
@@ -401,13 +406,51 @@ def read_codex_account_meters(account: Account) -> Meters:
401
406
  )
402
407
 
403
408
 
409
+ def _retry_after_seconds(error: BaseException, now: datetime) -> float | None:
410
+ cause = error.__cause__
411
+ if not isinstance(cause, urllib.error.HTTPError) or cause.headers is None:
412
+ return None
413
+ retry_after_text = (cause.headers.get(RETRY_AFTER_HEADER_NAME) or "").strip()
414
+ if retry_after_text.isdigit():
415
+ return float(retry_after_text)
416
+ try:
417
+ retry_at = parsedate_to_datetime(retry_after_text)
418
+ except (TypeError, ValueError, IndexError):
419
+ return None
420
+ if retry_at.tzinfo is None:
421
+ retry_at = retry_at.replace(tzinfo=timezone.utc)
422
+ return (retry_at - now).total_seconds()
423
+
424
+
425
+ def _rate_limit_hold_seconds(
426
+ error: BaseException, unread_reason: str, now: datetime
427
+ ) -> float | None:
428
+ cause = error.__cause__
429
+ is_rate_limited = (
430
+ isinstance(cause, urllib.error.HTTPError)
431
+ and cause.code == HTTPStatus.TOO_MANY_REQUESTS
432
+ ) or "HTTP Error 429" in unread_reason
433
+ if not is_rate_limited:
434
+ return None
435
+ retry_after_seconds = _retry_after_seconds(error, now)
436
+ if retry_after_seconds is None:
437
+ return METER_RATE_LIMIT_COOLDOWN_SECONDS
438
+ return min(
439
+ max(retry_after_seconds, METER_RATE_LIMIT_COOLDOWN_SECONDS),
440
+ METER_RATE_LIMIT_MAX_COOLDOWN_SECONDS,
441
+ )
442
+
443
+
404
444
  def _read_meter_attempt(
405
- read_meters: Callable[[Account], Meters | None], account: Account
406
- ) -> tuple[bool, Meters | None, str | None, bool]:
445
+ read_meters: Callable[[Account], Meters | None], account: Account, now: datetime
446
+ ) -> tuple[bool, Meters | None, str | None, float | None]:
407
447
  try:
408
- return True, read_meters(account), None, False
409
- except (codex_account_meters.CodexExecutableNotFoundError, ClaudeSignedOutError) as error:
410
- return True, None, str(error), False
448
+ return True, read_meters(account), None, None
449
+ except (
450
+ codex_account_meters.CodexExecutableNotFoundError,
451
+ ClaudeSignedOutError,
452
+ ) as error:
453
+ return True, None, str(error), None
411
454
  except (
412
455
  codex_account_meters.CodexMeterUnreadError,
413
456
  WeeklyUtilizationProbeError,
@@ -417,33 +460,58 @@ def _read_meter_attempt(
417
460
  subprocess.SubprocessError,
418
461
  ) as error:
419
462
  unread_reason = str(error) or type(error).__name__
420
- if "HTTP Error 429" in unread_reason:
421
- return True, None, unread_reason, True
422
- return False, None, unread_reason, False
463
+ rate_limit_hold_seconds = _rate_limit_hold_seconds(error, unread_reason, now)
464
+ return (
465
+ rate_limit_hold_seconds is not None,
466
+ None,
467
+ unread_reason,
468
+ rate_limit_hold_seconds,
469
+ )
423
470
 
424
471
 
425
- def read_meters_with_backoff(read_meters: Callable[[Account], Meters | None], account: Account) -> tuple[Meters | None, str | None, bool]:
472
+ def read_meters_with_backoff(
473
+ read_meters: Callable[[Account], Meters | None],
474
+ account: Account,
475
+ now: datetime | None = None,
476
+ ) -> tuple[Meters | None, str | None, float | None]:
426
477
  """Read one account's meters, retrying a failed read with exponential backoff.
427
478
 
479
+ ::
480
+
481
+ read fails twice, then succeeds -> (meters, None, None)
482
+ HTTP 429 with Retry-After: 900 -> (None, "...HTTP Error 429...", 900.0)
483
+ HTTP 429 with Retry-After: 30, or none -> (None, "...HTTP Error 429...", 300.0)
484
+ HTTP 429 with Retry-After: 7200 -> (None, "...HTTP Error 429...", 1200.0)
485
+
486
+ A rate limit stops the retries at once. So does a missing Codex
487
+ executable or a signed-out Claude account.
488
+
428
489
  Args:
429
490
  read_meters: The product's meter reader.
430
491
  account: Account whose meter is read.
492
+ now: The time a Retry-After date is measured from. Defaults to the
493
+ current time.
431
494
 
432
495
  Returns:
433
496
  The meters from the first read that succeeds, or None with the last
434
- failure text once every attempt failed, and whether the usage
435
- endpoint rate-limited the read, which stops the retries. A missing
436
- Codex executable or a signed-out Claude account fails at once,
437
- without a retry.
497
+ failure text once every attempt failed, and the seconds to hold the
498
+ next probe when the usage endpoint rate-limited the read, else None.
499
+ The hold is the reply's Retry-After, in seconds or as a date, bounded
500
+ to METER_RATE_LIMIT_COOLDOWN_SECONDS through
501
+ METER_RATE_LIMIT_MAX_COOLDOWN_SECONDS, and the lower bound when the
502
+ reply has no usable Retry-After.
438
503
  """
504
+ attempt_time = now or datetime.now(timezone.utc)
439
505
  unread_reason = None
440
506
  for each_attempt in range(METER_READ_ATTEMPTS):
441
507
  if each_attempt:
442
508
  time.sleep(meter_read_delay_seconds(each_attempt))
443
- is_final, meters, unread_reason, is_rate_limited = _read_meter_attempt(read_meters, account)
509
+ is_final, meters, unread_reason, rate_limit_hold_seconds = _read_meter_attempt(
510
+ read_meters, account, attempt_time
511
+ )
444
512
  if is_final:
445
- return meters, unread_reason, is_rate_limited
446
- return None, unread_reason, False
513
+ return meters, unread_reason, rate_limit_hold_seconds
514
+ return None, unread_reason, None
447
515
 
448
516
 
449
517
  all_product_adapters = {
@@ -626,19 +694,42 @@ def _read_one_account(account: Account, adapter: ProductAdapter, all_cache: dict
626
694
  cached_meters = None
627
695
  next_probe = datetime.fromtimestamp(retry_at, timezone.utc) if is_held else None
628
696
  return Reading(account, cached_meters, cached_reason if isinstance(cached_reason, str) else None, measured, next_probe), False
629
- meters, unread_reason, is_rate_limited = read_meters_with_backoff(adapter.read_meters, account)
697
+ meters, unread_reason, rate_limit_hold_seconds = read_meters_with_backoff(adapter.read_meters, account, now)
630
698
  measured_at = _measured_timestamp(meters, now)
631
- is_rate_limited = account.product is Product.CLAUDE and is_rate_limited
699
+ is_rate_limited = account.product is Product.CLAUDE and rate_limit_hold_seconds is not None
632
700
  last_good = _last_good_meters(cached, now) if is_rate_limited else None
633
701
  if last_good is not None:
634
702
  meters, measured_at = last_good
635
703
  all_cache[key] = {"read_at": now.timestamp(), "measured_at": measured_at, "meters": _meter_payload(meters), "unread_reason": unread_reason}
704
+ earlier_reading = _earlier_good_reading(cached) if is_rate_limited and last_good is None else None
705
+ if earlier_reading is not None:
706
+ all_cache[key]["meters"], all_cache[key]["measured_at"] = earlier_reading
707
+ measured_at = earlier_reading[1]
636
708
  if is_rate_limited:
637
- all_cache[key]["retry_at"] = now.timestamp() + METER_RATE_LIMIT_COOLDOWN_SECONDS
709
+ all_cache[key]["retry_at"] = now.timestamp() + rate_limit_hold_seconds
638
710
  next_probe = datetime.fromtimestamp(all_cache[key]["retry_at"], timezone.utc) if is_rate_limited else None
639
711
  return Reading(account, meters, unread_reason, datetime.fromtimestamp(measured_at, timezone.utc), next_probe), True
640
712
 
641
713
 
714
+ def _earlier_good_reading(all_cached_fields: dict[str, object]) -> tuple[dict[str, object], float] | None:
715
+ """Return the saved meters and their measurement time, so a rate limit keeps them in the state file.
716
+
717
+ ::
718
+
719
+ good reading at 19:20, HTTP 429 at 20:00 -> (the 19:20 meters, 19:20)
720
+ no saved meters -> None
721
+
722
+ The broker does not choose on a reading this old; the 30-minute
723
+ last-good check still drops it. The file keeps it so the reading is
724
+ not lost to a null written by the rate limit.
725
+ """
726
+ raw_meters = all_cached_fields.get("meters")
727
+ measured_at = all_cached_fields.get("measured_at", all_cached_fields.get("read_at"))
728
+ if _meters_from_payload(raw_meters) is None or not isinstance(measured_at, (int, float)):
729
+ return None
730
+ return raw_meters, float(measured_at)
731
+
732
+
642
733
  def _measured_timestamp(meters: Meters | None, now: datetime) -> float:
643
734
  """Return when *meters* were measured, never later than *now*.
644
735
 
@@ -61,6 +61,8 @@ METER_READ_DELAY_FACTOR = 2.0
61
61
  METER_READ_MAX_DELAY_SECONDS = 8.0
62
62
  LAST_GOOD_METER_MAX_AGE_SECONDS = 1800.0
63
63
  METER_RATE_LIMIT_COOLDOWN_SECONDS = 300.0
64
+ METER_RATE_LIMIT_MAX_COOLDOWN_SECONDS = 1200.0
65
+ RETRY_AFTER_HEADER_NAME = "Retry-After"
64
66
  PUBLISHED_USAGE_DIRECTORY_ENV_VAR = "CLAUDE_USAGE_READINGS_DIR"
65
67
  PUBLISHED_USAGE_FILE_PATTERN = "meters-*.json"
66
68
  PUBLISHED_USAGE_MAX_AGE_SECONDS = 1800.0
@@ -279,6 +281,7 @@ class Report:
279
281
  command: list[str]
280
282
  events: list[dict[str, object]] = field(default_factory=list)
281
283
  final_decision: Decision | None = None
284
+ all_readings: tuple[Reading, ...] = ()
282
285
 
283
286
 
284
287
  MeterReader = Callable[[Account], Meters | None]
@@ -1414,6 +1414,53 @@ def test_should_replay_stdin_bytes_and_only_print_served_stdout(
1414
1414
  assert json.loads(report_path.read_text(encoding="utf-8"))["final_decision"]["account"] == "second"
1415
1415
 
1416
1416
 
1417
+ def test_should_name_the_unread_meters_in_the_choose_decision(
1418
+ monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
1419
+ ) -> None:
1420
+ accounts = (_account("first"), _account("second"))
1421
+ monkeypatch.setitem(
1422
+ account_broker.all_product_adapters, Product.CODEX, _adapter(accounts, {"first": _meters(0, 0), "second": None})
1423
+ )
1424
+
1425
+ exit_code = account_broker.main(("choose", "--product", "codex"))
1426
+
1427
+ assert exit_code == WAIT_EXIT_CODE
1428
+ assert json.loads(capsys.readouterr().out)["decision"]["meter_unread"] == ["second"]
1429
+
1430
+
1431
+ def test_should_name_the_unread_meters_in_the_run_report(
1432
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
1433
+ ) -> None:
1434
+ accounts = (_account("first"), _account("second"))
1435
+ monkeypatch.setitem(
1436
+ account_broker.all_product_adapters, Product.CODEX, _adapter(accounts, {"first": None, "second": None})
1437
+ )
1438
+ monkeypatch.setattr(account_broker.sys, "stdin", io.TextIOWrapper(io.BytesIO(b""), encoding="utf-8"))
1439
+ report_path = tmp_path / "report.json"
1440
+
1441
+ code = account_broker.main(("run", "--product", "codex", "--report", str(report_path), "--", "job"))
1442
+
1443
+ report = json.loads(report_path.read_text(encoding="utf-8"))
1444
+ assert code == WAIT_EXIT_CODE
1445
+ assert report["final_decision"]["meter_unread"] == ["first", "second"]
1446
+ assert report["events"][0]["decision"]["meter_unread"] == ["first", "second"]
1447
+
1448
+
1449
+ def test_should_leave_meter_unread_empty_when_every_meter_was_read(
1450
+ monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
1451
+ ) -> None:
1452
+ monkeypatch.setitem(
1453
+ account_broker.all_product_adapters, Product.CODEX, _adapter((_account("first"),), {"first": _meters(80, 80)})
1454
+ )
1455
+
1456
+ exit_code = account_broker.main(("choose", "--product", "codex"))
1457
+
1458
+ decision = json.loads(capsys.readouterr().out)["decision"]
1459
+ assert exit_code == 0
1460
+ assert decision["account"] == "first"
1461
+ assert decision["meter_unread"] == []
1462
+
1463
+
1417
1464
  def test_should_write_wait_report_without_stdout(
1418
1465
  monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str]
1419
1466
  ) -> None:
@@ -2584,11 +2631,11 @@ def test_should_serialize_a_run_and_a_wait_decision() -> None:
2584
2631
  account = _account("first")
2585
2632
  reset = NOW + timedelta(hours=2)
2586
2633
 
2587
- run_payload = account_broker.decision_payload(account_broker.Decision("run", account, None, "first has 80% left", "normal"))
2588
- wait_payload = account_broker.decision_payload(account_broker.Decision("wait", None, reset, "no account has room", "wait"))
2634
+ run_payload = account_broker.decision_payload(account_broker.Decision("run", account, None, "first has 80% left", "normal"), (Reading(account, _meters(80, 80)),))
2635
+ wait_payload = account_broker.decision_payload(account_broker.Decision("wait", None, reset, "no account has room", "wait"), (Reading(account, None),))
2589
2636
 
2590
- assert run_payload == {"action": "run", "account": "first", "profile": None, "home": str(Path("/profiles/first")), "reason": "first has 80% left", "tier": "normal", "resets_at": None}
2591
- assert wait_payload == {"action": "wait", "account": None, "profile": None, "home": None, "reason": "no account has room", "tier": "wait", "resets_at": reset.isoformat()}
2637
+ assert run_payload == {"action": "run", "account": "first", "profile": None, "home": str(Path("/profiles/first")), "reason": "first has 80% left", "tier": "normal", "resets_at": None, "meter_unread": []}
2638
+ assert wait_payload == {"action": "wait", "account": None, "profile": None, "home": None, "reason": "no account has room", "tier": "wait", "resets_at": reset.isoformat(), "meter_unread": ["first"]}
2592
2639
 
2593
2640
 
2594
2641
  def test_should_print_the_whole_rate_limit_result_for_one_home(
@@ -2699,14 +2746,14 @@ def test_should_hand_the_live_log_to_the_subprocess_runner(tmp_path: Path, monke
2699
2746
  def test_decision_payload_should_carry_the_profile_of_a_claude_account() -> None:
2700
2747
  account = Account(Product.CLAUDE, "C:\\bin\\claude-editor.cmd", Path("/profiles/editor"), command="C:\\bin\\claude-editor.cmd", profile="editor")
2701
2748
 
2702
- assert account_broker.decision_payload(account_broker.Decision("run", account, None, "most room", "normal"))["profile"] == "editor"
2749
+ assert account_broker.decision_payload(account_broker.Decision("run", account, None, "most room", "normal"), ())["profile"] == "editor"
2703
2750
 
2704
2751
 
2705
2752
  def test_decision_payload_should_name_the_chosen_account_and_its_home() -> None:
2706
2753
  account = _account("codex-2")
2707
2754
  decision = account_broker.Decision("run", account, None, "most room", "normal")
2708
2755
 
2709
- assert account_broker.decision_payload(decision) == {
2756
+ assert account_broker.decision_payload(decision, (Reading(account, _meters(80, 80)),)) == {
2710
2757
  "action": "run",
2711
2758
  "account": "codex-2",
2712
2759
  "profile": None,
@@ -2714,6 +2761,7 @@ def test_decision_payload_should_name_the_chosen_account_and_its_home() -> None:
2714
2761
  "reason": "most room",
2715
2762
  "tier": "normal",
2716
2763
  "resets_at": None,
2764
+ "meter_unread": [],
2717
2765
  }
2718
2766
 
2719
2767
 
@@ -2721,7 +2769,7 @@ def test_decision_payload_should_leave_the_account_empty_and_give_the_reset_for_
2721
2769
  reset = datetime(2026, 10, 3, 4, 0, tzinfo=timezone(timedelta(hours=-4)))
2722
2770
  decision = account_broker.Decision("wait", None, reset, "no account has room", "wait")
2723
2771
 
2724
- payload = account_broker.decision_payload(decision)
2772
+ payload = account_broker.decision_payload(decision, ())
2725
2773
 
2726
2774
  assert payload["account"] is None
2727
2775
  assert payload["home"] is None
@@ -7,14 +7,18 @@ import shutil
7
7
  import subprocess
8
8
  import sys
9
9
  import time
10
+ import urllib.error
10
11
  from datetime import datetime, timedelta, timezone
11
12
  from collections.abc import Callable
13
+ from email.message import Message
14
+ from email.utils import format_datetime
12
15
  from pathlib import Path
13
16
  from types import SimpleNamespace
14
17
 
15
18
  import pytest
16
19
 
17
20
  import account_broker_support as support
21
+ import claude_chain_usage
18
22
  from account_broker_support import Account, Meters, Product, ProductAdapter
19
23
  from codex_account_meters import CodexAccountMeters, UsageWindow
20
24
 
@@ -620,11 +624,11 @@ def test_should_cap_the_meter_read_delay(monkeypatch: pytest.MonkeyPatch, tmp_pa
620
624
  all_failures = [support.WeeklyUtilizationProbeError("down") for _ in range(6)]
621
625
  _claude_meter_reads(monkeypatch, all_failures)
622
626
 
623
- meters, unread_reason, is_rate_limited = support.read_meters_with_backoff(support.read_claude_meters, Account(Product.CLAUDE, "one", tmp_path))
627
+ meters, unread_reason, rate_limit_hold_seconds = support.read_meters_with_backoff(support.read_claude_meters, Account(Product.CLAUDE, "one", tmp_path))
624
628
 
625
629
  assert meters is None
626
630
  assert unread_reason == "down"
627
- assert not is_rate_limited
631
+ assert rate_limit_hold_seconds is None
628
632
  assert all_delays == [1.0, 2.0, 4.0, 8.0, 8.0]
629
633
 
630
634
 
@@ -636,11 +640,11 @@ def test_should_read_a_signed_out_claude_account_once(monkeypatch: pytest.Monkey
636
640
  all_reads.append(account)
637
641
  raise support.ClaudeSignedOutError("no usable bearer token")
638
642
 
639
- meters, unread_reason, is_rate_limited = support.read_meters_with_backoff(signed_out_reader, Account(Product.CLAUDE, "main", tmp_path))
643
+ meters, unread_reason, rate_limit_hold_seconds = support.read_meters_with_backoff(signed_out_reader, Account(Product.CLAUDE, "main", tmp_path))
640
644
 
641
645
  assert meters is None
642
646
  assert unread_reason == "no usable bearer token"
643
- assert not is_rate_limited
647
+ assert rate_limit_hold_seconds is None
644
648
  assert len(all_reads) == 1
645
649
  assert all_delays == []
646
650
 
@@ -696,6 +700,95 @@ def test_should_keep_the_last_good_meters_when_the_usage_endpoint_rate_limits(
696
700
  assert reading.measured_at == datetime(2026, 10, 11, 19, 20, tzinfo=timezone.utc)
697
701
 
698
702
 
703
+ RATE_LIMITED_AT = datetime(2026, 10, 11, 19, 20, tzinfo=timezone.utc)
704
+
705
+
706
+ def _rate_limited_resolver(retry_after: str | None) -> object:
707
+ headers = Message()
708
+ if retry_after is not None:
709
+ headers["Retry-After"] = retry_after
710
+
711
+ class Resolver:
712
+ def read_oauth_access_token(self, credentials_path: Path, now: datetime) -> str:
713
+ return "fixture-token"
714
+
715
+ def _fetch_usage_payload(self, access_token: str) -> dict[str, object]:
716
+ raise urllib.error.HTTPError(
717
+ "https://usage.invalid", 429, "Too Many Requests", headers, None
718
+ )
719
+
720
+ return Resolver()
721
+
722
+
723
+ @pytest.mark.parametrize(
724
+ ("retry_after", "expected_hold"),
725
+ (
726
+ pytest.param("900", timedelta(seconds=900), id="seconds-inside-the-bounds"),
727
+ pytest.param("30", timedelta(seconds=300), id="seconds-below-the-floor"),
728
+ pytest.param("7200", timedelta(seconds=1200), id="seconds-above-the-ceiling"),
729
+ pytest.param(
730
+ format_datetime(RATE_LIMITED_AT + timedelta(seconds=600), usegmt=True),
731
+ timedelta(seconds=600),
732
+ id="http-date",
733
+ ),
734
+ pytest.param("soon", timedelta(seconds=300), id="unparsable"),
735
+ pytest.param(None, timedelta(seconds=300), id="no-header"),
736
+ ),
737
+ )
738
+ def test_should_hold_the_probe_for_the_retry_after_of_a_rate_limit(
739
+ monkeypatch: pytest.MonkeyPatch,
740
+ tmp_path: Path,
741
+ retry_after: str | None,
742
+ expected_hold: timedelta,
743
+ ) -> None:
744
+ monkeypatch.setattr(
745
+ support, "broker_state_path", lambda: tmp_path / "broker" / "state.json"
746
+ )
747
+ monkeypatch.setenv("CLAUDE_USAGE_READINGS_DIR", str(tmp_path / "no-readings"))
748
+ monkeypatch.setattr(
749
+ claude_chain_usage,
750
+ "_load_resolve_usage_window_module",
751
+ lambda: _rate_limited_resolver(retry_after),
752
+ )
753
+ _recorded_sleeps(monkeypatch)
754
+ account = Account(Product.CLAUDE, "main", tmp_path)
755
+ adapter = ProductAdapter(
756
+ lambda: (account,), support.read_claude_meters, "CLAUDE_CONFIG_DIR", ()
757
+ )
758
+ state = support._load_state(support.broker_state_path())
759
+
760
+ reading = support.read_accounts(
761
+ Product.CLAUDE, adapter, all_state=state, now=RATE_LIMITED_AT
762
+ )[0]
763
+
764
+ assert reading.meters is None
765
+ assert "HTTP Error 429" in reading.unread_reason
766
+ assert reading.retry_at == RATE_LIMITED_AT + expected_hold
767
+
768
+
769
+ def test_should_keep_the_earlier_good_reading_in_the_state_file_after_a_rate_limit(
770
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
771
+ ) -> None:
772
+ rate_limited = support.WeeklyUtilizationProbeError(
773
+ "usage probe failed: HTTP Error 429: Too Many Requests"
774
+ )
775
+ reading = _read_twice(
776
+ monkeypatch,
777
+ tmp_path,
778
+ [Meters(74.0, None, 81.0, None), rate_limited],
779
+ timedelta(minutes=40),
780
+ )
781
+
782
+ saved_entry = next(
783
+ iter(support._load_state(support.broker_state_path())["meters"].values())
784
+ )
785
+ assert reading.meters is None
786
+ assert saved_entry["meters"]["session_percent_left"] == 74.0
787
+ assert (
788
+ saved_entry["measured_at"]
789
+ == datetime(2026, 10, 11, 19, 20, tzinfo=timezone.utc).timestamp()
790
+ )
791
+ assert saved_entry["unread_reason"] == str(rate_limited)
699
792
  def test_should_drop_last_good_meters_older_than_the_fallback_window(
700
793
  monkeypatch: pytest.MonkeyPatch, tmp_path: Path
701
794
  ) -> None:
@@ -8,6 +8,7 @@ import sys
8
8
  import urllib.error
9
9
  from datetime import datetime, timezone
10
10
  from collections.abc import Callable
11
+ from email.message import Message
11
12
  from pathlib import Path
12
13
 
13
14
  import pytest
@@ -144,6 +145,27 @@ def test_probe_wraps_network_failure(monkeypatch: pytest.MonkeyPatch) -> None:
144
145
  usage.probe_account_meters(Path("account.json"))
145
146
 
146
147
 
148
+ def test_probe_keeps_a_rate_limit_reply_as_the_cause(monkeypatch: pytest.MonkeyPatch) -> None:
149
+ headers = Message()
150
+ headers["Retry-After"] = "900"
151
+ rate_limit_reply = urllib.error.HTTPError("https://usage.invalid", 429, "Too Many Requests", headers, None)
152
+
153
+ class Resolver:
154
+ def read_oauth_access_token(self, credentials_path: Path, now: datetime) -> str:
155
+ return "fixture-token"
156
+
157
+ def _fetch_usage_payload(self, access_token: str) -> dict[str, object]:
158
+ raise rate_limit_reply
159
+
160
+ monkeypatch.setattr(usage, "_load_resolve_usage_window_module", lambda: Resolver())
161
+
162
+ with pytest.raises(usage.WeeklyUtilizationProbeError, match="HTTP Error 429") as probe_failure:
163
+ usage.probe_account_meters(Path("account.json"))
164
+
165
+ assert probe_failure.value.__cause__ is rate_limit_reply
166
+ assert probe_failure.value.__cause__.headers["Retry-After"] == "900"
167
+
168
+
147
169
  def test_failed_module_load_does_not_poison_cache(
148
170
  monkeypatch: pytest.MonkeyPatch, tmp_path: Path
149
171
  ) -> None:
@@ -0,0 +1,85 @@
1
+ """The pr-lifecycle skill points at the slice rule, and the reference carries the four tests and the retro-split steps."""
2
+
3
+ from pathlib import Path
4
+
5
+ PACKAGE_ROOT = Path(__file__).resolve().parents[2]
6
+ SKILL_DIRECTORY = PACKAGE_ROOT / ".agents" / "skills" / "pr-lifecycle"
7
+ PR_LIFECYCLE_PATH = SKILL_DIRECTORY / "SKILL.md"
8
+ SLICE_REFERENCE_PATH = SKILL_DIRECTORY / "reference" / "split-a-pull-request.md"
9
+
10
+
11
+ def _decision_tree(skill_text: str) -> str:
12
+ return skill_text.split("### Workflow decision tree", 1)[1].split("\n### ", 1)[0]
13
+
14
+
15
+ def test_the_decision_tree_points_at_the_slice_reference() -> None:
16
+ decision_tree = _decision_tree(PR_LIFECYCLE_PATH.read_text(encoding="utf-8"))
17
+ assert "(reference/split-a-pull-request.md)" in decision_tree
18
+
19
+
20
+ def test_the_reference_lists_the_four_slice_tests_in_order() -> None:
21
+ reference_text = SLICE_REFERENCE_PATH.read_text(encoding="utf-8")
22
+ all_test_markers = (
23
+ "1. It merges alone and leaves the trunk working.",
24
+ "2. It has its own proof: a test or command that fails without the slice and passes with it.",
25
+ "3. It reverts alone.",
26
+ "4. One sentence states its purpose, and a reviewer can judge it without reading later levels.",
27
+ )
28
+ all_positions = [
29
+ reference_text.index(each_marker) for each_marker in all_test_markers
30
+ ]
31
+ assert all_positions == sorted(all_positions)
32
+ assert "A slice that needs two sentences is usually two slices." in reference_text
33
+
34
+
35
+ def test_the_reference_merges_cosmetic_cuts_back_and_allows_one_pull_request() -> None:
36
+ reference_text = SLICE_REFERENCE_PATH.read_text(encoding="utf-8")
37
+ assert (
38
+ "A cut by folder, file count, or line cap that fails these tests is cosmetic. Merge it back."
39
+ in reference_text
40
+ )
41
+ assert (
42
+ "Fewer slices is a valid answer, and so is one pull request with a stated reason."
43
+ in reference_text
44
+ )
45
+
46
+
47
+ def test_the_reference_says_when_to_split_and_what_to_try_first() -> None:
48
+ reference_text = SLICE_REFERENCE_PATH.read_text(encoding="utf-8")
49
+ assert "the change carries more than one purpose" in reference_text
50
+ assert (
51
+ "Isolate the part that switches the behaviour on, so its revert is small."
52
+ in reference_text
53
+ )
54
+ assert "`linguist-generated`" in reference_text
55
+ assert "Decide the slices when you write the plan." in reference_text
56
+
57
+
58
+ def test_the_retro_split_pins_the_head_and_posts_the_plan_before_building() -> None:
59
+ reference_text = SLICE_REFERENCE_PATH.read_text(encoding="utf-8")
60
+ assert "## Split a pull request that is already open" in reference_text
61
+ assert "Pin the head SHA" in reference_text
62
+ assert (
63
+ "Never rewrite or push to a branch another session or person owns."
64
+ in reference_text
65
+ )
66
+ assert "map each open finding to the slice it lands in" in reference_text
67
+ plan_position = reference_text.index("get the owner's go before you build")
68
+ no_code_position = reference_text.index("Change no code during the split.")
69
+ assert plan_position < no_code_position
70
+
71
+
72
+ def test_the_retro_split_keeps_the_tree_and_names_the_approvals_each_slice_needs() -> (
73
+ None
74
+ ):
75
+ reference_text = SLICE_REFERENCE_PATH.read_text(encoding="utf-8")
76
+ assert "`git diff <pinned-sha> <tip> --stat` prints nothing" in reference_text
77
+ assert "Approvals do not carry over" in reference_text
78
+ assert "links the original pull request" in reference_text
79
+
80
+
81
+ def test_the_retro_split_links_the_stack_level_proof_and_does_not_copy_it() -> None:
82
+ reference_text = SLICE_REFERENCE_PATH.read_text(encoding="utf-8")
83
+ assert "(../SKILL.md#each-stack-level-stands-on-its-own)" in reference_text
84
+ assert "A symbol belongs at the level that first" not in reference_text
85
+ assert "CI runs only on the stack tip" in reference_text
package/settings.json CHANGED
@@ -11,7 +11,6 @@
11
11
  "Read(~/.claude/docs/**)"
12
12
  ]
13
13
  },
14
- "advisorModel": "fable",
15
14
  "autoCompactWindow": 350000,
16
15
  "modelSettings": {
17
16
  "claude-haiku-5-5": {