Skip to content
Open
Original file line number Diff line number Diff line change
Expand Up @@ -795,6 +795,7 @@ def _run_main() -> None: # noqa: C901, PLR0915
auto_pr=args.auto_pr,
dry_run=args.dry_run,
skip_post=args.skip_post,
defer_ci_settle=args.skip_post,
first_iteration=args.iteration,
ledger_file=_SCRATCH_LEDGER if args.result_file else None,
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ class CiInspectionInputs:
detail_lookup: DetailLookup | None = None
rerun_failed: Callable[[str], bool] | None = None
log_lookup: Callable[[dict[str, Any]], str | None] | None = None
defer_ci_settle: bool = False


class CiInspection(NamedTuple):
Expand Down Expand Up @@ -95,30 +96,42 @@ def _fast_probe(inputs: CiInspectionInputs) -> CiInspection:


def _post_review_gate(inputs: CiInspectionInputs, context: FlowContext) -> CiInspection:
if inputs.pr_allowed and inputs.test_gate.needs_ci_registration() and inputs.github.available:
timer = inputs.iteration_timer
timeout = resolve_ci_registration_timeout(inputs.ci_registration_timeout)
inputs.wait_registration(
context,
inputs.repo_dir,
inputs.review_target,
inputs.proxy_env,
timer.remaining_capped(timeout) if timer is not None else timeout,
inputs.ci_poll_interval,
clock=inputs.clock,
sleep=inputs.sleep,
probe=inputs.probe_ci,
)
ci_status, waited = _settled_ci_status(inputs, context)
ci_wait = waited if waited and waited.exhausted else _kept_wait(inputs.ci_wait, ci_status)
tests_failed, unmeasured = _apply_guarded_test_evidence(inputs.test_gate, ci_status, False, False, True)
ci_green, ci_finding = gate_ci_flags(ci_status, tests_failed)
return CiInspection(ci_status, ci_wait, tests_failed, unmeasured, ci_green, ci_finding, True)


def _settled_ci_status(inputs: CiInspectionInputs, context: FlowContext) -> tuple[dict[str, Any], CiWaitResult | None]:
if inputs.defer_ci_settle:
# why: the host settles CI once after the --skip-post container returns, so the container must not wait too
return inputs.probe_ci(), None
_await_ci_registration(inputs, context)
ci_status = inputs.probe_ci()
ci_status, waited = settle_pending_ci(context, inputs.probe_ci, ci_status, inputs.ci_policy, bool(inputs.ci_wait))
if inputs.iteration_timer is not None:
# why: the CI wait has its own budget, so it is not charged to the iteration
inputs.iteration_timer.credit(waited.waited_seconds if waited else 0.0)
ci_wait = waited if waited and waited.exhausted else _kept_wait(inputs.ci_wait, ci_status)
tests_failed, unmeasured = _apply_guarded_test_evidence(inputs.test_gate, ci_status, False, False, True)
ci_green, ci_finding = gate_ci_flags(ci_status, tests_failed)
return CiInspection(ci_status, ci_wait, tests_failed, unmeasured, ci_green, ci_finding, True)
return ci_status, waited


def _await_ci_registration(inputs: CiInspectionInputs, context: FlowContext) -> None:
if not (inputs.pr_allowed and inputs.test_gate.needs_ci_registration() and inputs.github.available):
return
timer = inputs.iteration_timer
timeout = resolve_ci_registration_timeout(inputs.ci_registration_timeout)
inputs.wait_registration(
context,
inputs.repo_dir,
inputs.review_target,
inputs.proxy_env,
timer.remaining_capped(timeout) if timer is not None else timeout,
inputs.ci_poll_interval,
clock=inputs.clock,
sleep=inputs.sleep,
probe=inputs.probe_ci,
)


