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
29 changes: 29 additions & 0 deletions docs/architecture/rfcs/monorepo-distribution-split-v0.md
Original file line number Diff line number Diff line change
Expand Up @@ -4205,3 +4205,32 @@ File/SQLite negative cases guard this boundary without changing valid activation
C1 cutover. No runtime, schema, activation, permission or public evidence
policy changes; one-run relay/validator files remain private qualification
artifacts rather than a new shipped execution pipeline or CI fixture.

### 2026-11-15 — First-Goal admission failure preserves creation and confirmed work

- **Gap:** a failed first-Goal admission read or decision was converted into
permission to dispatch. Conversely, retrying a lost submit response could
apply a later admission failure or denial to already dispatched work.
- **Delta:** the existing creation owner retains Goal, initial Tasks and
completion requirements before checking admission. An unverifiable admission
now returns a safe retryable action failure without opening a Session or
sending model work. Creation without an executable Host does not read work
admission. Recovery first reads the original Session/client operation through
the existing Task-start reader, verifies its request and first-Turn state,
and retains dispatched work without new admission. Queued work still requires
admission; foreign Sessions and terminal-before-start work remain refused.
- **Evidence:** on `main@58cc5817e35e`, the real Chat HTTP/action/store path with
synthetic Codex protocol passes 36 creation-completion cases and 11 existing
Session/checkpoint recovery cases. Independent review identified two recovery
defects in the first candidate; their failing cases were retained and the
final candidate resolves both. The final runtime/test files also pass 22
selected File/SQLite and creation-only cases in an isolated combination with
C1 #8266 at `b8ac1ec5443b`, with exact source-byte readback. These are bounded
source and synthetic-Host checks, not current native-model qualification.
- **Boundary:** this repairs V2/V4/R1 admission and recovery using existing
Session, Task and quota owners; it adds no shared vocabulary, authority grant,
validator installation or alternate C1 pipeline. Automatic original-Task
adoption, selected D2/D5 closure, native App/model and compaction retention,
progressive controls, comparable complete costs, full V1–V5/V10, R1/M3 and
C1 cutover remain unqualified. Preserve original requirements and earlier
negative evidence; run full original-goal regression before completion.
22 changes: 22 additions & 0 deletions docs/architecture/rfcs/monorepo-distribution-split-v0.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -3266,3 +3266,25 @@ R1/M3、C1 切换和原目标回归仍未完成资格验证。
完整 D2/D5 闭包、可比完整成本、V1–V5/V10、R1/M3 或 C1 切换的资格验证。
没有改变运行时、schema、激活、权限或公共证据政策;单次 relay/校验器文件
保留为私有资格验证产物,没有新增已交付执行管线或 CI fixture。

### 2026-11-15 — 首个 Goal 准入失败保留创建与已确认工作

