diff --git a/apps/sandbox-executor/src/sandbox_executor/entrypoint/changed_markdown.py b/apps/sandbox-executor/src/sandbox_executor/entrypoint/changed_markdown.py index cce0d02cd..18ad3539d 100644 --- a/apps/sandbox-executor/src/sandbox_executor/entrypoint/changed_markdown.py +++ b/apps/sandbox-executor/src/sandbox_executor/entrypoint/changed_markdown.py @@ -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)])) diff --git a/apps/sandbox-executor/src/sandbox_executor/entrypoint/executor/__init__.py b/apps/sandbox-executor/src/sandbox_executor/entrypoint/executor/__init__.py index 7fa59c239..1bdf4d18f 100644 --- a/apps/sandbox-executor/src/sandbox_executor/entrypoint/executor/__init__.py +++ b/apps/sandbox-executor/src/sandbox_executor/entrypoint/executor/__init__.py @@ -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 @@ -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 diff --git a/apps/sandbox-executor/src/sandbox_executor/entrypoint/executor/outcome.py b/apps/sandbox-executor/src/sandbox_executor/entrypoint/executor/outcome.py index 7a08c4c14..d3d9e2c3f 100644 --- a/apps/sandbox-executor/src/sandbox_executor/entrypoint/executor/outcome.py +++ b/apps/sandbox-executor/src/sandbox_executor/entrypoint/executor/outcome.py @@ -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 @@ -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: diff --git a/apps/sandbox-executor/src/sandbox_executor/entrypoint/review_loop.py b/apps/sandbox-executor/src/sandbox_executor/entrypoint/review_loop.py index 5e203ff89..8082e5491 100644 --- a/apps/sandbox-executor/src/sandbox_executor/entrypoint/review_loop.py +++ b/apps/sandbox-executor/src/sandbox_executor/entrypoint/review_loop.py @@ -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 @@ -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: @@ -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 diff --git a/apps/sandbox-executor/src/sandbox_executor/execution_notes_format.py b/apps/sandbox-executor/src/sandbox_executor/execution_notes_format.py new file mode 100644 index 000000000..0c0812546 --- /dev/null +++ b/apps/sandbox-executor/src/sandbox_executor/execution_notes_format.py @@ -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] diff --git a/apps/sandbox-executor/src/sandbox_executor/plan_artifact_format.py b/apps/sandbox-executor/src/sandbox_executor/plan_artifact_format.py index 523685801..ae4e4afb6 100644 --- a/apps/sandbox-executor/src/sandbox_executor/plan_artifact_format.py +++ b/apps/sandbox-executor/src/sandbox_executor/plan_artifact_format.py @@ -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): @@ -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() @@ -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) @@ -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: diff --git a/apps/sandbox-executor/tests/test_execution_notes_format.py b/apps/sandbox-executor/tests/test_execution_notes_format.py new file mode 100644 index 000000000..b54434871 --- /dev/null +++ b/apps/sandbox-executor/tests/test_execution_notes_format.py @@ -0,0 +1,241 @@ +from __future__ import annotations + +import logging +import subprocess +from pathlib import Path +from unittest.mock import patch + +import pytest +from sandbox_executor import execution_notes_format +from sandbox_executor.calibration_format import LINT_DOCS_PRETTIER, PRETTIER_PASSES +from sandbox_executor.execution_notes_format import ( + format_execution_notes, + format_own_execution_notes, + is_own_execution_notes, + own_execution_notes_for_branch, + resolver_stage_pathspec, +) +from sandbox_executor.plan_artifact_format import FenceFormatOutcome, FenceFormatStatus + +FLOW_BRANCH = "I-1-x/P-1-y/E-1-z/_" +OWN_NOTES = "executions/E-1-z.md" +FOREIGN_NOTES = "executions/E-9-other.md" +MISALIGNED_NOTES = ( + "# Execution Record: E-1-x\n\n" + "## Actual Metrics\n\n" + "| metric | value |\n" + "|---|---|\n" + "| success_actual | 1.0 |\n" + "| learning_value_actual | 2.0 |\n" +) +# why: verbatim output of `npx --yes prettier --write` on MISALIGNED_NOTES with the repository .prettierrc.json +REPOSITORY_PRETTIER_NOTES = ( + "# Execution Record: E-1-x\n\n" + "## Actual Metrics\n\n" + "| metric | value |\n" + "| --------------------- | ----- |\n" + "| success_actual | 1.0 |\n" + "| learning_value_actual | 2.0 |\n" +) + + +class RepositoryPrettierStandIn: + def __init__(self, write_returncode: int = 0, failing_checks: int = 0) -> None: + self.write_returncode = write_returncode + self.failing_checks = failing_checks + self.calls: list[tuple[list[str], str]] = [] + + def __call__(self, mode: str, notes_rel: str, repo_dir: str) -> subprocess.CompletedProcess[str]: + argv = [*LINT_DOCS_PRETTIER, mode, notes_rel] + self.calls.append((argv, repo_dir)) + notes = Path(repo_dir, notes_rel) + if mode == "--write": + if self.write_returncode == 0: + notes.write_text(REPOSITORY_PRETTIER_NOTES, encoding="utf-8") + return subprocess.CompletedProcess(argv, self.write_returncode, stdout="", stderr="[error] boom\n") + returncode = 0 if passes_repository_prettier_check(notes.read_text(encoding="utf-8")) else 1 + if self.failing_checks > 0: + self.failing_checks -= 1 + returncode = 1 + return subprocess.CompletedProcess(argv, returncode, stdout="Checking formatting...\n", stderr="") + + +def passes_repository_prettier_check(text: str) -> bool: + return text == REPOSITORY_PRETTIER_NOTES + + +def unchanged_fences(notes_rel: str, _repo_dir: str) -> FenceFormatOutcome: + return FenceFormatOutcome(notes_rel, FenceFormatStatus.UNCHANGED) + + +def write_notes(repo: Path, notes_rel: str = OWN_NOTES, content: str = MISALIGNED_NOTES) -> Path: + notes = repo / notes_rel + notes.parent.mkdir(parents=True, exist_ok=True) + notes.write_text(content, encoding="utf-8") + return notes + + +@pytest.fixture +def prettier(monkeypatch: pytest.MonkeyPatch) -> RepositoryPrettierStandIn: + stand_in = RepositoryPrettierStandIn() + monkeypatch.setattr(execution_notes_format, "_repository_prettier", stand_in) + monkeypatch.setattr(execution_notes_format.shutil, "which", lambda name: f"/usr/bin/{name}") + monkeypatch.setattr(execution_notes_format, "format_plan_artifact", unchanged_fences) + return stand_in + + +@pytest.mark.parametrize( + ("branch", "expected"), + [ + (FLOW_BRANCH, OWN_NOTES), + ("I-1-x/P-1--2-child/P-3/E-4-sub/_", "executions/E-4-sub.md"), + ("I-1-x/P-1-y/_", None), + ("I-1-x/P-1-y/E-1-z/calibrated", None), + ("I-1-x/E-1-z/_", None), + ("I-1-x/P-1-y/E-..z/_", None), + ("", None), + ], +) +def test_own_notes_are_derived_only_from_an_execution_branch(branch: str, expected: str | None) -> None: + assert own_execution_notes_for_branch(branch) == expected + + +def test_only_the_flows_own_notes_count_as_own() -> None: + assert is_own_execution_notes(OWN_NOTES, FLOW_BRANCH) + assert is_own_execution_notes(f"./{OWN_NOTES}", FLOW_BRANCH) + assert not is_own_execution_notes(FOREIGN_NOTES, FLOW_BRANCH) + assert not is_own_execution_notes(OWN_NOTES, "I-1-x/P-1-y/_") + + +def test_repository_prettier_argv_writes_then_checks_in_the_repository(tmp_path: Path) -> None: + write_notes(tmp_path) + completed = subprocess.CompletedProcess([], 0, stdout="", stderr="") + with ( + patch.object(execution_notes_format.shutil, "which", return_value="/usr/bin/npx"), + patch.object(execution_notes_format, "format_plan_artifact", unchanged_fences), + patch.object(execution_notes_format.subprocess, "run", return_value=completed) as run, + ): + format_execution_notes(OWN_NOTES, str(tmp_path)) + argvs = [call.args[0] for call in run.call_args_list] + assert argvs == [ + ["npx", "--yes", "prettier", "--write", OWN_NOTES], + ["npx", "--yes", "prettier", "--check", OWN_NOTES], + ] + assert {call.kwargs["cwd"] for call in run.call_args_list} == {str(tmp_path)} + assert all("env" not in call.kwargs for call in run.call_args_list) + + +def test_notes_are_formatted_to_the_repository_style(tmp_path: Path, prettier: RepositoryPrettierStandIn) -> None: + notes = write_notes(tmp_path) + assert format_execution_notes(OWN_NOTES, str(tmp_path)) + assert notes.read_text(encoding="utf-8") == REPOSITORY_PRETTIER_NOTES + assert not format_execution_notes(OWN_NOTES, str(tmp_path)) + + +def test_convergence_stops_after_the_bounded_passes( + tmp_path: Path, prettier: RepositoryPrettierStandIn, caplog: pytest.LogCaptureFixture +) -> None: + write_notes(tmp_path) + prettier.failing_checks = PRETTIER_PASSES + 1 + with caplog.at_level(logging.WARNING): + format_execution_notes(OWN_NOTES, str(tmp_path)) + assert len(prettier.calls) == 2 * PRETTIER_PASSES + assert [record.message for record in caplog.records if OWN_NOTES in record.message] + + +def test_missing_npx_warns_once_naming_the_notes( + tmp_path: Path, + prettier: RepositoryPrettierStandIn, + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, + capsys: pytest.CaptureFixture[str], +) -> None: + write_notes(tmp_path) + monkeypatch.setattr(execution_notes_format.shutil, "which", lambda _name: None) + with caplog.at_level(logging.WARNING): + assert not format_execution_notes(OWN_NOTES, str(tmp_path)) + warnings = [record.message for record in caplog.records if record.levelno == logging.WARNING] + assert warnings == [f"Warning: Prettier formatting skipped for {OWN_NOTES}: npx is not on PATH"] + assert OWN_NOTES in capsys.readouterr().err + assert prettier.calls == [] + + +def test_failing_write_warns_once_and_skips_the_check( + tmp_path: Path, prettier: RepositoryPrettierStandIn, caplog: pytest.LogCaptureFixture +) -> None: + write_notes(tmp_path) + prettier.write_returncode = 2 + with caplog.at_level(logging.WARNING): + assert not format_execution_notes(OWN_NOTES, str(tmp_path)) + warnings = [record.message for record in caplog.records if record.levelno == logging.WARNING] + assert len(warnings) == 1 + assert OWN_NOTES in warnings[0] + assert [argv[3] for argv, _ in prettier.calls] == ["--write"] + + +def test_prettier_that_cannot_start_is_a_warning( + tmp_path: Path, + prettier: RepositoryPrettierStandIn, + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, +) -> None: + write_notes(tmp_path) + + def time_out(*_args: object) -> subprocess.CompletedProcess[str]: + raise subprocess.TimeoutExpired("npx", 120) + + monkeypatch.setattr(execution_notes_format, "_repository_prettier", time_out) + with caplog.at_level(logging.WARNING): + assert not format_execution_notes(OWN_NOTES, str(tmp_path)) + assert any(OWN_NOTES in record.message for record in caplog.records) + + +def test_missing_notes_start_no_process(tmp_path: Path, prettier: RepositoryPrettierStandIn) -> None: + with patch.object(execution_notes_format, "format_plan_artifact") as fences: + assert not format_execution_notes(OWN_NOTES, str(tmp_path)) + assert not format_execution_notes("../outside.md", str(tmp_path)) + fences.assert_not_called() + assert prettier.calls == [] + + +def test_fences_are_formatted_before_prettier(tmp_path: Path, prettier: RepositoryPrettierStandIn) -> None: + write_notes(tmp_path) + order: list[str] = [] + + def record_fences(notes_rel: str, repo_dir: str) -> FenceFormatOutcome: + order.append("fences") + return unchanged_fences(notes_rel, repo_dir) + + def record_prettier(mode: str, notes_rel: str, repo_dir: str) -> subprocess.CompletedProcess[str]: + order.append(mode) + return prettier(mode, notes_rel, repo_dir) + + with ( + patch.object(execution_notes_format, "format_plan_artifact", record_fences), + patch.object(execution_notes_format, "_repository_prettier", record_prettier), + ): + format_execution_notes(OWN_NOTES, str(tmp_path)) + assert order == ["fences", "--write", "--check"] + + +def test_own_notes_formatter_never_opens_another_flows_notes( + tmp_path: Path, prettier: RepositoryPrettierStandIn +) -> None: + write_notes(tmp_path) + foreign = write_notes(tmp_path, FOREIGN_NOTES) + assert format_own_execution_notes(str(tmp_path), FLOW_BRANCH) + assert foreign.read_text(encoding="utf-8") == MISALIGNED_NOTES + assert {argv[4] for argv, _ in prettier.calls} == {OWN_NOTES} + + +def test_plan_branch_formats_no_notes(tmp_path: Path, prettier: RepositoryPrettierStandIn) -> None: + write_notes(tmp_path) + assert not format_own_execution_notes(str(tmp_path), "I-1-x/P-1-y/_") + assert prettier.calls == [] + + +def test_resolver_stages_only_the_own_notes_without_an_applied_finding() -> None: + base = ["--", "."] + assert resolver_stage_pathspec(FLOW_BRANCH, False, base) == ["--", OWN_NOTES] + assert resolver_stage_pathspec(FLOW_BRANCH, True, base) == base + assert resolver_stage_pathspec("I-1-x/P-1-y/_", False, base) == base diff --git a/apps/sandbox-executor/tests/test_executor_characterisation.py b/apps/sandbox-executor/tests/test_executor_characterisation.py index 5caff5e2e..dd895030d 100644 --- a/apps/sandbox-executor/tests/test_executor_characterisation.py +++ b/apps/sandbox-executor/tests/test_executor_characterisation.py @@ -102,6 +102,7 @@ def __init__(self, root: Path) -> None: self.plan_tip = _git(seed, "rev-parse", "HEAD").strip() self.workspace = os.path.join(self.root, "workspace") _git(self.root, "clone", "-q", "--branch", PLAN, bare, self.workspace) + self.notes_formatter: Callable[[str, str], bool] = MagicMock(return_value=False) def main( self, first_turn: Callable[[str, str], None], *, breach: BudgetBreach | None = None, returncode: int = 0 @@ -132,6 +133,7 @@ def fake_run_turn(cmd: list[str], **kwargs: object) -> TurnResult: patch.object(executor, "workspace_mounted", return_value=True), patch.object(executor, "run_turn", side_effect=fake_run_turn), patch.object(executor, "get_runner", return_value=runner), + patch.object(executor, "format_execution_notes", self.notes_formatter), patch("sys.argv", ["executor.py", PLAN, "antigravity-agent", "gemini-3.5-flash"]), contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr), @@ -326,6 +328,7 @@ def test_unmounted_workspace_is_an_error_and_exits_1(capsys: pytest.CaptureFixtu "Running: git diff --name-only --no-renames -z --", "Running: git ls-files --others --exclude-standard -z", "Running: git status --porcelain", + "Running: git diff --name-only --diff-filter=d HEAD -- *.md", "Running: git add holon-knowledge/ledger/pending/executions", "Running: git add -A", "Running: git status --short", @@ -351,6 +354,7 @@ def test_unmounted_workspace_is_an_error_and_exits_1(capsys: pytest.CaptureFixtu SALVAGE_STDOUT = [ *_BRANCH_START_STDOUT, "Running: git status --porcelain", + "Running: git diff --name-only --diff-filter=d HEAD -- *.md", "Running: git add -A -- . :(exclude)holon-knowledge/ledger/executions.jsonl " ":(exclude)holon-knowledge/ledger/pending :(exclude)executions/E-.md", "Running: git diff --cached --quiet", diff --git a/apps/sandbox-executor/tests/test_executor_committed_notes_format.py b/apps/sandbox-executor/tests/test_executor_committed_notes_format.py new file mode 100644 index 000000000..4eb97f6cc --- /dev/null +++ b/apps/sandbox-executor/tests/test_executor_committed_notes_format.py @@ -0,0 +1,229 @@ +from __future__ import annotations + +import logging +import os +import shutil +import subprocess +from pathlib import Path +from typing import Any + +import pytest +from sandbox_executor import execution_notes_format +from sandbox_executor.entrypoint import executor +from sandbox_executor.entrypoint.changed_markdown import committed_markdown_files, markdown_to_format +from sandbox_executor.execution_notes_format import format_execution_notes +from sandbox_executor.git import GitRepository + +from tests.test_execution_notes_format import ( + MISALIGNED_NOTES, + REPOSITORY_PRETTIER_NOTES, + RepositoryPrettierStandIn, + passes_repository_prettier_check, + unchanged_fences, +) +from tests.test_executor_characterisation import _git, _Run +from tests.test_plan_artifact_format import OVERLONG_STATEMENT, passes_ruff_format_check, python_fence + +COMMITTED_DOC = "docs/committed.md" +WORKTREE_DOC = "docs/worktree.md" +DELETED_DOC = "docs/deleted.md" + + +class _ConvergeRecorder: + def __init__(self) -> None: + self.files: list[str] = [] + + def __call__(self, md_files: list[str], repo_dir: str) -> None: + self.files.extend(md_files) + + +@pytest.fixture +def repository_prettier(monkeypatch: pytest.MonkeyPatch) -> RepositoryPrettierStandIn: + stand_in = RepositoryPrettierStandIn() + monkeypatch.setattr(execution_notes_format, "_repository_prettier", stand_in) + monkeypatch.setattr(execution_notes_format.shutil, "which", lambda name: f"/usr/bin/{name}") + return stand_in + + +@pytest.fixture +def pinned_prettier(monkeypatch: pytest.MonkeyPatch) -> _ConvergeRecorder: + recorder = _ConvergeRecorder() + monkeypatch.setattr(executor, "converge_prettier", recorder) + return recorder + + +def _write(workspace: str, rel: str, content: str) -> None: + os.makedirs(os.path.dirname(os.path.join(workspace, rel)), exist_ok=True) + with open(os.path.join(workspace, rel), "w") as f: + f.write(content) + + +def _agent_commits(workspace: str, message: str) -> None: + _git(workspace, "add", "-A") + _git(workspace, "-c", "user.name=agent", "-c", "user.email=agent@example.com", "commit", "-q", "-m", message) + + +def _code_change(workspace: str) -> None: + with open(os.path.join(workspace, "src/codebase.py"), "a") as f: + f.write("def added(): pass\n") + + +def _notes_rel(notes_path: str, workspace: str) -> str: + return os.path.relpath(notes_path, workspace) + + +def _committed_notes_turn(notes: str): + def turn(workspace: str, notes_path: str) -> None: + _code_change(workspace) + _write(workspace, _notes_rel(notes_path, workspace), notes) + _agent_commits(workspace, "step 1: implement and record notes") + + return turn + + +def _uncommitted_notes_turn(workspace: str, notes_path: str) -> None: + _code_change(workspace) + _write(workspace, _notes_rel(notes_path, workspace), MISALIGNED_NOTES) + + +def _committed_notes(run: _Run) -> str: + notes_rel = run.summary_row()["execution_notes"] + return _git(run.workspace, "show", f"{run.exec_branch()}:{notes_rel}") + + +def _run_with_real_notes_formatter(tmp_path: Path, turn: Any) -> _Run: + run = _Run(tmp_path) + run.notes_formatter = format_execution_notes + code, _out, _err = run.main(turn) + assert code is None + return run + + +@pytest.mark.usefixtures("pinned_prettier") +def test_notes_the_agent_already_committed_are_committed_prettier_clean( + tmp_path: Path, repository_prettier: RepositoryPrettierStandIn, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr(execution_notes_format, "format_plan_artifact", unchanged_fences) + run = _run_with_real_notes_formatter(tmp_path, _committed_notes_turn(MISALIGNED_NOTES)) + + committed = _committed_notes(run) + assert committed == REPOSITORY_PRETTIER_NOTES + assert passes_repository_prettier_check(committed) + assert run.summary_row()["status"] == "success" + assert {argv[3] for argv, _ in repository_prettier.calls} == {"--write", "--check"} + + +@pytest.mark.usefixtures("pinned_prettier") +def test_uncommitted_notes_are_committed_prettier_clean( + tmp_path: Path, repository_prettier: RepositoryPrettierStandIn, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr(execution_notes_format, "format_plan_artifact", unchanged_fences) + run = _run_with_real_notes_formatter(tmp_path, _uncommitted_notes_turn) + + assert passes_repository_prettier_check(_committed_notes(run)) + + +def _both_sources_turn(workspace: str, notes_path: str) -> None: + _code_change(workspace) + _write(workspace, COMMITTED_DOC, "# Committed\n") + _write(workspace, DELETED_DOC, "# Deleted\n") + _agent_commits(workspace, "step 1: add docs") + os.remove(os.path.join(workspace, DELETED_DOC)) + _agent_commits(workspace, "step 2: drop a doc") + _write(workspace, WORKTREE_DOC, "# Worktree\n") + _write(workspace, _notes_rel(notes_path, workspace), MISALIGNED_NOTES) + _agent_commits(workspace, "step 3: notes") + _write(workspace, WORKTREE_DOC, "# Worktree only\n") + + +def test_committed_and_worktree_markdown_go_to_the_pinned_pass_and_notes_to_the_notes_formatter( + tmp_path: Path, pinned_prettier: _ConvergeRecorder +) -> None: + run = _Run(tmp_path) + code, _out, _err = run.main(_both_sources_turn) + + assert code is None + assert sorted(pinned_prettier.files) == [COMMITTED_DOC, WORKTREE_DOC] + notes_rel = run.summary_row()["execution_notes"] + run.notes_formatter.assert_called_once_with(notes_rel, run.workspace) + + +def test_committed_markdown_skips_files_deleted_since_the_base(tmp_path: Path) -> None: + _git(str(tmp_path), "init", "-q", "-b", "main") + _write(str(tmp_path), "kept.md", "# Kept\n") + _write(str(tmp_path), "gone.md", "# Gone\n") + _agent_commits(str(tmp_path), "base") + base = _git(str(tmp_path), "rev-parse", "HEAD").strip() + os.remove(tmp_path / "gone.md") + _write(str(tmp_path), "kept.md", "# Kept, edited\n") + _write(str(tmp_path), "added.md", "# Added\n") + _write(str(tmp_path), "code.py", "X = 1\n") + _agent_commits(str(tmp_path), "agent") + _write(str(tmp_path), "kept.md", "# Kept, edited again\n") + repo = GitRepository(tmp_path) + + assert sorted(committed_markdown_files(repo, base)) == ["added.md", "kept.md"] + assert committed_markdown_files(repo, None) == [] + assert sorted(markdown_to_format(repo, base)) == ["added.md", "kept.md"] + + +def _ruff_available() -> bool: + return bool(shutil.which("ruff") or shutil.which("uv")) + + +def _passes_committed_ruff_check(run: _Run, committed: str, notes_rel: str) -> bool: + check_dir = os.path.join(run.root, "committed") + _write(check_dir, notes_rel, committed) + if shutil.which("ruff"): + return passes_ruff_format_check(notes_rel, Path(check_dir)) + check = subprocess.run( + ["uv", "run", "--frozen", "ruff", "format", "--preview", "--check", notes_rel], + cwd=check_dir, + capture_output=True, + text=True, + check=False, + ) + return check.returncode == 0 + + +def _prettier_leaves_notes_alone(mode: str, notes_rel: str, _repo_dir: str) -> subprocess.CompletedProcess[str]: + return subprocess.CompletedProcess(["npx", "--yes", "prettier", mode, notes_rel], 0, stdout="", stderr="") + + +@pytest.mark.skipif(not _ruff_available(), reason="neither ruff nor uv is on PATH") +@pytest.mark.usefixtures("pinned_prettier") +def test_notes_with_an_overlong_python_fence_are_committed_with_the_fence_formatted( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr(execution_notes_format, "_repository_prettier", _prettier_leaves_notes_alone) + notes = "# Execution Record: E-test\n\n## Sketch\n\n" + python_fence(OVERLONG_STATEMENT) + run = _run_with_real_notes_formatter(tmp_path, _committed_notes_turn(notes)) + + committed = _committed_notes(run) + assert committed != notes + assert _passes_committed_ruff_check(run, committed, run.summary_row()["execution_notes"]) + + +@pytest.mark.usefixtures("pinned_prettier") +@pytest.mark.parametrize("failure", ["npx_missing", "write_fails"]) +def test_a_failing_notes_formatter_warns_once_and_the_execution_still_commits( + tmp_path: Path, + repository_prettier: RepositoryPrettierStandIn, + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, + failure: str, +) -> None: + monkeypatch.setattr(execution_notes_format, "format_plan_artifact", unchanged_fences) + if failure == "npx_missing": + monkeypatch.setattr(execution_notes_format.shutil, "which", lambda _name: None) + else: + repository_prettier.write_returncode = 2 + with caplog.at_level(logging.WARNING, logger=execution_notes_format.logger.name): + run = _run_with_real_notes_formatter(tmp_path, _committed_notes_turn(MISALIGNED_NOTES)) + + notes_rel = run.summary_row()["execution_notes"] + warnings = [r.message for r in caplog.records if r.name == execution_notes_format.logger.name] + assert len(warnings) == 1 + assert notes_rel in warnings[0] + assert run.summary_row()["status"] == "success" + assert run.subjects()[0].startswith("execute: E- completed") diff --git a/apps/sandbox-executor/tests/test_review_loop_execution_notes.py b/apps/sandbox-executor/tests/test_review_loop_execution_notes.py new file mode 100644 index 000000000..8b55c0a01 --- /dev/null +++ b/apps/sandbox-executor/tests/test_review_loop_execution_notes.py @@ -0,0 +1,190 @@ +from __future__ import annotations + +import logging +import subprocess +from pathlib import Path +from typing import Any +from unittest.mock import patch + +import pytest +from sandbox_executor import execution_notes_format +from sandbox_executor.entrypoint import review_loop +from sandbox_executor.entrypoint.review_loop import CommitOptions, _commit_resolution +from sandbox_executor.entrypoint.review_markdown_gate import PRETTIER_COMMAND +from sandbox_executor.review_report import FindingDisposition + +from tests.flow.review.test_resolver_touch_set import _applied_disposition, _git, _paths_of_head_commit +from tests.test_execution_notes_format import ( + FOREIGN_NOTES, + MISALIGNED_NOTES, + OWN_NOTES, + RepositoryPrettierStandIn, + passes_repository_prettier_check, + unchanged_fences, +) + +FLOW_BRANCH = "I-1-x/P-1-y/E-1-z/_" +PLAN_BRANCH = "I-1-x/P-1-y/_" +LINT_COMMAND = ["uv", "run", "task", "lint"] +TEST_COMMAND = ["uv", "run", "task", "test"] +TOUCH_SET = ("allowed.py",) +ITERATION = 3 +CommitResult = tuple[tuple[FindingDisposition, ...], str, bool, bool, str | None] + + +def _init_flow_repo(tmp_path: Path, branch: str) -> tuple[Path, str]: + repo = tmp_path / "repo" + subprocess.run(["git", "init", "-b", branch, str(repo)], capture_output=True, check=True) + _git(repo, "config", "user.name", "Test") + _git(repo, "config", "user.email", "test@example.com") + (repo / "allowed.py").write_text("VALUE = 1\n", encoding="utf-8") + (repo / "outside.py").write_text("OTHER = 1\n", encoding="utf-8") + (repo / "executions").mkdir() + for notes_rel in (OWN_NOTES, FOREIGN_NOTES): + (repo / notes_rel).write_text(MISALIGNED_NOTES, encoding="utf-8") + _git(repo, "add", ".") + _git(repo, "commit", "-m", "flow with unformatted execution notes") + return repo, _git(repo, "rev-parse", "HEAD") + + +@pytest.fixture +def flow_repo(tmp_path: Path) -> tuple[Path, str]: + return _init_flow_repo(tmp_path, FLOW_BRANCH) + + +@pytest.fixture +def repository_prettier(monkeypatch: pytest.MonkeyPatch) -> RepositoryPrettierStandIn: + stand_in = RepositoryPrettierStandIn() + monkeypatch.setattr(execution_notes_format, "_repository_prettier", stand_in) + monkeypatch.setattr(execution_notes_format.shutil, "which", lambda name: f"/usr/bin/{name}") + monkeypatch.setattr(execution_notes_format, "format_plan_artifact", unchanged_fences) + return stand_in + + +class _VerificationStandIns: + def __init__(self, repo: Path) -> None: + self.repo = repo + self.real_run_cmd = review_loop.run_cmd + self.markdown_checked: list[str] = [] + + def __call__(self, cmd: list[str], *args: Any, **kwargs: Any) -> subprocess.CompletedProcess[str]: + if cmd in (LINT_COMMAND, TEST_COMMAND): + return subprocess.CompletedProcess(cmd, 0, stdout="", stderr="") + if cmd[: len(PRETTIER_COMMAND)] == PRETTIER_COMMAND: + return self._prettier_check(cmd) + return self.real_run_cmd(cmd, *args, **kwargs) + + def _prettier_check(self, cmd: list[str]) -> subprocess.CompletedProcess[str]: + files = cmd[cmd.index("--") + 1 :] + self.markdown_checked.extend(files) + unformatted = [f for f in files if not passes_repository_prettier_check((self.repo / f).read_text())] + stderr = "".join(f"[warn] {f}\n" for f in unformatted) + return subprocess.CompletedProcess(cmd, 1 if unformatted else 0, stdout="", stderr=stderr) + + +def _open_dispositions() -> tuple[FindingDisposition, ...]: + return tuple( + FindingDisposition( + id=d.id, severity=d.severity, path=d.path, line=d.line, summary=d.summary, disposition="open" + ) + for d in _applied_disposition() + ) + + +def _commit( + repo: Path, initial_head: str, branch: str = FLOW_BRANCH, **commit_options: Any +) -> tuple[CommitResult, _VerificationStandIns]: + verification = _VerificationStandIns(repo) + options = CommitOptions(pre_resolver_head=initial_head, touch_set=TOUCH_SET, **commit_options) + with ( + patch.object(review_loop, "check_lockfile", return_value=None), + patch.object(review_loop, "run_cmd", side_effect=verification), + ): + result = _commit_resolution(str(repo), branch, ITERATION, _open_dispositions(), options) + return result, verification + + +@pytest.mark.usefixtures("repository_prettier") +def test_unformatted_own_notes_alone_get_a_formatting_only_resolver_commit(flow_repo: tuple[Path, str]) -> None: + repo, initial_head = flow_repo + + (updated, head_sha, lint_ok, tests_ok, err), verification = _commit(repo, initial_head) + + assert err is None + assert (lint_ok, tests_ok) == (True, True) + assert head_sha == _git(repo, "rev-parse", "HEAD") != initial_head + assert _paths_of_head_commit(repo) == {OWN_NOTES} + assert f"ITER-{ITERATION}" in _git(repo, "log", "-1", "--format=%s") + assert passes_repository_prettier_check(_git(repo, "show", f"HEAD:{OWN_NOTES}") + "\n") + assert verification.markdown_checked == [OWN_NOTES] + assert all(d.commit_sha is None for d in updated) + + +@pytest.mark.usefixtures("repository_prettier") +def test_another_flows_notes_are_never_formatted_or_committed(flow_repo: tuple[Path, str]) -> None: + repo, initial_head = flow_repo + + (_, _, _, _, err), _ = _commit(repo, initial_head) + + assert err is None + assert (repo / FOREIGN_NOTES).read_text(encoding="utf-8") == MISALIGNED_NOTES + assert FOREIGN_NOTES not in _paths_of_head_commit(repo) + assert _git(repo, "status", "--porcelain") == "" + + +@pytest.mark.usefixtures("repository_prettier") +def test_out_of_set_code_next_to_an_own_notes_change_is_still_refused(flow_repo: tuple[Path, str]) -> None: + repo, initial_head = flow_repo + (repo / "outside.py").write_text("OTHER = 2\n", encoding="utf-8") + + with patch.object(review_loop, "_verify_before_push") as verify_mock: + (_, head_sha, lint_ok, tests_ok, err), _ = _commit(repo, initial_head) + + assert err is not None + assert err.startswith("touch_set_violation") + assert "outside.py" in err + assert OWN_NOTES not in err + verify_mock.assert_not_called() + assert (lint_ok, tests_ok) == (False, False) + assert head_sha == _git(repo, "rev-parse", "HEAD") == initial_head + + +def test_plan_branch_formats_no_notes_and_returns_early( + tmp_path: Path, repository_prettier: RepositoryPrettierStandIn +) -> None: + repo, initial_head = _init_flow_repo(tmp_path, PLAN_BRANCH) + + (_, head_sha, _, _, err), _ = _commit(repo, initial_head, branch=PLAN_BRANCH) + + assert err is None + assert repository_prettier.calls == [] + assert head_sha == _git(repo, "rev-parse", "HEAD") == initial_head + assert (repo / OWN_NOTES).read_text(encoding="utf-8") == MISALIGNED_NOTES + + +def test_dry_run_formats_nothing(flow_repo: tuple[Path, str], repository_prettier: RepositoryPrettierStandIn) -> None: + repo, initial_head = flow_repo + + (_, head_sha, _, _, err), _ = _commit(repo, initial_head, dry_run=True) + + assert err is None + assert repository_prettier.calls == [] + assert head_sha == initial_head + assert (repo / OWN_NOTES).read_text(encoding="utf-8") == MISALIGNED_NOTES + + +@pytest.mark.usefixtures("repository_prettier") +def test_missing_npx_warns_once_and_is_not_a_halt( + flow_repo: tuple[Path, str], monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + repo, initial_head = flow_repo + monkeypatch.setattr(execution_notes_format.shutil, "which", lambda _name: None) + + with caplog.at_level(logging.WARNING, logger=execution_notes_format.logger.name): + (_, head_sha, _, _, err), _ = _commit(repo, initial_head) + + assert err is None + assert head_sha == _git(repo, "rev-parse", "HEAD") == initial_head + warnings = [r.getMessage() for r in caplog.records if r.name == execution_notes_format.logger.name] + assert len(warnings) == 1 + assert OWN_NOTES in warnings[0] diff --git a/docs/review_consensus.md b/docs/review_consensus.md index f2021e611..83d181f02 100644 --- a/docs/review_consensus.md +++ b/docs/review_consensus.md @@ -331,3 +331,8 @@ still fails is named in the halt message (`Resolver pre-push markdown formatting Markdown starts no Prettier process, and unrelated Markdown files are never touched. The review-loop image bakes in Prettier; a missing `npx` is a failure that names it, never a silent skip. `lint-json`, `lint-yaml` and `lint-shell` need tools the image lacks and stay CI-only, which `tests/test_resolver_lint_parity.py` records. + +Before deciding whether to commit, the resolver formats the flow's own execution notes (`executions/E-.md`, derived +from the execution branch name; no other file under `executions/` is touched) with ruff for python fences and then the +repository Prettier. When that is the only change it still commits it, after the same verification, with the iteration +id in place of the finding list. A missing or failing formatter logs one warning naming the file and is never a halt. diff --git a/executions/E-1796129676-CLA-CO5.5.md b/executions/E-1796129676-CLA-CO5.5.md new file mode 100644 index 000000000..1d60a4702 --- /dev/null +++ b/executions/E-1796129676-CLA-CO5.5.md @@ -0,0 +1,111 @@ +# Execution Record: E-1796129676-CLA-CO5.5 + +## Summary + +Implements plan `P-1796129440-CLA-CO5.5` for intent `I-1796129417-exec-notes-format-before-commit`: Stage 3 formats +committed and working-tree Markdown plus the flow's own execution notes before the execution commit, and the Stage 4 +resolver formats and commits the flow's own execution notes. + +## Actual Metrics + +| metric | value | +| --------------------- | ----- | +| success_actual | 1.0 | +| entropy_actual | 7.5 | +| impact_actual | 80.0 | +| cost_actual | 10.0 | +| learning_value_actual | 3.0 | + +## Steps Executed + +### Step 1: Baseline + +- In-scope baseline (`test_executor_outcome.py`, `test_executor_characterisation.py`, `test_executor_run.py`, + `test_executor_package.py`, `test_plan_artifact_format.py`, `test_review_loop_plan_artifacts.py`, + `flow/review/test_resolver_touch_set.py`, `test_review_markdown_gate.py`, `test_review_loop.py`, + `test_calibration_commit.py`, `test_ledger_append_only.py`): 349 passed in 14.55s. +- Line counts: `review_loop.py` 840, `outcome.py` 277 (A10 said 271), `changed_markdown.py` 23, + `executor/__init__.py` 130. + +### Step 2: `execution_notes_format.py` + +- Added `apps/sandbox-executor/src/sandbox_executor/execution_notes_format.py` (126 lines): own-notes derivation from + the execution branch (`executions/E-.md`, `None` for plan, calibration and malformed branches), python-fence + formatting followed by the repository Prettier (`npx --yes prettier --write` then `--check`, up to three passes), one + warning on a missing or failing Prettier, and `resolver_stage_pathspec`. +- Added `tests/test_execution_notes_format.py` (19 tests, all pass). The stand-in replays verbatim repository-Prettier + output captured once with `npx --yes prettier --write` on the misaligned fixture. + +### Step 3: Stage 3 formats committed Markdown and the own notes + +- `changed_markdown.py`: `committed_markdown_files` (`git diff --name-only --diff-filter=d HEAD -- *.md`) and + `markdown_to_format` (order-preserving union with the working-tree list). +- `executor/__init__.py`: re-exports `committed_markdown_files`, `markdown_to_format` and `format_execution_notes`. +- `outcome.py`: `_converge_markdown` split into `_markdown_to_converge` (union minus the own notes, pinned pass), + `_format_own_notes` (repository Prettier via `format_execution_notes`) and `_record_markdown_formatting`. A + pinned-pass failure no longer skips the notes. The plan's "minus any path that no longer exists" filter was dropped: + it broke `test_executor_run.py` and `test_ledger_append_only.py` (which must stay unchanged) and `converge_prettier` + already skips missing files; deleted committed files are excluded by `--diff-filter=d`. A second `except Exception` + around the notes step was dropped because `test_broad_except_ratchet.py` caps broad catches; `format_execution_notes` + never raises for a formatter failure. +- `test_executor_characterisation.py`: only the two pinned tests changed (one added + `git diff --name-only --diff-filter=d HEAD -- *.md` line in `SUCCESS_STDOUT` and `SALVAGE_STDOUT`); the `_Run` + harness gets a swappable `notes_formatter` (a `MagicMock` returning `False`) so no `npx` starts there. +- Observation: tests in `test_executor_run.py`, `test_executor_run_salvage.py` and + `test_execution_commit_excludes_scratch.py` write real notes; before this change the pinned pass already ran real + `npx prettier@3.8.4` on those uncommitted notes, now the repository Prettier runs instead, so hermeticity is + unchanged. +- New `tests/test_executor_committed_notes_format.py` (7 tests): agent-committed notes, uncommitted notes, both Markdown + sources with a committed-then-deleted file, `committed_markdown_files` deleted-file filter, python fence checked with + the real ruff on the committed blob, and formatter failures (missing `npx`, failing `--write`) that warn once and + still commit with status `success`. +- Stage 3 test set: 239 passed in 15.29s. `outcome.py` 292 lines, `changed_markdown.py` 36. + +### Step 4: Stage 4 resolver formats and commits the own notes + +- `review_loop.py` (840 to 844 lines, budget 913): `_commit_resolution` calls `format_own_execution_notes` after + `_restore_budget_config` and before the `git status` call (skipped on `dry_run`); the early return now also lets a + formatted own-notes change through; staging uses `resolver_stage_pathspec`, so with no applied finding only + `executions/E-.md` is staged and the message falls back to `ITER-`. +- New `tests/test_review_loop_execution_notes.py` (6 tests): formatting-only commit holding just the own notes with a + passing stand-in `--check` on the committed blob, foreign notes untouched, out-of-set code still refused, plan branch + and `dry_run` format nothing, missing `npx` warns once without a halt. 4 of the 6 fail on the pre-change + `review_loop.py`. +- Resolver test set (`test_review_loop_execution_notes.py`, `test_review_loop_plan_artifacts.py`, + `flow/review/test_resolver_touch_set.py`, `test_review_loop.py`, `test_review_markdown_gate.py`, + `test_review_resolver_failure.py`, `test_resolver_lint_parity.py`, `test_review_loop_git_identity.py`): 201 passed in + 7.18s, with no edits to the existing files. + +### Step 5: Documentation + +- `docs/review_consensus.md`, section `## Resolver pre-push verification`: one paragraph on the own-notes formatting and + the formatting-only commit. `npx --yes prettier --check` passes on it. + +### Step 6: Verification + +- `uv run task lint`: exit 0 (ruff, complexity limits, module budgets 440 modules, self-explaining check on 14 changed + files). No `# noqa` added. +- Module sizes: `review_loop.py` 844 (budget 913), `outcome.py` 292, `execution_notes_format.py` 127, + `changed_markdown.py` 36, `executor/__init__.py` 133. +- `git diff --name-only 7a38d6755 HEAD`: only in-scope files plus this notes file; `uv.lock` and + `holon-config/hygiene/module_budgets.json` untouched. `plan_artifact_format.py`, `test_executor_outcome.py`, + `test_executor_package.py`, `test_plan_artifact_format.py`, `test_review_loop_plan_artifacts.py` and + `flow/review/test_resolver_touch_set.py` needed no change. +- A9 overlap re-check not repeated: no open pull request list is provided in this container; it was checked at launch. + +## Tests Run + +| run | result | pytest time | +| -------------------------------------------------------------- | --------------------------- | ----------- | +| Step 1 baseline, 11 in-scope files | 349 passed | 14.55s | +| `uv run pytest tests/test_execution_notes_format.py` | 19 passed | 0.27s | +| Probe run of `uv run task test` (temporary call log, reverted) | 11222 passed, 1 failed | 95.59s | +| Step 3 Stage 3 set (9 files) | 239 passed | 15.29s | +| Step 4 resolver set (8 files) | 201 passed | 7.18s | +| Step 4 new resolver tests against the pre-change `review_loop` | 4 failed, 2 passed (expect) | 0.51s | +| `uv run task lint` | exit 0 | n/a | +| `npx --yes prettier --check` on the doc and this notes file | pass | n/a | +| `uv run task test` (final, once) | 11236 passed, 8 skipped | 87.03s | + +The probe run's one failure was `test_broad_except_ratchet.py` (an extra `except Exception` in `outcome.py`), fixed by +removing that catch before the final run. No timing measurement was required by the intent, so each suite ran once. diff --git a/holon-knowledge/ledger/pending/executions/I-1796129417-exec-notes-format-before-commit.jsonl b/holon-knowledge/ledger/pending/executions/I-1796129417-exec-notes-format-before-commit.jsonl new file mode 100644 index 000000000..f8c49dc28 --- /dev/null +++ b/holon-knowledge/ledger/pending/executions/I-1796129417-exec-notes-format-before-commit.jsonl @@ -0,0 +1,28 @@ +{"action_id": "ACT-1796130298-f6be5b47", "execution_id": "E-1796129676-CLA-CO5.5", "action": "Executed agent claude-agent with model claude-opus-5-5", "category": "code", "target": "claude-agent:claude-opus-5-5", "outcome": "success", "entry_type": "action", "parent_action_id": null, "event_type": "command_execution", "labels": ["agent", "claude-agent", "execution"], "error_context": null, "mistake_category": null, "action_origin": "initial_implementation", "review_severity": null, "review_iteration": null, "review_finding_ids": null, "review_disposition": null, "rejection_reason": null, "introduced_by_action_id": null, "created_at": "2026-12-01T13:04:58.774608Z"} +{"entry_type": "summary", "execution_id": "E-1796129676-CLA-CO5.5", "plan_branch": "I-1796129417-exec-notes-format-before-commit/P-1796129440-CLA-CO5.5/_", "agent": "claude-agent", "agent_version": "2.1.302", "model": "claude-opus-5-5", "status": "success", "summary": "Plan executed successfully", "created_at": "2026-12-01T12:54:37.735802Z", "agent_output_truncated": false, "agent_output_bytes": 384, "ledger_revision": 1, "execution_notes": "executions/E-1796129676-CLA-CO5.5.md", "execution_notes_valid": true, "elapsed_seconds": 748.4, "budget_seconds": 604721.0, "test_pass_rate": 1.0, "tests_passed": 11236, "tests_failed": 0, "tests_errored": 0, "test_exit_code": 0, "test_source": "stage_3"} +{"action_id": "ACT-1796130426-f2eddff6", "execution_id": "E-1796129676-CLA-CO5.5", "action": "Committed execution changes: execute: E-1796129676-CLA-CO5.5 completed for plan I-1796129417-exec-notes-format-before-commit/P-1796129440-CLA-CO5.5/_", "category": "code", "target": "HEAD", "outcome": "success", "entry_type": "action", "parent_action_id": null, "event_type": "git_mutation", "labels": ["commit", "git"], "error_context": null, "mistake_category": null, "action_origin": "initial_implementation", "review_severity": null, "review_iteration": null, "review_finding_ids": null, "review_disposition": null, "rejection_reason": null, "introduced_by_action_id": null, "created_at": "2026-12-01T13:07:06.133806Z"} +{"action_id": "ACT-REV-1796130802-af9f2ead", "execution_id": "REV-ITR-1-1796130802", "action": "Review Loop iteration 1 reviewer 1 completed", "category": "code", "target": "I-1796129417-exec-notes-format-before-commit/P-1796129440-CLA-CO5.5/E-1796129676-CLA-CO5.5/_", "outcome": "failure", "entry_type": "action", "action_origin": "pr_review", "review_severity": "nit", "review_iteration": 1, "review_finding_ids": ["FIND-R1-001-01"], "labels": ["review", "reviewer", "iteration-1"], "error_context": null, "review_reviewer_index": 1, "review_agent": "claude-agent", "review_model": "claude-opus-5-5", "review_status": "COMPLETED", "review_verdict": "CHANGES_REQUESTED", "review_counts": {"critical": 0, "important": 0, "nit": 1}, "created_at": "2026-12-01T13:13:22.977767Z"} +{"action_id": "ACT-FIND-1796130802-f8fb4eb1", "execution_id": "REV-FIND-1-1796130802", "action": "Review Loop iteration 1 finding detected: FIND-R1-001-01", "category": "code", "target": "I-1796129417-exec-notes-format-before-commit/P-1796129440-CLA-CO5.5/E-1796129676-CLA-CO5.5/_", "outcome": "failure", "entry_type": "action", "action_origin": "pr_review", "review_severity": "nit", "review_iteration": 1, "review_finding_ids": ["FIND-R1-001-01"], "labels": ["review", "finding", "iteration-1"], "error_context": "The Prettier convergence helpers (_repository_prettier, _summarise, _converge, _prettier_failure) and _is_markdown_file_inside are near-verbatim copies of private helpers in calibration_format.py and plan_artifact_format.py. Move them into shared public helpers so the two copies cannot drift.", "review_reviewer_index": 1, "review_file": "apps/sandbox-executor/src/sandbox_executor/execution_notes_format.py", "review_line": 42, "created_at": "2026-12-01T13:13:22.984717Z"} +{"action_id": "ACT-REV-1796130802-f20830da", "execution_id": "REV-ITR-1-1796130802", "action": "Review Loop iteration 1 reviewer 2 completed", "category": "code", "target": "I-1796129417-exec-notes-format-before-commit/P-1796129440-CLA-CO5.5/E-1796129676-CLA-CO5.5/_", "outcome": "failure", "entry_type": "action", "action_origin": "pr_review", "review_severity": "nit", "review_iteration": 1, "review_finding_ids": ["FIND-R2-001-01"], "labels": ["review", "reviewer", "iteration-1"], "error_context": null, "review_reviewer_index": 2, "review_agent": "claude-agent", "review_model": "claude-opus-5-5", "review_status": "COMPLETED", "review_verdict": "CHANGES_REQUESTED", "review_counts": {"critical": 0, "important": 0, "nit": 1}, "created_at": "2026-12-01T13:13:22.988561Z"} +{"action_id": "ACT-FIND-1796130802-26cd1e3e", "execution_id": "REV-FIND-1-1796130802", "action": "Review Loop iteration 1 finding detected: FIND-R2-001-01", "category": "code", "target": "I-1796129417-exec-notes-format-before-commit/P-1796129440-CLA-CO5.5/E-1796129676-CLA-CO5.5/_", "outcome": "failure", "entry_type": "action", "action_origin": "pr_review", "review_severity": "nit", "review_iteration": 1, "review_finding_ids": ["FIND-R2-001-01"], "labels": ["review", "finding", "iteration-1"], "error_context": "_is_markdown_file_inside and _notes_bytes copy plan_artifact_format's _is_markdown_file_inside and _artifact_bytes; import shared helpers instead of keeping two copies of the path-safety rules.", "review_reviewer_index": 2, "review_file": "apps/sandbox-executor/src/sandbox_executor/execution_notes_format.py", "review_line": 86, "created_at": "2026-12-01T13:13:22.991753Z"} +{"action_id": "ACT-REV-1796130802-7b19d7bb", "execution_id": "REV-ITR-1-1796130802", "action": "Review Loop iteration 1 reviewer 3 completed", "category": "code", "target": "I-1796129417-exec-notes-format-before-commit/P-1796129440-CLA-CO5.5/E-1796129676-CLA-CO5.5/_", "outcome": "success", "entry_type": "action", "action_origin": "pr_review", "review_severity": null, "review_iteration": 1, "review_finding_ids": null, "labels": ["review", "reviewer", "iteration-1"], "error_context": null, "review_reviewer_index": 3, "review_agent": "claude-agent", "review_model": "claude-opus-5-5", "review_status": "COMPLETED", "review_verdict": "APPROVED", "review_counts": {"critical": 0, "important": 0, "nit": 0}, "created_at": "2026-12-01T13:13:22.994994Z"} +{"action_id": "ACT-REV-1796130808-1e8dee8a", "execution_id": "REV-ITR-1-1796130808", "action": "Review Loop iteration 1 evaluation for I-1796129417-exec-notes-format-before-commit/P-1796129440-CLA-CO5.5/E-1796129676-CLA-CO5.5/_", "category": "code", "target": "I-1796129417-exec-notes-format-before-commit/P-1796129440-CLA-CO5.5/E-1796129676-CLA-CO5.5/_", "outcome": "failure", "entry_type": "action", "action_origin": "pr_review", "review_severity": "nit", "review_iteration": 1, "review_finding_ids": ["FIND-R1-001-01", "FIND-R2-001-01"], "labels": ["review", "review-loop", "iteration-1"], "error_context": "Findings detected: ['FIND-R1-001-01', 'FIND-R2-001-01']", "created_at": "2026-12-01T13:13:28.020857Z"} +{"action_id": "ACT-REV-1796130808-0c1ac983", "execution_id": "REV-ITR-1-1796130808", "action": "Review Loop iteration 1 reviewer 1 completed", "category": "code", "target": "I-1796129417-exec-notes-format-before-commit/P-1796129440-CLA-CO5.5/E-1796129676-CLA-CO5.5/_", "outcome": "failure", "entry_type": "action", "action_origin": "pr_review", "review_severity": "nit", "review_iteration": 1, "review_finding_ids": ["FIND-R1-001-01"], "labels": ["review", "reviewer", "iteration-1"], "error_context": null, "review_reviewer_index": 1, "review_agent": "claude-agent", "review_model": "claude-opus-5-5", "review_status": "COMPLETED", "review_verdict": "CHANGES_REQUESTED", "review_counts": {"critical": 0, "important": 0, "nit": 1}, "created_at": "2026-12-01T13:13:28.022451Z"} +{"action_id": "ACT-FIND-1796130808-a4214019", "execution_id": "REV-FIND-1-1796130808", "action": "Review Loop iteration 1 finding detected: FIND-R1-001-01", "category": "code", "target": "I-1796129417-exec-notes-format-before-commit/P-1796129440-CLA-CO5.5/E-1796129676-CLA-CO5.5/_", "outcome": "failure", "entry_type": "action", "action_origin": "pr_review", "review_severity": "nit", "review_iteration": 1, "review_finding_ids": ["FIND-R1-001-01"], "labels": ["review", "finding", "iteration-1"], "error_context": "The Prettier convergence helpers (_repository_prettier, _summarise, _converge, _prettier_failure) and _is_markdown_file_inside are near-verbatim copies of private helpers in calibration_format.py and plan_artifact_format.py. Move them into shared public helpers so the two copies cannot drift.", "review_reviewer_index": 1, "review_file": "apps/sandbox-executor/src/sandbox_executor/execution_notes_format.py", "review_line": 42, "created_at": "2026-12-01T13:13:28.023892Z"} +{"action_id": "ACT-REV-1796130808-75dcaa1c", "execution_id": "REV-ITR-1-1796130808", "action": "Review Loop iteration 1 reviewer 2 completed", "category": "code", "target": "I-1796129417-exec-notes-format-before-commit/P-1796129440-CLA-CO5.5/E-1796129676-CLA-CO5.5/_", "outcome": "failure", "entry_type": "action", "action_origin": "pr_review", "review_severity": "nit", "review_iteration": 1, "review_finding_ids": ["FIND-R2-001-01"], "labels": ["review", "reviewer", "iteration-1"], "error_context": null, "review_reviewer_index": 2, "review_agent": "claude-agent", "review_model": "claude-opus-5-5", "review_status": "COMPLETED", "review_verdict": "CHANGES_REQUESTED", "review_counts": {"critical": 0, "important": 0, "nit": 1}, "created_at": "2026-12-01T13:13:28.025437Z"} +{"action_id": "ACT-FIND-1796130808-8242289f", "execution_id": "REV-FIND-1-1796130808", "action": "Review Loop iteration 1 finding detected: FIND-R2-001-01", "category": "code", "target": "I-1796129417-exec-notes-format-before-commit/P-1796129440-CLA-CO5.5/E-1796129676-CLA-CO5.5/_", "outcome": "failure", "entry_type": "action", "action_origin": "pr_review", "review_severity": "nit", "review_iteration": 1, "review_finding_ids": ["FIND-R2-001-01"], "labels": ["review", "finding", "iteration-1"], "error_context": "_is_markdown_file_inside and _notes_bytes copy plan_artifact_format's _is_markdown_file_inside and _artifact_bytes; import shared helpers instead of keeping two copies of the path-safety rules.", "review_reviewer_index": 2, "review_file": "apps/sandbox-executor/src/sandbox_executor/execution_notes_format.py", "review_line": 86, "created_at": "2026-12-01T13:13:28.026743Z"} +{"action_id": "ACT-REV-1796130808-8fc69258", "execution_id": "REV-ITR-1-1796130808", "action": "Review Loop iteration 1 reviewer 3 completed", "category": "code", "target": "I-1796129417-exec-notes-format-before-commit/P-1796129440-CLA-CO5.5/E-1796129676-CLA-CO5.5/_", "outcome": "success", "entry_type": "action", "action_origin": "pr_review", "review_severity": null, "review_iteration": 1, "review_finding_ids": null, "labels": ["review", "reviewer", "iteration-1"], "error_context": null, "review_reviewer_index": 3, "review_agent": "claude-agent", "review_model": "claude-opus-5-5", "review_status": "COMPLETED", "review_verdict": "APPROVED", "review_counts": {"critical": 0, "important": 0, "nit": 0}, "created_at": "2026-12-01T13:13:28.028028Z"} +{"action_id": "ACT-RES-1796132401-dfa7a588", "execution_id": "REV-RES-1-1796132401", "action": "Review Loop iteration 1 finding R1-F1 adjudicated: rejected", "category": "code", "target": "I-1796129417-exec-notes-format-before-commit/P-1796129440-CLA-CO5.5/E-1796129676-CLA-CO5.5/_", "outcome": "success", "entry_type": "action", "action_origin": "pr_review", "review_severity": "nit", "review_iteration": 1, "review_finding_ids": ["R1-F1"], "review_disposition": "rejected", "rejection_reason": "out of scope", "introduced_by_action_id": "ACT-FIND-1796130808-a4214019", "labels": ["review", "resolver", "iteration-1"], "error_context": "out of scope", "created_at": "2026-12-01T13:40:01.534236Z"} +{"action_id": "ACT-RES-1796132401-49dac51e", "execution_id": "REV-RES-1-1796132401", "action": "Review Loop iteration 1 finding R2-F1 adjudicated: applied", "category": "code", "target": "I-1796129417-exec-notes-format-before-commit/P-1796129440-CLA-CO5.5/E-1796129676-CLA-CO5.5/_", "outcome": "success", "entry_type": "action", "action_origin": "pr_review", "review_severity": "nit", "review_iteration": 1, "review_finding_ids": ["R2-F1"], "review_disposition": "applied", "rejection_reason": null, "introduced_by_action_id": "ACT-FIND-1796130808-8242289f", "labels": ["review", "resolver", "iteration-1"], "error_context": null, "created_at": "2026-12-01T13:40:01.535476Z"} +{"action_id": "ACT-REV-1796133519-78b3117a", "execution_id": "REV-ITR-2-1796133519", "action": "Review Loop iteration 2 reviewer 1 completed", "category": "code", "target": "I-1796129417-exec-notes-format-before-commit/P-1796129440-CLA-CO5.5/E-1796129676-CLA-CO5.5/_", "outcome": "success", "entry_type": "action", "action_origin": "pr_review", "review_severity": null, "review_iteration": 2, "review_finding_ids": null, "labels": ["review", "reviewer", "iteration-2"], "error_context": null, "review_reviewer_index": 1, "review_agent": "claude-agent", "review_model": "claude-opus-5-5", "review_status": "COMPLETED", "review_verdict": "APPROVED", "review_counts": {"critical": 0, "important": 0, "nit": 0}, "created_at": "2026-12-01T13:58:39.958977Z"} +{"action_id": "ACT-REV-1796133519-68d2622d", "execution_id": "REV-ITR-2-1796133519", "action": "Review Loop iteration 2 reviewer 2 completed", "category": "code", "target": "I-1796129417-exec-notes-format-before-commit/P-1796129440-CLA-CO5.5/E-1796129676-CLA-CO5.5/_", "outcome": "success", "entry_type": "action", "action_origin": "pr_review", "review_severity": null, "review_iteration": 2, "review_finding_ids": null, "labels": ["review", "reviewer", "iteration-2"], "error_context": null, "review_reviewer_index": 2, "review_agent": "claude-agent", "review_model": "claude-opus-5-5", "review_status": "COMPLETED", "review_verdict": "APPROVED", "review_counts": {"critical": 0, "important": 0, "nit": 0}, "created_at": "2026-12-01T13:58:39.962063Z"} +{"action_id": "ACT-REV-1796133519-4a4be076", "execution_id": "REV-ITR-2-1796133519", "action": "Review Loop iteration 2 reviewer 3 completed", "category": "code", "target": "I-1796129417-exec-notes-format-before-commit/P-1796129440-CLA-CO5.5/E-1796129676-CLA-CO5.5/_", "outcome": "success", "entry_type": "action", "action_origin": "pr_review", "review_severity": null, "review_iteration": 2, "review_finding_ids": null, "labels": ["review", "reviewer", "iteration-2"], "error_context": null, "review_reviewer_index": 3, "review_agent": "claude-agent", "review_model": "claude-opus-5-5", "review_status": "COMPLETED", "review_verdict": "APPROVED", "review_counts": {"critical": 0, "important": 0, "nit": 0}, "created_at": "2026-12-01T13:58:39.964476Z"} +{"action_id": "ACT-REV-1796133523-6229813a", "execution_id": "REV-ITR-2-1796133523", "action": "Review Loop iteration 2 evaluation for I-1796129417-exec-notes-format-before-commit/P-1796129440-CLA-CO5.5/E-1796129676-CLA-CO5.5/_", "category": "code", "target": "I-1796129417-exec-notes-format-before-commit/P-1796129440-CLA-CO5.5/E-1796129676-CLA-CO5.5/_", "outcome": "success", "entry_type": "action", "action_origin": "pr_review", "review_severity": null, "review_iteration": 2, "review_finding_ids": null, "labels": ["review", "review-loop", "iteration-2"], "error_context": null, "created_at": "2026-12-01T13:58:43.616162Z"} +{"action_id": "ACT-REV-1796133523-306a4ca8", "execution_id": "REV-ITR-2-1796133523", "action": "Review Loop iteration 2 reviewer 1 completed", "category": "code", "target": "I-1796129417-exec-notes-format-before-commit/P-1796129440-CLA-CO5.5/E-1796129676-CLA-CO5.5/_", "outcome": "success", "entry_type": "action", "action_origin": "pr_review", "review_severity": null, "review_iteration": 2, "review_finding_ids": null, "labels": ["review", "reviewer", "iteration-2"], "error_context": null, "review_reviewer_index": 1, "review_agent": "claude-agent", "review_model": "claude-opus-5-5", "review_status": "COMPLETED", "review_verdict": "APPROVED", "review_counts": {"critical": 0, "important": 0, "nit": 0}, "created_at": "2026-12-01T13:58:43.617571Z"} +{"action_id": "ACT-REV-1796133523-18cc0847", "execution_id": "REV-ITR-2-1796133523", "action": "Review Loop iteration 2 reviewer 2 completed", "category": "code", "target": "I-1796129417-exec-notes-format-before-commit/P-1796129440-CLA-CO5.5/E-1796129676-CLA-CO5.5/_", "outcome": "success", "entry_type": "action", "action_origin": "pr_review", "review_severity": null, "review_iteration": 2, "review_finding_ids": null, "labels": ["review", "reviewer", "iteration-2"], "error_context": null, "review_reviewer_index": 2, "review_agent": "claude-agent", "review_model": "claude-opus-5-5", "review_status": "COMPLETED", "review_verdict": "APPROVED", "review_counts": {"critical": 0, "important": 0, "nit": 0}, "created_at": "2026-12-01T13:58:43.618672Z"} +{"action_id": "ACT-REV-1796133523-680817ad", "execution_id": "REV-ITR-2-1796133523", "action": "Review Loop iteration 2 reviewer 3 completed", "category": "code", "target": "I-1796129417-exec-notes-format-before-commit/P-1796129440-CLA-CO5.5/E-1796129676-CLA-CO5.5/_", "outcome": "success", "entry_type": "action", "action_origin": "pr_review", "review_severity": null, "review_iteration": 2, "review_finding_ids": null, "labels": ["review", "reviewer", "iteration-2"], "error_context": null, "review_reviewer_index": 3, "review_agent": "claude-agent", "review_model": "claude-opus-5-5", "review_status": "COMPLETED", "review_verdict": "APPROVED", "review_counts": {"critical": 0, "important": 0, "nit": 0}, "created_at": "2026-12-01T13:58:43.619785Z"} +{"action_id": "ACT-POST-1796133528-7cf718ab", "execution_id": "REV-POST-1796133528", "action": "Review consensus dual-posted to GitHub for I-1796129417-exec-notes-format-before-commit/P-1796129440-CLA-CO5.5/E-1796129676-CLA-CO5.5/_", "category": "code", "target": "I-1796129417-exec-notes-format-before-commit/P-1796129440-CLA-CO5.5/E-1796129676-CLA-CO5.5/_", "outcome": "success", "entry_type": "action", "action_origin": "pr_review", "review_iteration": 2, "labels": ["review", "github", "dual-post"], "created_at": "2026-12-01T13:58:48.085760Z"} +{"execution_id": "REV-1796133531-c4d41baa-claude-agent", "plan_branch": "I-1796129417-exec-notes-format-before-commit/P-1796129440-CLA-CO5.5/_", "execution_branch": "I-1796129417-exec-notes-format-before-commit/P-1796129440-CLA-CO5.5/E-1796129676-CLA-CO5.5/_", "agent": "claude-agent", "agent_version": "1.4.0", "model": "claude-opus-5-5", "status": "approved", "entry_type": "summary", "summary": "Review Loop reached consensus approval after 2 iteration(s); PR ready for maintainer merge; final verdicts: Reviewer 1 APPROVED (0/0/0); Reviewer 2 APPROVED (0/0/0); Reviewer 3 APPROVED (0/0/0)", "created_at": "2026-12-01T13:58:51.278Z", "total_iterations": 2, "max_iterations": 25, "ci_checks_summary": {"source": "github_cli", "total": 16, "passed": 16, "failed": 0, "pending": 0, "skipped": 0, "all_passed": true, "checks": [{"bucket": "pass", "event": "pull_request", "link": "https://github.com/Holon-Agentic-Coder/holon-agentic-coder/actions/runs/46658793951/job/142682424811", "name": "build (macos-latest)", "state": "SUCCESS", "workflow": "Run Make"}, {"bucket": "pass", "event": "pull_request", "link": "https://github.com/Holon-Agentic-Coder/holon-agentic-coder/actions/runs/46658793893/job/142682414382", "name": "unit (macos-latest, shard 1 of 2)", "state": "SUCCESS", "workflow": "Test - Unit"}, {"bucket": "pass", "event": "pull_request", "link": "https://github.com/Holon-Agentic-Coder/holon-agentic-coder/actions/runs/46658793893/job/142682414921", "name": "unit (macos-latest, shard 2 of 2)", "state": "SUCCESS", "workflow": "Test - Unit"}, {"bucket": "pass", "event": "", "link": "https://github.com/Holon-Agentic-Coder/holon-agentic-coder/runs/142682740547", "name": "CodeQL", "state": "SUCCESS", "workflow": ""}, {"bucket": "pass", "event": "pull_request", "link": "https://github.com/Holon-Agentic-Coder/holon-agentic-coder/actions/runs/46658794052/job/142682482666", "name": "self-doc-behavior", "state": "SUCCESS", "workflow": "Test - Self-Doc Behavior"}, {"bucket": "pass", "event": "pull_request", "link": "https://github.com/Holon-Agentic-Coder/holon-agentic-coder/actions/runs/46658793691/job/142682425584", "name": "ledger-invariants", "state": "SUCCESS", "workflow": "Test - Ledger Invariants"}, {"bucket": "pass", "event": "pull_request", "link": "https://github.com/Holon-Agentic-Coder/holon-agentic-coder/actions/runs/46658793730/job/142682425489", "name": "hygiene (ubuntu-latest)", "state": "SUCCESS", "workflow": "Test - Hygiene"}, {"bucket": "pass", "event": "pull_request", "link": "https://github.com/Holon-Agentic-Coder/holon-agentic-coder/actions/runs/46658793951/job/142682425360", "name": "build (ubuntu-latest)", "state": "SUCCESS", "workflow": "Run Make"}, {"bucket": "pass", "event": "pull_request", "link": "https://github.com/Holon-Agentic-Coder/holon-agentic-coder/actions/runs/46658794933/job/142682421657", "name": "integration (ubuntu-latest)", "state": "SUCCESS", "workflow": "Test - Integration"}, {"bucket": "pass", "event": "pull_request", "link": "https://github.com/Holon-Agentic-Coder/holon-agentic-coder/actions/runs/46658793669/job/142682415737", "name": "Workspace survival (ubuntu-latest)", "state": "SUCCESS", "workflow": "Test - Stress"}, {"bucket": "pass", "event": "pull_request", "link": "https://github.com/Holon-Agentic-Coder/holon-agentic-coder/actions/runs/46658795190/job/142682426249", "name": "build", "state": "SUCCESS", "workflow": "Docker Build"}, {"bucket": "pass", "event": "pull_request", "link": "https://github.com/Holon-Agentic-Coder/holon-agentic-coder/actions/runs/46658793893/job/142682414777", "name": "unit (ubuntu-latest)", "state": "SUCCESS", "workflow": "Test - Unit"}, {"bucket": "pass", "event": "pull_request", "link": "https://github.com/Holon-Agentic-Coder/holon-agentic-coder/actions/runs/46658794679/job/142682413089", "name": "commit-trailers", "state": "SUCCESS", "workflow": "Test - Commit Trailers"}, {"bucket": "pass", "event": "pull_request", "link": "https://github.com/Holon-Agentic-Coder/holon-agentic-coder/actions/runs/46658793931/job/142682378172", "name": "scan", "state": "SUCCESS", "workflow": "Test - No Harness References"}, {"bucket": "pass", "event": "dynamic", "link": "https://github.com/Holon-Agentic-Coder/holon-agentic-coder/actions/runs/46658779727/job/142682341542", "name": "Analyze (python)", "state": "SUCCESS", "workflow": "CodeQL"}, {"bucket": "pass", "event": "dynamic", "link": "https://github.com/Holon-Agentic-Coder/holon-agentic-coder/actions/runs/46658779727/job/142682342052", "name": "Analyze (actions)", "state": "SUCCESS", "workflow": "CodeQL"}], "test_source": "ci_head", "test_head_sha": "e577b68d3af5141555fd9cacac4782db83bee934"}, "trailers": {"action_origin": "pr_review", "review_severity": null, "review_iteration": 2, "review_finding_ids": ["none"], "review_disposition": null, "rejection_reason": null, "introduced_by_action_id": null, "consulted_knowledge_ids": null}, "review_post_withheld": null} +{"execution_id": "REV-1796133531-c4d41baa-claude-agent", "action": "Review Loop executed for I-1796129417-exec-notes-format-before-commit/P-1796129440-CLA-CO5.5/E-1796129676-CLA-CO5.5/_", "category": "test", "target": "I-1796129417-exec-notes-format-before-commit/P-1796129440-CLA-CO5.5/E-1796129676-CLA-CO5.5/_", "verdict": "success", "outcome": "success", "entry_type": "action", "context_fingerprint": "6a1a51c71077cccc", "labels": ["review", "review-loop", "claude-agent"], "error_context": null, "action_id": "ACT-1796133531-3649b35f", "created_at": "2026-12-01T13:58:51.279114Z"} +{"action_id": "ACT-CAL-1796133560-da37e270", "execution_id": "CAL-P-1796129440-CLA-CO5.5-1796133560-70249692", "action": "Calibration report generated for plan P-1796129440-CLA-CO5.5", "category": "doc", "target": "I-1796129417-exec-notes-format-before-commit/P-1796129440-CLA-CO5.5/E-1796129676-CLA-CO5.5/calibrated", "outcome": "success", "entry_type": "action", "action_origin": "calibration", "labels": ["calibration", "stage-5", "P-1796129440-CLA-CO5.5"], "error_context": null, "plan_branch": "I-1796129417-exec-notes-format-before-commit/P-1796129440-CLA-CO5.5/_", "execution_branch": "I-1796129417-exec-notes-format-before-commit/P-1796129440-CLA-CO5.5/E-1796129676-CLA-CO5.5/_", "evaluated_commit_sha": "fa6c03aaa4950d16be4fb82daf3149f8b8863ecc", "predicted_metrics": {"p_success": 0.8, "entropy": 9.0, "impact": 80.0, "cost": 14.0, "learning_value": 4.0, "ev": 49.3}, "actual_metrics": {"p_success": 1.0, "entropy": 2.0, "impact": 80.0, "cost": 11.9, "learning_value": 4.0, "ev": 69.5, "duration_seconds": null, "tokens": null, "exit_code": 0, "test_pass_rate": 1.0, "files_changed": 11, "insertions": 844, "deletions": 26, "ev_clean": 69.5, "ev_with_bugs": 69.5, "p_success_clean": 1.0, "p_success_with_bugs": 1.0, "impact_clean": 80.0, "impact_with_bugs": 80.0, "bug_ev_drag": 0.0}, "calibration_deltas": {"p_success_error": 0.2, "entropy_error": 7.0, "impact_error": 0.0, "cost_error": 2.1, "learning_value_error": 0.0, "ev_error": 20.2, "delta_ev": 20.2, "delta_ev_clean": 20.2, "delta_ev_with_bugs": 20.2, "bug_ev_drag": 0.0}, "calibration_report_path": "plans/I-1796129417-exec-notes-format-before-commit/P-1796129440-CLA-CO5.5_calibration.md", "created_at": "2026-12-01T13:59:20.075776Z", "touch_set_accuracy": {"precision": 0.6875, "recall": 1.0, "unpredicted_paths": [], "unused_entries": ["apps/sandbox-executor/tests/test_executor_outcome.py", "apps/sandbox-executor/tests/test_executor_package.py", "apps/sandbox-executor/tests/test_plan_artifact_format.py", "apps/sandbox-executor/tests/test_review_loop_plan_artifacts.py", "apps/sandbox-executor/tests/flow/review/test_resolver_touch_set.py"]}, "calibration_agent": "claude-agent", "calibration_model": "claude-opus-5-5", "plan_agent": "claude-agent", "plan_model": "claude-opus-5-5"} +{"action_id": "ACT-1796133560-7bb3bc1e", "parent_action_id": "I-1796129417-exec-notes-format-before-commit/P-1796129440-CLA-CO5.5/E-1796129676-CLA-CO5.5/_", "event_type": "reconciliation", "verdict": "success", "outcome": "success", "reason": "Stage 5 calibration reconciled execution outcome to success", "created_at": "2026-12-01T13:59:20.476706Z"} diff --git a/holon-knowledge/ledger/pending/intents/I-1796129417-exec-notes-format-before-commit.jsonl b/holon-knowledge/ledger/pending/intents/I-1796129417-exec-notes-format-before-commit.jsonl new file mode 100644 index 000000000..72b24ab9b --- /dev/null +++ b/holon-knowledge/ledger/pending/intents/I-1796129417-exec-notes-format-before-commit.jsonl @@ -0,0 +1 @@ +{"slug": "exec-notes-format-before-commit", "target_branch": "main", "description": "Stage 3 commits execution notes (executions/E-*.md) that fail the repository Prettier check, so the CI Markdown hygiene job is red on the flow's own bookkeeping file. The file is outside the plan touch set, the Stage 4 resolver records no outcome for the hygiene finding, and the review loop repeats without consensus. Plans and calibration reports are already formatted before they are committed; execution notes are the remaining generated artifact that is not.", "goal": "Make every execution notes file reach the execution branch already formatted, and let the Stage 4 resolver repair a flow's own execution notes instead of looping on them. Root cause (measured): the executor prompt tells the agent to commit after each plan step, so the agent commits executions/.md itself; apps/sandbox-executor/src/sandbox_executor/entrypoint/changed_markdown.py lists Markdown only from 'git status --porcelain', so CheckWorkSteps._converge_markdown in apps/sandbox-executor/src/sandbox_executor/entrypoint/executor/outcome.py never sees a notes file that is already committed and formats nothing; in addition that step uses the pinned Prettier of sandbox_executor.formatting, while CI runs the repository Prettier ('npx prettier --check'), the difference already recorded in apps/sandbox-executor/src/sandbox_executor/calibration_format.py. (1) Stage 3: before the engine's execution commit, the Markdown set that is formatted is the union of the working-tree changes (today's behaviour) and the Markdown files committed on the execution branch since the plan tip (self.plan_tip), deleted files excluded; the flow's own execution notes (self.notes_rel) are always in that set when the file exists. The execution notes are formatted in this order: python code fences with the existing format_plan_artifact of apps/sandbox-executor/src/sandbox_executor/plan_artifact_format.py (it accepts any Markdown file inside the repository), then the repository Prettier with the same argv family the calibration report uses ('npx --yes prettier --write' then '--check', up to three passes), implemented in apps/sandbox-executor/src/sandbox_executor/execution_notes_format.py (new) so that outcome.py only calls it; the re-formatted files are part of the engine's execution commit (the existing stage_changes and commit_steps path stages them, no new commit type is needed). A formatter that is missing or fails logs one warning naming the file and never fails the execution (today's behaviour for Prettier). sandbox_executor/formatting.py, entrypoint/executor/run.py and entrypoint/executor/pre_push.py are not changed. (2) Stage 4 resolver: apps/sandbox-executor/src/sandbox_executor/execution_notes_format.py (new) also provides the own-notes test and formatter for a flow branch (the notes path is derived from the execution branch name I-.../P-.../E-/_ as executions/E-.md, and nothing else under executions/ is ever touched), and _commit_resolution in apps/sandbox-executor/src/sandbox_executor/entrypoint/review_loop.py calls it next to the existing format_own_plan_artifacts call. It must run before the 'nothing applied or no worktree change' early return, so that a branch whose only defect is its own unformatted execution notes gets a resolver commit holding just that formatting change (the existing commit message already falls back to the iteration id when no finding was applied) after the unchanged pre-push verification; the touch-set refusal keeps ignoring executions/ paths as it does today and still refuses any code path outside the touch set. Keep review_loop.py within its existing 913-line module budget by keeping the new logic in the new module, never modify holon-config/hygiene/module_budgets.json, and keep every other module within the default 350 lines. Update the 'Resolver pre-push verification' section of docs/review_consensus.md to say that the flow's own execution notes are formatted there. Tests: update the two pinned tests in apps/sandbox-executor/tests/test_executor_characterisation.py that record the Stage 3 command sequence, update apps/sandbox-executor/tests/test_executor_outcome.py, apps/sandbox-executor/tests/test_executor_package.py, apps/sandbox-executor/tests/test_plan_artifact_format.py, apps/sandbox-executor/tests/test_review_loop_plan_artifacts.py and apps/sandbox-executor/tests/flow/review/test_resolver_touch_set.py only where the new behaviour requires it, and add the new tests in apps/sandbox-executor/tests/test_execution_notes_format.py (new), apps/sandbox-executor/tests/test_executor_committed_notes_format.py (new) and apps/sandbox-executor/tests/test_review_loop_execution_notes.py (new); tests/test_review_loop.py is 2,577 lines and tests/test_planner.py is 934 lines, so no test is added to either. Out of this slice, recorded as follow-up work: the Stage 4 loop halting after two consecutive iterations with zero resolver progress (host-side review loop), and any change to the pinned Prettier used for Stage 2 plan Markdown. Code is self-explaining: no docstrings and no comments except '# why:' comments that record a reason the code cannot show.", "rationale": "A flow must not be able to block itself on a bookkeeping file it generated: formatting the notes before they are committed removes the cause, and letting the resolver repair the flow's own notes removes the loop for branches that already carry an unformatted file.", "scope": ["apps/sandbox-executor/src/sandbox_executor/entrypoint/executor/outcome.py", "apps/sandbox-executor/src/sandbox_executor/entrypoint/changed_markdown.py", "apps/sandbox-executor/src/sandbox_executor/entrypoint/executor/__init__.py", "apps/sandbox-executor/src/sandbox_executor/plan_artifact_format.py", "apps/sandbox-executor/src/sandbox_executor/execution_notes_format.py (new)", "apps/sandbox-executor/src/sandbox_executor/entrypoint/review_loop.py", "docs/review_consensus.md", "apps/sandbox-executor/tests/test_executor_characterisation.py", "apps/sandbox-executor/tests/test_executor_outcome.py", "apps/sandbox-executor/tests/test_executor_package.py", "apps/sandbox-executor/tests/test_plan_artifact_format.py", "apps/sandbox-executor/tests/test_review_loop_plan_artifacts.py", "apps/sandbox-executor/tests/flow/review/test_resolver_touch_set.py", "apps/sandbox-executor/tests/test_execution_notes_format.py (new)", "apps/sandbox-executor/tests/test_executor_committed_notes_format.py (new)", "apps/sandbox-executor/tests/test_review_loop_execution_notes.py (new)"], "acceptance_criteria": ["An execution report with a misaligned metrics table is committed Prettier-clean (test asserts `prettier --check` passes on the committed file), in apps/sandbox-executor/tests/test_executor_committed_notes_format.py (new); the test covers the case where the agent has already committed the notes before the engine's formatting step runs.", "A Prettier failure limited to the flow's own `executions/` artifacts is handled by the resolver, not raised as a halt (test asserts it), in apps/sandbox-executor/tests/test_review_loop_execution_notes.py (new): with no finding applied and only the own execution notes unformatted, the resolver formats and commits them and returns no error.", "Regression tests run under `uv run pytest`.", "Execution notes containing an over-long python fence are committed with the fence formatted (test asserts the committed file passes `ruff format --check`).", "Markdown committed by the agent on the execution branch since the plan tip is formatted together with working-tree Markdown; deleted files are skipped; a test asserts both sources.", "Only the execution notes derived from the flow's own execution branch count as own notes: another flow's file under executions/ is never formatted by the resolver, and a code path outside the touch set is still refused next to an own-notes change (tests assert both).", "A missing or failing formatter logs one warning naming the file and the execution still completes, asserted in a test.", "The full test suite passes with only the two pinned command-sequence tests in apps/sandbox-executor/tests/test_executor_characterisation.py updated among the existing Stage 3 tests; `uv run task lint` and `uv run pytest` pass; review_loop.py stays within its 913-line budget, every other changed module stays within 350 lines and holon-config/hygiene/module_budgets.json is untouched.", "Changes are confined to these files and no others: apps/sandbox-executor/src/sandbox_executor/entrypoint/executor/outcome.py, apps/sandbox-executor/src/sandbox_executor/entrypoint/changed_markdown.py, apps/sandbox-executor/src/sandbox_executor/entrypoint/executor/__init__.py, apps/sandbox-executor/src/sandbox_executor/plan_artifact_format.py, apps/sandbox-executor/src/sandbox_executor/execution_notes_format.py, apps/sandbox-executor/src/sandbox_executor/entrypoint/review_loop.py, docs/review_consensus.md, apps/sandbox-executor/tests/test_executor_characterisation.py, apps/sandbox-executor/tests/test_executor_outcome.py, apps/sandbox-executor/tests/test_executor_package.py, apps/sandbox-executor/tests/test_plan_artifact_format.py, apps/sandbox-executor/tests/test_review_loop_plan_artifacts.py, apps/sandbox-executor/tests/flow/review/test_resolver_touch_set.py, apps/sandbox-executor/tests/test_execution_notes_format.py, apps/sandbox-executor/tests/test_executor_committed_notes_format.py, apps/sandbox-executor/tests/test_review_loop_execution_notes.py.", "Code is self-explaining: no docstrings and no comments except '# why:' comments."], "assumptions": [{"id": "A1", "statement": "The notes reach the branch unformatted because the agent commits them before the engine's formatting step, which only looks at the working tree. TESTED NOW on origin/main 4f46380e5 in a scratch detached worktree: a repository whose executions/E-1-x.md with a misaligned table was already committed makes changed_markdown_files return [] while 'npx --yes prettier@3.8.4 --check' on the file exits 1; holon-config/prompts/executor.template.md line 51 tells the agent to commit after each completed plan step; the observed failing notes file was added by an agent-authored commit, not by the engine's execution commit. Re-tested in Stage 3 by the new committed-notes test.", "impact": "high"}, {"id": "A2", "statement": "Adding the Markdown committed since the plan tip to the Stage 3 formatting set breaks no existing test except pinned command-sequence tests. TESTED NOW: outcome.py was temporarily patched to add 'git diff --name-only --diff-filter=d HEAD -- *.md' to the formatted set and `uv run task test` was run: 11044 passed, 2 failed, both in tests/test_executor_characterisation.py (test_success_run_pins_the_row_messages_commit_and_exit and test_budget_breach_salvages_partial_work_and_exits_1); the patch was then reverted. Hence that file is in scope and tests/test_executor_run.py and tests/test_ledger_append_only.py stay out of scope and must pass unchanged. Re-tested in Stage 3 by the full suite.", "impact": "medium"}, {"id": "A3", "statement": "The pinned Prettier of sandbox_executor.formatting and the repository Prettier that CI runs can disagree, so the notes must be checked with the repository Prettier. TESTED NOW by reading formatting.py (PRETTIER_SPEC prettier@3.8.4) and calibration_format.py (its why-comment records that the pinned version wrapped differently from CI and LINT_DOCS_PRETTIER is 'npx --yes prettier'). The other callers of converge_prettier (entrypoint/planner.py and the generic Stage 3 Markdown pass) keep using it unchanged. Re-tested in Stage 3 by the new test that runs the repository Prettier check on the committed notes.", "impact": "medium"}, {"id": "A4", "statement": "The resolver's touch-set refusal already ignores executions/ paths, so no touch-set module needs a change. TESTED NOW by reading touch_set.py out_of_set_files and code_paths and git.py METADATA_PATH_PREFIXES (plans/, executions/, the ledger directory, holon-knowledge/, .holon/). Re-tested in Stage 3 by the new resolver test and by tests/flow/review/test_resolver_touch_set.py.", "impact": "low"}, {"id": "A5", "statement": "_commit_resolution returns before any formatting when no finding was applied or the worktree is clean, which is why a hygiene-only finding on the notes never produced a commit; its commit message builder already supports an empty applied list. TESTED NOW by reading entrypoint/review_loop.py lines 555-596 and _resolver_commit_message (falls back to ITER-). Re-tested in Stage 3 by the new resolver test with no applied finding.", "impact": "medium"}, {"id": "A6", "statement": "format_plan_artifact works on any Markdown file inside the repository, not only plans. TESTED NOW by reading plan_artifact_format.py (_is_markdown_file_inside checks only the .md suffix and containment). Re-tested in Stage 3 by the python-fence test on execution notes.", "impact": "low"}, {"id": "A7", "statement": "Every reader and writer of the execution notes keeps working because formatting changes only whitespace and table alignment. TESTED NOW by grep of src and scripts for executions/, notes_rel, notes_path and the engine-owned notes glob: writers are the agent and entrypoint/executor/run.py (path only); readers are artefacts validation (runs before formatting), flow/partial_salvage.py, flow/github/ci_final_head_rerun.py, flow/stages/plan_scope_guard.py, git.py, scripts/ci_bookkeeping_gate.py, scripts/ci_merge_push_gate.py and scripts/prune_kb_single_flow_failures.py, all of which match on the path prefix only. Re-tested in Stage 3 by the full suite.", "impact": "low"}, {"id": "A8", "statement": "The existing tests of every in-scope module pass on origin/main 4f46380e5 before the change. TESTED NOW from the repository root of a scratch detached worktree: `uv run pytest -n 8 -p no:cacheprovider -q` over tests/test_executor_outcome.py, test_executor_characterisation.py, test_executor_run.py, test_executor_package.py, test_executor_pre_push.py, test_formatting.py, test_review_markdown_gate.py, test_review_loop_plan_artifacts.py, test_plan_artifact_format.py, flow/review/test_resolver_touch_set.py, test_review_loop.py, test_review_resolver_failure.py, test_self_doc_modules.py, test_ledger_append_only.py, test_review_loop_git_identity.py, test_resolver_lint_parity.py, test_planner_plan_fence_format.py and test_calibration_commit.py (all under apps/sandbox-executor/tests): 907 passed. `python scripts/check_module_budgets.py` (435 modules) and `python scripts/check_self_explaining.py` also pass on that commit.", "impact": "low"}, {"id": "A9", "statement": "The scope is disjoint from the only open pull request (464: calibration modules, entrypoint/planner.py, flow/stage5.py, plan_ev_sync.py, docs/ledger_schema.md and their tests) and from the sibling change that removes the Stage 5 no-approval pass-through (flow/review_restart.py, flow/calibrate_rerun.py and Stage 5 tests). TESTED NOW by a script comparing this scope with `gh pr diff 464 --name-only`, with that flow's intent scope and plan touch set, and with the sibling scope: zero common files; pull requests 457 and 460 merged before this check. Re-tested at launch by repeating the comparison.", "impact": "medium"}, {"id": "A10", "statement": "The changed modules have room: entrypoint/review_loop.py is 840 lines (budget 913), entrypoint/executor/outcome.py 271, plan_artifact_format.py 150, entrypoint/changed_markdown.py 23, entrypoint/executor/__init__.py 130 (default 350); the existing test files that get edits are 374, 411, 187, 402, 243 and 467 lines. TESTED NOW by wc -l on origin/main 4f46380e5; re-tested in Stage 3 and Stage 4 by `python scripts/check_module_budgets.py`.", "impact": "low"}], "assumption_validation": [{"assumption_id": "A1", "method": "Already run before launch with the result recorded in the assumption statement; re-run in Stage 3 with the pytest, module budget and self-explaining commands named there, and checked again by the Stage 4 reviewers against the diff."}, {"assumption_id": "A2", "method": "Already run before launch with the result recorded in the assumption statement; re-run in Stage 3 with the pytest, module budget and self-explaining commands named there, and checked again by the Stage 4 reviewers against the diff."}, {"assumption_id": "A3", "method": "Already run before launch with the result recorded in the assumption statement; re-run in Stage 3 with the pytest, module budget and self-explaining commands named there, and checked again by the Stage 4 reviewers against the diff."}, {"assumption_id": "A4", "method": "Already run before launch with the result recorded in the assumption statement; re-run in Stage 3 with the pytest, module budget and self-explaining commands named there, and checked again by the Stage 4 reviewers against the diff."}, {"assumption_id": "A5", "method": "Already run before launch with the result recorded in the assumption statement; re-run in Stage 3 with the pytest, module budget and self-explaining commands named there, and checked again by the Stage 4 reviewers against the diff."}, {"assumption_id": "A6", "method": "Already run before launch with the result recorded in the assumption statement; re-run in Stage 3 with the pytest, module budget and self-explaining commands named there, and checked again by the Stage 4 reviewers against the diff."}, {"assumption_id": "A7", "method": "Already run before launch with the result recorded in the assumption statement; re-run in Stage 3 with the pytest, module budget and self-explaining commands named there, and checked again by the Stage 4 reviewers against the diff."}, {"assumption_id": "A8", "method": "Already run before launch with the result recorded in the assumption statement; re-run in Stage 3 with the pytest, module budget and self-explaining commands named there, and checked again by the Stage 4 reviewers against the diff."}, {"assumption_id": "A9", "method": "Already run before launch with the result recorded in the assumption statement; re-run in Stage 3 with the pytest, module budget and self-explaining commands named there, and checked again by the Stage 4 reviewers against the diff."}, {"assumption_id": "A10", "method": "Already run before launch with the result recorded in the assumption statement; re-run in Stage 3 with the pytest, module budget and self-explaining commands named there, and checked again by the Stage 4 reviewers against the diff."}], "assumption_risk": [{"assumption_id": "A1", "likelihood": "low", "testability": "testable", "score": 1, "response": "fail fast in the named Stage 3 test; park and re-scope before Stage 4 if the check shows an out-of-scope file"}, {"assumption_id": "A2", "likelihood": "medium", "testability": "testable", "score": 2, "response": "fail fast in the named Stage 3 test; park and re-scope before Stage 4 if the check shows an out-of-scope file"}, {"assumption_id": "A3", "likelihood": "medium", "testability": "testable", "score": 2, "response": "fail fast in the named Stage 3 test; park and re-scope before Stage 4 if the check shows an out-of-scope file"}, {"assumption_id": "A4", "likelihood": "low", "testability": "testable", "score": 1, "response": "fail fast in the named Stage 3 test; park and re-scope before Stage 4 if the check shows an out-of-scope file"}, {"assumption_id": "A5", "likelihood": "medium", "testability": "testable", "score": 2, "response": "fail fast in the named Stage 3 test; park and re-scope before Stage 4 if the check shows an out-of-scope file"}, {"assumption_id": "A6", "likelihood": "low", "testability": "testable", "score": 1, "response": "fail fast in the named Stage 3 test; park and re-scope before Stage 4 if the check shows an out-of-scope file"}, {"assumption_id": "A7", "likelihood": "low", "testability": "testable", "score": 1, "response": "fail fast in the named Stage 3 test; park and re-scope before Stage 4 if the check shows an out-of-scope file"}, {"assumption_id": "A8", "likelihood": "low", "testability": "testable", "score": 1, "response": "fail fast in the named Stage 3 test; park and re-scope before Stage 4 if the check shows an out-of-scope file"}, {"assumption_id": "A9", "likelihood": "medium", "testability": "testable", "score": 2, "response": "fail fast in the named Stage 3 test; park and re-scope before Stage 4 if the check shows an out-of-scope file"}, {"assumption_id": "A10", "likelihood": "low", "testability": "testable", "score": 1, "response": "fail fast in the named Stage 3 test; park and re-scope before Stage 4 if the check shows an out-of-scope file"}], "branch": "I-1796129417-exec-notes-format-before-commit", "status": "proposed", "created_at": "2026-12-01T12:50:25.480Z"} diff --git a/holon-knowledge/ledger/pending/plans/I-1796129417-exec-notes-format-before-commit.jsonl b/holon-knowledge/ledger/pending/plans/I-1796129417-exec-notes-format-before-commit.jsonl new file mode 100644 index 000000000..57fb87eda --- /dev/null +++ b/holon-knowledge/ledger/pending/plans/I-1796129417-exec-notes-format-before-commit.jsonl @@ -0,0 +1 @@ +{"plan_id": "P-1796129440-CLA-CO5.5", "intent_branch": "I-1796129417-exec-notes-format-before-commit/_", "agent": "claude-agent", "agent_version": "2.1.302", "model": "claude-opus-5-5", "p_success": 0.8, "entropy": 9.0, "impact": 80.0, "cost": 14.0, "learning_value": 4.0, "ev": 49.3, "created_at": "2026-12-01T12:54:02.626Z", "plan_file": "plans/I-1796129417-exec-notes-format-before-commit/P-1796129440-CLA-CO5.5.md", "status": "proposed", "entropy_budget": 15.0, "decomposition_decision": "execute", "touch_set": [{"path": "apps/sandbox-executor/src/sandbox_executor/execution_notes_format.py"}, {"path": "apps/sandbox-executor/src/sandbox_executor/entrypoint/executor/outcome.py"}, {"path": "apps/sandbox-executor/src/sandbox_executor/entrypoint/changed_markdown.py"}, {"path": "apps/sandbox-executor/src/sandbox_executor/entrypoint/executor/__init__.py"}, {"path": "apps/sandbox-executor/src/sandbox_executor/plan_artifact_format.py"}, {"path": "apps/sandbox-executor/src/sandbox_executor/entrypoint/review_loop.py"}, {"path": "docs/review_consensus.md"}, {"path": "apps/sandbox-executor/tests/test_executor_characterisation.py"}, {"path": "apps/sandbox-executor/tests/test_executor_outcome.py"}, {"path": "apps/sandbox-executor/tests/test_executor_package.py"}, {"path": "apps/sandbox-executor/tests/test_plan_artifact_format.py"}, {"path": "apps/sandbox-executor/tests/test_review_loop_plan_artifacts.py"}, {"path": "apps/sandbox-executor/tests/flow/review/test_resolver_touch_set.py"}, {"path": "apps/sandbox-executor/tests/test_execution_notes_format.py"}, {"path": "apps/sandbox-executor/tests/test_executor_committed_notes_format.py"}, {"path": "apps/sandbox-executor/tests/test_review_loop_execution_notes.py"}]} diff --git a/plans/I-1796129417-exec-notes-format-before-commit/P-1796129440-CLA-CO5.5.md b/plans/I-1796129417-exec-notes-format-before-commit/P-1796129440-CLA-CO5.5.md new file mode 100644 index 000000000..c4a0cbbe3 --- /dev/null +++ b/plans/I-1796129417-exec-notes-format-before-commit/P-1796129440-CLA-CO5.5.md @@ -0,0 +1,651 @@ +# Plan for I-1796129417-exec-notes-format-before-commit + +- **Plan ID:** P-1796129440-CLA-CO5.5 +- **Parent Intent ID:** NONE +- **Agent:** claude-agent/claude-opus-5-5 (version: 2.1.302) +- **Created At:** 2026-12-01T12:50:41.966Z + +## Planner Autonomy Summary + +- **Intent handling:** ACCEPT_AS_IS +- **Reframed intent (if applicable):** N/A. The intent already names the root cause (measured), the touch set, the + module budgets and the tests; the plan only fixes the internal shape of the new module and the order of the calls. +- **Exploration stance:** conservative (fail_fast on the two pinned characterisation tests). The cause was measured + before launch (A1, A2), so the work is exploitation; the only open question is the exact stdout/stderr the two pinned + tests record, which is learned by running them once. +- **Safety priority level:** standard +- **Priority Justification:** No credential, ledger-rewrite or sandbox rule is touched. The change runs inside the + existing Stage 3 container and Stage 4 review-loop container, adds no environment overlay, never writes the ledgers + (`holon-config/world/constraints.md` section 3) and keeps `holon-config/hygiene/module_budgets.json` frozen. The one + elevated concern (the resolver must never touch another flow's `executions/` file or a code path outside the touch + set) is covered by dedicated tests rather than a higher safety level. + +## Exploration + +- **Proportion of steps that are exploratory:** 0.0 +- **Justification:** Every behaviour is specified and its premise was tested before launch (A1 to A10). Step 1 is a + cheap baseline re-run, not exploration. + +## Overall Plan Metrics + +| metric | value | +| ------------------- | ----- | +| p_success_pred | 0.80 | +| entropy_pred | 9.0 | +| impact_pred | 80.0 | +| cost_pred | 14.0 | +| learning_value_pred | 4.0 | +| ev_pred | 49.3 | + +`EV = P(success) * Impact + mu * LearningValue - lambda * Delta_S_intent - Cost` with `mu = 0.5` and `lambda = 0.3` +(`holon-config/metrics/ev_config.json`): +`EV = 0.80 * 80.0 + 0.5 * 4.0 - 0.3 * 9.0 - 14.0 = 64.0 + 2.0 - 2.7 - 14.0 = 49.3`. + +## Plan Description & Strategy + +The fix has two halves that share one new module, +`apps/sandbox-executor/src/sandbox_executor/execution_notes_format.py`: + +1. **Stage 3 (prevention).** `CheckWorkSteps._converge_markdown` in `entrypoint/executor/outcome.py` today formats only + the Markdown that `git status --porcelain` reports. Because the executor prompt tells the agent to commit after every + step, the agent's own notes file is usually already committed and is never formatted. The new behaviour formats the + union of working-tree Markdown and Markdown committed on the execution branch since `self.plan_tip` (deleted files + excluded), and always formats the flow's own notes (`self.notes_rel`) with python-fence formatting + (`format_plan_artifact`) followed by the repository Prettier (`npx --yes prettier --write` then `--check`, up to + three passes, the calibration report's argv family). The re-formatted files are staged by the unchanged + `stage_changes` (success: `repo.add(all_files=True)`; failure: the explicit `notes_rel` add) and land in the engine's + execution commit. +2. **Stage 4 (repair).** `_commit_resolution` in `entrypoint/review_loop.py` calls a new `format_own_execution_notes` + before the "nothing applied or no worktree change" early return. The own notes path is derived only from the flow + branch (`I-.../P-.../E-/_` gives `executions/E-.md`); a branch without an `E-` segment has no own notes. If + that call changed the file, the resolver continues to the unchanged touch-set refusal and pre-push verification (its + Markdown gate now sees the notes as a changed file and checks them with the repository Prettier) and commits. When no + finding was applied, only the own notes path is staged, so the commit holds just the formatting change and the + existing message falls back to `ITER-`. + +Everything new lives in `execution_notes_format.py` (target under 200 lines) so that `review_loop.py` grows by at most +about 15 lines (840 to at most 860 of its 913 budget) and `outcome.py` stays well under 350. `formatting.py`, `run.py`, +`pre_push.py`, `calibration_format.py` and every touch-set module stay unchanged. + +Tests are hermetic: Prettier is replaced by a stand-in that replays verbatim repository-Prettier output (captured once +during Stage 3 by running `npx --yes prettier --write` on the fixture and pasted as a constant with a `# why:` comment), +and the `--check` stand-in passes only on that exact text, which is how `tests/test_calibration_commit.py` already pins +Prettier behaviour. The python-fence test uses the real `ruff` (`uv run --frozen ruff`), as +`tests/test_planner_plan_fence_format.py` already does, and asserts `ruff format --check` on the committed file. + +## Touch Set + +- `apps/sandbox-executor/src/sandbox_executor/execution_notes_format.py` +- `apps/sandbox-executor/src/sandbox_executor/entrypoint/executor/outcome.py` +- `apps/sandbox-executor/src/sandbox_executor/entrypoint/changed_markdown.py` +- `apps/sandbox-executor/src/sandbox_executor/entrypoint/executor/__init__.py` +- `apps/sandbox-executor/src/sandbox_executor/plan_artifact_format.py` +- `apps/sandbox-executor/src/sandbox_executor/entrypoint/review_loop.py` +- `docs/review_consensus.md` +- `apps/sandbox-executor/tests/test_executor_characterisation.py` +- `apps/sandbox-executor/tests/test_executor_outcome.py` +- `apps/sandbox-executor/tests/test_executor_package.py` +- `apps/sandbox-executor/tests/test_plan_artifact_format.py` +- `apps/sandbox-executor/tests/test_review_loop_plan_artifacts.py` +- `apps/sandbox-executor/tests/flow/review/test_resolver_touch_set.py` +- `apps/sandbox-executor/tests/test_execution_notes_format.py` +- `apps/sandbox-executor/tests/test_executor_committed_notes_format.py` +- `apps/sandbox-executor/tests/test_review_loop_execution_notes.py` + +`plan_artifact_format.py`, `test_plan_artifact_format.py`, `test_review_loop_plan_artifacts.py` and +`flow/review/test_resolver_touch_set.py` are listed because the intent allows them; the plan expects to leave +`plan_artifact_format.py` unchanged (its `format_plan_artifact` is reused as is) and to touch those tests only if a run +shows the new behaviour requires it. + +--- + +## Step 1: Re-run the baseline of every in-scope test and the module budgets + +- **Sub‑intent recommendation:** NO +- **Reasoning:** A few minutes of foreground test runs that confirm A8 and A10 on the current tip; nothing to isolate. +- **Step Type:** INFO_GATHERING +- **Exploration level:** EXPLOIT + +### Intent & Git Integration + +- **Step Intent:** Confirm the starting state is green so every later failure is attributable to this change. +- **Git branch:** the execution branch of this plan (`.../P-1796129440-CLA-CO5.5/E-/_`) +- **Sub‑intent:** NONE + +### Implementation Details (No code blocks, only logic/steps) + +1. From the repository root run, in the foreground, `uv run pytest` over `apps/sandbox-executor/tests/` + `test_executor_outcome.py`, `test_executor_characterisation.py`, `test_executor_run.py`, `test_executor_package.py`, + `test_plan_artifact_format.py`, `test_review_loop_plan_artifacts.py`, `flow/review/test_resolver_touch_set.py`, + `test_review_markdown_gate.py`, `test_review_loop.py`, `test_calibration_commit.py` and `test_ledger_append_only.py`. +2. Run `wc -l` on `entrypoint/review_loop.py`, `entrypoint/executor/outcome.py`, `entrypoint/changed_markdown.py`, + `entrypoint/executor/__init__.py` and record the numbers in the execution notes. +3. Read `tests/test_executor_characterisation.py` `_Run`, `SUCCESS_STDOUT`, `SUCCESS_STDERR`, `SALVAGE_STDOUT` and + `SALVAGE_STDERR` to know what the two pinned tests record (command sequence and output). + +### Dependencies & Criticality + +- **Depends on:** NONE +- **Is Bottleneck:** NO + +### Safety & Constraint Considerations + +- **Relevant rules:** prompt Test-Run Discipline (foreground runs only), `holon-config/world/ruleset.md` section 3. +- **Potential failure modes for this step:** a pre-existing red test on the tip. +- **Guardrails and early‑abort checks:** if a baseline test fails, record it in the notes and do not attribute it to + this change; if it is in an in-scope file, stop and report rather than silently fixing unrelated behaviour. + +### Success & Discard Criteria + +- **Success:** all listed tests pass; line counts match A10 within a few lines. +- **Discard:** more than one unrelated failure in the in-scope files: stop and report, the intent's premise A8 no longer + holds. + +### Metrics + +| metric | value | +| ------------------- | ----- | +| p_success_pred | 0.97 | +| entropy_pred | 0.3 | +| impact_pred | 5.0 | +| cost_pred | 1.0 | +| learning_value_pred | 2.0 | +| ev_pred | 4.76 | + +### Step Metrics Rationale + +`EV = 0.97 * 5.0 + 0.5 * 2.0 - 0.3 * 0.3 - 1.0 = 4.85 + 1.0 - 0.09 - 1.0 = 4.76`. Read-only, already measured once +before launch; learning value comes from pinning the exact characterisation output before editing. + +--- + +## Step 2: Add execution_notes_format.py with the notes formatter, the own-notes derivation and its unit tests + +- **Sub‑intent recommendation:** NO +- **Reasoning:** One new leaf module of under 200 lines plus one new test file; both Stage 3 and Stage 4 depend on it, + but it is small and fully unit-testable, so a separate branch adds only overhead. +- **Step Type:** IMPLEMENTATION +- **Exploration level:** EXPLOIT + +### Intent & Git Integration + +- **Step Intent:** Provide one place that formats a flow's execution notes the way CI checks them and that decides which + notes file a flow branch owns. +- **Git branch:** the execution branch of this plan +- **Sub‑intent:** NONE + +### Implementation Details (No code blocks, only logic/steps) + +1. Create `apps/sandbox-executor/src/sandbox_executor/execution_notes_format.py` with + `from __future__ import annotations`, a module logger and imports only from leaf modules: `format_plan_artifact` and + `FenceFormatStatus` from `plan_artifact_format`, `LINT_DOCS_PRETTIER`, `PRETTIER_PASSES` and + `PRETTIER_TIMEOUT_SECONDS` from `calibration_format` (reusing the constants keeps one definition of the repository + Prettier argv; `calibration_format` itself is not edited), `redact_then_truncate` from `redaction`, `INTENT_SUFFIX` + from `ref_names`. Add no import from `entrypoint` or `flow`, so the module stays acyclic + (`tests/test_import_cycle.py`). +2. Define `EXECUTIONS_DIR = "executions"` and `EXECUTION_SEGMENT_PREFIX = "E-"`. +3. `own_execution_notes_for_branch(flow_branch) -> str | None`: strip whitespace and the `INTENT_SUFFIX` (`/_`), split + on `/`, take the last segment; return `executions/.md` only when the segment starts with `E-`, contains no + path separator or `..`, and at least one earlier segment starts with `P-`; otherwise `None` (plan branches, intent + branches, calibration branches and malformed names own no notes). +4. `is_own_execution_notes(path, flow_branch) -> bool`: normalise `./` and compare equal to the derived path; `False` + when there is none. +5. `_repository_prettier(mode, notes_rel, repo_dir)`: + `subprocess.run([*LINT_DOCS_PRETTIER, mode, notes_rel], cwd=repo_dir, capture_output=True, text=True, timeout=PRETTIER_TIMEOUT_SECONDS, check=False)`; + no `env=` argument, so no environment overlay is introduced. +6. `_prettier_failure(notes_rel, repo_dir) -> str | None`: `None` on success; a short reason when `shutil.which("npx")` + is `None`, when `OSError` or `subprocess.TimeoutExpired` is raised, when `--write` exits non-zero, or when `--check` + still fails after `PRETTIER_PASSES` write/check rounds. Keep each function under the ruff complexity limits by + splitting the pass loop into `_converge(notes_rel, repo_dir)`. +7. `format_execution_notes(notes_rel, repo_dir) -> bool`: return `False` without any subprocess when the file does not + exist or is not a regular Markdown file inside the repository. Otherwise read the bytes, call + `format_plan_artifact(notes_rel, repo_dir)` (it already logs exactly one warning naming the file when ruff is missing + or fails), then `_prettier_failure`; on a reason log exactly one warning + `Warning: Prettier formatting skipped for : ` and also print it to + stderr (Stage 3 surfaces warnings on stderr, as `_converge_markdown` does today). Return whether the bytes changed. + Never raise for a formatter failure. +8. `format_own_execution_notes(repo_dir, flow_branch) -> bool`: derive the own path; return `False` when there is none + or it is not a file; otherwise return `format_execution_notes(path, repo_dir)` and log an info line naming the file + when it changed. Nothing else under `executions/` is ever opened. +9. `resolver_stage_pathspec(flow_branch, applied_any, base_pathspec) -> list[str]`: return `base_pathspec` when a + finding was applied, otherwise `["--", own_notes_path]`, so a formatting-only resolver commit holds just the notes. + Keeping this choice here keeps `review_loop.py` small. +10. No docstrings and no comments except `# why:` lines (one on the reuse of the calibration Prettier argv: CI's + `lint-docs` runs the unpinned repository Prettier, which differs from the pinned `prettier@3.8.4`). +11. Create `apps/sandbox-executor/tests/test_execution_notes_format.py` covering: derivation for a root execution + branch, a nested sub-intent execution branch, a plan branch (`None`), a calibration branch (`None`) and a malformed + segment (`None`); `is_own_execution_notes` rejects another flow's `executions/E-other.md`; the Prettier argv is + exactly `npx --yes prettier --write ` then `--check ` with `cwd` the repository (patched + `subprocess.run`); convergence stops after three passes; a missing `npx` and a non-zero `--write` each log one + warning naming the file and return without raising (use `caplog` and `capsys`); a missing file starts no subprocess; + fence formatting runs before Prettier (record call order); `resolver_stage_pathspec` returns the notes-only pathspec + with no applied finding. +12. Run `uv run pytest apps/sandbox-executor/tests/test_execution_notes_format.py` in the foreground. + +### Dependencies & Criticality + +- **Depends on:** Step 1 +- **Is Bottleneck:** YES (Steps 3 and 4 call it), but its p_success is high, so no sub-intent. + +### Safety & Constraint Considerations + +- **Relevant rules:** prompt Code Placement & Sizing (new focused module, complexity limits, self-explaining code), + Environment Overlay Discipline (not triggered: no env, cwd-as-repository only, same as `calibration_format`), + `docs/safety.md` section 1 (git as boundary: the resolver touches only its own notes). +- **Potential failure modes for this step:** importing `calibration_format` pulls a cycle (it imports only + `plan_artifact_format` and `redaction`, so unlikely); branch derivation accepts a crafted path segment. +- **Guardrails and early‑abort checks:** run `python scripts/check_self_explaining.py`, `uv run task lint` on the new + file early; reject any derived path whose segment contains `/`, `\` or `..`. + +### Success & Discard Criteria + +- **Success:** new tests pass; module under 200 lines; lint clean. +- **Discard:** if the module would exceed 350 lines or needs an `entrypoint` import, stop and re-split before + continuing. + +### Metrics + +| metric | value | +| ------------------- | ----- | +| p_success_pred | 0.88 | +| entropy_pred | 2.0 | +| impact_pred | 25.0 | +| cost_pred | 3.5 | +| learning_value_pred | 1.5 | +| ev_pred | 18.65 | + +### Step Metrics Rationale + +`EV = 0.88 * 25.0 + 0.5 * 1.5 - 0.3 * 2.0 - 3.5 = 22.0 + 0.75 - 0.6 - 3.5 = 18.65`. New file with no existing callers, +so entropy is low; the pattern copies `calibration_format.py` and `plan_artifact_format.py`, both proven. + +--- + +## Step 3: Format committed and working-tree Markdown and the own notes before the Stage 3 execution commit + +- **Sub‑intent recommendation:** NO +- **Reasoning:** This is the bottleneck (it changes the pinned Stage 3 command sequence), but it is one method split + into helpers in a 271-line module plus one helper in a 23-line module; the risk is bounded by the characterisation + tests and A2's measurement (only two pinned tests change). +- **Step Type:** IMPLEMENTATION +- **Exploration level:** EXPLOIT + +### Intent & Git Integration + +- **Step Intent:** Make every execution notes file reach the execution branch already formatted, including when the + agent committed it before the engine's formatting step. +- **Git branch:** the execution branch of this plan +- **Sub‑intent:** NONE + +### Implementation Details (No code blocks, only logic/steps) + +1. In `entrypoint/changed_markdown.py` add `committed_markdown_files(repo, base) -> list[str]`: return `[]` when `base` + is empty; run `repo.run(["diff", "--name-only", "--diff-filter=d", base, "HEAD", "--", "*.md"], check=False)` (the + exact command A2 measured); `[]` on a non-zero exit; otherwise the stripped non-empty lines. `--diff-filter=d` drops + deleted files. Add `markdown_to_format(repo, base) -> list[str]` that returns the order-preserving union of + `changed_markdown_files(repo)` and `committed_markdown_files(repo, base)`, deduplicated. Module stays under 60 lines. +2. In `entrypoint/executor/__init__.py` re-export, in the existing `X as X` style, `committed_markdown_files`, + `markdown_to_format` and `format_execution_notes` (from `sandbox_executor.execution_notes_format`), so tests can + patch them on the facade as they already patch `converge_prettier`. +3. In `entrypoint/executor/outcome.py` rewrite `_converge_markdown` as three small methods, each within the complexity + limits: + - `_markdown_to_converge()`: `executor_facade.markdown_to_format(self.repo, self.plan_tip)` minus `self.notes_rel` + (the notes get the repository Prettier, not the pinned one, so the two Prettier versions never fight over one + file), and minus any path that no longer exists. + - `_format_own_notes()`: when `self.notes_rel` and the file at `self.notes_path` exist, call + `executor_facade.format_execution_notes(self.notes_rel, self.repo_dir)`; it never raises for a formatter failure. + - `_converge_markdown()`: keep today's `converge_prettier` call and `doc_update` action record for the other + Markdown, with the same `try/except LedgerRewriteError: raise / except Exception: warn` envelope; then call + `_format_own_notes()` in its own guarded block so a failure of one never skips the other. The action record counts + the notes when they changed (target list still capped at `_MAX_ACTION_TARGET_MD_FILES`). +4. Do not change `run.py`, `pre_push.py` or `formatting.py`: `stage_changes` already stages the re-formatted notes + (`repo.add(all_files=True)` on success, the explicit `notes_rel` add on failure) and `commit_steps` commits them in + the engine's execution commit; on the salvage path the notes are excluded from the partial commit by + `_salvage_pathspec` and committed in the failure commit, still formatted. +5. Update the two pinned tests in `tests/test_executor_characterisation.py` + (`test_success_run_pins_the_row_messages_commit_and_exit` and + `test_budget_breach_salvages_partial_work_and_exits_1`): first run them to see the exact difference; patch + `format_execution_notes` on the facade (or the Prettier runner) with a hermetic stand-in in the `_Run` harness so no + `npx` process starts, and update only the pinned expectations (`SUCCESS_STDOUT`, `SUCCESS_STDERR`, `SALVAGE_STDOUT`, + `SALVAGE_STDERR` or a recorded command list) that the new `git diff` call and notes step legitimately change. No + other existing Stage 3 test may be edited (acceptance criterion); `test_executor_run.py` and + `test_ledger_append_only.py` must pass unchanged. +6. Update `tests/test_executor_outcome.py` only where `_converge_markdown`'s behaviour is asserted (for example a + stubbed `self.repo` that now also answers the `diff` call); add cases there if they are unit-level: the notes are + excluded from the pinned pass, a `converge_prettier` failure still formats the notes, and a notes-formatter failure + leaves the execution status unchanged. +7. Update `tests/test_executor_package.py` only if it pins the facade's exported names. +8. Create `tests/test_executor_committed_notes_format.py` with real git repositories built from the existing fixtures + (`worktree_repo_templates.py` / `executor_fixtures.py`, whichever `test_executor_outcome.py` uses): + - committed-notes case: commit the plan tip, then on the execution branch commit `executions/E-1-x.md` with a + misaligned metrics table (the agent's commit), run `check_work` (or `_converge_markdown`) then `stage_changes` and + `commit_steps`; with the Prettier stand-in replaying the verbatim repository-Prettier output for that table + (captured once in this step by running `npx --yes prettier --write` on the fixture in a scratch directory and + pasted with a `# why:` line), assert the file at the new `HEAD` equals that text and that the stand-in `--check` + (which passes only on that exact text) passes on the committed blob read with `git show HEAD:`; + - working-tree case: an uncommitted notes file is formatted the same way; + - both sources: one Markdown file committed since the plan tip, one changed only in the working tree and one + committed-then-deleted file; assert the pinned pass receives exactly the first two (deleted file skipped) and the + notes go to the notes formatter; + - python fence: notes with an over-long python fence, real `ruff`; assert `ruff format --check` (via + `uv run --frozen ruff format --check` with the same preview fallback as `plan_artifact_format`) passes on the + committed file; skip only when neither `ruff` nor `uv` is on PATH, as the existing fence tests do; + - formatter failure: `npx` missing (patched `shutil.which`) and a failing `--write`; assert exactly one warning + naming the notes file and that the execution still commits with `exec_status == "success"`. +9. Run `uv run pytest` over `test_executor_committed_notes_format.py`, `test_executor_outcome.py`, + `test_executor_characterisation.py`, `test_executor_package.py`, `test_executor_run.py`, `test_ledger_append_only.py` + and `test_execution_workspace_untracked_plans.py` in the foreground. + +### Dependencies & Criticality + +- **Depends on:** Step 2 +- **Is Bottleneck:** YES (the prevention half of the intent); p_success 0.82, above the 0.6 threshold for a STRONGLY_YES + sub-intent. + +### Safety & Constraint Considerations + +- **Relevant rules:** prompt Test-Run Discipline; acceptance criterion "only the two pinned command-sequence tests ... + updated among the existing Stage 3 tests"; `holon-config/world/constraints.md` section 3 (the ledger row is written by + `record_ledger`, unchanged; formatting runs before it and never touches `holon-knowledge/`). +- **Potential failure modes for this step:** the extra `git diff` changes outputs pinned in more tests than A2 measured + (for example on another tip); a real `npx` is spawned in a unit test and hangs without network; formatting the agent's + other committed Markdown (for example a doc) with the pinned Prettier changes a file the plan did not mean to change + (it was already the behaviour for working-tree Markdown, and the touch-set gate ignores formatting-only diffs of + in-scope files only, so an out-of-scope doc reformat could be refused later). +- **Guardrails and early‑abort checks:** run the full Stage 3 test set right after the change and compare the failing + set with A2; if any test outside `test_executor_characterisation.py` breaks, change the implementation rather than the + test. Committed Markdown is limited to files changed by this execution since the plan tip, so files the agent did not + touch are never formatted. Every unit test patches the Prettier runner; the hermetic guard (`network_guard.py`) and + the `which` patch keep `npx` from running. + +### Success & Discard Criteria + +- **Success:** the new committed-notes tests pass; only the two named pinned tests were edited among the existing Stage + 3 tests; `outcome.py` at most about 310 lines and `changed_markdown.py` under 60. +- **Discard:** if more than the two pinned tests must change, or `outcome.py` would exceed 350 lines, stop and record + the finding in the notes (A2 is falsified) instead of editing further tests. + +### Metrics + +| metric | value | +| ------------------- | ----- | +| p_success_pred | 0.82 | +| entropy_pred | 3.0 | +| impact_pred | 30.0 | +| cost_pred | 4.5 | +| learning_value_pred | 1.5 | +| ev_pred | 19.95 | + +### Step Metrics Rationale + +`EV = 0.82 * 30.0 + 0.5 * 1.5 - 0.3 * 3.0 - 4.5 = 24.6 + 0.75 - 0.9 - 4.5 = 19.95`. Highest entropy of the plan because +it changes a pinned path every execution runs; mitigated by A2's measured blast radius (2 tests) and by keeping the new +subprocesses behind facade names the harness already patches. + +--- + +## Step 4: Let the Stage 4 resolver format and commit the flow's own execution notes + +- **Sub‑intent recommendation:** NO +- **Reasoning:** About 10 to 15 lines in `_commit_resolution` plus one new test file; the logic sits in Step 2's module + and the commit path is already covered by `test_review_loop_plan_artifacts.py`. +- **Step Type:** IMPLEMENTATION +- **Exploration level:** EXPLOIT + +### Intent & Git Integration + +- **Step Intent:** A branch whose only defect is its own unformatted notes gets a resolver commit with just that + formatting change and no error, instead of looping without consensus. +- **Git branch:** the execution branch of this plan +- **Sub‑intent:** NONE + +### Implementation Details (No code blocks, only logic/steps) + +1. In `entrypoint/review_loop.py` import `format_own_execution_notes` and `resolver_stage_pathspec` from + `sandbox_executor.execution_notes_format`. +2. In `_commit_resolution`, after `_restore_budget_config` and before the `git status` call, compute + `own_notes_formatted = not opts.dry_run and format_own_execution_notes(repo_dir, head_branch)` with a `# why:` line + (the flow wrote the notes itself, so a hygiene failure on them is repaired here instead of looping). Then the + existing status call sees the re-formatted notes as a worktree change. +3. Change the early-return condition to return when + `(not applied_items and not own_notes_formatted) or not has_worktree_changes`. The `dry_run` branch, the touch-set + refusal (which ignores `executions/` via `METADATA_PATH_PREFIXES` and still refuses any out-of-set code path), the + existing `format_own_plan_artifacts` call and `_verify_before_push` stay unchanged and in the same order. The + Markdown gate inside `_verify_before_push` now lists the notes as changed and checks them with the repository + Prettier. +4. Replace the stage command's pathspec with + `resolver_stage_pathspec(head_branch, bool(applied_items), _RESOLVER_PATHSPEC)`, so with no applied finding only the + own notes are staged; the commit message stays `_resolver_commit_message(iteration, applied_items)` (falls back to + `ITER-`). The `updated` tuple is unchanged (no applied disposition gets a sha when none was applied). +5. Confirm with `wc -l` that `review_loop.py` stays at or below 913 lines (expected about 850). +6. Create `tests/test_review_loop_execution_notes.py` reusing the `flow_repo` fixture style and the lint/test/Prettier + stand-ins of `test_review_loop_plan_artifacts.py` (imported helpers, not copied, where they are module-level; a small + local fixture otherwise), on a flow branch `I-1-x/P-1-y/E-1-z/_` whose committed `executions/E-1-z.md` has a + misaligned table: + - no finding applied, only own notes unformatted: `_commit_resolution` returns no error, a new `HEAD` whose + `git show --name-only` lists only `executions/E-1-z.md`, subject containing `ITER-`, and the stand-in + `--check` passes on the committed blob; + - another flow's `executions/E-9-other.md`, equally unformatted, is byte-for-byte unchanged and not in the commit; + - an out-of-touch-set code file changed next to the own-notes change is still refused with the existing touch-set + message and nothing is committed; + - a plan branch (no `E-` segment) formats no notes and returns early as today; + - `dry_run` formats nothing; + - a missing `npx` logs one warning naming the notes and returns the early "nothing to commit" result without a halt + error. +7. Run `uv run pytest` over `test_review_loop_execution_notes.py`, `test_review_loop_plan_artifacts.py`, + `flow/review/test_resolver_touch_set.py`, `test_review_loop.py`, `test_review_markdown_gate.py`, + `test_review_resolver_failure.py`, `test_resolver_lint_parity.py` and `test_review_loop_git_identity.py` in the + foreground. Edit `test_review_loop_plan_artifacts.py` (for example + `test_nothing_is_formatted_when_no_commit_will_be_made`) or `flow/review/test_resolver_touch_set.py` only if a run + shows the new behaviour legitimately changes what they assert; add nothing to `test_review_loop.py`. + +### Dependencies & Criticality + +- **Depends on:** Step 2 +- **Is Bottleneck:** YES for the repair half; independent of Step 3, so the two can be debugged separately. + +### Safety & Constraint Considerations + +- **Relevant rules:** `holon-config/world/constraints.md` section 1 (commit boundaries: never another flow's file), + `docs/safety.md` principle 1 (blast radius contained to the branch), the frozen module budget (`review_loop.py` 913). +- **Potential failure modes for this step:** the notes-only pathspec accidentally stages agent edits that the resolver + made without applying a finding; the formatting runs before the touch-set refusal and leaves a modified own notes file + in the worktree when the commit is refused (harmless: it is the flow's own file and the next iteration re-formats it + idempotently); a wrong branch parse targets another notes file. +- **Guardrails and early‑abort checks:** the own-notes path comes only from `head_branch`; the cross-flow and touch-set + tests above must pass before Step 6; abort if `review_loop.py` would exceed 913 lines (move more into the new module + instead). + +### Success & Discard Criteria + +- **Success:** the new resolver tests pass; existing resolver tests pass with at most the allowed edits; + `review_loop.py` at or below 913 lines. +- **Discard:** if a formatting-only commit cannot be made without staging non-notes paths, stop and record it rather + than widening the pathspec. + +### Metrics + +| metric | value | +| ------------------- | ----- | +| p_success_pred | 0.82 | +| entropy_pred | 2.5 | +| impact_pred | 20.0 | +| cost_pred | 3.0 | +| learning_value_pred | 1.0 | +| ev_pred | 13.15 | + +### Step Metrics Rationale + +`EV = 0.82 * 20.0 + 0.5 * 1.0 - 0.3 * 2.5 - 3.0 = 16.4 + 0.5 - 0.75 - 3.0 = 13.15`. The review-loop module is large and +heavily tested (2,577-line test file), which raises the chance of an unexpected assertion on the early-return path; the +change is small and mirrors the existing `format_own_plan_artifacts` wiring. + +--- + +## Step 5: Document the resolver's own-notes formatting in docs/review_consensus.md + +- **Sub‑intent recommendation:** NO +- **Reasoning:** A short paragraph in one section. +- **Step Type:** DOCUMENTATION +- **Exploration level:** EXPLOIT + +### Intent & Git Integration + +- **Step Intent:** Keep the "Resolver pre-push verification" section true. +- **Git branch:** the execution branch of this plan +- **Sub‑intent:** NONE + +### Implementation Details (No code blocks, only logic/steps) + +1. In `docs/review_consensus.md`, section `## Resolver pre-push verification`, add two or three sentences: before the + commit decision the resolver formats the flow's own execution notes (`executions/E-.md` derived from the + execution branch name; no other file under `executions/` is touched) with ruff for python fences and the repository + Prettier; when that is the only change it still commits it, after the same verification, with the iteration id as the + finding list; a missing or failing formatter logs one warning and is never a halt. +2. Run `npx --yes prettier --check docs/review_consensus.md` (or `uv run task lint-docs` limited to the file) and the + self-explaining Markdown check that `uv run task lint` runs. + +### Dependencies & Criticality + +- **Depends on:** Step 4 +- **Is Bottleneck:** NO + +### Safety & Constraint Considerations + +- **Relevant rules:** prompt Markdown Hygiene; `tests/test_self_explaining_markdown_coverage.py`. +- **Potential failure modes for this step:** line-wrap differences at width 120. +- **Guardrails and early‑abort checks:** let Prettier write the paragraph, then re-check. + +### Success & Discard Criteria + +- **Success:** the section names the new behaviour and passes the Prettier check. +- **Discard:** none expected. + +### Metrics + +| metric | value | +| ------------------- | ----- | +| p_success_pred | 0.97 | +| entropy_pred | 0.2 | +| impact_pred | 3.0 | +| cost_pred | 0.5 | +| learning_value_pred | 0.0 | +| ev_pred | 2.35 | + +### Step Metrics Rationale + +`EV = 0.97 * 3.0 + 0.5 * 0.0 - 0.3 * 0.2 - 0.5 = 2.91 - 0.06 - 0.5 = 2.35`. + +--- + +## Step 6: Verify lint, the full suite, module budgets and the file scope + +- **Sub‑intent recommendation:** NO +- **Reasoning:** Final gate, required by the acceptance criteria. +- **Step Type:** TEST +- **Exploration level:** EXPLOIT + +### Intent & Git Integration + +- **Step Intent:** Prove every acceptance criterion before the execution commit. +- **Git branch:** the execution branch of this plan +- **Sub‑intent:** NONE + +### Implementation Details (No code blocks, only logic/steps) + +1. `uv run task lint` (ruff, complexity limits without `# noqa`, module budgets, self-explaining comments) in the + foreground; fix anything it reports in the touched files. +2. `python scripts/check_module_budgets.py` and `wc -l` of every changed module: `review_loop.py` at most 913, every + other module at most 350; `git diff --name-only ` shows `holon-config/hygiene/module_budgets.json` + untouched. +3. `uv run task test` once, in the foreground; report the pass/fail counts and pytest time in the notes. +4. Compare `git diff --name-only HEAD` (plus the working tree) with the intent's sixteen allowed files, + ignoring `executions/`, `plans/` and `holon-knowledge/`; any other path is reverted before commit. +5. Run `npx --yes prettier --check` on this execution's own notes file before finishing, as a live check of the + behaviour being added. +6. Re-run the A9 overlap comparison only if the host provides the open pull request list; otherwise record that it was + checked at launch. + +### Dependencies & Criticality + +- **Depends on:** Steps 2 to 5 +- **Is Bottleneck:** NO (it detects failure; it does not add risk) + +### Safety & Constraint Considerations + +- **Relevant rules:** prompt Test-Run Discipline (affected tests first, full suite once, foreground), Code Placement & + Sizing, intent acceptance criteria. +- **Potential failure modes for this step:** an unrelated flaky test; a lint finding in an untouched file. +- **Guardrails and early‑abort checks:** a failure in an untouched file is recorded, not fixed; a repeat run of one + flaky test is allowed once and reported. + +### Success & Discard Criteria + +- **Success:** lint and full suite green; budgets respected; diff within the sixteen files. +- **Discard:** a failure that needs an out-of-scope file: stop, record, and leave the decision to the review. + +### Metrics + +| metric | value | +| ------------------- | ----- | +| p_success_pred | 0.90 | +| entropy_pred | 1.0 | +| impact_pred | 5.0 | +| cost_pred | 1.5 | +| learning_value_pred | 0.5 | +| ev_pred | 2.95 | + +### Step Metrics Rationale + +`EV = 0.90 * 5.0 + 0.5 * 0.5 - 0.3 * 1.0 - 1.5 = 4.5 + 0.25 - 0.3 - 1.5 = 2.95`. The full suite is about 11,000 tests; +cost is wall-clock rather than tokens. + +--- + +### Strategy Rationale + +The intent is accepted as is: it is well measured (A1 to A10 were tested on `origin/main`), the scope is narrow, and the +rationale (a flow must not block itself on its own bookkeeping) has high value because every flow writes an execution +notes file and an unformatted one currently burns whole Stage 4 iterations without consensus. Reframing to "tell the +agent not to commit notes" was considered and rejected: it relies on agent compliance, does not repair branches that +already carry a bad file, and still leaves the pinned/repository Prettier mismatch. Pushing all Markdown through the +repository Prettier was also rejected: it would change the Stage 2 pinned path the intent puts out of scope. + +Aggregation: entropy and cost are sums of the step values (`entropy = 0.3 + 2.0 + 3.0 + 2.5 + 0.2 + 1.0 = 9.0`, +`cost = 1.0 + 3.5 + 4.5 + 3.0 + 0.5 + 1.5 = 14.0`). Learning value is the sum rounded +(`2.0 + 1.5 + 1.5 + 1.0 + 0.0 + 0.5 = 6.5`, discounted to `4.0` because Steps 2 to 4 mostly confirm known behaviour). +`p_success` is a qualitative judgement, not the raw product of the bottleneck steps (`0.88 * 0.82 * 0.82 = 0.59`): +failures in Steps 2 to 4 are detected by fast local tests inside the same Stage 3 run and fixed there, so they are +largely recoverable; the residual risk is concentrated in Step 3 (the bottleneck, pinned Stage 3 sequence) and in Stage +4 reviewers disagreeing on the hermetic Prettier stand-in versus a real Prettier run, giving `0.80`. Impact `80.0` +reflects that the change removes a recurring self-inflicted CI failure and review loop for every future flow. Overall +`EV = 49.3` is strongly positive. + +## Safety & Constraint Alignment + +- **Key world ruleset constraints that affect this plan:** `holon-config/world/constraints.md` section 1 (commit + boundaries: the resolver may only commit the flow's own notes and in-scope code), section 3 (ledger immutability: no + ledger file is written by the new code); `holon-config/world/ruleset.md` section 3 (test changes declared here: the + two pinned characterisation tests and the listed test files); `docs/safety.md` principle 1 (git as the safety + boundary) and principle 4 (entropy budget 15.0); the frozen `holon-config/hygiene/module_budgets.json`; the prompt's + self-explaining code rule (overrides the ruleset's docstring requirement for this repository, as enforced by + `scripts/check_self_explaining.py`). +- **Potential violations or edge cases:** the resolver formatting a file under `executions/` that belongs to another + flow; a formatting-only resolver commit sweeping in unrelated worktree edits; Stage 3 tests spawning a real `npx` that + needs the network; `review_loop.py` crossing 913 lines; an out-of-scope Markdown file reformatted by the Stage 3 + union. +- **Mitigations built into the plan:** own notes derived only from the branch name and tested against a foreign notes + file; notes-only pathspec when no finding was applied; Prettier stand-ins and patched `which` in every test; logic + kept in the new module; committed Markdown limited to files changed since the plan tip (the agent's own changes); + scope check in Step 6. +- **Residual risk accepted (and why):** CI's unpinned repository Prettier can change between the Stage 3 run and CI; the + resolver repair path then fixes the notes on the next iteration, which is exactly the loop-breaker this intent adds. + The host-side "halt after two iterations with no resolver progress" stays out of scope as follow-up work, as the + intent states. +- **Allocated Entropy Budget:** 15.0 +- **Predicted Plan Entropy:** 9.0 +- **Budget Compliance:** The strategy fits within budget (9.0 of 15.0), so it runs as one plan with no sub-intent list. + +## Sub-intent list + +- None diff --git a/plans/I-1796129417-exec-notes-format-before-commit/P-1796129440-CLA-CO5.5_calibration.md b/plans/I-1796129417-exec-notes-format-before-commit/P-1796129440-CLA-CO5.5_calibration.md new file mode 100644 index 000000000..873779604 --- /dev/null +++ b/plans/I-1796129417-exec-notes-format-before-commit/P-1796129440-CLA-CO5.5_calibration.md @@ -0,0 +1,107 @@ +# Plan Calibration Report: P-1796129440-CLA-CO5.5 + +- **Plan Reference:** + [`plans/I-1796129417-exec-notes-format-before-commit/P-1796129440-CLA-CO5.5.md`](P-1796129440-CLA-CO5.5.md) +- **Execution ID:** `E-1796129676-CLA-CO5.5` +- **Execution Branch:** `I-1796129417-exec-notes-format-before-commit/P-1796129440-CLA-CO5.5/E-1796129676-CLA-CO5.5/_` +- **Intent Branch:** `I-1796129417-exec-notes-format-before-commit/_` +- **Evaluating Agent:** `claude-agent/claude-opus-5-5` +- **Plan Agent:** `claude-agent/claude-opus-5-5` +- **Evaluation Timestamp:** `2026-12-01T13:59:18.000Z` +- **Evaluated Commit SHA:** `fa6c03aaa4950d16be4fb82daf3149f8b8863ecc` +- **Base SHA:** `7a38d675513fab7b17547c4537ab7c68c786c522` +- **Merge-Base SHA:** `7a38d675513fab7b17547c4537ab7c68c786c522` +- **Merged Commits:** `0` +- **Patch Size Base:** `plan` + +--- + +## 1. Executive Calibration Summary + +| Metric | Predicted (`pred`) | Actual (`actual`) | Absolute Error (`abs(pred - actual)`) | Accuracy Rating | Bias Direction | +| :------------------------------------------------- | :----------------- | :---------------- | :------------------------------------ | :-------------- | :------------------------- | +| **$P(\text{success})$** | `0.80` | `1.00` | `0.20` | Moderate | Slight Underconfidence | +| **Entropy ($\Delta S$)** | `9.00` | `2.00` | `7.00` | Moderate | Overestimated Risk | +| **Impact** | `80.00` | `80.00` | `0.00` | Exact | Perfectly Calibrated | +| **Cost** | `14.00` | `11.90` | `2.10` | Moderate | Conservative Cost Estimate | +| **Learning Value** | `4.00` | `4.00` | `0.00` | Exact | Perfectly Calibrated | +| **Expected Value — Clean (without bugs)** | `49.30` | `69.50` | `20.20` | Moderate | Conservative Underestimate | +| **Expected Value — Observed (with bugs included)** | `49.30` | `69.50` | `20.20` | Moderate | Conservative Underestimate | +| **Bug EV Drag** | `0.00` | `0.00` | `0.00` | - | Drag Penalty | + +--- + +## 2. Mathematical Derivations & Calibration Errors + +- **Success Probability Error:** $|0.80 - 1.00| = 0.20$ +- **Entropy Error:** $|9.00 - 2.00| = 7.00$ +- **Impact Error:** $|80.00 - 80.00| = 0.00$ +- **Cost Error:** $|14.00 - 11.90| = 2.10$ +- **Learning Value Error:** $|4.00 - 4.00| = 0.00$ +- **Expected Value Realization:** + $$EV_{\text{pred}} = 0.80 \times 80.0 + 0.5 \times 4.0 - 0.3 \times 9.00 - 14.00 = 49.30$$ + $$EV_{\text{actual}} = EV_{\text{clean}} = 1.00 \times 80.0 + 0.5 \times 4.0 - 0.3 \times 2.00 - 11.90 = 69.50$$ + $$EV_{\text{with\_bugs}} = 1.00 \times 80.0 + 0.5 \times 4.0 - 0.3 \times 2.00 - 11.90 = 69.50$$ + $$\text{Bug EV Drag} = round(EV_{\text{clean}} - EV_{\text{with\_bugs}}, 2) = 0.00$$ $$\Delta EV = +20.20$$ + +--- + +## 3. Entropy Factor Breakdown + +- **State Surface Area (SSA):** Predicted `0.6` vs Observed `6.5` (11 files modified). +- **Irreversibility (IRR):** Predicted `0.0` vs Observed `0.0` (Zero destructive or stateful changes). +- **Conflict Likelihood (CL):** Predicted `0.1` vs Observed `0.0` (Clean sequential branch merges). +- **Sandbox Escape Risk (SER):** Predicted `0.0` vs Observed `0.0` (Zero security exceptions). +- **Novelty (NOV):** Predicted `0.4` vs Observed `0.4` (Standard calibration reporting schema). + +--- + +## 4. Calibration Assessment + +Plan `P-1796129440-CLA-CO5.5` executed with minimal error ($p\_success\_error = 0.20$, $cost\_error = 2.10$). The +calibration step successfully completed the execution lifecycle and delivered verified post-execution analysis. + +--- + +## 5. Touch Set Accuracy + +- **Precision (declared entries the diff touched):** `68.8%` +- **Recall (changed files the touch set covered):** `100.0%` + +Changed files outside the touch set: + +- none + +Declared entries the diff did not touch: + +- `apps/sandbox-executor/tests/test_executor_outcome.py` +- `apps/sandbox-executor/tests/test_executor_package.py` +- `apps/sandbox-executor/tests/test_plan_artifact_format.py` +- `apps/sandbox-executor/tests/test_review_loop_plan_artifacts.py` +- `apps/sandbox-executor/tests/flow/review/test_resolver_touch_set.py` + +--- + +## 6. Review Churn + +- **Full reviews:** `1` +- **Scoped reviews:** `1` +- **Approval carry-overs:** `0` +- **Pipeline runs:** `1` +- **Pipeline reruns:** `0` +- **Non-defect churn (target merge):** `0` +- **Non-defect churn (bookkeeping):** `0` +- **Non-defect churn (CI noise):** `0` + +--- + +## 7. Self-Explaining Code Counts + +Against the merge base with origin/main: added 0 docstring(s), added 0 comment(s), removed 0 docstring(s) and removed 0 +comment(s) across 16 changed file(s). + +- Changed files checked: 16 +- Added docstrings: 0 +- Added comments (not '# why:'): 0 +- Removed docstrings: 0 +- Removed comments (not '# why:'): 0