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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,19 @@ read-only quota observation. It admits no ordinary host Turn. These service
checks therefore do not qualify an ordinary PostgreSQL feedback Turn or justify
adding another execution profile to this slice.

Todo-bound planning closeout also reuses the existing typed receipt admission.
A positively admitted non-delivery review does not require a business execution
lease that its guard deliberately never prepares. Explicit or previously
prepared execution still requires the original proof; Goal Stop, source locks,
semantic review and settlement checks remain in force. Isolated
[File/SQLite CLI controls](../../../tests/control_plane/test_replan_writeback_lease_scope.py)
cover enabled/off reviews, foreign identity, explicit/prepared execution, Stop,
unchanged Todo/lease state and once-only replay. This repairs the planning-to-
writeback composition; installed cutover, actual model adoption and outcome/
full-cost qualification remain open.

The existing feedback qualification consumer reads a deferred Run path through the settled result's immutable `result_details` reader rather than assuming diagnostics remain inline. The public read selects only the original path and preserves the Vision, feedback, validation and once-only settlement assertions. Ordinary combined settlement verifies its runtime-owned debit; the planning checkpoint follows its returned agent-owned spend command. File/SQLite source and composed-path controls qualify the reader migration; scripted execution remains distinct from model adoption and benefit.

**Source checkpoint: product execution-observation readback (2026-11-19).** Saved
findings reuse Explore's execution-observation codec and retain the planned and
actual methods, deviation reason, candidate revision, costs and result reference.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,16 @@ Mapping 拒绝顺序、精确整数 IO、会话 ID 解码、轮询时钟及 pend
host Turn。因此这些服务检查不能取得普通 PostgreSQL 反馈 Turn 资格,
也不构成本切片新增执行 profile 的理由。

绑定 Todo 的规划结算也复用既有 typed receipt 准入。明确获准的非交付复核
不要求其 guard 本来就不准备的业务执行租约;显式或先前已准备的执行仍须
具备原证明。Goal Stop、源锁、语义复核及结算检查继续生效。隔离的
[File/SQLite CLI 对照](../../../tests/control_plane/test_replan_writeback_lease_scope.py)
覆盖启用/关闭复核、外国身份、显式/已准备执行、Stop、Todo/租约状态不变
和仅一次重放结算。这修复规划到写回的组合边界;安装态切换、真实模型采用
及成果/完整成本资格仍开放。

既有反馈资格消费者通过已结算结果的不可变 `result_details` reader 读取被延后展示的 Run 路径,不再假设诊断字段总在内联结果中。公开读取仅选择原路径,保留 Vision、反馈、验收及只结算一次的断言。普通组合结算验证运行时负责的扣额;规划 checkpoint 按返回的 Agent 负责命令结算。File/SQLite 源码与组合路径对照资格化该 reader 迁移;脚本执行仍不同于模型采用及收益。

