Skip to content
Open
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 @@ -335,6 +335,22 @@ 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.

Ordinary Turn planning and failed-Turn recovery now use one
[`TypeScript conversation policy`](../../../loopx/control_plane/turn_driver/session_binding.ts)
through the existing Turn RPC boundary. The Python start/resume/reject producer
is retired; the existing session store and public binding/context schemas stay
in place. Both callers retain fresh binding omission, schema/identity refusal
precedence, Agent versus Todo conversation scope, request-bound fresh execution
and the original recovery transaction. The retained Python adapter encodes
historical `str(value or "")` identities for existing callers and recorded
journals; remove that codec with their C1 historical-reader retirement, rather
than keeping a second normal decision path. The persisted session-key helper
remains an IO namespace contract. [Boundary checks](../../../tests/control_plane/test_turn_session_policy.py)
and existing [File/SQLite CLI and retry checks](../../../tests/control_plane/test_complete_session_binding.py)
cover readback, refusal without effects and once-only original-source recovery.
This is a source migration checkpoint; installed Host adoption, the remaining
C1/C4/C9 cutover, product composition and outcome/full-cost benefit stay 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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -316,6 +316,18 @@ soft claim/hard lease 及历史反馈仅作上下文:保留独立验证的成
host Turn。因此这些服务检查不能取得普通 PostgreSQL 反馈 Turn 资格,
也不构成本切片新增执行 profile 的理由。

普通 Turn 计划与失败 Turn 恢复现在通过既有 Turn RPC 边界使用同一个
[`TypeScript 会话策略`](../../../loopx/control_plane/turn_driver/session_binding.ts)。
Python 的新建/恢复/拒绝 producer 已退役,既有会话存储及公开 binding/context
schema 保留。两个调用方保持 fresh 对旧 binding 的忽略、schema/身份拒绝优先级、
Agent 与 Todo 会话作用域、request-bound fresh 执行及原恢复事务。保留的 Python
适配器为既有调用方和已记录 journal 编码历史 `str(value or "")` 身份;随 C1
历史 reader 退役删除该 codec,不保留第二条正常决策路径。持久化会话键 helper
仍是 IO 命名空间合同。[边界检查](../../../tests/control_plane/test_turn_session_policy.py)
及既有 [File/SQLite CLI 与重试检查](../../../tests/control_plane/test_complete_session_binding.py)
覆盖回读、拒绝无副作用及原来源的一次恢复结算。这是源码迁移 checkpoint;
已安装 Host 采用、剩余 C1/C4/C9 切换、产品组合及成果/完整成本收益仍开放。

首个任务须确有反馈或方法选择需求。已有链完整时直接复用;有缺口时由真实消费者证明并修复,不为配合示例制造失败。运行实验、训练模型和发布过程各沿原权限,本文不占用其他 lane 配额或预设 PR 数。

