Skip to content
10 changes: 4 additions & 6 deletions apps/sandbox-executor/src/sandbox_executor/entrypoint/planner.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
from sandbox_executor.decomposition_rule import should_decompose
from sandbox_executor.entrypoint.execution_workspace import start_branch_from_host_fetch
from sandbox_executor.entrypoint.plan_id_unique import mint_plan_id
from sandbox_executor.formatting import converge_prettier
from sandbox_executor.formatting import PlanPrettierError, format_plan_markdown
from sandbox_executor.git import GitRepository
from sandbox_executor.ledger import (
_sanitize_model_name,
Expand All @@ -34,7 +34,6 @@
)
from sandbox_executor.ledger.fragments import ledger_commit_paths
from sandbox_executor.module_budget_guard import module_budget_change_authorised, refusal_message, without_budget_config
from sandbox_executor.plan_artifact_format import format_plan_artifact
from sandbox_executor.plan_attempt import clear_failure_detail, discard_untracked_plan_file, write_failure_detail
from sandbox_executor.plan_ev_sync import (
PlanEvSyncError,
Expand Down Expand Up @@ -559,10 +558,9 @@ def build_agent_cmd(prompt_text: str) -> list[str]:
write_plan_ev(plan_md_path, ev)
# why: format before the ledger append so the recorded decision is parsed from the committed file
try:
converge_prettier([plan_md_rel], repo_dir=repo_dir)
except Exception as e:
print(f"Warning: Failed to converge prettier on {plan_md_rel}: {e}", file=sys.stderr)
format_plan_artifact(plan_md_rel, repo_dir)
format_plan_markdown(plan_md_rel, repo_dir)
except PlanPrettierError as e:
_fail_plan_attempt(repo_dir, plan_md_rel, str(e))
plan_entry.update(_plan_decision_fields(plan_entry, plan_md_path, intent_data))
plan_entry.update(_touch_set_field(plan_md_path, intent_data))

Expand Down
21 changes: 21 additions & 0 deletions apps/sandbox-executor/src/sandbox_executor/formatting.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,21 @@
from collections.abc import Sequence
from pathlib import Path

from sandbox_executor.calibration_format import _prettier_failure as repository_prettier_failure
from sandbox_executor.plan_artifact_format import format_plan_artifact
from sandbox_executor.redaction import redact_agent_secrets

logger = logging.getLogger(__name__)

PRETTIER_SPEC: str = "prettier@3.8.4"
DEFAULT_MAX_PASSES: int = 3
DEFAULT_TIMEOUT_SECONDS: int = 30


class PlanPrettierError(RuntimeError):
pass


def is_prettier_available() -> bool:
return shutil.which("npx") is not None

Expand Down Expand Up @@ -120,3 +128,16 @@ def converge_prettier(
except Exception as exc:
_warn_and_print(_format_exception_message(exc, timeout_seconds))
return False


def format_plan_markdown(plan_rel: str, repo_dir: str) -> None:
format_plan_artifact(plan_rel, repo_dir)
# why: CI's lint-docs runs the unpinned repository Prettier, which wraps differently from the pinned PRETTIER_SPEC
reason = repository_prettier_failure(plan_rel, repo_dir)
if reason is None:
logger.info("Plan %s passes the repository Prettier check", plan_rel)
return
raise PlanPrettierError(
f"Plan {plan_rel} failed the repository Prettier check ({redact_agent_secrets(reason)}); "
f"reproduce with: npx prettier --check {plan_rel}"
)
41 changes: 33 additions & 8 deletions apps/sandbox-executor/tests/test_planner.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import os
import pathlib
import re
import shutil
import subprocess
import tempfile
import unittest
Expand All @@ -11,7 +12,9 @@
from unittest.mock import MagicMock, patch

import pytest
from sandbox_executor import calibration_format
from sandbox_executor.budgets import DEFAULT_ENTROPY_BUDGET, BudgetBreach
from sandbox_executor.calibration_format import LINT_DOCS_PRETTIER
from sandbox_executor.decomposition_rule import (
DECISION_DECOMPOSED,
DECISION_EXECUTE,
Expand Down Expand Up @@ -204,6 +207,8 @@ def test_load_metrics_config(self):
"",
)

REAL_WHICH = shutil.which

INTENT = {
"branch": "I-12345",
"intent_id": "I-12345",
Expand All @@ -228,6 +233,25 @@ def __init__(self, testcase, agent_turns, model="gemini", env=None, build_cmd=No
self.stdout = ""
self.stderr = ""
self.converge_side_effect = None
self.prettier_check = lambda _text: True
self.prettier_write_returncode = 0
self.npx_path = "/usr/bin/npx"
self.prettier_calls = []

def _which(self, name):
return self.npx_path if name == "npx" else REAL_WHICH(name)

def _repository_prettier(self, mode, plan_rel, repo_dir):
argv = [*LINT_DOCS_PRETTIER, mode, plan_rel]
self.prettier_calls.append((mode, plan_rel, repo_dir))
if mode == "--write":
if self.prettier_write_returncode == 0 and self.converge_side_effect is not None:
self.converge_side_effect(plan_rel, repo_dir)
return subprocess.CompletedProcess(argv, self.prettier_write_returncode, stdout="", stderr="[error] boom\n")
passes = self.prettier_check(pathlib.Path(repo_dir, plan_rel).read_text(encoding="utf-8"))
return subprocess.CompletedProcess(
argv, 0 if passes else 1, stdout="" if passes else f"[warn] {plan_rel}\n", stderr=""
)

def _fake_run_cmd(self, args, cwd=None, env=None, check=True):
self.git_cmds.append(list(args))
Expand Down Expand Up @@ -272,7 +296,8 @@ def run(self):
patch.object(planner, "get_runner", return_value=runner),
patch.object(planner, "run_cmd", side_effect=self._fake_run_cmd),
patch.object(planner, "run_turn", side_effect=self._fake_run_turn),
patch.object(planner, "converge_prettier", side_effect=self.converge_side_effect) as self.mock_converge,
patch.object(calibration_format, "_run_prettier", side_effect=self._repository_prettier),
patch.object(calibration_format.shutil, "which", side_effect=self._which),
patch("sandbox_executor.flow.stage_conflicts.check_and_resolve_stage_conflicts"),
redirect_stdout(out),
redirect_stderr(err),
Expand Down Expand Up @@ -645,11 +670,11 @@ def test_a_model_name_with_no_derivable_code_fails_clearly(self):

def test_converges_prettier_on_plan_file(self):
h = self.harness([write_file(VALID_PLAN)])
h.mock_converge.assert_called_once()
call_files = h.mock_converge.call_args[0][0]
self.assertEqual(len(call_files), 1)
self.assertTrue(call_files[0].startswith("plans/I-12345/P-") and call_files[0].endswith(".md"))
self.assertEqual(h.mock_converge.call_args[1].get("repo_dir"), h.repo_dir)
self.assertEqual([mode for mode, _, _ in h.prettier_calls], ["--write", "--check"])
self.assertEqual(len({plan_rel for _, plan_rel, _ in h.prettier_calls}), 1)
plan_rel = h.prettier_calls[0][1]
self.assertTrue(plan_rel.startswith("plans/I-12345/P-") and plan_rel.endswith(".md"))
self.assertEqual({repo_dir for _, _, repo_dir in h.prettier_calls}, {h.repo_dir})

def committed_plan(self, h):
row = h.ledger_lines("plans.jsonl")[0]
Expand Down Expand Up @@ -679,8 +704,8 @@ def test_plan_row_records_the_list_after_prettier_rewrites_the_plan(self):
# why: Prettier runs before the ledger append, so the recorded list is parsed from the committed file
listed = VALID_PLAN + "\n## Sub-intent list\n\n- Add the validator module\n"

def rewrap(files, repo_dir):
path = pathlib.Path(repo_dir) / files[0]
def rewrap(plan_rel, repo_dir):
path = pathlib.Path(repo_dir) / plan_rel
path.write_text(path.read_text().replace("- Add the validator module", "- Add the validator\n module"))

h = _PlannerHarness(self, [write_file(listed)])
Expand Down
118 changes: 112 additions & 6 deletions apps/sandbox-executor/tests/test_planner_plan_fence_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@

import logging
import pathlib
import subprocess
import unittest
from collections.abc import Iterator

import pytest
from sandbox_executor import plan_artifact_format
from sandbox_executor import formatting, plan_artifact_format
from sandbox_executor.calibration_format import PRETTIER_PASSES
from sandbox_executor.decomposition_rule import (
DECISION_DECOMPOSED,
DecompositionDecision,
Expand All @@ -15,6 +17,7 @@
)
from sandbox_executor.entrypoint import planner
from sandbox_executor.plan_artifact_format import RUFF_NOT_FOUND_REASON, FenceFormatOutcome
from sandbox_executor.plan_attempt import PLAN_FAILURE_DETAIL_REL
from sandbox_executor.touch_set import parse_touch_set_section

from tests.test_plan_artifact_format import (
Expand All @@ -26,6 +29,12 @@
)
from tests.test_planner import INTENT, VALID_PLAN, _PlannerHarness, write_file

ALIGNED_STEP_TABLE = (
"| metric | value |\n| -------------- | ----- |\n| p_success_pred | 0.9 |\n| entropy_pred | 1.0 |\n"
)
MISALIGNED_STEP_TABLE = "| metric | value |\n|---|---|\n| p_success_pred | 0.9 |\n| entropy_pred | 1.0 |\n"
MISALIGNED_TABLE_PLAN = VALID_PLAN.replace(ALIGNED_STEP_TABLE, MISALIGNED_STEP_TABLE, 1)

OVERALL_METRICS = {"p_success": 0.8, "entropy": 2.5, "impact": 10.0, "cost": 0.5, "learning_value": 0.5, "ev": 7.0}
PLAN_WITH_OVERLONG_FENCE = (
VALID_PLAN.replace("| ev_pred | 6.0 |", "| ev_pred | 7.0 |", 1)
Expand All @@ -35,6 +44,28 @@
+ "\n## Sub-intent list\n\n- Add the validator module\n- Document the write protocol\n"
)

PLAN_WITH_OVERLONG_FENCE_AND_MISALIGNED_TABLE = PLAN_WITH_OVERLONG_FENCE.replace(
ALIGNED_STEP_TABLE, MISALIGNED_STEP_TABLE, 1
)


def align_step_table(plan_rel: str, repo_dir: str) -> None:
path = pathlib.Path(repo_dir) / plan_rel
aligned = path.read_text(encoding="utf-8").replace(MISALIGNED_STEP_TABLE, ALIGNED_STEP_TABLE)
path.write_text(aligned, encoding="utf-8")


def passes_repository_prettier_table_check(text: str) -> bool:
return MISALIGNED_STEP_TABLE not in text and ALIGNED_STEP_TABLE in text


def write_file_in_git_repo(content: str):
def turn(cmd, watch_path):
subprocess.run(["git", "init", "-q", str(pathlib.Path(watch_path).parents[2])], check=True)
return write_file(content)(cmd, watch_path)

return turn


class _RuffConfiguredHarness(_PlannerHarness):
def _seed_workspace(self) -> None:
Expand Down Expand Up @@ -84,14 +115,14 @@ def test_plan_row_fields_are_read_from_the_formatted_plan(harness: _RuffConfigur
assert {metric: row[metric] for metric in OVERALL_METRICS} == pytest.approx(OVERALL_METRICS)


def test_fence_formatter_runs_after_prettier_and_before_the_ledger_append(
def test_fence_formatter_runs_before_prettier_and_before_the_ledger_append(
harness: _RuffConfiguredHarness, monkeypatch: pytest.MonkeyPatch
) -> None:
real_format_plan_artifact = planner.format_plan_artifact
real_format_plan_artifact = formatting.format_plan_artifact
stages_seen: list[str] = []
state_at_format_call: dict[str, object] = {}

def prettier_stand_in(_files: list[str], repo_dir: str) -> None:
def prettier_stand_in(_plan_rel: str, repo_dir: str) -> None:
stages_seen.append("prettier")

def recording_format(artifact_rel: str, repo_dir: str) -> FenceFormatOutcome:
Expand All @@ -101,16 +132,91 @@ def recording_format(artifact_rel: str, repo_dir: str) -> FenceFormatOutcome:
return real_format_plan_artifact(artifact_rel, repo_dir)

harness.converge_side_effect = prettier_stand_in
monkeypatch.setattr(planner, "format_plan_artifact", recording_format)
monkeypatch.setattr(formatting, "format_plan_artifact", recording_format)
harness.run()

assert harness.exit_code == 0, harness.stderr
assert stages_seen == ["prettier", "fence format"]
assert stages_seen == ["fence format", "prettier"]
assert harness.prettier_calls[-1][0] == "--check"
assert state_at_format_call == {"plan_rows": [], "git_add_commands": []}
assert len(harness.ledger_lines("plans.jsonl")) == 1
assert harness.committed()


def test_plan_with_an_overlong_fence_and_a_misaligned_table_is_committed_clean() -> None:
harness = _RuffConfiguredHarness(unittest.TestCase(), [write_file(PLAN_WITH_OVERLONG_FENCE_AND_MISALIGNED_TABLE)])
harness.converge_side_effect = align_step_table
harness.prettier_check = passes_repository_prettier_table_check
harness.run()

try:
assert harness.exit_code == 0, harness.stderr
assert harness.committed()
plan_rel = harness.plan_row()["plan_file"]
committed_plan = harness.committed_plan()
assert passes_ruff_format_check(plan_rel, pathlib.Path(harness.repo_dir))
assert OVERLONG_STATEMENT not in committed_plan
assert passes_repository_prettier_table_check(committed_plan)
assert harness.prettier_calls[-1] == ("--check", plan_rel, harness.repo_dir)
finally:
harness.cleanup()


def test_misaligned_table_is_committed_prettier_clean() -> None:
harness = _PlannerHarness(unittest.TestCase(), [write_file(MISALIGNED_TABLE_PLAN)])
harness.converge_side_effect = align_step_table
harness.prettier_check = passes_repository_prettier_table_check
harness.run()

try:
assert harness.exit_code == 0, harness.stderr
assert harness.committed()
plan_rel = harness.ledger_lines("plans.jsonl")[0]["plan_file"]
plan_content = (pathlib.Path(harness.repo_dir) / plan_rel).read_text(encoding="utf-8")
assert passes_repository_prettier_table_check(plan_content)
assert harness.prettier_calls[-1] == ("--check", plan_rel, harness.repo_dir)
finally:
harness.cleanup()


@pytest.mark.parametrize(
("attribute", "value", "reason"),
[
pytest.param("npx_path", None, "npx is not on PATH", id="npx missing"),
pytest.param("prettier_write_returncode", 2, "write exited 2", id="write fails"),
pytest.param("prettier_check", lambda _text: False, "check exited 1", id="check never passes"),
],
)
def test_prettier_failure_stops_stage_2_with_a_named_cause(attribute: str, value: object, reason: str) -> None:
harness = _PlannerHarness(unittest.TestCase(), [write_file_in_git_repo(VALID_PLAN)])
setattr(harness, attribute, value)
harness.run()

try:
assert harness.exit_code == 1
assert "failed the repository Prettier check" in harness.stderr
assert reason in harness.stderr
detail = (pathlib.Path(harness.repo_dir) / PLAN_FAILURE_DETAIL_REL).read_text()
assert "failed the repository Prettier check" in detail
assert harness.ledger_lines("plans.jsonl") == []
assert not harness.committed()
assert list((pathlib.Path(harness.repo_dir) / "plans").rglob("P-*.md")) == []
finally:
harness.cleanup()


def test_prettier_check_retries_up_to_the_bounded_passes() -> None:
harness = _PlannerHarness(unittest.TestCase(), [write_file(VALID_PLAN)])
harness.prettier_check = lambda _text: False
harness.run()

try:
assert harness.exit_code == 1
assert len(harness.prettier_calls) == 2 * PRETTIER_PASSES
finally:
harness.cleanup()


@pytest.fixture
def logging_as_in_the_planner_container(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:
# why: the planner entrypoint configures no logging, so a warning reaches standard error through logging.lastResort
Expand Down
Loading
Loading