**源码 checkpoint:产品执行观察读回(2026-11-19)。** 已保存结论现在复用
Explore 的执行观察 codec,保留原方法、实际方法、改向原因、候选版本、成本和
结果引用。结论页与历史页复用同一展开式读回;现有 Lark finding Summary 同步
Expand Down
63 changes: 36 additions & 27 deletions loopx/control_plane/quota/execution_preparation.py
Original file line number Diff line number Diff line change
Expand Up @@ -393,6 +393,12 @@ def guard_first_writeback_execution(
yield
return

# The typed receipt owner positively admits a non-delivery planning review.
# A selected Todo supplies context; it is not business execution. Explicit
# or previously prepared execution proofs retain the original lease gate.
planning_only = (getattr(settlement, "replan_execution_pending", False)
and not prepared_required and requested_proof is None)

# Legacy spend acquires maintenance before the run index. Try maintenance
# once here so this order cannot block a competing accounting process.
with ExitStack() as locks:
Expand All @@ -402,33 +408,36 @@ def guard_first_writeback_execution(
operation="refresh-state-execution",
))
require_shadow_primary_write_allowed(runtime_root, goal_id)
snapshot = _read_execution_snapshot(runtime_root, goal_id, todo_id)
if snapshot is None:
raise RefreshTaskLeaseUnavailable("The selected Todo's execution authority could not be read.")
if prepared_required and snapshot.get("handoff_mode") != "hard_lease":
raise RefreshTaskLeaseUnavailable("The Todo's original hard-lease authority is unavailable.")
if snapshot.get("handoff_mode") == "hard_lease":
if not _hard_lease_execution_bound(
snapshot=snapshot,
goal_id=goal_id,
todo_id=todo_id,
agent_id=agent_id,
requested_proof=requested_proof,
settlement=settlement,
allow_same_generation_lease_renewal=allow_same_generation_lease_renewal,
validation_recovery_turn_instance_id=validation_recovery_turn_instance_id,
):
raise RefreshTaskLeaseUnavailable(
"The original writeback needs a current task lease recorded for this Turn. "
"Read the same Todo and Turn through its current guard before retrying."
)
if (
snapshot["todo"].get("status") == "done"
and prepared_required
and settlement.completion_event is None
and not _todo_superseded_for_turn(settlement, todo_id=todo_id, agent_id=agent_id)
):
raise RefreshTaskLeaseUnavailable("The completed Todo is missing this Turn's completion receipt.")
snapshot = None
if not planning_only:
snapshot = _read_execution_snapshot(runtime_root, goal_id, todo_id)
if snapshot is None:
raise RefreshTaskLeaseUnavailable("The selected Todo's execution authority could not be read.")
if prepared_required and snapshot.get("handoff_mode") != "hard_lease":
raise RefreshTaskLeaseUnavailable("The Todo's original hard-lease authority is unavailable.")
if snapshot.get("handoff_mode") == "hard_lease":
if not _hard_lease_execution_bound(
snapshot=snapshot,
goal_id=goal_id,
todo_id=todo_id,
agent_id=agent_id,
requested_proof=requested_proof,
settlement=settlement,
allow_same_generation_lease_renewal=allow_same_generation_lease_renewal,
validation_recovery_turn_instance_id=validation_recovery_turn_instance_id,
):
raise RefreshTaskLeaseUnavailable(
"The original writeback needs a current task lease recorded for this Turn. "
"Read the same Todo and Turn through its current guard before retrying."
)
if (
snapshot["todo"].get("status") == "done"
and prepared_required
and settlement.completion_event is None
and not _todo_superseded_for_turn(settlement, todo_id=todo_id, agent_id=agent_id)
):
raise RefreshTaskLeaseUnavailable("The completed Todo is missing this Turn's completion receipt.")
if planning_only or (snapshot is not None and snapshot.get("handoff_mode") == "hard_lease"):
goal = locked_goal
if goal is None:
source, _ = load_recommendation_source_goal(registry_path, goal_id)
Expand Down
4 changes: 3 additions & 1 deletion tests/control_plane/test_material_feedback_checkpoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,9 @@ def execute(command, **values):
def read_stage(command):
argv = shlex.split(command)
assert argv[:3] == [sys.executable, "-m", "loopx.entrypoint"]
assert argv[3:8] == ["--format", "json", "quota", "replan-view", "--decision-file"]
assert argv[3:6] == ["--format", "json", "quota"]
assert argv[6] in {"replan-view", "context-read"}
assert argv[7] == ("--decision-file" if argv[6] == "replan-view" else "--reference-file")
result = subprocess.run(argv, cwd=project, capture_output=True, text=True, check=True)
return json.loads(result.stdout)

Expand Down
10 changes: 4 additions & 6 deletions tests/control_plane/test_quota_execution_preparation.py
Original file line number Diff line number Diff line change
Expand Up @@ -582,16 +582,14 @@ def hook(name):
proof = ready["execution_preparation"]["lease_proof"]
identity = ready["heartbeat_receipt"]["settlement_identity"]
assert identity == first["heartbeat_receipt"]["settlement_identity"]
refresh = ["refresh-state", *scope,
"--task-lease-idempotency-key", proof["idempotency_key"],
"--task-lease-expected-version", str(proof["expected_version"]),
"--classification", "fixture_manual_result",
proof = ready["execution_preparation"]["lease_proof"]
refresh = ["refresh-state", *scope, "--classification", "fixture_manual_result",
"--delivery-batch-scale", "single_surface", "--delivery-outcome", "outcome_progress",
"--delivery-boundary", "in_flight_continuation", "--progress-result-class", "advanced",
"--progress-work-item-id", TODO, "--progress-evidence-id", "fixture:manual-result",
"--no-global-sync", "--suppress-external-sinks",
"--task-lease-idempotency-key", proof["idempotency_key"],
"--task-lease-expected-version", str(proof["expected_version"]),
"--no-global-sync", "--suppress-external-sinks"]
"--task-lease-expected-version", str(proof["expected_version"])]
if spend_committed:
refresh += ["--settle-turn", "--settlement-receipt"]
assert invoke(*refresh, cwd=delivery_worktree)["settlement_identity"] == identity
Expand Down
99 changes: 99 additions & 0 deletions tests/control_plane/test_replan_writeback_lease_scope.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
"""A receipt-admitted planning review does not execute its selected Todo."""
from __future__ import annotations

import json
import hashlib

import pytest

from canonical_authority_fixture import isolate_sqlite_runtime
from loopx.control_plane.goals.activation import build_goal_activation
from test_quota_settlement_cli import (
AGENT_ID, GOAL_ID, SELECTED_REPLAN_TODO_ID,
_bind_selected_replan_guard, _configure_selected_todo_replan_fixture,
_initialize_fixture_authority, _initialize_git_checkout, _run_cli,
_spend_run_count, _write_fixture,
)


