Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
6873190
intent: created I-1796100493-stage5-evaluator-plan-ev-sync/_
Dec 1, 2026
f09542b
plan: P-1796100517-CLA-CO5.5 created by claude-agent (claude-opus-5-5)
Dec 1, 2026
3d1db1e
step 1: baseline and scope-overlap check
Dec 1, 2026
9dc3429
step 2: plumb evaluating agent/model into calibration report and ACT-…
Dec 1, 2026
45232b9
step 3: test evaluator attribution and update fixtures and pinned key…
Dec 1, 2026
9e76d13
step 4: fail Stage 5 closed on a plans row versus plan file EV mismatch
Dec 1, 2026
55264eb
step 5: write one computed EV to the plan markdown and plans row in S…
Dec 1, 2026
b4de655
step 6: document ACT-CAL evaluator keys and fail-closed EV cross-check
Dec 1, 2026
d82eadf
step 7: lint, module budgets and full suite; split plan file EV read …
Dec 1, 2026
65ee022
execute: E-1796100754-CLA-CO5.5 completed for plan I-1796100493-stage…
Dec 1, 2026
81a3d61
fix(review): resolve findings R1-F1, R1-F2, R2-F1, R3-F1, R3-F2, R3-F…
Dec 1, 2026
6cf9b5d
chore(review): record review ledger rows (iteration 1)
Dec 1, 2026
243f809
chore(review): record review ledger rows (iteration 2)
Dec 1, 2026
51b2a8e
chore(calibration): add calibration report for P-1796100517-CLA-CO5.5
Dec 1, 2026
83284b2
chore(calibration): record stage 5 reconciliation
Dec 1, 2026
3a53985
chore(calibration): record stage 5 promoted knowledge and wisdom
Dec 1, 2026
69250dc
Merge remote-tracking branch 'origin/main' into I-1796100493-stage5-e…
thomashan Dec 1, 2026
86ff48e
sync: merge target origin/main at 3e9960ade406 (clean)
thomashan Dec 1, 2026
23d7338
chore(calibration): add calibration report for P-1796100517-CLA-CO5.5
Dec 1, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,17 @@ def _attribution(exec_meta: dict[str, Any], plan_meta: dict[str, Any]) -> tuple[
return agent_id, agent_version, model_name


def _evaluator(
attribution: tuple[str, str, str], evaluating_agent: str | None, evaluating_model: str | None
) -> tuple[str, str]:
agent_id, _agent_version, model_name = attribution
return evaluating_agent or agent_id, evaluating_model or model_name


def _plan_attribution(plan_meta: dict[str, Any]) -> tuple[str, str]:
return plan_meta.get("agent") or "N/A", plan_meta.get("model") or "N/A"


def _entropy_factors(actual: ActualMetrics, exec_meta: dict[str, Any]) -> EntropyFactors:
"""Predicted versus observed entropy factors; the observed SSA is the measured one, else a file-count fallback."""
ssa_fallback = 0.0 if actual.files_changed == 0 else max(0.2, actual.files_changed * 0.1)
Expand All @@ -132,6 +143,9 @@ def generate_calibration(
execution_branch: str,
target_worktree: str = ".",
review_accounting: dict[str, Any] | None = None,
*,
evaluating_agent: str | None = None,
evaluating_model: str | None = None,
) -> CalibrationReport:
"""Run calibration calculation and return a complete CalibrationReport.

Expand Down Expand Up @@ -159,7 +173,10 @@ def generate_calibration(
execution_id, resolved_plan_ref, predicted, execution_branch=resolved_exec_ref, target_worktree=target_worktree
)
deltas, ratings, biases = compute_calibration_deltas(predicted, actual)
agent_id, agent_version, model_name = _attribution(exec_meta, plan_meta)
attribution = _attribution(exec_meta, plan_meta)
_, agent_version, _ = attribution
agent_id, model_name = _evaluator(attribution, evaluating_agent, evaluating_model)
plan_agent, plan_model = _plan_attribution(plan_meta)
timestamp_str = datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%S.000Z")
lambda_val, mu_val = load_metrics_physics(target_worktree)
ef = _entropy_factors(actual, exec_meta)
Expand All @@ -174,6 +191,8 @@ def generate_calibration(
"agent_id": agent_id,
"agent_version": agent_version,
"model_name": model_name,
"plan_agent": plan_agent,
"plan_model": plan_model,
"timestamp": timestamp_str,
"predicted": predicted.to_dict(),
"actual": actual.to_dict(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,8 @@ class CalibrationReport:
touch_set: dict[str, Any] | None = None
diff_base: str | None = None
review_accounting: dict[str, Any] | None = None
plan_agent: str | None = None
plan_model: str | None = None
# Self-check inputs, not serialised: the counted (non-metadata) paths and the ledger summary rows read.
changed_paths: list[str] | None = None
summary_records: list[dict[str, Any]] = dataclasses.field(default_factory=list)
Expand Down Expand Up @@ -102,6 +104,10 @@ def _header_lines(report_data: dict[str, Any]) -> list[str]:
f"- **Execution Branch:** `{report_data.get('execution_branch') or 'N/A'}`",
f"- **Intent Branch:** `{report_data['intent_branch']}`",
f"- **Evaluating Agent:** `{report_data['agent_id']}/{report_data['model_name']}`",
]
if "plan_agent" in report_data:
lines.append(f"- **Plan Agent:** `{report_data['plan_agent']}/{report_data.get('plan_model') or 'N/A'}`")
lines += [
f"- **Evaluation Timestamp:** `{report_data['timestamp']}`",
f"- **Evaluated Commit SHA:** {sha_display}",
]
Expand Down
9 changes: 7 additions & 2 deletions apps/sandbox-executor/src/sandbox_executor/calibration/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,8 +140,13 @@ def run_calibrate(
log_fn: Callable[[str], None] | None = None,
**review: Unpack[CalibrateReview],
) -> CalibrationReport:
accounting = review.get("review_accounting")
report = generate_calibration(execution_branch, target_worktree=target_worktree, review_accounting=accounting)
report = generate_calibration(
execution_branch,
target_worktree=target_worktree,
review_accounting=review.get("review_accounting"),
evaluating_agent=review.get("evaluating_agent"),
evaluating_model=review.get("evaluating_model"),
)
# why: the self-check fails closed before any branch, file or commit is touched
enforce_report_self_check(report, target_worktree, review.get("approved_head"), log_fn)
report.committed = not skip_commit
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,18 @@
_METRIC_ROW = re.compile(r"\|\s*([a-zA-Z_0-9]+)\s*\|\s*([0-9\.\-]+)\s*\|")


class PlanEvMismatchError(RuntimeError):
def __init__(self, plan_file: str, ledger_ev: float, plan_file_ev: float) -> None:
self.plan_file = plan_file
self.ledger_ev = ledger_ev
self.plan_file_ev = plan_file_ev
super().__init__(
f"Predicted EV mismatch: plans.jsonl row ev={ledger_ev:g} vs plan file {plan_file} Overall Plan Metrics "
f"ev={plan_file_ev:g}; calibration refused; append a plans correction row (ledger_revision >= 2) or "
"correct the plan file so both carry one EV"
)


class PredictedMismatch(NamedTuple):
source: str
field: str
Expand Down Expand Up @@ -111,7 +123,7 @@ def execution_predicted_metrics(executions_path: str, execution_id: str, plan_br
return _float_fields(latest["predicted_metrics"]) if latest else {}


# why: the warning is advisory; calibration still uses the selected plans row, and ledgers are only ever read here.
# why: advisory, only the plan file EV fails closed; calibration uses the selected plans row and only reads ledgers
def cross_check_predicted(
selected: dict[str, Any], sources: list[tuple[str, dict[str, float]]]
) -> list[PredictedMismatch]:
Expand Down Expand Up @@ -140,20 +152,39 @@ def cross_check_predicted(
return mismatches


def plan_ev_mismatch(
selected: dict[str, Any], plan_file: str, plan_metrics: dict[str, float]
) -> PlanEvMismatchError | None:
ledger_ev = metrics_from_row(selected).get("ev")
plan_file_ev = plan_metrics.get("ev")
if ledger_ev is None or plan_file_ev is None or abs(ledger_ev - plan_file_ev) <= MISMATCH_TOLERANCE:
return None
return PlanEvMismatchError(plan_file, ledger_ev, plan_file_ev)


def cross_check_selected_row(
selected: dict[str, Any], plan_branch: str, target_worktree: str, execution_id: str = ""
) -> list[PredictedMismatch]:
ev_mismatch: PlanEvMismatchError | None = None
mismatches: list[PredictedMismatch] = []
try:
plan_file, plan_metrics = plan_file_overall_metrics(selected, plan_branch, target_worktree)
ev_mismatch = plan_ev_mismatch(selected, plan_file, plan_metrics)
executions_path = os.path.join(target_worktree, EXECUTIONS_JSONL_REL)
sources = [
(f"plan file {plan_file} Overall Plan Metrics", plan_metrics),
(
f"plan file {plan_file} Overall Plan Metrics",
{field: value for field, value in plan_metrics.items() if field != "ev"},
),
(
f"execution {execution_id} predicted_metrics",
execution_predicted_metrics(executions_path, execution_id, plan_branch),
),
]
return cross_check_predicted(selected, [(label, metrics) for label, metrics in sources if metrics])
mismatches = cross_check_predicted(selected, [(label, metrics) for label, metrics in sources if metrics])
except Exception as e:
logger.debug("Predicted-metric cross-check skipped: %s", e)
return []
# why: raised outside the try so the broad except above cannot turn the fail-closed EV check back into a warning
if ev_mismatch is not None:
raise ev_mismatch
return mismatches
Original file line number Diff line number Diff line change
Expand Up @@ -50,4 +50,8 @@ def calibration_action_row(
"calibration_report_path": report_rel,
"created_at": utc_now_z(),
"touch_set_accuracy": data.get("touch_set"),
"calibration_agent": data.get("agent_id"),
"calibration_model": data.get("model_name"),
"plan_agent": data.get("plan_agent"),
"plan_model": data.get("plan_model"),
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@
class CalibrateReview(TypedDict, total=False):
approved_head: str | None
review_accounting: dict[str, Any] | None
evaluating_agent: str | None
evaluating_model: str | None


class CalibrationSelfCheckError(RuntimeError):
Expand Down
20 changes: 19 additions & 1 deletion apps/sandbox-executor/src/sandbox_executor/entrypoint/planner.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,16 @@
from sandbox_executor.module_budget_guard import module_budget_change_authorised, refusal_message, without_budget_config
from sandbox_executor.plan_artifact_format import format_plan_artifact
from sandbox_executor.plan_attempt import clear_failure_detail, discard_untracked_plan_file, write_failure_detail
from sandbox_executor.plan_ev_sync import (
PlanEvSyncError,
PlanMetrics,
check_plan_ev,
plans_ledger_files,
restore_files,
rounded_plan_ev,
snapshot_files,
write_plan_ev,
)
from sandbox_executor.plan_paths import plan_file_rel
from sandbox_executor.redaction import redact_agent_secrets, redact_command, redact_command_args
from sandbox_executor.touch_set import parse_touch_set_section
Expand Down Expand Up @@ -511,7 +521,7 @@ def build_agent_cmd(prompt_text: str) -> list[str]:
impact = metrics["impact"]
cost = metrics["cost"]
learning_value = metrics["learning_value"]
ev = p_success * impact + ev_mu * learning_value - ev_lambda * entropy - cost
ev = rounded_plan_ev(PlanMetrics(p_success, impact, learning_value, entropy, cost), ev_lambda, ev_mu)
metrics["ev"] = ev

timestamp_str = datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
Expand All @@ -533,6 +543,7 @@ def build_agent_cmd(prompt_text: str) -> list[str]:
"entropy_budget": entropy_budget,
}

write_plan_ev(plan_md_path, ev)
# why: format before the ledger append so the recorded decision is parsed from the committed file
try:
converge_prettier([plan_md_rel], repo_dir=repo_dir)
Expand All @@ -545,9 +556,16 @@ def build_agent_cmd(prompt_text: str) -> list[str]:
plans_ledger_dir = os.path.join(repo_dir, "holon-knowledge/ledger")
os.makedirs(plans_ledger_dir, exist_ok=True)
plans_ledger_path = os.path.join(plans_ledger_dir, "plans.jsonl")
ledger_before = snapshot_files(plans_ledger_files(plans_ledger_path))
with atomic_ledger_append(plans_ledger_path) as lf:
lf.write(json.dumps(plan_entry) + "\n")
validate_ledger_file_unique_ids(plans_ledger_path, id_key="plan_id", parent_key="intent_branch")
try:
check_plan_ev(plan_md_path, plans_ledger_path, plan_id, intent_branch)
except PlanEvSyncError as e:
# why: a refused attempt must not leave its plans row for the next attempt's ledger add to commit
restore_files(ledger_before, plans_ledger_files(plans_ledger_path))
_fail_plan_attempt(repo_dir, plan_md_rel, str(e))

# why: no push here, the host pushes the branch after this container returns
run_cmd(["git", "add", plan_md_rel, *ledger_commit_paths(repo_dir, "plans.jsonl")], cwd=repo_dir)
Expand Down
2 changes: 2 additions & 0 deletions apps/sandbox-executor/src/sandbox_executor/flow/stage5.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,8 @@ def run_stage5(
log_fn=context.log,
approved_head=approved_head_of(context),
review_accounting=accounting_of(context),
evaluating_agent=context.agent,
evaluating_model=context.model,
)
context.calibrated_branch = report.calibrated_branch
outcome.report_dict = report.to_dict()
Expand Down
134 changes: 134 additions & 0 deletions apps/sandbox-executor/src/sandbox_executor/plan_ev_sync.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
from __future__ import annotations

import os
import re
from dataclasses import dataclass

from sandbox_executor.calibration_predicted import MISMATCH_TOLERANCE, OVERALL_HEADING, overall_plan_metrics
from sandbox_executor.ledger import read_merged_rows
from sandbox_executor.ledger.fragments import iter_fragment_files

EV_ROW = re.compile(r"^(\|\s*ev(?:_pred)?\s*\|)([^|]*)(\|.*)$")


class PlanEvSyncError(RuntimeError):
pass


@dataclass(frozen=True)
class PlanMetrics:
p_success: float
impact: float
learning_value: float
entropy: float
cost: float


def rounded_plan_ev(metrics: PlanMetrics, ev_lambda: float, ev_mu: float) -> float:
reward = metrics.p_success * metrics.impact + ev_mu * metrics.learning_value
return round(reward - ev_lambda * metrics.entropy - metrics.cost, 4)


def ev_cell_text(ev: float) -> str:
return repr(float(ev))


def _overall_section_bounds(lines: list[str]) -> tuple[int, int] | None:
start = next((index for index, line in enumerate(lines) if line.startswith(OVERALL_HEADING)), None)
if start is None:
return None
end = next((index for index in range(start + 1, len(lines)) if lines[index].startswith("## ")), len(lines))
return start, end


def _ev_row_with_value(match: re.Match[str], text: str) -> str:
cell = f" {text} "
return f"{match.group(1)}{cell.ljust(len(match.group(2)))}{match.group(3)}"


def _aligned_ev_row(previous_row: str, text: str) -> str:
widths = [len(cell) for cell in previous_row.split("|")[1:-1]]
if len(widths) != 2:
return f"| ev_pred | {text} |"
return f"|{' ev_pred '.ljust(widths[0])}|{f' {text} '.ljust(widths[1])}|"


def _synced_section(section: list[str], text: str) -> list[str]:
for index, line in enumerate(section):
if match := EV_ROW.match(line):
if match.group(2).strip() == text:
return section
return [*section[:index], _ev_row_with_value(match, text), *section[index + 1 :]]
table_rows = [index for index, line in enumerate(section) if line.startswith("|")]
if not table_rows:
return [*section, f"| ev_pred | {text} |"]
insert_at = table_rows[-1] + 1
return [*section[:insert_at], _aligned_ev_row(section[insert_at - 1], text), *section[insert_at:]]


def write_plan_ev(plan_md_path: str, ev: float) -> bool:
with open(plan_md_path, encoding="utf-8") as f:
content = f.read()
lines = content.split("\n")
bounds = _overall_section_bounds(lines)
if bounds is None:
return False
start, end = bounds
synced = [*lines[: start + 1], *_synced_section(lines[start + 1 : end], ev_cell_text(ev)), *lines[end:]]
if synced == lines:
return False
with open(plan_md_path, "w", encoding="utf-8") as f:
f.write("\n".join(synced))
return True


def _plans_row_ev(plans_ledger_path: str, plan_id: str, intent_branch: str) -> float | None:
rows = [
row
for row in read_merged_rows(plans_ledger_path)
if row.get("plan_id") == plan_id and row.get("intent_branch") == intent_branch
]
try:
return float(rows[-1]["ev"]) if rows else None
except (KeyError, TypeError, ValueError):
return None


def _plan_file_ev(plan_md_path: str) -> float | None:
with open(plan_md_path, encoding="utf-8") as f:
return overall_plan_metrics(f.read()).get("ev")


def check_plan_ev(plan_md_path: str, plans_ledger_path: str, plan_id: str, intent_branch: str) -> None:
markdown_ev = _plan_file_ev(plan_md_path)
ledger_ev = _plans_row_ev(plans_ledger_path, plan_id, intent_branch)
if markdown_ev is None or ledger_ev is None or abs(markdown_ev - ledger_ev) > MISMATCH_TOLERANCE:
raise PlanEvSyncError(
f"Plan {plan_id}: predicted EV differs between plans.jsonl (ev={ledger_ev}) and {plan_md_path} "
f"Overall Plan Metrics (ev_pred={markdown_ev}); the plan attempt is refused"
)


def plans_ledger_files(plans_ledger_path: str) -> list[str]:
return [plans_ledger_path, *iter_fragment_files(plans_ledger_path)]


def snapshot_files(paths: list[str]) -> dict[str, bytes | None]:
snapshot: dict[str, bytes | None] = {}
for path in paths:
try:
with open(path, "rb") as f:
snapshot[path] = f.read()
except FileNotFoundError:
snapshot[path] = None
return snapshot


def restore_files(snapshot: dict[str, bytes | None], current_paths: list[str]) -> None:
for path in current_paths:
if snapshot.get(path) is None and os.path.exists(path):
os.remove(path)
for path, data in snapshot.items():
if data is not None:
with open(path, "wb") as f:
f.write(data)
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
- **Execution Branch:** `I-1795409225-regress/P-1795409242-REG/E-1795409573-REG/_`
- **Intent Branch:** `I-1795409225-regress/_`
- **Evaluating Agent:** `claude-agent/claude-opus-5-5`
- **Plan Agent:** `claude-agent/claude-opus-5-5`
- **Evaluation Timestamp:** `2026-11-23T05:45:26.000Z`
- **Evaluated Commit SHA:** `<approved_head>`
- **Base SHA:** `<main_head>`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
- **Execution Branch:** `I-1795000000-golden/P-1795000001-CLA-CO5.5/E-1795000002-CLA-CO5.5/_`
- **Intent Branch:** `I-1795000000-golden/_`
- **Evaluating Agent:** `claude-agent/claude-opus-5-5`
- **Plan Agent:** `codex-agent/gpt-5.5`
- **Evaluation Timestamp:** `2026-11-26T05:30:00.000Z`
- **Evaluated Commit SHA:** `0123456789abcdef0123456789abcdef01234567`
- **Base SHA:** `1111111111111111111111111111111111111111`
Expand Down
4 changes: 4 additions & 0 deletions apps/sandbox-executor/tests/test_calibration_commit.py
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,10 @@ def test_run_calibrate_appends_and_commits_act_cal(calibrated_committed):
"calibration_report_path",
"created_at",
"touch_set_accuracy",
"calibration_agent",
"calibration_model",
"plan_agent",
"plan_model",
]
assert (row["entry_type"], row["action_origin"]) == ("action", "calibration")
assert row["outcome"] == "success"
Expand Down
Loading
Loading