## 12. 待确认的关键选择
Expand Down
2 changes: 2 additions & 0 deletions loopx/control_plane/quota/turn_envelope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {contextReadSectionDigests, initialContextReadPointers, prepareProgressiv
progressiveContextPlan, scopedReplanYardstickReversal,
type PreparationScopeDetail, type ReusableExactBody} from "./progressive_context.ts";
import type { LoopXTurnRouteValue } from "../turn_driver/turn_contract_generated.ts";
import {turnSessionPlan} from "../turn_driver/session_binding.ts";
import { EFFECTIVE_ACTIONS, EffectiveAction, type QuotaEffectiveActionValue } from "./effective_action.generated.ts";
import { AGENT_SCOPE_FRONTIER_ACTIONS } from "../agents/agent_scope_frontier.generated.ts";
import { createHash } from "node:crypto";
Expand Down Expand Up @@ -2561,6 +2562,7 @@ export function decodeTurnSource(request: JsonObject, inlineField: "payload" | "
export function evaluateTurnEnvelope(value: unknown): JsonObject {
const request = requireJsonObject(value, "turn envelope request");
const operation = request.operation;
if (operation === "session_plan") return turnSessionPlan(request);
if (operation === "planning_facts") return completePlanningFacts(request);
if (operation === "recorded_plan_lineage") {
const {work, decision} = checkedTurnPlanSource(
Expand Down
83 changes: 18 additions & 65 deletions loopx/control_plane/turn_driver/driver.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,73 +198,26 @@ def _session_plan(
iteration_context_policy: str,
session_scope: str = "agent",
) -> tuple[dict[str, Any], str | None]:
identity_fields = session_identity_fields(session_scope)
if lineage.get("request_binding_id") and iteration_context_policy == "fresh":
identity_fields = ("goal_id", "agent_id")
context_policy = {
"schema_version": LOOPX_ITERATION_CONTEXT_POLICY_SCHEMA_VERSION,
"mode": iteration_context_policy,
"scope": "iteration",
**({"binding_scope": session_scope} if session_scope != "todo" else {}),
}
host_route = route in {
LoopXTurnRoute.READY_FOR_HOST,
LoopXTurnRoute.REPAIR_REQUIRED,
LoopXTurnRoute.REPLAN_REQUIRED,
}
if not host_route:
return {
"schema_version": LOOPX_TURN_SESSION_BINDING_SCHEMA_VERSION,
"action": "none",
"binding_status": "not_applicable",
"context_policy": context_policy,
}, None
if (not all(lineage.get(field) for field in (*identity_fields, "action_hash"))
or not (lineage.get("todo_id") or lineage.get("replan_obligation_id") or lineage.get("request_binding_id"))):
return {
"schema_version": LOOPX_TURN_SESSION_BINDING_SCHEMA_VERSION,
"action": "reject",
"binding_status": "missing_turn_lineage",
}, "host-bound routes require goal, agent, todo, and action-hash lineage"

if iteration_context_policy == "fresh":
return {
"schema_version": LOOPX_TURN_SESSION_BINDING_SCHEMA_VERSION,
"action": "start_new",
"binding_status": (
"existing_binding_ignored" if session_binding else "not_found"
),
"context_policy": context_policy,
}, None
"""Transport both real callers to the single TypeScript session policy.

Keep invalid-scope exception precedence and Python's historical scalar
encoding. Neither this codec nor the persisted session-key helper selects
whether a Host starts, resumes or rejects a conversation.
"""
session_identity_fields(session_scope)
binding = dict(session_binding or {})
if not binding:
return {
"schema_version": LOOPX_TURN_SESSION_BINDING_SCHEMA_VERSION,
"action": "start_new",
"context_policy": context_policy,
}, None
if binding.get("schema_version") != LOOPX_TURN_SESSION_BINDING_SCHEMA_VERSION:
return {
"schema_version": LOOPX_TURN_SESSION_BINDING_SCHEMA_VERSION,
"action": "reject",
"binding_status": "unsupported_schema",
}, "unsupported LoopX Turn session binding schema"

actual = {field: str(binding.get(field) or "") for field in identity_fields}
expected = {field: lineage[field] for field in identity_fields}
if actual != expected:
return {
"schema_version": LOOPX_TURN_SESSION_BINDING_SCHEMA_VERSION,
"action": "reject",
"binding_status": "identity_mismatch",
}, "session binding does not match the current " + ", ".join(identity_fields)
return {
"schema_version": LOOPX_TURN_SESSION_BINDING_SCHEMA_VERSION,
"action": "resume",
"binding_status": "compatible",
"context_policy": context_policy,
}, None
result = _turn_envelope_result(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] 保留新增 RPC 失败时的结构化恢复判定。原失败 journal 和已存会话均可读时,只让此请求丢失响应,两种 provider 的公开 inspect 都从含 retry_failed_phase 的 exit 0 变成无 recovery_decision 的 exit 1。这里的异常越过了 failed-Turn session check 的转换,所以只读操作被报成可能已提交。请让这个错误经过原恢复检查,验证不启动 Host、不写回或扣额,恢复后仍沿原身份结算一次。

"session_plan", route=route.value, lineage=dict(lineage),
# Only presence and the schema token cross this boundary. Unrelated
# provider fields (including non-JSON metadata) are never decision input.
session_binding=({"schema_version": binding.get("schema_version")
if isinstance(binding.get("schema_version"), str) else None}
if binding else {}),
binding_identity_text={field: str(binding.get(field) or "")
for field in ("goal_id", "agent_id", "todo_id")},
iteration_context_policy=iteration_context_policy, session_scope=session_scope,
)
return result["session"], result["error"]


def reconcile_failed_turn_session_request(
Expand Down
61 changes: 61 additions & 0 deletions loopx/control_plane/turn_driver/session_binding.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/** Conversation reuse policy for normal planning and original-Turn recovery.
* Persistence and Python's historical scalar codec remain at the host IO edge.
*/
import {requireJsonObject, requireStringLiteral, type JsonObject} from "../runtime_decode.ts";
import {TURN_ROUTES} from "./turn_contract_generated.ts";

const SESSION_SCHEMA = "loopx_turn_session_binding_v0";
const CONTEXT_SCHEMA = "loopx_iteration_context_policy_v0";

type ContextPolicy = {
schema_version: typeof CONTEXT_SCHEMA;
mode: "fresh" | "resume";
scope: "iteration";
binding_scope?: "agent";
};
type SessionDecision =
| {action: "none"; binding_status: "not_applicable"; context_policy: ContextPolicy}
| {action: "start_new"; binding_status?: "existing_binding_ignored" | "not_found"; context_policy: ContextPolicy}
| {action: "resume"; binding_status: "compatible"; context_policy: ContextPolicy}
| {action: "reject"; binding_status: "missing_turn_lineage" | "unsupported_schema" | "identity_mismatch"};
type SessionPlan = {schema_version: typeof SESSION_SCHEMA} & SessionDecision;

export function turnSessionPlan(request: JsonObject): {session: SessionPlan; error: string | null} {
const scope = requireStringLiteral(request.session_scope, ["todo", "agent"], "session scope");
const mode = requireStringLiteral(request.iteration_context_policy, ["fresh", "resume"], "iteration context policy");
const route = requireStringLiteral(request.route, TURN_ROUTES, "Turn route");
const lineage = requireJsonObject(request.lineage, "Turn lineage");
// Lineage and binding identity are encoded by the production caller,
// including historical Python str/or values. Never trim that identity.
const fields = scope === "todo" && !(lineage.request_binding_id && mode === "fresh")
? ["goal_id", "agent_id", "todo_id"] : ["goal_id", "agent_id"];
const context: ContextPolicy = {schema_version: CONTEXT_SCHEMA, mode, scope: "iteration",
...(scope === "agent" ? {binding_scope: scope} : {})};
const result = (plan: SessionDecision, error: string | null = null): {session: SessionPlan; error: string | null} =>
({session: {schema_version: SESSION_SCHEMA, ...plan}, error});
if (route !== "ready_for_host" && route !== "repair_required" && route !== "replan_required") {
return result({action: "none", binding_status: "not_applicable", context_policy: context});
}
if ([...fields, "action_hash"].some(field => !lineage[field]) ||
!(lineage.todo_id || lineage.replan_obligation_id || lineage.request_binding_id)) {
return result({action: "reject", binding_status: "missing_turn_lineage"},
"host-bound routes require goal, agent, todo, and action-hash lineage");
}
const binding = requireJsonObject(request.session_binding, "session binding");
const hasBinding = Object.keys(binding).length > 0;
if (mode === "fresh") {
return result({action: "start_new", binding_status: hasBinding ? "existing_binding_ignored" : "not_found",
context_policy: context});
}
if (!hasBinding) return result({action: "start_new", context_policy: context});
if (binding.schema_version !== SESSION_SCHEMA) {
return result({action: "reject", binding_status: "unsupported_schema"},
"unsupported LoopX Turn session binding schema");
}
const identity = requireJsonObject(request.binding_identity_text, "encoded session identity");
if (fields.some(field => identity[field] !== lineage[field])) {
return result({action: "reject", binding_status: "identity_mismatch"},
"session binding does not match the current " + fields.join(", "));
}
return result({action: "resume", binding_status: "compatible", context_policy: context});
}
102 changes: 102 additions & 0 deletions tests/control_plane/test_turn_session_policy.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
"""Conversation reuse does not change Turn identity or recovery authority."""

from copy import deepcopy

import pytest

from loopx.control_plane.turn_driver.driver import (
FailedTurnSessionRecoveryError,
build_loopx_turn_plan,
reconcile_failed_turn_session_request,
)
from tests.test_loopx_turn_driver import _envelope


def _plan(envelope, **options):
return build_loopx_turn_plan(envelope, host="codex-cli",
execution_mode="isolated-headless", turn_instance_id="session-policy", **options)


@pytest.mark.parametrize(("value", "encoded"), [
(True, "True"), (1.0, "1.0"), (0.000001, "1e-06"),
(1152921504606846977, "1152921504606846977"),
([True, "task"], "[True, 'task']"),
({"name": "task", "active": True}, "{'name': 'task', 'active': True}"),
("任务-\"quoted\"", "任务-\"quoted\""),
])
def test_historical_binding_codec_survives_plan_and_failed_recovery(value, encoded):
envelope = _envelope()
envelope["action"]["selected_todo"]["todo_id"] = encoded
binding = {"schema_version": "loopx_turn_session_binding_v0",
"goal_id": "fixture-goal", "agent_id": "codex-fixture", "todo_id": value}
before = deepcopy((envelope, binding))
plan = _plan(envelope, session_scope="todo", session_binding=binding)
assert plan["ok"] and plan["session"]["action"] == "resume"
request = {"turn_envelope": envelope, "session": plan["session"], "original": "retained"}
assert reconcile_failed_turn_session_request(request, session_binding=binding) == request
assert (envelope, binding) == before


@pytest.mark.parametrize("binding", [None, {}, {"schema_version": "future"},
{"schema_version": "loopx_turn_session_binding_v0", "goal_id": "other"}])
@pytest.mark.parametrize("scope", ["todo", "agent"])
def test_fresh_ignores_old_binding_after_lineage_validation(binding, scope):
plan = _plan(_envelope(), session_scope=scope, session_binding=binding,
iteration_context_policy="fresh")
assert plan["ok"] and plan["session"] == {
"schema_version": "loopx_turn_session_binding_v0", "action": "start_new",
"binding_status": "existing_binding_ignored" if binding else "not_found",
"context_policy": {"schema_version": "loopx_iteration_context_policy_v0",
"mode": "fresh", "scope": "iteration",
**({"binding_scope": "agent"} if scope == "agent" else {})},
}
invalid = _envelope()
invalid["agent_id"] = ""
with pytest.raises(ValueError, match="identity.agent_id must be a non-empty string"):
_plan(invalid, session_scope=scope, session_binding=binding,
iteration_context_policy="fresh")


@pytest.mark.parametrize("binding", [None, {}, {"schema_version": "future"}])
@pytest.mark.parametrize("scope", ["todo", "agent"])
def test_wait_does_not_inspect_a_session(binding, scope):
envelope = _envelope(should_run=False, quiet_noop_allowed=True)
plan = _plan(envelope, session_scope=scope, session_binding=binding)
assert plan["ok"] and plan["session"] == {
"schema_version": "loopx_turn_session_binding_v0", "action": "none",
"binding_status": "not_applicable",
"context_policy": {"schema_version": "loopx_iteration_context_policy_v0",
"mode": "resume", "scope": "iteration",
**({"binding_scope": "agent"} if scope == "agent" else {})},
}


@pytest.mark.parametrize("value", [None, False, 0, 0.0, "", [], {}])
def test_false_binding_identity_is_rejected_without_a_fresh_fallback(value):
envelope = _envelope()
binding = {"schema_version": "loopx_turn_session_binding_v0",
"goal_id": "fixture-goal", "agent_id": "codex-fixture", "todo_id": value}
plan = _plan(envelope, session_scope="todo", session_binding=binding)
assert not plan["ok"] and plan["session"]["binding_status"] == "identity_mismatch"
assert plan["error"] == "session binding does not match the current goal_id, agent_id, todo_id"
request = {"turn_envelope": envelope, "session": {"action": "start_new"}}
with pytest.raises(FailedTurnSessionRecoveryError) as caught:
reconcile_failed_turn_session_request(request, session_binding=binding)
assert caught.value.reason == "session_binding_identity_mismatch"
assert str(caught.value) == "failed-Turn recovery " + plan["error"]


def test_agent_scope_reuses_conversation_without_changing_original_turn_identity():
envelope = _envelope()
binding = {"schema_version": "loopx_turn_session_binding_v0",
"goal_id": "fixture-goal", "agent_id": "codex-fixture", "todo_id": "previous-task"}
fresh = _plan(envelope, session_scope="agent")
resumed = _plan(envelope, session_scope="agent", session_binding=binding)
assert resumed["ok"] and resumed["session"]["action"] == "resume"
assert resumed["transaction"]["settlement_plan"]["identity"] == fresh["transaction"]["settlement_plan"]["identity"]
request = {"turn_envelope": envelope, "session": fresh["session"],
"transaction": fresh["transaction"]}
recovered = reconcile_failed_turn_session_request(request, session_binding=binding)
assert recovered["session"]["binding_status"] == "failed_turn_recovery"
assert recovered["transaction"] == fresh["transaction"]
assert request["session"]["action"] == "start_new"
Loading
Loading