def _fallback_probe(inputs: CiInspectionInputs) -> CiInspection:
Expand Down
43 changes: 2 additions & 41 deletions apps/sandbox-executor/src/sandbox_executor/flow/review/loop.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,51 +134,11 @@ def run_review_loop( # noqa: C901, PLR0912, PLR0913, PLR0915
run_ensemble_fn: Callable[..., list[ReviewerResult]] | None = None,
run_resolver_fn: Callable[..., Any] | None = None,
skip_post: bool = False,
defer_ci_settle: bool = False,
first_iteration: int = 1,
ledger_file: str | None = None,
github: GitForge | None = None,
) -> dict[str, Any]:
"""Execute the native Stage 4 review loop with the real reviewer ensemble.

Each iteration inspects PR mergeability and launches ``ensemble_size`` independent reviewer agent turns in parallel
with GitHub CI. Reviewers evaluate the real diff between the base and the resolved head SHA. If any reviewer
requests changes or reports open findings, pending CI checks are bypassed and findings are immediately dispatched to
the resolver. Only when all reviewers approve cleanly with zero open findings and mergeability is clean does the
loop wait for CI checks to settle as a post-review safety gate before calling ``decide_consensus()``. Reviewers run
only inside a sandbox: on the host the loop refuses before any PR, iteration or post. It enforces the
human-only PR merge rule by completing with approved consensus without merging to main.

Args:
context: Active FlowContext carrying repository and pipeline state.
target: Target execution branch name, PR number, or PR URL.
max_iterations: Maximum iteration budget before forced termination.
ensemble_size: Number of independent reviewer agent turns per iteration.
auto_pr: Whether to create PR automatically if target is only a branch.
dry_run: If True, evaluate without applying git commits or mutations.
ci_registration_timeout: Seconds to wait for CI checks to register when Stage 3 recorded no test
result (default: ``HOLON_CI_REGISTRATION_TIMEOUT``, then 180; ``0`` disables the wait).
ci_poll_interval: First interval between CI probes; pending-CI polls double from it.
ci_wait_budget: Seconds to wait for pending CI, outside the iteration budget (default: env, then 1800).
clock: Monotonic clock for the per-iteration budget and the CI waits (default: time.monotonic).
sleep: Sleep function used by the CI waits (default: time.sleep); injectable for tests.
run_ensemble_fn: Reviewer ensemble seam (default: ``review_ensemble.run_ensemble``); tests inject a fake.
skip_post: If True, never post the consensus to GitHub (the engine's container dispatch posts on the host).
first_iteration: Label of the first pass (default 1). It is only a label: the ledger ``review_iteration``
fields, finding IDs, trailers and the posted ``Iteration {n}`` heading carry it, while ``max_iterations``
alone caps how many passes run. The engine passes its own continued count here.
ledger_file: Where this pass appends ledger rows (default: the worktree's holon-knowledge ledger).
github: The stage's GitHub adapter, used for every PR, CI, mergeability and posting call (default: one built
here over the worktree with the token-reduction proxy environment); tests inject a ``FakeGitHub``.

The empty-diff guard runs for every target whatever ``auto_pr`` is: an empty diff is rejected and an
unverifiable one fails, before any PR, iteration or post. A dry run never measures anything, so it reports
``not_measured`` and is never approved; it never dispatches a reviewer. A consensus is posted only
on a terminal exit (approval, or the label budget exhausted) when at least one reviewer completed and no
infrastructure step failed (see ``decide_post``); one that cannot be posted is ``post_failed``, never approved.

Returns:
dict[str, Any]: Review loop outcome dictionary.
"""
ledger_commit._set_ledger_commit_suppressed(context, False)
clock = clock or time.monotonic
ensemble_fn = run_ensemble_fn or run_ensemble
Expand Down Expand Up @@ -288,6 +248,7 @@ def run_review_loop( # noqa: C901, PLR0912, PLR0913, PLR0915
ci_poll_interval,
clock,
sleep,
defer_ci_settle=defer_ci_settle,
)
iteration_summaries: list[str] = []
budget_breach: dict[str, Any] | None = None
Expand Down
28 changes: 16 additions & 12 deletions apps/sandbox-executor/src/sandbox_executor/flow/review/verdict.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,3 @@
"""The Stage 4 consensus verdict, decided from what the reviewers returned and cross-checked before any approval.

``decide_consensus`` judges the returned reviewer verdicts and counts; the blockers here add the checks it cannot see:
an activated role at ``CHANGES``, a reviewer whose verdict adjudication would have changed, and a container whose own
ensemble verdict was not APPROVED. Any blocker turns an APPROVED verdict into CHANGES_REQUESTED, never the reverse.
"""