@pytest.mark.parametrize("provider", ["file", "sqlite"])
@pytest.mark.parametrize("case,strategy", [
("planning", "off"), ("planning", "evidence_conditioned_v1"),
("foreign_turn", "off"), ("explicit_execution", "off"),
("prepared_execution", "off"), ("stopped", "off"),
])
def test_planning_closeout_keeps_business_execution_authority(tmp_path, monkeypatch, provider, case, strategy):
isolate_sqlite_runtime(tmp_path, monkeypatch)
project, runtime, registry = _write_fixture(tmp_path)
_configure_selected_todo_replan_fixture(project, registry, stride_strategy=strategy)
_initialize_git_checkout(project)
_initialize_fixture_authority(project, runtime, provider=provider, handoff_mode="hard_lease")
turn = "lease-scoped-planning"
guard = _bind_selected_replan_guard(registry, runtime, project, turn)
identity = guard["heartbeat_receipt"]["settlement_identity"]
assert guard["decision"] == "autonomous_replan_required"
assert guard["normal_delivery_allowed"] is False
assert "execution_preparation" not in guard
rc, before = _run_cli(registry, runtime, "todo", "list", "--goal-id", GOAL_ID,
"--todo-id", SELECTED_REPLAN_TODO_ID)
assert rc == 0
todo = before["todo"]
rc, lease_before = _run_cli(registry, runtime, "task-lease", "inspect", "--goal-id", GOAL_ID,
"--todo-id", SELECTED_REPLAN_TODO_ID)
assert rc == 0 and lease_before["active"] is False
args = ["refresh-state", "--goal-id", GOAL_ID, "--agent-id", AGENT_ID,
"--turn-instance-id", "foreign-planning" if case == "foreign_turn" else turn,
"--todo-id", SELECTED_REPLAN_TODO_ID, "--classification", "verified_planning_scope",
"--delivery-batch-scale", "single_surface", "--delivery-outcome", "outcome_progress",
"--delivery-boundary", "semantic_closeout", "--delivery-workspace-path", str(project),
"--autonomous-replan-recorded", "--repair-delta-kind", "successor_or_supersede",
"--progress-result-class", "advanced", "--progress-surface-id", "surface:planning-scope",
"--progress-hypothesis-id", "hypothesis:planning-scope", "--progress-probe-kind", "probe:planning-scope",
"--progress-evidence-id", "evidence:planning-scope", "--no-global-sync", "--suppress-external-sinks",
"--settle-turn", "--settlement-receipt"]
if case == "explicit_execution":
args += ["--task-lease-idempotency-key", "unadmitted-execution", "--task-lease-expected-version", "1"]
if case == "stopped":
data = json.loads(registry.read_text())
data["goals"][0]["activation"] = build_goal_activation(
state="stopped", updated_at="2026-01-01T00:00:00Z", reason="fixture Stop")
registry.write_text(json.dumps(data))
if case == "prepared_execution":
# This isolated receipt declares business execution, even though it
# also carries planning context. Its original proof must still hold.
log = runtime / "goals" / GOAL_ID / "rollout-event-log.jsonl"
rows = [json.loads(line) for line in log.read_text().splitlines()]
admitted = next(row for row in reversed(rows)
if row["event_kind"] == "quota_should_run" and row.get("run_id") == turn)
admitted["details"].update(prepared_lease_required=True,
prepared_lease_key_sha256=hashlib.sha256(b"unadmitted-execution").hexdigest(),
prepared_lease_version=1, prepared_lease_epoch=1)
log.write_text("".join(json.dumps(row) + "\n" for row in rows))
if strategy != "off":
vision = {"schema_version": "goal_vision_replan_contract_v0", "state": "vision_patch_proposed",
"vision_patch": {"acceptance_summary": "Retain the original task and verify the complete planning scope."},
"path_delta": {"outcome": "replan", "prior_assumption": "The next scope needed review.",
"observed_reality": "A bounded comparison identifies the next complete check.",
"retained": ["Original task and acceptance"], "evidence_refs": ["evidence:planning-scope"]},
"stride_decision": guard["replan_action_packet"]["stride_control"]["minimal_example"]}
vision_path = tmp_path / "vision.json"
vision_path.write_text(json.dumps(vision))
args += ["--agent-vision-json", str(vision_path)]
rc, result = _run_cli(registry, runtime, *args, cwd=project)
if case == "planning":
assert rc == 0 and result["ok"], result.get("error") or result
assert result["settlement_identity"] == identity
assert result["settlement_progress"]["state"] == "settled"
assert _spend_run_count(runtime) == 1
rc, replay = _run_cli(registry, runtime, *args, cwd=project)
assert rc == 0 and replay["idempotent_replay"], replay
assert _spend_run_count(runtime) == 1
else:
assert rc != 0 and not result["ok"] and not result.get("appended"), result
assert _spend_run_count(runtime) == 0
rc, after = _run_cli(registry, runtime, "todo", "list", "--goal-id", GOAL_ID,
"--todo-id", SELECTED_REPLAN_TODO_ID)
assert rc == 0 and after["todo"] == todo
rc, lease_after = _run_cli(registry, runtime, "task-lease", "inspect", "--goal-id", GOAL_ID,
"--todo-id", SELECTED_REPLAN_TODO_ID)
assert rc == 0 and lease_after == lease_before
Loading