diff --git a/loopx/cli_commands/todo.py b/loopx/cli_commands/todo.py index ccee773b84..78588c63d4 100644 --- a/loopx/cli_commands/todo.py +++ b/loopx/cli_commands/todo.py @@ -686,6 +686,8 @@ def handle_todo_command( claim_only=True, manage_execution=(args.agent_id is not None and args.agent_id == args.claimed_by and args.task_lease_idempotency_key is None and args.task_lease_expected_version is None), + allow_settled_execution_switch=(args.agent_id is not None and args.agent_id == args.claimed_by + and args.task_lease_idempotency_key is None and args.task_lease_expected_version is None), claim_operation_id=args.claim_operation_id, task_lease_idempotency_key=args.task_lease_idempotency_key, task_lease_expected_version=args.task_lease_expected_version, diff --git a/loopx/control_plane/coordination/claim_execution.ts b/loopx/control_plane/coordination/claim_execution.ts index 04c2e2875e..f8bdc585f7 100644 --- a/loopx/control_plane/coordination/claim_execution.ts +++ b/loopx/control_plane/coordination/claim_execution.ts @@ -11,7 +11,9 @@ import {leaseEpoch, leaseVersion, leaseIsActive, normalizeTtl, type LeaseRecord} import {sameLeaseWorkspace, type LeaseWorkspace} from "../work_items/task_lease_workspace.ts"; import {leaseWriteRepository} from "../work_items/task_lease_repository.ts"; import {evaluateTaskLeaseAcquireDecision, materializeTaskLeaseAcquire} from "../work_items/task_lease_acquire_decision.ts"; -import {decideTaskLeaseLifecycle, materializeTaskLeaseLifecycle} from "../work_items/task_lease_lifecycle_decision.ts"; +import {decideTaskLeaseLifecycle, materializeTaskLeaseLifecycle, + releasedTaskLeaseRecord} from "../work_items/task_lease_lifecycle_decision.ts"; +import {normalizeTodoRepository} from "../todos/work_requirements.ts"; export function claimExecutionReference(id: unknown, key: unknown, version: unknown): string | undefined { if (id == null) return undefined; @@ -26,6 +28,47 @@ type ExecutionInput = {goal_id: string; todo_id: string; actor_agent_id: string export type ClaimWorkspaceObserver = (writeScopes: readonly string[]) => Promise; +export const SETTLED_EXECUTION_SWITCH_PROOF_SCHEMA = + "todo_settled_execution_switch_proof_v0"; + +export interface ClaimExecutionSwitchProof extends JsonObject { + readonly schema_version: typeof SETTLED_EXECUTION_SWITCH_PROOF_SCHEMA; + readonly goal_id: string; + readonly source_todo_id: string; + readonly target_todo_id: string; + readonly agent_id: string; + readonly source_lease_idempotency_key: string; + readonly source_lease_version: number; + readonly source_lease_epoch: number; + readonly settlement_identity: JsonObject; +} + +export type ClaimExecutionSwitchVerifier = (input: { + readonly goal_id: string; + readonly source_todo_id: string; + readonly target_todo_id: string; + readonly agent_id: string; + readonly source_lease_idempotency_key: string; + readonly source_lease_version: number; + readonly source_lease_epoch: number; +}) => Promise; + +export interface PreparedClaimExecution { + readonly lease: LeaseRecord; + readonly changed: boolean; + readonly overlapAdvisories?: JsonObject[]; + readonly releasedSourceLease?: LeaseRecord; + readonly switchProof?: ClaimExecutionSwitchProof; +} + +export class ClaimExecutionSwitchRejected extends AuthorityStoreProtocolError { + readonly reasonCode: string; + constructor(reasonCode: string, message: string) { + super(message); + this.reasonCode = reasonCode; + } +} + /** A diagnostic distinction, never permission to renew or adopt another grant. */ export class ClaimExecutionUnavailable extends AuthorityStoreProtocolError { readonly sameExecutionExpired: boolean; @@ -99,8 +142,10 @@ export function maintainClaimExecution(head: JsonObject, input: ExecutionInput, * transfer grant). Expired execution is reclaimable without the old process; * acquisition still validates scope, eligibility and generation under one CAS. */ export async function prepareClaimExecution(head: JsonObject, - input: ExecutionInput & {operation_id: string; claimed_by: string}, - observeWorkspace?: ClaimWorkspaceObserver): Promise<{lease: LeaseRecord; changed: boolean; overlapAdvisories?: JsonObject[]}> { + input: ExecutionInput & {operation_id: string; claimed_by: string; + allow_settled_execution_switch?: boolean}, + observeWorkspace?: ClaimWorkspaceObserver, + verifySettledSwitch?: ClaimExecutionSwitchVerifier): Promise { const index = indexCoordinationProjection(head, input.goal_id); const facts = canonicalTaskLeaseAcquireFacts(index, input.goal_id, input.todo_id, input.registered_agents, input.now); const current = facts.current; @@ -121,14 +166,101 @@ export async function prepareClaimExecution(head: JsonObject, owner: input.claimed_by, operation_id: input.operation_id})}`, expected_version: current ? leaseVersion(current) : 0, ttl_seconds: normalizeTtl(null), write_scopes: writeScopes, ...(workspace ? {write_workspace: workspace} : {})}; - const decision = evaluateTaskLeaseAcquireDecision({handoff_mode: String(head.handoff_mode), + let decisionOtherLeases = facts.other_leases; + let decision = evaluateTaskLeaseAcquireDecision({handoff_mode: String(head.handoff_mode), registered_agents: [...input.registered_agents], ...facts, // Claim admission has already authorized this assignment. Acquire and the // Todo owner change commit together; the old assignment is not a new gate. todo: facts.todo === null ? null : {...facts.todo, claimed_by: input.claimed_by}, command}); + let releasedSourceLease: LeaseRecord | undefined; + let switchProof: ClaimExecutionSwitchProof | undefined; + if (decision.outcome === "conflict" && decision.code === "write_scope_conflict" && + input.allow_settled_execution_switch === true) { + if (!verifySettledSwitch) { + throw new ClaimExecutionSwitchRejected( + "settled_execution_switch_settlement_unavailable", + "Settled execution switch requires authoritative Turn settlement readback", + ); + } + if (decision.conflict_indexes.length !== 1) { + throw new ClaimExecutionSwitchRejected( + "settled_execution_switch_ambiguous_source", + "Settled execution switch requires exactly one conflicting source execution", + ); + } + const sourceIndex = decision.conflict_indexes[0]!; + const sourceFact = facts.other_leases[sourceIndex]; + if (!sourceFact || sourceFact.owner !== input.claimed_by || + !sourceFact.active || !sourceFact.effective) { + throw new ClaimExecutionSwitchRejected( + "settled_execution_switch_source_mismatch", + "Settled execution switch cannot release another Agent or an ineffective execution", + ); + } + const sourceTodo = index.todos.get(sourceFact.todo_id); + const targetRepository = normalizeTodoRepository(todo.task_repository); + const sourceRepository = normalizeTodoRepository(sourceTodo?.task_repository); + if (targetRepository === null || sourceRepository === null || + targetRepository.toLowerCase() !== sourceRepository.toLowerCase()) { + throw new ClaimExecutionSwitchRejected( + "settled_execution_switch_repository_mismatch", + "Settled execution switch requires source and target Todos in the same declared repository", + ); + } + const sourceRaw = index.leases.get(sourceFact.todo_id); + if (!sourceRaw) { + throw new ClaimExecutionSwitchRejected( + "settled_execution_switch_source_missing", + "Settled execution switch source lease disappeared", + ); + } + const sourceLease = canonicalTaskLease( + sourceRaw, + input.goal_id, + sourceFact.todo_id, + ); + switchProof = await verifySettledSwitch({ + goal_id: input.goal_id, + source_todo_id: sourceFact.todo_id, + target_todo_id: input.todo_id, + agent_id: input.claimed_by, + source_lease_idempotency_key: String(sourceLease.idempotency_key), + source_lease_version: leaseVersion(sourceLease), + source_lease_epoch: leaseEpoch(sourceLease), + }); + if (switchProof.schema_version !== SETTLED_EXECUTION_SWITCH_PROOF_SCHEMA || + switchProof.goal_id !== input.goal_id || + switchProof.source_todo_id !== sourceFact.todo_id || + switchProof.target_todo_id !== input.todo_id || + switchProof.agent_id !== input.claimed_by || + switchProof.source_lease_idempotency_key !== sourceLease.idempotency_key || + switchProof.source_lease_version !== leaseVersion(sourceLease) || + switchProof.source_lease_epoch !== leaseEpoch(sourceLease) || + switchProof.settlement_identity === null || + typeof switchProof.settlement_identity !== "object") { + throw new ClaimExecutionSwitchRejected( + "settled_execution_switch_proof_mismatch", + "Settled execution switch proof does not match the requested handoff", + ); + } + const remaining = facts.other_leases.filter((_, index) => index !== sourceIndex); + decisionOtherLeases = remaining; + decision = evaluateTaskLeaseAcquireDecision({ + handoff_mode: String(head.handoff_mode), + registered_agents: [...input.registered_agents], + ...facts, + other_leases: remaining, + todo: facts.todo === null ? null : {...facts.todo, claimed_by: input.claimed_by}, + command, + }); + if (decision.outcome === "apply") { + releasedSourceLease = releasedTaskLeaseRecord(sourceLease, input.now); + } + } if (decision.outcome !== "apply") throw new AuthorityStoreProtocolError(`Task claim execution rejected: ${decision.code}`); const overlapAdvisories = (decision.overlap_advisory_indexes ?? []).map(index => ({ - todo_id: facts.other_leases[index].todo_id, owner: facts.other_leases[index].owner ?? null, - write_scopes: facts.other_leases[index].write_scopes, reason: "independent_worktree_integration_overlap"})); - return {lease: materializeTaskLeaseAcquire(input, command, decision, input.now), changed: true, overlapAdvisories}; + todo_id: decisionOtherLeases[index].todo_id, owner: decisionOtherLeases[index].owner ?? null, + write_scopes: decisionOtherLeases[index].write_scopes, reason: "independent_worktree_integration_overlap"})); + return {lease: materializeTaskLeaseAcquire(input, command, decision, input.now), + changed: true, overlapAdvisories, releasedSourceLease, switchProof}; } diff --git a/loopx/control_plane/coordination/local_authority.py b/loopx/control_plane/coordination/local_authority.py index 0cb1fbe886..59a053b3bf 100644 --- a/loopx/control_plane/coordination/local_authority.py +++ b/loopx/control_plane/coordination/local_authority.py @@ -163,6 +163,7 @@ def claim_canonical_todo_if_promoted( task_lease_idempotency_key: str | None = None, task_lease_expected_version: int | None = None, manage_execution: bool = False, + allow_settled_execution_switch: bool = False, project: Path | None = None, state_file: Path | None = None, ) -> dict[str, Any]: @@ -191,6 +192,11 @@ def claim_canonical_todo_if_promoted( else f"todo-claim:{goal_id}:{todo_id}:{uuid4().hex}" ), **({"manage_execution": True} if manage_execution else {}), + **( + {"allow_settled_execution_switch": True} + if allow_settled_execution_switch + 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..d7d9878fdf 100644 --- a/loopx/control_plane/coordination/local_authority_runtime.ts +++ b/loopx/control_plane/coordination/local_authority_runtime.ts @@ -1,4 +1,5 @@ import {requirePromotionRegisteredAgents} from "./shadow_registry_source.ts"; +import {verifySettledExecutionSwitch} from "./settled_execution_switch.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'; @@ -1058,6 +1059,12 @@ export async function claimLocalCoordinationTodo( } if (Object.hasOwn(input, "manage_execution") && input.schema_version !== LOCAL_COORDINATION_TODO_MANAGED_CLAIM_REQUEST_SCHEMA) throw new TypeError("Managed execution requires claim request v2"); + if (Object.hasOwn(input, "allow_settled_execution_switch") && + (input.schema_version !== LOCAL_COORDINATION_TODO_MANAGED_CLAIM_REQUEST_SCHEMA || + input.manage_execution !== true || + typeof input.allow_settled_execution_switch !== "boolean")) { + throw new TypeError("Settled execution switch requires a managed claim boolean"); + } const worktree = input.write_worktree; if (worktree !== undefined && (input.schema_version !== LOCAL_COORDINATION_TODO_MANAGED_CLAIM_REQUEST_SCHEMA || input.manage_execution !== true || typeof worktree !== "string" || !isAbsolute(worktree))) { @@ -1111,9 +1118,15 @@ 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}), + ...(input.allow_settled_execution_switch === undefined ? {} : { + allow_settled_execution_switch: input.allow_settled_execution_switch as boolean, + }), dry_run: input.dry_run === true, now: claimObservedAt(input.observed_at), - }, authoritySourcesCurrent, claimWorkspaceObserver(worktree)); + }, authoritySourcesCurrent, claimWorkspaceObserver(worktree), + input.allow_settled_execution_switch === true + ? request => verifySettledExecutionSwitch(root, request) + : undefined); return { ...result, source_authority: sourceAuthority, diff --git a/loopx/control_plane/coordination/settled_execution_switch.ts b/loopx/control_plane/coordination/settled_execution_switch.ts new file mode 100644 index 0000000000..835c0953d8 --- /dev/null +++ b/loopx/control_plane/coordination/settled_execution_switch.ts @@ -0,0 +1,113 @@ +/** Qualify the previous Todo Turn before one explicit managed claim atomically + * releases its overlapping lease and acquires the target execution. */ +import {jsonObject} from "../runtime_decode.ts"; +import { + QUOTA_SETTLEMENT_READBACK_REQUEST_SCHEMA, + readQuotaSettlementFromSnapshot, + readQuotaSettlementSnapshot, +} from "../quota/settlement_readback.ts"; +import {heartbeatReceiptFactFromEvent} from "../quota/heartbeat_receipt_identity.ts"; +import { + ClaimExecutionSwitchRejected, + SETTLED_EXECUTION_SWITCH_PROOF_SCHEMA, + type ClaimExecutionSwitchProof, +} from "./claim_execution.ts"; + +function nonEmpty(value: unknown): string | null { + return typeof value === "string" && value.trim() ? value.trim() : null; +} + +/** The newest Turn ever bound to the source Todo must be the settled Turn. + * This prevents an older successful receipt from releasing work while a newer + * source Turn is still open. Reentries of the same Turn do not change order. */ +function latestBoundSourceTurn( + events: readonly Record[], + goalId: string, + agentId: string, + todoId: string, +): string | null { + const ordered: string[] = []; + const seen = new Set(); + for (const event of events) { + if (event.event_kind !== "quota_should_run" || event.goal_id !== goalId || + event.agent_id !== agentId) continue; + const fact = heartbeatReceiptFactFromEvent(event); + const turn = nonEmpty(fact.run_id); + if (fact.todo_id !== todoId || turn === null || seen.has(turn)) continue; + seen.add(turn); + ordered.push(turn); + } + return ordered.at(-1) ?? null; +} + +export async function verifySettledExecutionSwitch( + runtimeRoot: string, + input: { + readonly goal_id: string; + readonly source_todo_id: string; + readonly target_todo_id: string; + readonly agent_id: string; + readonly source_lease_idempotency_key: string; + readonly source_lease_version: number; + readonly source_lease_epoch: number; + }, +): Promise { + if (input.source_todo_id === input.target_todo_id) { + throw new ClaimExecutionSwitchRejected( + "settled_execution_switch_same_todo", + "Settled execution switch requires distinct source and target Todos", + ); + } + const snapshot = await readQuotaSettlementSnapshot(runtimeRoot, input.goal_id); + const sourceTurn = latestBoundSourceTurn( + snapshot.events, + input.goal_id, + input.agent_id, + input.source_todo_id, + ); + if (sourceTurn === null) { + throw new ClaimExecutionSwitchRejected( + "settled_execution_switch_source_turn_missing", + "Settled execution switch requires a durable source Todo Turn binding", + ); + } + const readback = readQuotaSettlementFromSnapshot({ + schema_version: QUOTA_SETTLEMENT_READBACK_REQUEST_SCHEMA, + runtime_root: runtimeRoot, + goal_id: input.goal_id, + agent_id: input.agent_id, + todo_id: input.source_todo_id, + turn_instance_id: sourceTurn, + replan_obligation_id: null, + infer_turn_instance_id: false, + allow_unbound_binding: false, + }, snapshot); + const identityBundle = jsonObject(readback.identity); + const identityResult = jsonObject(identityBundle?.result); + const identity = jsonObject(identityResult?.value); + const progress = jsonObject(readback.progress); + const settlementOk = jsonObject(jsonObject(readback.settlement)?.payload)?.ok === true; + if (readback.found !== true || !identity || !settlementOk || + progress?.schema_version !== "quota_settlement_progress_v0" || + progress.state !== "settled" || identity.goal_id !== input.goal_id || + identity.agent_id !== input.agent_id || + identity.todo_id !== input.source_todo_id || + identity.turn_instance_id !== sourceTurn || + identity.replan_obligation_id != null) { + throw new ClaimExecutionSwitchRejected( + "settled_execution_switch_unsettled_source", + "Settled execution switch requires the latest source Todo Turn's complete writeback and quota receipts", + ); + } + return { + schema_version: SETTLED_EXECUTION_SWITCH_PROOF_SCHEMA, + goal_id: input.goal_id, + source_todo_id: input.source_todo_id, + target_todo_id: input.target_todo_id, + agent_id: input.agent_id, + source_lease_idempotency_key: input.source_lease_idempotency_key, + source_lease_version: input.source_lease_version, + source_lease_epoch: input.source_lease_epoch, + settlement_identity: identity, + }; +} diff --git a/loopx/control_plane/coordination/todo_claim.ts b/loopx/control_plane/coordination/todo_claim.ts index 8a35b7c1d7..e30e3bdbfa 100644 --- a/loopx/control_plane/coordination/todo_claim.ts +++ b/loopx/control_plane/coordination/todo_claim.ts @@ -1,4 +1,5 @@ -import {prepareClaimExecution, type ClaimWorkspaceObserver} from "./claim_execution.ts"; +import {ClaimExecutionSwitchRejected, prepareClaimExecution, type ClaimExecutionSwitchProof, + type ClaimExecutionSwitchVerifier, type ClaimWorkspaceObserver} from "./claim_execution.ts"; import {retiredHandoffModeRejection, HANDOFF_MODE_RETIRED_REASON, EXECUTION_HANDOFF_MODES, type ExecutionHandoffMode} from "./handoff_mode_policy.ts"; import {AUTHORITY_SOURCE_CHANGED, uncheckedAuthoritySource, type AuthoritySourceCheck} from "./authority_source.ts"; @@ -66,6 +67,8 @@ export interface CoordinationTodoClaimInput { readonly replan_obligation_id?: string; readonly lease_request?: CoordinationTodoClaimLeaseRequest | null; readonly manage_execution?: boolean; + /** Explicit caller intent; the verifier still requires a settled source Turn. */ + readonly allow_settled_execution_switch?: boolean; /** Admission constraint on every attempt and replay, not a new business intent. */ readonly required_handoff_mode?: ExecutionHandoffMode; readonly dry_run: boolean; @@ -346,13 +349,15 @@ export async function executeCoordinationTodoClaim( rawInput: CoordinationTodoClaimInput, authoritySourcesCurrent: AuthoritySourceCheck = uncheckedAuthoritySource, observeWorkspace?: ClaimWorkspaceObserver, + verifySettledSwitch?: ClaimExecutionSwitchVerifier, ): Promise { // Retry only a conclusive provider CAS rejection. Each attempt rereads the // original receipt and the complete head, then rechecks source authorization, // claim ownership, acceptance and lease/write-scope exclusion. Pinned revisions // (including handoff grants) must return to their caller for a fresh observation. for (let attempt = 0; ; attempt++) { - const result = await executeClaimAttempt(store, rawInput, authoritySourcesCurrent, observeWorkspace); + const result = await executeClaimAttempt(store, rawInput, authoritySourcesCurrent, + observeWorkspace, verifySettledSwitch); if (attempt >= 2 || rawInput.expected_provider_revision !== undefined || rawInput.transfer_grant !== undefined || result.status !== "conflict" || result.conflict_kind !== "provider_revision_mismatch") return result; @@ -364,6 +369,7 @@ async function executeClaimAttempt( rawInput: CoordinationTodoClaimInput, authoritySourcesCurrent: AuthoritySourceCheck, observeWorkspace?: ClaimWorkspaceObserver, + verifySettledSwitch?: ClaimExecutionSwitchVerifier, ): Promise { let input: CoordinationTodoClaimInput; try { @@ -379,12 +385,18 @@ async function executeClaimAttempt( lease_request: normalizeLeaseRequest(rawInput.lease_request), }; if (input.manage_execution !== undefined) requireAuthorityBoolean(input.manage_execution, "manage_execution"); + if (input.allow_settled_execution_switch !== undefined) { + requireAuthorityBoolean(input.allow_settled_execution_switch, "allow_settled_execution_switch"); + } if (input.required_handoff_mode !== undefined && !EXECUTION_HANDOFF_MODES.includes(input.required_handoff_mode)) { throw new AuthorityStoreProtocolError("required_handoff_mode must be a current execution mode"); } if (input.manage_execution && (input.lease_request != null || input.actor_agent_id !== input.claimed_by)) { throw new AuthorityStoreProtocolError("Managed execution requires the claiming actor and no explicit lease request"); } + if (input.allow_settled_execution_switch && !input.manage_execution) { + throw new AuthorityStoreProtocolError("Settled execution switch requires managed execution"); + } requireAuthorityBoolean(input.dry_run, "dry_run"); requireAuthorityDate(input.now, "now"); } catch (error) { @@ -414,6 +426,7 @@ async function executeClaimAttempt( dry_run: input.dry_run, ...(leaseRequest === null ? {} : {lease_request: leaseRequest}), ...(input.manage_execution ? {manage_execution: true} : {}), + ...(input.allow_settled_execution_switch ? {allow_settled_execution_switch: true} : {}), ...(input.replan_obligation_id === undefined ? {} : {replan_obligation_id: input.replan_obligation_id}), }; const requestSha = canonicalAuthoritySha256(requestIdentity); @@ -477,6 +490,35 @@ async function executeClaimAttempt( return result; }; const recoverProof = async (result: CoordinationTodoClaimResult): Promise => { + if (input.manage_execution && !input.allow_settled_execution_switch && + result.reason_code === "coordination_operation_identity_mismatch") { + const original = await store.readReceipt(input.operation_id); + const upgradedIntent = {...requestIdentity, allow_settled_execution_switch: true}; + if (original.status === "found" && original.receipts.length === 1 && + original.receipts[0]?.schema_version === COORDINATION_TODO_CLAIM_RECEIPT_SCHEMA && + original.receipts[0]?.goal_id === input.goal_id && + original.receipts[0]?.request_sha256 === canonicalAuthoritySha256(upgradedIntent)) { + // The switch bit only admits a new conflicting claim. Replaying the + // already committed operation can safely recover through either client. + return executeClaimAttempt(store, + {...input, allow_settled_execution_switch: true}, + authoritySourcesCurrent, observeWorkspace, verifySettledSwitch); + } + } + if (input.allow_settled_execution_switch && + result.reason_code === "coordination_operation_identity_mismatch") { + const original = await store.readReceipt(input.operation_id); + const legacyIntent = {...requestIdentity}; + delete legacyIntent.allow_settled_execution_switch; + if (original.status === "found" && original.receipts.length === 1 && + original.receipts[0]?.schema_version === COORDINATION_TODO_CLAIM_RECEIPT_SCHEMA && + original.receipts[0]?.goal_id === input.goal_id && + original.receipts[0]?.request_sha256 === canonicalAuthoritySha256(legacyIntent)) { + return executeClaimAttempt(store, + {...input, allow_settled_execution_switch: false}, + authoritySourcesCurrent, observeWorkspace, verifySettledSwitch); + } + } if (input.manage_execution && result.reason_code === "coordination_operation_identity_mismatch") { const original = await store.readReceipt(input.operation_id); const legacyIntent = {...requestIdentity}; @@ -487,7 +529,8 @@ async function executeClaimAttempt( original.receipts[0]?.request_sha256 === canonicalAuthoritySha256(legacyIntent)) { // Preserve pre-upgrade assignment recovery. It remains historical, not // a new managed execution; fresh work needs a new ordinary claim. - return executeClaimAttempt(store, {...input, manage_execution: false}, authoritySourcesCurrent); + return executeClaimAttempt(store, {...input, manage_execution: false, + allow_settled_execution_switch: false}, authoritySourcesCurrent); } } return currentProof(result); @@ -593,14 +636,19 @@ async function executeClaimAttempt( let leaseChanged = false; let leaseIdempotent = false; let overlapAdvisories: JsonObject[] = []; + let releasedSourceLease: JsonObject | null = null; + let executionSwitchProof: ClaimExecutionSwitchProof | null = null; try { const currentLease = projection.leases.get(input.todo_id); if (handoffMode === "hard_lease" && input.manage_execution === true) { - const prepared = await prepareClaimExecution(head.head, input, observeWorkspace); + const prepared = await prepareClaimExecution(head.head, input, observeWorkspace, + verifySettledSwitch); lease = prepared.lease; leaseChanged = prepared.changed; leaseIdempotent = !leaseChanged; overlapAdvisories = prepared.overlapAdvisories ?? []; + releasedSourceLease = prepared.releasedSourceLease ?? null; + executionSwitchProof = prepared.switchProof ?? null; } else if (handoffMode === "hard_lease" && leaseRequest !== null) { // Validate required scopes before planning; a caller cannot omit a required conflict. const writeScopes = coordinationTodoWriteScopes(todo); @@ -666,6 +714,10 @@ async function executeClaimAttempt( ); } } catch (error) { + if (error instanceof ClaimExecutionSwitchRejected) { + return failure(error.reasonCode, error.message, {todo_id: input.todo_id}, + "decision_rejection"); + } return failure( "invalid_coordination_task_lease", error instanceof Error ? error.message : "invalid canonical task lease", @@ -704,6 +756,19 @@ async function executeClaimAttempt( ...(changed ? {updated_at: updatedAt} : {}), mutation_authority: mutationAuthority, ...(overlapAdvisories.length ? {integration_overlap_advisories: overlapAdvisories} : {}), + ...(executionSwitchProof === null || releasedSourceLease === null ? {} : { + execution_switch: { + ...executionSwitchProof, + source_lease: { + todo_id: releasedSourceLease.todo_id, + owner: releasedSourceLease.owner, + idempotency_key: releasedSourceLease.idempotency_key, + version: releasedSourceLease.version, + lease_epoch: releasedSourceLease.lease_epoch, + status: releasedSourceLease.status, + }, + }, + }), ...(input.manage_execution ? {execution_managed: true, claim_operation_id: input.operation_id} : {}), ...(leaseRequest === null && !(input.manage_execution && handoffMode === "hard_lease") ? {} : { todo_changed: todoChanged, @@ -728,6 +793,9 @@ async function executeClaimAttempt( // A successful no-op still consumes its operation identity. Commit only its // receipt under the observed head's CAS; never fabricate a Todo mutation. const mutations: CoordinationProjectionMutation[] = [ + ...(releasedSourceLease !== null + ? [{kind: "lease_upsert" as const, lease: releasedSourceLease}] + : []), ...(leaseChanged && lease !== null ? [{kind: "lease_upsert" as const, lease}] : []), diff --git a/loopx/control_plane/todos/mutation_api.py b/loopx/control_plane/todos/mutation_api.py index dde21871f9..b5e04b26f2 100644 --- a/loopx/control_plane/todos/mutation_api.py +++ b/loopx/control_plane/todos/mutation_api.py @@ -301,6 +301,7 @@ def update_goal_todo( claim_only: bool = False, claim_operation_id: str | None = None, manage_execution: bool = False, + allow_settled_execution_switch: bool = False, update_operation_id: str | None = None, update_expected_provider_revision: str | None = None, update_expected_registry_sha256: str | None = None, @@ -375,6 +376,7 @@ def update_goal_todo( dry_run=dry_run, operation_id=claim_operation_id, manage_execution=manage_execution, + allow_settled_execution_switch=allow_settled_execution_switch, task_lease_idempotency_key=task_lease_idempotency_key, task_lease_expected_version=task_lease_expected_version, project=project, diff --git a/tests/control_plane_ts/local_settled_execution_switch.test.ts b/tests/control_plane_ts/local_settled_execution_switch.test.ts new file mode 100644 index 0000000000..481a4d5a12 --- /dev/null +++ b/tests/control_plane_ts/local_settled_execution_switch.test.ts @@ -0,0 +1,77 @@ +import assert from "node:assert/strict"; +import {createHash} from "node:crypto"; +import {mkdir, mkdtemp, rm, writeFile} from "node:fs/promises"; +import {tmpdir} from "node:os"; +import {join} from "node:path"; +import test from "node:test"; + +import {settlementIdentity, type JsonObject} from "../../loopx/control_plane/effect_program.ts"; +import {FileAuthorityStore} from "../../loopx/control_plane/coordination/file_authority_store.ts"; +import { + claimLocalCoordinationTodo, + LOCAL_COORDINATION_TODO_MANAGED_CLAIM_REQUEST_SCHEMA, +} from "../../loopx/control_plane/coordination/local_authority_runtime.ts"; +import {authorityProjectionFixture} from "./authority_projection_fixture.ts"; +import {engageCanonicalRoute} from "./local_promotion_fixture.ts"; + +test("local managed claim verifies settlement and atomically switches overlapping execution", async () => { + const root = await mkdtemp(join(tmpdir(), "loopx-local-settled-switch-")); + try { + await engageCanonicalRoute(root); + const registryPath = join(root, "registry.json"); + await writeFile(registryPath, "{}"); + const store = new FileAuthorityStore(join(root, "authority", "file-v0"), "goal-a"); + const repository = "git:github.com/example/project"; + const todos = ["todo_source", "todo_target"].map(todo_id => ({todo_id, + role: "agent", status: "open", done: false, archive_state: "active", + text: `Execute ${todo_id}`, task_class: "advancement_task", task_domain: "code", + task_repository: repository, required_write_scopes: ["src/**"]})); + assert.equal((await store.commitAuthority({operation_id: "seed-switch", + expected_provider_revision: null, + next_projection: authorityProjectionFixture("goal-a", todos, [], "native", + {handoff_mode: "hard_lease"}), events: [], receipts: []})).status, "applied"); + const base = {schema_version: LOCAL_COORDINATION_TODO_MANAGED_CLAIM_REQUEST_SCHEMA, + runtime_root: root, goal_id: "goal-a", role: "agent", claimed_by: "agent-a", + actor_agent_id: "agent-a", registered_agents: ["agent-a"], manage_execution: true, + registry_source: {path: registryPath, + sha256: createHash("sha256").update("{}").digest("hex")}, + lease_request: null, observed_at: "2026-09-13T10:00:00Z", dry_run: false}; + const sourceClaim = await claimLocalCoordinationTodo({...base, + todo_id: "todo_source", operation_id: "claim-source"}); + assert.equal(sourceClaim.status, "applied", JSON.stringify(sourceClaim)); + + const turn = "turn-source-settled"; + const identity = settlementIdentity({goal_id: "goal-a", agent_id: "agent-a", + todo_id: "todo_source", turn_instance_id: turn}); + const goalRoot = join(root, "goals", "goal-a"), runsRoot = join(goalRoot, "runs"); + await mkdir(runsRoot, {recursive: true}); + const event = (kind: string, id: string) => ({schema_version: "loopx_rollout_event_v0", + event_id: id, event_kind: kind, goal_id: "goal-a", agent_id: "agent-a", + run_id: turn, details: {todo_id: "todo_source", settlement_effect_id: identity.effect_id}}); + await writeFile(join(goalRoot, "rollout-event-log.jsonl"), + [event("quota_should_run", "guard"), event("refresh_state", "writeback"), + event("quota_spend", "spend")].map(value => JSON.stringify(value)).join("\n") + "\n"); + const checkpoint = {schema_version: "vision_checkpoint_v0", agent_id: "agent-a", + satisfied: true, delivery_boundary: "in_flight_continuation", decision: "unchanged", + triggers: [{kind: "in_flight_continuation", todo_id: "todo_source"}]}; + await writeFile(join(runsRoot, "index.jsonl"), [ + {classification: "state_refreshed", delivery_outcome: "outcome_progress", + goal_id: "goal-a", agent_id: "agent-a", todo_id: "todo_source", + turn_instance_id: turn, settlement_identity: identity, vision_checkpoint: checkpoint}, + {classification: "quota_slot_spent", goal_id: "goal-a", agent_id: "agent-a", + todo_id: "todo_source", turn_instance_id: turn, settlement_identity: identity}, + ].map(value => JSON.stringify(value)).join("\n") + "\n"); + + const switched = await claimLocalCoordinationTodo({...base, + todo_id: "todo_target", operation_id: "claim-target", + allow_settled_execution_switch: true}); + assert.equal(switched.status, "applied", JSON.stringify(switched)); + assert.equal((switched.execution_switch as JsonObject).source_todo_id, "todo_source"); + const head = await store.loadAuthority(); + assert.equal(head.status, "loaded"); + if (head.status !== "loaded") return; + const leases = head.head.leases as JsonObject[]; + assert.equal(leases.find(row => row.todo_id === "todo_source")?.status, "released"); + assert.equal(leases.find(row => row.todo_id === "todo_target")?.status, "active"); + } finally {await rm(root, {recursive: true, force: true});} +}); diff --git a/tests/control_plane_ts/managed_claim_execution_conformance.ts b/tests/control_plane_ts/managed_claim_execution_conformance.ts index a73afda9d9..97e365c058 100644 --- a/tests/control_plane_ts/managed_claim_execution_conformance.ts +++ b/tests/control_plane_ts/managed_claim_execution_conformance.ts @@ -10,6 +10,8 @@ import {executeCanonicalTaskLeaseLifecycle as maintain} from "../../loopx/contro import {prepareCoordinationProjectionCommit} from "../../loopx/control_plane/coordination/coordination_projection.ts"; import {todoUpdateLeaseRecovery} from "../../loopx/control_plane/coordination/task_lease_proof.ts"; import {authorityProjectionFixture} from "./authority_projection_fixture.ts"; +import {SETTLED_EXECUTION_SWITCH_PROOF_SCHEMA, + type ClaimExecutionSwitchVerifier} from "../../loopx/control_plane/coordination/claim_execution.ts"; async function loaded(store: AuthorityStore) { const value = await store.loadAuthority(); @@ -17,6 +19,20 @@ async function loaded(store: AuthorityStore) { return value; } export function registerManagedClaimExecutionConformance(provider: string, factory: AuthorityStoreConformanceFactory) { + const settledSwitch: ClaimExecutionSwitchVerifier = async input => ({ + schema_version: SETTLED_EXECUTION_SWITCH_PROOF_SCHEMA, + ...input, + settlement_identity: { + schema_version: "quota_settlement_identity_v0", + goal_id: input.goal_id, + agent_id: input.agent_id, + todo_id: input.source_todo_id, + turn_instance_id: "settled-source-turn", + binding_kind: "todo", + binding_id: input.source_todo_id, + effect_id: `settled:${input.source_todo_id}`, + }, + }); async function setup(t: test.TestContext, mode = "hard_lease") { const {store} = await factory(t); const projection = authorityProjectionFixture("goal-a", [{todo_id: "todo_managed", role: "agent", @@ -46,6 +62,205 @@ export function registerManagedClaimExecutionConformance(provider: string, facto clear_claim: false, validation_declaration: null, validation_receipt: null, completion_policy_request: null, dry_run: false, now: request.now}; } + test(`${provider} managed execution: explicit settled switch releases source and acquires target atomically`, async t => { + const {store} = await factory(t); + const repository = "git:github.com/example/project"; + const todos = ["todo_source", "todo_target"].map(todo_id => ({ + todo_id, role: "agent", status: "open", done: false, + archive_state: "active", text: `Execute ${todo_id}`, + task_class: "advancement_task", task_domain: "code", task_repository: repository, + required_write_scopes: ["src/**"], + })); + assert.equal((await store.commitAuthority({operation_id: "seed-switch", expected_provider_revision: null, + next_projection: authorityProjectionFixture("goal-a", todos, [], "native", {handoff_mode: "hard_lease"}), + events: [], receipts: []})).status, "applied"); + const base = {goal_id: "goal-a", claimed_by: "agent-a", actor_agent_id: "agent-a", + expected_role: "agent", registered_agents: ["agent-a", "agent-b"], manage_execution: true, + dry_run: false, now: new Date("2026-09-13T10:00:00Z")}; + const source = await claim(store, {...base, todo_id: "todo_source", operation_id: "claim-source"}); + assert.equal(source.status, "applied", JSON.stringify(source)); + const beforeSwitch = await loaded(store); + + const implicit = await claim(store, {...base, todo_id: "todo_target", operation_id: "implicit-target"}, + undefined, undefined, settledSwitch); + assert.equal(implicit.status, "failed"); + assert.deepEqual(await loaded(store), beforeSwitch, + "ordinary scheduler-style selection cannot release the current execution"); + + const request = {...base, todo_id: "todo_target", operation_id: "explicit-target", + allow_settled_execution_switch: true}; + const switched = await claim(store, request, undefined, undefined, settledSwitch); + assert.equal(switched.status, "applied", JSON.stringify(switched)); + const switchReceipt = switched.execution_switch as JsonObject; + assert.equal(switchReceipt.source_todo_id, "todo_source"); + assert.equal((switchReceipt.source_lease as JsonObject).status, "released"); + const after = await loaded(store); + const leases = after.head.leases as JsonObject[]; + assert.equal(leases.find(row => row.todo_id === "todo_source")?.status, "released"); + assert.equal(leases.find(row => row.todo_id === "todo_target")?.status, "active"); + assert.equal(leases.find(row => row.todo_id === "todo_target")?.owner, "agent-a"); + assert.equal((after.head.todos as JsonObject[]).find(row => row.todo_id === "todo_target")?.claimed_by, "agent-a"); + assert.equal((await claim(store, request, undefined, undefined, async () => { + throw new Error("replay must use the original atomic receipt"); + })).status, "replayed"); + assert.deepEqual(await loaded(store), after); + }); + + test(`${provider} managed execution: settled switch recovers a lost acknowledgement without split leases`, async t => { + const {store} = await factory(t); + const repository = "git:github.com/example/project"; + const todos = ["todo_source", "todo_target"].map(todo_id => ({ + todo_id, role: "agent", status: "open", done: false, + archive_state: "active", text: `Execute ${todo_id}`, + task_class: "advancement_task", task_domain: "code", task_repository: repository, + required_write_scopes: ["src/**"], + })); + assert.equal((await store.commitAuthority({operation_id: "seed-lost-switch", + expected_provider_revision: null, + next_projection: authorityProjectionFixture("goal-a", todos, [], "native", {handoff_mode: "hard_lease"}), + events: [], receipts: []})).status, "applied"); + const base = {goal_id: "goal-a", claimed_by: "agent-a", actor_agent_id: "agent-a", + expected_role: "agent", registered_agents: ["agent-a", "agent-b"], manage_execution: true, + dry_run: false, now: new Date("2026-09-13T10:00:00Z")}; + assert.equal((await claim(store, {...base, todo_id: "todo_source", + operation_id: "claim-source-lost-switch"})).status, "applied"); + let commits = 0; + const responseLost = new Proxy(store, {get(target, key) { + if (key === "commitAuthority") return async (...args: Parameters) => { + commits++; + const committed = await target.commitAuthority(...args); + assert.equal(committed.status, "applied", JSON.stringify(committed)); + return {status: "ambiguous" as const, reason_code: "synthetic_response_loss", + reason: "switch commit response lost"}; + }; + const value = Reflect.get(target, key, target); + return typeof value === "function" ? value.bind(target) : value; + }}); + const request = {...base, todo_id: "todo_target", operation_id: "switch-lost-response", + allow_settled_execution_switch: true}; + const recovered = await claim(responseLost, request, undefined, undefined, settledSwitch); + assert.equal(recovered.status, "recovered", JSON.stringify(recovered)); + assert.equal(commits, 1, "an ambiguous response must not submit the switch twice"); + const after = await loaded(store); + const leases = after.head.leases as JsonObject[]; + assert.equal(leases.find(row => row.todo_id === "todo_source")?.status, "released"); + assert.equal(leases.find(row => row.todo_id === "todo_target")?.status, "active"); + assert.equal((await claim(store, request, undefined, undefined, async () => { + throw new Error("durable receipt must recover before settlement is reread"); + })).status, "replayed"); + assert.deepEqual(await loaded(store), after); + }); + + test(`${provider} managed execution: concurrent settled switches have one winner and no split lease`, async t => { + const {store, contender} = await factory(t); + const repository = "git:github.com/example/project"; + const todos = ["todo_source", "todo_target_a", "todo_target_b"].map(todo_id => ({ + todo_id, role: "agent", status: "open", done: false, + archive_state: "active", text: `Execute ${todo_id}`, + task_class: "advancement_task", task_domain: "code", task_repository: repository, + required_write_scopes: ["src/**"], + })); + assert.equal((await store.commitAuthority({operation_id: "seed-racing-switch", + expected_provider_revision: null, + next_projection: authorityProjectionFixture("goal-a", todos, [], "native", {handoff_mode: "hard_lease"}), + events: [], receipts: []})).status, "applied"); + const base = {goal_id: "goal-a", claimed_by: "agent-a", actor_agent_id: "agent-a", + expected_role: "agent", registered_agents: ["agent-a", "agent-b"], manage_execution: true, + allow_settled_execution_switch: true, dry_run: false, + now: new Date("2026-09-13T10:00:00Z")}; + assert.equal((await claim(store, {...base, allow_settled_execution_switch: false, + todo_id: "todo_source", operation_id: "claim-racing-source"})).status, "applied"); + const originalOnly: ClaimExecutionSwitchVerifier = async input => { + if (input.source_todo_id !== "todo_source") { + throw new Error("a newly acquired target has no settled Turn"); + } + return settledSwitch(input); + }; + const results = await Promise.all([ + claim(store, {...base, todo_id: "todo_target_a", operation_id: "switch-target-a"}, + undefined, undefined, originalOnly), + claim(contender, {...base, todo_id: "todo_target_b", operation_id: "switch-target-b"}, + undefined, undefined, originalOnly), + ]); + assert.equal(results.filter(result => result.status === "applied").length, 1, + JSON.stringify(results)); + assert.equal(results.filter(result => result.status === "failed").length, 1, + JSON.stringify(results)); + const after = await loaded(store); + const leases = after.head.leases as JsonObject[]; + assert.equal(leases.find(row => row.todo_id === "todo_source")?.status, "released"); + const activeTargets = leases.filter(row => row.todo_id !== "todo_source" && row.status === "active"); + assert.equal(activeTargets.length, 1, JSON.stringify(leases)); + assert.deepEqual(await loaded(contender), after); + }); + + test(`${provider} managed execution: multiple conflicting sources reject without releasing either`, async t => { + const {store} = await factory(t); + const repository = "git:github.com/example/project"; + const todos = [ + {todo_id: "todo_source", required_write_scopes: ["src/a/**"]}, + {todo_id: "todo_blocker", required_write_scopes: ["src/b/**"]}, + {todo_id: "todo_target", required_write_scopes: ["src/**"]}, + ].map(row => ({...row, role: "agent", status: "open", done: false, + archive_state: "active", text: `Execute ${row.todo_id}`, + task_class: "advancement_task", task_domain: "code", task_repository: repository})); + assert.equal((await store.commitAuthority({operation_id: "seed-ambiguous-switch", + expected_provider_revision: null, + next_projection: authorityProjectionFixture("goal-a", todos, [], "native", {handoff_mode: "hard_lease"}), + events: [], receipts: []})).status, "applied"); + const common = {goal_id: "goal-a", expected_role: "agent", + registered_agents: ["agent-a", "agent-b"], manage_execution: true, + dry_run: false, now: new Date("2026-09-13T10:00:00Z")}; + assert.equal((await claim(store, {...common, todo_id: "todo_source", operation_id: "claim-source-ambiguous", + claimed_by: "agent-a", actor_agent_id: "agent-a"})).status, "applied"); + assert.equal((await claim(store, {...common, todo_id: "todo_blocker", operation_id: "claim-blocker-ambiguous", + claimed_by: "agent-b", actor_agent_id: "agent-b"})).status, "applied"); + const before = await loaded(store); + const rejected = await claim(store, {...common, todo_id: "todo_target", operation_id: "switch-ambiguous", + claimed_by: "agent-a", actor_agent_id: "agent-a", allow_settled_execution_switch: true}, + undefined, undefined, settledSwitch); + assert.equal(rejected.status, "failed", JSON.stringify(rejected)); + assert.equal(rejected.reason_code, "settled_execution_switch_ambiguous_source"); + assert.deepEqual(await loaded(store), before); + }); + + test(`${provider} managed execution: settled switch rejects missing, stale and foreign proof without release`, async t => { + for (const scenario of ["unsettled", "stale", "foreign"] as const) { + const {store} = await factory(t); + const sourceRepository = "git:github.com/example/project"; + const targetRepository = sourceRepository; + const todos = [ + {todo_id: "todo_source", task_repository: sourceRepository}, + {todo_id: "todo_target", task_repository: targetRepository}, + ].map(row => ({...row, role: "agent", status: "open", done: false, + archive_state: "active", text: `Execute ${row.todo_id}`, + task_class: "advancement_task", task_domain: "code", + required_write_scopes: ["src/**"]})); + assert.equal((await store.commitAuthority({operation_id: `seed-${scenario}`, expected_provider_revision: null, + next_projection: authorityProjectionFixture("goal-a", todos, [], "native", {handoff_mode: "hard_lease"}), + events: [], receipts: []})).status, "applied"); + const base = {goal_id: "goal-a", claimed_by: "agent-a", actor_agent_id: "agent-a", + expected_role: "agent", registered_agents: ["agent-a", "agent-b"], manage_execution: true, + dry_run: false, now: new Date("2026-09-13T10:00:00Z")}; + assert.equal((await claim(store, {...base, todo_id: "todo_source", + operation_id: `source-${scenario}`})).status, "applied"); + const before = await loaded(store); + const verifier: ClaimExecutionSwitchVerifier = scenario === "unsettled" + ? async () => {throw new Error("source Turn settlement is incomplete");} + : async input => { + const proof = await settledSwitch(input); + if (scenario === "stale") return {...proof, + source_lease_version: proof.source_lease_version + 1}; + if (scenario === "foreign") return {...proof, agent_id: "agent-b"}; + return proof; + }; + const result = await claim(store, {...base, todo_id: "todo_target", + operation_id: `target-${scenario}`, allow_settled_execution_switch: true}, + undefined, undefined, verifier); + assert.equal(result.status, "failed", `${scenario}: ${JSON.stringify(result)}`); + assert.deepEqual(await loaded(store), before, scenario); + } + }); test(`${provider} managed execution: worktree observation uses canonical code scopes only for new execution`, async t => { const {store, request} = await setup(t); const before = await loaded(store); diff --git a/tests/control_plane_ts/settled_execution_switch.test.ts b/tests/control_plane_ts/settled_execution_switch.test.ts new file mode 100644 index 0000000000..9d93e2b2b6 --- /dev/null +++ b/tests/control_plane_ts/settled_execution_switch.test.ts @@ -0,0 +1,90 @@ +import assert from "node:assert/strict"; +import {appendFile, mkdir, mkdtemp, rm, writeFile} from "node:fs/promises"; +import {tmpdir} from "node:os"; +import {join} from "node:path"; +import test from "node:test"; + +import {settlementIdentity} from "../../loopx/control_plane/effect_program.ts"; +import {verifySettledExecutionSwitch} from "../../loopx/control_plane/coordination/settled_execution_switch.ts"; + +const goal = "switch-goal"; +const agent = "agent-a"; +const source = "todo_source"; +const target = "todo_target"; +const turn = "turn-source-settled"; + +async function fixture(spent = true): Promise { + const root = await mkdtemp(join(tmpdir(), "loopx-settled-switch-")); + const goalRoot = join(root, "goals", goal); + const runsRoot = join(goalRoot, "runs"); + await mkdir(runsRoot, {recursive: true}); + const identity = settlementIdentity({goal_id: goal, agent_id: agent, + todo_id: source, turn_instance_id: turn}); + const event = (kind: string, id: string) => ({ + schema_version: "loopx_rollout_event_v0", + event_id: id, + event_kind: kind, + goal_id: goal, + agent_id: agent, + run_id: turn, + details: {todo_id: source, settlement_effect_id: identity.effect_id}, + }); + const events = [event("quota_should_run", "guard"), event("refresh_state", "writeback"), + ...(spent ? [event("quota_spend", "spend")] : [])]; + const runs = [{classification: "state_refreshed", delivery_outcome: "outcome_progress", + goal_id: goal, agent_id: agent, todo_id: source, turn_instance_id: turn, + settlement_identity: identity, vision_checkpoint: { + schema_version: "vision_checkpoint_v0", agent_id: agent, satisfied: true, + delivery_boundary: "in_flight_continuation", decision: "unchanged", + triggers: [{kind: "in_flight_continuation", todo_id: source}], + }}, ...(spent ? [{classification: "quota_slot_spent", goal_id: goal, + agent_id: agent, todo_id: source, turn_instance_id: turn, + settlement_identity: identity}] : [])]; + await writeFile(join(goalRoot, "rollout-event-log.jsonl"), + `${events.map(value => JSON.stringify(value)).join("\n")}\n`); + await writeFile(join(runsRoot, "index.jsonl"), + `${runs.map(value => JSON.stringify(value)).join("\n")}\n`); + return root; +} + +function request() { + return {goal_id: goal, source_todo_id: source, target_todo_id: target, + agent_id: agent, source_lease_idempotency_key: "source-key", + source_lease_version: 3, source_lease_epoch: 5}; +} + +test("settled execution switch returns an exact source lease and Turn proof", async () => { + const root = await fixture(); + try { + const proof = await verifySettledExecutionSwitch(root, request()); + assert.equal(proof.source_lease_idempotency_key, "source-key"); + assert.equal(proof.source_lease_version, 3); + assert.equal(proof.source_lease_epoch, 5); + assert.equal(proof.settlement_identity.turn_instance_id, turn); + assert.equal(proof.settlement_identity.todo_id, source); + } finally {await rm(root, {recursive: true, force: true});} +}); + +test("settled execution switch rejects an incomplete or superseded source Turn", async t => { + await t.test("missing spend", async () => { + const root = await fixture(false); + try { + await assert.rejects(verifySettledExecutionSwitch(root, request()), + /complete writeback and quota receipts/); + } finally {await rm(root, {recursive: true, force: true});} + }); + await t.test("newer source Turn", async () => { + const root = await fixture(); + try { + const identity = settlementIdentity({goal_id: goal, agent_id: agent, + todo_id: source, turn_instance_id: "turn-source-newer"}); + await appendFile(join(root, "goals", goal, "rollout-event-log.jsonl"), + `${JSON.stringify({schema_version: "loopx_rollout_event_v0", event_id: "newer-guard", + event_kind: "quota_should_run", goal_id: goal, agent_id: agent, + run_id: "turn-source-newer", details: {todo_id: source, + settlement_effect_id: identity.effect_id}})}\n`); + await assert.rejects(verifySettledExecutionSwitch(root, request()), + /latest source Todo Turn's complete writeback and quota receipts/); + } finally {await rm(root, {recursive: true, force: true});} + }); +}); diff --git a/tests/test_cli_argument_diagnostics.py b/tests/test_cli_argument_diagnostics.py index 9c886f6909..192481bab1 100644 --- a/tests/test_cli_argument_diagnostics.py +++ b/tests/test_cli_argument_diagnostics.py @@ -58,6 +58,40 @@ def fake_list_goal_todos(**kwargs: object) -> dict[str, object]: assert captured_list["state_file"] == tmp_path / "ACTIVE_GOAL_STATE.md" +@pytest.mark.parametrize( + ("lease_args", "managed"), + [([], True), (["--task-lease-idempotency-key", "explicit-key"], False)], +) +def test_todo_claim_enables_settled_switch_only_for_explicit_managed_claims( + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, + lease_args: list[str], + managed: bool, +) -> None: + captured: dict[str, object] = {} + + def fake_update_goal_todo(**kwargs: object) -> dict[str, object]: + captured.update(kwargs) + return {"ok": True, "dry_run": True} + + monkeypatch.setattr(todo_command, "update_goal_todo", fake_update_goal_todo) + args = build_parser().parse_args([ + "todo", "claim", "--goal-id", "example-goal", "--todo-id", "todo_example", + "--agent-id", "agent-a", "--claimed-by", "agent-a", "--dry-run", *lease_args, + ]) + result = todo_command.handle_todo_command( + args, + registry_path=tmp_path / "registry.json", + runtime_root_arg=None, + print_payload=lambda *_args: None, + append_cli_rollout_event=lambda *_args, **_kwargs: {}, + ) + + assert result == 0 + assert captured["manage_execution"] is managed + assert captured["allow_settled_execution_switch"] is managed + + def test_todo_requires_explicit_command_without_mutating_state( monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str],