from __future__ import annotations

from collections.abc import Iterable, Mapping, Sequence
Expand Down Expand Up @@ -64,11 +57,22 @@ def consensus_blockers(
container_verdict: ConsensusVerdict | None,
adjudication: Adjudication,
) -> list[str]:
"""Every reason beyond the reviewer verdicts that forbids approval; a missing container verdict adds none."""
blockers = role_objections(reviewers) + adjudication_mismatches(reviewers, adjudication)
if container_verdict is not None and container_verdict is not ConsensusVerdict.APPROVED:
blockers.append(f"reviewer container reported ensemble verdict {container_verdict}")
return blockers
objections = role_objections(reviewers) + adjudication_mismatches(reviewers, adjudication)
return objections + _container_verdict_blockers(reviewers, container_verdict, objections)


def _container_verdict_blockers(
reviewers: Sequence[ReviewerResult],
container_verdict: ConsensusVerdict | None,
objections: Sequence[str],
) -> list[str]:
if container_verdict is None or container_verdict is ConsensusVerdict.APPROVED:
return []
# why: a --skip-post container leaves pending CI to the host, so CHANGES_REQUESTED here is no objection
clean_ensemble = bool(reviewers) and not objections and not not_approved_verdicts(reviewers)
if container_verdict is ConsensusVerdict.CHANGES_REQUESTED and clean_ensemble:
return []
return [f"reviewer container reported ensemble verdict {container_verdict}"]