- **缺口:**首个 Goal 的准入读取或判断失败会被转换为允许派发;反过来,
派发响应丢失后重试,又可能用之后的准入失败或拒绝阻断已派发工作。
- **增量:**既有创建 owner 先保留 Goal、初始 Task 和完成要求,再检查准入。
准入不可验证时返回安全、可重试的 action 失败,不打开 Session 或发送模型
工作。没有可执行 Host 的纯创建不读取工作准入。恢复先通过既有 Task-start
reader 读回原 Session/client 操作,核对原请求及首轮状态;已派发工作直接
读回,不重新准入。排队工作仍需准入;外来 Session 和启动前已终止的工作
继续拒绝。
- **证据:**在 `main@58cc5817e35e` 上,真实 Chat HTTP/action/store 路径配合
合成 Codex 协议通过 36 项创建与完成测试,以及 11 项既有 Session/checkpoint
恢复测试。独立评审在第一版候选发现两个恢复缺陷;对应失败用例保留,最终
候选已解决两项。最终运行时与测试文件还在 C1 #8266 的 `b8ac1ec5443b`
隔离组合中通过 22 项选定的 File/SQLite 及纯创建测试,逐字节读回来源一致。
这些是限定范围的源码与合成 Host 检查,不是当前原生模型资格验证。
- **边界:**本次复用既有 Session、Task 与 quota owner,修复 V2/V4/R1 的
准入和恢复;没有新增共享词汇、授权、校验器安装或替代 C1 管线。自动采用
原 Task、选定 D2/D5 闭包、原生 App/模型与 compaction 保留、渐进控制、
可比完整成本、完整 V1–V5/V10、R1/M3 和 C1 切换仍未通过资格验证。原要求
与此前负面证据保留;完成目标前仍需完整原目标回归。
113 changes: 68 additions & 45 deletions loopx/chat_actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
)
from .chat_goal_lifecycle_actions import ChatGoalLifecycleActionMixin
from .chat.monitor_actions import ChatMonitorActionMixin
from .chat_store import ChatSessionStore
from .chat_store import ChatSessionStore, TERMINAL_TURN_STATES
from .chat.todo_actions import ChatTodoActionMixin
from .control_plane.goals.acceptance_actions import GoalAcceptanceActionMixin
from .control_plane.goals.goal_objective_actions import GoalObjectiveActionMixin
Expand Down Expand Up @@ -844,6 +844,12 @@ def require_first_turn_readback(turn: dict[str, Any]) -> None:
)
turn_result: dict[str, Any] | None = None
session_id = ""
first_turn_message = (f"/goal start --tokens {parameters['native_token_budget']} {objective}"
if parameters.get("native_token_budget") else (
f"开始推进 Goal {goal_id}。先核对目标边界和现有 Todo,"
f"首个 Todo:{';'.join(str(item) for item in (parameters.get('initial_todos') or [])[:3]) or '按目标边界建立首个可验证进展'}。"
"然后直接推进并报告可验证结果;遇到权限边界时停止并提出明确 Gate。"
))
if progress.get("firstTurn"):
session_id = progress["firstTurn"]["sessionId"]
turn_id = progress["firstTurn"]["turnId"]
Expand All @@ -854,46 +860,68 @@ def require_first_turn_readback(turn: dict[str, Any]) -> None:
raise ValueError("The recorded first Turn is unavailable; restore its original Session instead of starting another")
require_first_turn_readback(turn)
turn_result = {"turn_id": turn_id, "status": str(turn["status"]), "created": False}
elif progress.get("sessionId"):
turn_store = self.chat_store or getattr(self.runtime_controller, "store", None)
if turn_store is None:
raise ValueError("The original first Session is unavailable; restore it before retrying")
session, turn = self._read_task_start(
turn_store, goal_id=goal_id, agent_id=agent_id, channel_id=f"goal.{goal_id}",
client_turn_id=f"goal-start-{proposal_id}", checkpoint={"session_id": progress["sessionId"]},
)
if turn is not None:
if turn.get("message") != first_turn_message:
raise ValueError("The original first Turn request changed; retain its recorded operation")
require_first_turn_readback(turn)
if turn.get("status") in TERMINAL_TURN_STATES or turn.get("started_at") or turn.get("upstream_turn_id"):
session_id = session["session_id"]
turn_result = {"turn_id": turn["turn_id"], "status": str(turn["status"]), "created": False}
self.store.save_checkpoint(proposal_id, step="first_turn_started", receipt={
"outcome": "first_turn_started", "session_id": session_id, "turn_id": turn["turn_id"],
})
first_turn_gate: dict[str, Any] | None = None
try:
from .status import collect_status
if agent_id and self.runtime_controller is not None and turn_result is None:
try:
from .status import collect_status

