: null}
{digest.work.groups.map(group =>
{ownerName(group.ownerId)}
{group.todoIds.length} {zh ? "项任务" : "tasks"} · {group.todoIds.filter(id => rows.get(id)?.displayClass === group.displayClass).length} {goalWorkClassLabel(group.displayClass, zh)}
{!readOnly && group.ownerId && onOpenAgentConversation ? : null}
diff --git a/apps/presentation/dashboard/src/features/personal-workspace/i18n.tsx b/apps/presentation/dashboard/src/features/personal-workspace/i18n.tsx
index ce9b6dbff1..fcc0bf4be6 100644
--- a/apps/presentation/dashboard/src/features/personal-workspace/i18n.tsx
+++ b/apps/presentation/dashboard/src/features/personal-workspace/i18n.tsx
@@ -959,8 +959,13 @@ const en = {
"drawer.recoverEditResult": "Recover operation result",
"drawer.retryOriginal": "Retry original operation",
"actionReview.canonical_update_retry": "The edit is not yet verified. Retry this operation to recover its result.",
+ "goalWork.displayPending": "Display updates pending",
+ "actionReview.canonical_create_projection_pending": "The task was created. Retry the original confirmation to finish updating its display.",
"actionReview.goal_creation_retry": "Goal initialization is incomplete. Retry the original creation; its recorded storage choice is preserved.",
"actionReview.task_start_retry": "The Task was saved. Retry its original start to continue with that Task.",
+ "actionReview.todo_creation_retry": "Confirmation submitted. Retry to recover the original result.",
+ "drawer.todoCreationUnverified": "Refresh to check the original confirmation.",
+ "drawer.todoCreationStale": "The source changed before creation. Start a new request if you still need it.",
"actionReview.canonical_update_projection_pending": "The operation was committed; display delivery is pending. Retry this operation to restore the current view.",
"actionReview.team_plan_retry": "Retry this assignment using the original plan. Current state is checked again, and any tasks already created are recovered without duplication.",
"actionReview.apply_failed": "Execution did not complete. Check the failure and regenerate the preview before retrying.",
@@ -2585,8 +2590,13 @@ const zhCN: Record = {
"drawer.recoverEditResult": "恢复操作结果",
"drawer.retryOriginal": "重试原操作",
"actionReview.canonical_update_retry": "编辑结果尚未确认。重试此操作以恢复原结果。",
+ "goalWork.displayPending": "展示待更新",
+ "actionReview.canonical_create_projection_pending": "任务已创建,展示尚未更新。重试原确认以完成更新。",
"actionReview.goal_creation_retry": "Goal 初始化尚未完成。请重试原创建操作,已记录的存储选择会保留。",
"actionReview.task_start_retry": "任务已保存。重试原操作以继续启动这个任务。",
+ "actionReview.todo_creation_retry": "已提交创建确认。重试本次确认以取回结果。",
+ "drawer.todoCreationUnverified": "刷新页面以检查原确认的结果。",
+ "drawer.todoCreationStale": "创建前来源已变化。如仍需创建,请发起新请求。",
"actionReview.canonical_update_projection_pending": "操作已提交,展示尚未同步。重试此操作以恢复当前视图。",
"actionReview.team_plan_retry": "可以从同一提案重试分配。系统会重新核验当前状态,并恢复已记录的结果,不会重复创建任务。",
"actionReview.apply_failed": "执行未完成。请检查失败原因并重新生成预览后再试。",
diff --git a/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-page.tsx b/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-page.tsx
index a87734025c..62b0fc1a5b 100644
--- a/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-page.tsx
+++ b/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-page.tsx
@@ -129,7 +129,9 @@ function dedupeProposals(proposals: WorkspaceActionPreview[]): WorkspaceActionPr
const latest = new Map();
proposals.forEach((proposal) => {
const subject = proposal.fields.find((field) => field.key === "todo_id")?.value ?? "";
- const key = proposal.actionKind === "operation.execute" || proposal.reviewPlan?.taskExecution ? proposal.previewId
+ const ownConfirmation = proposal.reviewPlan?.retryOriginal === true
+ && (proposal.actionKind === "todo.create" || proposal.actionKind === "monitor.create");
+ const key = proposal.actionKind === "operation.execute" || proposal.reviewPlan?.taskExecution || ownConfirmation ? proposal.previewId
: [proposal.actionKind, proposal.goalId ?? "", subject, proposal.title].join(":");
// Two records can describe the same draft; keep the newest by its stored
// time rather than whichever one this list happened to end with, since a
@@ -688,8 +690,14 @@ function workspaceProposal(proposal: TypedActionProposal, t: WorkspaceTranslate)
: "";
const operationFrame = reviewPlan.operationFrame;
const decision = reviewPlan.decisionFrame?.decision;
+ const retryGate = reviewPlan.retryOriginal && proposal.gate?.kind === "canonical_authority_required"
+ ? [proposal.gate.summary, proposal.gate.next_action].filter(value => typeof value === "string").join(" ")
+ : "";
const operationTitle = operationFrame?.content.title ?? proposal.summary;
- const localizedSummary = proposal.action_kind === "operation.execute"
+ const taskText = proposal.normalized_parameters.text;
+ const localizedSummary = reviewPlan.reason === "canonical_create_projection_pending"
+ && proposal.action_kind === "todo.create" && typeof taskText === "string" ? taskText
+ : proposal.action_kind === "operation.execute"
? operationTitle
: proposal.action_kind === "team.plan"
? proposal.status === "applied"
@@ -729,7 +737,7 @@ function workspaceProposal(proposal: TypedActionProposal, t: WorkspaceTranslate)
|| proposal.status === "applied"
|| ["objective", "completion_criteria", "execution_boundary", "permission", "workspace_ref"].includes(field.key)),
goalId: typeof proposal.normalized_parameters.goal_id === "string" ? proposal.normalized_parameters.goal_id : undefined,
- impact: reviewPlan.retryOriginal ? t(`actionReview.${reviewPlan.reason}`) : proposal.action_kind === "operation.execute"
+ impact: reviewPlan.retryOriginal ? retryGate || t(`actionReview.${reviewPlan.reason}`) : proposal.action_kind === "operation.execute"
? operationFrame?.kind === "inactive" ? t(`actionReview.${operationFrame.reason}`)
: operationFrame?.kind === "pending" && operationFrame.executionState
? t(operationFrame.executionState === "consumed_outcome_pending"
@@ -2123,6 +2131,7 @@ export function PersonalWorkspacePage({
if (proposal.reviewPlan && !proposal.reviewPlan.canApply) return proposal;
if (proposal.actionKind === "team.plan" && proposal.status === "error"
&& !proposal.reviewPlan?.retryOriginal) return proposal;
+ const isTodoCreation = proposal.actionKind === "todo.create" || proposal.actionKind === "monitor.create";
const matchesTodoTarget = (observed: TypedActionProposal) => proposal.actionKind !== "todo.update" || (
observed.normalized_parameters.goal_id === proposal.goalId
&& (!proposal.sourceRequest || observed.normalized_parameters.todo_id === proposal.sourceRequest.normalizedParameters.todo_id)
@@ -2180,6 +2189,7 @@ export function PersonalWorkspacePage({
if (result.proposal.proposal_id !== proposal.previewId
|| result.proposal.action_kind !== proposal.actionKind
|| !matchesTodoTarget(result.proposal)
+ || (isTodoCreation && result.proposal.normalized_parameters.goal_id !== proposal.goalId)
|| (proposal.actionKind === "goal.lifecycle" && (
result.proposal.normalized_parameters.goal_id !== proposal.goalId
|| lifecycleOperationFor(result.proposal) !== proposal.lifecycleOperation
@@ -2207,7 +2217,7 @@ export function PersonalWorkspacePage({
setActionFeedback(completedActionFeedback(applied, t));
// Keep the success receipt visible for reviewed actions. Direct actions
// surface the same result through the persistent feedback receipt.
- if (applied.actionKind === "todo.create" || applied.actionKind === "goal.create") {
+ if (isTodoCreation || applied.actionKind === "goal.create") {
await callbacks.onRefresh?.();
}
if (applied.actionKind === "goal.lifecycle" && (applied.lifecycleOperation === "delete" || (applied.lifecycleOperation === "stop" && !options.keepGoalSelected))) {
@@ -2231,17 +2241,23 @@ export function PersonalWorkspacePage({
const observed = returned.success && returned.data.proposal_id === proposal.previewId
&& returned.data.action_kind === proposal.actionKind && returned.data.normalized_parameters.goal_id === proposal.goalId
? workspaceProposal(returned.data, t) : proposal;
+ const retryOriginal = returned.success && returned.data.status === "gated"
+ && observed !== proposal && observed.reviewPlan?.retryOriginal === true
+ && observed.reviewPlan.sourceFingerprint === proposal.reviewPlan?.sourceFingerprint;
+ if (retryOriginal) await actionReadback.acceptProposal(returned.data);
const gated = {
...observed,
- reviewPlan: proposal.reviewPlan ? { ...proposal.reviewPlan, retryOriginal: undefined, interaction: "gated" as const, reason: "authority_gate" as const, canApply: false as const } : undefined,
- impact: proposal.reviewPlan?.retryOriginal ? "" : proposal.impact,
- primaryLabel: proposal.reviewPlan?.retryOriginal ? undefined : proposal.primaryLabel,
+ ...(retryOriginal ? {} : {
+ reviewPlan: proposal.reviewPlan ? { ...proposal.reviewPlan, retryOriginal: undefined, interaction: "gated" as const, reason: "authority_gate" as const, canApply: false as const } : undefined,
+ impact: proposal.reviewPlan?.retryOriginal ? "" : proposal.impact,
+ primaryLabel: proposal.reviewPlan?.retryOriginal ? undefined : proposal.primaryLabel,
+ status: "gated" as const,
+ }),
gate: {
kind: String(gate.kind ?? "protected_action"),
nextAction: typeof gate.next_action === "string" ? gate.next_action : undefined,
summary: String(gate.summary ?? error.message),
},
- status: "gated" as const,
};
setProposals((current) => ({ ...current, [proposal.previewId]: gated }));
// A newly discovered authority gate always deserves review. Preserve
@@ -2261,7 +2277,13 @@ export function PersonalWorkspacePage({
const returned = error instanceof ChatApiError
? typedActionProposalSchema.safeParse(error.payload.proposal) : null;
let stored = returned?.success ? returned.data : undefined;
- const scopedReadback = ["team.plan", "goal.create", "todo.update", "todo.create"].includes(proposal.actionKind);
+ const scopedReadback = isTodoCreation || ["team.plan", "goal.create", "todo.update"].includes(proposal.actionKind);
+ if (!stored && isTodoCreation && !readbackMismatch && !stale) {
+ try {
+ // The Goal list can fail independently of a single confirmation.
+ stored = await loadTypedAction(proposal.previewId, AbortSignal.timeout(8000));
+ } catch { /* The Goal list may still be readable. */ }
+ }
if (!stored && scopedReadback && !readbackMismatch) {
const readback = await actionReadback.refetch();
// Query errors retain cached data; it cannot certify this attempt.
@@ -2279,12 +2301,27 @@ export function PersonalWorkspacePage({
if (observed.reviewPlan?.creationProgress?.goalId) void callbacks.onRefresh?.();
setActionFeedback(stored.status === "stale" ? t("feedback.stale")
: observed.reviewPlan?.interaction === "completed" ? completedActionFeedback(observed, t)
+ : observed.reviewPlan?.retryOriginal ? t(`actionReview.${observed.reviewPlan.reason}`)
+ : isTodoCreation ? t("actionReview.readback_unverified")
: t("feedback.executionFailed", { error: error instanceof Error ? error.message : String(error) }));
return reconciled;
}
+ const httpStatus = error instanceof ChatApiError ? error.payload.http_status : undefined;
+ const interruptedResponse = error instanceof ChatApiError && error.payload.error_code === "chat_api_unavailable"
+ && (httpStatus === undefined || (typeof httpStatus === "number"
+ && (httpStatus < 400 || (httpStatus >= 500 && httpStatus < 600))));
+ if (!stored && !stale && !readbackMismatch && interruptedResponse
+ && isTodoCreation && proposal.reviewPlan?.reason === "canonical_create_projection_pending") {
+ // A lost response or gateway 5xx without a typed result cannot erase
+ // an observed commitment. The original apply rechecks its authority.
+ setProposals(current => ({ ...current, [proposal.previewId]: proposal }));
+ if (options.presentation !== "inline") selectReceipt(proposal);
+ setActionFeedback(t("actionReview.readback_unverified"));
+ return proposal;
+ }
const failed = {
...proposal,
- reviewPlan: proposal.reviewPlan ? { ...proposal.reviewPlan, retryOriginal: undefined, interaction: stale ? "refresh" as const : "repair" as const, reason: readbackMismatch ? "readback_unverified" as const : stale ? "stale_proposal" as const : "apply_failed" as const, canApply: false as const } : undefined,
+ reviewPlan: proposal.reviewPlan ? { ...proposal.reviewPlan, retryOriginal: undefined, interaction: stale ? "refresh" as const : "repair" as const, reason: readbackMismatch || (isTodoCreation && !stale) ? "readback_unverified" as const : stale ? "stale_proposal" as const : "apply_failed" as const, canApply: false as const } : undefined,
impact: proposal.reviewPlan?.retryOriginal ? "" : proposal.impact,
primaryLabel: proposal.reviewPlan?.retryOriginal ? undefined : proposal.primaryLabel,
errorMessage: error instanceof Error ? error.message : String(error),
@@ -2292,7 +2329,7 @@ export function PersonalWorkspacePage({
};
setProposals((current) => ({ ...current, [proposal.previewId]: failed }));
if (options.presentation !== "inline") selectReceipt(failed);
- setActionFeedback(t("feedback.executionFailed", { error: failed.errorMessage }));
+ setActionFeedback(isTodoCreation && !stale ? t("actionReview.readback_unverified") : t("feedback.executionFailed", { error: failed.errorMessage }));
return failed;
}
}
diff --git a/docs/project-agent-todo-contract.md b/docs/project-agent-todo-contract.md
index 78552760cf..793fb6d2ca 100644
--- a/docs/project-agent-todo-contract.md
+++ b/docs/project-agent-todo-contract.md
@@ -90,6 +90,33 @@ same operation ID is a conflict. No provider promotion or receipt rewrite occurs
## Write Contract
+Confirming a typed Chat Todo or Monitor prepares the provider revision and
+source registry digest and store identity before writing. The proposal's operation ID and the
+Monitor's first due time are reused on retry. After checking the current Goal
+source and caller authority, retry returns the original receipt for a committed
+create. Chat keeps the original card available after refresh and offers a retry
+through that card. A confirmed create with display delivery pending remains
+recoverable by its original proposal; it cannot be cancelled or regenerated.
+The Goal overview and conversation keep each pending confirmation separate.
+After upgrade, a create-only confirmation saved by an older version can
+recover its original receipt when the provider still proves the create and its
+reviewed predecessor revision. This recovery updates only the display. If the
+confirmation also requested assignment, retry checks that the Agent is still
+registered and the Todo still matches the original creation receipt before
+resuming assignment. If the source cannot be verified, the original card
+identifies the recorded Todo and shows how to recover. A stale preview that
+never started can still be regenerated. An uncommitted create requires the
+reviewed source and provider revision. Older control planes reject the source-bound
+v3 request before writing.
+
+确认 Chat 的 Todo 或 Monitor 提案时,先记录源注册表摘要、权威存储身份和修订号,再执行写入。
+重试沿用原操作 ID 和 Monitor 的首次到期时间。已提交的操作返回原回执,未提交的操作仍校验
+确认时的来源和修订号。刷新后仍可用原确认卡重试。任务已提交但展示还未更新时,不能取消或重新生成原确认。
+Goal 概览和对话保留各自独立的恢复入口。升级后,若权威库仍能验证旧版仅创建确认的原操作和审阅时的前一修订,
+用户可以取回原回执。该恢复只更新展示。如果原确认还要求指派,重试会先确认 Agent 仍在注册表中,
+且 Todo 仍与原创建回执一致,再接续指派。如果无法核验来源,原卡会显示已记录的 Todo 和恢复方式。
+尚未执行的过期预览仍可重新生成。来源绑定请求采用 v3 协议,旧版控制面会在写入前拒绝。
+
For a caller-owned runtime that already registered its Goal/Agent, generate the
model planning checkpoint before writing executable task Todos:
@@ -1328,6 +1355,27 @@ create/update/poll/terminal receipt is recovered before checking current source
contents. Claim replay retains its current acceptance check and rejects a stale
source while preserving `original_receipt`; this adds no new claim grant.
+Chat Task detail and reviewed actions resolve the Goal's source registry and
+runtime before reading or writing. The review basis carries the source identity,
+source registry digest and provider revision. A created Task checkpoint also
+retains the authority store identity and original operation.
+If an unrelated write advances the same store, assignment and managed claim can
+refresh their provider revision after the native owner rejects the previous one.
+The current Todo must match the record in the original native create receipt.
+Chat saves the new revision before dispatch so an interrupted response replays
+the same assignment.
+
+When a separate directory supplies the Goal route, Chat Task, Monitor and Gate
+mutations carry its byte witness as `registry_source.routing_registry`. The
+native transaction checks both registry files at admission and before commit.
+Restore the original source and inspect the retained Task when either source
+changes or the original Todo no longer matches.
+
+The local v3 Todo create and managed claim wires require both
+`expected_provider_revision` and `expected_registry_sha256`. The source check
+uses the existing registry witness. Earlier wire versions retain their original
+behavior.
+
On `authority_source_changed`, inspect current registration and the Todo again
before issuing new work. The rejected attempt writes no canonical head or receipt;
an external validator already executed may have its own effects. This is an
diff --git a/examples/personal-workspace-browser/goal-workspace-create.mjs b/examples/personal-workspace-browser/goal-workspace-create.mjs
index 790f90923a..2c90b13b26 100644
--- a/examples/personal-workspace-browser/goal-workspace-create.mjs
+++ b/examples/personal-workspace-browser/goal-workspace-create.mjs
@@ -22,15 +22,15 @@ export const goalWorkspaceCreateScenario = {
try {
const ready=await Promise.race([once(lines,'line').then(([line])=>JSON.parse(line)),closed.then(()=>{throw new Error(diagnostics);}),new Promise((_,reject)=>{timer=setTimeout(()=>reject(new Error(`Todo backend startup: ${diagnostics}`)),30000);})]);
clearTimeout(timer);
- const backend=`http://127.0.0.1:${ready.port}`, requests=[];
- let refuseApply=true, applyAttempts=0;
+ const backend=`http://127.0.0.1:${ready.port}`, requests=[], applyPaths=[];
+ let refuseApply=true;
const target=new URL(url);target.searchParams.set('goalId','progress-projection');target.searchParams.set('view','overview');
context=await openWorkspacePage(browser,target.toString(),{gotoWaitUntil:"domcontentloaded",beforeGoto:async(_api,page)=>{
for(const pattern of ['**/status.json*','**/api/actions{,/**,?*}','**/api/chat/todo/detail?*']) await page.route(pattern,async route=>{
const request=route.request(),path=new URL(request.url());
if(path.pathname==='/api/actions/preview')requests.push(request.postDataJSON());
if(path.pathname.endsWith('/apply')){
- applyAttempts++;
+ applyPaths.push(path.pathname);
if(refuseApply){await route.fulfill({status:503,json:{ok:false,error:'Synthetic temporary transport refusal'}});return;}
}
const response=await fetchWorkspaceBackend(route,backend);await route.fulfill({response});
@@ -54,8 +54,8 @@ export const goalWorkspaceCreateScenario = {
assert.equal(requests.length,1);assert.equal(requests[0].normalized_parameters.text,text);
assert.equal(requests[0].normalized_parameters.priority,undefined,'Ordinary creation leaves priority to the Todo owner');
await drawer.locator('.personal-primary-action').click();
- await page.getByRole('status').filter({hasText:'Synthetic temporary transport refusal'}).waitFor();
- assert.equal(applyAttempts,1,'The first apply was attempted exactly once');
+ await page.getByRole('status').filter({hasText:'尚不能确认完成'}).waitFor();
+ assert.equal(applyPaths.length,1,'The first apply was attempted exactly once');
assert.equal(await now.locator('.goal-work-row').filter({hasText:text}).count(),0,'The refused apply did not create a task');
await page.locator('.personal-drawer-close').click();assert.equal(await task.inputValue(),rawText);
refuseApply=false;
@@ -65,7 +65,8 @@ export const goalWorkspaceCreateScenario = {
assert.equal(await task.inputValue(),'');
const {stdout}=await promisify(execFile)(python,['-c','from loopx.entrypoint import main; main()','--format','json','--registry',ready.registry,'todo','list','--goal-id','progress-projection','--role','agent'],{cwd:repoRoot,env:{...process.env,PYTHONPATH:repoRoot,LOOPX_USAGE_PING:'0'},timeout:30000});
const result=JSON.parse(stdout),created=result.todos.filter(todo=>todo.title===text);
- assert.equal(applyAttempts,2,'Recovery attempted only one new apply');
+ assert.equal(requests.length,1,'Recovery reopened the original preview');
+ assert.deepEqual(applyPaths,[applyPaths[0],applyPaths[0]],'Recovery applied the same confirmation exactly once more');
assert.equal(created.length,1,'CLI must read exactly one created task');
assert.equal(created[0].priority,'P1','The real Todo owner defaults omitted creation priority');
await page.screenshot({path:resolve(outputDir,'goal-workspace-created.png'),animations:'disabled'});
diff --git a/loopx/capabilities/native_chat/external_conversations.py b/loopx/capabilities/native_chat/external_conversations.py
index 081e83bb6c..f6a33ebfe7 100644
--- a/loopx/capabilities/native_chat/external_conversations.py
+++ b/loopx/capabilities/native_chat/external_conversations.py
@@ -28,6 +28,7 @@
from . import result_review_evidence
from .codex_context import checked_session_home
from .file_discovery import FileChatDiscovery, external_source_route_path, later_equivalent_source_input, source_control_fields
+from .steward_commands import todo_confirmation_readback
# Request journals are named by their 24-hex request_ref; lock metadata and
# other siblings in this directory are not requests.
@@ -1896,14 +1897,12 @@ def _run_steward_action(self, row: dict[str, Any]) -> None:
else:
result = self.actions.apply(argument, steward_context=context, steward_confirmed_at=row["created_at"])
applied = result["proposal"]
- if applied.get("status") != "applied":
- raise ValueError("the creation preview became stale; prepare a new preview")
- resources = applied["receipt"]["resource_ids"]
if applied["action_kind"] == "todo.create":
- row.update(todo_receipt=applied["receipt"], response=(
- f"已记录待办:{applied['normalized_parameters']['text']}\n"
- f"目标:{resources['goal_id']};规范写入回执已读回。本次没有启动执行。"))
+ row.update(todo_confirmation_readback(applied, argument))
else:
+ if applied.get("status") != "applied":
+ raise ValueError("the creation preview became stale; prepare a new preview")
+ resources = applied["receipt"]["resource_ids"]
# Persist a committed creation before fallible adoption.
row.update(commission_resources=resources, commission_adoption_pending=True,
commission_gate=bool(result.get("gate")))
diff --git a/loopx/capabilities/native_chat/steward_commands.py b/loopx/capabilities/native_chat/steward_commands.py
index 5e1c8aae77..c2fbb54fce 100644
--- a/loopx/capabilities/native_chat/steward_commands.py
+++ b/loopx/capabilities/native_chat/steward_commands.py
@@ -121,10 +121,25 @@ def native_command(controller: Any, argv: list[str]) -> dict[str, Any]:
return result
+def todo_confirmation_readback(proposal: dict[str, Any], proposal_id: str) -> dict[str, Any]:
+ failure = proposal.get("failure") or {}
+ if (proposal.get("status") == "failed" and failure.get("error_code") == "canonical_create_projection_pending"
+ and (failure.get("details") or {}).get("canonical_committed") is True):
+ return {"response": ("待办已创建,展示尚未更新。请在原确认有效期内"
+ f"重试 /confirm {proposal_id} 以完成更新。")}
+ if proposal.get("status") != "applied":
+ raise ValueError("the creation preview became stale; prepare a new preview")
+ receipt = proposal["receipt"]
+ return {"todo_receipt": receipt, "response": (
+ f"已记录待办:{proposal['normalized_parameters']['text']}\n"
+ f"目标:{receipt['resource_ids']['goal_id']};规范写入回执已读回。本次没有启动执行。")}
+
+
__all__ = [
"NativeStewardCommandError",
"execute_steward_fast_path",
"native_command",
"native_fast_path_triage",
"parse_steward_fast_path_intent",
+ "todo_confirmation_readback",
]
diff --git a/loopx/chat.py b/loopx/chat.py
index b7dddbc829..d930e35936 100644
--- a/loopx/chat.py
+++ b/loopx/chat.py
@@ -1038,7 +1038,7 @@ def _compact_todo_payload(payload: dict[str, Any], *, applied: bool) -> dict[str
}
-def _todo_preview_fingerprint(payload: dict[str, Any]) -> str:
+def _todo_preview_fingerprint(payload: dict[str, Any], *, source_identity: str | None = None) -> str:
compact = _compact_todo_payload(payload, applied=False)
if payload.get("decision_read_from_provider") is True:
# Bind the transport operation to reviewed intent and provider head.
@@ -1051,19 +1051,28 @@ def _todo_preview_fingerprint(payload: dict[str, Any]) -> str:
"added": compact["added"],
"already_exists": compact["already_exists"],
"expected_revision": _todo_revision(payload),
+ **({"source_identity": source_identity} if source_identity is not None else {}),
}
)
+def todo_create_was_duplicate(payload: dict[str, Any]) -> bool:
+ """Classify the original create, even when this call only read its receipt."""
+ if payload.get("decision_read_from_provider") is True:
+ return payload.get("status") == "no_change"
+ return bool(payload.get("already_exists"))
+
+
def _todo_write_receipt(
*,
preview_id: str,
- preview_payload: dict[str, Any],
+ preview_revision: str | None,
applied_payload: dict[str, Any],
) -> dict[str, Any]:
compact = _compact_todo_payload(applied_payload, applied=True)
todo = compact["todo"]
- outcome = "todo_already_exists" if compact["already_exists"] else "todo_added"
+ already_exists = todo_create_was_duplicate(applied_payload)
+ outcome = "todo_already_exists" if already_exists else "todo_added"
receipt = {
"schema_version": CHAT_TODO_RECEIPT_SCHEMA_VERSION,
"preview_id": preview_id,
@@ -1071,8 +1080,8 @@ def _todo_write_receipt(
"todo_id": todo["todo_id"],
"status": "applied",
"outcome": outcome,
- "already_exists": compact["already_exists"],
- "preview_revision": _todo_revision(preview_payload),
+ "already_exists": already_exists,
+ "preview_revision": preview_revision,
}
receipt["receipt_id"] = _stable_digest(receipt)
return receipt
@@ -1084,6 +1093,7 @@ def _todo_no_write_receipt(
current_preview: dict[str, Any],
write_attempted: bool = False,
state_revision: str | None = None,
+ source_identity: str | None = None,
) -> dict[str, Any]:
receipt = {
"schema_version": CHAT_TODO_NO_WRITE_RECEIPT_SCHEMA_VERSION,
@@ -1092,7 +1102,7 @@ def _todo_no_write_receipt(
"outcome": "preview_stale",
"write_attempted": write_attempted,
**(
- {"current_preview_id": _todo_preview_fingerprint(current_preview)}
+ {"current_preview_id": _todo_preview_fingerprint(current_preview, source_identity=source_identity)}
if not write_attempted and state_revision is None
else {}
),
@@ -1106,15 +1116,20 @@ def _add_review_todo(
*,
registry_path: Path,
goal_id: str,
+ runtime_root_arg: str | None,
text: str,
priority: str | None = None,
dry_run: bool,
expected_provider_revision: str | None = None,
operation_id: str | None = None,
+ expected_registry_sha256: str | None = None,
+ routing_registry_witness: dict[str, str] | None = None,
+ expected_store_identity: str | None = None,
) -> dict[str, Any]:
return add_goal_todo(
registry_path=registry_path,
goal_id=goal_id,
+ runtime_root_arg=runtime_root_arg,
role="agent",
text=_normalize_todo_text(text),
priority=priority,
@@ -1127,19 +1142,63 @@ def _add_review_todo(
if expected_provider_revision is not None
else {}
),
+ **({"expected_store_identity": expected_store_identity} if expected_store_identity is not None else {}),
+ **({"expected_registry_sha256": expected_registry_sha256}
+ if expected_registry_sha256 is not None else {}),
+ **({"routing_registry_witness": routing_registry_witness}
+ if routing_registry_witness is not None else {}),
)
+def plan_reviewed_todo_create(
+ *, registry_path: Path, goal_id: str, runtime_root_arg: str, text: str,
+ priority: str | None, source_identity: str,
+) -> tuple[str, str]:
+ preview = _add_review_todo(registry_path=registry_path, goal_id=goal_id,
+ runtime_root_arg=runtime_root_arg, text=text, priority=priority, dry_run=True)
+ revision = _todo_revision(preview)
+ if preview.get("decision_read_from_provider") is not True or not revision:
+ raise ValueError("Todo confirmation requires a canonical preview")
+ return _todo_preview_fingerprint(preview, source_identity=source_identity), revision
+
+
+def apply_prepared_todo_review(
+ *, registry_path: Path, goal_id: str, runtime_root_arg: str, text: str,
+ priority: str | None, preview_id: str, operation_id: str,
+ expected_provider_revision: str, expected_registry_sha256: str, expected_store_identity: str,
+ routing_registry_witness: dict[str, str] | None = None,
+) -> dict[str, Any]:
+ """Send the original reviewed request so the provider can recover it."""
+ applied = _add_review_todo(registry_path=registry_path, goal_id=goal_id,
+ runtime_root_arg=runtime_root_arg, text=text, priority=priority, dry_run=False,
+ operation_id=operation_id, expected_provider_revision=expected_provider_revision,
+ expected_registry_sha256=expected_registry_sha256, expected_store_identity=expected_store_identity,
+ routing_registry_witness=routing_registry_witness)
+ return {
+ "receipt": _todo_write_receipt(preview_id=preview_id,
+ preview_revision=expected_provider_revision, applied_payload=applied),
+ "authority_write": _todo_authority_write(applied),
+ "projection_delivery": applied["projection_delivery"],
+ }
+
+
+def _todo_authority_write(applied: dict[str, Any]) -> dict[str, Any]:
+ return {key: applied[key] for key in ("provider_revision", "source_authority", "operation_id")}
+
+
def _bound_todo_review_preview(
*,
registry_path: Path,
goal_id: str,
+ runtime_root_arg: str | None,
text: str,
priority: str | None,
+ source_identity: str | None,
) -> dict[str, Any]:
payload = _add_review_todo(
registry_path=registry_path,
goal_id=goal_id,
+ runtime_root_arg=runtime_root_arg,
text=text,
priority=priority,
dry_run=True,
@@ -1153,10 +1212,11 @@ def _bound_todo_review_preview(
return _add_review_todo(
registry_path=registry_path,
goal_id=goal_id,
+ runtime_root_arg=runtime_root_arg,
text=text,
priority=priority,
dry_run=True,
- operation_id="chat-todo:" + _todo_preview_fingerprint(payload),
+ operation_id="chat-todo:" + _todo_preview_fingerprint(payload, source_identity=source_identity),
expected_provider_revision=_todo_revision(payload),
)
except LocalCoordinationAuthorityUnavailable as exc:
@@ -1178,15 +1238,19 @@ def build_todo_review_preview(
goal_id: str,
text: str,
priority: str | None = None,
+ runtime_root_arg: str | None = None,
+ source_identity: str | None = None,
) -> dict[str, Any]:
payload = _bound_todo_review_preview(
registry_path=registry_path,
goal_id=goal_id,
+ runtime_root_arg=runtime_root_arg,
text=text,
priority=priority,
+ source_identity=source_identity,
)
compact = _compact_todo_payload(payload, applied=False)
- compact["preview_id"] = _todo_preview_fingerprint(payload)
+ compact["preview_id"] = _todo_preview_fingerprint(payload, source_identity=source_identity)
return compact
@@ -1197,28 +1261,41 @@ def apply_todo_review_preview(
text: str,
priority: str | None = None,
preview_id: str,
+ runtime_root_arg: str | None = None,
+ expected_registry_sha256: str | None = None,
+ routing_registry_witness: dict[str, str] | None = None,
+ source_identity: str | None = None,
+ return_authority_write: bool = False,
) -> dict[str, Any]:
current_preview = _bound_todo_review_preview(
registry_path=registry_path,
goal_id=goal_id,
+ runtime_root_arg=runtime_root_arg,
text=text,
priority=priority,
+ source_identity=source_identity,
)
- if not preview_id or preview_id != _todo_preview_fingerprint(current_preview):
+ if not preview_id or preview_id != _todo_preview_fingerprint(current_preview, source_identity=source_identity):
raise TodoReviewPreviewConflict(
"stale todo preview; preview the proposal again before applying",
receipt=_todo_no_write_receipt(
goal_id=goal_id,
current_preview=current_preview,
+ source_identity=source_identity,
),
)
try:
applied = _add_review_todo(
registry_path=registry_path,
goal_id=goal_id,
+ runtime_root_arg=runtime_root_arg,
text=text,
priority=priority,
dry_run=False,
+ **({"expected_registry_sha256": expected_registry_sha256}
+ if expected_registry_sha256 is not None else {}),
+ **({"routing_registry_witness": routing_registry_witness}
+ if routing_registry_witness is not None else {}),
**(
{
"expected_provider_revision": _todo_revision(current_preview),
@@ -1229,7 +1306,7 @@ def apply_todo_review_preview(
),
)
except LocalCoordinationAuthorityUnavailable as exc:
- if exc.code != "provider_revision_mismatch":
+ if exc.code not in {"provider_revision_mismatch", "authority_source_changed"}:
raise
# Only a conclusive owner rejection proves no write. Unknown commit
# responses keep their existing original-operation recovery contract.
@@ -1246,7 +1323,9 @@ def apply_todo_review_preview(
compact = _compact_todo_payload(applied, applied=True)
compact["receipt"] = _todo_write_receipt(
preview_id=preview_id,
- preview_payload=current_preview,
+ preview_revision=_todo_revision(current_preview),
applied_payload=applied,
)
+ if return_authority_write and applied.get("decision_read_from_provider") is True:
+ compact["authority_write"] = _todo_authority_write(applied)
return compact
diff --git a/loopx/chat/monitor_actions.py b/loopx/chat/monitor_actions.py
index c73ca78d02..1f6046c60f 100644
--- a/loopx/chat/monitor_actions.py
+++ b/loopx/chat/monitor_actions.py
@@ -7,6 +7,7 @@
from ..control_plane.runtime.time import parse_timestamp
from ..control_plane.todos.mutation_api import complete_goal_todo, update_goal_todo
+from .todo_source import resolve_chat_todo_source
class ChatMonitorActionMixin:
@@ -20,9 +21,13 @@ def _run_monitor_update(
goal_id = str(parameters["goal_id"])
operation = str(parameters["operation"])
+ source = resolve_chat_todo_source(self, goal_id)
+ if basis is not None:
+ source.require_review(basis)
if operation == "stop":
result = complete_goal_todo(
- registry_path=self.registry_path,
+ **source.writer_scope(),
+ routing_registry_witness=source.routing_registry_witness,
goal_id=goal_id,
todo_id=str(parameters["todo_id"]),
evidence="Owner stopped the continuous monitor from typed Chat action.",
@@ -35,7 +40,8 @@ def _run_monitor_update(
)
else:
kwargs: dict[str, Any] = {
- "registry_path": self.registry_path,
+ **source.writer_scope(),
+ "routing_registry_witness": source.routing_registry_witness,
"goal_id": goal_id,
"todo_id": str(parameters["todo_id"]),
"agent_id": str(parameters["agent_id"]),
diff --git a/loopx/chat/status_api.py b/loopx/chat/status_api.py
index c43b0e48d0..770fb85afb 100644
--- a/loopx/chat/status_api.py
+++ b/loopx/chat/status_api.py
@@ -53,10 +53,11 @@
from ..control_plane.todos.list_readback import list_goal_todos
-def goal_read_runtime_root(server: Any) -> str | None:
+def goal_read_runtime_root(server: Any, *, registry: dict[str, Any] | None = None) -> str | None:
"""Keep registry source routing; Chat storage is only an unbound fallback."""
- registry = _discovery_registry(server.registry_path)
- if registry.get("common_runtime_root"):
+ if registry is None:
+ registry = _discovery_registry(server.registry_path)
+ if registry.get("common_runtime_root") or registry.get("registry_role") == "global-local":
# Passing the coordinator's resolved root as an explicit override
# suppresses the collector's per-Goal source_registry routing. A
# global directory may contain Goals owned by different runtimes.
diff --git a/loopx/chat/todo_actions.py b/loopx/chat/todo_actions.py
index 89661dfdeb..a1f852863d 100644
--- a/loopx/chat/todo_actions.py
+++ b/loopx/chat/todo_actions.py
@@ -2,25 +2,22 @@
from __future__ import annotations
-from collections.abc import Iterator
+from collections.abc import Callable, Iterator
from contextlib import ExitStack, contextmanager
from pathlib import Path
from typing import Any
from ..chat_store import ChatSessionStore, TERMINAL_TURN_STATES
from ..file_lock import exclusive_cross_runtime_file_lock
-from ..history import load_registry
-from ..registry import find_registry_goal
from ..control_plane.goals.activation import goal_is_stopped
from ..control_plane.coordination.shadow_management import shadow_maintenance_lock_target
-from ..control_plane.runtime.runtime_projection_route import resolve_goal_source_runtime_route
from ..control_plane.todos.mutation_api import complete_goal_todo, update_goal_todo
from ..control_plane.coordination.local_authority import (
LocalCoordinationAuthorityUnavailable, read_canonical_todos_if_promoted,
)
-from ..paths import effective_runtime_root
from ..control_plane.todos.provider_projection import projection_delivery_requires_ack
from ..control_plane.work_items.task_lease import lease_is_active
+from .todo_source import ChatTodoSource, ChatTodoSourceChanged, resolve_chat_todo_source
def _decision_readback(result: dict[str, Any]) -> dict[str, Any]:
@@ -35,29 +32,50 @@ def _decision_readback(result: dict[str, Any]) -> dict[str, Any]:
class ChatTodoActionMixin:
"""Keep Todo preview/apply parity separate from general orchestration."""
+ def _apply_created_todo_assignment(
+ self, proposal_id: str, *, goal_id: str, todo_id: str, binding: dict[str, Any],
+ steps: dict[str, Any], apply: Callable[[ChatTodoSource, str], dict[str, Any]],
+ ) -> dict[str, Any]:
+ def observe() -> tuple[ChatTodoSource, dict[str, Any]]:
+ source = resolve_chat_todo_source(self, goal_id)
+ source.require_review(binding)
+ authority = read_canonical_todos_if_promoted(runtime_root=source.runtime_root, goal_id=goal_id)
+ source.require_created_todo(binding, authority)
+ return source, authority
+
+ source, _ = observe()
+ basis = steps.get("todo_assignment_basis", binding)
+ try:
+ return apply(source, basis["provider_revision"])
+ except LocalCoordinationAuthorityUnavailable as error:
+ if error.code != "provider_revision_mismatch":
+ raise
+
+ # Only a definitive stale-revision rejection permits a new CAS basis.
+ # Preserve it before dispatch so a lost response replays the same intent.
+ source, authority = observe()
+ revision = source.current_assignment_revision(binding, authority, todo_id)
+ self.store.save_checkpoint(proposal_id, step="todo_assignment_basis", receipt={"provider_revision": revision})
+ return apply(source, revision)
+
@contextmanager
def _confirmed_task_commit(
self, *, goal_id: str, todo_id: str, endpoint: str, project: Path,
- claim: dict[str, Any],
+ claim: dict[str, Any], source: ChatTodoSource, binding: dict[str, Any],
) -> Iterator[None]:
"""Fence acceptance with the same registry and canonical writers as Stop and Todo edits."""
invoked = self.registry_path.resolve()
- route = resolve_goal_source_runtime_route(registry_path=invoked, goal_id=goal_id)
- source = Path(route["source_registry"])
- # Claim used this runtime. Recheck it after taking the same maintenance
- # guard as canonical writers, in the order used by Goal deletion.
- runtime = effective_runtime_root(invoked, None).resolve()
- targets: tuple[Path, ...] = (shadow_maintenance_lock_target(runtime, goal_id), source)
- if source != invoked:
+ runtime = source.runtime_root
+ targets = (shadow_maintenance_lock_target(runtime, goal_id), source.registry_path)
+ if source.registry_path != invoked:
targets += (invoked,)
with ExitStack() as locks:
for target in targets:
locks.enter_context(exclusive_cross_runtime_file_lock(target, operation="confirm_task_admission"))
- if (route != resolve_goal_source_runtime_route(registry_path=invoked, goal_id=goal_id)
- or runtime != effective_runtime_root(invoked, None).resolve()):
- raise ValueError("The reviewed Task's Goal source changed")
- goal = find_registry_goal(load_registry(source), goal_id)
- if goal is None or goal.get("status", "active") not in {"active", "ready"} or goal_is_stopped(goal):
+ current_source = resolve_chat_todo_source(self, goal_id)
+ current_source.require_review(binding)
+ goal = current_source.goal
+ if goal.get("status", "active") not in {"active", "ready"} or goal_is_stopped(goal):
raise ValueError("The Task's Goal is no longer active")
if Path(str(goal.get("repo") or ".")).expanduser().resolve() != project:
raise ValueError("The reviewed Task's project root changed")
@@ -65,6 +83,7 @@ def _confirmed_task_commit(
if self._resolve_goal_agent(goal_id, endpoint, goal=goal) != owner:
raise ValueError("The reviewed Agent endpoint now belongs to another Goal Agent")
authority = read_canonical_todos_if_promoted(runtime_root=runtime, goal_id=goal_id, include_leases=True)
+ current_source.require_created_todo(binding, authority)
todo = next((row for row in authority["todos"] if row["todo_id"] == todo_id), None)
if (todo is None or todo.get("role") != "agent" or todo.get("status") != "open"
or todo.get("claimed_by") != owner or authority["handoff_mode"] != claim["handoff_mode"]):
@@ -107,6 +126,7 @@ def _read_task_start(
def _start_confirmed_task(
self, proposal_id: str, parameters: dict[str, Any], todo_id: str, steps: dict[str, Any],
+ *, source: ChatTodoSource, binding: dict[str, Any],
) -> dict[str, Any]:
from ..chat_actions import _opaque
@@ -142,23 +162,35 @@ def _start_confirmed_task(
raise ValueError("Chat Runtime Controller is unavailable")
if session is not None and session.get("status") == "closed":
raise ValueError("The original Task Session is closed")
- goal = self._goal(goal_id)
+ goal = source.goal
if goal.get("status", "active") not in {"active", "ready"} or goal_is_stopped(goal):
raise ValueError("The Task's Goal is no longer active")
project = Path(str(goal.get("repo") or ".")).expanduser().resolve()
if not project.is_dir():
raise ValueError("the Goal project root is unavailable")
self._agent_eligibility(endpoint, project=project)
- if parameters.get("endpoint_id") and self._resolve_goal_agent(goal_id, endpoint) != owner:
+ if parameters.get("endpoint_id") and self._resolve_goal_agent(goal_id, endpoint, goal=goal) != owner:
raise ValueError("The reviewed Agent endpoint now belongs to another Goal Agent")
- claim_args = {
- "registry_path": self.registry_path, "goal_id": goal_id, "todo_id": todo_id,
+ claim_args: dict[str, Any] = {
+ "goal_id": goal_id, "todo_id": todo_id,
"claimed_by": owner, "agent_id": owner, "claim_only": True, "manage_execution": True,
}
- claim = update_goal_todo(**claim_args, claim_operation_id=f"chat-task-start:{proposal_id}", dry_run=False)
+
+ def apply_claim(current_source: ChatTodoSource, revision: str) -> dict[str, Any]:
+ return update_goal_todo(
+ **current_source.writer_scope(), **claim_args,
+ claim_operation_id=f"chat-task-start:{proposal_id}", dry_run=False,
+ claim_expected_provider_revision=revision,
+ claim_expected_registry_sha256=binding["registry_sha256"],
+ routing_registry_witness=current_source.routing_registry_witness,
+ )
+
+ claim = self._apply_created_todo_assignment(
+ proposal_id, goal_id=goal_id, todo_id=todo_id, binding=binding, steps=steps, apply=apply_claim,
+ )
if claim["handoff_mode"] == "soft_claim" and claim["status"] in {"recovered", "replayed"}:
# A past soft claim still needs a read-only current-owner check.
- if update_goal_todo(**claim_args, dry_run=True)["changed"]:
+ if update_goal_todo(**source.writer_scope(), **claim_args, dry_run=True)["changed"]:
raise ValueError("The reviewed Task assignment changed before launch")
if not isinstance(steps.get("todo_assigned"), dict):
self.store.save_checkpoint(
@@ -176,6 +208,7 @@ def _start_confirmed_task(
session_id=sid, client_turn_id=client_turn_id, message=message, work_dir=project, objective=message,
_goal_commit=lambda: self._confirmed_task_commit(
goal_id=goal_id, todo_id=todo_id, endpoint=endpoint, project=project, claim=claim,
+ source=source, binding=binding,
),
)
@@ -193,8 +226,13 @@ def _run_todo_update(
) -> dict[str, Any]:
goal_id = str(parameters["goal_id"])
operation = str(parameters.get("operation") or "edit")
- if parameters.get("review_basis") is not None and parameters["review_basis"] != basis:
+ reviewed = parameters.get("review_basis")
+ if dry_run and reviewed is not None and (
+ basis is None or any(basis.get(key) != value for key, value in reviewed.items())):
raise ValueError("The Task source changed. Reload its complete requirements before saving.")
+ source = resolve_chat_todo_source(self, goal_id)
+ if basis is not None:
+ source.require_review(basis)
# Transport only caller-supplied proof. The terminal owner revalidates
# the execution; a lease read or a Todo claim is never substitute proof.
proof = {key: parameters[key] for key in (
@@ -203,7 +241,8 @@ def _run_todo_update(
if operation == "complete" and (basis is None or
basis.get("schema_version") == "loopx_chat_canonical_terminal_basis_v0"):
return complete_goal_todo(
- registry_path=self.registry_path,
+ **source.writer_scope(),
+ routing_registry_witness=source.routing_registry_witness,
goal_id=goal_id,
todo_id=str(parameters["todo_id"]),
note=parameters.get("note"),
@@ -223,7 +262,8 @@ def _run_todo_update(
elif operation == "defer":
status = "deferred"
return update_goal_todo(
- registry_path=self.registry_path,
+ **source.writer_scope(),
+ routing_registry_witness=source.routing_registry_witness,
goal_id=goal_id,
todo_id=str(parameters["todo_id"]),
text=parameters.get("text"),
@@ -258,9 +298,14 @@ def _run_gate_resolve(
) -> dict[str, Any]:
# The typed User completion owner decides whether this source may carry
# the outcome and what it does to the dependent; the App only records it.
+ goal_id = str(parameters["goal_id"])
+ source = resolve_chat_todo_source(self, goal_id)
+ if basis is not None:
+ source.require_review(basis)
return complete_goal_todo(
- registry_path=self.registry_path,
- goal_id=str(parameters["goal_id"]),
+ **source.writer_scope(),
+ routing_registry_witness=source.routing_registry_witness,
+ goal_id=goal_id,
todo_id=str(parameters["todo_id"]),
role="user",
decision_outcome=str(parameters["decision"]),
@@ -302,12 +347,14 @@ def _canonical_update_basis(
self, goal_id: str, *, completion_todo_id: str | None = None,
decision: bool = False,
) -> dict[str, Any] | None:
- registry_sha256 = self._registry_fingerprint()
+ source = resolve_chat_todo_source(self, goal_id)
authority = read_canonical_todos_if_promoted(
- runtime_root=effective_runtime_root(self.registry_path, None),
- goal_id=goal_id, include_leases=True,
+ runtime_root=source.runtime_root,
+ goal_id=goal_id,
)
- if self._registry_fingerprint() != registry_sha256:
+ current = resolve_chat_todo_source(self, goal_id)
+ if (current.source_identity, current.registry_sha256) != (
+ source.source_identity, source.registry_sha256):
raise ValueError("Todo authority registration changed while reading; retry")
if authority is None:
return None
@@ -322,7 +369,8 @@ def _canonical_update_basis(
"loopx_chat_canonical_update_basis_v0"),
"provider_revision": authority["provider_revision"],
"source_authority": authority["source_authority"],
- "registry_sha256": registry_sha256,
+ "registry_sha256": source.registry_sha256,
+ "source_identity": source.source_identity,
}
def _apply_reviewed_todo_edit(
@@ -343,6 +391,12 @@ def _apply_reviewed_todo_edit(
terminal = action_kind == "gate.resolve" or parameters.get("operation") in {"complete", "stop"}
try:
result = run(parameters, dry_run=False, basis=basis, operation_id=operation_id)
+ except ChatTodoSourceChanged as error:
+ failed = self.store.mark_failed(
+ proposal_id, error_code="canonical_update_source_changed", message=str(error),
+ details={"operation_id": operation_id},
+ )
+ return {"proposal": failed, "turn": None}
except LocalCoordinationAuthorityUnavailable as error:
if (terminal and error.code == "authority_source_changed"
and error.payload.get("completion_validation_executed") is True):
@@ -358,7 +412,7 @@ def _apply_reviewed_todo_edit(
# The native transaction first established that no matching
# historical receipt exists. This is a rejected new edit.
stale = self.store.apply(proposal_id, current_state_fingerprint=_digest({
- "current": self._goal_state_fingerprint(str(parameters["goal_id"])),
+ "expected": proposal["expected_state_fingerprint"],
"conflict": error.code,
}), receipt={})
return {"proposal": stale, "turn": None}
diff --git a/loopx/chat/todo_creation.py b/loopx/chat/todo_creation.py
new file mode 100644
index 0000000000..db2a0eea64
--- /dev/null
+++ b/loopx/chat/todo_creation.py
@@ -0,0 +1,377 @@
+"""Prepare and recover reviewed Chat Todo and Monitor creation."""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Any, TypedDict
+
+from ..agent_registry import registered_agent_ids_for_goal
+from ..chat import (
+ apply_prepared_todo_review, plan_reviewed_todo_create, todo_create_was_duplicate,
+)
+from ..chat_action_store import action_checkpoint_steps, is_todo_create_recovery
+from ..control_plane.coordination.local_authority import (
+ LocalCoordinationAuthorityUnavailable, read_canonical_todos_if_promoted,
+)
+from ..control_plane.todos.mutation_api import add_goal_todo, update_goal_todo
+from ..control_plane.todos.provider_projection import (
+ projection_delivery_requires_ack, settle_canonical_todo_projection,
+)
+from ..file_lock import LOCK_HOLDER_DEAD, LOCK_HOLDER_RELEASED, lock_holder_liveness, try_exclusive_file_lock
+from .todo_source import ChatTodoSource, ChatTodoSourceChanged, resolve_chat_todo_source
+
+
+class ReviewedCreateAuthority(TypedDict):
+ provider_revision: str
+ store_identity: str
+ source_authority: str
+
+
+class ChatTodoCreationMixin:
+ """Own the confirmation checkpoint; canonical storage owns the write."""
+
+ @staticmethod
+ def _create_authority(source: ChatTodoSource, goal_id: str) -> ReviewedCreateAuthority:
+ authority = read_canonical_todos_if_promoted(runtime_root=source.runtime_root, goal_id=goal_id)
+ if not authority or not all(isinstance(authority.get(key), str) and authority[key] for key in (
+ "provider_revision", "store_identity", "source_authority",
+ )):
+ raise ValueError("The Goal's Todo authority is unavailable")
+ return ReviewedCreateAuthority(provider_revision=authority["provider_revision"],
+ store_identity=authority["store_identity"], source_authority=authority["source_authority"])
+
+ @staticmethod
+ def _monitor_create_fingerprint(source: ChatTodoSource, authority: ReviewedCreateAuthority) -> str:
+ from ..chat_actions import _digest
+
+ return _digest({
+ "source_identity": source.source_identity,
+ "registry_sha256": source.registry_sha256,
+ "store_identity": authority["store_identity"],
+ "provider_revision": authority["provider_revision"],
+ })
+
+ def _save_create_plan(
+ self, proposal: dict[str, Any], source: ChatTodoSource, authority: ReviewedCreateAuthority,
+ *, fingerprint: str, **metadata: Any,
+ ) -> dict[str, Any]:
+ proposal_id = proposal["proposal_id"]
+ return self.store.save_checkpoint(proposal_id, step="todo_create_prepared", once=True,
+ receipt={"operation_id": f"chat-create:{proposal_id}", "preview_id": fingerprint,
+ "source_identity": source.source_identity, "source_authority": authority["source_authority"],
+ "expected_store_identity": authority["store_identity"],
+ "expected_registry_sha256": source.registry_sha256,
+ "expected_provider_revision": authority["provider_revision"], **metadata})
+
+ @staticmethod
+ def _prepared_create_arguments(
+ proposal: dict[str, Any], source: ChatTodoSource,
+ ) -> dict[str, str]:
+ plan = action_checkpoint_steps(proposal).get("todo_create_prepared")
+ if (not isinstance(plan, dict)
+ or plan.get("operation_id") != f"chat-create:{proposal['proposal_id']}"
+ or plan.get("preview_id") != proposal["expected_state_fingerprint"]
+ or not plan.get("source_identity")):
+ raise ValueError("The original confirmation has no complete create plan")
+ source.require_review(plan)
+ keys = ("operation_id", "expected_provider_revision", "expected_registry_sha256", "expected_store_identity")
+ if any(not isinstance(plan.get(key), str) or not plan[key] for key in keys):
+ raise ValueError("The original confirmation has no complete create basis")
+ return {key: plan[key] for key in keys}
+
+ def _create_no_write(
+ self, proposal: dict[str, Any], fingerprint: str,
+ ) -> dict[str, Any]:
+ stale = self.store.apply(proposal["proposal_id"], current_state_fingerprint=fingerprint, receipt={})
+ return {"proposal": stale, "turn": self._turn_from_receipt(stale.get("receipt"))}
+
+ def _create_confirmation_conflict(
+ self, proposal: dict[str, Any], error: LocalCoordinationAuthorityUnavailable,
+ ) -> dict[str, Any]:
+ from ..chat_actions import _digest
+
+ if error.code == "local_authority_provider_identity_mismatch":
+ raise ChatTodoSourceChanged("The reviewed Todo store changed. Restore the original store before retrying.") from error
+ if error.code not in {"provider_revision_mismatch", "authority_source_changed"}:
+ raise error
+ # Only the same opened provider, after original receipt lookup, can
+ # conclusively reject a write that never landed.
+ return self._create_no_write(proposal, _digest({
+ "expected": proposal["expected_state_fingerprint"], "conflict": error.code,
+ "provider_revision": error.payload.get("current_provider_revision"),
+ }))
+
+ def _creation_lock_path(self, proposal_id: str) -> Path:
+ from ..chat_actions import _opaque
+
+ key = _opaque(proposal_id, field="proposal_id")
+ return self.store.root / "task-starts" / f"{key}.json"
+
+ def _creation_lock(self, proposal_id: str):
+ return try_exclusive_file_lock(self._creation_lock_path(proposal_id), operation="confirm_task_start")
+
+ def _project_creation_recovery(self, proposal: dict[str, Any]) -> dict[str, Any]:
+ if proposal.get("status") != "applying" or proposal.get("checkpoint") is not None:
+ return proposal
+ if not is_todo_create_recovery(proposal) or (proposal.get("context") or {}).get("binding_id"):
+ return proposal
+ # Read the holder record without acquiring the lock. Apply still takes
+ # the same kernel fence and validates the current reviewed source.
+ liveness, _ = lock_holder_liveness(self._creation_lock_path(proposal["proposal_id"]))
+ if liveness in {LOCK_HOLDER_DEAD, LOCK_HOLDER_RELEASED}:
+ return {**proposal, "creation_retry_available": True}
+ return proposal
+
+ def _pending_create_projection(
+ self, proposal: dict[str, Any], *, todo_id: str, operation_id: str,
+ ) -> dict[str, Any]:
+ saved = self.store.mark_failed(
+ proposal["proposal_id"],
+ error_code="canonical_create_projection_pending",
+ message="The task was committed. Retry this confirmation to finish updating its display.",
+ details={"canonical_committed": True, "todo_id": todo_id, "operation_id": operation_id,
+ "projection_delivery": "pending"},
+ )
+ return {"proposal": saved, "turn": None}
+
+ def _recover_create_display(
+ self, source: ChatTodoSource, *, goal_id: str, todo_id: str, operation_id: str,
+ binding: dict[str, Any], duplicate: bool = False,
+ ) -> str:
+ # Repair presentation from the confirmed Goal, never from a new create
+ # or assignment. A historical receipt only proves its original effect.
+ snapshot = read_canonical_todos_if_promoted(runtime_root=source.runtime_root, goal_id=goal_id)
+ source.require_created_todo(binding, snapshot)
+ if duplicate:
+ # Semantic duplicates are no-ops and do not get a commit receipt.
+ if not any(row.get("todo_id") == todo_id for row in snapshot["todos"]):
+ raise ChatTodoSourceChanged("Restore the original Goal source to recover this Task confirmation.")
+ else:
+ source.todo_operation_receipt(operation_id, todo_id, snapshot["source_authority"])
+ return settle_canonical_todo_projection(
+ {}, registry_path=source.registry_path, runtime_root=source.runtime_root,
+ goal_id=goal_id, expected_store_identity=snapshot["store_identity"],
+ )["projection_delivery"]
+
+ def _apply_monitor_create(
+ self, proposal_id: str, proposal: dict[str, Any], parameters: dict[str, Any]
+ ) -> dict[str, Any]:
+ from ..chat_actions import _digest, _monitor_metadata, _monitor_text, _opaque
+
+ goal_id = str(parameters["goal_id"])
+ source = resolve_chat_todo_source(self, goal_id)
+ steps = action_checkpoint_steps(proposal)
+ if "todo_create_prepared" not in steps:
+ authority = self._create_authority(source, goal_id)
+ fingerprint = self._monitor_create_fingerprint(source, authority)
+ if fingerprint != proposal["expected_state_fingerprint"]:
+ return self._create_no_write(proposal, fingerprint)
+ agent_id = str(parameters["agent_id"])
+ if agent_id not in registered_agent_ids_for_goal(source.goal):
+ raise ValueError("monitor Agent must be registered for the Goal")
+ if "todo_create_prepared" not in steps:
+ metadata = _monitor_metadata(parameters)
+ stop = str(parameters.get("stop_condition") or "").strip()
+ resume_when = stop if stop and not (metadata.get("expires_at") or metadata.get("watch_only")) else None
+ if not (metadata.get("expires_at") or resume_when or metadata.get("watch_only")):
+ metadata["watch_only"] = "true"
+ proposal = self._save_create_plan(proposal, source, authority, fingerprint=fingerprint,
+ resume_when=resume_when, monitor_metadata=metadata)
+ arguments = self._prepared_create_arguments(proposal, source)
+ operation_id = arguments["operation_id"]
+ created = steps.get("todo_created")
+ if isinstance(created, dict):
+ binding = created.get("source")
+ if not isinstance(binding, dict) or binding.get("operation_id") != operation_id:
+ raise ChatTodoSourceChanged("Restore the original Goal source to recover this Monitor confirmation.")
+ source.require_review(binding)
+ todo_id = _opaque(created.get("todo_id"), field="todo_id")
+ duplicate = created.get("already_exists") is True
+ delivery = self._recover_create_display(source, goal_id=goal_id, todo_id=todo_id,
+ operation_id=operation_id, binding=binding, duplicate=duplicate)
+ else:
+ plan = action_checkpoint_steps(proposal)["todo_create_prepared"]
+ try:
+ result = add_goal_todo(
+ **source.writer_scope(), goal_id=goal_id, role="agent",
+ routing_registry_witness=source.routing_registry_witness,
+ text=_monitor_text(parameters) or str(parameters["target"]),
+ task_class="continuous_monitor", action_kind="observe",
+ claimed_by=agent_id, agent_id=agent_id, resume_when=plan["resume_when"],
+ monitor_metadata=plan["monitor_metadata"], dry_run=False, **arguments,
+ )
+ except LocalCoordinationAuthorityUnavailable as error:
+ return self._create_confirmation_conflict(proposal, error)
+ todo_id = _opaque(result.get("todo_id"), field="todo_id")
+ duplicate = todo_create_was_duplicate(result)
+ delivery = result["projection_delivery"]
+ self.store.save_checkpoint(proposal_id, step="todo_created", once=True, receipt={
+ "todo_id": todo_id, "already_exists": duplicate, "projection_delivery": delivery,
+ "source": {"source_identity": source.source_identity, "source_authority": result["source_authority"],
+ "store_identity": arguments["expected_store_identity"], "operation_id": operation_id},
+ })
+ if not projection_delivery_requires_ack(delivery):
+ return self._pending_create_projection(proposal, todo_id=todo_id, operation_id=operation_id)
+ receipt = {
+ "receipt_id": _digest(
+ {"proposal_id": proposal_id, "goal_id": goal_id, "todo_id": todo_id}
+ )[:32],
+ "outcome": "monitor_already_exists" if duplicate else "monitor_created",
+ "projection_verified": True,
+ "projection_delivery": delivery,
+ "resource_ids": {"goal_id": goal_id, "todo_id": todo_id, "agent_id": agent_id},
+ }
+ stored = self.store.apply(proposal_id,
+ current_state_fingerprint=proposal["expected_state_fingerprint"], receipt=receipt)
+ return {"proposal": stored, "turn": None}
+
+ def _apply_todo_create(
+ self, proposal_id: str, proposal: dict[str, Any], parameters: dict[str, Any],
+ ) -> dict[str, Any]:
+ from ..chat_actions import ProtectedActionGate, _opaque
+
+ goal_id = str(parameters["goal_id"])
+ source = resolve_chat_todo_source(self, goal_id)
+ agent_id = parameters.get("agent_id")
+ start_execution = parameters.get("start_execution") is True
+ steps = action_checkpoint_steps(proposal)
+ current_fingerprint = proposal["expected_state_fingerprint"]
+ todo_step = steps.get("todo_created")
+ assigned = steps.get("todo_assigned")
+ assignment_owns_display = isinstance(assigned, dict) and bool(agent_id) and not start_execution
+ if isinstance(todo_step, dict) and todo_step.get("todo_id"):
+ todo_id = _opaque(todo_step.get("todo_id"), field="todo_id")
+ canonical_receipt = todo_step.get("canonical_receipt")
+ if not isinstance(canonical_receipt, dict):
+ raise ValueError("Todo creation checkpoint is malformed")
+ binding = todo_step.get("source")
+ if "source" not in todo_step:
+ try:
+ if agent_id and agent_id not in registered_agent_ids_for_goal(source.goal):
+ raise ChatTodoSourceChanged("The selected Agent is no longer registered for the Goal")
+ authority = read_canonical_todos_if_promoted(runtime_root=source.runtime_root, goal_id=goal_id)
+ binding = source.recover_legacy_creation(
+ todo_id=todo_id, preview_id=current_fingerprint, receipt=canonical_receipt, authority=authority,
+ require_unchanged=bool(agent_id) or start_execution,
+ )
+ except (ChatTodoSourceChanged, LocalCoordinationAuthorityUnavailable) as error:
+ if not agent_id and not start_execution:
+ raise
+ raise ProtectedActionGate("todo.create", gate={
+ "kind": "canonical_authority_required",
+ "summary": f"The original confirmation recorded Todo {todo_id}. Its assignment source could not be verified.",
+ "next_action": "Restore the original Goal source and retry, or review the assignment from the existing Todo.",
+ }) from error
+ self.store.save_checkpoint(proposal_id, step="todo_created", receipt={**todo_step, "source": binding})
+ if not isinstance(binding, dict):
+ raise ValueError("Todo creation checkpoint source is malformed")
+ source.require_review(binding)
+ create_operation_id = _opaque(binding.get("operation_id"), field="operation_id")
+ delivery = todo_step.get("projection_delivery")
+ if not assignment_owns_display:
+ delivery = self._recover_create_display(source, goal_id=goal_id, todo_id=todo_id,
+ operation_id=create_operation_id, binding=binding,
+ duplicate=canonical_receipt.get("already_exists") is True)
+ else:
+ if agent_id and agent_id not in registered_agent_ids_for_goal(source.goal):
+ raise ValueError("the selected Agent is no longer registered for this Goal")
+ if "todo_create_prepared" not in steps:
+ authority = self._create_authority(source, goal_id)
+ fingerprint, revision = plan_reviewed_todo_create(
+ **source.writer_scope(), goal_id=goal_id, text=str(parameters["text"]),
+ priority=parameters.get("priority"), source_identity=source.source_identity,
+ )
+ if fingerprint != current_fingerprint:
+ return self._create_no_write(proposal, fingerprint)
+ if revision != authority["provider_revision"]:
+ # Never take a preview from one store and prepare it
+ # against an independently observed store or revision.
+ raise ChatTodoSourceChanged("The Todo store changed while confirming. Retry the original preview.")
+ proposal = self._save_create_plan(proposal, source, authority, fingerprint=fingerprint)
+ arguments = self._prepared_create_arguments(proposal, source)
+ try:
+ applied = apply_prepared_todo_review(
+ **source.writer_scope(), goal_id=goal_id, text=str(parameters["text"]),
+ routing_registry_witness=source.routing_registry_witness,
+ priority=parameters.get("priority"), preview_id=current_fingerprint, **arguments,
+ )
+ except LocalCoordinationAuthorityUnavailable as error:
+ return self._create_confirmation_conflict(proposal, error)
+ canonical_receipt = applied["receipt"]
+ delivery = applied["projection_delivery"]
+ todo_id = _opaque(canonical_receipt["todo_id"], field="todo_id")
+ binding = {
+ **applied["authority_write"],
+ "source_identity": source.source_identity,
+ "store_identity": arguments["expected_store_identity"],
+ "registry_sha256": arguments["expected_registry_sha256"],
+ }
+ create_operation_id = binding["operation_id"]
+ proposal = self.store.save_checkpoint(proposal_id, step="todo_created", once=True,
+ receipt={"todo_id": todo_id, "canonical_receipt": canonical_receipt, "source": binding,
+ "projection_delivery": delivery})
+ steps = action_checkpoint_steps(proposal)
+ if not assignment_owns_display and not projection_delivery_requires_ack(delivery):
+ return self._pending_create_projection(proposal, todo_id=todo_id, operation_id=create_operation_id)
+ if agent_id and not start_execution:
+ assignment_operation_id = f"chat-assign:{proposal_id}"
+ source = resolve_chat_todo_source(self, goal_id)
+ source.require_review(binding)
+ if isinstance(assigned, dict):
+ delivery = assigned.get("projection_delivery")
+ if delivery is None or not projection_delivery_requires_ack(delivery):
+ delivery = self._recover_create_display(source, goal_id=goal_id, todo_id=todo_id,
+ operation_id=assignment_operation_id, binding=binding)
+ else:
+ source.require_created_todo(binding,
+ read_canonical_todos_if_promoted(runtime_root=source.runtime_root, goal_id=goal_id))
+ else:
+ def apply_assignment(current_source: ChatTodoSource, revision: str) -> dict[str, Any]:
+ return update_goal_todo(
+ **current_source.writer_scope(), goal_id=goal_id, todo_id=todo_id,
+ claimed_by=str(agent_id), agent_id=str(agent_id),
+ authority_reason="owner-confirmed typed Chat action",
+ update_operation_id=assignment_operation_id,
+ update_expected_provider_revision=revision,
+ update_expected_registry_sha256=binding["registry_sha256"],
+ routing_registry_witness=current_source.routing_registry_witness,
+ dry_run=False,
+ )
+
+ assignment = self._apply_created_todo_assignment(
+ proposal_id, goal_id=goal_id, todo_id=todo_id, binding=binding, steps=steps, apply=apply_assignment,
+ )
+ delivery = assignment["projection_delivery"]
+ self.store.save_checkpoint(proposal_id, step="todo_assigned", once=True,
+ receipt={"todo_id": todo_id, "agent_id": str(agent_id), "projection_delivery": delivery})
+ if not projection_delivery_requires_ack(delivery):
+ return self._pending_create_projection(proposal, todo_id=todo_id, operation_id=assignment_operation_id)
+ receipt = {
+ "receipt_id": str(canonical_receipt["receipt_id"]),
+ "outcome": str(canonical_receipt["outcome"]),
+ "projection_verified": True,
+ "projection_delivery": delivery,
+ "resource_ids": {
+ "goal_id": str(canonical_receipt["goal_id"]),
+ "todo_id": todo_id,
+ **({"agent_id": str(agent_id)} if agent_id else {}),
+ },
+ "canonical_receipt": canonical_receipt,
+ }
+ turn_result = None
+ if start_execution:
+ source = resolve_chat_todo_source(self, goal_id)
+ source.require_review(binding)
+ turn_result = self._start_confirmed_task(
+ proposal_id, parameters, todo_id, steps, source=source, binding=binding,
+ )
+ receipt["resource_ids"].update(
+ {"session_id": turn_result["session_id"], "turn_id": turn_result["turn_id"]}
+ )
+ receipt["outcome"] = "task_execution_started"
+ stored = self.store.apply(
+ proposal_id,
+ current_state_fingerprint=current_fingerprint,
+ receipt=receipt,
+ )
+ return {"proposal": stored, "turn": turn_result}
diff --git a/loopx/chat/todo_detail.py b/loopx/chat/todo_detail.py
index 08def79434..43fd4cad99 100644
--- a/loopx/chat/todo_detail.py
+++ b/loopx/chat/todo_detail.py
@@ -1,9 +1,8 @@
"""Loopback-only exact Task request reads over the existing Todo owner."""
-import hashlib
from urllib.parse import parse_qs, urlparse
-from .status_api import goal_read_runtime_root
+from .todo_source import resolve_chat_todo_source
from ..status_server import is_loopback_host
from ..control_plane.todos.list_readback import list_goal_todos
@@ -23,12 +22,10 @@ def _todo_detail(self) -> None:
try:
if not self.server.registry_path.is_file():
raise OSError("Task registry is unavailable")
- registry_digest = hashlib.sha256(self.server.registry_path.read_bytes()).hexdigest()
- self._registry_and_goal(goal_id)
+ source = resolve_chat_todo_source(self.server, goal_id)
payload = list_goal_todos(
- registry_path=self.server.registry_path, goal_id=goal_id,
+ **source.writer_scope(), goal_id=goal_id,
role="agent", todo_id=todo_id,
- runtime_root_arg=goal_read_runtime_root(self.server),
)
if payload.get("ambiguous"):
self._send_error("The Task source is ambiguous. Refresh its Goal.", status=409)
@@ -37,7 +34,9 @@ def _todo_detail(self) -> None:
if item is None:
self._send_error("The Task is no longer available in this Goal.", status=404)
return
- if hashlib.sha256(self.server.registry_path.read_bytes()).hexdigest() != registry_digest:
+ current = resolve_chat_todo_source(self.server, goal_id)
+ if (current.source_identity, current.registry_sha256) != (
+ source.source_identity, source.registry_sha256):
raise OSError("Task registration changed during the read")
authority = payload.get("authority_read") or {}
# Echo the same canonical CAS used by the existing Chat edit owner.
@@ -45,7 +44,8 @@ def _todo_detail(self) -> None:
basis = ({"schema_version": "loopx_chat_canonical_update_basis_v0",
"provider_revision": authority["provider_revision"],
"source_authority": authority["source_authority"],
- "registry_sha256": registry_digest}
+ "source_identity": source.source_identity,
+ "registry_sha256": source.registry_sha256}
if authority.get("decision_read_from_provider") is True else None)
self._send_json({
"ok": True, "goal_id": goal_id, "todo_id": item["todo_id"],
diff --git a/loopx/chat/todo_source.py b/loopx/chat/todo_source.py
new file mode 100644
index 0000000000..105b79fd20
--- /dev/null
+++ b/loopx/chat/todo_source.py
@@ -0,0 +1,176 @@
+"""Route Chat's Todo reads and reviewed mutations to the same Goal source."""
+
+from dataclasses import dataclass
+from hashlib import sha256
+from pathlib import Path
+from typing import Any
+
+from ..chat import CHAT_TODO_RECEIPT_SCHEMA_VERSION, _stable_digest, apply_todo_review_preview, build_todo_review_preview
+from ..control_plane.effect_runtime import effect_runtime_result
+from ..control_plane.runtime.runtime_projection_route import resolve_goal_source_runtime_route
+from ..history import load_registry
+from ..registry import find_registry_goal
+from .status_api import goal_read_runtime_root
+
+
+class ChatTodoSourceChanged(ValueError):
+ """The current route cannot recover a reviewed operation's historical receipt."""
+
+
+@dataclass(frozen=True)
+class ChatTodoSource:
+ registry_path: Path
+ runtime_root: Path
+ source_identity: str
+ registry_sha256: str
+ goal: dict[str, Any]
+ routing_registry_witness: dict[str, str] | None = None
+
+ def writer_scope(self) -> dict[str, Any]:
+ return {"registry_path": self.registry_path, "runtime_root_arg": str(self.runtime_root)}
+
+ def require_review(self, basis: dict[str, Any]) -> None:
+ identity = basis.get("source_identity")
+ if identity is None:
+ # Older reviewed actions carry an exact provider revision and
+ # registry digest. The same canonical transaction still verifies
+ # both before it can authorize a new mutation.
+ return
+ if identity != self.source_identity:
+ raise ChatTodoSourceChanged("The Task's Goal source changed. Restore its original source before retrying.")
+
+ def require_created_todo(self, binding: dict[str, Any], authority: dict[str, Any]) -> None:
+ self.require_review(binding)
+ if (binding.get("source_authority") != authority["source_authority"]
+ or binding.get("store_identity") != authority["store_identity"]):
+ raise ChatTodoSourceChanged("The created Task's Todo store changed. Restore its original store before retrying.")
+
+ def todo_operation_receipt(self, operation_id: str, todo_id: str, source_authority: str) -> dict[str, Any]:
+ goal_id = str(self.goal["id"])
+ result = effect_runtime_result("coordination.local_authority.operation_receipt", {
+ "schema_version": "loopx_local_coordination_operation_receipt_request_v0",
+ "runtime_root": str(self.runtime_root),
+ "goal_id": goal_id,
+ "operation_id": operation_id,
+ }, timeout=15.0)
+ receipts = result.get("receipts", []) if isinstance(result, dict) and result.get("status") == "found" else []
+ if (not isinstance(receipts, list) or len(receipts) != 1 or not isinstance(receipts[0], dict)
+ or result.get("source_authority") != source_authority
+ or result.get("decision_read_from_provider") is not True or result.get("legacy_fallback_used") is not False
+ or not isinstance(result.get("provider_revision"), str)):
+ raise ChatTodoSourceChanged("Restore the original Goal source to recover this Task confirmation.")
+ receipt = receipts[0]
+ if receipt.get("goal_id") != goal_id or receipt.get("todo_id") != todo_id or receipt.get("operation_id") != operation_id:
+ raise ChatTodoSourceChanged("The original operation receipt does not identify this Todo.")
+ return result
+
+ def _created_todo_operation(self, operation_id: str, todo_id: str, source_authority: str) -> dict[str, Any]:
+ result = self.todo_operation_receipt(operation_id, todo_id, source_authority)
+ created = result["receipts"][0]
+ if (created.get("schema_version") != "loopx_coordination_todo_create_receipt_v0"
+ or not isinstance(created.get("todo"), dict)):
+ raise ChatTodoSourceChanged("The original Task creation receipt does not identify this Todo.")
+ return result
+
+ def recover_legacy_creation(
+ self, *, todo_id: str, preview_id: str, receipt: dict[str, Any], authority: dict[str, Any],
+ require_unchanged: bool,
+ ) -> dict[str, Any]:
+ goal_id = str(self.goal["id"])
+ if (not preview_id or receipt.get("schema_version") != CHAT_TODO_RECEIPT_SCHEMA_VERSION
+ or receipt.get("preview_id") != preview_id or receipt.get("goal_id") != goal_id
+ or receipt.get("todo_id") != todo_id or receipt.get("status") != "applied"
+ or receipt.get("receipt_id") != _stable_digest({k: v for k, v in receipt.items() if k != "receipt_id"})):
+ raise ValueError("Todo creation checkpoint is malformed")
+ preview_revision = receipt.get("preview_revision")
+ if (receipt.get("outcome") != "todo_added" or not isinstance(preview_revision, str) or not preview_revision
+ or not authority or not authority.get("store_identity") or not authority.get("source_authority")):
+ raise ChatTodoSourceChanged("The original Task creation authority is unavailable.")
+ operation_id = f"chat-todo:{preview_id}"
+ result = self._created_todo_operation(operation_id, todo_id, authority["source_authority"])
+ cursor = result.get("cursor")
+ if not isinstance(cursor, str) or not cursor.isdecimal() or int(cursor) < 2:
+ raise ChatTodoSourceChanged("The original Task creation revision is unavailable.")
+
+ # The preview revision must be the predecessor of this operation in
+ # the same verified store, even if a replacement reused the Todo id.
+ original = effect_runtime_result("coordination.local_authority.todo_source", {
+ "schema_version": "loopx_local_coordination_todo_source_request_v0",
+ "runtime_root": str(self.runtime_root),
+ "goal_id": goal_id,
+ "source": {
+ "source_authority": authority["source_authority"],
+ "store_identity": authority["store_identity"],
+ "provider_revision": preview_revision,
+ "cursor": str(int(cursor) - 1),
+ },
+ }, timeout=15.0)
+ if (not isinstance(original, dict) or original.get("status") != "loaded"
+ or original.get("decision_read_from_provider") is not True or original.get("legacy_fallback_used") is not False):
+ raise ChatTodoSourceChanged("Restore the original Goal source to recover this Task confirmation.")
+ if require_unchanged:
+ todo = next((row for row in authority["todos"] if row["todo_id"] == todo_id), None)
+ if result["receipts"][0]["todo"] != todo:
+ raise ChatTodoSourceChanged("The created Task no longer matches its original receipt. Review it before assigning.")
+ return {
+ "operation_id": operation_id,
+ "provider_revision": result["provider_revision"],
+ "source_authority": authority["source_authority"],
+ "source_identity": self.source_identity,
+ "store_identity": authority["store_identity"],
+ "registry_sha256": self.registry_sha256,
+ }
+
+ def current_assignment_revision(self, binding: dict[str, Any], authority: dict[str, Any], todo_id: str) -> str:
+ operation_id = binding.get("operation_id")
+ if not isinstance(operation_id, str) or not operation_id:
+ raise ChatTodoSourceChanged("The original Task creation operation is unavailable.")
+ result = self._created_todo_operation(operation_id, todo_id, binding["source_authority"])
+ todo = next((row for row in authority["todos"] if row["todo_id"] == todo_id), None)
+ if result["provider_revision"] != binding["provider_revision"] or result["receipts"][0]["todo"] != todo:
+ raise ChatTodoSourceChanged("The created Task no longer matches its original receipt. Review it before assigning.")
+ return str(authority["provider_revision"])
+
+
+def resolve_chat_todo_source(host: Any, goal_id: str) -> ChatTodoSource:
+ invoked = host.registry_path.expanduser().resolve()
+ snapshots: dict[Path, bytes | None] = {}
+ directory = load_registry(invoked, source_snapshots=snapshots)
+ if find_registry_goal(directory, goal_id) is None:
+ raise ValueError("goal_id was not found in the active LoopX registry")
+ route = resolve_goal_source_runtime_route(
+ registry_path=invoked, goal_id=goal_id, registry=directory, source_snapshots=snapshots,
+ runtime_root_override=goal_read_runtime_root(host, registry=directory),
+ )
+ source = Path(route["source_registry"])
+ registry = load_registry(source, source_snapshots=snapshots)
+ goal = find_registry_goal(registry, goal_id)
+ if goal is None:
+ raise ValueError("The Goal is unavailable in its source registry")
+ for path in {invoked, source}:
+ if path.read_bytes() != snapshots[path]:
+ raise ValueError("Todo authority registration changed while reading; retry")
+ runtime = Path(route["source_runtime_root"])
+ return ChatTodoSource(
+ source, runtime, _stable_digest({"registry": str(source), "runtime": str(runtime)}, length=64),
+ sha256(snapshots[source] or b"").hexdigest(), goal,
+ routing_registry_witness=(
+ {"path": str(invoked), "sha256": sha256(snapshots[invoked] or b"").hexdigest()}
+ if invoked != source else None
+ ),
+ )
+
+
+def review_todo_create(
+ host: Any, *, goal_id: str, text: str, preview_id: str | None,
+) -> dict[str, Any]:
+ source = resolve_chat_todo_source(host, goal_id)
+ if preview_id is None:
+ return build_todo_review_preview(
+ **source.writer_scope(), goal_id=goal_id, text=text, source_identity=source.source_identity,
+ )
+ return apply_todo_review_preview(
+ **source.writer_scope(), goal_id=goal_id, text=text, preview_id=preview_id,
+ source_identity=source.source_identity, expected_registry_sha256=source.registry_sha256,
+ routing_registry_witness=source.routing_registry_witness,
+ )
diff --git a/loopx/chat_action_normalization.py b/loopx/chat_action_normalization.py
index ebdfc9f9a8..7c5ebd2d8d 100644
--- a/loopx/chat_action_normalization.py
+++ b/loopx/chat_action_normalization.py
@@ -40,6 +40,7 @@ def _normalize(
_opaque,
_text,
)
+ from .chat.todo_source import resolve_chat_todo_source
if action_kind == "goal.acceptance.check":
values = self._allowed_parameters(parameters, allowed={"goal_id", "document", "prepared_by"})
@@ -360,7 +361,7 @@ def _normalize(
},
)
goal_id = _opaque(values.get("goal_id"), field="goal_id")
- self._goal(goal_id)
+ goal = resolve_chat_todo_source(self, goal_id).goal
result = {
"goal_id": goal_id,
"text": _text(values.get("text"), field="text", limit=400),
@@ -370,10 +371,10 @@ def _normalize(
if values.get("endpoint_id"):
endpoint_id = _opaque(values.get("endpoint_id"), field="endpoint_id")
result["endpoint_id"] = endpoint_id
- result["agent_id"] = self._resolve_goal_agent(goal_id, endpoint_id)
+ result["agent_id"] = self._resolve_goal_agent(goal_id, endpoint_id, goal=goal)
elif values.get("agent_id"):
agent_id = _opaque(values.get("agent_id"), field="agent_id")
- if agent_id not in registered_agent_ids_for_goal(self._goal(goal_id)):
+ if agent_id not in registered_agent_ids_for_goal(goal):
raise ProtectedActionGate(
"agent.bind",
gate={
@@ -415,7 +416,7 @@ def _normalize(
},
)
goal_id = _opaque(values.get("goal_id"), field="goal_id")
- self._goal(goal_id)
+ goal = resolve_chat_todo_source(self, goal_id).goal
result: dict[str, Any] = {
"goal_id": goal_id,
"todo_id": _opaque(values.get("todo_id"), field="todo_id"),
@@ -436,10 +437,13 @@ def _normalize(
if "review_basis" in values:
basis = values["review_basis"]
if (operation != "edit" or not values.get("text") or not isinstance(basis, dict)
- or set(basis) != {"schema_version", "provider_revision", "source_authority", "registry_sha256"}
+ or set(basis) - {"source_identity"} != {
+ "schema_version", "provider_revision", "source_authority", "registry_sha256",
+ }
or basis.get("schema_version") != "loopx_chat_canonical_update_basis_v0"
or any(not isinstance(x, str) or not x for x in basis.values())
- or not BARE_SHA256_PATTERN.fullmatch(basis["registry_sha256"])):
+ or not BARE_SHA256_PATTERN.fullmatch(basis["registry_sha256"])
+ or ("source_identity" in basis and not BARE_SHA256_PATTERN.fullmatch(basis["source_identity"]))):
raise ValueError("Task edit requires its complete current source basis")
result["review_basis"] = dict(basis)
if values.get("text"):
@@ -460,7 +464,7 @@ def _normalize(
if values.get("endpoint_id"):
endpoint_id = _opaque(values["endpoint_id"], field="endpoint_id")
result["endpoint_id"] = endpoint_id
- result["agent_id"] = self._resolve_goal_agent(goal_id, endpoint_id)
+ result["agent_id"] = self._resolve_goal_agent(goal_id, endpoint_id, goal=goal)
elif values.get("agent_id"):
result["agent_id"] = _opaque(values["agent_id"], field="agent_id")
if values.get("resume_when"):
@@ -798,7 +802,7 @@ def _normalize(
},
)
goal_id = _opaque(values.get("goal_id"), field="goal_id")
- self._goal(goal_id)
+ goal = resolve_chat_todo_source(self, goal_id).goal
operation = str(values.get("operation") or "").strip().lower()
if operation not in {"pause", "resume", "stop", "run_now", "edit"}:
raise ValueError(
@@ -813,7 +817,7 @@ def _normalize(
if values.get("endpoint_id"):
endpoint_id = _opaque(values["endpoint_id"], field="endpoint_id")
result["endpoint_id"] = endpoint_id
- result["agent_id"] = self._resolve_goal_agent(goal_id, endpoint_id)
+ result["agent_id"] = self._resolve_goal_agent(goal_id, endpoint_id, goal=goal)
if values.get("target"):
result["target"] = _text(values["target"], field="target", limit=400)
if values.get("target_key"):
diff --git a/loopx/chat_action_store.py b/loopx/chat_action_store.py
index 3601c7a6f3..fc2ebad67c 100644
--- a/loopx/chat_action_store.py
+++ b/loopx/chat_action_store.py
@@ -90,6 +90,22 @@ class ActionConflictError(RuntimeError):
"""Raised when a typed action transition conflicts with durable state."""
+def action_checkpoint_steps(proposal: Mapping[str, Any]) -> dict[str, Any]:
+ checkpoint = proposal.get("checkpoint")
+ steps = checkpoint.get("steps") if isinstance(checkpoint, dict) else None
+ return steps if isinstance(steps, dict) else {}
+
+
+def is_todo_create_recovery(proposal: Mapping[str, Any]) -> bool:
+ return (
+ proposal.get("action_kind") in ("todo.create", "monitor.create")
+ and (bool(action_checkpoint_steps(proposal).keys() & {"todo_create_prepared", "todo_created"})
+ or (proposal.get("status") == "failed"
+ and (proposal.get("failure") or {}).get("error_code") == "canonical_action_failed")
+ or proposal.get("status") == "applying")
+ )
+
+
def _utc_now() -> str:
return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
@@ -1320,6 +1336,8 @@ def cancel(self, proposal_id: str) -> dict[str, Any]:
raise ActionConflictError(
f"proposal in {proposal.get('status')} state cannot be cancelled"
)
+ if is_todo_create_recovery(proposal):
+ raise ActionConflictError("Creation is already confirmed; recover the original operation.")
now = _utc_now()
proposal["status"] = "cancelled"
proposal["cancelled_at"] = now
@@ -1398,6 +1416,7 @@ def save_checkpoint(
*,
step: str,
receipt: Mapping[str, Any],
+ once: bool = False,
) -> dict[str, Any]:
safe_step = _opaque_id(step, field="step")
safe_receipt = _safe_json_value(dict(receipt), path="checkpoint.receipt")
@@ -1413,6 +1432,8 @@ def save_checkpoint(
proposal = payload["proposals"].get(token)
if not isinstance(proposal, dict):
raise KeyError("typed Chat action proposal was not found")
+ if once and proposal.get("status") == "applied":
+ return proposal
if proposal.get("status") not in {"applying", "gated", "failed"}:
raise ActionConflictError(
f"proposal in {proposal.get('status')} state cannot save a checkpoint"
@@ -1423,6 +1444,8 @@ def save_checkpoint(
)
steps = checkpoint.get("steps")
steps = dict(steps) if isinstance(steps, dict) else {}
+ if once and safe_step in steps:
+ return proposal
steps[safe_step] = safe_receipt
checkpoint["steps"] = steps
checkpoint["last_completed_step"] = safe_step
@@ -1499,6 +1522,8 @@ def _transition(
raise ActionConflictError(
f"proposal in {status} state cannot become {to_state}"
)
+ if to_state in {"deferred", "rejected"} and is_todo_create_recovery(proposal):
+ raise ActionConflictError("Creation is already confirmed; recover the original operation.")
proposal["status"] = to_state
proposal.update(_safe_json_value(dict(updates), path="transition"))
proposal["updated_at"] = _utc_now()
diff --git a/loopx/chat_actions.py b/loopx/chat_actions.py
index f743e72841..2a08326bce 100644
--- a/loopx/chat_actions.py
+++ b/loopx/chat_actions.py
@@ -8,20 +8,27 @@
import re
from typing import Any, Mapping, Sequence
-from .agent_registry import agent_profile_for_goal, registered_agent_ids_for_goal
+from .agent_registry import (
+ agent_profile_for_goal,
+ registered_agent_ids_for_goal,
+)
from .control_plane.projects.identity import GoalCreationConflictError
from .control_plane.coordination.new_goal_storage_transport import initialize_goal_storage_target
-from .chat import apply_todo_review_preview, build_todo_review_preview
+from .chat import build_todo_review_preview
from .chat_action_normalization import ChatActionNormalizationMixin
from .chat_action_store import (
ACTION_KINDS as SUPPORTED_ACTION_KINDS,
ActionConflictError,
ChatActionStore,
+ action_checkpoint_steps,
+ is_todo_create_recovery,
)
from .chat_goal_lifecycle_actions import ChatGoalLifecycleActionMixin
from .chat.monitor_actions import ChatMonitorActionMixin
from .chat_store import ChatSessionStore, TERMINAL_TURN_STATES
from .chat.todo_actions import ChatTodoActionMixin
+from .chat.todo_creation import ChatTodoCreationMixin
+from .chat.todo_source import resolve_chat_todo_source
from .control_plane.goals.acceptance_actions import GoalAcceptanceActionMixin
from .control_plane.goals.goal_objective_actions import GoalObjectiveActionMixin
from .configure_goal import configure_goal
@@ -40,8 +47,7 @@
from .public_safe_text import OPAQUE_ID_PATTERN as _OPAQUE_ID
from .quota import build_quota_should_run
from .registry import registry_goals
-from .control_plane.todos.mutation_api import add_goal_todo, update_goal_todo
-from .file_lock import try_exclusive_file_lock
+from .control_plane.todos.mutation_api import add_goal_todo
CHAT_ACTION_RESPONSE_SCHEMA_VERSION = "loopx_chat_action_response_v1"
@@ -225,6 +231,7 @@ class ChatActionService(
ChatGoalLifecycleActionMixin,
ChatMonitorActionMixin,
ChatTodoActionMixin,
+ ChatTodoCreationMixin,
):
"""Validate previews and route applies through canonical LoopX services."""
@@ -1186,66 +1193,6 @@ def _heartbeat_gate(self, parameters: dict[str, Any]) -> ProtectedActionGate:
},
)
- def _apply_monitor_create(
- self, proposal_id: str, proposal: dict[str, Any], parameters: dict[str, Any]
- ) -> dict[str, Any]:
- current_fingerprint = self._registry_fingerprint()
- if current_fingerprint != proposal.get("expected_state_fingerprint"):
- stale = self.store.apply(
- proposal_id, current_state_fingerprint=current_fingerprint, receipt={}
- )
- return {"proposal": stale, "turn": None}
- goal_id = str(parameters["goal_id"])
- agent_id = str(parameters["agent_id"])
- if agent_id not in registered_agent_ids_for_goal(self._goal(goal_id)):
- raise ValueError("monitor Agent must be registered for the Goal")
- stop_condition = str(parameters.get("stop_condition") or "").strip()
- resume_when = None
- if (
- stop_condition
- and parse_timestamp(stop_condition) is None
- and stop_condition.lower()
- not in {"watch_only", "watch-only", "watch", "continuous", "never"}
- ):
- resume_when = stop_condition
- metadata = _monitor_metadata(parameters)
- if not (
- metadata.get("expires_at") or resume_when or metadata.get("watch_only")
- ):
- metadata["watch_only"] = "true"
- result = add_goal_todo(
- registry_path=self.registry_path,
- goal_id=goal_id,
- role="agent",
- text=_monitor_text(parameters) or str(parameters["target"]),
- task_class="continuous_monitor",
- action_kind="observe",
- claimed_by=agent_id,
- agent_id=agent_id,
- resume_when=resume_when,
- monitor_metadata=metadata,
- dry_run=False,
- )
- todo_id = _opaque(result.get("todo_id"), field="todo_id")
- receipt = {
- "receipt_id": _digest(
- {"proposal_id": proposal_id, "goal_id": goal_id, "todo_id": todo_id}
- )[:32],
- "outcome": "monitor_already_exists"
- if result.get("already_exists")
- else "monitor_created",
- "projection_verified": True,
- "resource_ids": {
- "goal_id": goal_id,
- "todo_id": todo_id,
- "agent_id": agent_id,
- },
- }
- stored = self.store.apply(
- proposal_id, current_state_fingerprint=current_fingerprint, receipt=receipt
- )
- return {"proposal": stored, "turn": None}
-
def _apply_team_plan(
self, proposal_id: str, proposal: dict[str, Any], parameters: dict[str, Any]
) -> dict[str, Any]:
@@ -1396,15 +1343,23 @@ def preview(self, request: Mapping[str, Any]) -> dict[str, Any]:
]
permission = "protected"
elif action_kind == "todo.create":
+ source = resolve_chat_todo_source(self, normalized["goal_id"])
canonical_preview = build_todo_review_preview(
- registry_path=self.registry_path,
+ **source.writer_scope(),
goal_id=normalized["goal_id"],
text=normalized["text"],
priority=normalized.get("priority"),
+ source_identity=source.source_identity,
)
fingerprint = str(canonical_preview["preview_id"])
evidence = ["Canonical LoopX Todo dry-run validated the proposal."]
permission = "durable_write"
+ elif action_kind == "monitor.create":
+ goal_id = normalized["goal_id"]
+ source = resolve_chat_todo_source(self, goal_id)
+ fingerprint = self._monitor_create_fingerprint(source, self._create_authority(source, goal_id))
+ evidence = ["The original Goal's Todo authority and current revision validated the Monitor preview."]
+ permission = "durable_write"
elif action_kind == "run.correct":
fingerprint = self._session_fingerprint(
normalized["session_id"], normalized["goal_id"]
@@ -1548,7 +1503,14 @@ def preview(self, request: Mapping[str, Any]) -> dict[str, Any]:
)
def load(self, proposal_id: str) -> dict[str, Any] | None:
- return self.store.load(proposal_id)
+ proposal = self.store.load(proposal_id)
+ return self._project_creation_recovery(proposal) if proposal is not None else None
+
+ def list_proposals(
+ self, *, goal_id: str | None, context_kind: str | None, status: str | None,
+ ) -> list[dict[str, Any]]:
+ proposals = self.store.list(goal_id=goal_id, context_kind=context_kind, status=status)
+ return [self._project_creation_recovery(proposal) for proposal in proposals]
def cancel(self, proposal_id: str) -> dict[str, Any]:
return self.store.cancel(proposal_id)
@@ -1592,7 +1554,19 @@ def regenerate(self, proposal_id: str) -> dict[str, Any]:
"next_action": "Prepare a new operation instead of regenerating this one.",
},
)
- if proposal.get("action_kind") == "goal.create" and (proposal.get("checkpoint") or {}).get("steps"):
+ if proposal.get("action_kind") in {"todo.create", "monitor.create"}:
+ with self._creation_lock(proposal_id) as held:
+ if held is None:
+ raise ActionConflictError("The original confirmation is in progress.")
+ return self._regenerate_current(proposal_id)
+ return self._regenerate_current(proposal_id)
+
+ def _regenerate_current(self, proposal_id: str) -> dict[str, Any]:
+ proposal = self.store.load(proposal_id)
+ if proposal is None:
+ raise KeyError("typed Chat action proposal was not found")
+ if is_todo_create_recovery(proposal) or (
+ proposal.get("action_kind") == "goal.create" and action_checkpoint_steps(proposal)):
raise ActionConflictError("Creation already recorded effects; recover the original operation instead of regenerating")
if proposal.get("status") not in {"stale", "failed", "gated", "rejected"}:
raise ActionConflictError(
@@ -1651,14 +1625,12 @@ def _apply_owner_action(self, proposal_id: str, *, steward_context: dict[str, ob
},
)
parameters = proposal.get("normalized_parameters")
- if (proposal.get("action_kind") in {"todo.create", "goal.create"} and isinstance(parameters, dict)
- and parameters.get("start_execution") is True):
- key = _opaque(proposal_id, field="proposal_id")
- with try_exclusive_file_lock(
- self.store.root / "task-starts" / f"{key}.json", operation="confirm_task_start",
- ) as held:
+ action_kind = proposal.get("action_kind")
+ if isinstance(parameters, dict) and (action_kind in {"todo.create", "monitor.create"}
+ or (action_kind == "goal.create" and parameters.get("start_execution") is True)):
+ with self._creation_lock(proposal_id) as held:
if held is None:
- raise ActionConflictError("The original Task confirmation is in progress. Retry it when it finishes.")
+ raise ActionConflictError("The original confirmation is in progress. Retry it when it finishes.")
return self._apply_confirmed_action(proposal_id)
return self._apply_confirmed_action(proposal_id)
@@ -1710,91 +1682,7 @@ def _apply_confirmed_action(self, proposal_id: str) -> dict[str, object]:
},
)
if action_kind == "todo.create":
- checkpoint = proposal.get("checkpoint")
- steps = checkpoint.get("steps") if isinstance(checkpoint, dict) else {}
- steps = steps if isinstance(steps, dict) else {}
- todo_step = steps.get("todo_created")
- if isinstance(todo_step, dict) and todo_step.get("todo_id"):
- todo_id = _opaque(todo_step.get("todo_id"), field="todo_id")
- canonical_receipt = todo_step.get("canonical_receipt")
- if not isinstance(canonical_receipt, dict):
- raise ValueError("Todo creation checkpoint is malformed")
- current_fingerprint = str(
- proposal.get("expected_state_fingerprint") or ""
- )
- else:
- current = build_todo_review_preview(
- registry_path=self.registry_path,
- goal_id=str(parameters["goal_id"]),
- text=str(parameters["text"]),
- priority=parameters.get("priority"),
- )
- current_fingerprint = str(current["preview_id"])
- if current_fingerprint != proposal.get("expected_state_fingerprint"):
- stale = self.store.apply(
- proposal_id,
- current_state_fingerprint=current_fingerprint,
- receipt={},
- )
- return {"proposal": stale, "turn": None}
- applied = apply_todo_review_preview(
- registry_path=self.registry_path,
- goal_id=str(parameters["goal_id"]),
- text=str(parameters["text"]),
- priority=parameters.get("priority"),
- preview_id=current_fingerprint,
- )
- canonical_receipt = applied["receipt"]
- todo_id = _opaque(canonical_receipt["todo_id"], field="todo_id")
- self.store.save_checkpoint(
- proposal_id,
- step="todo_created",
- receipt={
- "todo_id": todo_id,
- "canonical_receipt": canonical_receipt,
- },
- )
- agent_id = parameters.get("agent_id")
- start_execution = parameters.get("start_execution") is True
- if agent_id and not start_execution and not isinstance(steps.get("todo_assigned"), dict):
- update_goal_todo(
- registry_path=self.registry_path,
- goal_id=str(parameters["goal_id"]),
- todo_id=todo_id,
- claimed_by=str(agent_id),
- agent_id=str(agent_id),
- authority_reason="owner-confirmed typed Chat action",
- dry_run=False,
- )
- self.store.save_checkpoint(
- proposal_id,
- step="todo_assigned",
- receipt={"todo_id": todo_id, "agent_id": str(agent_id)},
- )
- receipt = {
- "receipt_id": str(canonical_receipt["receipt_id"]),
- "outcome": str(canonical_receipt["outcome"]),
- "projection_verified": True,
- "resource_ids": {
- "goal_id": str(canonical_receipt["goal_id"]),
- "todo_id": todo_id,
- **({"agent_id": str(agent_id)} if agent_id else {}),
- },
- "canonical_receipt": canonical_receipt,
- }
- turn_result = None
- if start_execution:
- turn_result = self._start_confirmed_task(proposal_id, parameters, todo_id, steps)
- receipt["resource_ids"].update(
- {"session_id": turn_result["session_id"], "turn_id": turn_result["turn_id"]}
- )
- receipt["outcome"] = "task_execution_started"
- stored = self.store.apply(
- proposal_id,
- current_state_fingerprint=current_fingerprint,
- receipt=receipt,
- )
- return {"proposal": stored, "turn": turn_result}
+ return self._apply_todo_create(proposal_id, proposal, parameters)
if action_kind == "run.correct":
if self.runtime_controller is None or self.chat_store is None:
raise ValueError("Chat Runtime Controller is unavailable")
diff --git a/loopx/chat_server.py b/loopx/chat_server.py
index ab9a4425ea..251b602534 100644
--- a/loopx/chat_server.py
+++ b/loopx/chat_server.py
@@ -20,12 +20,7 @@
from .capabilities.native_chat.transports import ChatConversationTransports
from .attached_session_api import AttachedSessionRequestMixin
from .zcode_goal_mode.api import ZCodeGoalRequestMixin
-from .chat import (
- TodoReviewPreviewConflict,
- apply_todo_review_preview,
- build_todo_review_preview,
- redact_local_paths,
-)
+from .chat import TodoReviewPreviewConflict, redact_local_paths
from .chat_agent import CodexChatAgentError
from .capabilities.native_chat.project_context import ChatProjectContexts
from .chat_attachments import (
@@ -45,6 +40,7 @@
from .capabilities.native_chat.model_settings_api import ChatModelSettingsRequestMixin
from .capabilities.native_chat.queue_api import ChatQueueRequestMixin
from .chat.status_api import ChatStatusRequestMixin
+from .chat.todo_source import review_todo_create
from .chat_runtime import (
STEERING_NOT_DELIVERED_CODES,
ChatRuntimeController,
@@ -1174,19 +1170,10 @@ def _todo(self, *, apply: bool) -> None:
if not goal_id:
raise ValueError("goal_id is required")
self._registry_and_goal(goal_id)
- if apply:
- payload = apply_todo_review_preview(
- registry_path=self.server.registry_path,
- goal_id=goal_id,
- text=text,
- preview_id=str(body.get("preview_id") or ""),
- )
- else:
- payload = build_todo_review_preview(
- registry_path=self.server.registry_path,
- goal_id=goal_id,
- text=text,
- )
+ payload = review_todo_create(
+ self.server, goal_id=goal_id, text=text,
+ preview_id=str(body.get("preview_id") or "") if apply else None,
+ )
except TodoReviewPreviewConflict as exc:
self._send_error(str(exc), status=409, todo_receipt=exc.receipt)
return
@@ -1419,7 +1406,7 @@ def _action_list(self) -> None:
) or None
status = _compact_text((query.get("status") or [""])[0], limit=80) or None
try:
- proposals = self.server.action_store.list(
+ proposals = self.server.action_service.list_proposals(
goal_id=goal_id,
context_kind=context_kind,
status=status,
@@ -1536,18 +1523,23 @@ def _action_apply(self, proposal_id: str) -> None:
return
except Exception:
try:
- self.server.action_store.mark_failed(
+ proposal = self.server.action_store.mark_failed(
proposal_id,
error_code="canonical_action_failed",
message="Canonical LoopX service did not complete the transition.",
)
- except (ActionConflictError, KeyError, ValueError):
- pass
- self._send_error(
- "Typed action could not be applied through its canonical LoopX service.",
- status=424,
- error_code="canonical_action_failed",
- )
+ except (ActionConflictError, KeyError, ValueError, OSError):
+ proposal = None
+ payload = {
+ "ok": False,
+ "error": "Typed action could not be applied through its canonical LoopX service.",
+ "error_code": "canonical_action_failed",
+ }
+ if proposal and proposal.get("action_kind") in {"todo.create", "monitor.create"}:
+ # Present the original confirmation's durable facts, including
+ # when the first write succeeded and this acknowledgement failed.
+ payload["proposal"] = proposal
+ self._send_json(payload, status=424)
return
proposal = result["proposal"]
if proposal.get("status") == "stale":
diff --git a/loopx/control_plane/coordination/authority_source.ts b/loopx/control_plane/coordination/authority_source.ts
index 2779466d32..af6647ca36 100644
--- a/loopx/control_plane/coordination/authority_source.ts
+++ b/loopx/control_plane/coordination/authority_source.ts
@@ -15,6 +15,26 @@ export const AUTHORITY_SOURCE_CHANGED = {
reason: "Todo authority registration changed; review the current state before continuing",
} as const;
+function decodeRegistryWitness(value: unknown, field: string): {path: string; sha256: string} {
+ const witness = requireJsonObject(value, field);
+ if (typeof witness.path !== "string" || !isAbsolute(witness.path) ||
+ typeof witness.sha256 !== "string" || !BARE_SHA256_PATTERN.test(witness.sha256)) {
+ throw new TypeError(`${field} requires an absolute path and SHA-256 digest`);
+ }
+ return {path: witness.path, sha256: witness.sha256};
+}
+
+async function registryMatches(witness: {path: string; sha256: string}): Promise {
+ return createHash("sha256").update(await readFile(witness.path)).digest("hex") === witness.sha256;
+}
+
+export function requireReviewedRegistrySha256(value: unknown): string {
+ if (typeof value !== "string" || !BARE_SHA256_PATTERN.test(value)) {
+ throw new TypeError("expected_registry_sha256 must be a SHA-256 digest");
+ }
+ return value;
+}
+
export function registryAuthoritySourceCheck(
input: JsonObject, witnessed: boolean, expectedDigest: unknown = null,
): AuthoritySourceCheck {
@@ -25,16 +45,15 @@ export function registryAuthoritySourceCheck(
return uncheckedAuthoritySource;
}
const source = requireJsonObject(input.registry_source, "registry_source");
- if (typeof source.path !== "string" || !isAbsolute(source.path) ||
- typeof source.sha256 !== "string" || !BARE_SHA256_PATTERN.test(source.sha256)) {
- throw new TypeError("registry_source requires an absolute path and SHA-256 digest");
- }
// Copy primitive values: later mutation of the decoded request cannot change
// the witness while an awaited store operation or validation effect runs.
- const path = source.path, digest = source.sha256;
+ const witness = decodeRegistryWitness(source, "registry_source");
+ const routing = Object.hasOwn(source, "routing_registry")
+ ? decodeRegistryWitness(source.routing_registry, "registry_source.routing_registry")
+ : undefined;
return async () => {
- if (expectedDigest != null && expectedDigest !== digest) return false;
- try { return createHash("sha256").update(await readFile(path)).digest("hex") === digest; }
+ if (expectedDigest != null && expectedDigest !== witness.sha256) return false;
+ try { return await registryMatches(witness) && (routing === undefined || await registryMatches(routing)); }
catch (error) {
if (error instanceof Error && "code" in error && error.code === "ENOENT") return false;
throw error;
diff --git a/loopx/control_plane/coordination/authority_source_capture.py b/loopx/control_plane/coordination/authority_source_capture.py
index 673917b47a..c401a2750c 100644
--- a/loopx/control_plane/coordination/authority_source_capture.py
+++ b/loopx/control_plane/coordination/authority_source_capture.py
@@ -20,10 +20,15 @@
@contextmanager
-def authority_registry_source(registry_path: Path) -> Iterator[dict[str, str]]:
+def authority_registry_source(
+ registry_path: Path, *, routing_registry_witness: dict[str, str] | None = None,
+) -> Iterator[dict[str, object]]:
path = registry_path.resolve()
digest = hashlib.sha256(path.read_bytes()).hexdigest()
- yield {"path": str(path), "sha256": digest}
+ yield {
+ "path": str(path), "sha256": digest,
+ **({"routing_registry": routing_registry_witness} if routing_registry_witness is not None else {}),
+ }
if hashlib.sha256(path.read_bytes()).hexdigest() != digest:
raise ValueError("Todo authority registration changed while reading; retry")
diff --git a/loopx/control_plane/coordination/local_authority.py b/loopx/control_plane/coordination/local_authority.py
index 0cb1fbe886..ebdd9c06f2 100644
--- a/loopx/control_plane/coordination/local_authority.py
+++ b/loopx/control_plane/coordination/local_authority.py
@@ -163,11 +163,17 @@ def claim_canonical_todo_if_promoted(
task_lease_idempotency_key: str | None = None,
task_lease_expected_version: int | None = None,
manage_execution: bool = False,
+ expected_provider_revision: str | None = None,
+ expected_registry_sha256: str | None = None,
+ routing_registry_witness: dict[str, str] | None = None,
project: Path | None = None,
state_file: Path | None = None,
) -> dict[str, Any]:
"""Route a claim to the canonical TypeScript transaction owner."""
- with authority_registry_source(registry_path) as registry_source:
+ reviewed = expected_provider_revision is not None or expected_registry_sha256 is not None
+ if reviewed and not (manage_execution and expected_provider_revision and expected_registry_sha256):
+ raise ValueError("A reviewed managed claim requires both canonical revision and registry digest")
+ with authority_registry_source(registry_path, routing_registry_witness=routing_registry_witness) as registry_source:
registered = registered_agent_ids_from_registry(registry_path, goal_id)
# This is only a candidate location. The lease owner observes physical
# isolation and the current canonical scopes before granting execution.
@@ -175,8 +181,11 @@ def claim_canonical_todo_if_promoted(
result = effect_runtime_result(
LOCAL_COORDINATION_TODO_CLAIM_METHOD,
{
- "schema_version": ("loopx_local_coordination_todo_claim_request_v2" if manage_execution
- else LOCAL_COORDINATION_TODO_CLAIM_WITNESSED_REQUEST_SCHEMA),
+ "schema_version": (
+ "loopx_local_coordination_todo_claim_request_v3" if reviewed
+ else "loopx_local_coordination_todo_claim_request_v2" if manage_execution
+ else LOCAL_COORDINATION_TODO_CLAIM_WITNESSED_REQUEST_SCHEMA
+ ),
"runtime_root": str(runtime_root.expanduser().resolve(strict=False)),
"goal_id": goal_id,
"todo_id": todo_id,
@@ -191,6 +200,11 @@ def claim_canonical_todo_if_promoted(
else f"todo-claim:{goal_id}:{todo_id}:{uuid4().hex}"
),
**({"manage_execution": True} if manage_execution else {}),
+ **(
+ {"expected_provider_revision": expected_provider_revision,
+ "expected_registry_sha256": expected_registry_sha256}
+ if reviewed else {}
+ ),
**({"write_worktree": str(worktree)} if worktree is not None else {}),
"lease_request": (
{
diff --git a/loopx/control_plane/coordination/local_authority_runtime.ts b/loopx/control_plane/coordination/local_authority_runtime.ts
index 3115e78b46..8c29a169a4 100644
--- a/loopx/control_plane/coordination/local_authority_runtime.ts
+++ b/loopx/control_plane/coordination/local_authority_runtime.ts
@@ -2,7 +2,7 @@ import {requirePromotionRegisteredAgents} from "./shadow_registry_source.ts";
import {verifyReentrySettlement} from "./todo_terminal_reentry.ts";
import {readPromotionReceipt, commitPromotionAndReadBack} from './promotion_receipt.ts';
import {reviewedPromotionPlan, promotionPlanDigest, decodeReviewedPromotionOperation, REVIEWED_PROMOTION_OPERATION_RESULT_SCHEMA} from './reviewed_promotion_plan.ts';
-import {registryAuthoritySourceCheck} from "./authority_source.ts";
+import {registryAuthoritySourceCheck, requireReviewedRegistrySha256} from "./authority_source.ts";
import {decodeTaskLeaseProof} from "./task_lease_proof.ts";
import type {ClaimWorkspaceObserver} from "./claim_execution.ts";
import {LeaseWorktreeObservationError, observeLeaseWorktree} from "../work_items/task_lease_workspace.ts";
@@ -107,12 +107,14 @@ export const LOCAL_COORDINATION_TODO_CLAIM_REQUEST_SCHEMA =
"loopx_local_coordination_todo_claim_request_v0";
export const LOCAL_COORDINATION_TODO_CLAIM_WITNESSED_REQUEST_SCHEMA = "loopx_local_coordination_todo_claim_request_v1";
export const LOCAL_COORDINATION_TODO_MANAGED_CLAIM_REQUEST_SCHEMA = "loopx_local_coordination_todo_claim_request_v2";
+const REVIEWED_MANAGED_CLAIM_REQUEST_SCHEMA = "loopx_local_coordination_todo_claim_request_v3";
export const LOCAL_COORDINATION_TODO_EXECUTION_UPDATE_REQUEST_SCHEMA = "loopx_local_coordination_todo_update_request_v6";
export const LOCAL_COORDINATION_TODO_EXECUTION_TERMINAL_REQUEST_SCHEMA = "loopx_local_coordination_todo_terminal_lifecycle_request_v4";
export const LOCAL_COORDINATION_TODO_CREATE_REQUEST_SCHEMA =
"loopx_local_coordination_todo_create_request_v0";
export const LOCAL_COORDINATION_TODO_CREATE_WITNESSED_REQUEST_SCHEMA = "loopx_local_coordination_todo_create_request_v1";
export const LOCAL_COORDINATION_TODO_CREATE_REVIEWED_REQUEST_SCHEMA = "loopx_local_coordination_todo_create_request_v2";
+const SOURCE_BOUND_TODO_CREATE_REQUEST_SCHEMA = "loopx_local_coordination_todo_create_request_v3";
export const LOCAL_COORDINATION_TODO_TERMINAL_LIFECYCLE_REQUEST_SCHEMA =
"loopx_local_coordination_todo_terminal_lifecycle_request_v3";
export const LOCAL_COORDINATION_TODO_ARCHIVE_REQUEST_SCHEMA =
@@ -1051,20 +1053,28 @@ export async function claimLocalCoordinationTodo(
let sourceAuthority = "file_v0";
try {
const input = requireJsonObject(value, "local coordination Todo claim request");
+ const reviewed = input.schema_version === REVIEWED_MANAGED_CLAIM_REQUEST_SCHEMA;
+ const managed = reviewed || input.schema_version === LOCAL_COORDINATION_TODO_MANAGED_CLAIM_REQUEST_SCHEMA;
if (input.schema_version !== LOCAL_COORDINATION_TODO_CLAIM_REQUEST_SCHEMA &&
input.schema_version !== LOCAL_COORDINATION_TODO_CLAIM_WITNESSED_REQUEST_SCHEMA &&
- input.schema_version !== LOCAL_COORDINATION_TODO_MANAGED_CLAIM_REQUEST_SCHEMA) {
+ !managed) {
throw new Error("local coordination Todo claim request schema mismatch");
}
- if (Object.hasOwn(input, "manage_execution") && input.schema_version !== LOCAL_COORDINATION_TODO_MANAGED_CLAIM_REQUEST_SCHEMA)
+ if (Object.hasOwn(input, "manage_execution") && !managed)
throw new TypeError("Managed execution requires claim request v2");
+ if (reviewed ? input.manage_execution !== true || typeof input.expected_registry_sha256 !== "string"
+ : Object.hasOwn(input, "expected_registry_sha256"))
+ throw new TypeError("A Todo claim review basis requires a reviewed managed claim");
+ // Earlier claim wires did not bind caller-supplied provider revisions.
+ const expectedRevision = reviewed
+ ? requireAuthorityStoreId(input.expected_provider_revision, "expected provider revision") : undefined;
const worktree = input.write_worktree;
- if (worktree !== undefined && (input.schema_version !== LOCAL_COORDINATION_TODO_MANAGED_CLAIM_REQUEST_SCHEMA ||
+ if (worktree !== undefined && (!managed ||
input.manage_execution !== true || typeof worktree !== "string" || !isAbsolute(worktree))) {
throw new TypeError("Worktree observation requires a managed claim and an absolute caller path");
}
const authoritySourcesCurrent = registryAuthoritySourceCheck(input,
- input.schema_version !== LOCAL_COORDINATION_TODO_CLAIM_REQUEST_SCHEMA);
+ input.schema_version !== LOCAL_COORDINATION_TODO_CLAIM_REQUEST_SCHEMA, input.expected_registry_sha256);
if (typeof input.dry_run !== "boolean") {
throw new Error("dry_run must be a JSON boolean");
}
@@ -1111,6 +1121,7 @@ export async function claimLocalCoordinationTodo(
operation_id: requireAuthorityStoreId(input.operation_id, "operation id"),
lease_request: leaseRequest,
...(input.manage_execution === undefined ? {} : {manage_execution: input.manage_execution as boolean}),
+ ...(expectedRevision === undefined ? {} : {expected_provider_revision: expectedRevision}),
dry_run: input.dry_run === true,
now: claimObservedAt(input.observed_at),
}, authoritySourcesCurrent, claimWorkspaceObserver(worktree));
@@ -1149,17 +1160,27 @@ export async function createLocalCoordinationTodo(
};
try {
const input = requireJsonObject(value, "local coordination Todo create request");
+ const sourceBound = input.schema_version === SOURCE_BOUND_TODO_CREATE_REQUEST_SCHEMA;
+ const reviewed = sourceBound || input.schema_version === LOCAL_COORDINATION_TODO_CREATE_REVIEWED_REQUEST_SCHEMA;
if (input.schema_version !== LOCAL_COORDINATION_TODO_CREATE_REQUEST_SCHEMA &&
input.schema_version !== LOCAL_COORDINATION_TODO_CREATE_WITNESSED_REQUEST_SCHEMA &&
- input.schema_version !== LOCAL_COORDINATION_TODO_CREATE_REVIEWED_REQUEST_SCHEMA) {
+ !reviewed) {
throw new TypeError("local coordination Todo create request schema mismatch");
}
- const reviewed = input.schema_version === LOCAL_COORDINATION_TODO_CREATE_REVIEWED_REQUEST_SCHEMA;
if (!reviewed && Object.hasOwn(input, "expected_provider_revision")) {
throw new TypeError("expected_provider_revision requires Todo create request v2");
}
+ if (!sourceBound && Object.hasOwn(input, "expected_registry_sha256")) {
+ throw new TypeError("expected_registry_sha256 requires Todo create request v3");
+ }
+ if (!sourceBound && Object.hasOwn(input, "expected_store_identity")) {
+ throw new TypeError("expected_store_identity requires Todo create request v3");
+ }
+ const expectedStore = Object.hasOwn(input, "expected_store_identity")
+ ? requireAuthorityStoreId(input.expected_store_identity, "expected store identity") : undefined;
+ const expectedRegistry = sourceBound ? requireReviewedRegistrySha256(input.expected_registry_sha256) : undefined;
const authoritySourcesCurrent = registryAuthoritySourceCheck(input,
- input.schema_version !== LOCAL_COORDINATION_TODO_CREATE_REQUEST_SCHEMA);
+ input.schema_version !== LOCAL_COORDINATION_TODO_CREATE_REQUEST_SCHEMA, expectedRegistry);
const expectedRevision = reviewed
? requireAuthorityStoreId(input.expected_provider_revision, "expected provider revision") : undefined;
if (typeof input.dry_run !== "boolean") {
@@ -1171,6 +1192,16 @@ export async function createLocalCoordinationTodo(
const store = await openRuntimeStore(root, goalId, dependencies);
sourceAuthority = sourceAuthorityFor(store);
providerEvidence.source_authority = sourceAuthority;
+ if (expectedStore !== undefined) {
+ // Check within the same maintenance guard and against the same opened
+ // store used for receipt lookup, planning and commit.
+ const identity = await store.storeIdentity();
+ if (identity.status !== "available" || identity.store_identity !== expectedStore) {
+ return {...providerEvidence, schema_version: COORDINATION_TODO_CREATE_RESULT_SCHEMA,
+ status: "failed", reason_code: "local_authority_provider_identity_mismatch",
+ reason: "The reviewed Todo store is unavailable or changed"};
+ }
+ }
if (!Array.isArray(input.registered_agents)) {
throw new TypeError("registered_agents must be a JSON array");
}
@@ -1186,6 +1217,9 @@ export async function createLocalCoordinationTodo(
operation_id: requireAuthorityStoreId(input.operation_id, "operation id"),
dry_run: input.dry_run === true,
...(expectedRevision === undefined ? {} : {expected_provider_revision: expectedRevision}),
+ // Prepared confirmations bind the original digest to the receipt.
+ // Witness-only callers retain the receipt identity of earlier builds.
+ ...(expectedStore === undefined ? {} : {expected_registry_sha256: expectedRegistry}),
now: claimObservedAt(input.observed_at),
}, authoritySourcesCurrent);
return {
diff --git a/loopx/control_plane/coordination/todo_create.ts b/loopx/control_plane/coordination/todo_create.ts
index 64c9e4a4e9..f6424e8474 100644
--- a/loopx/control_plane/coordination/todo_create.ts
+++ b/loopx/control_plane/coordination/todo_create.ts
@@ -1,6 +1,6 @@
import {planTodoCreationPriority} from "../todos/priority.ts";
import {planMonitorSchedule} from "../todos/monitor_metadata.ts";
-import {AUTHORITY_SOURCE_CHANGED, uncheckedAuthoritySource, type AuthoritySourceCheck} from "./authority_source.ts";
+import {AUTHORITY_SOURCE_CHANGED, requireReviewedRegistrySha256, uncheckedAuthoritySource, type AuthoritySourceCheck} from "./authority_source.ts";
import type { JsonObject } from "../effect_program.ts";
import {CoordinationCommandReceipt} from "./command_receipt.ts";
import type { AuthorityStore } from "./authority_store.ts";
@@ -35,6 +35,7 @@ export interface CoordinationTodoCreateInput {
readonly operation_id: string;
readonly dry_run: boolean;
readonly expected_provider_revision?: string;
+ readonly expected_registry_sha256?: string;
readonly now: Date;
}
@@ -85,6 +86,9 @@ function normalizeCreateInput(rawInput: CoordinationTodoCreateInput,
if (input.expected_provider_revision !== undefined) {
requireAuthorityStoreId(input.expected_provider_revision, "expected provider revision");
}
+ if (input.expected_registry_sha256 !== undefined) {
+ requireReviewedRegistrySha256(input.expected_registry_sha256);
+ }
if (todo.status === "done" || todo.archive_state !== "active") {
throw new AuthorityStoreProtocolError(
"Todo create requires an active record that is not already done",
@@ -251,6 +255,8 @@ export async function executeCoordinationTodoCreate(
dry_run: input.dry_run,
...(input.expected_provider_revision === undefined ? {} :
{expected_provider_revision: input.expected_provider_revision}),
+ ...(input.expected_registry_sha256 === undefined ? {} :
+ {expected_registry_sha256: input.expected_registry_sha256}),
});
const receipt = createReceipt(input, requestSha);
const existing = await receipt.read(store);
@@ -282,17 +288,17 @@ export async function executeCoordinationTodoCreate(
}
const todoId = requireAuthorityStoreId(input.todo.todo_id, "todo id");
const readModel = canonicalAuthorityObject(head.head.todo_read_model, "Todo read model");
- // A derived due time belongs to the first result, never to the retry identity.
- const {todo} = input;
- const needsInitialDue = todo.role === "agent" && todo.task_class === "continuous_monitor" &&
- todo.next_due_at == null && todo.cadence != null;
- const initialDue = needsInitialDue
- ? planMonitorSchedule(input.now.toISOString(), todo.cadence).next_due_at : null;
- const plannedInput = initialDue === null ? input : {...input, todo: {...todo, next_due_at: initialDue}};
- const plan = planCoordinationTodoCreate(plannedInput, projection.todos, readModel.schema_version);
+ const plan = planCoordinationTodoCreate(input, projection.todos, readModel.schema_version);
if (!await authoritySourcesCurrent()) return failure(AUTHORITY_SOURCE_CHANGED.code, AUTHORITY_SOURCE_CHANGED.reason);
if (plan.status !== "planned") return {...plan, provider_revision: head.provider_revision, cursor: head.cursor};
- const created = canonicalAuthorityObject(plan.todo, "created Todo");
+ // An implicit due time belongs to a new record. Duplicate matching compares
+ // the submitted configuration and respects any explicitly requested due time.
+ const planned = canonicalAuthorityObject(plan.todo, "created Todo");
+ const needsInitialDue = planned.role === "agent" && planned.task_class === "continuous_monitor" &&
+ planned.next_due_at == null && planned.cadence != null;
+ const initialDue = needsInitialDue
+ ? planMonitorSchedule(input.now.toISOString(), planned.cadence).next_due_at : null;
+ const created = initialDue === null ? planned : {...planned, next_due_at: initialDue};
if (input.dry_run) {
return {
schema_version: COORDINATION_TODO_CREATE_RESULT_SCHEMA,
diff --git a/loopx/control_plane/presentation/action_review_plan.ts b/loopx/control_plane/presentation/action_review_plan.ts
index 00ca24d4a6..39ed3cd65a 100644
--- a/loopx/control_plane/presentation/action_review_plan.ts
+++ b/loopx/control_plane/presentation/action_review_plan.ts
@@ -17,7 +17,8 @@ export type ActionReviewReason =
| "apply_failed" | "inactive_proposal"
| "operation_authorization_pending" | "operation_outcome_pending"
| "operation_confirmation_expired" | "operation_expiry_unknown" | "team_plan_retry"
- | "canonical_update_retry" | "canonical_update_projection_pending" | "goal_creation_retry" | "task_start_retry";
+ | "canonical_update_retry" | "canonical_update_projection_pending" | "goal_creation_retry" | "task_start_retry"
+ | "todo_creation_retry" | "canonical_create_projection_pending";
export type OperationReviewContent = {
title: string;
@@ -94,6 +95,8 @@ export type ActionReviewPlan = ActionReviewIdentity & ActionReviewState & {
decisionFrame?: DecisionReviewFrame;
/** Recover this exact canonical command; generating a new preview loses its receipt identity. */
retryOriginal?: true;
+ /** A saved create attempt is never replaced by implicit regeneration. */
+ prohibitRegeneration?: true;
/** Recorded creation effects, not evidence of a completed Goal or model Turn. */
creationProgress?: GoalCreationProgress;
creationOutcome?: GoalCreationOutcome;
@@ -549,6 +552,28 @@ export function compileActionReviewPlan(proposalValue: unknown, nowMs?: number):
const reviewCardFrame = compileReviewCardFrame(proposal);
const decisionFrame = compileDecisionReviewFrame(proposal);
const parameters = objectValue(proposal.normalized_parameters);
+ const steps = objectValue(objectValue(proposal.checkpoint)?.steps);
+ const createPlan = objectValue(steps?.todo_create_prepared);
+ const failure = objectValue(proposal.failure);
+ const createdTodo = objectValue(steps?.todo_created);
+ const createReceipt = objectValue(createdTodo?.canonical_receipt);
+ const originalTodoMatches = proposal.action_kind === "todo.create"
+ && textValue(createdTodo?.todo_id) && createdTodo?.todo_id === createReceipt?.todo_id
+ && textValue(parameters?.goal_id) && createReceipt?.goal_id === parameters?.goal_id
+ && createReceipt?.preview_id === identity.sourceFingerprint && createReceipt.status === "applied";
+ const creationContext = objectValue(proposal.context);
+ const legacyCreateMatches = originalTodoMatches && createdTodo !== null && !Object.hasOwn(createdTodo, "source")
+ && createReceipt?.schema_version === "loopx_chat_todo_receipt_v0"
+ && createReceipt.outcome === "todo_added" && textValue(createReceipt.receipt_id) && textValue(createReceipt.preview_revision)
+ && (creationContext?.goal_id == null || creationContext.goal_id === parameters?.goal_id)
+ && !textValue(creationContext?.binding_id);
+ const legacySourceGate = proposal.status === "gated" && legacyCreateMatches
+ && proposal.permission_classification === "durable_write"
+ && objectValue(proposal.gate)?.kind === "canonical_authority_required";
+ const todoCreation = proposal.action_kind === "todo.create" || proposal.action_kind === "monitor.create";
+ const createAttemptFailed = proposal.status === "failed" && failure?.error_code === "canonical_action_failed";
+ const prohibitRegeneration = todoCreation && (createAttemptFailed || proposal.status === "applying"
+ || Object.hasOwn(steps ?? {}, "todo_create_prepared") || Object.hasOwn(steps ?? {}, "todo_created"));
const creationProgress = goalCreationProgress(proposal);
const creationExecution = proposal.action_kind === "goal.create" && parameters
? goalCreationExecutionReview(parameters) : undefined;
@@ -557,17 +582,16 @@ export function compileActionReviewPlan(proposalValue: unknown, nowMs?: number):
const creationOutcome = creationProgress?.todoIds && (!creationProgress.sessionId && !creationProgress.firstTurn
|| creationProgress.completionBasis)
? goalCreationOutcome(identity.proposalId, parameters ?? {}, creationProgress.todoIds) : undefined;
- const creationSteps = objectValue(objectValue(proposal.checkpoint)?.steps);
// A persisted Session/Turn, including a malformed checkpoint, always owns
// recovery. Never infer a new managed identity from its old creation fields.
const creationSession = proposal.action_kind === "goal.create" && parameters?.agent_id === "codex"
&& parameters.native_token_budget == null && proposal.status !== "applied"
&& !creationProgress?.sessionId && !creationProgress?.firstTurn
&& !Object.hasOwn(proposal, "first_turn_readback")
- && (proposal.checkpoint == null || creationSteps !== null
- && (Object.keys(creationSteps).length === 0 || creationProgress !== undefined))
- && !Object.hasOwn(creationSteps ?? {}, "first_session_opened")
- && !Object.hasOwn(creationSteps ?? {}, "first_turn_started")
+ && (proposal.checkpoint == null || steps !== null
+ && (Object.keys(steps).length === 0 || creationProgress !== undefined))
+ && !Object.hasOwn(steps ?? {}, "first_session_opened")
+ && !Object.hasOwn(steps ?? {}, "first_turn_started")
? {managedAgentId: "codex"} : undefined;
const finish = (state: ActionReviewState): ActionReviewPlan => ({
...identity,
@@ -576,6 +600,7 @@ export function compileActionReviewPlan(proposalValue: unknown, nowMs?: number):
...(reviewCardFrame ? { reviewCardFrame } : {}),
...(decisionFrame ? { decisionFrame } : {}),
...(creationProgress ? { creationProgress } : {}),
+ ...(prohibitRegeneration ? {prohibitRegeneration: true as const} : {}),
...(creationOutcome ? { creationOutcome } : {}),
...(creationSession ? { creationSession } : {}),
...(creationExecution ? { creationExecution } : {}),
@@ -588,7 +613,9 @@ export function compileActionReviewPlan(proposalValue: unknown, nowMs?: number):
if (operationFrame?.kind === "inactive") return held("inactive", operationFrame.reason);
// Lifecycle uses conservative fact precedence. Generic deferred proposals may
// retain a historical gate; their existing status-based retry path is preserved.
- if ((lifecycle && proposal.gate != null) || proposal.status === "gated") return held("gated", "authority_gate");
+ if ((lifecycle && proposal.gate != null) || (proposal.status === "gated" && !legacySourceGate)) {
+ return held("gated", "authority_gate");
+ }
if ((lifecycle && proposal.stale != null) || proposal.status === "stale") return held("refresh", "stale_proposal");
// Host readback may return an immutable terminal replay which never started.
// Its acceptance id is still original, but cannot certify first-Turn startup.
@@ -621,17 +648,39 @@ export function compileActionReviewPlan(proposalValue: unknown, nowMs?: number):
&& creationProgress) {
return {...finish({interaction: "review", canApply: true, reason: "goal_creation_retry"}), retryOriginal: true};
}
- if (proposal.action_kind === "todo.create" && parameters?.start_execution === true
+ const pendingDisplay = (failure?.error_code === "canonical_create_projection_pending"
+ && objectValue(failure.details)?.canonical_committed === true)
+ || (objectValue(steps?.todo_assigned) ?? createdTodo)?.projection_delivery === "pending";
+ if (originalTodoMatches && parameters?.start_execution === true && !pendingDisplay
&& proposal.permission_classification === "durable_write" && identity.proposalId && identity.sourceFingerprint
- && (proposal.status === "applying" || (proposal.status === "failed" && objectValue(proposal.failure)?.retry_safe === true))) {
- const steps = objectValue(objectValue(proposal.checkpoint)?.steps);
- const created = objectValue(steps?.todo_created);
- const receipt = objectValue(created?.canonical_receipt);
- if (textValue(created?.todo_id) && created?.todo_id === receipt?.todo_id
- && textValue(parameters.goal_id) && receipt?.goal_id === parameters.goal_id
- && receipt?.preview_id === identity.sourceFingerprint && receipt.status === "applied") {
- return {...finish({interaction: "review", canApply: true, reason: "task_start_retry"}), retryOriginal: true};
- }
+ && (proposal.status === "applying" || (proposal.status === "failed" && failure?.retry_safe === true))) {
+ return {...finish({interaction: "review", canApply: true, reason: "task_start_retry"}), retryOriginal: true};
+ }
+ // Older confirmations may have saved the created Todo before the
+ // preparation checkpoint was introduced.
+ const createdSource = objectValue(createdTodo?.source);
+ const recordedCreateMatches = originalTodoMatches
+ && textValue(createdSource?.source_identity) && textValue(createdSource?.source_authority)
+ && textValue(createdSource?.store_identity) && textValue(createdSource?.registry_sha256)
+ && textValue(createdSource?.provider_revision) && textValue(createdSource?.operation_id);
+ const preparedCreateMatches = createPlan?.operation_id === ("chat-create:" + identity.proposalId)
+ && createPlan.preview_id === identity.sourceFingerprint
+ && textValue(createPlan.source_identity) && textValue(createPlan.source_authority)
+ && textValue(createPlan.expected_provider_revision) && textValue(createPlan.expected_registry_sha256)
+ && textValue(createPlan.expected_store_identity);
+ // The server may fail before any checkpoint is saved. The same apply still
+ // owns the reviewed source and must revalidate it before the first write.
+ const interruptedBeforePlan = proposal.checkpoint == null
+ && Array.isArray(proposal.available_transitions) && proposal.available_transitions.includes("apply")
+ && ((createAttemptFailed && failure?.retry_safe === true)
+ || (proposal.status === "applying" && proposal.creation_retry_available === true));
+ if (todoCreation && (["failed", "applying"].includes(String(proposal.status)) || legacySourceGate)
+ && proposal.permission_classification === "durable_write"
+ && failure?.retry_safe !== false
+ && identity.proposalId && identity.sourceFingerprint && textValue(parameters?.goal_id)
+ && (interruptedBeforePlan || preparedCreateMatches || recordedCreateMatches || legacyCreateMatches)) {
+ return {...finish({interaction: "review", canApply: true,
+ reason: pendingDisplay ? "canonical_create_projection_pending" : "todo_creation_retry"}), retryOriginal: true};
}
const isCanonicalUpdate = basis?.schema_version === "loopx_chat_canonical_update_basis_v0"
&& textValue(basis.provider_revision) !== null && textValue(basis.registry_sha256) !== null
@@ -643,7 +692,6 @@ export function compileActionReviewPlan(proposalValue: unknown, nowMs?: number):
|| (proposal.action_kind === "monitor.update" && parameters?.operation === "stop")
|| (proposal.action_kind === "gate.resolve" && ["approve", "reject", "cancel"].includes(String(parameters?.decision))));
if ((isCanonicalUpdate || isCanonicalTerminal) && (proposal.status === "applying" || proposal.status === "failed")) {
- const failure = objectValue(proposal.failure);
return {...finish({interaction: "review", canApply: true,
reason: failure?.error_code === "canonical_update_projection_pending"
? "canonical_update_projection_pending" : "canonical_update_retry"}), retryOriginal: true};
diff --git a/loopx/control_plane/runtime/runtime_projection_route.py b/loopx/control_plane/runtime/runtime_projection_route.py
index e0fe8eefe9..85876c2897 100644
--- a/loopx/control_plane/runtime/runtime_projection_route.py
+++ b/loopx/control_plane/runtime/runtime_projection_route.py
@@ -104,19 +104,21 @@ def resolve_goal_source_runtime_route(
``source_registry``, goal-scoped capabilities must use that registry's
runtime rather than treating the shared projection as the source of truth.
An explicit runtime override remains authoritative for diagnostics and
- recovery commands.
+ recovery commands. It also supplies the invoked runtime for an unbound
+ registry.
"""
invoked_registry = registry_path.expanduser().resolve()
registry_payload = registry if registry is not None else load_registry(
invoked_registry, source_snapshots=source_snapshots,
)
- invoked_runtime = _registry_runtime_root(
- registry_payload,
- registry_path=invoked_registry,
- )
if runtime_root_override:
runtime_root = Path(runtime_root_override).expanduser().resolve()
+ invoked_runtime = (
+ _registry_runtime_root(registry_payload, registry_path=invoked_registry)
+ if registry_payload.get("common_runtime_root")
+ else runtime_root
+ )
return _goal_source_route_packet(
status="explicit_override",
declaration_source="cli.runtime_root_override",
@@ -127,6 +129,10 @@ def resolve_goal_source_runtime_route(
source_runtime=runtime_root,
)
+ invoked_runtime = _registry_runtime_root(
+ registry_payload,
+ registry_path=invoked_registry,
+ )
registry_is_global = bool(registry_payload.get("registry_role") == "global-local") or _same_path(
invoked_registry,
global_registry_path(invoked_runtime),
diff --git a/loopx/control_plane/todos/mutation_api.py b/loopx/control_plane/todos/mutation_api.py
index dde21871f9..efbb810b70 100644
--- a/loopx/control_plane/todos/mutation_api.py
+++ b/loopx/control_plane/todos/mutation_api.py
@@ -76,6 +76,9 @@ def add_goal_todo(
dry_run: bool = False,
operation_id: str | None = None,
expected_provider_revision: str | None = None,
+ expected_registry_sha256: str | None = None,
+ routing_registry_witness: dict[str, str] | None = None,
+ expected_store_identity: str | None = None,
) -> dict[str, Any]:
shadow_runtime_root = effective_runtime_root(registry_path, runtime_root_arg)
if role not in TODO_SECTION_HEADINGS:
@@ -149,6 +152,9 @@ def add_goal_todo(
return create_canonical_todo_if_promoted(
operation_id=operation_id,
expected_provider_revision=expected_provider_revision,
+ expected_registry_sha256=expected_registry_sha256,
+ routing_registry_witness=routing_registry_witness,
+ expected_store_identity=expected_store_identity,
registry_path=registry_path,
runtime_root=shadow_runtime_root,
goal_id=goal_id,
@@ -301,9 +307,12 @@ def update_goal_todo(
claim_only: bool = False,
claim_operation_id: str | None = None,
manage_execution: bool = False,
+ claim_expected_provider_revision: str | None = None,
+ claim_expected_registry_sha256: str | None = None,
update_operation_id: str | None = None,
update_expected_provider_revision: str | None = None,
update_expected_registry_sha256: str | None = None,
+ routing_registry_witness: dict[str, str] | None = None,
task_lease_idempotency_key: str | None = None,
task_lease_expected_version: int | None = None,
project: Path | None = None,
@@ -323,6 +332,9 @@ def update_goal_todo(
update_operation_id, update_expected_provider_revision, update_expected_registry_sha256,
)):
raise ValueError("Todo update identity and review basis cannot be used for todo claim")
+ if not (claim_only and manage_execution) and (
+ claim_expected_provider_revision is not None or claim_expected_registry_sha256 is not None):
+ raise ValueError("A Todo claim review basis requires a managed claim")
if excluded_agents and clear_excluded_agents:
raise ValueError(
"todo update accepts either excluded_agents or clear_excluded_agents, not both"
@@ -375,6 +387,9 @@ def update_goal_todo(
dry_run=dry_run,
operation_id=claim_operation_id,
manage_execution=manage_execution,
+ expected_provider_revision=claim_expected_provider_revision,
+ expected_registry_sha256=claim_expected_registry_sha256,
+ routing_registry_witness=routing_registry_witness,
task_lease_idempotency_key=task_lease_idempotency_key,
task_lease_expected_version=task_lease_expected_version,
project=project,
@@ -423,6 +438,7 @@ def update_goal_todo(
authority_reason=authority_reason,
expected_provider_revision=update_expected_provider_revision,
expected_registry_sha256=update_expected_registry_sha256,
+ routing_registry_witness=routing_registry_witness,
task_lease_idempotency_key=task_lease_idempotency_key,
task_lease_expected_version=task_lease_expected_version,
monitor_observation=monitor_metadata if isinstance(monitor_metadata, todo_monitor_metadata.MonitorPollObservation) else None,
@@ -446,6 +462,7 @@ def complete_goal_todo(
completion_turn_key: str | None = None,
completion_identity_source: str | None = None,
terminal_review_basis: Mapping[str, Any] | None = None,
+ routing_registry_witness: dict[str, str] | None = None,
expected_todo_text_sha256: str | None = None,
require_captured_todo_text: bool = False,
completion_delivery_workspace: Mapping[str, Any] | None = None,
diff --git a/loopx/control_plane/todos/provider_create.py b/loopx/control_plane/todos/provider_create.py
index 8386b1b018..6e8376ca91 100644
--- a/loopx/control_plane/todos/provider_create.py
+++ b/loopx/control_plane/todos/provider_create.py
@@ -47,11 +47,18 @@ def create_canonical_todo_if_promoted(
project: Path | None = None, state_file: Path | None = None,
operation_id: str | None = None,
expected_provider_revision: str | None = None,
+ expected_registry_sha256: str | None = None,
+ routing_registry_witness: dict[str, str] | None = None,
+ expected_store_identity: str | None = None,
) -> dict[str, Any]:
# The native writer guard selects the route under the same maintenance
# lock as provider open and commit. A separate source read grants nothing.
if operation_id is not None and not re.fullmatch(r"[A-Za-z0-9_.:-]+", operation_id):
raise ValueError("operation_id must be a non-empty public-safe token")
+ if expected_registry_sha256 is not None and expected_provider_revision is None:
+ raise ValueError("A reviewed Todo create requires a canonical provider revision and registry digest")
+ if expected_store_identity is not None and expected_registry_sha256 is None:
+ raise ValueError("A reviewed Todo store requires a registry digest")
operation_id = operation_id if operation_id is not None else f"todo-create:{uuid4().hex}"
# Identity is independent of current Todo count: exact retries still address
# the original operation after other creates, edits, completion or archive.
@@ -90,7 +97,7 @@ def create_canonical_todo_if_promoted(
**{key: metadata[key] for key in ("priority", "title") if key in metadata and metadata.get("priority") is not None},
**({"claimed_by": claimed_by} if claimed_by else {}),
}
- with authority_registry_source(registry_path) as registry_source:
+ with authority_registry_source(registry_path, routing_registry_witness=routing_registry_witness) as registry_source:
registered = registered_agent_ids_from_registry(registry_path, goal_id)
if validation_declaration is not None and not dry_run:
prepare_completion_validation_declaration(runtime_root=runtime_root,
@@ -99,10 +106,17 @@ def create_canonical_todo_if_promoted(
result = effect_runtime_result(
"coordination.local_authority.todo_create",
{
- "schema_version": ("loopx_local_coordination_todo_create_request_v2"
- if expected_provider_revision is not None else "loopx_local_coordination_todo_create_request_v1"),
+ "schema_version": (
+ "loopx_local_coordination_todo_create_request_v3" if expected_registry_sha256 is not None
+ else "loopx_local_coordination_todo_create_request_v2" if expected_provider_revision is not None
+ else "loopx_local_coordination_todo_create_request_v1"
+ ),
**({"expected_provider_revision": expected_provider_revision}
if expected_provider_revision is not None else {}),
+ **({"expected_registry_sha256": expected_registry_sha256}
+ if expected_registry_sha256 is not None else {}),
+ **({"expected_store_identity": expected_store_identity}
+ if expected_store_identity is not None else {}),
"runtime_root": str(runtime_root.resolve()),
"goal_id": goal_id,
"todo": todo,
diff --git a/loopx/control_plane/todos/provider_projection.py b/loopx/control_plane/todos/provider_projection.py
index 062b7078e1..05da14aa2d 100644
--- a/loopx/control_plane/todos/provider_projection.py
+++ b/loopx/control_plane/todos/provider_projection.py
@@ -82,6 +82,7 @@ def project_current_canonical_todos(
execute: bool = True,
registry_data: Mapping[str, Any] | None = None,
canonical_snapshot: dict[str, Any] | None = None,
+ expected_store_identity: str | None = None,
) -> dict[str, Any]:
"""Render one exact canonical head into machine-owned Markdown regions."""
@@ -114,6 +115,8 @@ def project_current_canonical_todos(
attempt = 0
while True:
attempt += 1
+ if expected_store_identity is not None and authority_read.get("store_identity") != expected_store_identity:
+ raise ValueError("canonical Todo projection store identity changed")
provider_revision = authority_read.get("provider_revision")
if not isinstance(provider_revision, str) or not provider_revision:
raise ValueError("canonical Todo authority omitted provider revision")
@@ -179,6 +182,8 @@ def project_current_canonical_todos(
)
if not isinstance(confirmed, dict) or not isinstance(confirmed.get("projection_readback"), dict):
raise ValueError("canonical projection confirmation is missing")
+ if expected_store_identity is not None and confirmed.get("store_identity") != expected_store_identity:
+ raise ValueError("canonical Todo projection store identity changed during readback")
confirmation = confirmed["projection_readback"]
if confirmation["next_action"] == "finish":
break
@@ -222,6 +227,7 @@ def settle_canonical_todo_projection(
state_file: Path | None = None,
only_if_promoted: bool = False,
canonical_snapshot: dict[str, Any] | None = None,
+ expected_store_identity: str | None = None,
) -> dict[str, Any]:
"""Drain the committed provider head, preserving a successful mutation."""
@@ -246,6 +252,7 @@ def settle_canonical_todo_projection(
state_file=state_file,
execute=True,
canonical_snapshot=canonical_snapshot,
+ **({"expected_store_identity": expected_store_identity} if expected_store_identity is not None else {}),
)
except Exception as error: # noqa: BLE001 - canonical commit already landed
if isinstance(error, LocalCoordinationAuthorityUnavailable):
diff --git a/loopx/control_plane/todos/provider_terminal_lifecycle.py b/loopx/control_plane/todos/provider_terminal_lifecycle.py
index 4d30d47d93..2780f7101a 100644
--- a/loopx/control_plane/todos/provider_terminal_lifecycle.py
+++ b/loopx/control_plane/todos/provider_terminal_lifecycle.py
@@ -127,6 +127,7 @@ def route_terminal_call(command: str, call: Mapping[str, Any]) -> dict[str, Any]
call.get("completion_identity_source") if complete else None
),
review_basis=call.get("terminal_review_basis"),
+ routing_registry_witness=call.get("routing_registry_witness"),
expected_todo_text_sha256=call.get("expected_todo_text_sha256"),
require_captured_todo_text=call.get("require_captured_todo_text") is True,
completion_delivery_workspace=(
@@ -281,6 +282,7 @@ def terminal_canonical_todo_if_promoted(
self_merged: bool,
dry_run: bool,
review_basis: Mapping[str, Any] | None = None,
+ routing_registry_witness: dict[str, str] | None = None,
expected_todo_text_sha256: str | None = None,
require_captured_todo_text: bool = False,
project: Path | None = None,
@@ -329,7 +331,7 @@ def terminal_canonical_todo_if_promoted(
)["result"]
result_descriptor = {key: bound[key] for key in
("provider", "sha256", "size_bytes", "content_type")}
- with authority_registry_source(registry_path) as registry_source:
+ with authority_registry_source(registry_path, routing_registry_witness=routing_registry_witness) as registry_source:
registered, grants = todo_lifecycle_facts(registry_path, goal_id)
successor_intents = build_successor_intents(
next_agent_todo=next_agent_todo,
diff --git a/loopx/control_plane/todos/provider_update.py b/loopx/control_plane/todos/provider_update.py
index a5ef46aae6..a2026a8048 100644
--- a/loopx/control_plane/todos/provider_update.py
+++ b/loopx/control_plane/todos/provider_update.py
@@ -277,12 +277,13 @@ def update_canonical_todo_if_promoted(
authority_reason: str | None = None,
expected_provider_revision: str | None = None,
expected_registry_sha256: str | None = None,
+ routing_registry_witness: dict[str, str] | None = None,
monitor_observation: MonitorPollObservation | None = None,
completion_validation_revision: dict[str, Any] | None = None,
) -> dict[str, Any]:
# The witness brackets fact projection and is rechecked by the native
# transaction. Reviewed edits additionally bind the preview's registry hash.
- with authority_registry_source(registry_path) as registry_source:
+ with authority_registry_source(registry_path, routing_registry_witness=routing_registry_witness) as registry_source:
registered, grants = todo_lifecycle_facts(registry_path, goal_id)
patch: dict[str, Any] = {}
if text is not None:
diff --git a/tests/control_plane/test_chat_create_confirmation_recovery.py b/tests/control_plane/test_chat_create_confirmation_recovery.py
new file mode 100644
index 0000000000..bfdd6433f5
--- /dev/null
+++ b/tests/control_plane/test_chat_create_confirmation_recovery.py
@@ -0,0 +1,472 @@
+"""Recover the original Chat confirmation against the real Todo providers."""
+
+from concurrent.futures import ThreadPoolExecutor
+from datetime import datetime, timedelta, timezone
+from hashlib import sha256
+import json
+from threading import Event
+
+import pytest
+
+from canonical_authority_fixture import isolate_sqlite_runtime, promoted_create_fixture
+from loopx.chat import apply_todo_review_preview, build_todo_review_preview
+from loopx.chat import todo_creation
+from loopx.chat_action_store import ActionConflictError, ChatActionStore
+from loopx.chat_actions import ChatActionService
+from loopx.chat.todo_source import ChatTodoSourceChanged
+from loopx.control_plane.coordination.local_authority import read_canonical_todos_if_promoted
+from loopx.control_plane.todos import provider_create
+from loopx.control_plane.todos.mutation_api import add_goal_todo, update_goal_todo
+
+
+@pytest.fixture(params=["file", "sqlite"])
+def confirmation(tmp_path, monkeypatch, request):
+ isolate_sqlite_runtime(tmp_path, monkeypatch)
+ registry, runtime, _ = promoted_create_fixture(
+ tmp_path, provider=request.param, registered_agents=["agent-a", "agent-b"],
+ )
+ service = ChatActionService(store=ChatActionStore(runtime / "chat" / "actions"),
+ registry_path=registry)
+ return service, registry, runtime, request.param
+
+
+def _preview(service, kind, key, *, agent=None):
+ parameters = {"goal_id": "goal-a"}
+ if kind == "monitor.create":
+ parameters.update(agent_id="agent-a", target="Review service availability",
+ target_key="service-health", cadence="2h", timezone="UTC",
+ stop_condition="watch_only")
+ else:
+ parameters.update(text="Review service availability", priority="P2")
+ if agent:
+ parameters["agent_id"] = agent
+ return service.preview({
+ "action_kind": kind, "summary": "Review service availability",
+ "normalized_parameters": parameters, "context": {"kind": "goal", "goal_id": "goal-a"},
+ "idempotency_key": key,
+ })["proposal_id"]
+
+
+def _snapshot(runtime):
+ return read_canonical_todos_if_promoted(runtime_root=runtime, goal_id="goal-a")
+
+
+def _interrupt_after_create(service, monkeypatch, kind):
+ lost = []
+ if kind == "todo.create":
+ checkpoint = service.store.save_checkpoint
+
+ def save(proposal_id, *, step, receipt, **kwargs):
+ if step == "todo_created" and not lost:
+ lost.append(receipt["canonical_receipt"])
+ raise OSError("interrupted after provider commit")
+ return checkpoint(proposal_id, step=step, receipt=receipt, **kwargs)
+
+ monkeypatch.setattr(service.store, "save_checkpoint", save)
+ else:
+ apply = service.store.apply
+
+ def save(proposal_id, *, current_state_fingerprint, receipt, **kwargs):
+ if receipt.get("outcome") == "monitor_created" and not lost:
+ lost.append(receipt)
+ raise OSError("interrupted after provider commit")
+ return apply(proposal_id, current_state_fingerprint=current_state_fingerprint, receipt=receipt, **kwargs)
+
+ monkeypatch.setattr(service.store, "apply", save)
+ return lost
+
+
+@pytest.mark.parametrize("kind", ["todo.create", "monitor.create"])
+def test_lost_chat_confirmation_recovers_original_create(confirmation, monkeypatch, kind):
+ service, registry, runtime, _ = confirmation
+ proposal_id = _preview(service, kind, "original-confirmation")
+ lost = _interrupt_after_create(service, monkeypatch, kind)
+ confirmed_at = datetime.now(timezone.utc)
+ monkeypatch.setattr("loopx.chat_actions.now_utc", lambda: confirmed_at)
+ with pytest.raises(OSError, match="after provider commit"):
+ service.apply(proposal_id)
+ after_commit = _snapshot(runtime)
+ assert len(after_commit["todos"]) == 1
+ todo = after_commit["todos"][0]
+ if kind == "monitor.create":
+ assert todo["next_due_at"]
+
+ # Advance the time and registration revision without changing the source.
+ registry.write_text(registry.read_text() + "\n")
+ monkeypatch.setattr("loopx.chat_actions.now_utc", lambda: confirmed_at + timedelta(minutes=5))
+ reopened = ChatActionService(store=ChatActionStore(runtime / "chat" / "actions"),
+ registry_path=registry)
+ recovered = reopened.apply(proposal_id)["proposal"]
+ assert recovered["status"] == "applied", recovered
+ assert recovered["receipt"]["receipt_id"] == lost[0]["receipt_id"]
+ assert recovered["receipt"]["outcome"] == lost[0]["outcome"]
+ assert recovered["receipt"]["resource_ids"]["todo_id"] == todo["todo_id"]
+ assert _snapshot(runtime) == after_commit
+ assert reopened.apply(proposal_id)["proposal"]["receipt"] == recovered["receipt"]
+
+
+def test_separate_confirmation_cannot_claim_the_original_create(confirmation, monkeypatch):
+ service, _, runtime, _ = confirmation
+ first = _preview(service, "todo.create", "first", agent="agent-a")
+ competing = _preview(service, "todo.create", "competing", agent="agent-b")
+ _interrupt_after_create(service, monkeypatch, "todo.create")
+ with pytest.raises(OSError, match="after provider commit"):
+ service.apply(first)
+ saved = _snapshot(runtime)
+ assert service.apply(competing)["proposal"]["status"] == "stale"
+ assert _snapshot(runtime) == saved
+ assert service.apply(first)["proposal"]["status"] == "applied"
+ after_assignment = _snapshot(runtime)
+ assert len(after_assignment["todos"]) == 1
+ assert after_assignment["todos"][0]["claimed_by"] == "agent-a"
+ assert service.apply(first)["proposal"]["status"] == "applied"
+ assert _snapshot(runtime) == after_assignment
+
+
+def test_duplicate_confirmation_keeps_the_running_owner(confirmation, monkeypatch):
+ service, _, runtime, _ = confirmation
+ proposal_id = _preview(service, "todo.create", "concurrent")
+ entered, resume = Event(), Event()
+ original_plan = todo_creation.plan_reviewed_todo_create
+
+ def plan(**arguments):
+ entered.set()
+ assert resume.wait(15), "the duplicate confirmer did not return"
+ return original_plan(**arguments)
+
+ monkeypatch.setattr(todo_creation, "plan_reviewed_todo_create", plan)
+ lost = _interrupt_after_create(service, monkeypatch, "todo.create")
+ with ThreadPoolExecutor(max_workers=1) as pool:
+ pending = pool.submit(service.apply, proposal_id)
+ try:
+ assert entered.wait(10)
+ with pytest.raises(ActionConflictError, match="original confirmation is in progress"):
+ service.apply(proposal_id)
+ with pytest.raises(ActionConflictError, match="original confirmation is in progress"):
+ service.regenerate(proposal_id)
+ finally:
+ resume.set()
+ with pytest.raises(OSError, match="after provider commit"):
+ pending.result(timeout=30)
+ committed = _snapshot(runtime)
+ recovered = service.apply(proposal_id)["proposal"]
+ assert recovered["receipt"]["canonical_receipt"] == lost[0]
+ assert len(committed["todos"]) == 1
+ assert _snapshot(runtime) == committed
+
+
+def test_interrupted_assignment_recovers_at_original_revision(confirmation, monkeypatch):
+ service, _, runtime, _ = confirmation
+ proposal_id = _preview(service, "todo.create", "assignment", agent="agent-a")
+ original_save = service.store.save_checkpoint
+
+ def save(proposal_id, *, step, receipt, **kwargs):
+ if step == "todo_assigned":
+ raise OSError("interrupted after assignment")
+ return original_save(proposal_id, step=step, receipt=receipt, **kwargs)
+
+ with monkeypatch.context() as faults:
+ faults.setattr(service.store, "save_checkpoint", save)
+ with pytest.raises(OSError, match="after assignment"):
+ service.apply(proposal_id)
+ assigned = _snapshot(runtime)
+ assert assigned["todos"][0]["claimed_by"] == "agent-a"
+ recovered = service.apply(proposal_id)["proposal"]
+ assert recovered["status"] == "applied"
+ saved = service.load(proposal_id)["checkpoint"]["steps"]["todo_created"]
+ assert recovered["receipt"]["canonical_receipt"] == saved["canonical_receipt"]
+ assert _snapshot(runtime) == assigned
+
+
+@pytest.mark.parametrize("kind", ["todo.create", "monitor.create"])
+def test_uncommitted_confirmation_rejects_changed_basis(confirmation, monkeypatch, kind):
+ service, registry, runtime, _ = confirmation
+ proposal_id = _preview(service, kind, "unfinished")
+ original_save = service.store.save_checkpoint
+
+ def save(proposal_id, *, step, receipt, **kwargs):
+ saved = original_save(proposal_id, step=step, receipt=receipt, **kwargs)
+ if step == "todo_create_prepared":
+ raise OSError("interrupted before provider commit")
+ return saved
+
+ with monkeypatch.context() as faults:
+ faults.setattr(service.store, "save_checkpoint", save)
+ with pytest.raises(OSError, match="before provider commit"):
+ service.apply(proposal_id)
+ assert not _snapshot(runtime)["todos"]
+ if kind == "todo.create":
+ add_goal_todo(registry_path=registry, goal_id="goal-a", role="agent", text="Independent Todo")
+ else:
+ registry.write_text(registry.read_text() + "\n")
+ before_retry = _snapshot(runtime)
+ assert service.apply(proposal_id)["proposal"]["status"] == "stale"
+ assert _snapshot(runtime) == before_retry
+
+
+def test_unprepared_monitor_confirmation_rejects_a_new_revision(confirmation, monkeypatch):
+ service, registry, runtime, _ = confirmation
+ proposal_id = _preview(service, "monitor.create", "unprepared-monitor")
+ with monkeypatch.context() as faults:
+ def interrupted(*args, **kwargs):
+ raise OSError("interrupted before the create plan")
+
+ faults.setattr(service.store, "save_checkpoint", interrupted)
+ with pytest.raises(OSError, match="before the create plan"):
+ service.apply(proposal_id)
+ assert service.load(proposal_id)["checkpoint"] is None
+ assert not _snapshot(runtime)["todos"]
+ add_goal_todo(registry_path=registry, goal_id="goal-a", role="agent", text="Independent Todo")
+ before_retry = _snapshot(runtime)
+ rejected = service.apply(proposal_id)["proposal"]
+ assert rejected["status"] == "stale"
+ assert _snapshot(runtime) == before_retry
+
+
+def test_concurrent_monitor_confirmation_uses_one_schedule(confirmation, monkeypatch):
+ service, _, runtime, _ = confirmation
+ proposal_id = _preview(service, "monitor.create", "concurrent")
+ entered, resume = Event(), Event()
+ prepare = service.store.save_checkpoint
+
+ def save(proposal_id, *, step, receipt, **kwargs):
+ if step == "todo_create_prepared":
+ entered.set()
+ assert resume.wait(15), "the duplicate confirmer did not return"
+ return prepare(proposal_id, step=step, receipt=receipt, **kwargs)
+
+ monkeypatch.setattr(service.store, "save_checkpoint", save)
+ with ThreadPoolExecutor(max_workers=1) as pool:
+ pending = pool.submit(service.apply, proposal_id)
+ try:
+ assert entered.wait(10)
+ live = service.load(proposal_id)
+ assert live["status"] == "applying" and live["checkpoint"] is None
+ assert "creation_retry_available" not in live
+ with pytest.raises(ActionConflictError, match="in progress"):
+ service.apply(proposal_id)
+ finally:
+ resume.set()
+ initial = pending.result(timeout=30)["proposal"]
+ assert initial["receipt"] == service.apply(proposal_id)["proposal"]["receipt"]
+ todos = _snapshot(runtime)["todos"]
+ assert len(todos) == 1 and todos[0]["next_due_at"]
+
+
+def test_retry_never_writes_a_replacement_runtime(confirmation, monkeypatch, tmp_path):
+ service, registry, runtime, provider = confirmation
+ proposal_id = _preview(service, "todo.create", "source-bound")
+ _interrupt_after_create(service, monkeypatch, "todo.create")
+ with pytest.raises(OSError, match="after provider commit"):
+ service.apply(proposal_id)
+ after_commit = _snapshot(runtime)
+ alternate = tmp_path / "alternate"
+ alternate.mkdir()
+ _, alternate_runtime, _ = promoted_create_fixture(alternate, provider=provider)
+ alternate_before = _snapshot(alternate_runtime)
+ source = registry.read_text()
+ registry.write_text(json.dumps({**json.loads(source), "common_runtime_root": str(alternate_runtime)}))
+ with pytest.raises(ValueError, match="source changed"):
+ service.apply(proposal_id)
+ assert _snapshot(alternate_runtime) == alternate_before
+ registry.write_text(source)
+ assert service.apply(proposal_id)["proposal"]["status"] == "applied"
+ assert _snapshot(runtime) == after_commit
+
+
+@pytest.mark.parametrize("kind", ["todo.create", "monitor.create"])
+def test_create_refuses_directory_retarget_at_provider_dispatch(confirmation, monkeypatch, tmp_path, kind):
+ service, registry, runtime, provider = confirmation
+ alternative_registry, alternative_runtime, _ = promoted_create_fixture(tmp_path / "alternative", provider=provider)
+ directory = tmp_path / "directory.json"
+ registration = json.loads(registry.read_text())
+ registration["registry_role"] = "global-local"
+ registration["goals"][0]["source_registry"] = str(registry)
+ directory.write_text(json.dumps(registration))
+ service.registry_path = directory
+ proposal_id = _preview(service, kind, "directory-retarget")
+ original, alternative = _snapshot(runtime), _snapshot(alternative_runtime)
+ dispatch = provider_create.effect_runtime_result
+
+ def retarget(name, request, **kwargs):
+ if name == "coordination.local_authority.todo_create" and not request["dry_run"]:
+ registration["goals"][0]["source_registry"] = str(alternative_registry)
+ directory.write_text(json.dumps(registration))
+ return dispatch(name, request, **kwargs)
+
+ monkeypatch.setattr(provider_create, "effect_runtime_result", retarget)
+ assert service.apply(proposal_id)["proposal"]["status"] == "stale"
+ assert _snapshot(runtime) == original
+ assert _snapshot(alternative_runtime) == alternative
+ with pytest.raises(ActionConflictError, match="recover the original operation"):
+ service.regenerate(proposal_id)
+
+
+def test_witness_only_create_retains_existing_receipt_identity(confirmation):
+ _, registry, runtime, _ = confirmation
+ arguments = dict(registry_path=registry, goal_id="goal-a", role="agent", text="Existing reviewed write",
+ operation_id="chat-todo:prior-confirmation",
+ expected_provider_revision=_snapshot(runtime)["provider_revision"])
+ applied = add_goal_todo(**arguments)
+ saved = _snapshot(runtime)
+ replayed = add_goal_todo(**arguments, expected_registry_sha256=sha256(registry.read_bytes()).hexdigest())
+ assert (applied["status"], replayed["status"]) == ("applied", "replayed")
+ assert replayed["todo_id"] == applied["todo_id"]
+ assert _snapshot(runtime) == saved
+
+
+@pytest.mark.parametrize("edited_since_creation", [False, True])
+def test_legacy_creation_recovers_only_the_receipt_from_the_reviewed_provider_history(
+ confirmation, tmp_path, edited_since_creation,
+):
+ service, registry, runtime, provider = confirmation
+ text = "Verify the release checklist"
+ request = {"goal_id": "goal-a", "text": text}
+ preview = build_todo_review_preview(registry_path=registry, **request)
+ preview_id = preview["preview_id"]
+ legacy = service.store.create_preview(action_kind="todo.create", summary=text,
+ normalized_parameters=request, context={"kind": "goal", "goal_id": "goal-a"},
+ expected_state_fingerprint=preview_id, permission_classification="durable_write",
+ validation_evidence=[], available_transitions=["apply", "cancel"], idempotency_key="legacy-created")
+ proposal_id = legacy["proposal_id"]
+ service.store.start_apply(proposal_id)
+ result = apply_todo_review_preview(registry_path=registry, **request, preview_id=preview_id)
+ receipt = result["receipt"]
+ todo_id = receipt["todo_id"]
+ service.store.save_checkpoint(proposal_id, step="todo_created",
+ receipt={"todo_id": todo_id, "canonical_receipt": receipt})
+ committed = _snapshot(runtime)
+
+ # An independent store can reuse the operation and Todo ID. Its receipt's
+ # predecessor will still differ from the original reviewed revision.
+ other_registry, other_runtime, _ = promoted_create_fixture(tmp_path / "replacement", provider=provider)
+ replacement = add_goal_todo(registry_path=other_registry, **request, role="agent",
+ operation_id=f"chat-todo:{preview_id}")
+ assert replacement["todo_id"] == todo_id
+ other = _snapshot(other_runtime)
+ reopened = ChatActionService(store=service.store, registry_path=other_registry)
+ with pytest.raises(ChatTodoSourceChanged, match="Restore the original Goal source"):
+ reopened.apply(proposal_id)
+ assert _snapshot(other_runtime) == other
+ assert _snapshot(runtime) == committed
+
+ if edited_since_creation:
+ update_goal_todo(registry_path=registry, goal_id="goal-a", todo_id=todo_id,
+ agent_id="agent-a", text="Review the updated release checklist")
+ edited = _snapshot(runtime)
+ assert edited["todos"][0]["todo_id"] == todo_id
+ assert edited["todos"][0]["title"] == "Review the updated release checklist"
+ assert edited["cursor"] != committed["cursor"]
+ committed = edited
+
+ reopened = ChatActionService(store=service.store, registry_path=registry)
+ recovered = reopened.apply(proposal_id)["proposal"]
+ assert recovered["status"] == "applied"
+ assert recovered["receipt"]["projection_verified"] is True
+ assert recovered["receipt"]["projection_delivery"] in {"current", "delivered"}
+ assert recovered["receipt"]["canonical_receipt"] == receipt
+ assert reopened.apply(proposal_id)["proposal"]["receipt"] == recovered["receipt"]
+ assert _snapshot(runtime) == committed
+
+
+@pytest.mark.parametrize("kind, assign", [
+ ("todo.create", False), ("todo.create", True), ("monitor.create", False),
+])
+def test_pending_create_display_recovers_original_confirmation(confirmation, monkeypatch, kind, assign):
+ from loopx.chat_action_store import ActionConflictError
+ from loopx.control_plane.todos import provider_projection
+
+ service, registry, runtime, _ = confirmation
+ record = json.loads(registry.read_text())["goals"][0]
+ display = registry.parent / "project" / record["state_file"]
+ proposal_id = _preview(service, kind, "display-pending", agent="agent-a" if assign else None)
+ original_write = provider_projection.atomic_write_state_text
+ writes = 0
+
+ def write(path, text, **kwargs):
+ nonlocal writes
+ writes += 1
+ if assign and writes == 1:
+ return original_write(path, text, **kwargs)
+ raise PermissionError("synthetic display failure")
+
+ with monkeypatch.context() as faults:
+ faults.setattr(provider_projection, "atomic_write_state_text", write)
+ pending = service.apply(proposal_id)["proposal"]
+ assert pending["status"] == "failed" and pending.get("receipt") is None
+ failure = pending["failure"]
+ assert failure["error_code"] == "canonical_create_projection_pending"
+ details = failure["details"]
+ assert details["canonical_committed"] is True and details["projection_delivery"] == "pending"
+ todo_id = details["todo_id"]
+ assert details["operation_id"] == f"{'chat-assign' if assign else 'chat-create'}:{proposal_id}"
+ with pytest.raises(ActionConflictError, match="recover the original"):
+ service.cancel(proposal_id)
+ assert service.store.load(proposal_id)["failure"]["details"] == details
+ committed = _snapshot(runtime)
+ assert [row["todo_id"] for row in committed["todos"]] == [todo_id]
+ if assign:
+ assert committed["todos"][0]["claimed_by"] == "agent-a"
+ assert "claimed_by=agent-a" not in display.read_text()
+ else:
+ assert todo_id not in display.read_text()
+ with pytest.raises(ActionConflictError, match="recover the original operation"):
+ service.regenerate(proposal_id)
+ if kind == "monitor.create":
+ def unexpected_create(**kwargs):
+ pytest.fail("Display recovery re-entered the Monitor create writer")
+
+ faults.setattr(todo_creation, "add_goal_todo", unexpected_create)
+ retry = service.apply(proposal_id)["proposal"]
+ assert retry["failure"]["details"] == details
+ assert _snapshot(runtime) == committed
+
+ reopened = ChatActionService(store=ChatActionStore(runtime / "chat" / "actions"),
+ registry_path=registry)
+ recovered = reopened.apply(proposal_id)["proposal"]
+ assert recovered["status"] == "applied", recovered
+ assert recovered["receipt"]["projection_verified"] is True
+ assert recovered["receipt"]["projection_delivery"] in {"current", "delivered"}
+ assert recovered["receipt"]["resource_ids"]["todo_id"] == todo_id
+ assert todo_id in display.read_text()
+ if assign:
+ assert "claimed_by=agent-a" in display.read_text()
+ assert reopened.apply(proposal_id)["proposal"]["receipt"] == recovered["receipt"]
+ assert _snapshot(runtime) == committed
+
+
+def test_pending_monitor_confirmation_preserves_the_registered_source_fence(confirmation, monkeypatch, tmp_path):
+ from loopx import paths
+
+ service, registry, runtime, _ = confirmation
+ defaults = (tmp_path / "current", tmp_path / "legacy")
+ for root in defaults:
+ root.mkdir()
+ (root / "machine.json").write_text("{}")
+ monkeypatch.setattr(paths, "DEFAULT_RUNTIME_ROOT", defaults[0])
+ monkeypatch.setattr(paths, "LEGACY_RUNTIME_ROOT", defaults[1])
+
+ original_registry = registry.read_text()
+ unbound = json.loads(original_registry)
+ del unbound["common_runtime_root"]
+ registry.write_text(json.dumps(unbound))
+ service.runtime_root_override = str(runtime)
+ display = tmp_path / "project" / unbound["goals"][0]["state_file"]
+ original_display = display.read_bytes()
+ proposal_id = _preview(service, "monitor.create", "unbound-display")
+
+ pending = service.apply(proposal_id)["proposal"]
+ todo_id = pending["failure"]["details"]["todo_id"]
+ committed = _snapshot(runtime)
+ assert [row["todo_id"] for row in committed["todos"]] == [todo_id]
+ assert service.apply(proposal_id)["proposal"]["status"] == "failed"
+ assert display.read_bytes() == original_display and _snapshot(runtime) == committed
+
+ registry.write_text(original_registry)
+ applied = service.apply(proposal_id)["proposal"]
+ assert applied["status"] == "applied", applied
+ assert applied["receipt"]["resource_ids"]["todo_id"] == todo_id
+ assert todo_id in display.read_text() and _snapshot(runtime) == committed
+ for root in defaults:
+ assert list(root.iterdir()) == [root / "machine.json"]
+ assert (root / "machine.json").read_text() == "{}"
diff --git a/tests/control_plane/test_chat_reviewed_create.py b/tests/control_plane/test_chat_reviewed_create.py
index c29a70d3fa..73b2db6fa4 100644
--- a/tests/control_plane/test_chat_reviewed_create.py
+++ b/tests/control_plane/test_chat_reviewed_create.py
@@ -1,10 +1,188 @@
"""Reviewed App creates must retain their revision through the actual write."""
+import json
+from datetime import datetime, timedelta, timezone
+from http.client import HTTPConnection
+from threading import Thread
+
import pytest
import loopx.chat as chat
-from canonical_authority_fixture import isolate_sqlite_runtime, promoted_create_fixture
+from canonical_authority_fixture import (
+ initialize_canonical_authority, isolate_sqlite_runtime, promoted_create_fixture,
+)
+from loopx.chat_action_store import ChatActionStore
+from loopx.chat_actions import ChatActionService
+from loopx.chat_server import ChatHTTPServer, ChatRequestHandler
from loopx.control_plane.coordination.local_authority import read_canonical_todos_if_promoted
-from loopx.control_plane.todos.mutation_api import add_goal_todo
+from loopx.control_plane.coordination.runtime_shadow import build_todo_runtime_shadow_projection
+from loopx.control_plane.todos.mutation_api import add_goal_todo, update_goal_todo
+
+
+@pytest.mark.parametrize("provider", ["file", "sqlite"])
+@pytest.mark.parametrize("route", ["serving", "registered", "shared-directory", "shared-unbound"])
+@pytest.mark.parametrize("kind", ["todo.create", "monitor.create", "todo-review"])
+def test_http_create_uses_goal_runtime(tmp_path, monkeypatch, provider, route, kind):
+ isolate_sqlite_runtime(tmp_path, monkeypatch)
+ source_registry, runtime, state = promoted_create_fixture(tmp_path, provider=provider)
+ registry = source_registry
+ monkeypatch.setattr("loopx.paths.DEFAULT_RUNTIME_ROOT", tmp_path / "ambient-current")
+ monkeypatch.setattr("loopx.paths.LEGACY_RUNTIME_ROOT", tmp_path / "ambient-legacy")
+ serving_root = runtime
+ decoy = None
+ if route == "serving":
+ registration = json.loads(registry.read_text())
+ del registration["common_runtime_root"]
+ registry.write_text(json.dumps(registration))
+ else:
+ (tmp_path / "other").mkdir()
+ _, decoy_root, _ = promoted_create_fixture(tmp_path / "other", provider=provider)
+ decoy = read_canonical_todos_if_promoted(runtime_root=decoy_root, goal_id="goal-a")
+ serving_root = decoy_root if route == "registered" else tmp_path / "chat-storage"
+ if route.startswith("shared"):
+ registration = json.loads(registry.read_text())
+ registration.update(registry_role="global-local", common_runtime_root=str(decoy_root))
+ if route == "shared-unbound":
+ del registration["common_runtime_root"]
+ registration["goals"][0]["source_registry"] = str(source_registry)
+ registry = tmp_path / "directory.json"
+ registry.write_text(json.dumps(registration))
+ before = read_canonical_todos_if_promoted(runtime_root=runtime, goal_id="goal-a")
+ store = ChatActionStore(serving_root / "chat" / "actions")
+ server = ChatHTTPServer(("127.0.0.1", 0), ChatRequestHandler)
+ server.registry_path, server.runtime_root_override, server.verbose = registry, str(serving_root), False
+ server.action_store = store
+ server.action_service = ChatActionService(store=store, registry_path=registry,
+ runtime_root_override=str(serving_root))
+ worker = Thread(target=server.serve_forever, daemon=True)
+ worker.start()
+ connection = HTTPConnection(*server.server_address, timeout=30)
+
+ def request(method, path, body=None):
+ connection.request(method, path, None if body is None else json.dumps(body),
+ {"Content-Type": "application/json"})
+ response = connection.getresponse()
+ return response.status, json.loads(response.read())
+
+ text = "Review the project index"
+ after_interrupted_create = None
+ try:
+ if kind == "todo-review":
+ intent = {"goal_id": "goal-a", "text": text}
+ code, preview = request("POST", "/api/chat/todo/dry-run", intent)
+ assert code == 200, preview
+ apply_path, confirmation = "/api/chat/todo/apply", {**intent, "preview_id": preview["preview_id"]}
+ else:
+ parameters = {"goal_id": "goal-a", "agent_id": "agent-a"}
+ if kind == "monitor.create":
+ parameters.update(target=text, target_key="index-check", cadence="2h",
+ timezone="UTC", stop_condition="watch_only")
+ else:
+ parameters.update(text=text, priority="P2")
+ code, preview = request("POST", "/api/actions/preview", {
+ "action_kind": kind, "summary": text, "normalized_parameters": parameters,
+ "context": {"kind": "goal", "goal_id": "goal-a"}, "idempotency_key": "review-index",
+ })
+ assert code == 201, preview
+ action_path = f"/api/actions/{preview['proposal']['proposal_id']}"
+ if kind == "todo.create" and route == "shared-directory":
+ original = source_registry.read_text()
+ changed = json.loads(original)
+ changed["goals"][0]["coordination"]["registered_agents"] = ["another-agent"]
+ source_registry.write_text(json.dumps(changed))
+ refused_code, refused = request("POST", f"{action_path}/apply", {})
+ assert refused_code == 400 and "no longer registered" in refused["error"], refused
+ assert read_canonical_todos_if_promoted(runtime_root=runtime, goal_id="goal-a") == before
+ source_registry.write_text(original)
+ if kind == "monitor.create" and route == "shared-directory":
+ original = source_registry.read_text()
+ source_registry.unlink()
+ unavailable_code, unavailable = request("POST", f"{action_path}/apply", {})
+ assert unavailable_code == 400 and unavailable["error_code"] == "invalid_action_apply", unavailable
+ assert str(tmp_path) not in json.dumps(unavailable)
+ assert read_canonical_todos_if_promoted(runtime_root=decoy_root, goal_id="goal-a") == decoy
+ source_registry.write_text(json.dumps({**json.loads(original),
+ "common_runtime_root": str(decoy_root)}))
+ refused_code, refused = request("POST", f"{action_path}/apply", {})
+ assert refused_code == 409 and refused["proposal"]["status"] == "stale", refused
+ assert read_canonical_todos_if_promoted(runtime_root=decoy_root, goal_id="goal-a") == decoy
+ source_registry.write_text(original)
+ code, preview = request("POST", f"{action_path}/regenerate", {})
+ assert code == 201, preview
+ action_path = f"/api/actions/{preview['proposal']['proposal_id']}"
+ apply_path, confirmation = f"{action_path}/apply", {}
+
+ assert read_canonical_todos_if_promoted(runtime_root=runtime, goal_id="goal-a") == before
+ assert text not in state.read_text()
+ if kind == "monitor.create" and route == "registered":
+ original_registration = registry.read_text()
+
+ def retarget_at_write(**kwargs):
+ changed = json.loads(original_registration)
+ changed["common_runtime_root"] = str(decoy_root)
+ registry.write_text(json.dumps(changed))
+ return add_goal_todo(**kwargs)
+
+ with monkeypatch.context() as fault:
+ fault.setattr("loopx.chat.todo_creation.add_goal_todo", retarget_at_write)
+ code, refused = request("POST", apply_path, confirmation)
+ assert code == 409 and refused["proposal"]["status"] == "stale", refused
+ assert read_canonical_todos_if_promoted(runtime_root=runtime, goal_id="goal-a") == before
+ assert read_canonical_todos_if_promoted(runtime_root=decoy_root, goal_id="goal-a") == decoy
+ registry.write_text(original_registration)
+ assert request("POST", f"{action_path}/regenerate", {})[0] == 409
+ code, preview = request("POST", "/api/actions/preview", {
+ "action_kind": kind, "summary": text, "normalized_parameters": parameters,
+ "context": {"kind": "goal", "goal_id": "goal-a"}, "idempotency_key": "new-reviewed-index",
+ })
+ assert code == 201, preview
+ apply_path = f"/api/actions/{preview['proposal']['proposal_id']}/apply"
+
+ def interrupt_after_create(*args, **kwargs):
+ raise OSError("Interrupted after the reviewed Monitor was created")
+
+ monitor_time = datetime.now(timezone.utc).replace(microsecond=0)
+ monkeypatch.setattr("loopx.chat_actions.now_utc", lambda: monitor_time)
+ monkeypatch.setattr("loopx.control_plane.todos.provider_create.now_local", lambda: monitor_time.isoformat())
+ with monkeypatch.context() as fault:
+ fault.setattr(store, "apply", interrupt_after_create)
+ code, interrupted = request("POST", apply_path, confirmation)
+ assert code == 424 and interrupted["error_code"] == "canonical_action_failed", interrupted
+ after_interrupted_create = read_canonical_todos_if_promoted(runtime_root=runtime, goal_id="goal-a")
+ assert int(after_interrupted_create["cursor"]) == int(before["cursor"]) + 1
+ created, = after_interrupted_create["todos"]
+ assert datetime.fromisoformat(created["next_due_at"]) == monitor_time + timedelta(hours=2)
+ monitor_time += timedelta(minutes=1)
+ code, applied = request("POST", apply_path, confirmation)
+ assert code == 200, applied
+ receipt = applied["receipt"] if kind == "todo-review" else applied["proposal"]["receipt"]
+ todo_id = receipt["todo_id"] if kind == "todo-review" else receipt["resource_ids"]["todo_id"]
+ saved = read_canonical_todos_if_promoted(runtime_root=runtime, goal_id="goal-a")
+ if after_interrupted_create is not None:
+ assert saved == after_interrupted_create
+ assert len(saved["todos"]) == 1
+ todo = saved["todos"][0]
+ assert todo["todo_id"] == todo_id and text in todo["text"]
+ assert text in state.read_text()
+ if kind != "todo-review":
+ assert todo["claimed_by"] == "agent-a"
+ if kind == "monitor.create":
+ assert (todo["task_class"], todo["cadence"], todo["target_key"]) == (
+ "continuous_monitor", "2h", "index-check")
+ assert todo["next_due_at"]
+ else:
+ assert todo["priority"] == "P2"
+ assert request("POST", apply_path, confirmation) == (code, applied)
+ assert read_canonical_todos_if_promoted(runtime_root=runtime, goal_id="goal-a") == saved
+ detail_code, detail = request("GET", f"/api/chat/todo/detail?goal_id=goal-a&todo_id={todo_id}")
+ assert detail_code == 200, detail
+ assert detail["review_basis"]["provider_revision"] == saved["provider_revision"]
+ if decoy is not None:
+ assert read_canonical_todos_if_promoted(runtime_root=decoy_root, goal_id="goal-a") == decoy
+ finally:
+ connection.close()
+ server.shutdown()
+ server.server_close()
+ worker.join(timeout=5)
@pytest.mark.parametrize("provider", ["file", "sqlite"])
@@ -82,3 +260,306 @@ def test_changed_intent_cannot_apply_another_preview(tmp_path, monkeypatch, prov
chat.apply_todo_review_preview(registry_path=registry, goal_id="goal-a",
preview_id=preview["preview_id"], **changed)
assert read_canonical_todos_if_promoted(runtime_root=runtime, goal_id="goal-a") == before
+
+
+@pytest.mark.parametrize("provider", ["file", "sqlite"])
+@pytest.mark.parametrize("change", [
+ "same", "directory", "runtime", "registration", "store", "unrelated_todo",
+ "edited_todo", "lost_assignment_checkpoint", "directory_during_assignment",
+ "legacy_same", "legacy_runtime", "legacy_registration", "legacy_store",
+ "legacy_unrelated_todo", "legacy_edited_todo",
+])
+def test_interrupted_assignment_keeps_the_created_todo_source(tmp_path, monkeypatch, provider, change):
+ legacy = change.startswith("legacy_")
+ change = change.removeprefix("legacy_")
+ isolate_sqlite_runtime(tmp_path, monkeypatch)
+ goal_id = "goal-a"
+ original_registry, original_root, _ = promoted_create_fixture(tmp_path / "original", provider=provider)
+ original_registration = original_registry.read_text()
+ replacement_root = tmp_path / "replacement" / "runtime"
+ replacement_state = replacement_root.parent / "state.md"
+ replacement_state.parent.mkdir()
+ replacement_state.write_text("# Other Goal\n\n## Agent Todo\n\n## Completed Work Archive\n")
+ replacement_registry = replacement_root.parent / "registry.json"
+ replacement_doc = json.loads(original_registration)
+ replacement_doc["common_runtime_root"] = str(replacement_root)
+ replacement_doc["goals"][0].update(repo=str(replacement_state.parent), state_file=replacement_state.name)
+ replacement_registry.write_text(json.dumps(replacement_doc))
+ directory = tmp_path / "directory.json"
+ directory_doc = json.loads(replacement_registry.read_text())
+ directory_doc["registry_role"] = "global-local"
+ directory_doc["goals"][0]["source_registry"] = str(original_registry)
+ original_directory = json.dumps(directory_doc)
+ directory.write_text(original_directory)
+ store = ChatActionStore(tmp_path / "chat" / "actions")
+ server = ChatHTTPServer(("127.0.0.1", 0), ChatRequestHandler)
+ server.registry_path, server.runtime_root_override, server.verbose = directory, str(tmp_path / "chat"), False
+ server.action_store = store
+ server.action_service = ChatActionService(store=store, registry_path=directory)
+ worker = Thread(target=server.serve_forever, daemon=True)
+ worker.start()
+ connection = HTTPConnection(*server.server_address, timeout=40)
+ checkpoint = store.save_checkpoint
+
+ def write_checkpoint(proposal_id, *, step, receipt, **kwargs):
+ saved = checkpoint(proposal_id, step=step, receipt=receipt, **kwargs)
+ if step == "todo_created":
+ raise OSError("Interrupted after creating the Todo and before assigning it")
+ return saved
+
+ def post(path, body):
+ connection.request("POST", path, json.dumps(body), {"Content-Type": "application/json"})
+ response = connection.getresponse()
+ return response.status, json.loads(response.read())
+
+ def read(runtime):
+ return read_canonical_todos_if_promoted(runtime_root=runtime, goal_id=goal_id)
+
+ try:
+ text = "Prepare the original delivery"
+ request = {
+ "action_kind": "todo.create", "summary": text,
+ "normalized_parameters": {"goal_id": goal_id, "agent_id": "agent-a", "text": text},
+ "context": {"kind": "goal", "goal_id": goal_id}, "idempotency_key": "reviewed-original",
+ }
+ if legacy:
+ # Exercise the original native operation identity and persisted step,
+ # before the Chat create preparation and source fields existed.
+ preview = chat.build_todo_review_preview(registry_path=original_registry, goal_id=goal_id, text=text)
+ proposal = store.create_preview(**request, expected_state_fingerprint=preview["preview_id"],
+ permission_classification="durable_write", validation_evidence=[], available_transitions=["apply", "cancel"])
+ proposal_id = proposal["proposal_id"]
+ store.start_apply(proposal_id)
+ receipt = chat.apply_todo_review_preview(registry_path=original_registry, goal_id=goal_id,
+ text=text, preview_id=preview["preview_id"])["receipt"]
+ checkpoint(proposal_id, step="todo_created", receipt={"todo_id": receipt["todo_id"], "canonical_receipt": receipt})
+ store.mark_failed(proposal_id, error_code="canonical_action_failed", message="Interrupted before assignment")
+ else:
+ code, preview = post("/api/actions/preview", request)
+ assert code == 201, preview
+ proposal_id = preview["proposal"]["proposal_id"]
+ with monkeypatch.context() as fault:
+ fault.setattr(store, "save_checkpoint", write_checkpoint)
+ code, interrupted = post(f"/api/actions/{proposal_id}/apply", {})
+ assert code == 424 and interrupted["error_code"] == "canonical_action_failed", interrupted
+ path = f"/api/actions/{proposal_id}/apply"
+ created = store.load(proposal_id)["checkpoint"]["steps"]["todo_created"]
+ todo_id = created["todo_id"]
+ original = read(original_root)
+ assert original["todos"][0]["todo_id"] == todo_id
+ assert original["todos"][0].get("claimed_by") is None
+
+ # Same public ids, independently initialized authority and different content.
+ replacement_record = {**original["todos"][0], "text": "[P1] Unrelated replacement work",
+ "title": "Unrelated replacement work"}
+ initialize_canonical_authority(replacement_root, goal_id,
+ build_todo_runtime_shadow_projection(goal_id=goal_id, todos=[replacement_record],
+ handoff_mode="soft_claim"),
+ state_path=replacement_state, provider=provider)
+ replacement = read(replacement_root)
+ saved_root = original_root.with_name("saved-runtime")
+ if change == "directory":
+ directory_doc["goals"][0]["source_registry"] = str(replacement_registry)
+ directory.write_text(json.dumps(directory_doc))
+ elif change == "runtime":
+ changed = json.loads(original_registration)
+ changed["common_runtime_root"] = str(replacement_root)
+ original_registry.write_text(json.dumps(changed))
+ elif change == "registration":
+ revoked = json.loads(original_registration)
+ revoked["goals"][0]["coordination"]["registered_agents"] = ["another-agent"]
+ original_registry.write_text(json.dumps(revoked))
+ elif change == "store":
+ original_root.rename(saved_root)
+ replacement_root.rename(original_root)
+ if change in {"directory", "runtime", "registration", "store"}:
+ code, denied = post(path, {})
+ if legacy:
+ assert code == 409 and denied["error_code"] == "protected_action", denied
+ assert denied["proposal"]["checkpoint"]["steps"]["todo_created"] == created
+ assert todo_id in denied["gate"]["summary"]
+ else:
+ assert code == 400 and "receipt" not in denied, denied
+ if change == "store":
+ assert read(original_root) == replacement
+ original_root.rename(replacement_root)
+ saved_root.rename(original_root)
+ assert read(original_root) == original and read(replacement_root) == replacement
+ saved_steps = store.load(proposal_id)["checkpoint"]["steps"]
+ assert set(saved_steps) == ({"todo_created"} if legacy else {"todo_create_prepared", "todo_created"})
+ assert saved_steps["todo_created"] == created
+ directory.write_text(original_directory)
+ original_registry.write_text(original_registration)
+ if change == "directory_during_assignment":
+ from loopx.control_plane.todos import provider_update
+
+ dispatch = provider_update._dispatch_canonical_todo_update
+
+ def retarget_before_dispatch(request, *, registry_path):
+ directory_doc["goals"][0]["source_registry"] = str(replacement_registry)
+ directory.write_text(json.dumps(directory_doc))
+ return dispatch(request, registry_path=registry_path)
+
+ with monkeypatch.context() as fault:
+ fault.setattr(provider_update, "_dispatch_canonical_todo_update", retarget_before_dispatch)
+ code, denied = post(path, {})
+ assert code == 400 and "receipt" not in denied, denied
+ assert directory.read_text() != original_directory
+ assert read(original_root) == original and read(replacement_root) == replacement
+ directory.write_text(original_directory)
+ if change == "edited_todo":
+ update_goal_todo(registry_path=original_registry, goal_id=goal_id, todo_id=todo_id,
+ agent_id="agent-a", text="A different assignment")
+ edited = read(original_root)
+ code, denied = post(path, {})
+ if legacy:
+ assert code == 409 and denied["error_code"] == "protected_action", denied
+ assert denied["proposal"]["checkpoint"]["steps"]["todo_created"] == created
+ else:
+ assert code == 400 and "receipt" not in denied, denied
+ assert "original receipt" in str(denied)
+ assert read(original_root) == edited and read(replacement_root) == replacement
+ return
+ if change in {"unrelated_todo", "lost_assignment_checkpoint"}:
+ added = add_goal_todo(registry_path=original_registry, goal_id=goal_id,
+ role="agent", text="Independent work in the same Goal")
+ original = read(original_root)
+ unrelated_todo = next(row for row in original["todos"] if row["todo_id"] == added["todo_id"])
+ if change == "lost_assignment_checkpoint":
+ def lose_assignment_checkpoint(proposal_id, *, step, receipt, **kwargs):
+ if step == "todo_assigned":
+ raise OSError("Interrupted after assigning the original Todo")
+ return checkpoint(proposal_id, step=step, receipt=receipt, **kwargs)
+
+ with monkeypatch.context() as fault:
+ fault.setattr(store, "save_checkpoint", lose_assignment_checkpoint)
+ code, failed = post(path, {})
+ assert code == 424 and failed["error_code"] == "canonical_action_failed", failed
+ assigned_without_checkpoint = read(original_root)
+ assert int(assigned_without_checkpoint["cursor"]) == int(original["cursor"]) + 1
+ code, applied = post(path, {})
+ assert code == 200 and applied["proposal"]["status"] == "applied", applied
+ assert applied["proposal"]["receipt"]["canonical_receipt"] == created["canonical_receipt"]
+ final = read(original_root)
+ assigned = next(row for row in final["todos"] if row["todo_id"] == todo_id)
+ assert assigned["claimed_by"] == "agent-a"
+ assert len(final["todos"]) == len(original["todos"])
+ if change in {"unrelated_todo", "lost_assignment_checkpoint"}:
+ assert next(row for row in final["todos"] if row["todo_id"] == unrelated_todo["todo_id"]) == unrelated_todo
+ if change == "lost_assignment_checkpoint":
+ assert final == assigned_without_checkpoint
+ assert int(final["cursor"]) == int(original["cursor"]) + 1
+ assert post(path, {}) == (code, applied)
+ assert read(original_root) == final and read(replacement_root) == replacement
+ finally:
+ connection.close()
+ server.shutdown()
+ server.server_close()
+ worker.join(timeout=5)
+
+
+@pytest.mark.parametrize("provider", ["file", "sqlite"])
+@pytest.mark.parametrize("operation", ["edit", "complete", "monitor.stop", "gate.resolve"])
+def test_existing_chat_actions_and_detail_follow_the_same_goal_source(tmp_path, monkeypatch, provider, operation):
+ isolate_sqlite_runtime(tmp_path, monkeypatch)
+ goal_id = "goal-a"
+ source, root, _ = promoted_create_fixture(tmp_path / "source", provider=provider)
+ shared, shared_root, _ = promoted_create_fixture(tmp_path / "shared", provider=provider)
+ kind = {"monitor.stop": "monitor.update", "gate.resolve": "gate.resolve"}.get(operation, "todo.update")
+
+ def add(registry, text):
+ if kind == "monitor.update":
+ intent = {"task_class": "continuous_monitor", "claimed_by": "agent-a",
+ "monitor_metadata": {"cadence": "2h", "target_key": text, "watch_only": "true"}}
+ elif kind == "gate.resolve":
+ intent = {"task_class": "user_gate", "blocks_agent": "agent-a"}
+ else:
+ intent = {"task_class": "advancement_task", "claimed_by": "agent-a"}
+ return add_goal_todo(registry_path=registry, goal_id=goal_id, text=text,
+ role="user" if kind == "gate.resolve" else "agent", **intent)["todo_id"]
+
+ todo_id = add(source, "Review source task")
+ shared_id = add(shared, "Shared decoy task")
+ def read(runtime):
+ return read_canonical_todos_if_promoted(runtime_root=runtime, goal_id=goal_id)
+
+ source_before, shared_before = read(root), read(shared_root)
+ directory = tmp_path / "directory.json"
+ doc = json.loads(shared.read_text())
+ doc["registry_role"] = "global-local"
+ doc["goals"][0]["source_registry"] = str(source)
+ directory.write_text(json.dumps(doc))
+ store = ChatActionStore(tmp_path / "chat" / "actions")
+ server = ChatHTTPServer(("127.0.0.1", 0), ChatRequestHandler)
+ server.registry_path, server.runtime_root_override, server.verbose = directory, str(tmp_path / "chat"), False
+ server.action_store = store
+ server.action_service = ChatActionService(store=store, registry_path=directory)
+ worker = Thread(target=server.serve_forever, daemon=True)
+ worker.start()
+ connection = HTTPConnection(*server.server_address, timeout=40)
+
+ def request(method, path, body=None):
+ connection.request(method, path, None if body is None else json.dumps(body),
+ {"Content-Type": "application/json"})
+ response = connection.getresponse()
+ return response.status, json.loads(response.read())
+
+ def detail(task_id):
+ return request("GET", f"/api/chat/todo/detail?goal_id={goal_id}&todo_id={task_id}")
+
+ def preview(task_id, key, review_basis=None):
+ intent = {"goal_id": goal_id, "todo_id": task_id, "agent_id": "agent-a"}
+ if kind == "gate.resolve":
+ intent.update(decision="approve")
+ elif kind == "monitor.update":
+ intent.update(operation="stop")
+ else:
+ intent.update(operation=operation)
+ if operation == "edit":
+ intent.update(text="Reviewed authoritative requirements")
+ if review_basis:
+ intent["review_basis"] = review_basis
+ else:
+ intent.update(note="Completed the selected task")
+ return request("POST", "/api/actions/preview", {
+ "action_kind": kind, "summary": "Apply a source Task action",
+ "context": {"kind": "goal", "goal_id": goal_id},
+ "normalized_parameters": intent, "idempotency_key": key,
+ })
+
+ try:
+ basis = None
+ if kind != "gate.resolve":
+ code, shown = detail(todo_id)
+ assert code == 200, shown
+ basis = shown["review_basis"]
+ assert shown["text"] == source_before["todos"][0]["text"]
+ assert detail(shared_id)[0] == 404
+ code, refused = preview(shared_id, "shared-only")
+ assert code == 400 and refused.get("ok") is False, refused
+
+ code, proposal = preview(todo_id, "authoritative", basis)
+ assert code == 201, proposal
+ preview_basis = proposal["proposal"]["canonical_update_basis"]
+ assert preview_basis["provider_revision"] == source_before["provider_revision"]
+ if basis is not None:
+ assert preview_basis["source_identity"] == basis["source_identity"]
+ assert read(root) == source_before and read(shared_root) == shared_before
+ path = f"/api/actions/{proposal['proposal']['proposal_id']}/apply"
+ code, response = request("POST", path, {})
+ assert code == 200 and response["proposal"]["status"] == "applied", response
+ after = read(root)
+ assert int(after["cursor"]) == int(source_before["cursor"]) + 1
+ (updated,) = after["todos"]
+ if operation == "edit":
+ assert updated["text"] == "[P1] Reviewed authoritative requirements"
+ assert detail(todo_id)[1]["text"] == updated["text"]
+ else:
+ assert updated["status"] == "done"
+ assert request("POST", path, {}) == (code, response)
+ assert read(root) == after and read(shared_root) == shared_before
+ finally:
+ connection.close()
+ server.shutdown()
+ server.server_close()
+ worker.join(timeout=5)
diff --git a/tests/control_plane/test_chat_task_start_recovery.py b/tests/control_plane/test_chat_task_start_recovery.py
index 56dd2af5cf..48605c1ad5 100644
--- a/tests/control_plane/test_chat_task_start_recovery.py
+++ b/tests/control_plane/test_chat_task_start_recovery.py
@@ -16,6 +16,7 @@
from loopx.chat_runtime import ChatRuntimeController
from loopx.chat_store import ChatSessionStore
from loopx.control_plane.coordination.local_authority import read_canonical_todos_if_promoted
+from loopx.control_plane.todos.mutation_api import add_goal_todo
from test_goal_create_completion import preview_goal
from test_new_goal_storage_defaults import app, environment # noqa: F401
@@ -142,11 +143,11 @@ def test_concurrent_task_confirmation_preserves_the_inflight_owner(task_start, m
entered, proceed = Event(), Event()
save = actions.save_checkpoint
- def pause(proposal_id, *, step, receipt):
+ def pause(proposal_id, *, step, receipt, **kwargs):
if step == "task_session_opened" and not entered.is_set():
entered.set()
assert proceed.wait(15), "the first confirmation did not resume"
- return save(proposal_id, step=step, receipt=receipt)
+ return save(proposal_id, step=step, receipt=receipt, **kwargs)
monkeypatch.setattr(actions, "save_checkpoint", pause)
with ThreadPoolExecutor(max_workers=1) as pool:
@@ -173,16 +174,55 @@ def pause(proposal_id, *, step, receipt):
assert calls.count("thread/start") == calls.count("turn/start") == 1
+def test_task_start_recovers_after_unrelated_todo_write(task_start, monkeypatch):
+ actions, post, _, controller, _, runtime, capture, proposal_id = task_start
+ path = f"/api/actions/{proposal_id}/apply"
+ save = actions.save_checkpoint
+
+ def interrupt(proposal_id, *, step, receipt, **kwargs):
+ stored = save(proposal_id, step=step, receipt=receipt, **kwargs)
+ if step == "todo_created":
+ raise OSError("Interrupted before the managed claim")
+ return stored
+
+ with monkeypatch.context() as fault:
+ fault.setattr(actions, "save_checkpoint", interrupt)
+ code, result = post(path, {})
+ assert code == 424, result
+ original = actions.load(proposal_id)["checkpoint"]["steps"]["todo_created"]
+ other = add_goal_todo(registry_path=controller.registry_path, runtime_root_arg=str(runtime),
+ goal_id="report", text="Follow up on the separate budget check", role="agent")
+ before = {row["todo_id"]: row for row in _snapshot(runtime)["todos"]}
+ assert before[other["todo_id"]].get("claimed_by") is None
+ code, applied = post(path, {})
+ assert code == 202, applied
+ receipt = applied["proposal"]["receipt"]
+ assert receipt["canonical_receipt"] == original["canonical_receipt"]
+ ids = receipt["resource_ids"]
+ assert ids["todo_id"] == original["todo_id"]
+ assert controller.wait_for_turn(session_id=ids["session_id"], turn_id=ids["turn_id"], timeout_sec=10)["status"] == "completed"
+ final = _snapshot(runtime)
+ rows = {row["todo_id"]: row for row in final["todos"]}
+ assert rows[original["todo_id"]].get("claimed_by") == "codex"
+ assert {key: row for key, row in rows.items() if key != original["todo_id"]} == {
+ key: row for key, row in before.items() if key != original["todo_id"]
+ }
+ assert post(path, {})[1]["proposal"]["receipt"] == receipt
+ assert _snapshot(runtime) == final
+ calls = [json.loads(line)["method"] for line in capture.read_text().splitlines()]
+ assert calls.count("turn/start") == 1
+
+
@pytest.mark.parametrize("change", ["defaults", "close"])
def test_task_session_is_pinned_before_its_checkpoint(task_start, monkeypatch, change):
actions, post, chat, controller, reopen, runtime, capture, proposal_id = task_start
path = f"/api/actions/{proposal_id}/apply"
save = actions.save_checkpoint
- def interrupt(proposal_id, *, step, receipt):
+ def interrupt(proposal_id, *, step, receipt, **kwargs):
if step == "task_session_opened":
raise OSError("Session persisted before the confirmation checkpoint")
- return save(proposal_id, step=step, receipt=receipt)
+ return save(proposal_id, step=step, receipt=receipt, **kwargs)
with monkeypatch.context() as faults:
faults.setattr(actions, "save_checkpoint", interrupt)
@@ -244,7 +284,7 @@ def before_dispatch(*, session_id, turn_id, **kwargs):
save = actions.save_checkpoint
- def after_completion(proposal_id, *, step, receipt):
+ def after_completion(proposal_id, *, step, receipt, **kwargs):
if step == "task_session_opened" and interruption.startswith("legacy"):
# Old confirmations admitted a Turn without this checkpoint.
return actions.load(proposal_id)
@@ -252,7 +292,7 @@ def after_completion(proposal_id, *, step, receipt):
lost.update(receipt)
assert controller.wait_for_turn(**receipt, timeout_sec=10)["status"] == "completed"
raise OSError("Turn completed before the confirmation checkpoint")
- return save(proposal_id, step=step, receipt=receipt)
+ return save(proposal_id, step=step, receipt=receipt, **kwargs)
with monkeypatch.context() as faults:
if interruption.startswith("accepted"):
diff --git a/tests/control_plane/test_native_user_completion_update.py b/tests/control_plane/test_native_user_completion_update.py
index 6b68426f70..62d7c24077 100644
--- a/tests/control_plane/test_native_user_completion_update.py
+++ b/tests/control_plane/test_native_user_completion_update.py
@@ -75,6 +75,17 @@ def validation_command(source: str) -> str:
return shlex.join([sys.executable, "-c", source])
+def chat_runtime_routes(
+ registry: Path, *, host_fallback: bool,
+) -> tuple[str, str | None]:
+ if not host_fallback:
+ return str(registry.parent / "chat-history"), None
+ registration = json.loads(registry.read_text(encoding="utf-8"))
+ runtime = str(registration.pop("common_runtime_root"))
+ registry.write_text(json.dumps(registration), encoding="utf-8")
+ return runtime, runtime
+
+
@pytest.mark.parametrize("provider", ["file", "sqlite"])
def test_validation_failure_preview_and_replay(tmp_path: Path, provider: str) -> None:
marker = tmp_path / "calls"
@@ -134,14 +145,26 @@ def test_invalid_input_and_permission_do_not_run_validation(tmp_path: Path, prov
@pytest.mark.parametrize("provider", ["file", "sqlite"])
-@pytest.mark.parametrize("failure_boundary", ["display", "action_receipt"])
-def test_reviewed_chat_completion_recovers_projection(tmp_path: Path, provider: str, monkeypatch: pytest.MonkeyPatch, failure_boundary: str) -> None:
+@pytest.mark.parametrize(
+ ("failure_boundary", "host_fallback"),
+ [("display", False), ("action_receipt", False), ("action_receipt", True)],
+ ids=["registered-display", "registered-receipt", "host-fallback-receipt"],
+)
+def test_reviewed_chat_completion_recovers_projection(
+ tmp_path: Path, provider: str, monkeypatch: pytest.MonkeyPatch,
+ failure_boundary: str, host_fallback: bool,
+) -> None:
from loopx.chat_action_store import ChatActionStore
from loopx.chat_actions import ChatActionService
from loopx.control_plane.todos import provider_projection
registry, state, todo_id = fixture(tmp_path, provider)
- service = ChatActionService(store=ChatActionStore(tmp_path / "actions"), registry_path=registry)
+ chat_root, todo_root = chat_runtime_routes(registry, host_fallback=host_fallback)
+ route = {"registry_path": registry, "goal_id": "goal-a", "runtime_root_arg": todo_root}
+ service = ChatActionService(
+ store=ChatActionStore(tmp_path / "actions"), registry_path=registry,
+ runtime_root_override=chat_root,
+ )
proposal = service.preview({"action_kind": "todo.update", "summary": "Record an observed outcome",
"normalized_parameters": {"goal_id": "goal-a", "todo_id": todo_id,
"agent_id": "agent-a", "operation": "complete", "note": "Reviewed observation"},
@@ -160,13 +183,16 @@ def lost_response(*args, **kwargs):
patch.setattr(service.store, "apply", lost_response)
with pytest.raises(ConnectionError):
service.apply(proposal["proposal_id"])
- assert list_goal_todos(registry_path=registry, goal_id="goal-a")["todos"][0]["status"] == "done"
+ committed = list_goal_todos(**route)
+ assert committed["todos"][0]["status"] == "done"
state.unlink()
recovered = service.apply(proposal["proposal_id"])["proposal"]
assert recovered["status"] == "applied"
assert recovered["receipt"]["outcome"] == "todo_completed"
assert state.exists()
- dependent = next(row for row in list_goal_todos(registry_path=registry, goal_id="goal-a")["todos"] if row["role"] == "agent")
+ after = list_goal_todos(**route)
+ assert after["authority_read"]["provider_revision"] == committed["authority_read"]["provider_revision"]
+ dependent = next(row for row in after["todos"] if row["role"] == "agent")
assert (dependent["status"], dependent["claimed_by"]) == ("open", "agent-a")
@@ -189,7 +215,10 @@ def test_chat_user_validation_failure_never_creates_success_receipt(tmp_path: Pa
@pytest.mark.parametrize("provider", ["file", "sqlite"])
@pytest.mark.parametrize("case", ["multiline_command", "multiline_argv", "failed"])
-def test_packaged_chat_http_user_completion(tmp_path: Path, provider: str, case: str) -> None:
+@pytest.mark.parametrize("host_fallback", [False, True], ids=["registered", "host-fallback"])
+def test_packaged_chat_http_user_completion(
+ tmp_path: Path, provider: str, case: str, host_fallback: bool,
+) -> None:
from http.client import HTTPConnection
from threading import Thread
from loopx.chat_action_store import ChatActionStore
@@ -217,12 +246,20 @@ def test_packaged_chat_http_user_completion(tmp_path: Path, provider: str, case:
validation_argv=argv if use_argv else None,
validation_label=label if passed else None,
)
+ chat_root, todo_root = chat_runtime_routes(registry, host_fallback=host_fallback)
+ route = {"registry_path": registry, "goal_id": "goal-a", "runtime_root_arg": todo_root}
+ before = list_goal_todos(**route)
+ dependent_id = next(row["todo_id"] for row in before["todos"] if row["role"] == "agent")
store = ChatActionStore(tmp_path / "actions")
server = ChatHTTPServer(("127.0.0.1", 0), ChatRequestHandler)
server.verbose = False
server.assets_dir = default_chat_assets_dir()
+ server.registry_path = registry
+ server.runtime_root_override = chat_root
server.action_store = store
- server.action_service = ChatActionService(store=store, registry_path=registry)
+ server.action_service = ChatActionService(
+ store=store, registry_path=registry, runtime_root_override=chat_root,
+ )
thread = Thread(target=server.serve_forever, daemon=True)
thread.start()
connection = HTTPConnection("127.0.0.1", server.server_address[1], timeout=45)
@@ -231,6 +268,11 @@ def test_packaged_chat_http_user_completion(tmp_path: Path, provider: str, case:
response = connection.getresponse()
assert response.status == 200
assert b"