diff --git a/loopx/control_plane/coordination/authority_store_codec.ts b/loopx/control_plane/coordination/authority_store_codec.ts index 8c5ac6fd1f..1e29cf7d71 100644 --- a/loopx/control_plane/coordination/authority_store_codec.ts +++ b/loopx/control_plane/coordination/authority_store_codec.ts @@ -42,6 +42,63 @@ export function requireAuthorityStoreId(value: unknown, name: string): string { return value; } +export function optionalAuthorityString(value: unknown, label: string): string | null { + if (value === null || value === undefined || value === "") return null; + if (typeof value !== "string") { + throw new AuthorityStoreProtocolError(`${label} must be a string or null`); + } + return value; +} + +export function optionalAuthoritySafeInteger(value: unknown, label: string): number | null { + if (value === null || value === undefined) return null; + if (!Number.isSafeInteger(value) || Number(value) < 0) { + throw new AuthorityStoreProtocolError(`${label} must be a non-negative safe integer or null`); + } + return Number(value); +} + +export function requireAuthorityBoolean(value: unknown, label: string): boolean { + if (typeof value !== "boolean") { + throw new AuthorityStoreProtocolError(`${label} must be a boolean`); + } + return value; +} + +export function optionalAuthorityBoolean(value: unknown, label: string): boolean | null { + if (value === null || value === undefined) return null; + return requireAuthorityBoolean(value, label); +} + +export function requireAuthorityDate(value: unknown, label: string): Date { + if (!(value instanceof Date) || Number.isNaN(value.valueOf())) { + throw new AuthorityStoreProtocolError(`${label} must be a valid Date`); + } + return value; +} + +export function requireAuthorityLiteral( + value: unknown, + values: readonly T[], + label: string, +): T { + if (typeof value !== "string" || !values.includes(value as T)) { + throw new AuthorityStoreProtocolError(`${label} must be one of: ${values.join(", ")}`); + } + return value as T; +} + +export function uniqueAuthorityStoreIds(value: readonly string[], label: string): string[] { + if (!Array.isArray(value)) { + throw new AuthorityStoreProtocolError(`${label} must be an array`); + } + const values = value.map((item, index) => requireAuthorityStoreId(item, `${label}[${index}]`)); + if (new Set(values).size !== values.length) { + throw new AuthorityStoreProtocolError(`${label} must contain unique ids`); + } + return values; +} + export function canonicalAuthorityJson( value: unknown, stack = new Set(), diff --git a/loopx/control_plane/coordination/todo_agents.ts b/loopx/control_plane/coordination/todo_agents.ts index 8a7b51807a..5024dbff83 100644 --- a/loopx/control_plane/coordination/todo_agents.ts +++ b/loopx/control_plane/coordination/todo_agents.ts @@ -1,7 +1,24 @@ -import {AuthorityStoreProtocolError} from "./authority_store_codec.ts"; +import {AuthorityStoreProtocolError, optionalAuthorityString} from "./authority_store_codec.ts"; import {compactPythonWhitespace} from "./python_whitespace.ts"; export {compactPythonWhitespace, hasPythonNonWhitespaceText, stripPythonWhitespace} from "./python_whitespace.ts"; +export function optionalTodoAgent(value: unknown, label: string): string | null { + const candidate = optionalAuthorityString(value, label); + return candidate === null ? null : normalizeTodoAgent(candidate, label); +} + +export function optionalRegisteredTodoAgent( + value: unknown, + label: string, + registeredAgents: readonly string[], +): string | null { + const agent = optionalTodoAgent(value, label); + if (agent !== null && !registeredAgents.includes(agent)) { + throw new AuthorityStoreProtocolError(`${label} is not a registered agent`); + } + return agent; +} + export function normalizeTodoAgent(value: unknown, label: string): string { if (typeof value !== "string") { throw new AuthorityStoreProtocolError(`${label} must be a public-safe agent id`); diff --git a/loopx/control_plane/coordination/todo_claim.ts b/loopx/control_plane/coordination/todo_claim.ts index b85f72f070..8a35b7c1d7 100644 --- a/loopx/control_plane/coordination/todo_claim.ts +++ b/loopx/control_plane/coordination/todo_claim.ts @@ -11,6 +11,8 @@ import { AuthorityStoreProtocolError, canonicalAuthorityObject, canonicalAuthoritySha256, + requireAuthorityBoolean, + requireAuthorityDate, requireAuthorityStoreId, } from "./authority_store_codec.ts"; import {validateContinuationNote, computeContinuationTodoFacts} from "./continuation_note.ts"; @@ -376,21 +378,15 @@ async function executeClaimAttempt( registered_agents: normalizeRegisteredTodoAgents(rawInput.registered_agents), lease_request: normalizeLeaseRequest(rawInput.lease_request), }; - if (input.manage_execution !== undefined && typeof input.manage_execution !== "boolean") { - throw new AuthorityStoreProtocolError("manage_execution must be a boolean"); - } + if (input.manage_execution !== undefined) requireAuthorityBoolean(input.manage_execution, "manage_execution"); 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 (typeof input.dry_run !== "boolean") { - throw new AuthorityStoreProtocolError("dry_run must be a boolean"); - } - if (!(input.now instanceof Date) || Number.isNaN(input.now.valueOf())) { - throw new AuthorityStoreProtocolError("now must be a valid Date"); - } + requireAuthorityBoolean(input.dry_run, "dry_run"); + requireAuthorityDate(input.now, "now"); } catch (error) { return failure( "invalid_coordination_todo_claim", diff --git a/loopx/control_plane/coordination/todo_successor_derivation.ts b/loopx/control_plane/coordination/todo_successor_derivation.ts index e023515dfc..009911d833 100644 --- a/loopx/control_plane/coordination/todo_successor_derivation.ts +++ b/loopx/control_plane/coordination/todo_successor_derivation.ts @@ -1,17 +1,28 @@ +import {createHash} from "node:crypto"; import {planTodoPriority} from "../todos/priority.ts"; import type { JsonObject } from "../effect_program.ts"; -import {AGENT_TODO_TASK_CLASSES as AGENT_TASK_CLASSES, USER_TODO_TASK_CLASSES as USER_TASK_CLASSES} from "../todos/authoring_scope.ts"; +import {AGENT_TODO_TASK_CLASSES as AGENT_TASK_CLASSES, USER_TODO_TASK_CLASSES as USER_TASK_CLASSES, userTodoScopeConflict} from "../todos/authoring_scope.ts"; import { AuthorityStoreProtocolError, canonicalAuthorityObject, + optionalAuthorityBoolean, + optionalAuthorityString, + requireAuthorityLiteral, requireAuthorityStoreId, } from "./authority_store_codec.ts"; +import { + TODO_CANONICAL_READ_RECORD_SCHEMA, + TODO_DOMAIN_ITEM_SCHEMA, + canonicalTodoDomainRecord, +} from "./coordination_state_contract.ts"; import { compactPythonWhitespace, normalizeRegisteredTodoAgents, normalizeTodoAgent, + optionalRegisteredTodoAgent, stripPythonWhitespace, } from "./todo_agents.ts"; +import {canonicalTodoRecord, materializeTodoRecordForSchema} from "./todo_presentation.ts"; export const TODO_SUCCESSOR_DERIVATION_REQUEST_SCHEMA = "loopx_todo_successor_derivation_request_v0"; @@ -44,41 +55,6 @@ interface NormalizedSuccessorIntent extends JsonObject { task_class: string; } -function requireLiteral( - value: unknown, - allowed: readonly T[], - label: string, -): T { - if (typeof value !== "string" || !allowed.includes(value as T)) { - throw new AuthorityStoreProtocolError( - `${label} must be one of: ${allowed.join(", ")}`, - ); - } - return value as T; -} - -function optionalString(value: unknown, label: string): string | null { - if (value === null || value === undefined || value === "") return null; - if (typeof value !== "string") { - throw new AuthorityStoreProtocolError(`${label} must be a string or null`); - } - return value; -} - -function optionalRegisteredAgent( - value: unknown, - label: string, - registeredAgents: readonly string[], -): string | null { - const raw = optionalString(value, label); - if (raw === null) return null; - const agent = normalizeTodoAgent(raw, label); - if (!registeredAgents.includes(agent)) { - throw new AuthorityStoreProtocolError(`${label} is not a registered agent`); - } - return agent; -} - function optionalStringArray(value: unknown, label: string): string[] { if (value === null || value === undefined) return []; if (!Array.isArray(value)) { @@ -116,8 +92,8 @@ function normalizeIntent( registeredAgents: readonly string[], ): NormalizedSuccessorIntent { const raw = canonicalAuthorityObject(value, `successor_intents[${index}]`); - const role = requireLiteral(raw.role, TODO_ROLES, `successor_intents[${index}].role`); - const rawTaskClass = optionalString( + const role = requireAuthorityLiteral(raw.role, TODO_ROLES, `successor_intents[${index}].role`); + const rawTaskClass = optionalAuthorityString( raw.task_class, `successor_intents[${index}].task_class`, ); @@ -134,7 +110,7 @@ function normalizeIntent( "User successor task_class must be user_action or user_gate", ); } - const claimedBy = optionalRegisteredAgent( + const claimedBy = optionalRegisteredTodoAgent( raw.claimed_by, `successor_intents[${index}].claimed_by`, registeredAgents, @@ -149,7 +125,7 @@ function normalizeIntent( "successor claimed_by cannot also appear in excluded_agents", ); } - const rawContinuationPolicy = optionalString( + const rawContinuationPolicy = optionalAuthorityString( raw.continuation_policy, `successor_intents[${index}].continuation_policy`, ); @@ -165,7 +141,7 @@ function normalizeIntent( raw.required_capabilities, `successor_intents[${index}].required_capabilities`, ); - const rawActionKind = optionalString( + const rawActionKind = optionalAuthorityString( raw.action_kind, `successor_intents[${index}].action_kind`, ); @@ -180,7 +156,7 @@ function normalizeIntent( return { ...raw, role, - text: optionalString(raw.text, `successor_intents[${index}].text`) ?? "", + text: optionalAuthorityString(raw.text, `successor_intents[${index}].text`) ?? "", task_class: taskClass, ...(claimedBy === null ? {} : {claimed_by: claimedBy}), excluded_agents: excludedAgents, @@ -206,7 +182,7 @@ function completionPolicyAgent( field: "effective_claimed_by" | "effective_next_claimed_by", registeredAgents: readonly string[], ): string | null { - return optionalRegisteredAgent(policy[field], `completion_policy.${field}`, registeredAgents); + return optionalRegisteredTodoAgent(policy[field], `completion_policy.${field}`, registeredAgents); } /** @@ -222,7 +198,7 @@ export function deriveCoordinationTodoSuccessorProposals( if (rawInput.schema_version !== TODO_SUCCESSOR_DERIVATION_REQUEST_SCHEMA) { throw new AuthorityStoreProtocolError("Todo successor derivation schema mismatch"); } - const command = requireLiteral(rawInput.command, TERMINAL_COMMANDS, "command"); + const command = requireAuthorityLiteral(rawInput.command, TERMINAL_COMMANDS, "command"); if (!Array.isArray(rawInput.successor_intents)) { throw new AuthorityStoreProtocolError("successor_intents must be an array"); } @@ -232,7 +208,7 @@ export function deriveCoordinationTodoSuccessorProposals( const predecessor = canonicalAuthorityObject(rawInput.predecessor, "predecessor"); const predecessorId = requireAuthorityStoreId(predecessor.todo_id, "predecessor.todo_id"); const registeredAgents = normalizeRegisteredTodoAgents(rawInput.registered_agents); - const actor = optionalRegisteredAgent( + const actor = optionalRegisteredTodoAgent( rawInput.actor_agent_id, "actor_agent_id", registeredAgents, @@ -269,7 +245,7 @@ export function deriveCoordinationTodoSuccessorProposals( }; compactOptionalField(proposal, "created_by", actor); if (intent.role === "agent") { - let claimedBy = optionalRegisteredAgent( + let claimedBy = optionalRegisteredTodoAgent( intent.claimed_by, "successor_intent.claimed_by", registeredAgents, @@ -292,7 +268,7 @@ export function deriveCoordinationTodoSuccessorProposals( ); } else if (claimedBy === null && intent.continuation_policy === "same_agent_non_delivery") { - claimedBy = optionalRegisteredAgent( + claimedBy = optionalRegisteredTodoAgent( predecessor.claimed_by, "predecessor.claimed_by", registeredAgents, @@ -343,7 +319,7 @@ export function deriveCoordinationTodoSuccessorProposals( } } } else { - boundAgent = optionalRegisteredAgent( + boundAgent = optionalRegisteredTodoAgent( predecessor.bound_agent ?? predecessor.blocks_agent ?? predecessor.claimed_by ?? intents.find((candidate) => candidate.role === "agent")?.claimed_by, @@ -390,3 +366,247 @@ export function evaluateCoordinationTodoSuccessorDerivation( }; } } + +function validateSuccessorSemantics( + successors: readonly JsonObject[], + registeredAgents: readonly string[], +): void { + for (const role of TODO_ROLES) { + if (successors.filter((successor) => successor.role === role).length > 1) { + throw new AuthorityStoreProtocolError( + `terminal lifecycle permits at most one generated ${role} successor`, + ); + } + } + for (const successor of successors) { + const role = requireAuthorityLiteral(successor.role, TODO_ROLES, "successor.role"); + const taskClass = optionalAuthorityString(successor.task_class, "successor.task_class"); + const claimedBy = optionalRegisteredTodoAgent(successor.claimed_by, "successor.claimed_by", registeredAgents); + const boundAgent = optionalRegisteredTodoAgent(successor.bound_agent, "successor.bound_agent", registeredAgents); + const blocksAgent = optionalRegisteredTodoAgent(successor.blocks_agent, "successor.blocks_agent", registeredAgents); + const goalBound = optionalAuthorityBoolean(successor.goal_bound, "successor.goal_bound"); + const globalGate = optionalAuthorityBoolean(successor.global_gate, "successor.global_gate"); + if (role === "agent") { + if (USER_TASK_CLASSES.has(taskClass ?? "") || boundAgent !== null || + blocksAgent !== null || goalBound === true || globalGate === true) { + throw new AuthorityStoreProtocolError( + "generated Agent successor carries user-only task or binding semantics", + ); + } + continue; + } + if (!USER_TASK_CLASSES.has(taskClass ?? "")) { + throw new AuthorityStoreProtocolError( + "generated User successor requires task_class user_action or user_gate", + ); + } + if (claimedBy !== null) { + throw new AuthorityStoreProtocolError( + "generated User successor cannot carry claimed_by ownership", + ); + } + const scopeConflict = userTodoScopeConflict(taskClass, { + bound_agent: boundAgent, goal_bound: goalBound, blocks_agent: blocksAgent, global_gate: globalGate, + }, registeredAgents.length); + if (scopeConflict === "binding_conflict") { + throw new AuthorityStoreProtocolError("generated User successor cannot be both agent-bound and goal-bound"); + } + if (taskClass === "user_action" && (blocksAgent !== null || globalGate === true)) { + throw new AuthorityStoreProtocolError("generated user_action successor cannot carry blocking gate scope"); + } + if (scopeConflict) { + throw new AuthorityStoreProtocolError({ + gate_scope_conflict: "goal-wide User gate successor requires goal_bound and no Agent binding", + global_binding_conflict: "goal-wide User gate successor requires goal_bound and no Agent binding", + agent_binding_conflict: "Agent-scoped User gate successor must bind to its blocks_agent", + gate_scope_missing: "multi-agent User gate successor requires an explicit blocking scope", + binding_missing: "multi-agent User successor requires an explicit Agent or Goal binding", + }[scopeConflict]); + } + } +} + +function generatedSuccessorId(predecessorId: string, successor: JsonObject, offset: number): string { + const role = String(successor.role); + const section = role === "agent" ? "Agent Todo" : "User Todo"; + const identity = [role, section, `${predecessorId}:${offset}`, compactPythonWhitespace(String(successor.text ?? ""))].join("|"); + return `todo_${createHash("sha1").update(identity, "utf8").digest("hex").slice(0, 12)}`; +} + +function materializeSuccessorProposals(predecessorId: string, proposals: readonly JsonObject[]): JsonObject[] { + const successors = proposals.map((proposal, index) => canonicalTodoDomainRecord({ + ...proposal, + schema_version: TODO_DOMAIN_ITEM_SCHEMA, + todo_id: generatedSuccessorId(predecessorId, proposal, index + 1), + status: "open", + done: false, + archive_state: "active", + }, `derived successors[${index}]`)); + const successorIds = successors.map((successor) => String(successor.todo_id)); + if (new Set(successorIds).size !== successorIds.length) { + throw new AuthorityStoreProtocolError("derived successors must contain unique Todo ids"); + } + return successors; +} + +function successorCandidate( + todo: JsonObject, + actor: string | null, + now: Date, + domainReadModel: boolean, + completionPolicy: JsonObject | null, +): JsonObject { + const policyOwned: JsonObject = todo.role === "agent" && completionPolicy !== null ? { + ...(completionPolicy.effective_next_claimed_by === null ? {} : {claimed_by: completionPolicy.effective_next_claimed_by}), + excluded_agents: completionPolicy.effective_next_excluded_agents, + } : {}; + const candidate: JsonObject = { + ...todo, + ...policyOwned, + schema_version: TODO_DOMAIN_ITEM_SCHEMA, + created_by: todo.created_by ?? actor, + last_actor_agent_id: actor, + updated_at: now.toISOString().replace(/\.\d{3}Z$/u, "Z"), + }; + if (todo.role === "agent" && completionPolicy !== null && completionPolicy.effective_next_claimed_by === null) { + delete candidate.claimed_by; + } + const created = canonicalTodoDomainRecord(candidate, "terminal successor"); + return domainReadModel ? created : materializeTodoRecordForSchema( + created, + TODO_CANONICAL_READ_RECORD_SCHEMA, + "terminal successor compatibility record", + ); +} + +function semanticDuplicate( + todos: Iterable, + successor: JsonObject, + retiringTodoId: string | null = null, +): JsonObject | undefined { + for (const todo of todos) { + if (todo.todo_id !== retiringTodoId && todo.role === successor.role && + todo.archive_state === "active" && todo.status !== "done" && + todo.status !== "deferred" && todo.text === successor.text) return todo; + } + return undefined; +} + +export type TerminalSuccessorsPreparation = + | { + readonly status: "ready"; + readonly successorCandidates: JsonObject[]; + readonly successorIds: string[]; + readonly generatedSuccessorIds: string[]; + } + | { + readonly status: "failed"; + readonly failureKind: "decision_rejection" | "protocol_failure"; + readonly reasonCode: string; + readonly reason: string; + readonly detail?: JsonObject; + }; + +export function prepareCoordinationTodoTerminalSuccessors(params: { + readonly command: TerminalCommand; + readonly todoId: string; + readonly todo: JsonObject; + readonly todos: ReadonlyMap; + readonly registeredAgents: readonly string[]; + readonly actorAgentId: string | null; + readonly linkedSuccessorTodoIds: readonly string[]; + readonly successorIntents: readonly JsonObject[]; + readonly completionPolicy: JsonObject | null; + readonly completionPolicyRequest: JsonObject | null; + readonly domainReadModel: boolean; + readonly now: Date; +}): TerminalSuccessorsPreparation { + const { + command, todoId, todo, todos, registeredAgents, actorAgentId, linkedSuccessorTodoIds, + successorIntents, completionPolicy, completionPolicyRequest, domainReadModel, now, + } = params; + const fail = ( + reasonCode: string, + reason: string, + detail?: JsonObject, + failureKind: "decision_rejection" | "protocol_failure" = "protocol_failure", + ): TerminalSuccessorsPreparation => ({ + status: "failed", + failureKind, + reasonCode, + reason, + ...(detail === undefined ? {} : {detail}), + }); + let successors: JsonObject[]; + try { + const proposals = deriveCoordinationTodoSuccessorProposals({ + schema_version: TODO_SUCCESSOR_DERIVATION_REQUEST_SCHEMA, + command, + predecessor: todo, + registered_agents: registeredAgents, + actor_agent_id: actorAgentId, + completion_policy: completionPolicy, + successor_intents: successorIntents, + }); + successors = materializeSuccessorProposals(todoId, proposals); + validateSuccessorSemantics(successors, registeredAgents); + } catch (error) { + return fail( + "invalid_todo_successor_derivation", + error instanceof Error ? error.message : "invalid Todo successor derivation", + undefined, + "decision_rejection", + ); + } + const generatedSuccessorIds = successors.map((successor) => String(successor.todo_id)); + const successorIds = [...new Set([...linkedSuccessorTodoIds, ...generatedSuccessorIds])]; + if (successorIds.includes(todoId)) { + return fail("todo_successor_cycle", "Todo cannot name itself as a successor"); + } + if (completionPolicy !== null) { + const agentSuccessorIntents = successorIntents.filter((successor) => successor.role === "agent"); + if (agentSuccessorIntents.length > 1) { + return fail( + "completion_policy_successor_ambiguity", + "completion policy currently permits at most one generated Agent successor", + ); + } + const requestedNextAgentTodo = completionPolicyRequest?.next_agent_todo; + if ((requestedNextAgentTodo === null || requestedNextAgentTodo === undefined) !== + (agentSuccessorIntents.length === 0) || + (agentSuccessorIntents.length === 1 && requestedNextAgentTodo !== agentSuccessorIntents[0]!.text)) { + return fail( + "completion_policy_successor_mismatch", + "completion policy next_agent_todo must identify the generated Agent successor", + ); + } + } + const userSuccessor = successors.find((successor) => successor.role === "user"); + if (command === "complete" && registeredAgents.length > 1 && userSuccessor !== undefined) { + const completingAgent = completionPolicy?.effective_claimed_by; + if (typeof completingAgent !== "string" || userSuccessor.bound_agent !== completingAgent || + (userSuccessor.task_class === "user_gate" && userSuccessor.blocks_agent !== completingAgent)) { + return fail( + "completion_user_successor_binding_mismatch", + "multi-agent completion must bind its User successor to the effective completing Agent", + ); + } + } + const successorCandidates: JsonObject[] = []; + for (const successor of successors) { + const successorId = String(successor.todo_id); + if (todos.has(successorId)) { + return fail("todo_already_exists", "terminal successor Todo id already exists", {todo_id: successorId}); + } + const duplicate = semanticDuplicate(todos.values(), successor, todoId); + if (duplicate !== undefined) { + return fail( + "todo_semantic_duplicate_conflict", + "an active Todo with the same role/text already exists", + {todo_id: duplicate.todo_id}, + ); + } + successorCandidates.push(successorCandidate(successor, actorAgentId, now, domainReadModel, completionPolicy)); + } + return {status: "ready", successorCandidates, successorIds, generatedSuccessorIds}; +} diff --git a/loopx/control_plane/coordination/todo_terminal_lifecycle.ts b/loopx/control_plane/coordination/todo_terminal_lifecycle.ts index 387f7e65f1..f62335f165 100644 --- a/loopx/control_plane/coordination/todo_terminal_lifecycle.ts +++ b/loopx/control_plane/coordination/todo_terminal_lifecycle.ts @@ -18,8 +18,9 @@ export type TodoTerminalEvidenceGuard = (context: { }) => Promise; import {todoUpdateAdmissionRejection} from "./todo_update_admission.ts"; import { createHash } from "node:crypto"; -import {acceptanceWorkGuard, acceptanceCompletionRequirements, validateAcceptanceCompletion, - acceptanceRequire, acceptanceValidationEffects, type AcceptanceCompletionRequirements} from "../goals/acceptance_contract.ts"; +import {acceptanceWorkGuard, acceptanceCompletionRequirements, acceptanceCompletionEvidence, + acceptanceCriterionFailure, acceptanceSourceBinding, acceptedCompletionResult, + acceptanceValidationEffects, type AcceptanceCompletionRequirements} from "../goals/acceptance_contract.ts"; import {CoordinationCommandReceipt, commandReceiptResult} from "./command_receipt.ts"; import type { JsonObject } from "../effect_program.ts"; @@ -30,27 +31,25 @@ import type { import { AuthorityStoreProtocolError, canonicalAuthorityObject, + canonicalAuthorityObjectList, canonicalAuthoritySha256, + optionalAuthoritySafeInteger, + optionalAuthorityString, + requireAuthorityBoolean, + requireAuthorityDate, + requireAuthorityLiteral, requireAuthorityStoreId, + uniqueAuthorityStoreIds, } from "./authority_store_codec.ts"; -import { - TODO_CANONICAL_READ_RECORD_SCHEMA, - TODO_DOMAIN_ITEM_SCHEMA, - TODO_DOMAIN_READ_RECORD_SCHEMA, - canonicalTodoDomainRecord, -} from "./coordination_state_contract.ts"; -import {canonicalTodoRecord, materializeTodoRecordForSchema} from "./todo_presentation.ts"; +import {TODO_DOMAIN_READ_RECORD_SCHEMA} from "./coordination_state_contract.ts"; +import {canonicalTodoRecord} from "./todo_presentation.ts"; import { indexCoordinationProjection, prepareCoordinationProjectionCommit, validateCoordinationTodoReadModel, type CoordinationProjectionMutation, } from "./coordination_projection.ts"; -import { - compactPythonWhitespace, - normalizeRegisteredTodoAgents, - normalizeTodoAgent, -} from "./todo_agents.ts"; +import {normalizeRegisteredTodoAgents, optionalTodoAgent} from "./todo_agents.ts"; import { evaluateCoordinationTodoTerminalDecision, type CoordinationTodoTerminalDecisionResult, @@ -59,12 +58,6 @@ import { reduceTodoCompletionTransaction, TODO_COMPLETION_TRANSACTION_REQUEST_SCHEMA, } from "../todos/completion_transaction.ts"; -import {resolveTodoCompletionPolicy} from "../todos/completion_policy.ts"; -import {evaluateTodoCompletionFence, TODO_COMPLETION_FENCE_REQUEST_SCHEMA} from "../todos/completion_fence.ts"; -import { - selectTodoCompletionState, - TODO_COMPLETION_STATE_REQUEST_SCHEMA, -} from "../todos/completion_state.ts"; import { TASK_LEASE_SCHEMA_VERSION, leaseEpoch, @@ -72,14 +65,17 @@ import { normalizeAgent, normalizeWriteScopes, } from "../work_items/task_lease_acquire.ts"; -import { userTodoScopeConflict, USER_TODO_TASK_CLASSES } from "../todos/authoring_scope.ts"; -import { - deriveCoordinationTodoSuccessorProposals, - TODO_SUCCESSOR_DERIVATION_REQUEST_SCHEMA, -} from "./todo_successor_derivation.ts"; +import {prepareCoordinationTodoTerminalSuccessors} from "./todo_successor_derivation.ts"; import { BARE_SHA256_PATTERN } from "../content_digest.ts"; import {todoExecutionDependencyRejection} from "./todo_execution_dependency.ts"; -import {isLifecycleCloseout, prepareTerminalReentry, requiresReentrySettlement} from "./todo_terminal_reentry.ts"; +import { + evaluateSameTurnTerminalUpgradeFence, + isLifecycleCloseout, + planUntypedCompletionRepair, + prepareTerminalReentry, + requiresReentrySettlement, + type UntypedCompletionRepairPlan, +} from "./todo_terminal_reentry.ts"; import {selectCoordinationTodoArchive} from "./todo_archive_selection.ts"; export const COORDINATION_TODO_TERMINAL_LIFECYCLE_RESULT_SCHEMA = @@ -180,8 +176,8 @@ export function decodeTerminalOperationIntent(value: { throw new AuthorityStoreProtocolError("use operation_identity instead of top-level operation_id"); } const identity = canonicalAuthorityObject(value.operation_identity, "terminal operation identity"); - const command = requireLiteral(value.command, TERMINAL_COMMANDS, "command"); - const turnKey = optionalString(value.requested_completion_turn_key, "requested_completion_turn_key"); + const command = requireAuthorityLiteral(value.command, TERMINAL_COMMANDS, "command"); + const turnKey = optionalAuthorityString(value.requested_completion_turn_key, "requested_completion_turn_key"); if (value.requested_completion_turn_key != null && (turnKey === null || turnKey.trim().length === 0)) { throw new AuthorityStoreProtocolError("requested_completion_turn_key must be a non-empty string or null"); } @@ -220,162 +216,6 @@ type CoordinationTodoTerminalFailureKind = | "decision_rejection" | "protocol_failure"; -function optionalString(value: unknown, label: string): string | null { - if (value === null || value === undefined || value === "") return null; - if (typeof value !== "string") { - throw new AuthorityStoreProtocolError(`${label} must be a string or null`); - } - return value; -} - -function optionalAgent(value: unknown, label: string): string | null { - const candidate = optionalString(value, label); - return candidate === null ? null : normalizeTodoAgent(candidate, label); -} - -function optionalSafeInteger(value: unknown, label: string): number | null { - if (value === null || value === undefined) return null; - if (!Number.isSafeInteger(value) || Number(value) < 0) { - throw new AuthorityStoreProtocolError(`${label} must be a non-negative safe integer or null`); - } - return Number(value); -} - -function requireBoolean(value: unknown, label: string): boolean { - if (typeof value !== "boolean") { - throw new AuthorityStoreProtocolError(`${label} must be a boolean`); - } - return value; -} - -function optionalBoolean(value: unknown, label: string): boolean | null { - if (value === null || value === undefined) return null; - return requireBoolean(value, label); -} - -function requireDate(value: unknown, label: string): Date { - if (!(value instanceof Date) || Number.isNaN(value.valueOf())) { - throw new AuthorityStoreProtocolError(`${label} must be a valid Date`); - } - return value; -} - -function requireLiteral( - value: unknown, - values: readonly T[], - label: string, -): T { - if (typeof value !== "string" || !values.includes(value as T)) { - throw new AuthorityStoreProtocolError(`${label} must be one of: ${values.join(", ")}`); - } - return value as T; -} - -function uniqueIds(value: readonly string[], label: string): string[] { - if (!Array.isArray(value)) { - throw new AuthorityStoreProtocolError(`${label} must be an array`); - } - const values = value.map((item, index) => - requireAuthorityStoreId(item, `${label}[${index}]`)); - if (new Set(values).size !== values.length) { - throw new AuthorityStoreProtocolError(`${label} must contain unique ids`); - } - return values; -} - -function lifecycleGrants(value: readonly JsonObject[]): JsonObject[] { - if (!Array.isArray(value)) { - throw new AuthorityStoreProtocolError("lifecycle_grants must be an array"); - } - return value.map((grant, index) => - canonicalAuthorityObject(grant, `lifecycle_grants[${index}]`)); -} - -function requireRegisteredSuccessorAgent( - value: unknown, - label: string, - registeredAgents: readonly string[], -): string | null { - const agent = optionalAgent(value, label); - if (agent !== null && !registeredAgents.includes(agent)) { - throw new AuthorityStoreProtocolError(`${label} is not a registered agent`); - } - return agent; -} - -function validateSuccessorSemantics( - successors: readonly JsonObject[], - registeredAgents: readonly string[], -): void { - for (const role of TODO_ROLES) { - if (successors.filter((successor) => successor.role === role).length > 1) { - throw new AuthorityStoreProtocolError( - `terminal lifecycle permits at most one generated ${role} successor`, - ); - } - } - for (const successor of successors) { - const role = requireLiteral(successor.role, TODO_ROLES, "successor.role"); - const taskClass = optionalString(successor.task_class, "successor.task_class"); - const claimedBy = requireRegisteredSuccessorAgent( - successor.claimed_by, - "successor.claimed_by", - registeredAgents, - ); - const boundAgent = requireRegisteredSuccessorAgent( - successor.bound_agent, - "successor.bound_agent", - registeredAgents, - ); - const blocksAgent = requireRegisteredSuccessorAgent( - successor.blocks_agent, - "successor.blocks_agent", - registeredAgents, - ); - const goalBound = optionalBoolean(successor.goal_bound, "successor.goal_bound"); - const globalGate = optionalBoolean(successor.global_gate, "successor.global_gate"); - if (role === "agent") { - if (USER_TODO_TASK_CLASSES.has(taskClass ?? "") || boundAgent !== null || - blocksAgent !== null || goalBound === true || globalGate === true) { - throw new AuthorityStoreProtocolError( - "generated Agent successor carries user-only task or binding semantics", - ); - } - continue; - } - if (!USER_TODO_TASK_CLASSES.has(taskClass ?? "")) { - throw new AuthorityStoreProtocolError( - "generated User successor requires task_class user_action or user_gate", - ); - } - if (claimedBy !== null) { - throw new AuthorityStoreProtocolError( - "generated User successor cannot carry claimed_by ownership", - ); - } - const scopeConflict = userTodoScopeConflict(taskClass, { - bound_agent: boundAgent, goal_bound: goalBound, blocks_agent: blocksAgent, global_gate: globalGate, - }, registeredAgents.length); - // Preserve the terminal protocol's diagnostic vocabulary. The invariant is - // shared; a resolved successor never goes through draft authoring inference. - if (scopeConflict === "binding_conflict") { - throw new AuthorityStoreProtocolError("generated User successor cannot be both agent-bound and goal-bound"); - } - if (taskClass === "user_action" && (blocksAgent !== null || globalGate === true)) { - throw new AuthorityStoreProtocolError("generated user_action successor cannot carry blocking gate scope"); - } - if (scopeConflict) { - throw new AuthorityStoreProtocolError({ - gate_scope_conflict: "goal-wide User gate successor requires goal_bound and no Agent binding", - global_binding_conflict: "goal-wide User gate successor requires goal_bound and no Agent binding", - agent_binding_conflict: "Agent-scoped User gate successor must bind to its blocks_agent", - gate_scope_missing: "multi-agent User gate successor requires an explicit blocking scope", - binding_missing: "multi-agent User successor requires an explicit Agent or Goal binding", - }[scopeConflict]); - } - } -} - function normalizeTerminalInput( raw: CoordinationTodoTerminalLifecycleInput, ): CoordinationTodoTerminalLifecycleInput { @@ -406,11 +246,7 @@ function normalizeTerminalInput( throw new AuthorityStoreProtocolError("User completion update requires complete"); } const registeredAgents = normalizeRegisteredTodoAgents(raw.registered_agents); - if (!Array.isArray(raw.successor_intents)) { - throw new AuthorityStoreProtocolError("successor_intents must be an array"); - } - const successorIntents = raw.successor_intents.map((intent, index) => - canonicalAuthorityObject(intent, `successor_intents[${index}]`)); + const successorIntents = canonicalAuthorityObjectList(raw.successor_intents, "successor_intents"); const operationIntent = decodeTerminalOperationIntent(raw); const normalized = { ...raw, @@ -418,42 +254,42 @@ function normalizeTerminalInput( goal_id: requireAuthorityStoreId(raw.goal_id, "goal id"), todo_id: requireAuthorityStoreId(raw.todo_id, "todo id"), expected_role: raw.expected_role === null - ? null : requireLiteral(raw.expected_role, TODO_ROLES, "expected_role"), + ? null : requireAuthorityLiteral(raw.expected_role, TODO_ROLES, "expected_role"), ...operationIntent, - actor_agent_id: optionalAgent(raw.actor_agent_id, "actor_agent_id"), + actor_agent_id: optionalTodoAgent(raw.actor_agent_id, "actor_agent_id"), registered_agents: registeredAgents, - lifecycle_grants: lifecycleGrants(raw.lifecycle_grants), - authority_reason: optionalString(raw.authority_reason, "authority_reason"), + lifecycle_grants: canonicalAuthorityObjectList(raw.lifecycle_grants, "lifecycle_grants"), + authority_reason: optionalAuthorityString(raw.authority_reason, "authority_reason"), decision_outcome: raw.decision_outcome === null - ? null : requireLiteral(raw.decision_outcome, DECISION_OUTCOMES, "decision_outcome"), + ? null : requireAuthorityLiteral(raw.decision_outcome, DECISION_OUTCOMES, "decision_outcome"), ...(raw.claim_operation_id == null ? {} : {claim_operation_id: claimExecutionReference(raw.claim_operation_id, raw.lease_idempotency_key, raw.lease_expected_version)}), - lease_idempotency_key: optionalString(raw.lease_idempotency_key, "lease_idempotency_key"), - lease_expected_version: optionalSafeInteger( + lease_idempotency_key: optionalAuthorityString(raw.lease_idempotency_key, "lease_idempotency_key"), + lease_expected_version: optionalAuthoritySafeInteger( raw.lease_expected_version, "lease_expected_version", ), - allow_user_gate_auto_acquire: requireBoolean( + allow_user_gate_auto_acquire: requireAuthorityBoolean( raw.allow_user_gate_auto_acquire, "allow_user_gate_auto_acquire", ), - requested_no_followup: requireBoolean(raw.requested_no_followup, "requested_no_followup"), + requested_no_followup: requireAuthorityBoolean(raw.requested_no_followup, "requested_no_followup"), requested_completion_identity_source: raw.requested_completion_identity_source === null ? null - : requireLiteral( + : requireAuthorityLiteral( raw.requested_completion_identity_source, COMPLETION_IDENTITY_SOURCES, "requested_completion_identity_source", ), - linked_successor_todo_ids: uniqueIds( + linked_successor_todo_ids: uniqueAuthorityStoreIds( raw.linked_successor_todo_ids, "linked_successor_todo_ids", ), successor_intents: successorIntents, - note: optionalString(raw.note, "note"), - evidence: optionalString(raw.evidence, "evidence"), - reason: optionalString(raw.reason, "reason"), - clear_claim: requireBoolean(raw.clear_claim, "clear_claim"), + note: optionalAuthorityString(raw.note, "note"), + evidence: optionalAuthorityString(raw.evidence, "evidence"), + reason: optionalAuthorityString(raw.reason, "reason"), + clear_claim: requireAuthorityBoolean(raw.clear_claim, "clear_claim"), validation_declaration: raw.validation_declaration === null ? null : canonicalAuthorityObject( raw.validation_declaration, @@ -464,8 +300,8 @@ function normalizeTerminalInput( completion_policy_request: raw.completion_policy_request === null ? null : canonicalAuthorityObject(raw.completion_policy_request, "completion_policy_request"), - dry_run: requireBoolean(raw.dry_run, "dry_run"), - now: requireDate(raw.now, "now"), + dry_run: requireAuthorityBoolean(raw.dry_run, "dry_run"), + now: requireAuthorityDate(raw.now, "now"), }; return normalized; } @@ -718,105 +554,6 @@ async function observeImplicitMonitorCompletion( }; } -function acceptanceSourceBinding(input: ResolvedCoordinationTodoTerminalLifecycleInput, - requirements: AcceptanceCompletionRequirements, providerRevision: string): JsonObject { - return {goal_id: input.goal_id, todo_id: input.todo_id, operation_id: input.operation_id, - provider_revision: providerRevision, contract_revision: requirements.contract_revision, - contract_digest: requirements.contract_digest, todo_semantic_digest: requirements.todo_semantic_digest}; -} - -/** Only the trusted execution adapter supplies these fresh, structured runner - * receipts. Save the public-safe criterion results, never command output. */ -function acceptanceCompletionEvidence(head: JsonObject, input: ResolvedCoordinationTodoTerminalLifecycleInput, - requirements: AcceptanceCompletionRequirements, binding: JsonObject): JsonObject { - acceptanceRequire(input.goal_acceptance_source_binding != null && - canonicalAuthoritySha256(input.goal_acceptance_source_binding) === canonicalAuthoritySha256(binding), - "Acceptance completion source changed; run the configured criteria again against the current work."); - const receipts = input.goal_acceptance_validation_receipts; - acceptanceRequire(Array.isArray(receipts), "Acceptance completion requires fresh validation receipts."); - const results = receipts.map(value => { - const row = canonicalAuthorityObject(value, "acceptance validation receipt"); - const receipt = canonicalAuthorityObject(row.receipt, "acceptance criterion runner receipt"); - acceptanceRequire(receipt.schema_version === "issue_fix_validation_command_v0" && - typeof row.criterion_id === "string" && receipt.command_label === row.criterion_id && - receipt.stdout_captured === false && receipt.stderr_captured === false && receipt.local_path_captured === false, - "Acceptance completion requires the configured criterion's public-safe runner receipt."); - return {criterion_id: row.criterion_id, passed: receipt.passed, exit_code: receipt.exit_code}; - }); - const validationReceipts = receipts.map(value => { - const row = canonicalAuthorityObject(value, "acceptance validation receipt"); - const receipt = canonicalAuthorityObject(row.receipt, "acceptance criterion runner receipt"); - return {criterion_id: row.criterion_id, receipt: Object.fromEntries([ - "schema_version", "command_label", "passed", "exit_code", "status", "summary", - "stdout_captured", "stderr_captured", "local_path_captured", - ].flatMap(key => receipt[key] === undefined ? [] : [[key, receipt[key]]]))}; - }); - const evidence = validateAcceptanceCompletion(head, input.goal_id, input.todo_id, { - contract_revision: requirements.contract_revision, contract_digest: requirements.contract_digest, - todo_id: input.todo_id, todo_semantic_digest: requirements.todo_semantic_digest, results, - }); - acceptanceRequire(evidence !== null, "Acceptance completion requirements disappeared."); - return {source_binding: binding, ...evidence, validation_receipts: validationReceipts}; -} - -function acceptedCompletionResult(input: ResolvedCoordinationTodoTerminalLifecycleInput, - todo: JsonObject, acceptanceEvidence: JsonObject | null): JsonObject | null { - if (input.completion_result == null) return null; - const row = canonicalAuthorityObject(input.completion_result, "completion result"); - acceptanceRequire(input.command === "complete" && todo.role === "agent" && - acceptanceEvidence !== null && input.actor_agent_id === todo.claimed_by, - "A result requires an independently accepted Agent Todo owned by its producer."); - const fields = ["content_type", "provider", "sha256", "size_bytes"]; - acceptanceRequire(Object.keys(row).length === fields.length && fields.every(field => Object.hasOwn(row, field)) && - row.provider === "local_runtime_v0" && - ["application/json", "text/markdown", "text/plain"].includes(String(row.content_type)) && - typeof row.sha256 === "string" && BARE_SHA256_PATTERN.test(row.sha256) && - Number.isSafeInteger(row.size_bytes) && Number(row.size_bytes) > 0 && Number(row.size_bytes) <= 128000, - "Completion result must be a bounded local content-addressed object."); - return {...row, schema_version: "loopx_completion_result_v0", - producer_agent_id: input.actor_agent_id, todo_id: input.todo_id, - completion_operation_id: input.operation_id, - acceptance_contract_digest: acceptanceEvidence.contract_digest, - acceptance_contract_revision: acceptanceEvidence.contract_revision}; -} - -/** Keep the runner's typed failure at the public boundary without exposing its - * command, output, workspace path, or caller-controlled summary. */ -function acceptanceCriterionFailure(receipts: unknown): JsonObject | null { - if (!Array.isArray(receipts)) return null; - for (const value of receipts) { - if (value === null || typeof value !== "object" || Array.isArray(value)) continue; - const row = value as Record; - const receipt = row.receipt; - if (receipt === null || typeof receipt !== "object" || Array.isArray(receipt)) continue; - const result = receipt as Record; - if (result.passed !== false || typeof row.criterion_id !== "string") continue; - const status = typeof result.status === "string" ? result.status : "command_failed"; - const nextActions: Record = { - workspace_dirty: "Preserve unrelated Git-visible files in ignored private storage or outside the worktree, then retry completion from that clean worktree with the same Turn identity.", - workspace_unverified: "Re-enter a verifiable independent delivery worktree and retry with the same Turn identity.", - workspace_receipt_unavailable: "Recover the recorded delivery workspace receipt before retrying completion.", - workspace_receipt_invalid: "Inspect the recorded delivery workspace receipt before retrying completion.", - workspace_receipt_mismatch: "Re-enter the recorded delivery worktree before retrying completion.", - workspace_repository_mismatch: "Re-enter the recorded delivery repository and revision before retrying completion.", - workspace_unavailable: "Restore the declared validation workspace before retrying completion.", - validation_basis_changed: "Inspect the changed verifier files and ask the contract owner to review the acceptance basis.", - timeout: "Inspect the validator runtime and retry the same criterion without changing the acceptance binding.", - command_not_run: "Restore the configured validation executable and retry completion.", - command_malformed: "Ask the contract owner to repair the configured validation command.", - command_failed: "Inspect the configured criterion's evidence and validator, then retry completion without rebinding acceptance.", - }; - const validationStatus = Object.hasOwn(nextActions, status) ? status : "unknown_failure"; - const exitCode = typeof result.exit_code === "number" && Number.isInteger(result.exit_code) - ? result.exit_code : null; - return {schema_version: "goal_acceptance_validation_failure_v0", - criterion_id: row.criterion_id, validation_status: validationStatus, - exit_code: exitCode, - next_action: nextActions[validationStatus] ?? "Inspect the privacy-safe runner receipt and configured criterion before retrying completion."}; - } - return null; -} - async function commitTerminalResult( store: AuthorityStore, input: ResolvedCoordinationTodoTerminalLifecycleInput, @@ -938,79 +675,6 @@ function releasedLease( }; } -function successorCandidate( - todo: JsonObject, - actor: string | null, - now: Date, - domainReadModel: boolean, - completionPolicy: JsonObject | null, -): JsonObject { - const policyOwned: JsonObject = todo.role === "agent" && completionPolicy !== null - ? { - ...(completionPolicy.effective_next_claimed_by === null - ? {} - : {claimed_by: completionPolicy.effective_next_claimed_by}), - excluded_agents: completionPolicy.effective_next_excluded_agents, - } - : {}; - const candidate: JsonObject = { - ...todo, - ...policyOwned, - schema_version: TODO_DOMAIN_ITEM_SCHEMA, - created_by: todo.created_by ?? actor, - last_actor_agent_id: actor, - updated_at: now.toISOString().replace(/\.\d{3}Z$/u, "Z"), - }; - if (todo.role === "agent" && completionPolicy !== null && - completionPolicy.effective_next_claimed_by === null) { - delete candidate.claimed_by; - } - const created = canonicalTodoDomainRecord(candidate, "terminal successor"); - return domainReadModel - ? created - : materializeTodoRecordForSchema( - created, - TODO_CANONICAL_READ_RECORD_SCHEMA, - "terminal successor compatibility record", - ); -} - -function generatedSuccessorId( - predecessorId: string, - successor: JsonObject, - offset: number, -): string { - const role = String(successor.role); - const section = role === "agent" ? "Agent Todo" : "User Todo"; - const identity = [ - role, - section, - `${predecessorId}:${offset}`, - compactPythonWhitespace(String(successor.text ?? "")), - ].join("|"); - return `todo_${createHash("sha1").update(identity, "utf8").digest("hex").slice(0, 12)}`; -} - -function materializeSuccessorProposals( - predecessorId: string, - proposals: readonly JsonObject[], -): JsonObject[] { - const successors = proposals.map((proposal, index) => - canonicalTodoDomainRecord({ - ...proposal, - schema_version: TODO_DOMAIN_ITEM_SCHEMA, - todo_id: generatedSuccessorId(predecessorId, proposal, index + 1), - status: "open", - done: false, - archive_state: "active", - }, `derived successors[${index}]`)); - const successorIds = successors.map((successor) => String(successor.todo_id)); - if (new Set(successorIds).size !== successorIds.length) { - throw new AuthorityStoreProtocolError("derived successors must contain unique Todo ids"); - } - return successors; -} - function terminalTarget( todo: JsonObject, input: ResolvedCoordinationTodoTerminalLifecycleInput, @@ -1061,148 +725,6 @@ function terminalTarget( return {todo: next, clear_fields: clearFields}; } -interface UntypedCompletionRepairPlan { - readonly todo: JsonObject; - readonly successorTodoIds: readonly string[]; -} - -function validateUntypedCompletionRepairPolicy( - request: JsonObject, - input: ResolvedCoordinationTodoTerminalLifecycleInput, - todo: JsonObject, -): void { - const allowedFields = new Set([ - "schema_version", - "goal_id", - "agent_model", - "claimed_by", - "registered_agents", - "next_claimed_by", - "next_agent_todo", - "next_continuation_policy", - "next_excluded_agents", - "self_merged", - "evidence", - "linked_successors", - ]); - if (Object.keys(request).some((field) => !allowedFields.has(field))) { - throw new AuthorityStoreProtocolError( - "imported completion repair must not carry completion policy extensions", - ); - } - const policy = resolveTodoCompletionPolicy(request); - if (request.goal_id !== input.goal_id || - canonicalAuthoritySha256(policy.registered_agents) !== - canonicalAuthoritySha256(input.registered_agents) || - // An explicit repeat of the stored claim is a source fact, not an edit. - (policy.effective_claimed_by !== null && - policy.effective_claimed_by !== (todo.claimed_by ?? null)) || - policy.effective_next_claimed_by !== null || - policy.effective_next_excluded_agents.length > 0 || - policy.self_merged || - policy.linked_successor_id !== null || - (request.next_agent_todo != null && request.next_agent_todo !== "") || - (request.next_continuation_policy != null && - request.next_continuation_policy !== "") || - (Array.isArray(request.linked_successors) && - request.linked_successors.length > 0) || - (request.evidence != null && request.evidence !== "")) { - throw new AuthorityStoreProtocolError( - "imported completion repair must not carry completion policy edits", - ); - } -} - -function planUntypedCompletionRepair( - todo: JsonObject, - input: ResolvedCoordinationTodoTerminalLifecycleInput, - authority: CoordinationTodoTerminalDecisionResult, -): UntypedCompletionRepairPlan | null { - if (input.command !== "complete" || input.requested_no_followup || todo.status !== "done") return null; - const fence = evaluateTodoCompletionFence({ - schema_version: TODO_COMPLETION_FENCE_REQUEST_SCHEMA, - projection_source: "materialized", - goal_id: input.goal_id, - todo_id: input.todo_id, - todo, - requested_no_followup: false, - requested_completion_turn_key: input.requested_completion_turn_key, - requested_completion_identity_source: input.requested_completion_identity_source, - }); - if (fence.outcome !== "continue" || fence.reason !== "untyped_completion_repair") return null; - - const storedTurnKey = typeof todo.completion_turn_key === "string" - ? todo.completion_turn_key : null; - if (input.requested_completion_turn_key !== storedTurnKey) { - throw new AuthorityStoreProtocolError( - "imported completion repair must preserve the stored completion_turn_key", - ); - } - if (authority.outcome !== "no_change") { - throw new AuthorityStoreProtocolError( - "imported completion repair cannot apply a fresh authority transition", - ); - } - if (input.user_update !== undefined || input.note !== null || input.evidence !== null || - input.reason !== null || input.decision_outcome !== null || input.clear_claim || - input.linked_successor_todo_ids.length > 0 || - input.successor_intents.length > 0 || input.completion_result != null || - input.validation_declaration !== null || - input.validation_receipt !== null || input.validation_source_provider_revision != null || - input.goal_acceptance_source_binding != null || - input.goal_acceptance_validation_receipts != null) { - throw new AuthorityStoreProtocolError( - "imported completion repair must not carry fresh completion content, policy, validation, or ownership edits", - ); - } - if (input.completion_policy_request !== null) { - validateUntypedCompletionRepairPolicy( - input.completion_policy_request, - input, - todo, - ); - } - if (input.validation_declaration_sha256 != null && - input.validation_declaration_sha256 !== todo.completion_validation_sha256) { - throw new AuthorityStoreProtocolError( - "imported completion repair must preserve the stored validation commitment", - ); - } - const successorTodoIds = Array.isArray(todo.successor_todo_ids) - ? todo.successor_todo_ids.map((value, index) => - requireAuthorityStoreId(value, `todo.successor_todo_ids[${index}]`)) - : []; - const completionState = selectTodoCompletionState({ - schema_version: TODO_COMPLETION_STATE_REQUEST_SCHEMA, - todo, - requested_no_followup: false, - has_successor: successorTodoIds.length > 0, - completion_identity_source: input.requested_completion_identity_source, - }); - const target: JsonObject = { - ...todo, - completion_continuation: completionState.continuation, - ...(completionState.recovery === null - ? {} - : {completion_recovery: completionState.recovery}), - }; - canonicalTodoRecord(target, "imported completion repair"); - return {todo: target, successorTodoIds}; -} - -function semanticDuplicate( - todos: Iterable, - successor: JsonObject, - retiringTodoId: string | null = null, -): JsonObject | undefined { - for (const todo of todos) { - if (todo.todo_id !== retiringTodoId && todo.role === successor.role && - todo.archive_state === "active" && todo.status !== "done" && - todo.status !== "deferred" && todo.text === successor.text) return todo; - } - return undefined; -} - async function readSameTurnCompletionReceipt( store: AuthorityStore, input: ResolvedCoordinationTodoTerminalLifecycleInput, @@ -1213,18 +735,14 @@ async function readSameTurnCompletionReceipt( !input.requested_no_followup) return null; const validationRequired = todo.completion_validation_required === true; const validationSha256 = todo.completion_validation_sha256; - let fence; + let sameTurnUpgrade = false; try { - fence = evaluateTodoCompletionFence({schema_version: TODO_COMPLETION_FENCE_REQUEST_SCHEMA, - projection_source: "materialized", goal_id: input.goal_id, todo_id: input.todo_id, todo, - requested_no_followup: input.requested_no_followup, - requested_completion_turn_key: input.requested_completion_turn_key, - requested_completion_identity_source: input.requested_completion_identity_source}); + sameTurnUpgrade = evaluateSameTurnTerminalUpgradeFence(input, todo); } catch (error) { return terminalFailure("invalid_todo_completion_transaction", error instanceof Error ? error.message : "Invalid original completion identity"); } - if (fence.outcome === "continue" && fence.reason === "same_turn_terminal_upgrade") { + if (sameTurnUpgrade) { const originalInput = {...input, ...(normalized.claim_operation_id === undefined ? {} : {claim_operation_id: normalized.claim_operation_id, lease_idempotency_key: normalized.lease_idempotency_key, lease_expected_version: normalized.lease_expected_version}), @@ -1568,7 +1086,7 @@ export async function executeCoordinationTodoTerminalLifecycle( } let untypedCompletionRepair: UntypedCompletionRepairPlan | null; try { - untypedCompletionRepair = planUntypedCompletionRepair(todo, input, authority); + untypedCompletionRepair = planUntypedCompletionRepair(todo, input, authority.outcome); } catch (error) { return terminalFailure( "invalid_todo_completion_transaction", @@ -1871,98 +1389,29 @@ export async function executeCoordinationTodoTerminalLifecycle( "completion policy registered_agents must match terminal authority facts", ); } - let successors: JsonObject[]; - try { - const proposals = deriveCoordinationTodoSuccessorProposals({ - schema_version: TODO_SUCCESSOR_DERIVATION_REQUEST_SCHEMA, - command: input.command, - predecessor: todo, - registered_agents: input.registered_agents, - actor_agent_id: input.actor_agent_id, - completion_policy: completionPolicy, - successor_intents: input.successor_intents, - }); - successors = materializeSuccessorProposals(input.todo_id, proposals); - validateSuccessorSemantics(successors, input.registered_agents); - } catch (error) { + const successorPrep = prepareCoordinationTodoTerminalSuccessors({ + command: input.command, + todoId: input.todo_id, + todo, + todos: projection.todos, + registeredAgents: input.registered_agents, + actorAgentId: input.actor_agent_id, + linkedSuccessorTodoIds: input.linked_successor_todo_ids, + successorIntents: input.successor_intents, + completionPolicy, + completionPolicyRequest: input.completion_policy_request, + domainReadModel, + now: input.now, + }); + if (successorPrep.status === "failed") { return terminalFailure( - "invalid_todo_successor_derivation", - error instanceof Error ? error.message : "invalid Todo successor derivation", - {}, - "decision_rejection", - ); - } - const generatedSuccessorIds = successors.map((successor) => String(successor.todo_id)); - const successorIds = [...new Set([ - ...input.linked_successor_todo_ids, - ...generatedSuccessorIds, - ])]; - for (const successorId of successorIds) { - if (successorId === input.todo_id) { - return terminalFailure("todo_successor_cycle", "Todo cannot name itself as a successor"); - } - } - if (completionPolicy !== null) { - const agentSuccessorIntents = input.successor_intents.filter( - (successor) => successor.role === "agent", + successorPrep.reasonCode, + successorPrep.reason, + successorPrep.detail ?? {}, + successorPrep.failureKind, ); - if (agentSuccessorIntents.length > 1) { - return terminalFailure( - "completion_policy_successor_ambiguity", - "completion policy currently permits at most one generated Agent successor", - ); - } - const requestedNextAgentTodo = input.completion_policy_request?.next_agent_todo; - if ((requestedNextAgentTodo === null || requestedNextAgentTodo === undefined) !== - (agentSuccessorIntents.length === 0) || - (agentSuccessorIntents.length === 1 && - requestedNextAgentTodo !== agentSuccessorIntents[0]!.text)) { - return terminalFailure( - "completion_policy_successor_mismatch", - "completion policy next_agent_todo must identify the generated Agent successor", - ); - } - } - const userSuccessor = successors.find((successor) => successor.role === "user"); - if (input.command === "complete" && input.registered_agents.length > 1 && - userSuccessor !== undefined) { - const completingAgent = completionPolicy?.effective_claimed_by; - if (typeof completingAgent !== "string" || userSuccessor.bound_agent !== completingAgent || - (userSuccessor.task_class === "user_gate" && - userSuccessor.blocks_agent !== completingAgent)) { - return terminalFailure( - "completion_user_successor_binding_mismatch", - "multi-agent completion must bind its User successor to the effective completing Agent", - ); - } - } - const successorCandidates: JsonObject[] = []; - for (const successor of successors) { - const successorId = String(successor.todo_id); - if (projection.todos.has(successorId)) { - return terminalFailure("todo_already_exists", "terminal successor Todo id already exists", { - todo_id: successorId, - }); - } - // This CAS retires the source and creates the successors together. Only - // that source stops competing for its title. Peers still participate in - // the unchanged rule; successor admission already permits one per role. - const duplicate = semanticDuplicate(projection.todos.values(), successor, input.todo_id); - if (duplicate !== undefined) { - return terminalFailure( - "todo_semantic_duplicate_conflict", - "an active Todo with the same role/text already exists", - {todo_id: duplicate.todo_id}, - ); - } - successorCandidates.push(successorCandidate( - successor, - input.actor_agent_id, - input.now, - domainReadModel, - completionPolicy, - )); } + const {successorCandidates, successorIds, generatedSuccessorIds} = successorPrep; const currentLease = projection.leases.get(input.todo_id); const released = releasedLease(currentLease, authority, input); diff --git a/loopx/control_plane/coordination/todo_terminal_reentry.ts b/loopx/control_plane/coordination/todo_terminal_reentry.ts index 1f5a7b059a..97821cab7f 100644 --- a/loopx/control_plane/coordination/todo_terminal_reentry.ts +++ b/loopx/control_plane/coordination/todo_terminal_reentry.ts @@ -1,6 +1,7 @@ import {settlementIdentity, settlementIdentityPayload, type JsonObject} from "../effect_program.ts"; import {jsonObject} from "../runtime_decode.ts"; -import {AuthorityStoreProtocolError, canonicalAuthoritySha256} from "./authority_store_codec.ts"; +import {AuthorityStoreProtocolError, canonicalAuthoritySha256, requireAuthorityStoreId} from "./authority_store_codec.ts"; +import {canonicalTodoRecord} from "./todo_presentation.ts"; import type {CoordinationTodoTerminalLifecycleInput} from "./todo_terminal_lifecycle.ts"; import {registeredTodoMutationRejection} from "./todo_lifecycle_decision.ts"; import {evaluateTodoCompletionFence, localTodoCompletionIdentity, TODO_COMPLETION_FENCE_REQUEST_SCHEMA} from "../todos/completion_fence.ts"; @@ -89,3 +90,121 @@ export function prepareTerminalReentry(todo: JsonObject, input: CoordinationTodo completion_recovery: state.recovery, completion_turn_key: input.requested_completion_turn_key, updated_at: input.now.toISOString().replace(/\.\d{3}Z$/u, "Z")}; } + +export function evaluateSameTurnTerminalUpgradeFence( + input: CoordinationTodoTerminalLifecycleInput, + todo: JsonObject, +): boolean { + const fence = evaluateTodoCompletionFence({ + schema_version: TODO_COMPLETION_FENCE_REQUEST_SCHEMA, + projection_source: "materialized", + goal_id: input.goal_id, + todo_id: input.todo_id, + todo, + requested_no_followup: input.requested_no_followup, + requested_completion_turn_key: input.requested_completion_turn_key, + requested_completion_identity_source: input.requested_completion_identity_source, + }); + return fence.outcome === "continue" && fence.reason === "same_turn_terminal_upgrade"; +} + +export interface UntypedCompletionRepairPlan { + readonly todo: JsonObject; + readonly successorTodoIds: readonly string[]; +} + +function validateUntypedCompletionRepairPolicy( + request: JsonObject, + input: CoordinationTodoTerminalLifecycleInput, + todo: JsonObject, +): void { + const allowedFields = new Set([ + "schema_version", "goal_id", "agent_model", "claimed_by", "registered_agents", + "next_claimed_by", "next_agent_todo", "next_continuation_policy", "next_excluded_agents", + "self_merged", "evidence", "linked_successors", + ]); + if (Object.keys(request).some((field) => !allowedFields.has(field))) { + throw new AuthorityStoreProtocolError( + "imported completion repair must not carry completion policy extensions", + ); + } + const policy = resolveTodoCompletionPolicy(request); + if (request.goal_id !== input.goal_id || + canonicalAuthoritySha256(policy.registered_agents) !== canonicalAuthoritySha256(input.registered_agents) || + (policy.effective_claimed_by !== null && policy.effective_claimed_by !== (todo.claimed_by ?? null)) || + policy.effective_next_claimed_by !== null || + policy.effective_next_excluded_agents.length > 0 || + policy.self_merged || + policy.linked_successor_id !== null || + (request.next_agent_todo != null && request.next_agent_todo !== "") || + (request.next_continuation_policy != null && request.next_continuation_policy !== "") || + (Array.isArray(request.linked_successors) && request.linked_successors.length > 0) || + (request.evidence != null && request.evidence !== "")) { + throw new AuthorityStoreProtocolError( + "imported completion repair must not carry completion policy edits", + ); + } +} + +export function planUntypedCompletionRepair( + todo: JsonObject, + input: CoordinationTodoTerminalLifecycleInput, + authorityOutcome: string, +): UntypedCompletionRepairPlan | null { + if (input.command !== "complete" || input.requested_no_followup || todo.status !== "done") return null; + const fence = evaluateTodoCompletionFence({ + schema_version: TODO_COMPLETION_FENCE_REQUEST_SCHEMA, + projection_source: "materialized", + goal_id: input.goal_id, + todo_id: input.todo_id, + todo, + requested_no_followup: false, + requested_completion_turn_key: input.requested_completion_turn_key, + requested_completion_identity_source: input.requested_completion_identity_source, + }); + if (fence.outcome !== "continue" || fence.reason !== "untyped_completion_repair") return null; + + const storedTurnKey = typeof todo.completion_turn_key === "string" ? todo.completion_turn_key : null; + if (input.requested_completion_turn_key !== storedTurnKey) { + throw new AuthorityStoreProtocolError("imported completion repair must preserve the stored completion_turn_key"); + } + if (authorityOutcome !== "no_change") { + throw new AuthorityStoreProtocolError("imported completion repair cannot apply a fresh authority transition"); + } + if (input.user_update !== undefined || input.note !== null || input.evidence !== null || + input.reason !== null || input.decision_outcome !== null || input.clear_claim || + input.linked_successor_todo_ids.length > 0 || + input.successor_intents.length > 0 || input.completion_result != null || + input.validation_declaration !== null || + input.validation_receipt !== null || input.validation_source_provider_revision != null || + input.goal_acceptance_source_binding != null || + input.goal_acceptance_validation_receipts != null) { + throw new AuthorityStoreProtocolError( + "imported completion repair must not carry fresh completion content, policy, validation, or ownership edits", + ); + } + if (input.completion_policy_request !== null) { + validateUntypedCompletionRepairPolicy(input.completion_policy_request, input, todo); + } + if (input.validation_declaration_sha256 != null && + input.validation_declaration_sha256 !== todo.completion_validation_sha256) { + throw new AuthorityStoreProtocolError("imported completion repair must preserve the stored validation commitment"); + } + const successorTodoIds = Array.isArray(todo.successor_todo_ids) + ? todo.successor_todo_ids.map((value, index) => requireAuthorityStoreId(value, `todo.successor_todo_ids[${index}]`)) + : []; + const completionState = selectTodoCompletionState({ + schema_version: TODO_COMPLETION_STATE_REQUEST_SCHEMA, + todo, + requested_no_followup: false, + has_successor: successorTodoIds.length > 0, + completion_identity_source: input.requested_completion_identity_source, + }); + const target: JsonObject = { + ...todo, + completion_continuation: completionState.continuation, + ...(completionState.recovery === null ? {} : {completion_recovery: completionState.recovery}), + }; + canonicalTodoRecord(target, "imported completion repair"); + return {todo: target, successorTodoIds}; +} diff --git a/loopx/control_plane/coordination/todo_update_intent.ts b/loopx/control_plane/coordination/todo_update_intent.ts index 5000acc0ba..a2746d9a1b 100644 --- a/loopx/control_plane/coordination/todo_update_intent.ts +++ b/loopx/control_plane/coordination/todo_update_intent.ts @@ -7,7 +7,7 @@ import {isDeferredReopen} from "./todo_deferred_lifecycle.ts"; import {planTodoPriority} from "../todos/priority.ts"; import type {JsonObject} from "../effect_program.ts"; import {AuthorityStoreProtocolError, canonicalAuthorityObject, canonicalAuthorityBytes, - requireAuthorityStoreId} from "./authority_store_codec.ts"; + requireAuthorityBoolean, requireAuthorityDate, requireAuthorityStoreId} from "./authority_store_codec.ts"; import {normalizeRegisteredTodoAgents, normalizeTodoAgent} from "./todo_agents.ts"; import {canonicalTodoRecord} from "./todo_presentation.ts"; import {planTodoAuthoringScope, TODO_AUTHORING_SCOPE_REQUEST_SCHEMA} from "../todos/authoring_scope.ts"; @@ -146,12 +146,8 @@ export function normalizeTodoUpdateEnvelope( if (raw.expected_role !== null && !["agent", "user"].includes(raw.expected_role)) { throw new AuthorityStoreProtocolError("expected_role must be agent or user"); } - if (typeof raw.dry_run !== "boolean") { - throw new AuthorityStoreProtocolError("dry_run must be a boolean"); - } - if (!(raw.now instanceof Date) || Number.isNaN(raw.now.valueOf())) { - throw new AuthorityStoreProtocolError("now must be a valid Date"); - } + requireAuthorityBoolean(raw.dry_run, "dry_run"); + requireAuthorityDate(raw.now, "now"); return {...raw, ...(completion === undefined ? {} : {completion}), ...(observation === undefined ? {} : {monitor_observation: observation}), ...(validationRevision === undefined ? {} : {completion_validation_revision: validationRevision}), diff --git a/loopx/control_plane/goals/acceptance_contract.ts b/loopx/control_plane/goals/acceptance_contract.ts index 05c6f2ab3c..267341d58b 100644 --- a/loopx/control_plane/goals/acceptance_contract.ts +++ b/loopx/control_plane/goals/acceptance_contract.ts @@ -692,3 +692,123 @@ export function validateAcceptanceCompletion(head: JsonObject, goalId: string, t acceptanceRequire(results.every(item => item.passed), "acceptance completion criteria failed"); return {...receipt, results}; } + +export function acceptanceSourceBinding( + input: {readonly goal_id: string; readonly todo_id: string; readonly operation_id: string}, + requirements: AcceptanceCompletionRequirements, + providerRevision: string, +): JsonObject { + return {goal_id: input.goal_id, todo_id: input.todo_id, operation_id: input.operation_id, + provider_revision: providerRevision, contract_revision: requirements.contract_revision, + contract_digest: requirements.contract_digest, todo_semantic_digest: requirements.todo_semantic_digest}; +} + +/** Only the trusted execution adapter supplies these fresh, structured runner + * receipts. Save the public-safe criterion results, never command output. */ +export function acceptanceCompletionEvidence( + head: JsonObject, + input: { + readonly goal_id: string; + readonly todo_id: string; + readonly goal_acceptance_source_binding?: JsonObject | null; + readonly goal_acceptance_validation_receipts?: unknown; + }, + requirements: AcceptanceCompletionRequirements, + binding: JsonObject, +): JsonObject { + acceptanceRequire(input.goal_acceptance_source_binding != null && + canonicalAuthoritySha256(input.goal_acceptance_source_binding) === canonicalAuthoritySha256(binding), + "Acceptance completion source changed; run the configured criteria again against the current work."); + const receipts = input.goal_acceptance_validation_receipts; + acceptanceRequire(Array.isArray(receipts), "Acceptance completion requires fresh validation receipts."); + const results: JsonObject[] = []; + const validationReceipts: JsonObject[] = []; + for (const value of receipts) { + const row = canonicalAuthorityObject(value, "acceptance validation receipt"); + const receipt = canonicalAuthorityObject(row.receipt, "acceptance criterion runner receipt"); + acceptanceRequire(receipt.schema_version === "issue_fix_validation_command_v0" && + typeof row.criterion_id === "string" && receipt.command_label === row.criterion_id && + receipt.stdout_captured === false && receipt.stderr_captured === false && receipt.local_path_captured === false, + "Acceptance completion requires the configured criterion's public-safe runner receipt."); + results.push({criterion_id: row.criterion_id, passed: receipt.passed, exit_code: receipt.exit_code}); + validationReceipts.push({criterion_id: row.criterion_id, receipt: Object.fromEntries([ + "schema_version", "command_label", "passed", "exit_code", "status", "summary", + "stdout_captured", "stderr_captured", "local_path_captured", + ].flatMap(key => receipt[key] === undefined ? [] : [[key, receipt[key]]]))}); + } + const evidence = validateAcceptanceCompletion(head, input.goal_id, input.todo_id, { + contract_revision: requirements.contract_revision, contract_digest: requirements.contract_digest, + todo_id: input.todo_id, todo_semantic_digest: requirements.todo_semantic_digest, results, + }); + acceptanceRequire(evidence !== null, "Acceptance completion requirements disappeared."); + return {source_binding: binding, ...evidence, validation_receipts: validationReceipts}; +} + +export function acceptedCompletionResult( + input: { + readonly command: string; + readonly completion_result?: JsonObject | null; + readonly actor_agent_id: string | null; + readonly todo_id: string; + readonly operation_id: string; + }, + todo: JsonObject, + acceptanceEvidence: JsonObject | null, +): JsonObject | null { + if (input.completion_result == null) return null; + const row = canonicalAuthorityObject(input.completion_result, "completion result"); + acceptanceRequire(input.command === "complete" && todo.role === "agent" && + acceptanceEvidence !== null && input.actor_agent_id === todo.claimed_by, + "A result requires an independently accepted Agent Todo owned by its producer."); + const fields = ["content_type", "provider", "sha256", "size_bytes"]; + acceptanceRequire(Object.keys(row).length === fields.length && fields.every(field => Object.hasOwn(row, field)) && + row.provider === "local_runtime_v0" && + ["application/json", "text/markdown", "text/plain"].includes(String(row.content_type)) && + typeof row.sha256 === "string" && BARE_SHA256_PATTERN.test(row.sha256) && + Number.isSafeInteger(row.size_bytes) && Number(row.size_bytes) > 0 && Number(row.size_bytes) <= 128000, + "Completion result must be a bounded local content-addressed object."); + return {...row, schema_version: "loopx_completion_result_v0", + producer_agent_id: input.actor_agent_id, todo_id: input.todo_id, + completion_operation_id: input.operation_id, + acceptance_contract_digest: acceptanceEvidence.contract_digest, + acceptance_contract_revision: acceptanceEvidence.contract_revision}; +} + +const ACCEPTANCE_FAILURE_NEXT_ACTIONS: Record = { + workspace_dirty: "Preserve unrelated Git-visible files in ignored private storage or outside the worktree, then retry completion from that clean worktree with the same Turn identity.", + workspace_unverified: "Re-enter a verifiable independent delivery worktree and retry with the same Turn identity.", + workspace_receipt_unavailable: "Recover the recorded delivery workspace receipt before retrying completion.", + workspace_receipt_invalid: "Inspect the recorded delivery workspace receipt before retrying completion.", + workspace_receipt_mismatch: "Re-enter the recorded delivery worktree before retrying completion.", + workspace_repository_mismatch: "Re-enter the recorded delivery repository and revision before retrying completion.", + workspace_unavailable: "Restore the declared validation workspace before retrying completion.", + validation_basis_changed: "Inspect the changed verifier files and ask the contract owner to review the acceptance basis.", + timeout: "Inspect the validator runtime and retry the same criterion without changing the acceptance binding.", + command_not_run: "Restore the configured validation executable and retry completion.", + command_malformed: "Ask the contract owner to repair the configured validation command.", + command_failed: "Inspect the configured criterion's evidence and validator, then retry completion without rebinding acceptance.", +}; + +/** Keep the runner's typed failure at the public boundary without exposing its + * command, output, workspace path, or caller-controlled summary. */ +export function acceptanceCriterionFailure(receipts: unknown): JsonObject | null { + if (!Array.isArray(receipts)) return null; + for (const value of receipts) { + if (value === null || typeof value !== "object" || Array.isArray(value)) continue; + const row = value as Record; + const receipt = row.receipt; + if (receipt === null || typeof receipt !== "object" || Array.isArray(receipt)) continue; + const result = receipt as Record; + if (result.passed !== false || typeof row.criterion_id !== "string") continue; + const status = typeof result.status === "string" ? result.status : "command_failed"; + const validationStatus = Object.hasOwn(ACCEPTANCE_FAILURE_NEXT_ACTIONS, status) ? status : "unknown_failure"; + const exitCode = typeof result.exit_code === "number" && Number.isInteger(result.exit_code) + ? result.exit_code : null; + return {schema_version: "goal_acceptance_validation_failure_v0", + criterion_id: row.criterion_id, validation_status: validationStatus, + exit_code: exitCode, + next_action: ACCEPTANCE_FAILURE_NEXT_ACTIONS[validationStatus] ?? + "Inspect the privacy-safe runner receipt and configured criterion before retrying completion."}; + } + return null; +}