Skip to content

Commit 3344f54

Browse files
authored
fix(quota): preserve failures without runtime presentation (#7660)
Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com>
1 parent 27faba6 commit 3344f54

3 files changed

Lines changed: 74 additions & 19 deletions

File tree

‎loopx/cli_commands/quota.py‎

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -186,9 +186,11 @@ def _effective_spend_turn_instance_id(
186186

187187
def _quota_renderer(
188188
args: argparse.Namespace,
189+
*,
190+
failure: bool = False,
189191
) -> Callable[[dict[str, object]], str]:
190192
command = args.quota_command
191-
if bool(getattr(args, "turn_envelope", False)):
193+
if not failure and bool(getattr(args, "turn_envelope", False)):
192194
return render_turn_envelope_markdown
193195
return {
194196
"should-run": render_quota_should_run_markdown,
@@ -306,16 +308,20 @@ def _project_quota_cli_payload(
306308
*,
307309
captured_decision_path: str | None = None,
308310
) -> dict[str, object]:
309-
"""Project already-decided facts; preserve typed failures on envelope rejection.
311+
"""Project successful decisions; failed requests retain their diagnostic.
310312
311-
The envelope is an additive hot-path view over a decided payload. A typed
312-
validation/failure payload has no interaction contract to project, so a
313-
renderer rejection keeps the typed diagnostic itself (with the skip reason)
314-
instead of masking it with a crash (issue #3687).
313+
Optional presentation must not call a runtime that failed during collection.
314+
A rejected envelope likewise retains the already-decided facts (issue #3687).
315315
"""
316316
from ..control_plane.effect_program import reject_retired_quota_format
317317

318318
reject_retired_quota_format(payload)
319+
if payload.get("ok") is False:
320+
# Failure reporting must not reenter the runtime that just failed.
321+
# Keep the decided diagnostic, including its original recovery/receipt.
322+
if bool(getattr(args, "turn_envelope", False)):
323+
return {**payload, "turn_envelope_skipped": "quota request failed; original diagnostic retained"}
324+
return payload
319325
if not bool(getattr(args, "turn_envelope", False)):
320326
if args.quota_command in {"status", "plan"}:
321327
return compact_quota_plan_cli_payload(payload, detail_sections=detail_sections)
@@ -397,7 +403,7 @@ def _emit_quota_result(
397403
and args.format == "json" and not getattr(args, "defer_context_presentation", False)):
398404
print_payload(captured_quota_failure_view(payload, capture_directory=capture_directory,
399405
max_page_output_bytes=getattr(args, "max_page_output_bytes", None)),
400-
args.format, _quota_renderer(args))
406+
args.format, _quota_renderer(args, failure=True))
401407
return 1
402408
if payload.get("ok") is True:
403409
delivery_request = handoff_decision(capture_directory, getattr(args, "decision_handoff_socket", None), context_delivery_enabled)
@@ -408,7 +414,7 @@ def _emit_quota_result(
408414
failure = quota_decision_transport_failure_payload(
409415
args, payload, exc, capture_directory=capture_directory,
410416
)
411-
print_payload(failure, args.format, _quota_renderer(args))
417+
print_payload(failure, args.format, _quota_renderer(args, failure=True))
412418
return 1
413419
if (delivery_request is not None or getattr(args, "codex_context_dir", None)
414420
or getattr(args, "codex_context_root", None)):
@@ -477,9 +483,9 @@ def _emit_quota_result(
477483
failure = quota_decision_transport_failure_payload(
478484
args, captured_payload, exc, capture_directory=capture_directory,
479485
)
480-
print_payload(failure, args.format, _quota_renderer(args))
486+
print_payload(failure, args.format, _quota_renderer(args, failure=True))
481487
return 1
482-
print_payload(payload, args.format, _quota_renderer(args))
488+
print_payload(payload, args.format, _quota_renderer(args, failure=not succeeded))
483489
return 0 if succeeded else 1
484490

485491

‎skills/loopx-self-repair/references/repair-patterns.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,7 @@ teaches a reusable control-plane lesson.
190190
| `local_release_python_runtime_drift` | A locally promoted release imports under CI's declared Python but the default macOS `python3` exits during CLI startup on a newly added standard-library symbol. | `python3 --version`, default wrapper target, failing import traceback, `pyproject.toml` requirement, changed module imports, candidate doctor under the actual wrapper interpreter. | A new module used a newer convenience alias even though the source-based local wrapper still runs on an older system interpreter, and release validation did not exercise that real default path before promotion. | Prefer an equivalent broadly available standard-library API at the narrow import seam, add a focused timestamp/import regression, run candidate doctor plus the affected product smoke with the actual default interpreter, and only then promote the repaired release. Do not claim broad interpreter support beyond the verified CLI path. |
191191
| `node_test_python_selector_bypass` | Python-backed Node tests or browser smokes fail under a system Python 3.9 although `uv` prepared a compatible worktree interpreter. | `requires-python`, source checkout/active venv, selected child argv and `sys.executable`, bare `python3` fallbacks, and the test runner's environment. | JS/TS subprocess callers independently selected `python3` from PATH instead of the source checkout's Python discovery contract. | Resolve one checked Python 3.11+ interpreter for test subprocesses, honoring explicit overrides and the active/worktree environment before system discovery; fail with an actionable setup hint when none exists. Cover 3.9 rejection, worktree precedence, native Windows discovery, source import provenance, and a static guard against new bare-`python3` test subprocesses. Do not rewrite historical validation receipts or change product runtime interpreter authority. |
192192
| `heartbeat_prompt_error_projection_gap` | `loopx heartbeat-prompt --help` succeeds, but an invalid generation command exits 1 while markdown shows a copyable empty task body and `Generator Inputs` fields such as `active_state`, `thin`, `agent_id`, or `agent_scopes` as `None`. | failing markdown output, `--format json` payload, CLI handler exception branch, active-state lookup inputs, agent identity arguments. | The command caught generation errors into a minimal `{ok:false,error}` payload and then reused the success markdown renderer, which made an error look like a generated blank automation. | Build a heartbeat-prompt error payload that preserves requested inputs, render a distinct error page with no copyable task-body fence, and cover markdown plus JSON failure output with a focused smoke. |
193+
| `quota_failure_presentation_runtime_reentry` | `quota status` or `quota plan` catches a host/runtime failure, then throws again while compacting the failure report; `--turn-envelope` can also hide the original recovery in Markdown. | Original typed error, CLI failure payload, projection RPC count, JSON/Markdown readback, locator and registry bytes before/after, permission-restored retry. | Optional success presentation reentered the unavailable runtime after the command had already decided its failure. | Preserve failed quota payloads before optional runtime-backed projection and render their existing command diagnostic. Cover one denied connection, bounded locator retries, no dispatch or replacement process, original recovery/receipt, both output formats and envelope modes, and recovery without changing permission policy. |
193194
| `shell_pr_comment_command_substitution` | A PR comment, issue body, or review body is posted with shell command substitution artifacts because Markdown backticks were passed through a double-quoted `gh ... --body "..."` argument. | shell command used for the PR/comment operation, rendered public comment body, recent agent transcript, and PR review/comment hygiene instructions. | Agent treated Markdown as inert text inside a shell string; the shell evaluated backticks before `gh` received the body. | Do not pass Markdown-rich bodies through double-quoted shell arguments. Use a single-quoted body when safe, stdin or `--body-file` for multiline text, or a GitHub connector/API call that bypasses shell interpolation; add a smoke or checklist item when the workflow recurs. |
194195
| `external_delivery_clock_override` | A caller can move an external send into or out of a configured delivery window by supplying an artifact timestamp such as `--generated-at`. | execute-path CLI arguments, sink window decision input, current invocation time, focused zero-provider-call smoke. | One caller-controlled timestamp was reused for both reproducible artifact metadata and runtime delivery authorization. | Keep artifact time and execution-observation time separate. Bind live CLI delivery decisions to a trusted invocation clock, expose any injected clock only as an internal test seam, and prove that an in-window artifact timestamp cannot override an out-of-window execution observation. |
195196
| `reviewer_notification_semantic_dedupe_gap` | A reviewer was already tagged by a clear public review-request comment, but a later automated fallback posts another comment because the earlier message lacks the current idempotency marker or uses different handle casing. | live PR comments, normalized selected reviewer, request/comment write calls, marker receipts, reviewer-request packet. | Idempotency recognized only system-authored markers and ignored older or human-authored explicit review-request evidence. | Keep marker matching as the fast path, then recognize only bounded, direct review-request language near a normalized reviewer mention; ignore quotes, code, ordinary discussion, and weak mentions. Return the existing public comment URL and perform zero writes. |

‎tests/control_plane/test_effect_runtime_host_permission.py‎

Lines changed: 57 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -108,17 +108,22 @@ def denied(*_args, **_kwargs):
108108
assert not list(tmp_path.glob("start-*.lock"))
109109

110110

111+
@pytest.mark.parametrize("command_name", ["status", "plan"])
112+
@pytest.mark.parametrize("output_format", ["json", "markdown"])
111113
def test_cli_configuration_collection_reports_host_fault_without_review_execution(
112-
tmp_path: Path, monkeypatch, capsys,
114+
tmp_path: Path, monkeypatch, capsys, command_name, output_format,
113115
) -> None:
114116
from loopx.cli_commands import quota as command
115117
from loopx.capabilities.pr_review_queue.goal_configuration import configuration_summary
116118

117-
_locator(tmp_path, monkeypatch)
119+
locator, info = _locator(tmp_path, monkeypatch)
118120
registry = tmp_path / "registry.json"
119121
registry.write_text("{}")
120122

123+
connections = []
124+
121125
def denied(*_args, **_kwargs):
126+
connections.append(True)
122127
raise PermissionError(errno.EPERM, "private sandbox details")
123128

124129
monkeypatch.setattr(effect_runtime.socket, "create_connection", denied)
@@ -130,13 +135,56 @@ def collect(**_kwargs):
130135
}}})
131136

132137
monkeypatch.setattr(command, "collect_status", collect)
133-
assert main(["--format", "json", "--registry", str(registry), "--runtime-root",
134-
str(tmp_path), "quota", "status"]) == 1
135-
payload = json.loads(capsys.readouterr().out)
136-
assert payload["ok"] is False
137-
assert payload["error_code"] == "quota_runtime_permission_denied"
138-
assert "host-approved" in payload["health_items"][0]["recommended_action"]
139-
assert "private sandbox" not in json.dumps(payload)
138+
assert main(["--format", output_format, "--registry", str(registry), "--runtime-root",
139+
str(tmp_path), "quota", command_name]) == 1
140+
output = capsys.readouterr().out
141+
if output_format == "json":
142+
payload = json.loads(output)
143+
assert payload["ok"] is False
144+
assert payload["error_code"] == "quota_runtime_permission_denied"
145+
assert "host-approved" in payload["health_items"][0]["recommended_action"]
146+
else:
147+
assert "- ok: `False`" in output
148+
assert "host-approved" in output
149+
assert "private sandbox" not in output
150+
assert len(connections) == 1, "failure presentation must not reconnect"
151+
assert json.loads(locator.read_text()) == info
152+
assert registry.read_text() == "{}"
153+
154+
155+
@pytest.mark.parametrize("turn_envelope", [False, True])
156+
@pytest.mark.parametrize("output_format", ["json", "markdown"])
157+
def test_failed_guard_keeps_host_recovery_without_runtime_presentation(
158+
tmp_path: Path, monkeypatch, capsys, turn_envelope, output_format,
159+
) -> None:
160+
from loopx.cli_commands import quota as command
161+
from loopx.cli_runtime import print_payload
162+
163+
registry = tmp_path / "registry.json"
164+
registry.write_text("{}")
165+
args = build_parser().parse_args([
166+
"--format", output_format, "quota", "should-run", "--goal-id", "fixture-goal",
167+
*(["--turn-envelope"] if turn_envelope else []),
168+
])
169+
170+
def denied(*_args, **_kwargs):
171+
raise effect_runtime.EffectRuntimeHostPermissionError()
172+
173+
monkeypatch.setattr(command, "_prepare_quota_command_execution", denied)
174+
monkeypatch.setattr(effect_runtime, "effect_runtime_result",
175+
lambda *_a, **_k: pytest.fail("failed guard must not invoke runtime projection"))
176+
assert command.handle_quota_command(
177+
args, registry_path=registry, runtime_root_arg=str(tmp_path),
178+
print_payload=print_payload, append_cli_rollout_event=lambda *_a, **_k: {},
179+
) == 1
180+
output = capsys.readouterr().out
181+
assert "host-approved" in output
182+
if output_format == "json":
183+
payload = json.loads(output)
184+
assert payload["ok"] is False and payload["should_run"] is False
185+
assert payload["error_code"] == "quota_runtime_permission_denied"
186+
else:
187+
assert "- ok: `False`" in output
140188
assert registry.read_text() == "{}"
141189

142190

0 commit comments

Comments
 (0)