From 935e0917e827af6dd22a7659f25d391642e6120d Mon Sep 17 00:00:00 2001 From: "lusendong.6789" Date: Sat, 21 Nov 2026 01:35:48 +0800 Subject: [PATCH 1/2] fix(quota): preserve planning writeback lease scope Signed-off-by: lusendong.6789 Co-authored-by: TRAE CLI --- ...hanism-convergence-and-learning-loop-v0.md | 11 +++ ...-convergence-and-learning-loop-v0.zh-CN.md | 8 ++ .../quota/execution_preparation.py | 95 ++++++++++-------- .../test_quota_execution_preparation.py | 5 +- .../test_replan_writeback_lease_scope.py | 99 +++++++++++++++++++ 5 files changed, 174 insertions(+), 44 deletions(-) create mode 100644 tests/control_plane/test_replan_writeback_lease_scope.py diff --git a/docs/architecture/rfcs/mechanism-convergence-and-learning-loop-v0.md b/docs/architecture/rfcs/mechanism-convergence-and-learning-loop-v0.md index cecec7e793..3a4439064c 100644 --- a/docs/architecture/rfcs/mechanism-convergence-and-learning-loop-v0.md +++ b/docs/architecture/rfcs/mechanism-convergence-and-learning-loop-v0.md @@ -335,6 +335,17 @@ 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 first task needs an actual feedback or method-choice requirement. Reuse complete existing paths; real consumers must demonstrate gaps before repairing them rather than manufacturing a failure for the example. Experiments, training and procedural publication retain original authority. This document allocates neither another lane's quota nor a prescribed PR count. ## 12. Consequential choices to confirm diff --git a/docs/architecture/rfcs/mechanism-convergence-and-learning-loop-v0.zh-CN.md b/docs/architecture/rfcs/mechanism-convergence-and-learning-loop-v0.zh-CN.md index 500f003c4b..ea705bbd32 100644 --- a/docs/architecture/rfcs/mechanism-convergence-and-learning-loop-v0.zh-CN.md +++ b/docs/architecture/rfcs/mechanism-convergence-and-learning-loop-v0.zh-CN.md @@ -316,6 +316,14 @@ soft claim/hard lease 及历史反馈仅作上下文:保留独立验证的成 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/租约状态不变 +和仅一次重放结算。这修复规划到写回的组合边界;安装态切换、真实模型采用 +及成果/完整成本资格仍开放。 + 首个任务须确有反馈或方法选择需求。已有链完整时直接复用;有缺口时由真实消费者证明并修复,不为配合示例制造失败。运行实验、训练模型和发布过程各沿原权限,本文不占用其他 lane 配额或预设 PR 数。 ## 12. 待确认的关键选择 diff --git a/loopx/control_plane/quota/execution_preparation.py b/loopx/control_plane/quota/execution_preparation.py index 43e4cea981..3ffa22f1c4 100644 --- a/loopx/control_plane/quota/execution_preparation.py +++ b/loopx/control_plane/quota/execution_preparation.py @@ -189,6 +189,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 = (settlement.replan_execution_pending + 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: @@ -198,49 +204,52 @@ 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": - todo_open = snapshot["todo"].get("status") == "open" - facts = _execution_facts(snapshot, goal_id, todo_id, agent_id) - current = _project_execution_facts({**facts, "include_retired_lease_for_writeback": not todo_open}) - current_proof = (current.get("lease_proof") if current.get("state") == "ready" - else current.get("retired_lease_proof")) - if todo_open or prepared_required: - # Legacy prepared receipts can prove their exact version, but cannot - # advance to a later version without a recorded generation. - lease_epoch = (current.get("lease_epoch") - if prepared_lease and "prepared_lease_epoch" in prepared_lease else None) - # Recovery can read the retired proof from the same locked - # snapshot, including a renewal within the admitted generation. - proof = current_proof if not todo_open and requested_proof is None else requested_proof - execution_bound = False - if prepared_lease is not None and proof is not None and proof == current_proof: - observed = prepared_lease_receipt_fields(proof, lease_epoch=lease_epoch) - admitted_version = prepared_lease["prepared_lease_version"] - if ( - not todo_open and lease_epoch is not None - and observed["prepared_lease_version"] > admitted_version - ): - observed["prepared_lease_version"] = admitted_version - execution_bound = prepared_lease == observed - else: - # Older admitted closeouts may predate persisted lease readiness. - # Their retired holder still has to match the original binding. - admission = settlement.native_child_admission or {} - execution_bound = (current_proof is not None - and admission.get("report_permission") in {"new_operation", "existing_operation_only"} - and (requested_proof is None or requested_proof == current_proof)) - if not execution_bound: - 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: - 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": + todo_open = snapshot["todo"].get("status") == "open" + facts = _execution_facts(snapshot, goal_id, todo_id, agent_id) + current = _project_execution_facts({**facts, "include_retired_lease_for_writeback": not todo_open}) + current_proof = (current.get("lease_proof") if current.get("state") == "ready" + else current.get("retired_lease_proof")) + if todo_open or prepared_required: + # Legacy prepared receipts can prove their exact version, but cannot + # advance to a later version without a recorded generation. + lease_epoch = (current.get("lease_epoch") + if prepared_lease and "prepared_lease_epoch" in prepared_lease else None) + # Recovery can read the retired proof from the same locked + # snapshot, including a renewal within the admitted generation. + proof = current_proof if not todo_open and requested_proof is None else requested_proof + execution_bound = False + if prepared_lease is not None and proof is not None and proof == current_proof: + observed = prepared_lease_receipt_fields(proof, lease_epoch=lease_epoch) + admitted_version = prepared_lease["prepared_lease_version"] + if ( + not todo_open and lease_epoch is not None + and observed["prepared_lease_version"] > admitted_version + ): + observed["prepared_lease_version"] = admitted_version + execution_bound = prepared_lease == observed + else: + # Older admitted closeouts may predate persisted lease readiness. + # Their retired holder still has to match the original binding. + admission = settlement.native_child_admission or {} + execution_bound = (current_proof is not None + and admission.get("report_permission") in {"new_operation", "existing_operation_only"} + and (requested_proof is None or requested_proof == current_proof)) + if not execution_bound: + 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: + 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) diff --git a/tests/control_plane/test_quota_execution_preparation.py b/tests/control_plane/test_quota_execution_preparation.py index 58d7ccc214..226cad2066 100644 --- a/tests/control_plane/test_quota_execution_preparation.py +++ b/tests/control_plane/test_quota_execution_preparation.py @@ -578,11 +578,14 @@ def hook(name): assert ready["execution_preparation"]["state"] == "ready" identity = ready["heartbeat_receipt"]["settlement_identity"] assert identity == first["heartbeat_receipt"]["settlement_identity"] + 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"] + "--no-global-sync", "--suppress-external-sinks", + "--task-lease-idempotency-key", proof["idempotency_key"], + "--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 diff --git a/tests/control_plane/test_replan_writeback_lease_scope.py b/tests/control_plane/test_replan_writeback_lease_scope.py new file mode 100644 index 0000000000..fd0396139d --- /dev/null +++ b/tests/control_plane/test_replan_writeback_lease_scope.py @@ -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 From 8859b01fe69c531d3d114bb6187b6e6e76fe4d71 Mon Sep 17 00:00:00 2001 From: "lusendong.6789" Date: Sat, 21 Nov 2026 02:38:53 +0800 Subject: [PATCH 2/2] Repair feedback qualification reads over original settlement receipts Signed-off-by: lusendong.6789 Co-authored-by: TRAE CLI --- ...hanism-convergence-and-learning-loop-v0.md | 2 ++ ...-convergence-and-learning-loop-v0.zh-CN.md | 2 ++ .../test_material_feedback_checkpoint.py | 20 ++++++++++++++----- 3 files changed, 19 insertions(+), 5 deletions(-) diff --git a/docs/architecture/rfcs/mechanism-convergence-and-learning-loop-v0.md b/docs/architecture/rfcs/mechanism-convergence-and-learning-loop-v0.md index 3a4439064c..5d3ab25390 100644 --- a/docs/architecture/rfcs/mechanism-convergence-and-learning-loop-v0.md +++ b/docs/architecture/rfcs/mechanism-convergence-and-learning-loop-v0.md @@ -346,6 +346,8 @@ 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. + The first task needs an actual feedback or method-choice requirement. Reuse complete existing paths; real consumers must demonstrate gaps before repairing them rather than manufacturing a failure for the example. Experiments, training and procedural publication retain original authority. This document allocates neither another lane's quota nor a prescribed PR count. ## 12. Consequential choices to confirm diff --git a/docs/architecture/rfcs/mechanism-convergence-and-learning-loop-v0.zh-CN.md b/docs/architecture/rfcs/mechanism-convergence-and-learning-loop-v0.zh-CN.md index ea705bbd32..593652a636 100644 --- a/docs/architecture/rfcs/mechanism-convergence-and-learning-loop-v0.zh-CN.md +++ b/docs/architecture/rfcs/mechanism-convergence-and-learning-loop-v0.zh-CN.md @@ -324,6 +324,8 @@ host Turn。因此这些服务检查不能取得普通 PostgreSQL 反馈 Turn 和仅一次重放结算。这修复规划到写回的组合边界;安装态切换、真实模型采用 及成果/完整成本资格仍开放。 +既有反馈资格消费者通过已结算结果的不可变 `result_details` reader 读取被延后展示的 Run 路径,不再假设诊断字段总在内联结果中。公开读取仅选择原路径,保留 Vision、反馈、验收及只结算一次的断言。普通组合结算验证运行时负责的扣额;规划 checkpoint 按返回的 Agent 负责命令结算。File/SQLite 源码与组合路径对照资格化该 reader 迁移;脚本执行仍不同于模型采用及收益。 + 首个任务须确有反馈或方法选择需求。已有链完整时直接复用;有缺口时由真实消费者证明并修复,不为配合示例制造失败。运行实验、训练模型和发布过程各沿原权限,本文不占用其他 lane 配额或预设 PR 数。 ## 12. 待确认的关键选择 diff --git a/tests/control_plane/test_material_feedback_checkpoint.py b/tests/control_plane/test_material_feedback_checkpoint.py index 087027a989..6b1fc12012 100644 --- a/tests/control_plane/test_material_feedback_checkpoint.py +++ b/tests/control_plane/test_material_feedback_checkpoint.py @@ -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) @@ -149,14 +151,21 @@ def read_stage(command): assert fixture._spend_run_count(runtime) == 0 refreshed = execute(result_command, validated_progress="route_feedback_verified", scale="implementation", outcome="outcome_progress", file=vision) - execute(result_command, validated_progress="route_feedback_verified", + replayed = execute(result_command, validated_progress="route_feedback_verified", scale="implementation", outcome="outcome_progress", file=vision) assert fixture._classification_count(runtime, "route_feedback_verified") == 1 - persisted = json.loads(Path(refreshed["json_path"]).read_text()) + # Settlement controls stay inline; the original Run path is diagnostic + # detail. Read that one field from the immutable source without admission. + detail = read_stage(refreshed["result_details"]["command"] + " --select /json_path") + assert detail["eof"] is True + selected = {row["pointer"]: row["value"] + for row in json.loads(detail["content"])["selections"]} + assert set(selected) == {"/json_path"} + persisted = json.loads(Path(selected["/json_path"]).read_text()) assert persisted["vision_checkpoint"]["delivery_boundary"] == "semantic_closeout" assert persisted["agent_vision"]["path_delta"]["evidence_refs"] == [evidence] - execute(plan["ordered_steps"][2]["command_template"]) - execute(plan["ordered_steps"][2]["command_template"]) + assert refreshed["quota_spend"]["appended"] is True + assert replayed["settlement_identity"] == refreshed["settlement_identity"] assert fixture._spend_run_count(runtime) == 1 retained_todo = cli("todo", "list", "--goal-id", fixture.GOAL_ID, "--todo-id", fixture.TODO_ID)["todo"] assert retained_todo["status"] == "open" and retained_todo["completion_validation_required"] @@ -215,6 +224,7 @@ def read_stage(command): validated_progress="route_comparison_decided", scale="implementation", outcome="outcome_progress") assert acknowledged["autonomous_replan_ack"]["semantic_delta"]["accepted"] execute(review_plan["ordered_steps"][2]["command_template"]) + assert fixture._spend_run_count(runtime) == 2 next_guard = cli("quota", "should-run", *binding, "--runtime-profile", "generic_cli", "--todo-id", fixture.TODO_ID, "--turn-instance-id", "route-feedback-2") assert next_guard["should_run"] and next_guard["selected_todo"]["todo_id"] == fixture.TODO_ID