From 4a411cfc42022da316a94e49acf9a9f7bec0f695 Mon Sep 17 00:00:00 2001 From: Holon Intent Agent Date: Tue, 1 Dec 2026 13:00:33 +0000 Subject: [PATCH 01/17] intent: created I-1796130017-quota-intra-ladder-step-down/_ Description: When an agent hits quota or a spend limit, Stage 2 misreports the stop as an empty or invalid plan instead of a quota cause, and Stages 2, 3, and 4 halt immediately instead of stepping down the runner's configured model fallback ladder while persisting a per-model cooldown marker. Goal: Classify Stage 2 planner quota stops and automatically step down intra-ladder models on quota exits in Stages 2, 3, and 4, persisting per-model cooldown markers and halting cleanly at the checkpoint only when the entire ladder is exhausted. (1) In apps/sandbox-executor/src/sandbox_executor/runners/spec.py, add `quota_fallback_ladder: tuple[str, ...] = ()` to `RunnerSpec`; declare `("gemini-4-neon", "gemini-4-argon", "gemini-4-hydrogen", "gemini-3.8-flash")` on `SPEC` in runners/antigravity.py and `("claude-fable-5-2", "claude-opus-5-5", "claude-sonnet-4-6", "claude-haiku-4-5")` on `SPEC` in runners/claude.py without altering `model_capabilities`, `RUNNER_CAPABILITIES`, `DEFAULT_MODELS`, or `holon models`. (2) In apps/sandbox-executor/src/sandbox_executor/model_tiers.py, add `fallback_ladder(runner)` and `next_fallback_model(runner, current_model, *, is_available=None)` reading `RunnerSpec.quota_fallback_ladder` after normalising `current_model` with `normalise_model_and_effort`, returning the next available rung or `None` when none remains while keeping `tier_ladder`, `next_tier`, and `start_tier` unchanged. (3) In apps/sandbox-executor/src/sandbox_executor/preflight_cooldown.py, extract `_read_marker_at` and add model-scoped cooldown helpers (`model_marker_path`, `record_model_cooldown`, `read_active_model_cooldown`, `clear_model_cooldown`) stored as `--.json` (normalising model aliases) without changing provider-level `marker_path` or `record_cooldown`; `active_cooldown_result` checks provider cooldown then model cooldown, and `sync_cooldown_for_result` clears model cooldown on `ok`. (4) In apps/sandbox-executor/src/sandbox_executor/quota_park.py, add `PLAN_STAGE = "plan"`, `park_plan`, and `review_quota_stop` (shared with `park_review`) while keeping `quota_park.py` free of `flow`, `cli`, and `entrypoint` imports. (5) Add apps/sandbox-executor/src/sandbox_executor/quota_step_down.py (new), importing only standard library, `model_tiers`, `preflight_cooldown`, and `quota_park`, providing `step_down_for_quota` to record the exhausted model's cooldown, skip any ladder model already in active model cooldown, advance `context.model`, log the exhausted runner/model, reset hint, and replacement model, and return a step-down record dict (or `None` when exhausted). (6) In apps/sandbox-executor/src/sandbox_executor/entrypoint/planner.py, classify failed non-usable planner turns with `rendered_quota_cause` before `_api_error_of` so quota and monthly spend-limit exits fail via `_fail_plan_attempt` with `"the planner agent exited with code ()"` while keeping 400/401 API errors, budget breaches, and usable plans unchanged. (7) In apps/sandbox-executor/src/sandbox_executor/flow/stages/plan.py, wrap `dispatch_planner` inside `PlanStage.produce()` with intra-ladder step-down on `read_quota_stop(failure.error)` (updating `context.model`, recomputing `preferred_suffix`, refreshing `existing_plans`, recording `model_step_downs` in the stage payload when non-empty), and call `park_plan` when the ladder is exhausted, keeping `dispatch_planner()` single-attempt for direct callers. (8) In apps/sandbox-executor/src/sandbox_executor/flow/stages/execute.py, inside `ExecuteStage.run()` within its 430-line budget, step down on a failed stage result whose `summary_row` carries a quota stop, preserve any `partial_head` via `resume_partial`, reset `ExecuteState` keeping `start_time`, retry `_run_steps()`, record `model_step_downs` when non-empty, and call `park_execution` only when the ladder is exhausted. (9) In apps/sandbox-executor/src/sandbox_executor/flow/stages/review.py, inside `_run_review_stage_body()` within its 350-line budget, when the loop fails without `is_dirty`, `MISSING_REF`, `loop_res.get("error")`, or `budget_breach` and `review_quota_stop(reviewers)` finds a quota-failed reviewer matching `context.agent` with iterations remaining, step down `context.model` and re-run `_run_engine_review_loop(context, github=github)`, recording `model_step_downs` when non-empty, and call `park_review` only when the ladder is exhausted; resolver-turn classification in the review-loop container entrypoint is outside this slice. (10) Document Stage 2 quota classification, model-scoped cooldowns, and intra-ladder step-down in docs/budgets.md. (11) Add hermetic tests in apps/sandbox-executor/tests/test_quota_step_down.py (new), apps/sandbox-executor/tests/test_planner_quota.py (new), and apps/sandbox-executor/tests/flow/stages/test_plan_quota_step_down.py (new), and extend apps/sandbox-executor/tests/test_quota_park.py, apps/sandbox-executor/tests/test_preflight_cooldown.py, apps/sandbox-executor/tests/test_runner_specs.py, apps/sandbox-executor/tests/flow/stages/test_execute_steps.py, and apps/sandbox-executor/tests/flow/stages/test_review.py without touching tests/test_planner.py or tests/test_review_loop.py. Never modify holon-config/hygiene/module_budgets.json and keep every module within its existing budget. Never reference harness-specific directories or task-tracker ids in code, tests or documents. Code is self-explaining: no docstrings and no comments except '# why:' comments that record a reason the code cannot show. Generated by Holon Intent Agent at 2026-12-01T13:00:33Z --- .../intents/I-1796130017-quota-intra-ladder-step-down.jsonl | 1 + 1 file changed, 1 insertion(+) create mode 100644 holon-knowledge/ledger/pending/intents/I-1796130017-quota-intra-ladder-step-down.jsonl diff --git a/holon-knowledge/ledger/pending/intents/I-1796130017-quota-intra-ladder-step-down.jsonl b/holon-knowledge/ledger/pending/intents/I-1796130017-quota-intra-ladder-step-down.jsonl new file mode 100644 index 000000000..071ed83fd --- /dev/null +++ b/holon-knowledge/ledger/pending/intents/I-1796130017-quota-intra-ladder-step-down.jsonl @@ -0,0 +1 @@ +{"slug": "quota-intra-ladder-step-down", "target_branch": "main", "description": "When an agent hits quota or a spend limit, Stage 2 misreports the stop as an empty or invalid plan instead of a quota cause, and Stages 2, 3, and 4 halt immediately instead of stepping down the runner's configured model fallback ladder while persisting a per-model cooldown marker.", "goal": "Classify Stage 2 planner quota stops and automatically step down intra-ladder models on quota exits in Stages 2, 3, and 4, persisting per-model cooldown markers and halting cleanly at the checkpoint only when the entire ladder is exhausted. (1) In apps/sandbox-executor/src/sandbox_executor/runners/spec.py, add `quota_fallback_ladder: tuple[str, ...] = ()` to `RunnerSpec`; declare `(\"gemini-4-neon\", \"gemini-4-argon\", \"gemini-4-hydrogen\", \"gemini-3.8-flash\")` on `SPEC` in runners/antigravity.py and `(\"claude-fable-5-2\", \"claude-opus-5-5\", \"claude-sonnet-4-6\", \"claude-haiku-4-5\")` on `SPEC` in runners/claude.py without altering `model_capabilities`, `RUNNER_CAPABILITIES`, `DEFAULT_MODELS`, or `holon models`. (2) In apps/sandbox-executor/src/sandbox_executor/model_tiers.py, add `fallback_ladder(runner)` and `next_fallback_model(runner, current_model, *, is_available=None)` reading `RunnerSpec.quota_fallback_ladder` after normalising `current_model` with `normalise_model_and_effort`, returning the next available rung or `None` when none remains while keeping `tier_ladder`, `next_tier`, and `start_tier` unchanged. (3) In apps/sandbox-executor/src/sandbox_executor/preflight_cooldown.py, extract `_read_marker_at` and add model-scoped cooldown helpers (`model_marker_path`, `record_model_cooldown`, `read_active_model_cooldown`, `clear_model_cooldown`) stored as `--.json` (normalising model aliases) without changing provider-level `marker_path` or `record_cooldown`; `active_cooldown_result` checks provider cooldown then model cooldown, and `sync_cooldown_for_result` clears model cooldown on `ok`. (4) In apps/sandbox-executor/src/sandbox_executor/quota_park.py, add `PLAN_STAGE = \"plan\"`, `park_plan`, and `review_quota_stop` (shared with `park_review`) while keeping `quota_park.py` free of `flow`, `cli`, and `entrypoint` imports. (5) Add apps/sandbox-executor/src/sandbox_executor/quota_step_down.py (new), importing only standard library, `model_tiers`, `preflight_cooldown`, and `quota_park`, providing `step_down_for_quota` to record the exhausted model's cooldown, skip any ladder model already in active model cooldown, advance `context.model`, log the exhausted runner/model, reset hint, and replacement model, and return a step-down record dict (or `None` when exhausted). (6) In apps/sandbox-executor/src/sandbox_executor/entrypoint/planner.py, classify failed non-usable planner turns with `rendered_quota_cause` before `_api_error_of` so quota and monthly spend-limit exits fail via `_fail_plan_attempt` with `\"the planner agent exited with code ()\"` while keeping 400/401 API errors, budget breaches, and usable plans unchanged. (7) In apps/sandbox-executor/src/sandbox_executor/flow/stages/plan.py, wrap `dispatch_planner` inside `PlanStage.produce()` with intra-ladder step-down on `read_quota_stop(failure.error)` (updating `context.model`, recomputing `preferred_suffix`, refreshing `existing_plans`, recording `model_step_downs` in the stage payload when non-empty), and call `park_plan` when the ladder is exhausted, keeping `dispatch_planner()` single-attempt for direct callers. (8) In apps/sandbox-executor/src/sandbox_executor/flow/stages/execute.py, inside `ExecuteStage.run()` within its 430-line budget, step down on a failed stage result whose `summary_row` carries a quota stop, preserve any `partial_head` via `resume_partial`, reset `ExecuteState` keeping `start_time`, retry `_run_steps()`, record `model_step_downs` when non-empty, and call `park_execution` only when the ladder is exhausted. (9) In apps/sandbox-executor/src/sandbox_executor/flow/stages/review.py, inside `_run_review_stage_body()` within its 350-line budget, when the loop fails without `is_dirty`, `MISSING_REF`, `loop_res.get(\"error\")`, or `budget_breach` and `review_quota_stop(reviewers)` finds a quota-failed reviewer matching `context.agent` with iterations remaining, step down `context.model` and re-run `_run_engine_review_loop(context, github=github)`, recording `model_step_downs` when non-empty, and call `park_review` only when the ladder is exhausted; resolver-turn classification in the review-loop container entrypoint is outside this slice. (10) Document Stage 2 quota classification, model-scoped cooldowns, and intra-ladder step-down in docs/budgets.md. (11) Add hermetic tests in apps/sandbox-executor/tests/test_quota_step_down.py (new), apps/sandbox-executor/tests/test_planner_quota.py (new), and apps/sandbox-executor/tests/flow/stages/test_plan_quota_step_down.py (new), and extend apps/sandbox-executor/tests/test_quota_park.py, apps/sandbox-executor/tests/test_preflight_cooldown.py, apps/sandbox-executor/tests/test_runner_specs.py, apps/sandbox-executor/tests/flow/stages/test_execute_steps.py, and apps/sandbox-executor/tests/flow/stages/test_review.py without touching tests/test_planner.py or tests/test_review_loop.py. Never modify holon-config/hygiene/module_budgets.json and keep every module within its existing budget. Never reference harness-specific directories or task-tracker ids in code, tests or documents. Code is self-explaining: no docstrings and no comments except '# why:' comments that record a reason the code cannot show.", "rationale": "Stage 3 and Stage 4 already emit machine-readable quota causes in summaries and failure reasons, and Stage 5 already attributes calibration to the active context model after a model change. Defining the step-down ladder on RunnerSpec and orchestrating intra-stage retries through a pure root step-down helper and stage wrappers in plan.py, execute.py, and review.py avoids modifying pipeline.py or the review loop, keeps every module under its line budget, and eliminates multi-hour idle stalls whenever lower ladder tiers remain available.", "scope": ["apps/sandbox-executor/src/sandbox_executor/runners/spec.py", "apps/sandbox-executor/src/sandbox_executor/runners/antigravity.py", "apps/sandbox-executor/src/sandbox_executor/runners/claude.py", "apps/sandbox-executor/src/sandbox_executor/model_tiers.py", "apps/sandbox-executor/src/sandbox_executor/preflight_cooldown.py", "apps/sandbox-executor/src/sandbox_executor/quota_park.py", "apps/sandbox-executor/src/sandbox_executor/quota_step_down.py (new)", "apps/sandbox-executor/src/sandbox_executor/entrypoint/planner.py", "apps/sandbox-executor/src/sandbox_executor/flow/stages/plan.py", "apps/sandbox-executor/src/sandbox_executor/flow/stages/execute.py", "apps/sandbox-executor/src/sandbox_executor/flow/stages/review.py", "docs/budgets.md", "apps/sandbox-executor/tests/test_quota_step_down.py (new)", "apps/sandbox-executor/tests/test_planner_quota.py (new)", "apps/sandbox-executor/tests/flow/stages/test_plan_quota_step_down.py (new)", "apps/sandbox-executor/tests/test_quota_park.py", "apps/sandbox-executor/tests/test_preflight_cooldown.py", "apps/sandbox-executor/tests/test_runner_specs.py", "apps/sandbox-executor/tests/flow/stages/test_execute_steps.py", "apps/sandbox-executor/tests/flow/stages/test_review.py"], "acceptance_criteria": ["Stage 2 (`entrypoint/planner.py` + `flow/stages/plan.py`), Stage 3 (`flow/stages/execute.py`), and Stage 4 (`flow/stages/review.py`) turns exiting with code `3` (or non-zero planner spend-limit exit) and a quota-exhaustion message automatically retry on the next available fallback model in the runner's ladder (`runners/spec.py`, `runners/antigravity.py`, `runners/claude.py`, `model_tiers.py`) via `quota_step_down.py` without halting the flow, while skipping any rung already marked in active model cooldown (`preflight_cooldown.py`).", "Each fallback step records the exhausted model + reset hint (`reset_at`/`resume_after`) and the replacement model in checkpoint payloads (`model_step_downs`), context logs, and stage ledger rows (`plans.jsonl` on Stage 2 success; `executions.jsonl` summary and `ACT-REV` rows per attempt in Stages 3 and 4), and persists a per-model cooldown marker in `preflight_cooldown.py`.", "When all ladder tiers are exhausted, the flow halts cleanly at the checkpoint without corrupting branch state, recording `quota_park` via `quota_park.py` (`park_plan`, `park_execution`, `park_review`) with `stage`, `exhausted_agent`, `exhausted_model`, `reset_at`, `resume_after`, and `recorded_at`.", "Hermetic tests in `apps/sandbox-executor/tests/test_quota_step_down.py` (new), `apps/sandbox-executor/tests/test_planner_quota.py` (new), `apps/sandbox-executor/tests/flow/stages/test_plan_quota_step_down.py` (new), `apps/sandbox-executor/tests/test_quota_park.py`, `apps/sandbox-executor/tests/test_preflight_cooldown.py`, `apps/sandbox-executor/tests/test_runner_specs.py`, `apps/sandbox-executor/tests/flow/stages/test_execute_steps.py`, and `apps/sandbox-executor/tests/flow/stages/test_review.py` verify ladder step-down, model cooldown persistence/isolation, Stage 2 quota classification, and full-ladder exhaustion; `uv run pytest` passes.", "`docs/budgets.md` documents Stage 2 quota classification, model-scoped cooldown markers, and intra-ladder step-down next to the quota stop record section, and passes `npx prettier --check docs/budgets.md`.", "`uv run python scripts/check_module_budgets.py`, `uv run python scripts/check_self_explaining.py`, `uv run pytest apps/sandbox-executor/tests/test_import_cycle_ratchet.py`, and `uv run pytest apps/sandbox-executor/tests/test_entrypoint_imports.py` pass with `holon-config/hygiene/module_budgets.json` unchanged."], "assumptions": [{"id": "A1", "statement": "The existing quota classifier recognises both Antigravity RESOURCE_EXHAUSTED exits with reset duration and Claude monthly spend-limit text. TESTED NOW on origin/main 1ecfcee68: `rendered_quota_cause(TurnResult(returncode=1, stderr=\"You've hit your monthly spend limit\"), now)` returned `'quota'` and `rendered_quota_cause(TurnResult(returncode=3, stderr='error: Individual quota reached\\nAGY_ERROR: RESOURCE_EXHAUSTED (code 429)\\nResets in 1h45m23s.'), now)` returned `'quota (resets 2026-12-01T05:58Z)'`, both reading back via `read_quota_stop`. Re-tested in Stage 3 by `test_planner_quota.py`.", "impact": "high"}, {"id": "A2", "statement": "Adding `quota_fallback_ladder: tuple[str, ...] = ()` to `RunnerSpec` and populating it on `antigravity` and `claude` preserves `model_capabilities`, `RUNNER_CAPABILITIES`, `DEFAULT_MODELS`, `holon models` counts, and `naming.model_code` across all 8 ladder models. TESTED NOW on origin/main 1ecfcee68: `model_code` and `ticker_for` produce valid ref-safe codes (`ANA-G4N`, `ANA-G4A`, `ANA-G4H`, `ANA-G3.8F`, `CLA-CF5.2`, `CLA-CO5.5`, `CLA-CS4.6`, `CLA-CH4.5`), and `normalise_model_and_effort` resolves all 8 canonical names and aliases cleanly. Re-tested in Stage 3 by `test_runner_specs.py`, `test_models_cli.py`, and `test_quota_step_down.py`.", "impact": "high"}, {"id": "A3", "statement": "Provider-level `preflight_cooldown.py` tests assert that recording a provider cooldown on one Claude model blocks another Claude model (`test_preflight_cooldown.py:149`), so intra-ladder step-down must use a distinct model-scoped marker (`--.json`) rather than changing `record_cooldown`. TESTED NOW by reading `test_preflight_cooldown.py` and `preflight_cooldown.py` (292 of 350 lines). Re-tested in Stage 3 by `test_preflight_cooldown.py`.", "impact": "high"}, {"id": "A4", "statement": "Stage 2, Stage 3, and Stage 4 can perform intra-ladder step-down inside `flow/stages/plan.py` (199/350), `flow/stages/execute.py` (412/430), and `flow/stages/review.py` (297/350) without modifying `flow/pipeline.py`, `flow/review/loop.py`, or `flow/__init__.py` by placing step-down logic in a root module `quota_step_down.py` (outside `flow/`, so `test_package_exports.py` is unaffected and `test_import_cycle_ratchet.py` adds zero cycle edges). TESTED NOW by reading `flow/pipeline.py`, `flow/stages/plan.py`, `flow/stages/execute.py`, `flow/stages/review.py`, `tests/flow/test_package_exports.py`, and `tests/test_import_cycle_ratchet.py`. Re-tested in Stage 3 by running `test_import_cycle_ratchet.py`, `test_package_exports.py`, `test_entrypoint_imports.py`, and `check_module_budgets.py`.", "impact": "high"}, {"id": "A5", "statement": "Existing `quota_park` tests in `test_execute_steps.py` construct `ctx` with `claude-agent` / `claude-opus-5-5` (which now has lower rungs `claude-sonnet-4-6` and `claude-haiku-4-5`) and do not isolate `HOME`; updating those cases to use `claude-haiku-4-5` (exhausted ladder) and isolating `HOME` in `test_execute_steps.py` and `test_review.py` preserves full-ladder-exhaustion coverage without touching real `~/.holon/preflight-cooldown`. TESTED NOW by reading `test_execute_steps.py` and `test_review.py`. Re-tested in Stage 3 by running both files.", "impact": "medium"}, {"id": "A6", "statement": "Baseline tests and hygiene checks pass on origin/main 1ecfcee68: 906 passed in `uv run pytest` across the candidate test files, plus `check_module_budgets.py` (439 modules), `check_self_explaining.py`, `ruff check`, and `npx prettier --check docs/budgets.md`. Re-tested in Stage 3 and Stage 4.", "impact": "low"}], "assumption_validation": [{"assumption_id": "A1", "method": "Already run on origin/main 1ecfcee68; re-run in Stage 3 via `uv run pytest apps/sandbox-executor/tests/test_planner_quota.py`."}, {"assumption_id": "A2", "method": "Already run on origin/main 1ecfcee68; re-run in Stage 3 via `test_runner_specs.py`, `test_models_cli.py`, and `test_quota_step_down.py`."}, {"assumption_id": "A3", "method": "Verified by code inspection; re-tested in Stage 3 via `test_preflight_cooldown.py`."}, {"assumption_id": "A4", "method": "Verified by code inspection; re-tested in Stage 3 via `test_import_cycle_ratchet.py`, `test_package_exports.py`, `test_entrypoint_imports.py`, and `check_module_budgets.py`."}, {"assumption_id": "A5", "method": "Verified by reading `test_execute_steps.py` and `test_review.py`; re-tested in Stage 3 by running those test files."}, {"assumption_id": "A6", "method": "Already run on origin/main 1ecfcee68; re-run in Stage 3 and Stage 4."}], "assumption_risk": [{"assumption_id": "A1", "likelihood": "low", "testability": "testable", "score": 1, "response": "fail fast in `test_planner_quota.py`; adjust classifier call order if needed"}, {"assumption_id": "A2", "likelihood": "low", "testability": "testable", "score": 1, "response": "fail fast in `test_runner_specs.py` or `test_models_cli.py`"}, {"assumption_id": "A3", "likelihood": "low", "testability": "testable", "score": 1, "response": "fail fast in `test_preflight_cooldown.py`"}, {"assumption_id": "A4", "likelihood": "medium", "testability": "testable", "score": 2, "response": "fail fast in `check_module_budgets.py` or `test_import_cycle_ratchet.py`; keep `execute.py` diff minimal within 18 lines of headroom"}, {"assumption_id": "A5", "likelihood": "low", "testability": "testable", "score": 1, "response": "fail fast in `test_execute_steps.py` and `test_review.py`"}, {"assumption_id": "A6", "likelihood": "low", "testability": "testable", "score": 1, "response": "re-run full baseline suite in Stage 3"}], "branch": "I-1796130017-quota-intra-ladder-step-down", "status": "proposed", "created_at": "2026-12-01T13:00:33.111Z"} From 435525f907c0c6707034eee62b285aee6beedd17 Mon Sep 17 00:00:00 2001 From: Holon Planner Agent Date: Tue, 1 Dec 2026 13:05:21 +0000 Subject: [PATCH 02/17] plan: P-1796130057-CLA-CO5.5 created by claude-agent (claude-opus-5-5) --- ...6130017-quota-intra-ladder-step-down.jsonl | 1 + .../P-1796130057-CLA-CO5.5.md | 866 ++++++++++++++++++ 2 files changed, 867 insertions(+) create mode 100644 holon-knowledge/ledger/pending/plans/I-1796130017-quota-intra-ladder-step-down.jsonl create mode 100644 plans/I-1796130017-quota-intra-ladder-step-down/P-1796130057-CLA-CO5.5.md diff --git a/holon-knowledge/ledger/pending/plans/I-1796130017-quota-intra-ladder-step-down.jsonl b/holon-knowledge/ledger/pending/plans/I-1796130017-quota-intra-ladder-step-down.jsonl new file mode 100644 index 000000000..0395a4daf --- /dev/null +++ b/holon-knowledge/ledger/pending/plans/I-1796130017-quota-intra-ladder-step-down.jsonl @@ -0,0 +1 @@ +{"plan_id": "P-1796130057-CLA-CO5.5", "intent_branch": "I-1796130017-quota-intra-ladder-step-down/_", "agent": "claude-agent", "agent_version": "2.1.302", "model": "claude-opus-5-5", "p_success": 0.65, "entropy": 13.5, "impact": 85.0, "cost": 22.0, "learning_value": 6.0, "ev": 32.2, "created_at": "2026-12-01T13:05:15.597Z", "plan_file": "plans/I-1796130017-quota-intra-ladder-step-down/P-1796130057-CLA-CO5.5.md", "status": "proposed", "entropy_budget": 15.0, "decomposition_decision": "execute", "touch_set": [{"path": "apps/sandbox-executor/src/sandbox_executor/runners/spec.py"}, {"path": "apps/sandbox-executor/src/sandbox_executor/runners/antigravity.py"}, {"path": "apps/sandbox-executor/src/sandbox_executor/runners/claude.py"}, {"path": "apps/sandbox-executor/src/sandbox_executor/model_tiers.py"}, {"path": "apps/sandbox-executor/src/sandbox_executor/preflight_cooldown.py"}, {"path": "apps/sandbox-executor/src/sandbox_executor/quota_park.py"}, {"path": "apps/sandbox-executor/src/sandbox_executor/quota_step_down.py"}, {"path": "apps/sandbox-executor/src/sandbox_executor/entrypoint/planner.py"}, {"path": "apps/sandbox-executor/src/sandbox_executor/flow/stages/plan.py"}, {"path": "apps/sandbox-executor/src/sandbox_executor/flow/stages/execute.py"}, {"path": "apps/sandbox-executor/src/sandbox_executor/flow/stages/review.py"}, {"path": "docs/budgets.md"}, {"path": "apps/sandbox-executor/tests/test_quota_step_down.py"}, {"path": "apps/sandbox-executor/tests/test_planner_quota.py"}, {"path": "apps/sandbox-executor/tests/flow/stages/test_plan_quota_step_down.py"}, {"path": "apps/sandbox-executor/tests/test_quota_park.py"}, {"path": "apps/sandbox-executor/tests/test_preflight_cooldown.py"}, {"path": "apps/sandbox-executor/tests/test_runner_specs.py"}, {"path": "apps/sandbox-executor/tests/flow/stages/test_execute_steps.py"}, {"path": "apps/sandbox-executor/tests/flow/stages/test_review.py"}]} diff --git a/plans/I-1796130017-quota-intra-ladder-step-down/P-1796130057-CLA-CO5.5.md b/plans/I-1796130017-quota-intra-ladder-step-down/P-1796130057-CLA-CO5.5.md new file mode 100644 index 000000000..217e25bd2 --- /dev/null +++ b/plans/I-1796130017-quota-intra-ladder-step-down/P-1796130057-CLA-CO5.5.md @@ -0,0 +1,866 @@ +# Plan for I-1796130017-quota-intra-ladder-step-down + +- **Plan ID:** P-1796130057-CLA-CO5.5 +- **Parent Intent ID:** NONE +- **Agent:** claude-agent/claude-opus-5-5 (version: 2.1.302) +- **Created At:** 2026-12-01T13:01:01.721Z + +## Planner Autonomy Summary + +- **Intent handling:** ACCEPT_AS_IS +- **Reframed intent (if applicable):** N/A. One clarification only: the "stage ledger rows" acceptance criterion is met + by the rows each attempt already writes under its own model (the container's `plans.jsonl` row for the plan that + succeeds, one `executions.jsonl` summary row per Stage 3 attempt, `ACT-REV` rows per Stage 4 pass); the host adds + `model_step_downs` to the stage payload that the checkpoint persists. No new host-side ledger writer is added. +- **Exploration stance:** balanced. The data layer (ladder, cooldown markers, park records, step-down helper) is routine + exploit work; the three stage wrappers carry real uncertainty (the Stage 3 retry inside an 18-line headroom, the + resume/salvage path on a retried execution, and re-running the review loop against its iteration budget), so those + steps are planned as BALANCED with explicit early-abort checks. +- **Safety priority level:** elevated +- **Priority Justification:** The change alters which model a running flow uses after a failure in Stages 2-4 and writes + state under `~/.holon/preflight-cooldown`. `docs/safety.md` "Git is the safety boundary" and "Failure containment" + require that a retried attempt never corrupts branch state, and `holon-config/world/constraints.md` §3 (ledger + immutability) requires retries to append, never rewrite, ledger rows. Tests must isolate `HOME` so the host user's + cooldown directory is never touched. + +## Exploration + +- **Proportion of steps that are exploratory:** 0.3 +- **Justification:** Three of ten steps (Stage 2, 3, 4 wrappers) are BALANCED: each validates a hypothesis about how an + existing stage behaves when re-entered with a new model. The rest is deterministic plumbing with fast unit tests. + +## Overall Plan Metrics + +| metric | value | +| ------------------- | ----- | +| p_success_pred | 0.65 | +| entropy_pred | 13.5 | +| impact_pred | 85.0 | +| cost_pred | 22.0 | +| learning_value_pred | 6.0 | +| ev_pred | 32.2 | + +## Plan Description & Strategy + +Implement bottom-up so each layer is tested before the stage that uses it: + +1. Data: `RunnerSpec.quota_fallback_ladder` plus `model_tiers.fallback_ladder` / `next_fallback_model`. +2. State: model-scoped cooldown markers `--.json` in `preflight_cooldown.py`, next to (not replacing) + the provider marker. +3. Records: `PLAN_STAGE`, `park_plan`, `review_quota_stop` in `quota_park.py`. +4. Policy: a new root module `quota_step_down.py` (stdlib + `model_tiers` + `preflight_cooldown` + `quota_park` only) + with `step_down_for_quota`, typed against a small `Protocol` (agent, model, log) so it never imports `flow`. +5. Classification: the Stage 2 container entrypoint renders quota stops so the host can read them with + `read_quota_stop`. +6. Orchestration: thin wrappers in `flow/stages/plan.py`, `flow/stages/execute.py`, and `flow/stages/review.py` that + loop "run, read quota stop, step down, re-run" and call the existing `park_*` only when the ladder is exhausted. +7. Docs and the hygiene/test gates. + +`flow/pipeline.py`, `flow/review/loop.py`, `flow/__init__.py`, `holon-config/hygiene/module_budgets.json`, +`tests/test_planner.py` and `tests/test_review_loop.py` are not touched. Measured headroom on the current tree: +`plan.py` 199/350, `execute.py` 412/430, `review.py` 297/350, `entrypoint/planner.py` 581/655, `preflight_cooldown.py` +292/350, `quota_park.py` 123/350, `model_tiers.py` 37/350, `runners/spec.py` 103/350. + +Test runs: each step runs its affected test files with `uv run pytest ` in the foreground; Step 10 runs the +hygiene scripts and then the full suite once with `uv run task test`. No repeated runs: the intent measures no timing. + +## Touch Set + +- `apps/sandbox-executor/src/sandbox_executor/runners/spec.py` +- `apps/sandbox-executor/src/sandbox_executor/runners/antigravity.py` +- `apps/sandbox-executor/src/sandbox_executor/runners/claude.py` +- `apps/sandbox-executor/src/sandbox_executor/model_tiers.py` +- `apps/sandbox-executor/src/sandbox_executor/preflight_cooldown.py` +- `apps/sandbox-executor/src/sandbox_executor/quota_park.py` +- `apps/sandbox-executor/src/sandbox_executor/quota_step_down.py` +- `apps/sandbox-executor/src/sandbox_executor/entrypoint/planner.py` +- `apps/sandbox-executor/src/sandbox_executor/flow/stages/plan.py` +- `apps/sandbox-executor/src/sandbox_executor/flow/stages/execute.py` +- `apps/sandbox-executor/src/sandbox_executor/flow/stages/review.py` +- `docs/budgets.md` +- `apps/sandbox-executor/tests/test_quota_step_down.py` +- `apps/sandbox-executor/tests/test_planner_quota.py` +- `apps/sandbox-executor/tests/flow/stages/test_plan_quota_step_down.py` +- `apps/sandbox-executor/tests/test_quota_park.py` +- `apps/sandbox-executor/tests/test_preflight_cooldown.py` +- `apps/sandbox-executor/tests/test_runner_specs.py` +- `apps/sandbox-executor/tests/flow/stages/test_execute_steps.py` +- `apps/sandbox-executor/tests/flow/stages/test_review.py` + +--- + +## Step 1: Declare the quota fallback ladder on RunnerSpec and resolve the next rung in model_tiers + +- **Sub‑intent recommendation:** NO +- **Reasoning:** Small, additive data change with a default of `()`; low risk and fully covered by fast unit tests. +- **Step Type:** CONFIG +- **Exploration level:** EXPLOIT + +### Intent & Git Integration + +- **Step Intent:** Give each runner an ordered, declarative quota fallback ladder and a pure lookup for the next rung. +- **Git branch:** execution branch of this plan (no separate branch) +- **Sub‑intent:** NONE + +### Implementation Details (No code blocks, only logic/steps) + +- In `runners/spec.py` add the field `quota_fallback_ladder: tuple[str, ...] = ()` to `RunnerSpec` after the existing + defaulted fields (tuples are hashable, so `frozen=True` hashing is unaffected). +- In `runners/antigravity.py` pass + `quota_fallback_ladder=("gemini-4-neon", "gemini-4-argon", "gemini-4-hydrogen", "gemini-3.8-flash")` to `SPEC`; in + `runners/claude.py` pass `("claude-fable-5-2", "claude-opus-5-5", "claude-sonnet-4-6", "claude-haiku-4-5")`. Do not + touch `model_capabilities`, `RUNNER_CAPABILITIES`, `DEFAULT_MODELS` or the `holon models` command. +- In `model_tiers.py` add `fallback_ladder(runner) -> tuple[str, ...]` that looks up the runner's spec through the + existing spec registry (the same lookup `agent_defaults` uses; `model_tiers` already imports `agent_defaults`, so no + new cycle edge) after normalising the agent id, and returns `()` for unknown runners. +- Add `next_fallback_model(runner, current_model, *, is_available=None) -> str | None`: normalise `current_model` with + `normalise_model_and_effort(runner, current_model)[0]`; return `None` when it is not on the ladder; otherwise return + the first later rung for which `is_available(rung)` is true (all rungs when `is_available` is `None`), or `None`. +- Leave `tier_ladder`, `next_tier`, `start_tier` byte-identical. +- Extend `tests/test_runner_specs.py`: both ladders are exactly the declared tuples; every rung normalises to itself via + `normalise_model_and_effort`; every rung is a canonical model of its runner's capabilities; runners other than + `antigravity`/`claude` have `()`; `next_fallback_model` walks the ladder, resolves an alias of `claude-opus-5-5` to + `claude-sonnet-4-6`, skips unavailable rungs, and returns `None` from the last rung and from an off-ladder model. +- Run + `uv run pytest apps/sandbox-executor/tests/test_runner_specs.py apps/sandbox-executor/tests/test_models_cli.py apps/sandbox-executor/tests/test_naming.py`. + +### Dependencies & Criticality + +- **Depends on:** NONE +- **Is Bottleneck:** YES (every later step reads the ladder), but p_success is high. + +### Safety & Constraint Considerations + +- **Relevant rules:** `holon-config/world/ruleset.md` §2 (typing, imports discipline); the `runners/spec.py` "# why:" + rule that the runners package must not import `agent_defaults`. +- **Potential failure modes for this step:** a ladder rung that is not a registered canonical model (e.g. a typo or a + model only reachable by alias) silently never matches; `holon models` output drifts if the field leaks into rendering. +- **Guardrails and early‑abort checks:** the "every rung is a canonical capability" test fails fast; + `test_models_cli.py` pins `holon models` output. + +### Success & Discard Criteria + +- **Success:** the three listed test files pass; `git diff` of `agent_defaults.py` and the models CLI is empty. +- **Discard:** a rung is not a registered model and the intent forbids editing capabilities: stop and report rather than + altering `model_capabilities`. + +### Metrics + +| metric | value | +| ------------------- | ----- | +| p_success_pred | 0.92 | +| entropy_pred | 1.0 | +| impact_pred | 60.0 | +| cost_pred | 3.0 | +| learning_value_pred | 3.0 | +| ev_pred | 53.4 | + +### Step Metrics Rationale + +`EV = 0.92 * 60 + 0.5 * 3 - 0.3 * 1.0 - 3 = 55.2 + 1.5 - 0.3 - 3 = 53.4`. Additive field plus a 15-line pure function; +the intent's A2 already verified naming and normalisation for all 8 rungs. + +--- + +## Step 2: Add model-scoped cooldown markers beside the provider marker + +- **Sub‑intent recommendation:** NO +- **Reasoning:** Contained to one module (292/350 lines) and its test file; the provider-level contract is pinned by + existing tests, so regressions surface immediately. +- **Step Type:** IMPLEMENTATION +- **Exploration level:** EXPLOIT + +### Intent & Git Integration + +- **Step Intent:** Persist a per-model quota cooldown so a step-down skips rungs that are known exhausted, without + changing provider-wide cooldown behaviour. +- **Git branch:** execution branch of this plan +- **Sub‑intent:** NONE + +### Implementation Details (No code blocks, only logic/steps) + +- Extract `_read_marker_at(path, *, now)` from `read_active_cooldown` (open, JSON-load, unlink on corrupt or expired, + return the parsed `CooldownMarker` or `None`); `read_active_cooldown(agent)` becomes a one-line call with + `marker_path(agent)`. +- Add `model_marker_path(agent, model)`: provider via `normalise_agent_id`, model via + `normalise_model_and_effort(provider, model)[0]` (so an alias and its canonical name share one file), both passed + through `_SAFE_FILENAME_RE`, file name `--.json` in `cooldown_dir()`. `marker_path` stays unchanged + (the `--` separator cannot collide with a provider file name). +- Add `record_model_cooldown(agent, model, output, *, now=None, ttl_seconds=None)` mirroring `record_cooldown` but + writing to `model_marker_path` with `model` stored as the normalised name; reuse `_write_marker_atomic`, `_clamp_ttl`, + `parse_cooldown_ttl`, `redact_output`. +- Add `read_active_model_cooldown(agent, model, *, now=None)` and `clear_model_cooldown(agent, model)`. +- `active_cooldown_result`: after the provider check returns no marker, check `read_active_model_cooldown(agent, model)` + and build the same `PreflightResult` via `build_cooldown_result`. +- `sync_cooldown_for_result`: on `result.ok and not result.skipped` also call + `clear_model_cooldown(result.agent, result.model)`. Do not record model cooldowns from preflight (`record_cooldown` + stays provider-level, keeping the `test_preflight_cooldown.py:149` contract). +- Import `normalise_model_and_effort` from `agent_defaults` (already imported module, no new edge). +- Extend `tests/test_preflight_cooldown.py` (HOME isolated via the file's existing fixture): file name for alias and + canonical is identical; a model marker for `claude-opus-5-5` does not block `claude-sonnet-4-6`; a provider marker + still blocks every model; expiry and corrupt files are unlinked; `active_cooldown_result` reports a model cooldown; an + ok preflight clears the model marker; `record_cooldown`/`marker_path` outputs are unchanged. +- Run + `uv run pytest apps/sandbox-executor/tests/test_preflight_cooldown.py apps/sandbox-executor/tests/test_preflight.py apps/sandbox-executor/tests/test_preflight_retries.py`. + +### Dependencies & Criticality + +- **Depends on:** NONE +- **Is Bottleneck:** NO (step-down still works without skipping cooled rungs, but acceptance needs it) + +### Safety & Constraint Considerations + +- **Relevant rules:** `docs/safety.md` Invariant 6 (immutability of shared state); hermetic testing + (`apps/sandbox-executor/docs/hermetic_testing.md`): tests never write the real `~/.holon`. +- **Potential failure modes for this step:** module grows past 350 lines; `_clamp_ttl` caps a long reset (e.g. 1h45m) at + 3600 s, so a rung may be retried once before its real reset. +- **Guardrails and early‑abort checks:** count lines after the edit (target <= 340); the capped TTL is accepted (the + retry just steps down again) and noted in docs. + +### Success & Discard Criteria + +- **Success:** the three test files pass; `preflight_cooldown.py` stays at or below 350 lines. +- **Discard:** if the module exceeds its budget, share one `_record_marker(path, ...)` helper between the provider and + model writers; if it still exceeds 350 lines, stop and report (the budget file is frozen). + +### Metrics + +| metric | value | +| ------------------- | ----- | +| p_success_pred | 0.88 | +| entropy_pred | 1.6 | +| impact_pred | 65.0 | +| cost_pred | 4.0 | +| learning_value_pred | 3.0 | +| ev_pred | 54.2 | + +### Step Metrics Rationale + +`EV = 0.88 * 65 + 0.5 * 3 - 0.3 * 1.6 - 4 = 57.2 + 1.5 - 0.48 - 4 = 54.22`. The 58-line headroom is the main risk; the +helpers reuse existing private functions so the expected growth is about 40 lines. + +--- + +## Step 3: Add the plan-stage park record and a shared review quota-stop reader + +- **Sub‑intent recommendation:** NO +- **Reasoning:** Pure functions in a 123-line module with an existing test file; trivially reversible. +- **Step Type:** IMPLEMENTATION +- **Exploration level:** EXPLOIT + +### Intent & Git Integration + +- **Step Intent:** Let Stage 2 park on full-ladder exhaustion, and let Stage 4 find the quota-failed reviewer before + deciding to step down or park. +- **Git branch:** execution branch of this plan +- **Sub‑intent:** NONE + +### Implementation Details (No code blocks, only logic/steps) + +- Add `PLAN_STAGE = "plan"` beside `EXECUTE_STAGE`/`REVIEW_STAGE`. +- Add `park_plan(payload, runner: ExhaustedRunner, stop: QuotaStop, recorded_at, log)` that attaches + `build_record(PLAN_STAGE, runner, stop, recorded_at)` through `_attach`. +- Add `review_quota_stop(reviewers) -> tuple[Mapping, QuotaStop] | None`: collect `(reviewer, stop)` pairs from + `read_quota_stop(reviewer.get("failure_reason"))`, return `None` when empty, else `_latest_reset(...)`. +- Rewrite `park_review` to call `review_quota_stop` and keep its observable behaviour identical (latest named reset, + else first). +- Keep imports unchanged (no `flow`, `cli`, `entrypoint`). +- Extend `tests/test_quota_park.py`: `park_plan` record fields (`stage == "plan"`, agent, model, `reset_at`, + `resume_after` = reset + 60 s, `recorded_at`), bare quota gives null times, the log line contains `parked_quota`; + `review_quota_stop` returns `None` for no quota reviewer and picks the latest reset otherwise; an import-scan + assertion that `quota_park` imports nothing under `sandbox_executor.flow`, `.cli` or `.entrypoint`. +- Run + `uv run pytest apps/sandbox-executor/tests/test_quota_park.py apps/sandbox-executor/tests/flow/stages/test_review.py`. + +### Dependencies & Criticality + +- **Depends on:** NONE +- **Is Bottleneck:** NO + +### Safety & Constraint Considerations + +- **Relevant rules:** `KB-failure-bidirectional-flow-entrypoint-cycle` (keep root modules free of flow imports). +- **Potential failure modes for this step:** refactoring `park_review` changes which reviewer is recorded. +- **Guardrails and early‑abort checks:** existing `test_review.py` park tests (latest reset, bare quota, no park) must + stay green unchanged. + +### Success & Discard Criteria + +- **Success:** both test files pass with the existing park assertions untouched. +- **Discard:** any existing park assertion has to change to pass: revert the `park_review` refactor and duplicate the + selection inside `review_quota_stop` instead. + +### Metrics + +| metric | value | +| ------------------- | ----- | +| p_success_pred | 0.92 | +| entropy_pred | 0.9 | +| impact_pred | 55.0 | +| cost_pred | 2.5 | +| learning_value_pred | 2.0 | +| ev_pred | 48.8 | + +### Step Metrics Rationale + +`EV = 0.92 * 55 + 0.5 * 2 - 0.3 * 0.9 - 2.5 = 50.6 + 1.0 - 0.27 - 2.5 = 48.83`. Tiny, well-tested surface. + +--- + +## Step 4: Add the quota_step_down module + +- **Sub‑intent recommendation:** NO +- **Reasoning:** New, isolated root module whose import set is fixed by the intent; it is the reusable core of the + feature, but it is small enough (about 60 lines) to land with its callers. +- **Step Type:** IMPLEMENTATION +- **Exploration level:** EXPLOIT + +### Intent & Git Integration + +- **Step Intent:** One policy function every stage calls: record the exhausted rung, pick the next available rung, + switch the flow to it, and return an auditable record. +- **Git branch:** execution branch of this plan +- **Sub‑intent:** NONE + +### Implementation Details (No code blocks, only logic/steps) + +- Create `apps/sandbox-executor/src/sandbox_executor/quota_step_down.py` importing only stdlib (`datetime`, `typing`), + `sandbox_executor.model_tiers`, `sandbox_executor.preflight_cooldown`, `sandbox_executor.quota_park`. +- Define a `StepDownTarget` `Protocol` with attributes `agent: str`, `model: str` and method `log(message: str)`, so + `FlowContext` satisfies it without importing `flow`. +- `step_down_for_quota(context, exhausted: ExhaustedRunner, stop: QuotaStop, *, now: datetime | None = None) -> dict | None`: + - compute `now` (UTC) and the cooldown TTL as `stop.reset_at - now` in seconds when a reset is named and in the + future, else `None` (default TTL); + - `record_model_cooldown(exhausted.agent, exhausted.model, , now=..., ttl_seconds=...)`; + - `replacement = next_fallback_model(context.agent, exhausted.model, is_available=)`; + return `None` when it is `None`; + - build the record with `build_record`-compatible times: `exhausted_agent`, `exhausted_model`, `reset_at`, + `resume_after` (reset + `RESUME_MARGIN`), `replacement_model`, `recorded_at`; + - set `context.model = replacement` and log one line naming the exhausted runner/model, the reset hint (or "no reset + time was named") and the replacement model, e.g. + `Quota step-down: claude-agent / claude-opus-5-5 is out of quota (resume after ...); continuing on claude-sonnet-4-6.` +- Return `None` without side effects on `context.model` when the stop's agent differs from `context.agent` (caller + guards this too). +- Create `tests/test_quota_step_down.py` (HOME isolated with `monkeypatch.setenv("HOME", tmp_path)`; a tiny dataclass + stands in for the context): steps from opus to sonnet and writes `claude-agent--claude-opus-5-5.json`; skips a rung + with an active model cooldown; returns `None` and leaves `context.model` unchanged at `claude-haiku-4-5`; Antigravity + ladder walks neon -> argon -> hydrogen -> 3.8-flash; record carries `reset_at`/`resume_after`; the log line names both + models; an AST import scan proves only the allowed imports. +- Run + `uv run pytest apps/sandbox-executor/tests/test_quota_step_down.py apps/sandbox-executor/tests/test_import_cycle_ratchet.py`. + +### Dependencies & Criticality + +- **Depends on:** Step 1, Step 2, Step 3 +- **Is Bottleneck:** YES (all three stage wrappers call it) + +### Safety & Constraint Considerations + +- **Relevant rules:** `test_import_cycle_ratchet.py` (no new cycle edges); code placement rule (one module per concern); + self-explaining code gate. +- **Potential failure modes for this step:** an import cycle via `preflight_cooldown -> agent_defaults`; a TTL derived + from a past reset time. +- **Guardrails and early‑abort checks:** run the cycle ratchet immediately after creating the module; clamp negative + TTLs by passing `None`. + +### Success & Discard Criteria + +- **Success:** new tests pass; ratchet reports zero new edges. +- **Discard:** a cycle appears that cannot be broken by import placement: stop and report rather than editing the + ratchet baseline. + +### Metrics + +| metric | value | +| ------------------- | ----- | +| p_success_pred | 0.88 | +| entropy_pred | 1.5 | +| impact_pred | 75.0 | +| cost_pred | 4.0 | +| learning_value_pred | 4.0 | +| ev_pred | 63.6 | + +### Step Metrics Rationale + +`EV = 0.88 * 75 + 0.5 * 4 - 0.3 * 1.5 - 4 = 66 + 2 - 0.45 - 4 = 63.55`. High impact because it is the shared core; risk +is limited to import hygiene. + +--- + +## Step 5: Classify Stage 2 planner quota stops in the container entrypoint + +- **Sub‑intent recommendation:** NO +- **Reasoning:** A single early branch in the planner's failure path plus a new focused test file; does not touch + `tests/test_planner.py`. +- **Step Type:** IMPLEMENTATION +- **Exploration level:** EXPLOIT + +### Intent & Git Integration + +- **Step Intent:** Make a quota or monthly spend-limit planner exit report a machine-readable quota cause instead of an + empty or invalid plan. +- **Git branch:** execution branch of this plan +- **Sub‑intent:** NONE + +### Implementation Details (No code blocks, only logic/steps) + +- In `entrypoint/planner.py`, right after `result = outcome.last` / `report = outcome.report` and before the + `_api_error_of` call, add: when `result.returncode != 0` and the report is not usable and + `rendered_quota_cause(result, datetime.now(UTC))` returns a cause, call + `_fail_plan_attempt(repo_dir, plan_md_rel, f"the planner agent exited with code {result.returncode} ({cause})")`. + Extract it into a small `_quota_stop_of(outcome) -> str | None` helper to keep the run function's complexity flat. +- Import `rendered_quota_cause` from `sandbox_executor.quota_park` (root module; allowed by + `test_entrypoint_imports.py`). +- The rendered failure detail reaches the host as + `Plan stage failed: the planner agent exited with code 3 (quota (resets ...)) (planner agent exited with code 1)`; the + first `code N (quota...)` occurrence matches `read_quota_stop`. +- Create `tests/test_planner_quota.py` reusing the planner fixtures that `test_planner_api_error`/`test_plan_attempt` + use (fake runner returning a `TurnResult`): Antigravity `returncode=3` RESOURCE_EXHAUSTED with `Resets in 1h45m23s.` + writes a failure detail that `read_quota_stop` parses with a reset; Claude `returncode=1` "You've hit your monthly + spend limit" yields `(quota)`; a 400/401 API error still reports "API call failed"; a budget breach keeps its message; + a usable plan with a non-zero exit still succeeds. +- Run + `uv run pytest apps/sandbox-executor/tests/test_planner_quota.py apps/sandbox-executor/tests/test_planner.py apps/sandbox-executor/tests/test_agent_api_error.py apps/sandbox-executor/tests/test_entrypoint_imports.py`. + +### Dependencies & Criticality + +- **Depends on:** NONE (uses existing `rendered_quota_cause`) +- **Is Bottleneck:** YES for Stage 2 step-down (without it the host cannot see a quota stop) + +### Safety & Constraint Considerations + +- **Relevant rules:** entrypoints must not import `flow.pipeline`/`flow.stages`/`cli`; redaction is applied by + `_fail_plan_attempt`. +- **Potential failure modes for this step:** an API 429 that the API-error classifier used to report now reports as + quota (intended); the planner's ruff complexity rises past limits. +- **Guardrails and early‑abort checks:** run `ruff check` on the file; keep the new branch in a helper. + +### Success & Discard Criteria + +- **Success:** listed tests pass; `tests/test_planner.py` unchanged and green. +- **Discard:** an existing planner test's expectation would have to change: narrow the classification to + `returncode != 0` with no usable report and no `budget_failure` and retry. + +### Metrics + +| metric | value | +| ------------------- | ----- | +| p_success_pred | 0.85 | +| entropy_pred | 1.3 | +| impact_pred | 70.0 | +| cost_pred | 3.5 | +| learning_value_pred | 4.0 | +| ev_pred | 57.6 | + +### Step Metrics Rationale + +`EV = 0.85 * 70 + 0.5 * 4 - 0.3 * 1.3 - 3.5 = 59.5 + 2 - 0.39 - 3.5 = 57.61`. A1 verified the classifier; the main risk +is fixture reuse in the new test file. + +--- + +## Step 6: Step down the planner model inside PlanStage.produce + +- **Sub‑intent recommendation:** NO +- **Reasoning:** `plan.py` has 150 lines of headroom and the retry is a loop around one existing method; the risk is + behavioural (branch discovery after a model change), which is better learnt in-plan than in a separate branch. +- **Step Type:** IMPLEMENTATION +- **Exploration level:** BALANCED + +- **Hypothesis being tested:** re-running `dispatch_planner` after a quota failure with a refreshed `existing_plans` + snapshot and a recomputed `preferred_suffix` adopts only the new model's plan branch, never the failed attempt's + salvage branch. +- **Learning target:** whether a failed planner's pushed salvage branch is excluded by the refreshed snapshot. +- **Maximum acceptable cost for this learning:** 1.5x this step's `cost_pred`. + +### Intent & Git Integration + +- **Step Intent:** A Stage 2 quota stop retries on the next ladder rung and parks only when the ladder is exhausted. +- **Git branch:** execution branch of this plan +- **Sub‑intent:** NONE + +### Implementation Details (No code blocks, only logic/steps) + +- Add `model_step_downs: list[dict[str, Any]]` (default empty) to the `PlanStage` dataclass. +- Add `dispatch_with_step_down()`: loop calling `self.dispatch_planner()`; on success return `None`; on failure read + `stop = read_quota_stop(failure.error)`; when `stop` is `None` return the failure; otherwise call + `step_down_for_quota(self.context, ExhaustedRunner(context.agent, context.model), stop)`. When it returns `None`, call + `park_plan(failure.payload, ExhaustedRunner(...), stop, _utc_now(), context.log)` and return the failure. Else append + the record, call `self.resolve_suffix()` (return its failure if any) and refresh `self.existing_plans` with the same + snapshot logic as `prepare()` (extract `_snapshot_existing_plans()` used by both), then loop. +- In `produce()` replace `self.dispatch_planner` in the step tuple with `self.dispatch_with_step_down`; + `dispatch_planner()` stays single-attempt for direct callers. +- In `run_plan_stage`, after building `payload` add `payload["model_step_downs"] = stage.model_step_downs` when + non-empty. On failure, also attach it to the failure payload when non-empty (so the checkpoint records the attempts + before parking). +- The ladder is finite (4 rungs) so the loop terminates; no extra cap needed. +- Create `tests/flow/stages/test_plan_quota_step_down.py` using the patching style of `test_plan_api_error.py` + (monkeypatch `_dispatch_role`, `publish_planned_branches`, `settle_failed_plan_attempt`, snapshots; HOME isolated): + first dispatch fails with a quota detail, second succeeds -> `context.model` is `claude-sonnet-4-6`, the second + dispatch receives the new model in its args, `preferred_suffix` ends `-CLA-CS4.6`, payload has one `model_step_downs` + entry, a model marker exists for opus; a rung in cooldown is skipped; at `claude-haiku-4-5` the stage fails with + `quota_park.stage == "plan"`; a non-quota failure neither steps down nor parks; `dispatch_planner` alone still makes + exactly one attempt. +- Run + `uv run pytest apps/sandbox-executor/tests/flow/stages/test_plan_quota_step_down.py apps/sandbox-executor/tests/flow/stages/test_plan_api_error.py apps/sandbox-executor/tests/flow/stages/test_plan_resume_adopts_branch.py apps/sandbox-executor/tests/flow/stages/test_plan_support.py`. + +### Dependencies & Criticality + +- **Depends on:** Step 3, Step 4, Step 5 +- **Is Bottleneck:** NO (Stages 3 and 4 still deliver value independently) + +### Safety & Constraint Considerations + +- **Relevant rules:** `docs/safety.md` "Git is the safety boundary"; `holon-config/world/constraints.md` §1 (plan + branches named per model code). +- **Potential failure modes for this step:** the failed attempt's salvage plan branch is adopted as the new plan; + `MissingTickerError` for a rung (ruled out by A2). +- **Guardrails and early‑abort checks:** the snapshot refresh test asserts the salvage branch is excluded; the + `_discover_child_branch` preferred-suffix match pins the new model's branch. + +### Success & Discard Criteria + +- **Success:** listed tests pass; `plan.py` <= 350 lines. +- **Discard:** adoption picks the wrong branch and cannot be fixed by the snapshot refresh within 1.5x cost: keep the + classification (Step 5) and park-only behaviour for Stage 2, and record the gap in the execution report. + +### Metrics + +| metric | value | +| ------------------- | ----- | +| p_success_pred | 0.80 | +| entropy_pred | 1.9 | +| impact_pred | 75.0 | +| cost_pred | 5.0 | +| learning_value_pred | 5.0 | +| ev_pred | 56.9 | + +### Step Metrics Rationale + +`EV = 0.80 * 75 + 0.5 * 5 - 0.3 * 1.9 - 5 = 60 + 2.5 - 0.57 - 5 = 56.93`. Moderate uncertainty about branch adoption +after a retry; good learning value about the plan-branch lifecycle. + +--- + +## Step 7: Step down the executor model inside ExecuteStage.run within the 430-line budget + +- **Sub‑intent recommendation:** NO +- **Reasoning:** Riskiest step (18 lines of headroom, re-entering salvage/resume), but splitting it out would not lower + risk: it needs Steps 1-4 in the same tree. Strict early-abort checks are used instead. +- **Step Type:** IMPLEMENTATION +- **Exploration level:** BALANCED + +- **Hypothesis being tested:** resetting `ExecuteState` (keeping `start_time`) and re-running `_run_steps()` with + `resume_partial=True` re-dispatches the executor on the new model and continues from the failed attempt's + `partial_head`, without the admission check counting the flow's own failed branch as a conflict. +- **Learning target:** how `salvage_partial`, `_republish_recorded_execution` and admission behave on an in-process + retry. +- **Maximum acceptable cost for this learning:** 1.5x this step's `cost_pred`. + +### Intent & Git Integration + +- **Step Intent:** A Stage 3 quota stop retries on the next rung, keeping partial work, and parks only when the ladder + is exhausted. +- **Git branch:** execution branch of this plan +- **Sub‑intent:** NONE + +### Implementation Details (No code blocks, only logic/steps) + +- Rewrite `ExecuteStage.run()` (about +12 lines net): run `_run_steps()`; while the result failed and + `self._step_down()` returns a record, append it, set `self.resume_partial = True`, replace `self.state` with + `ExecuteState(start_time=self.state.start_time)`, and re-run `_run_steps()`. When records exist set + `result.payload["model_step_downs"]`. Keep the existing `park_execution` call for failures, which now only fires when + the ladder is exhausted (step-down returned `None`). +- `_step_down()` (about 6 lines): read `read_quota_stop(summary_row.get("summary"))` from `self.state.summary_row`; + return `None` without a row or stop; build `ExhaustedRunner` from the row's agent/model with the context fallback + (same as `park_execution`); return `step_down_for_quota(self.context, runner, stop)`. +- Import `read_quota_stop` from `quota_park` (extend the existing import line) and `step_down_for_quota` from + `quota_step_down`. +- `resume_point` already rebuilds `executor_args` from `context.model`, so the new model is dispatched; + `salvage_partial` then appends the newest partial head. +- If the post-edit count exceeds 430, compress by moving the summary-row reading into a helper inside + `quota_step_down.py` (e.g. `execution_step_down(context, summary_row)`), which is in scope. +- Extend `tests/flow/stages/test_execute_steps.py`: add an autouse HOME-isolation fixture; change the existing + quota-park cases to `claude-haiku-4-5` so they still prove full-ladder exhaustion; add: a quota failure on opus + triggers a second `_run_steps()` with `claude-sonnet-4-6`, `resume_partial` true and the same `start_time`, payload + `model_step_downs` length 1, no `quota_park`; the success path after step-down records `model_step_downs`; a non-quota + failure makes exactly one attempt. +- Run + `uv run pytest apps/sandbox-executor/tests/flow/stages/test_execute_steps.py apps/sandbox-executor/tests/test_partial_salvage.py apps/sandbox-executor/tests/test_executor_run_salvage.py` + and `uv run python scripts/check_module_budgets.py`. + +### Dependencies & Criticality + +- **Depends on:** Step 3, Step 4 +- **Is Bottleneck:** YES (largest share of the intent's value; tightest budget) + +### Safety & Constraint Considerations + +- **Relevant rules:** `docs/safety.md` "Failure containment" (execution failure keeps partial work); module budget + freeze (`holon-config/hygiene/module_budgets.json` is never edited); constraints §3 (ledger rows are appended per + attempt, never rewritten). +- **Potential failure modes for this step:** `_republish_recorded_execution` adopts the failed attempt's branch and + skips dispatch; admission counts the flow's own failed execution branch as in flight; line budget overflow; ruff + `PLR0912/C901` on `run()`. +- **Guardrails and early‑abort checks:** the new test asserts a second dispatch with the new model; if the republish + path intercepts, clear the recorded execution branch on the context before retrying; budget script after the edit. + +### Success & Discard Criteria + +- **Success:** listed tests pass; `execute.py` <= 430 lines; ruff clean without new `# noqa`. +- **Discard:** the retry cannot avoid adopting the failed branch within 1.5x cost: keep park-only behaviour for Stage 3, + document it, and still ship Steps 1-6 and 8. + +### Metrics + +| metric | value | +| ------------------- | ----- | +| p_success_pred | 0.70 | +| entropy_pred | 2.4 | +| impact_pred | 80.0 | +| cost_pred | 6.0 | +| learning_value_pred | 6.0 | +| ev_pred | 52.3 | + +### Step Metrics Rationale + +`EV = 0.70 * 80 + 0.5 * 6 - 0.3 * 2.4 - 6 = 56 + 3 - 0.72 - 6 = 52.28`. Bottleneck step: lowest p_success from the line +budget and salvage interactions, highest learning value. + +--- + +## Step 8: Step down the reviewer model inside the Stage 4 review body + +- **Sub‑intent recommendation:** NO +- **Reasoning:** 53 lines of headroom and the loop already honours the checkpointed iteration budget on re-entry, so a + retry wrapper is contained. +- **Step Type:** IMPLEMENTATION +- **Exploration level:** BALANCED + +- **Hypothesis being tested:** calling `_run_engine_review_loop(context, github=github)` again after `context.model` + changes resumes with the remaining iteration budget (it reads `context.review_iterations_done`) and produces fresh + reviewer verdicts on the new model. +- **Learning target:** whether a second loop run double-counts accounting or re-posts duplicate PR review comments. +- **Maximum acceptable cost for this learning:** 1.5x this step's `cost_pred`. + +### Intent & Git Integration + +- **Step Intent:** A Stage 4 quota stop on the flow's own runner retries the review loop on the next rung and parks only + when the ladder is exhausted. +- **Git branch:** execution branch of this plan +- **Sub‑intent:** NONE + +### Implementation Details (No code blocks, only logic/steps) + +- Add module-level `_review_loop_with_step_down(context, github) -> tuple[dict, list[dict]]`: run the loop; while + `_quota_retry_allowed(context, loop_res)` and a step-down record is returned, append it and re-run the loop. +- `_quota_retry_allowed`: consensus not approved; `mergeability.is_dirty` false; `merge_state_status != "MISSING_REF"`; + no `loop_res.get("error")`; no `budget_breach`; `context.review_iterations_done < context.max_review_iterations`. +- The step-down: `found = review_quota_stop(loop_res.get("reviewers") or [])`; proceed only when the reviewer's `agent` + normalises to `context.agent`; call + `step_down_for_quota(context, ExhaustedRunner(agent, reviewer model or context.model), stop)`. +- In `_run_review_stage_body` replace the single `_run_engine_review_loop` call with the helper; add `model_step_downs` + to the failure payload when non-empty and to the success result returned by `build_review_stage_outcome` (set on + `outcome.payload` after the call). `park_review` stays where it is and now only runs after the ladder is exhausted or + for other runners. +- Extend `tests/flow/stages/test_review.py` (HOME isolated): context agent `claude-agent` on opus, the first loop + returns a quota-failed `claude-agent` reviewer and the second approves -> two loop calls, + `context.model == "claude-sonnet-4-6"`, `model_step_downs` length 1, no `quota_park`; a quota-failed reviewer of + another agent parks without stepping down (existing tests); exhausted ladder on haiku parks with `stage == "review"`; + no retry when `budget_breach`, `is_dirty`, `MISSING_REF`, loop `error`, or no iterations remain. +- Run + `uv run pytest apps/sandbox-executor/tests/flow/stages/test_review.py apps/sandbox-executor/tests/flow/stages/test_review_keeps_branch.py apps/sandbox-executor/tests/test_review_accounting.py`. + +### Dependencies & Criticality + +- **Depends on:** Step 3, Step 4 +- **Is Bottleneck:** NO + +### Safety & Constraint Considerations + +- **Relevant rules:** `docs/safety.md` "Human review is the final gate" (never auto-approve; a retry only re-runs + reviewers); `docs/review_consensus.md`. +- **Potential failure modes for this step:** `_run_review_stage_body` already carries `# noqa: C901, PLR0912, PLR0915`; + adding branches inside it would hide complexity growth, so the logic goes in helpers; duplicated PR comments from a + second loop run. +- **Guardrails and early‑abort checks:** no new `# noqa`; the body gains only the helper call and two payload lines. + +### Success & Discard Criteria + +- **Success:** listed tests pass; `review.py` <= 350 lines; no new `# noqa`. +- **Discard:** a second loop run breaks accounting invariants in `test_review_accounting.py`: keep park-only for Stage 4 + and document it. + +### Metrics + +| metric | value | +| ------------------- | ----- | +| p_success_pred | 0.75 | +| entropy_pred | 2.0 | +| impact_pred | 75.0 | +| cost_pred | 5.0 | +| learning_value_pred | 5.0 | +| ev_pred | 53.2 | + +### Step Metrics Rationale + +`EV = 0.75 * 75 + 0.5 * 5 - 0.3 * 2.0 - 5 = 56.25 + 2.5 - 0.6 - 5 = 53.15`. The loop's checkpointed iteration counter +makes re-entry safe by design; residual risk is accounting/posting side-effects. + +--- + +## Step 9: Document Stage 2 quota classification, model cooldowns and intra-ladder step-down + +- **Sub‑intent recommendation:** NO +- **Reasoning:** Documentation only, next to the existing "Quota stop record" section. +- **Step Type:** DOCUMENTATION +- **Exploration level:** EXPLOIT + +### Intent & Git Integration + +- **Step Intent:** Operators can read how a quota stop is classified, which ladder is walked, where markers live, and + when a flow parks. +- **Git branch:** execution branch of this plan +- **Sub‑intent:** NONE + +### Implementation Details (No code blocks, only logic/steps) + +- In `docs/budgets.md` "Quota stop record": add a Stage 2 bullet (the planner exits with + `the planner agent exited with code (quota (resets