Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,16 @@ def changed_markdown_files(repo: Any) -> list[str]:
if file_path.endswith(".md"):
md_files.append(file_path)
return md_files


def committed_markdown_files(repo: Any, base: str | None) -> list[str]:
if not base:
return []
diff_res = repo.run(["diff", "--name-only", "--diff-filter=d", base, "HEAD", "--", "*.md"], check=False)
if diff_res.returncode != 0:
return []
return [line.strip() for line in diff_res.stdout.splitlines() if line.strip()]


def markdown_to_format(repo: Any, base: str | None) -> list[str]:
return list(dict.fromkeys([*changed_markdown_files(repo), *committed_markdown_files(repo, base)]))
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@
from sandbox_executor.entrypoint.agent_output_block import prepare_agent_output_block as prepare_agent_output_block
from sandbox_executor.entrypoint.agent_output_block import sanitize_agent_output as sanitize_agent_output
from sandbox_executor.entrypoint.changed_markdown import changed_markdown_files as changed_markdown_files
from sandbox_executor.entrypoint.changed_markdown import committed_markdown_files as committed_markdown_files
from sandbox_executor.entrypoint.changed_markdown import markdown_to_format as markdown_to_format
from sandbox_executor.entrypoint.empty_diff_excerpt import report_empty_diff_output as report_empty_diff_output
from sandbox_executor.entrypoint.execution_args import ExecutionArgs as ExecutionArgs
from sandbox_executor.entrypoint.execution_args import _parse_review_finding_ids as _parse_review_finding_ids
Expand Down Expand Up @@ -88,6 +90,7 @@
from sandbox_executor.entrypoint.sync_conflict import record_sync_failure as record_sync_failure
from sandbox_executor.entrypoint.sync_conflict import superseding_failure_row as superseding_failure_row
from sandbox_executor.entrypoint.taken_ids import taken_child_ids as taken_child_ids
from sandbox_executor.execution_notes_format import format_execution_notes as format_execution_notes
from sandbox_executor.formatting import converge_prettier as converge_prettier
from sandbox_executor.git import GitRepository as GitRepository
from sandbox_executor.ledger import ActionRecord as ActionRecord
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
import sandbox_executor.entrypoint.executor as executor_facade
from sandbox_executor.artefacts import ArtefactReport
from sandbox_executor.budgets import BudgetBreach
from sandbox_executor.entrypoint.changed_markdown import changed_markdown_files
from sandbox_executor.entrypoint.empty_diff_excerpt import report_empty_diff_output
from sandbox_executor.entrypoint.execution_workspace import format_skipped_scratch_message, unstage_sidecar_scratch
from sandbox_executor.entrypoint.executor.commands import _entrypoint_git_runner, _get_repo, is_action_logging_enabled
Expand Down Expand Up @@ -159,30 +158,46 @@ def _guard_empty_diff(self) -> None:
print(f"Error: {self.summary}", file=sys.stderr)
report_empty_diff_output(self.failure_reason, self.agent_output_text, self.agent_output_bytes)

def _markdown_to_converge(self) -> list[str]:
md_files = executor_facade.markdown_to_format(self.repo, self.plan_tip)
return [md_file for md_file in md_files if md_file != self.notes_rel]

def _format_own_notes(self) -> list[str]:
if not self.notes_rel or not os.path.isfile(self.notes_path):
return []
return [self.notes_rel] if executor_facade.format_execution_notes(self.notes_rel, self.repo_dir) else []

def _record_markdown_formatting(self, md_files: list[str]) -> None:
if not md_files or not is_action_logging_enabled(self.intent_data):
return
with suppress_ledger_failures():
executor_facade.append_action_record(
self.executions_ledger,
ActionRecord(
action_id=generate_action_id(),
execution_id=self.exec_id,
event_type="doc_update",
action=f"Formatted {len(md_files)} markdown files with prettier",
category="doc",
labels=["formatting", "prettier"],
target=", ".join(md_files[:_MAX_ACTION_TARGET_MD_FILES]),
outcome="success",
action_origin=self.action_origin,
),
)

def _converge_markdown(self) -> None:
formatted: list[str] = []
try:
if md_files := changed_markdown_files(self.repo):
if md_files := self._markdown_to_converge():
executor_facade.converge_prettier(md_files, repo_dir=self.repo_dir)
if is_action_logging_enabled(self.intent_data):
with suppress_ledger_failures():
executor_facade.append_action_record(
self.executions_ledger,
ActionRecord(
action_id=generate_action_id(),
execution_id=self.exec_id,
event_type="doc_update",
action=f"Formatted {len(md_files)} markdown files with prettier",
category="doc",
labels=["formatting", "prettier"],
target=", ".join(md_files[:_MAX_ACTION_TARGET_MD_FILES]),
outcome="success",
action_origin=self.action_origin,
),
)
formatted.extend(md_files)
except LedgerRewriteError:
raise
except Exception as e:
print(f"Warning: Prettier formatting failed: {redact_agent_secrets(str(e))}", file=sys.stderr)
formatted.extend(self._format_own_notes())
self._record_markdown_formatting(formatted)