status_payload = collect_status(
registry_path=self.registry_path,
runtime_root_override=str(runtime_root) if runtime_root else None,
limit=5,
goal_id=goal_id,
available_capabilities=(
self.runtime_controller.capabilities()
if self.runtime_controller is not None
else None
),
)
guard = build_quota_should_run(
status_payload,
goal_id=goal_id,
agent_id=agent_id or None,
available_capabilities=(
self.runtime_controller.capabilities()
if self.runtime_controller is not None
else None
),
)
except Exception:
guard = {"should_run": True, "state": "status_unavailable"}
if guard.get("should_run") is not True and turn_result is None:
first_turn_gate = {
"kind": "goal_quota_gate",
"summary": str(
guard.get("reason")
or "The new Goal is not eligible for its first Agent Turn."
)[:600],
"next_action": str(
guard.get("recommended_action")
or "Resolve the projected Goal Gate and retry the first Turn."
)[:600],
"quota_state": str(guard.get("state") or "waiting"),
}
status_payload = collect_status(
registry_path=self.registry_path,
runtime_root_override=str(runtime_root) if runtime_root else None,
limit=5,
goal_id=goal_id,
available_capabilities=(
self.runtime_controller.capabilities()
if self.runtime_controller is not None
else None
),
)
guard = build_quota_should_run(
status_payload,
goal_id=goal_id,
agent_id=agent_id or None,
available_capabilities=(
self.runtime_controller.capabilities()
if self.runtime_controller is not None
else None
),
)
except Exception as exc:
raise ValueError(
"The first Turn's Goal admission could not be verified. "
"Retain this creation and retry when its admission source is available."
) from exc
if guard.get("should_run") is not True:
first_turn_gate = {
"kind": "goal_quota_gate",
"summary": str(
guard.get("reason")
or "The new Goal is not eligible for its first Agent Turn."
)[:600],
"next_action": str(
guard.get("recommended_action")
or "Resolve the projected Goal Gate and retry the first Turn."
)[:600],
"quota_state": str(guard.get("state") or "waiting"),
}
if agent_id and self.runtime_controller is not None and first_turn_gate is None and turn_result is None:
if progress.get("sessionId"):
session = self.runtime_controller.store.load_session(progress["sessionId"])
Expand All @@ -920,12 +948,7 @@ def require_first_turn_readback(turn: dict[str, Any]) -> None:
first_turn, created = self.runtime_controller.submit_turn(
session_id=session_id,
client_turn_id=f"goal-start-{proposal_id}",
message=(f"/goal start --tokens {parameters['native_token_budget']} {objective}"
if parameters.get("native_token_budget") else (
f"开始推进 Goal {goal_id}。先核对目标边界和现有 Todo,"
f"首个 Todo:{';'.join(str(item) for item in (parameters.get('initial_todos') or [])[:3]) or '按目标边界建立首个可验证进展'}。"
"然后直接推进并报告可验证结果;遇到权限边界时停止并提出明确 Gate。"
)),
message=first_turn_message,
work_dir=project,
objective=objective,
)
Expand Down
61 changes: 54 additions & 7 deletions tests/control_plane/test_goal_create_completion.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,13 +180,15 @@ def conflict_before_commit(**kwargs):


@pytest.mark.parametrize("provider", ["file", "sqlite"])
@pytest.mark.parametrize("fault", ["declaration_response", "first_turn_response"])
@pytest.mark.parametrize("fault", ["declaration_response", "admission_read", "admission_decision", "first_turn_response",
"first_turn_response_then_read_failure", "first_turn_response_then_denial"])
def test_managed_creation_retains_requirements_before_one_host_dispatch(environment, app, monkeypatch, provider, fault):
import runpy
from loopx.chat_runtime import ChatRuntimeController
from loopx.chat_store import ChatSessionStore
from loopx.capabilities.native_chat.project_context import ChatProjectContexts
from loopx.control_plane.goals import acceptance
from loopx import chat_actions, status as status_owner

configure, _, _, project, runtime = environment
_, request, service = app
Expand All @@ -203,8 +205,14 @@ def test_managed_creation_retains_requirements_before_one_host_dispatch(environm
project_contexts=ChatProjectContexts([project]))
service.chat_store, service.runtime_controller = chat, controller
proposal = preview_goal(request)
target = acceptance if fault == "declaration_response" else controller
method = "refine_goal_outcome" if fault == "declaration_response" else "submit_turn"
target, method = {
"declaration_response": (acceptance, "refine_goal_outcome"),
"admission_read": (status_owner, "collect_status"),
"admission_decision": (chat_actions, "build_quota_should_run"),
"first_turn_response": (controller, "submit_turn"),
"first_turn_response_then_read_failure": (controller, "submit_turn"),
"first_turn_response_then_denial": (controller, "submit_turn"),
}[fault]
original = getattr(target, method)

