diff --git a/docs/architecture/rfcs/controller-executor-unified-contract-v0/contract-and-context.md b/docs/architecture/rfcs/controller-executor-unified-contract-v0/contract-and-context.md index 375aa960ca..764d33c21a 100644 --- a/docs/architecture/rfcs/controller-executor-unified-contract-v0/contract-and-context.md +++ b/docs/architecture/rfcs/controller-executor-unified-contract-v0/contract-and-context.md @@ -574,6 +574,14 @@ must include matched baseline/head real-provider outcomes, rejection sensitivity and packaged recovery. Adoption reduces the parent's diff only after the slice lands on main and main is integrated into the parent; opening a PR does not. +Current v1 Host dispatch, model input and session-lineage reads validate the +complete source and capture header directly. The same TypeScript rules still +check selection, choose the primary action and interpret checkpointed write +approval. Codex and the structured Host renderers keep the captured material +references in the final input. The historical executor projection still proves +transitional v0/v1 pairs and supports recorded recovery. Plan and effect +consumers that still use that projection have separate retirement conditions. + For each normal, selection, replan, wait, recovery and capability-off fixture, check independently authored obligations at **three boundaries**: composed contract, reconstructed delivery, and final model input plus required material diff --git a/docs/architecture/rfcs/controller-executor-unified-contract-v0/contract-and-context.zh-CN.md b/docs/architecture/rfcs/controller-executor-unified-contract-v0/contract-and-context.zh-CN.md index e0fc5b3656..066e608259 100644 --- a/docs/architecture/rfcs/controller-executor-unified-contract-v0/contract-and-context.zh-CN.md +++ b/docs/architecture/rfcs/controller-executor-unified-contract-v0/contract-and-context.zh-CN.md @@ -421,6 +421,11 @@ reader;这个分阶段边界保留普通 quota writer 和 thin-heartbeat 的 成果与完整成本对照。评审须包含匹配基线/候选版本的真实 provider 成果、拒绝敏感性和 打包恢复。只有切片合入 main、父提案集成 main 后,父提案的差异才会减少;开 PR 不算。 +当前 v1 Host 的派发预检、模型输入和会话身份读回直接校验完整来源与捕获标头。选择 +校验、主动作判定和写权限审批仍由同一套 TypeScript 规则处理。Codex 与结构化 Host +在最终输入中保留原捕获的材料引用。历史执行投影继续校验过渡期的 v0/v1 成对记录并 +支持已记录工作的恢复。仍依赖该投影的 plan 和 effect 消费方有各自的退役条件。 + 对 normal、selection、replan、wait、recovery 和 capability-off 的每个 fixture, 在**三个边界**核对独立编写的义务:组合契约、重建交付、最终模型输入及必需材料读取。 包含旧 action signature 未覆盖的源变化、必需来源缺失、不兼容消费者和结算响应丢失。 diff --git a/loopx/control_plane/quota/turn_envelope.py b/loopx/control_plane/quota/turn_envelope.py index f62a709a3b..7807ffa16e 100644 --- a/loopx/control_plane/quota/turn_envelope.py +++ b/loopx/control_plane/quota/turn_envelope.py @@ -148,7 +148,9 @@ def turn_plan_host_source(request: Mapping[str, Any]) -> Mapping[str, Any]: def captured_turn_host_input(request: Mapping[str, Any]) -> dict[str, Any]: - """Transport original-reader metadata after complete-source validation.""" + """Use the checked wire or transfer original-reader metadata from v0.""" + if "turn_envelope" not in request: + return {**request, "schema_version": COMPLETE_TURN_HOST_REQUEST_SCHEMA} envelope = _wire_mapping(request.get("turn_envelope")) model_input = {**{key: value for key, value in request.items() if key != "turn_envelope"}, "schema_version": COMPLETE_TURN_HOST_REQUEST_SCHEMA} @@ -189,14 +191,15 @@ def complete_turn_host_source( assert_turn_host_request_version(request) if "work_contract" not in request: return None - header = ({"complete_host_request": {key: request[key] for key in ( - "schema_version", "turn_key", "source_decision_hash", "detail_ref", - ) if key in request}} if request.get("schema_version") == COMPLETE_TURN_HOST_REQUEST_SCHEMA else {}) - # Identity-only current callers need no executor adapter. Keep an explicit - # adapter, even a damaged one, on the typed owner's full Host validation. - adapter = ({"envelope": _wire_mapping(request.get("turn_envelope"))} - if "turn_envelope" in request or operation != "complete_host_lineage" else {}) - checked = _turn_envelope_result(operation, payload=request["work_contract"], **adapter, **header, + wire = {} + if request.get("schema_version") == COMPLETE_TURN_HOST_REQUEST_SCHEMA: + wire["complete_host_request"] = {key: request[key] for key in ( + "schema_version", "turn_key", "source_decision_hash", "detail_ref", + ) if key in request} + elif "turn_envelope" in request or operation != "complete_host_lineage": + # An explicit historical adapter still requires full validation. + wire["envelope"] = _wire_mapping(request.get("turn_envelope")) + checked = _turn_envelope_result(operation, payload=request["work_contract"], **wire, **({"recorded_capability_result": True} if recorded_capability_result else {}), **({"include_model_context": True} if include_model_context else {}), **({"include_session_lineage": True} if include_session_lineage else {})) diff --git a/loopx/control_plane/quota/turn_envelope.ts b/loopx/control_plane/quota/turn_envelope.ts index 71b56c8eab..c46bc19203 100644 --- a/loopx/control_plane/quota/turn_envelope.ts +++ b/loopx/control_plane/quota/turn_envelope.ts @@ -34,6 +34,7 @@ import { projectTurnStartUnavailableContext } from "../capability_hooks.ts"; import { jsonObject, requireBoolean, requireJsonObject, requireNonEmptyString, requireStringLiteral, sourceNumberTokens } from "../runtime_decode.ts"; import { projectPendingCapabilityIntent } from "../work_items/pending_capability_intent.ts"; +import { assertActionSelectionConsistency } from "../work_items/action_selection_admission.ts"; import { INTERACTION_CONTRACT_SCHEMA_VERSION, assertGoalContextDelivered, assertInteractionRequiredReads, capturedTodoTextSha256, decodeInteractionContract, hasUnboundActionSelection, projectInteractionRequiredReads, selectedWorkTodo, selectedWorkTodoId, USER_CHANNEL_NOTIFICATION_POLICIES } from "../work_items/interaction_contract.ts"; @@ -1136,6 +1137,19 @@ function requiredReads(interaction: JsonObject, payload: JsonObject): JsonObject return result; } +function checkpointedBoundaryAuthority(source: JsonObject): JsonObject | null { + const approved = object(source.checkpointed_boundary_authority); + const approvedScopes = Array.isArray(approved.active_write_scope) + ? approved.active_write_scope.filter((scope): scope is string => + typeof scope === "string" && scope.length > 0) + : []; + if (approved.schema_version !== "checkpointed_boundary_authority_v0" || + !Number.isInteger(approved.active_count) || Number(approved.active_count) <= 0 || + approvedScopes.length === 0) return null; + return {schema_version: approved.schema_version, active_count: approved.active_count, + active_write_scope: approvedScopes}; +} + export function projectTurnBoundary(payload: JsonObject): JsonObject { const source = object(payload.goal_boundary); const result: JsonObject = { @@ -1156,20 +1170,8 @@ export function projectTurnBoundary(payload: JsonObject): JsonObject { } // Carry the already resolved approval from quota; dropping it leaves only // the bootstrap approval requirement and strands authorized execution. - const approved = object(source.checkpointed_boundary_authority); - const approvedScopes = Array.isArray(approved.active_write_scope) - ? approved.active_write_scope.filter((scope): scope is string => - typeof scope === "string" && scope.length > 0) - : []; - if (approved.schema_version === "checkpointed_boundary_authority_v0" - && Number.isInteger(approved.active_count) && Number(approved.active_count) > 0 - && approvedScopes.length > 0) { - result.checkpointed_boundary_authority = { - schema_version: approved.schema_version, - active_count: approved.active_count, - active_write_scope: approvedScopes, - }; - } + const approved = checkpointedBoundaryAuthority(source); + if (approved) result.checkpointed_boundary_authority = approved; // Effective automation is already resolved for this Goal/Agent. Keep the // shared participation facts, not private config, diagnostics or recall. const memory = object(object(source.capabilities).reward_memory); @@ -1355,11 +1357,28 @@ function contractCapsule(payload: JsonObject): JsonObject { return capsule; } +function turnPrimaryAction(payload: JsonObject, reads: JsonObject | null) { + const interaction = object(payload.interaction_contract); + const agentChannel = object(interaction.agent_channel); + const cliChannel = object(interaction.cli_channel); + const turnBindingRequired = cliChannel.turn_binding_required === true; + const capabilityIntent = payload.effective_action === EffectiveAction.GOVERNED_CAPABILITY_INTENT + ? projectPendingCapabilityIntent(payload.pending_capability_intent) : null; + // A governed capability action has already won the live decision. Stale + // replan/host-reentry projections must not replace its exact command. + const replanPacket = capabilityIntent || turnBindingRequired ? null : replanActionPacket(payload, reads); + const replanSettlementOnly = object(payload.replan_action_packet).settlement_only === true; + const primaryAction = scalarString(agentChannel.primary_action, "agent_channel.primary_action").trim(); + return {capabilityIntent, turnBindingRequired, replanPacket, replanSettlementOnly, + primaryAction: replanPacket && !replanSettlementOnly + ? reads?.review ?? "produce one required semantic outcome" + : primaryAction || null}; +} + function actionProjection(payload: JsonObject, deferSettlement = true, precision?: ReplanReadPrecision, verifiedSourceHash?: string): JsonObject { // Reader identity belongs to the original captured source. Expanding shared // diagnostic lanes for the historical executor must not hash that local view. - const reads = payload.effective_action === EffectiveAction.GOVERNED_CAPABILITY_INTENT - ? null : replanReadCommands(payload, payload.replan_read_path, payload.replan_read_argv ?? ["loopx"], verifiedSourceHash); + const reads = replanReadCommands(payload, payload.replan_read_path, payload.replan_read_argv ?? ["loopx"], verifiedSourceHash); if (payload.schema_version === COMPLETE_TURN_DECISION_VERSION) payload = resolveQuotaSummaryLanes(payload); const agentIdentity = object(payload.agent_identity); const semanticAgentId = scalarString( @@ -1373,13 +1392,8 @@ function actionProjection(payload: JsonObject, deferSettlement = true, precision const interaction = object(payload.interaction_contract); const agentChannel = object(interaction.agent_channel); const cliChannel = object(interaction.cli_channel); - const turnBindingRequired = cliChannel.turn_binding_required === true; - const capabilityIntent = payload.effective_action === EffectiveAction.GOVERNED_CAPABILITY_INTENT - ? projectPendingCapabilityIntent(payload.pending_capability_intent) : null; - // A governed capability action has already won the live decision. Stale - // replan/host-reentry projections must not replace its exact command. - const replanPacket = capabilityIntent || turnBindingRequired ? null : replanActionPacket(payload, reads); - const replanSettlementOnly = object(payload.replan_action_packet).settlement_only === true; + const {capabilityIntent, turnBindingRequired, replanPacket, replanSettlementOnly, primaryAction} = + turnPrimaryAction(payload, reads); const recommendedAction = replanPacket ? replanSettlementOnly ? scalarString(object(object(payload.replan_action_packet).writeback_contract).rule, "replan settlement rule") @@ -1388,12 +1402,9 @@ function actionProjection(payload: JsonObject, deferSettlement = true, precision : text(turn.observation.recommended_action || payload.recommended_action, 480); // The signed host action is executable authority, not a display summary. // Budget diagnostics may warn on long commands but must not cut them. - const primaryAction = scalarString(agentChannel.primary_action, "agent_channel.primary_action").trim(); const action: JsonObject = { recommended_action: recommendedAction, - primary_action: replanPacket && !replanSettlementOnly - ? reads?.review ?? "produce one required semantic outcome" - : primaryAction || null, + primary_action: primaryAction, must_attempt: Boolean(agentChannel.must_attempt), delivery_allowed: Boolean(agentChannel.delivery_allowed), quiet_noop_allowed: Boolean(agentChannel.quiet_noop_allowed), @@ -1816,15 +1827,20 @@ function requireCompleteHostHeader(request: JsonObject, decision: JsonObject): J return header; } -/** One checked source for model input and transport session identity. The - * historical effect adapter may remain in the request during migration, but it - * cannot redirect the complete contract to another Goal, Agent or work item. */ -export function completeHostSource(request: JsonObject): {decision: JsonObject; projection: JsonObject} { +function requireCompleteHostDecision(request: JsonObject): JsonObject { const decision = requireCompleteTurnDecision(request.payload, request.source_number_tokens); + requireCompleteHostHeader(request, decision); + return decision; +} + +/** Check a source for consumers that still use the executor projection. An + * explicit historical adapter cannot redirect the admitted work or identity. */ +export function completeHostSource(request: JsonObject): {decision: JsonObject; projection: JsonObject} { if (Object.hasOwn(request, "complete_host_request")) { - requireCompleteHostHeader(request, decision); + const decision = requireCompleteHostDecision(request); return {decision, projection: turnActionProjection(decision)}; } + const decision = requireCompleteTurnDecision(request.payload, request.source_number_tokens); const envelope = requireJsonObject(request.envelope, "complete Turn executor envelope"); assertTurnEnvelopeConsumerVersion(envelope); const signature = object(envelope.action_signature); @@ -1963,7 +1979,11 @@ export function completePlanningFacts(request: JsonObject): JsonObject { } function completeHostDecision(request: JsonObject): JsonObject { - return completeHostSource(request).decision; + if (!Object.hasOwn(request, "complete_host_request")) return completeHostSource(request).decision; + const decision = requireCompleteHostDecision(request); + // Keep the selection refusal previously reached through the quota interpreter. + assertActionSelectionConsistency(decision, object(decision.interaction_contract)); + return decision; } function checkedContextPresentationSource(request: JsonObject): JsonObject { @@ -2610,15 +2630,21 @@ export function evaluateTurnEnvelope(value: unknown): JsonObject { typeof request.include_model_context !== "boolean") { throw new EffectRuntimeRequestError("Host model-context projection option must be a boolean"); } - const {decision, projection} = completeHostSource(request); - if (operation === "host_dispatch_context" && Object.keys(object(projection.replan_action_packet)).length === 0) { + // The current wire carries complete work facts. Only transitional requests + // need the historical executor projection to prove agreement with them. + const legacy = Object.hasOwn(request, "complete_host_request") ? null : completeHostSource(request); + const decision = legacy?.decision ?? completeHostDecision(request); + const {primaryAction, replanPacket} = legacy + ? {primaryAction: object(legacy.projection.action).primary_action ?? null, + replanPacket: legacy.projection.replan_action_packet ?? null} + : turnPrimaryAction(decision, replanReadCommands(decision)); + if (operation === "host_dispatch_context" && replanPacket === null) { assertGoalContextDelivered(object(object(decision.interaction_contract).agent_channel)); } // The caller already holds this exact checked source. Return only the // resolved facts it needs, not another full copy over the transport. - return {primary_action: object(projection.action).primary_action ?? null, - replan_admitted: Object.keys(object(projection.replan_action_packet)).length > 0, - checkpointed_write_approval: Object.hasOwn(object(projection.boundary), "checkpointed_boundary_authority"), + return {primary_action: primaryAction, replan_admitted: replanPacket !== null, + checkpointed_write_approval: checkpointedBoundaryAuthority(object(decision.goal_boundary)) !== null, execution_profile_present: Object.keys(object(decision.execution_profile)).length > 0, ...(request.include_model_context === true ? {model_context_schema_version: "loopx_turn_model_context_v0", diff --git a/tests/control_plane/test_complete_host_request.py b/tests/control_plane/test_complete_host_request.py index 99d7a20f61..32ecc13eab 100644 --- a/tests/control_plane/test_complete_host_request.py +++ b/tests/control_plane/test_complete_host_request.py @@ -13,6 +13,7 @@ from loopx.control_plane.turn_driver.host_candidate import ( complete_host_input, extract_turn_authority, extract_turn_work_identity, ) +from tests.control_plane.host_process_fixture import assert_host_task_context from tests.control_plane.test_turn_host_decision_capture import ( complete_host_request as complete_host_request, ) @@ -44,7 +45,9 @@ def test_complete_wire_roundtrip_has_one_source_and_original_readers(complete_ho assert extract_turn_work_identity(wire) == extract_turn_work_identity(legacy) assert extract_turn_authority(wire)["primary_action"] == extract_turn_authority(legacy)["primary_action"] rendered = json.loads(_prompt(wire).split("Turn request:\n", 1)[1]) - assert rendered == wire + assert_host_task_context(rendered, wire["work_contract"]) + assert rendered["detail_ref"] == wire["detail_ref"] + assert rendered["turn_key"] == wire["turn_key"] assert internal == before @@ -95,7 +98,9 @@ def test_open_goal_acceptance_judgment_keeps_its_read_audit( assert "vision_continuation_audit" not in instructions assert "Do not write LoopX state" in instructions assert "owns those effects" in instructions - assert json.JSONDecoder().raw_decode(encoded)[0] == wire + model_input = json.JSONDecoder().raw_decode(encoded)[0] + assert_host_task_context(model_input, wire["work_contract"]) + assert model_input["detail_ref"] == wire["detail_ref"] assert request == before @@ -118,7 +123,9 @@ def test_complete_host_keeps_notification_and_execution_boundaries( assert "alternatives and capability intents do not override admission or scope" in instructions assert "Do not write LoopX state" in instructions assert "owns those effects" in instructions - assert json.JSONDecoder().raw_decode(encoded)[0] == wire + model_input = json.JSONDecoder().raw_decode(encoded)[0] + assert_host_task_context(model_input, wire["work_contract"]) + assert model_input["detail_ref"] == wire["detail_ref"] def test_private_plan_lineage_is_not_a_host_wire(complete_host_request): diff --git a/tests/control_plane/test_complete_host_request_cutover.py b/tests/control_plane/test_complete_host_request_cutover.py index e6aa82e7c5..e8c8b6f302 100644 --- a/tests/control_plane/test_complete_host_request_cutover.py +++ b/tests/control_plane/test_complete_host_request_cutover.py @@ -292,6 +292,7 @@ def test_original_source_capture_keeps_its_read_reference_without_a_fabricated_j ): from loopx.control_plane.turn_driver.decision_capture import write_decision_capture from loopx.control_plane.turn_driver.host_candidate import extract_turn_authority + from tests.control_plane.host_process_fixture import assert_host_task_context _legacy, contract = complete_host_request path = tmp_path / "original-source.json" @@ -306,7 +307,9 @@ def test_original_source_capture_keeps_its_read_reference_without_a_fabricated_j assert "turn_key" not in capture assert capture["turn_instance_id"] == contract.get("heartbeat_receipt", {}).get("turn_instance_id") assert capture["path"] == str(path) and wire["work_contract"] == contract - assert extract_turn_authority(wire)["_model_input"] == wire + model_input = extract_turn_authority(wire)["_model_input"] + assert_host_task_context(model_input, contract) + assert model_input["detail_ref"] == wire["detail_ref"] for field, value in (("goal_id", "other-goal"), ("agent_id", "other-agent"), ("turn_instance_id", "other-turn"), ("path", "bad\0path"), ("source_hash_ref", "$.unverified")): diff --git a/tests/control_plane_ts/turn_envelope.test.ts b/tests/control_plane_ts/turn_envelope.test.ts index 8693d3738b..022fa8ad54 100644 --- a/tests/control_plane_ts/turn_envelope.test.ts +++ b/tests/control_plane_ts/turn_envelope.test.ts @@ -165,15 +165,36 @@ test("read-only session lineage consumes one complete source without relaxing Ho assert.deepEqual(complete, before); }); +test("current Host dispatch refuses a captured selection that still requires reentry", () => { + const source = payload(); + source.action_selection_qualification = { + state: "rejected", requested_todo_id: "todo_111111111111111111111111", + recovery_action: "reenter_guard_without_selection", + }; + const complete = evaluateTurnEnvelope({operation: "compose_complete", payload: source, scheduler_execution_args: ""}); + for (const operation of ["host_context", "host_dispatch_context", "complete_host_lineage"]) { + assert.throws(() => evaluateTurnEnvelope({operation, payload: complete, + complete_host_request: {schema_version: "loopx_turn_host_request_v1", turn_key: "sha256:" + "a".repeat(64)}}), + /unadmitted action selection cannot carry execution or settlement authority/); + } +}); + test("operation preflight optionally shares the existing normalized session lineage", () => { - const complete = evaluateTurnEnvelope({operation: "compose_complete", payload: payload(), scheduler_execution_args: ""}); + const source = payload(); + (source.goal_boundary as JsonObject).checkpointed_boundary_authority = { + schema_version: "checkpointed_boundary_authority_v0", active_count: 1, active_write_scope: ["src/**"], + }; + const complete = evaluateTurnEnvelope({operation: "compose_complete", payload: source, scheduler_execution_args: ""}); const envelope = buildTurnEnvelope({payload: complete, scheduler_execution_args: ""}); const before = structuredClone(complete); + const legacy = evaluateTurnEnvelope({operation: "host_dispatch_context", payload: complete, envelope}); + assert.equal(legacy.checkpointed_write_approval, true); for (const carrier of [{envelope}, {complete_host_request: { schema_version: "loopx_turn_host_request_v1", turn_key: `sha256:${"a".repeat(64)}`, }}]) { const request = {operation: "host_dispatch_context", payload: complete, ...carrier}; const original = evaluateTurnEnvelope(request); + assert.deepEqual(original, legacy); assert.equal(Object.hasOwn(original, "session_lineage"), false); assert.deepEqual(evaluateTurnEnvelope({...request, include_session_lineage: false}), original); const shared = evaluateTurnEnvelope({...request, include_session_lineage: true}); @@ -894,6 +915,11 @@ test("settlement-only replans preserve owed commands and do not demand another o assert.match(String((envelope.action as JsonObject).recommended_action), /original Turn settlement/); assert.equal((envelope.action as JsonObject).primary_action, (interaction.agent_channel as JsonObject).primary_action); assert.deepEqual(quotaActionSignatureDocument(source), turnEnvelopeActionSignatureDocument(envelope)); + const complete = evaluateTurnEnvelope({operation: "compose_complete", payload: source, scheduler_execution_args: ""}); + const host = evaluateTurnEnvelope({operation: "host_dispatch_context", payload: complete, + complete_host_request: {schema_version: "loopx_turn_host_request_v1", turn_key: "sha256:" + "a".repeat(64)}}); + assert.equal(host.primary_action, (interaction.agent_channel as JsonObject).primary_action); + assert.equal(host.replan_admitted, true); } }); @@ -1103,6 +1129,11 @@ test("pending capability action outranks stale replan commands and remains signe envelope: buildTurnEnvelope({payload: replanContract, scheduler_execution_args: ""})}); assert.equal(replanHost.primary_action, "produce one required semantic outcome"); assert.equal(replanHost.replan_admitted, true); + for (const [decision, expected] of [[contract, host], [replanContract, replanHost]]) { + assert.deepEqual(evaluateTurnEnvelope({operation: "host_context", payload: decision, + complete_host_request: {schema_version: "loopx_turn_host_request_v1", turn_key: "sha256:" + "a".repeat(64)}}), + expected); + } (source.pending_capability_intent as JsonObject).command = "untrusted replacement"; assert.throws(() => buildTurnEnvelope({payload: source, scheduler_execution_args: ""}), /action is unsupported/);