def salvage(self) -> None:
if self.exec_status != "success" and self.plan_tip:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
verification_error,
)
from sandbox_executor.entrypoint.uv_lock import LockfileMismatchError, check_lockfile, frozen_env
from sandbox_executor.execution_notes_format import format_own_execution_notes, resolver_stage_pathspec
from sandbox_executor.flow.context import FlowContext
from sandbox_executor.flow.review.delta_review_forwarding import load_forwarded_decision
from sandbox_executor.flow.review.git_identity import _review_git_env
Expand Down Expand Up @@ -557,11 +558,13 @@ def _commit_resolution(
run_cmd(reset_cmd, cwd=repo_dir, check=True)
initial_head = pre_resolver_head or current_head
budget_refusal = None if opts.dry_run else _restore_budget_config(repo_dir, opts.intent_data)
# why: the flow wrote its execution notes itself, so a hygiene failure on them is repaired here instead of looping
own_notes_formatted = not opts.dry_run and format_own_execution_notes(repo_dir, head_branch)
status_proc = run_cmd(["git", "status", "--porcelain", *_RESOLVER_PATHSPEC], cwd=repo_dir, check=False)
has_worktree_changes = bool((status_proc.stdout or "").strip())
applied_items = [d for d in dispositions if d.disposition == "applied"]

if not applied_items or not has_worktree_changes:
if (not applied_items and not own_notes_formatted) or not has_worktree_changes:
return dispositions, initial_head, False, False, budget_refusal

if opts.dry_run:
Expand All @@ -579,7 +582,8 @@ def _commit_resolution(
if not lint_ok or not tests_ok:
return dispositions, initial_head, lint_ok, tests_ok, verify_err

run_cmd(["git", "add", "-A", *_RESOLVER_PATHSPEC], cwd=repo_dir, check=True)
stage_pathspec = resolver_stage_pathspec(head_branch, bool(applied_items), _RESOLVER_PATHSPEC)
run_cmd(["git", "add", "-A", *stage_pathspec], cwd=repo_dir, check=True)
commit_cmd = ["git", "commit", "-m", _resolver_commit_message(iteration, applied_items)]
_assert_safe_git_args(commit_cmd)
# why: the review git identity reaches only the resolver commit, never the process environment
Expand Down
114 changes: 114 additions & 0 deletions apps/sandbox-executor/src/sandbox_executor/execution_notes_format.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
from __future__ import annotations

import logging
import shutil
import subprocess
import sys

# why: CI's lint-docs runs the unpinned repository Prettier, which wraps differently from the pinned prettier@3.8.4
from sandbox_executor.calibration_format import LINT_DOCS_PRETTIER, PRETTIER_PASSES, PRETTIER_TIMEOUT_SECONDS
from sandbox_executor.plan_artifact_format import (
MARKDOWN_SUFFIX,
WARNING_ERROR_TEXT_LIMIT,
artifact_bytes,
format_plan_artifact,
is_markdown_file_inside,
)
from sandbox_executor.redaction import redact_then_truncate
from sandbox_executor.ref_names import INTENT_SUFFIX

logger = logging.getLogger(__name__)

EXECUTIONS_DIR = "executions"
EXECUTION_SEGMENT_PREFIX = "E-"
PLAN_SEGMENT_PREFIX = "P-"
PRETTIER_OUTPUT_LINES = 5


def _is_safe_segment(segment: str) -> bool:
return bool(segment) and "/" not in segment and "\\" not in segment and ".." not in segment


def own_execution_notes_for_branch(flow_branch: str) -> str | None:
segments = flow_branch.strip().removesuffix(INTENT_SUFFIX).strip("/").split("/")
execution_segment = segments[-1]
if not execution_segment.startswith(EXECUTION_SEGMENT_PREFIX) or not _is_safe_segment(execution_segment):
return None
if not any(segment.startswith(PLAN_SEGMENT_PREFIX) for segment in segments[:-1]):
return None
return f"{EXECUTIONS_DIR}/{execution_segment}{MARKDOWN_SUFFIX}"


def is_own_execution_notes(path: str, flow_branch: str) -> bool:
own_notes = own_execution_notes_for_branch(flow_branch)
return own_notes is not None and path.strip().removeprefix("./") == own_notes


def _repository_prettier(mode: str, notes_rel: str, repo_dir: str) -> subprocess.CompletedProcess[str]:
return subprocess.run(
[*LINT_DOCS_PRETTIER, mode, notes_rel],
cwd=repo_dir,
capture_output=True,
text=True,
timeout=PRETTIER_TIMEOUT_SECONDS,
check=False,
)


def _summarise(label: str, proc: subprocess.CompletedProcess[str]) -> str:
output = f"{proc.stdout or ''}{proc.stderr or ''}".strip().splitlines()[:PRETTIER_OUTPUT_LINES]
return f"{label} exited {proc.returncode}: " + " | ".join(output)


def _converge(notes_rel: str, repo_dir: str) -> str | None:
reason = None
for _ in range(PRETTIER_PASSES):
write = _repository_prettier("--write", notes_rel, repo_dir)
if write.returncode != 0:
return _summarise("write", write)
check = _repository_prettier("--check", notes_rel, repo_dir)
if check.returncode == 0:
return None
reason = _summarise("check", check)
return reason


def _prettier_failure(notes_rel: str, repo_dir: str) -> str | None:
if shutil.which("npx") is None:
return "npx is not on PATH"
try:
return _converge(notes_rel, repo_dir)
except (OSError, subprocess.TimeoutExpired) as could_not_run:
return f"Prettier could not run: {could_not_run}"


def _warn_prettier_skipped(notes_rel: str, reason: str) -> None:
bounded_reason = redact_then_truncate(reason, WARNING_ERROR_TEXT_LIMIT) or ""
message = f"Warning: Prettier formatting skipped for {notes_rel}: {bounded_reason}"
logger.warning(message)
print(message, file=sys.stderr)


def format_execution_notes(notes_rel: str, repo_dir: str) -> bool:
if not is_markdown_file_inside(notes_rel, repo_dir):
return False
bytes_before = artifact_bytes(notes_rel, repo_dir)
format_plan_artifact(notes_rel, repo_dir)
if reason := _prettier_failure(notes_rel, repo_dir):
_warn_prettier_skipped(notes_rel, reason)
return artifact_bytes(notes_rel, repo_dir) != bytes_before


def format_own_execution_notes(repo_dir: str, flow_branch: str) -> bool:
own_notes = own_execution_notes_for_branch(flow_branch)
if own_notes is None or not format_execution_notes(own_notes, repo_dir):
return False
logger.info("Formatted the flow's own execution notes: %s", own_notes)
return True


def resolver_stage_pathspec(flow_branch: str, applied_any: bool, base_pathspec: list[str]) -> list[str]:
own_notes = own_execution_notes_for_branch(flow_branch)
if applied_any or own_notes is None:
return base_pathspec
return ["--", own_notes]
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ def _run_ruff_format_on_markdown(command_prefix: tuple[str, ...], artifact_rel:
return _run_ruff_format(command_prefix, artifact_rel, repo_dir, preview=True)


def _is_markdown_file_inside(artifact_rel: str, repo_dir: str) -> bool:
def is_markdown_file_inside(artifact_rel: str, repo_dir: str) -> bool:
if os.path.isabs(artifact_rel) or os.pardir in artifact_rel.replace("\\", "/").split("/"):
return False
if not artifact_rel.endswith(MARKDOWN_SUFFIX):
Expand All @@ -94,7 +94,7 @@ def _is_markdown_file_inside(artifact_rel: str, repo_dir: str) -> bool:
return os.path.realpath(artifact_path).startswith(resolved_repo_dir + os.sep)


def _artifact_bytes(artifact_rel: str, repo_dir: str) -> bytes | None:
def artifact_bytes(artifact_rel: str, repo_dir: str) -> bytes | None:
try:
with open(os.path.join(repo_dir, artifact_rel), "rb") as artifact_file:
return artifact_file.read()
Expand All @@ -110,18 +110,18 @@ def _skipped_with_warning(artifact_rel: str, reason: str) -> FenceFormatOutcome:


def format_plan_artifact(artifact_rel: str, repo_dir: str) -> FenceFormatOutcome:
if not _is_markdown_file_inside(artifact_rel, repo_dir):
if not is_markdown_file_inside(artifact_rel, repo_dir):
return FenceFormatOutcome(artifact_rel, FenceFormatStatus.SKIPPED, "not a Markdown file inside the repository")
command_prefix = _ruff_command_prefix()
if not command_prefix:
return _skipped_with_warning(artifact_rel, RUFF_NOT_FOUND_REASON)
bytes_before = _artifact_bytes(artifact_rel, repo_dir)
bytes_before = artifact_bytes(artifact_rel, repo_dir)
if bytes_before is None:
return _skipped_with_warning(artifact_rel, "the file could not be read")
ruff_run = _run_ruff_format_on_markdown(command_prefix, artifact_rel, repo_dir)
if not ruff_run.succeeded:
return _skipped_with_warning(artifact_rel, ruff_run.error_text)
if _artifact_bytes(artifact_rel, repo_dir) == bytes_before:
if artifact_bytes(artifact_rel, repo_dir) == bytes_before:
return FenceFormatOutcome(artifact_rel, FenceFormatStatus.UNCHANGED)
return FenceFormatOutcome(artifact_rel, FenceFormatStatus.FORMATTED)

Expand All @@ -142,7 +142,7 @@ def format_own_plan_artifacts(repo_dir: str, flow_branch: str) -> tuple[FenceFor
outcomes = tuple(
format_plan_artifact(artifact, repo_dir)
for artifact in _plan_artifacts_derived_from(flow_branch)
if is_own_plan_artifact(artifact, flow_branch) and _is_markdown_file_inside(artifact, repo_dir)
if is_own_plan_artifact(artifact, flow_branch) and is_markdown_file_inside(artifact, repo_dir)
)
formatted = [outcome.artifact for outcome in outcomes if outcome.status is FenceFormatStatus.FORMATTED]
if formatted:
Expand Down
Loading
Loading