def _verdict_count_blocker(reviewers: Sequence[ReviewerResult]) -> list[str]:
Expand Down
37 changes: 37 additions & 0 deletions apps/sandbox-executor/tests/flow/review/test_ci_inspection.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,43 @@ def test_post_review_gate_without_a_wait_credits_nothing_and_drops_a_stale_wait(
assert (result.ci_green, result.ci_finding, result.ci_wait) == (False, True, None)


def test_a_deferred_gate_probes_pending_ci_once_without_settling_it(tmp_path):
inputs = _inputs(PENDING, defer_ci_settle=True, ci_wait=MagicMock())
with patch.object(ci_inspection, "settle_pending_ci") as settle:
result = inspect_ci(inputs, _ctx(tmp_path))

settle.assert_not_called()
inputs.wait_registration.assert_not_called()
inputs.iteration_timer.credit.assert_not_called()
assert (result.ci_green, result.ci_finding, result.decides) == (None, False, True)
assert result.ci_status["pending"] == 1
assert result.ci_wait is inputs.ci_wait


def test_a_deferred_gate_skips_the_registration_wait(tmp_path):
inputs = _inputs(PENDING, defer_ci_settle=True, test_gate=_TestGate(needs_registration=True))
with patch.object(ci_inspection, "settle_pending_ci") as settle:
result = inspect_ci(inputs, _ctx(tmp_path))

settle.assert_not_called()
inputs.wait_registration.assert_not_called()
assert result.ci_wait is None


def test_an_undeferred_gate_still_settles_pending_ci(tmp_path):
inputs = _inputs(PENDING)
with patch.object(ci_inspection, "settle_pending_ci", return_value=(dict(GREEN), None)) as settle:
result = inspect_ci(inputs, _ctx(tmp_path))

settle.assert_called_once()
assert (result.ci_green, result.ci_finding) == (True, False)


def test_a_deferred_gate_still_reports_red_ci_as_a_finding(tmp_path):
result = inspect_ci(_inputs(RED, defer_ci_settle=True), _ctx(tmp_path))
assert (result.ci_green, result.ci_finding, result.decides) == (False, True, True)


def test_fallback_under_dry_run_decides_nothing(tmp_path):
result = inspect_ci(_inputs(GREEN, effective_dry_run=True), _ctx(tmp_path))
assert result.decides is False
Expand Down
75 changes: 63 additions & 12 deletions apps/sandbox-executor/tests/flow/review/test_consensus_integrity.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import pytest
from sandbox_executor.flow import run_review_loop
from sandbox_executor.flow.review.adjudication import (
Adjudication,
_augment_pr_text_with_rejected,
_filter_adjudicated_findings,
record_nit_rejections,
Expand All @@ -38,7 +39,14 @@
)
from sandbox_executor.review_report import FindingDisposition, FindingRow, finding_signature, with_reviewer_detail

from tests.review_fakes import FAKE_HEAD_SHA, FakeEnsemble, clean_reviewer, install_fake_reviewers
from tests.review_fakes import (
FAKE_HEAD_SHA,
FakeEnsemble,
clean_reviewer,
install_fake_reviewers,
objecting_reviewer,
with_clean_peers,
)
from tests.test_review_dispatch import EXEC_TARGET
from tests.test_review_loop import _ensemble_ctx, _LoopStubs

Expand Down Expand Up @@ -259,24 +267,67 @@ def test_a_passing_role_table_still_approves(tmp_path, monkeypatch):
assert res["consensus"]["approved"] is True


def test_a_container_verdict_other_than_approved_blocks_a_clean_host_view(tmp_path, monkeypatch):
install_fake_reviewers(monkeypatch)
monkeypatch.delenv("HOLON_IN_SANDBOX", raising=False)
monkeypatch.delenv("HOLON_ROLE", raising=False)

def _container_reporting(verdict: ConsensusVerdict):
def fake_dispatch(role, runner, model, args, **kwargs):
reviewers = [clean_reviewer(1), clean_reviewer(2), clean_reviewer(3)]
payload = serialize_review_outcome(reviewers, ConsensusVerdict.CHANGES_REQUESTED)
payload = serialize_review_outcome(reviewers, verdict)
Path(kwargs["result_file"]).write_text(json.dumps(payload), encoding="utf-8")
return 0
return 0 if verdict is ConsensusVerdict.APPROVED else 1

ctx = _ensemble_ctx(tmp_path, dispatcher=fake_dispatch)
with _LoopStubs():
return fake_dispatch


def _host_loop_over_container(tmp_path, monkeypatch, verdict: ConsensusVerdict):
install_fake_reviewers(monkeypatch)
monkeypatch.delenv("HOLON_IN_SANDBOX", raising=False)
monkeypatch.delenv("HOLON_ROLE", raising=False)
ctx = _ensemble_ctx(tmp_path, dispatcher=_container_reporting(verdict))
with _LoopStubs() as stubs:
res = run_review_loop(ctx, target=EXEC_TARGET, max_iterations=1, ensemble_size=3)
return res, ctx, stubs


def test_a_changes_requested_container_verdict_over_a_clean_ensemble_lets_the_host_gate_ci(tmp_path, monkeypatch):
res, ctx, stubs = _host_loop_over_container(tmp_path, monkeypatch, ConsensusVerdict.CHANGES_REQUESTED)

assert res["consensus"]["approved"] is True
assert res["ensemble_verdict"] == "APPROVED"
assert res["consensus_blockers"] == []
assert "ci_checks" in stubs.github.methods()
assert not any("reviewer container reported" in line for line in ctx.logs)


def test_a_failed_container_verdict_still_blocks_a_clean_host_view(tmp_path, monkeypatch):
res, ctx, _stubs = _host_loop_over_container(tmp_path, monkeypatch, ConsensusVerdict.FAILED)

assert res["consensus"]["approved"] is False
assert res["ensemble_verdict"] == "CHANGES_REQUESTED"
assert any("reviewer container reported ensemble verdict CHANGES_REQUESTED" in line for line in ctx.logs)
assert res["consensus_blockers"] == ["reviewer container reported ensemble verdict FAILED"]
assert any("reviewer container reported ensemble verdict FAILED" in line for line in ctx.logs)


_CONTAINER_BLOCKER = "reviewer container reported ensemble verdict CHANGES_REQUESTED"


def test_a_changes_requested_container_verdict_over_a_clean_ensemble_is_no_blocker():
clean = [clean_reviewer(1), clean_reviewer(2), clean_reviewer(3)]
assert consensus_blockers(clean, ConsensusVerdict.CHANGES_REQUESTED, Adjudication()) == []


def test_a_role_objection_keeps_the_container_blocker():
reviewers = [clean_reviewer(1), clean_reviewer(2), _clean_with_security(3, "CHANGES")]
assert consensus_blockers(reviewers, ConsensusVerdict.CHANGES_REQUESTED, Adjudication()) == [
"reviewer 3 Security role CHANGES",
_CONTAINER_BLOCKER,
]


def test_a_reviewer_with_a_finding_keeps_the_container_blocker():
reviewers = with_clean_peers([objecting_reviewer(1, "nit", ReviewerVerdict.APPROVED)])
assert consensus_blockers(reviewers, ConsensusVerdict.CHANGES_REQUESTED, Adjudication()) == [_CONTAINER_BLOCKER]


def test_no_returned_reviewer_keeps_the_container_blocker():
assert consensus_blockers([], ConsensusVerdict.CHANGES_REQUESTED, Adjudication()) == [_CONTAINER_BLOCKER]


def test_a_reviewer_whose_findings_were_all_suppressed_is_logged_and_never_approved(tmp_path, monkeypatch):
Expand Down
60 changes: 60 additions & 0 deletions apps/sandbox-executor/tests/flow/review/test_loop.py
Original file line number Diff line number Diff line change
Expand Up @@ -890,3 +890,63 @@ def test_the_same_red_check_on_a_green_target_stays_a_ci_finding_while_a_reviewe

assert res["blocked_on"] is None
assert sorted(resolver_calls[0]) == ["FIND-CI-001", "R1-F1"]


_PENDING_CI = {"all_passed": False, "passed": 0, "failed": 0, "pending": 1, "total": 1, "source": "github_cli"}


def _loop_over_pending_ci(tmp_path, **kwargs):
from sandbox_executor.flow.review import ci_inspection

pending = {**_PENDING_CI, "checks": ci_checks_payload(pending=1)}
with (
_LoopStubs(ci=_PENDING_CI),
patch.object(ci_inspection, "settle_pending_ci", return_value=(pending, None)) as settle,
):
res = run_review_loop(
_ensemble_ctx(tmp_path),
target=EXEC_TARGET,
max_iterations=1,
run_ensemble_fn=FakeEnsemble(),
skip_post=True,
clock=lambda: 0.0,
sleep=lambda _s: None,
**kwargs,
)
return res, settle


def test_a_skip_post_container_deferring_ci_never_settles_pending_ci(tmp_path):
res, settle = _loop_over_pending_ci(tmp_path, defer_ci_settle=True)

settle.assert_not_called()
assert res["ci_checks"]["pending"] == 1
assert res["consensus"]["approved"] is False


def test_a_loop_without_deferral_still_settles_pending_ci(tmp_path):
_res, settle = _loop_over_pending_ci(tmp_path)

settle.assert_called_once()


@pytest.mark.parametrize(("flags", "deferred"), [(["--skip-post"], True), ([], False)])
def test_the_container_entrypoint_defers_ci_settling_only_under_skip_post(tmp_path, flags, deferred):
import sys

from sandbox_executor.entrypoint.review_loop import main as review_loop_main

(tmp_path / ".git").mkdir()
argv = ["review_loop", EXEC_TARGET, f"--target-worktree={tmp_path}", "--dry-run", *flags]
prepared = ReviewTarget(raw=EXEC_TARGET, head_branch=EXEC_TARGET, head_sha="a" * 40)
with (
patch.object(sys, "argv", argv),
patch("sandbox_executor.entrypoint.review_loop.check_and_resolve_stage_conflicts"),
patch("sandbox_executor.entrypoint.review_loop._prepare_workspace", return_value=prepared),
patch("sandbox_executor.entrypoint.review_loop.run_review_loop", return_value={"consensus": {}}) as loop,
pytest.raises(SystemExit),
):
review_loop_main()

assert loop.call_args.kwargs["defer_ci_settle"] is deferred
assert loop.call_args.kwargs["skip_post"] is deferred
Loading
Loading