def lose_response(*args, **kwargs):
Expand All @@ -214,11 +222,27 @@ def lose_response(*args, **kwargs):
monkeypatch.setattr(target, method, lose_response)
try:
status, failed = request(f"/api/actions/{proposal['proposal_id']}/apply", {})
assert status == 424, failed
assert status == (400 if fault.startswith("admission_") else 424), failed
assert inspect(project, runtime)["goal_acceptance_contract"]["outcome_requirements"]["revision"] == 1
if fault == "declaration_response":
assert chat.list_sessions(goal_id="report") == [], "an uncertain declaration must block Host startup"
if not fault.startswith("first_turn_response"):
assert chat.list_sessions(goal_id="report") == [], "uncertain requirements or admission must block Host startup"
assert not capture.exists(), "no native request may precede a verified first-Turn admission"
retained = inspect(project, runtime)["goal_acceptance_contract"]
monkeypatch.setattr(target, method, original)
confirmed = None
admission_calls = []
if fault.startswith("first_turn_response_then_"):
sid = chat.list_sessions(goal_id="report")[0]["session_id"]
accepted = chat.turn_for_client(sid, f"goal-start-{proposal['proposal_id']}")
confirmed = controller.wait_for_turn(session_id=sid, turn_id=accepted["turn_id"], timeout_sec=10)
assert confirmed["status"] == "completed"
def changed_admission(*args, **kwargs):
admission_calls.append(True)
if fault.endswith("read_failure"):
raise TimeoutError("The later admission source is unavailable")
return {"should_run": False, "state": "throttled", "reason": "No new work is eligible"}
monkeypatch.setattr(status_owner if fault.endswith("read_failure") else chat_actions,
"collect_status" if fault.endswith("read_failure") else "build_quota_should_run", changed_admission)
submit = controller.submit_turn

def assert_retained_then_submit(*args, **kwargs):
Expand All @@ -230,15 +254,38 @@ def assert_retained_then_submit(*args, **kwargs):
status, recovered = request(f"/api/actions/{proposal['proposal_id']}/apply", {})
assert status == 202, recovered
ids = recovered["proposal"]["receipt"]["resource_ids"]
if confirmed is not None:
assert ids["session_id"] == sid and ids["turn_id"] == confirmed["turn_id"]
assert admission_calls == [], "confirmed first work is readback, not a new admission"
assert recovered.get("gate") is None
controller.wait_for_turn(session_id=ids["session_id"], turn_id=ids["turn_id"], timeout_sec=10)
assert len(chat.list_sessions(goal_id="report")) == 1
starts = [json.loads(line) for line in capture.read_text().splitlines() if json.loads(line).get("method") == "turn/start"]
assert len(starts) == 1
assert inspect(project, runtime)["goal_acceptance_contract"]["outcome_requirements"]["revision"] == 1
assert inspect(project, runtime)["goal_acceptance_contract"] == retained
finally:
controller.close()


@pytest.mark.parametrize("agent_id", ["", "codex"])
def test_creation_without_a_host_does_not_require_work_admission(environment, app, monkeypatch, agent_id):
from loopx import status as status_owner

store, request, _ = app
proposal = preview_goal(request, agent_id=agent_id, completion_criteria=CRITERIA if agent_id else "")
admission_calls = []
def unavailable(*args, **kwargs):
admission_calls.append(True)
raise TimeoutError("Admission is unavailable for new model work")
monkeypatch.setattr(status_owner, "collect_status", unavailable)
status, created = request(f"/api/actions/{proposal['proposal_id']}/apply", {})
assert status == 200, created
assert created["proposal"]["receipt"]["outcome"] == "goal_created"
assert "session_id" not in created["proposal"]["receipt"]["resource_ids"]
assert "first_session_opened" not in store.load(proposal["proposal_id"])["checkpoint"]["steps"]
assert admission_calls == [], "configuration-only creation never dispatches model work"


@pytest.mark.parametrize("provider", ["file", "sqlite"])
@pytest.mark.parametrize("mode", ["soft_claim", "hard_lease"])
def test_confirmed_task_start_recovers_the_same_claim_and_dispatch(environment, app, monkeypatch, provider, mode):
Expand Down
Loading