From 5878d78441f5fd03ea1a2232c10114bc9caa97b1 Mon Sep 17 00:00:00 2001 From: "lusendong.6789" Date: Fri, 20 Nov 2026 23:20:00 +0800 Subject: [PATCH] refactor(quota): delegate stateless read selection to TypeScript owner Signed-off-by: lusendong.6789 Co-authored-by: TRAE CLI --- ...hanism-convergence-and-learning-loop-v0.md | 12 ++++ ...-convergence-and-learning-loop-v0.zh-CN.md | 9 +++ loopx/cli_commands/quota_capture.py | 21 +++---- .../quota/progressive_context.ts | 12 ++-- loopx/control_plane/quota/turn_envelope.ts | 11 +++- .../control_plane/test_context_first_read.py | 34 ++++++++-- .../test_saved_context_project.py | 62 +++++++++++++++++++ tests/control_plane_ts/turn_envelope.test.ts | 31 ++++++++++ 8 files changed, 167 insertions(+), 25 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 cecec7e793..3f8d2882d6 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,18 @@ 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. +**Source checkpoint: stateless read ownership (2026-11-20).** The stateless capture +adapter delegates its normal-work initial navigation to the existing TypeScript +Progressive owner through `context_select`; Python retains publication, byte +budgets and fallback. The invocation-only option leaves generic selection and +its validation order unchanged. Captured File/SQLite sources preserve their +original preparation and settlement facts after a later claim; selected display, +off and digest-refusal paths have immutable-base/current-candidate controls. +Existing wide-scope and note-reuse test callers carry the original captured lease +proof into their manual writeback, retaining pagination, recovery and once-only +settlement assertions. This retires a duplicate read classifier; full C1/C4/C9 +cutover, installed/native adoption and method/outcome benefit 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..c72216997d 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,15 @@ soft claim/hard lease 及历史反馈仅作上下文:保留独立验证的成 host Turn。因此这些服务检查不能取得普通 PostgreSQL 反馈 Turn 资格, 也不构成本切片新增执行 profile 的理由。 +**源码 checkpoint:无会话读回所有权(2026-11-20)。** 无会话捕获适配器通过 +`context_select` 将正常工作初始导航交给既有 TypeScript Progressive owner, +Python 保留发布、字节预算与 fallback。仅用于本次调用的选项保留通用选择及其 +校验顺序。File/SQLite 捕获在后续认领后仍保留原 preparation 与结算事实; +实际选中展示、关闭及摘要拒绝路径有不可变基线/当前候选对照。既有大 scope +与 note 复用测试调用将原捕获的 lease proof 带入手动写回,保留分页、恢复和 +只结算一次的断言。这退役一个重复读回分类器;完整 C1/C4/C9 切换、已安装/ +原生采用及方法/成果收益仍开放。 + 首个任务须确有反馈或方法选择需求。已有链完整时直接复用;有缺口时由真实消费者证明并修复,不为配合示例制造失败。运行实验、训练模型和发布过程各沿原权限,本文不占用其他 lane 配额或预设 PR 数。 ## 12. 待确认的关键选择 diff --git a/loopx/cli_commands/quota_capture.py b/loopx/cli_commands/quota_capture.py index ef2c636b09..298ca81b43 100644 --- a/loopx/cli_commands/quota_capture.py +++ b/loopx/cli_commands/quota_capture.py @@ -13,7 +13,6 @@ from typing import Any from ..control_plane.effect_runtime import EffectRuntimeRemoteError, EffectRuntimeStartupError -from ..control_plane.quota.effective_action import EffectiveAction from ..control_plane.quota.error_codes import QuotaCommandValidationError, QuotaDecisionTransportError from ..control_plane.quota.turn_envelope import ( COMPLETE_TURN_DECISION_VERSION, TURN_ENVELOPE_SCHEMA_VERSION, @@ -123,24 +122,22 @@ def pin_initial_selection(plan: dict[str, Any]) -> None: # metadata is optional and never a read/authority receipt. pass - interaction = current_document.get("interaction_contract") - channel = interaction.get("agent_channel") if isinstance(interaction, dict) else None - stateless_ready = ( + stateless_navigation = ( progressive_enabled and initial_read_plan is None and context_directory is None and not page_attached - and current_document.get("effective_action") == EffectiveAction.NORMAL_RUN.value - and current_document.get("normal_delivery_allowed") is True - and isinstance(channel, dict) and channel.get("delivery_allowed") is True ) - if stateless_ready: + if stateless_navigation: try: navigation_plan = _turn_envelope_result("context_select", context=current_document, - select=[""], list_fields=True, include_initial_read_plan=True) + select=[""], list_fields=True, include_initial_read_plan=True, normal_work_initial_read=True) except (EffectRuntimeRemoteError, EffectRuntimeStartupError): pass else: selection = navigation_plan.get("initial_read_plan") - initial_read_plan = {"initial": selection is not None, - "plan": navigation_plan if selection is None else selection} + if selection is not None: + initial_read_plan = {"initial": True, "plan": selection} + else: + field_index = _context_index_fields(current_document, navigation_plan["selections"][0]["children"]) + initial_read_pointers = navigation_plan.get("initial_read_pointers") if progressive_enabled and initial_read_plan is not None: try: @@ -152,7 +149,7 @@ def pin_initial_selection(plan: dict[str, Any]) -> None: except (EffectRuntimeRemoteError, EffectRuntimeStartupError): # Optional discovery cannot invalidate the immutable file reference. pass - elif progressive_enabled and not stateless_first_read and not stateless_ready: + elif progressive_enabled and not stateless_first_read and not stateless_navigation: try: plan = _turn_envelope_result("context_select", context=current_document, select=[""], list_fields=True) except (EffectRuntimeRemoteError, EffectRuntimeStartupError): diff --git a/loopx/control_plane/quota/progressive_context.ts b/loopx/control_plane/quota/progressive_context.ts index 7ade3bce89..1b0da2e709 100644 --- a/loopx/control_plane/quota/progressive_context.ts +++ b/loopx/control_plane/quota/progressive_context.ts @@ -39,12 +39,16 @@ function orderedSettlementSteps(plan: JsonObject | null | undefined): unknown[] && Array.isArray(plan.ordered_steps) ? plan.ordered_steps : undefined; } +export function normalWorkReadContext(context: JsonObject): boolean { + return context.effective_action === EffectiveAction.NORMAL_RUN && context.normal_delivery_allowed === true + && jsonObject(jsonObject(context.interaction_contract)?.agent_channel)?.delivery_allowed === true; +} + function readySettlementIdentity(context: JsonObject, interaction: JsonObject, plan: JsonObject | null | undefined): JsonObject | undefined { const cli = jsonObject(interaction.cli_channel), prepared = jsonObject(cli?.execution_preparation); const identity = jsonObject(plan?.identity); - return context.effective_action === EffectiveAction.NORMAL_RUN && context.normal_delivery_allowed === true - && jsonObject(interaction.agent_channel)?.delivery_allowed === true && cli?.selection_required !== true + return normalWorkReadContext(context) && cli?.selection_required !== true && prepared?.state === "ready" && typeof identity?.effect_id === "string" && identity.effect_id.length > 0 && typeof identity.todo_id === "string" && prepared.todo_id === identity.todo_id && jsonObject(context.selected_todo)?.todo_id === identity.todo_id @@ -1004,8 +1008,8 @@ function initialContextReadGroups(context: JsonObject, decisionFields: readonly const selectingBeforeWork = context.ok === true && context.should_run === true && channel?.delivery_allowed === false && cli?.spend_allowed_now === false && cli.spend_after_validation === false && hasUnboundActionSelection(cli); - const normalWork = context.effective_action === EffectiveAction.NORMAL_RUN && context.normal_delivery_allowed === true - && (channel?.delivery_allowed === true || selectingBeforeWork); + const normalWork = normalWorkReadContext(context) || context.effective_action === EffectiveAction.NORMAL_RUN + && context.normal_delivery_allowed === true && selectingBeforeWork; // The same pending owner read applies before a required replan. Delivery // remains disabled while that review is being settled. const replanningBeforeWork = replanRequired && context.ok === true && context.should_run === true diff --git a/loopx/control_plane/quota/turn_envelope.ts b/loopx/control_plane/quota/turn_envelope.ts index a39e9e5ba9..5cf95290b8 100644 --- a/loopx/control_plane/quota/turn_envelope.ts +++ b/loopx/control_plane/quota/turn_envelope.ts @@ -1,7 +1,7 @@ import {EXECUTION_PREPARATION_SCHEMA_VERSION} from "../work_items/execution_preparation.ts"; import {leaseEpoch} from "../work_items/task_lease_record.ts"; import {capturedContextSelection} from "./context_selection.ts"; -import {contextReadSectionDigests, initialContextReadPointers, prepareProgressiveContext, prepareProgressiveContextDelivery, +import {contextReadSectionDigests, initialContextReadPointers, normalWorkReadContext, prepareProgressiveContext, prepareProgressiveContextDelivery, progressiveContextPlan, scopedReplanYardstickReversal, type PreparationScopeDetail, type ReusableExactBody} from "./progressive_context.ts"; import type { LoopXTurnRouteValue } from "../turn_driver/turn_contract_generated.ts"; @@ -2390,10 +2390,15 @@ function turnPlanInspectionPaths(decision: JsonObject, route: "ready_for_host" | /** Navigation over captured facts, never a summary or a source-read receipt. */ function capturedDecisionSelection(request: JsonObject): JsonObject { + const normalOnly = request.normal_work_initial_read === undefined ? false + : requireBoolean(request.normal_work_initial_read, "normal_work_initial_read"); + const context = normalOnly ? requireJsonObject(request.context, "captured context") : undefined; + const scoped = context && !normalWorkReadContext(context) + ? {...request, include_initial_read_plan: false} : request; const initial = request.initial_read === true || request.list_fields === true && Array.isArray(request.select) && request.select.length === 1 && request.select[0] === ""; - return capturedContextSelection(request, initial ? initialContextReadPointers( - requireJsonObject(request.context, "captured context"), INITIAL_CONTEXT_DECISION_FIELDS) : []); + return capturedContextSelection(scoped, initial ? initialContextReadPointers( + context ?? requireJsonObject(request.context, "captured context"), INITIAL_CONTEXT_DECISION_FIELDS) : []); } function replanCliView(payload: JsonObject, identity: ReplanValueIdentity = canonicalHash, diff --git a/tests/control_plane/test_context_first_read.py b/tests/control_plane/test_context_first_read.py index 77c90bee54..643469e03c 100644 --- a/tests/control_plane/test_context_first_read.py +++ b/tests/control_plane/test_context_first_read.py @@ -748,15 +748,19 @@ def read(command): if warm: prior = capture("wide-prior") _, prior_ref = read_context_read_reference(prior["recovery"]["reference_file"]) - rows = json.loads(Path(prior_ref["path"]).read_bytes())["interaction_contract"]["agent_channel"]["work_context"]["sources"] + prior_source = json.loads(Path(prior_ref["path"]).read_bytes()) + rows = prior_source["interaction_contract"]["agent_channel"]["work_context"]["sources"] index = next(i for i, source in enumerate(rows) if source["source"] == "goal_state") body_pointer = f"/interaction_contract/agent_channel/work_context/sources/{index}/content/text" prior_pages, prior_facts = read(prior["recovery"]["command"] + " --select " + body_pointer) assert narrative in prior_facts[body_pointer] deliver(journal, event, prior_pages) + proof = prior_source["interaction_contract"]["cli_channel"].get("execution_preparation", {}).get("lease_proof") + proof_args = (["--task-lease-idempotency-key", proof["idempotency_key"], + "--task-lease-expected-version", str(proof["expected_version"])] if proof else []) cli("refresh-state", *binding, "--turn-instance-id", "wide-prior", "--classification", "fixture_verified", "--delivery-batch-scale", "implementation", "--delivery-outcome", "outcome_progress", - "--delivery-boundary", "in_flight_continuation", "--no-global-sync", "--suppress-external-sinks") + "--delivery-boundary", "in_flight_continuation", "--no-global-sync", "--suppress-external-sinks", *proof_args) cli("quota", "spend-slot", *binding, "--turn-instance-id", "wide-prior", "--slots", "1", "--source", "heartbeat", "--execute") scopes = [*scopes[:-1], "docs/areas/current-fixture-scope/**"] @@ -2058,16 +2062,25 @@ def cli(*args, registry_path=registry): def binding(turn): return ("--goal-id", GOAL_ID, "--agent-id", AGENT_ID, "--todo-id", TODO_ID, "--turn-instance-id", turn) + proofs = {} + def capture(turn, registry_path=registry): - return cli("quota", "should-run", "--codex-app", "--context-delivery", "auto", "--delta-delivery", "auto", + view = cli("quota", "should-run", "--codex-app", "--context-delivery", "auto", "--delta-delivery", "auto", *binding(turn), "--decision-output-root", str(captures), "--codex-context-dir", str(journal), registry_path=registry_path) + _, reference = read_context_read_reference(view["recovery"]["reference_file"]) + source = json.loads(Path(reference["path"]).read_bytes()) + proofs[turn] = source["interaction_contract"]["cli_channel"]["execution_preparation"]["lease_proof"] + return view def settle(turn, registry_path=registry): + proof = proofs[turn] cli("refresh-state", *binding(turn), "--classification", "fixture_validated", "--delivery-batch-scale", "implementation", "--delivery-outcome", "outcome_progress", "--delivery-boundary", "in_flight_continuation", "--delivery-workspace-path", str(project), - "--no-global-sync", "--suppress-external-sinks", registry_path=registry_path) + "--no-global-sync", "--suppress-external-sinks", + "--task-lease-idempotency-key", proof["idempotency_key"], + "--task-lease-expected-version", str(proof["expected_version"]), registry_path=registry_path) spent = cli("quota", "spend-slot", *binding(turn), "--slots", "1", "--source", "heartbeat", "--execute", registry_path=registry_path) assert spent["appended"] @@ -2222,16 +2235,25 @@ def binding(turn, todo_id=TODO_ID): return ("--goal-id", GOAL_ID, "--agent-id", AGENT_ID, "--todo-id", todo_id, "--turn-instance-id", turn) + proofs = {} + def capture(turn, todo_id=TODO_ID): - return cli("quota", "should-run", "--codex-app", "--context-delivery", "on", + view = cli("quota", "should-run", "--codex-app", "--context-delivery", "on", "--delta-delivery", "auto", *binding(turn, todo_id), "--decision-output-root", str(captures), "--codex-context-dir", str(journal)) + _, reference = read_context_read_reference(view["recovery"]["reference_file"]) + source = json.loads(Path(reference["path"]).read_bytes()) + proofs[turn] = source["interaction_contract"]["cli_channel"]["execution_preparation"]["lease_proof"] + return view def settle(turn): + proof = proofs[turn] cli("refresh-state", *binding(turn), "--classification", "fixture_validated", "--delivery-batch-scale", "implementation", "--delivery-outcome", "outcome_progress", "--delivery-boundary", "in_flight_continuation", "--delivery-workspace-path", str(project), - "--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"])) spent = cli("quota", "spend-slot", *binding(turn), "--slots", "1", "--source", "heartbeat", "--execute") assert spent["appended"] diff --git a/tests/control_plane/test_saved_context_project.py b/tests/control_plane/test_saved_context_project.py index 084caa7f56..fd6b0f48c5 100644 --- a/tests/control_plane/test_saved_context_project.py +++ b/tests/control_plane/test_saved_context_project.py @@ -12,6 +12,68 @@ from tests.control_plane.codex_checkpoint_fixture import reference_metadata_oracle as machine_reference_oracle +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_stateless_saved_work_keeps_the_captured_preparation_and_readback(tmp_path, monkeypatch, provider): + from tests.control_plane.canonical_authority_fixture import isolate_sqlite_runtime + from tests.control_plane.codex_checkpoint_fixture import read_cli_policy_payload + from tests.control_plane.test_quota_settlement_cli import ( + AGENT_ID, GOAL_ID, TODO_ID, _heartbeat_receipt_count, _initialize_fixture_authority, + _spend_run_count, _write_fixture, + ) + + isolate_sqlite_runtime(tmp_path, monkeypatch) + monkeypatch.delenv("CODEX_THREAD_ID", raising=False) + project, runtime, registry = _write_fixture(tmp_path) + _initialize_fixture_authority(project, runtime, provider=provider, handoff_mode="hard_lease") + turn = "stateless-read-scope" + binding = ["--goal-id", GOAL_ID, "--agent-id", AGENT_ID, "--todo-id", TODO_ID, + "--turn-instance-id", turn] + captures = [] + for phase in ("unprepared", "ready"): + if phase == "ready": + code, claim = _run_cli(registry, runtime, "todo", "claim", "--goal-id", GOAL_ID, + "--todo-id", TODO_ID, "--agent-id", AGENT_ID, "--claimed-by", AGENT_ID, cwd=project) + assert code == 0 and claim["ok"], claim + directory = tmp_path / phase + code, source = _run_cli(registry, runtime, "quota", "should-run", *binding, "--complete-turn", + "--context-delivery", "off", "--decision-output-dir", str(directory), cwd=project) + assert code == 0, source + assert source["normal_delivery_allowed"] is (phase == "ready") + captures.append(directory / "decision.json") + + state = project / f".codex/goals/{GOAL_ID}/ACTIVE_GOAL_STATE.md" + original_state = state.read_bytes() + original_receipts = _heartbeat_receipt_count(runtime, turn) + for path in captures: + raw = path.read_bytes() + original = json.loads(raw) + digest = hashlib.sha256(raw).hexdigest() + args = ["quota", "context-project", "--capture-file", str(path), "--capture-sha256", digest, + "--goal-id", GOAL_ID, "--agent-id", AGENT_ID, "--turn-instance-id", turn, + "--context-delivery", "auto", "--delta-delivery", "off"] + code, view = _run_cli(registry, runtime, *args, cwd=project) + assert code == 0 and view["ok"], view + presented = read_cli_policy_payload(json.dumps(view), returncode=code) + assert presented["goal_id"] == GOAL_ID + assert presented["normal_delivery_allowed"] is original["normal_delivery_allowed"] + assert presented["heartbeat_receipt"]["settlement_identity"] == original["heartbeat_receipt"]["settlement_identity"] + current = presented["interaction_contract"]["cli_channel"] + captured = original["interaction_contract"]["cli_channel"] + assert current["execution_preparation"] == captured["execution_preparation"] + assert ("settlement_plan" in current) == ("settlement_plan" in captured) + assert current.get("settlement_plan") == captured.get("settlement_plan") + # A historical unprepared source stays unprepared after the live claim; + # presentation cannot adopt today's lease or perform another admission. + assert path.read_bytes() == raw + bad = args.copy() + bad[bad.index("--capture-sha256") + 1] = "0" * 64 + code, rejected = _run_cli(registry, runtime, *bad, cwd=project) + assert code != 0 and rejected["ok"] is False, rejected + assert state.read_bytes() == original_state + assert _heartbeat_receipt_count(runtime, turn) == original_receipts + assert _spend_run_count(runtime) == 0 + + @pytest.mark.parametrize("failure", [None, "digest", "goal", "agent", "turn", "symlink", "object"]) @pytest.mark.parametrize("setting", [None, "auto", "off"]) def test_saved_projection_checks_original_before_any_publication(tmp_path, failure, setting): diff --git a/tests/control_plane_ts/turn_envelope.test.ts b/tests/control_plane_ts/turn_envelope.test.ts index 42e8a4e754..c246ac3da3 100644 --- a/tests/control_plane_ts/turn_envelope.test.ts +++ b/tests/control_plane_ts/turn_envelope.test.ts @@ -26,6 +26,37 @@ import {projectQuotaDiagnostics, referenceQuotaSummaryLanes, resolveQuotaSummary import { controllerRequest } from "../../loopx/control_plane/turn_driver/loop_controller.ts"; import {turnScopedCliSettlementPlan} from "../../loopx/control_plane/quota/settlement_plan.ts"; +test("normal-work initial navigation stays scoped while other reads keep discovery", () => { + const source = payload(); + source.normal_delivery_allowed = true; + const request = {operation: "context_select", select: [""], list_fields: true, include_initial_read_plan: true}; + for (const change of [null, "action", "delivery", "channel", "missing_channel"]) { + const context = structuredClone(source); + if (change === "action") context.effective_action = "wait"; + if (change === "delivery") context.normal_delivery_allowed = false; + const interaction = context.interaction_contract as JsonObject; + if (change === "channel") (interaction.agent_channel as JsonObject).delivery_allowed = false; + if (change === "missing_channel") delete interaction.agent_channel; + const before = structuredClone(context); + const scoped = evaluateTurnEnvelope({...request, context, normal_work_initial_read: true}); + if (change === null) assert.ok(scoped.initial_read_plan); + else { + assert.equal(scoped.initial_read_plan, undefined); + assert.equal((scoped.selections as JsonObject[])[0].pointer, ""); + assert.ok(Array.isArray(scoped.initial_read_pointers)); + } + assert.ok(evaluateTurnEnvelope({...request, context}).initial_read_plan); + assert.deepEqual(evaluateTurnEnvelope({...request, context, normal_work_initial_read: false}), + evaluateTurnEnvelope({...request, context})); + assert.deepEqual(context, before); + } + assert.throws(() => evaluateTurnEnvelope({...request, context: source, normal_work_initial_read: "true"}), + /normal_work_initial_read must be a boolean/); + for (const scope of [{}, {normal_work_initial_read: false}]) + assert.throws(() => evaluateTurnEnvelope({operation: "context_select", context: null, + select: ["/goal_id"], recover_selection_errors: "true", ...scope}), /recover-selection-errors must be boolean/); +}); + test("complete captures reuse progressive presentation only after source validation", () => { const source = payload(); source.planning_horizon = {core_goal: {acceptance_contract: {outcome_requirements: {