@fabricorg/platform-host 8.0.0 → 8.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +73 -0
- package/README.md +95 -0
- package/dist/index.cjs +576 -34
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +106 -0
- package/dist/index.d.ts +106 -0
- package/dist/index.js +575 -35
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["createHash","canonicalJson","candidate","createHash","canonicalJson","utilTypes","createFabricId","performance","AdapterRegistry","AdapterCircuitBreakerRegistry","createFabricId","FABRIC_GOVERNANCE_CONTRACT_VERSION","isReconciliationRequiredError","evaluatePolicyDefinitions","aggregatePolicyOutcomes","evaluateStateMachineTransition","executeWithAdapterRetry","isAdapterCircuitOpenError","isRetryableExecutionError","createHash","isRetryableExecutionError"],"sources":["../src/types.ts","../src/command-identity.ts","../src/observability.ts","../src/host-internals.ts","../src/external-completion.ts","../src/submission-snapshot.ts","../src/outbox-requeue.ts","../src/host.ts","../src/outbox.ts","../src/memory-store.ts","../src/postgres-migrations.ts","../src/postgres-store.ts","../src/worker.ts","../src/saga-parent-lifecycle.ts","../src/tenant-isolation.ts"],"sourcesContent":["import type {\n\tActionId,\n\tActionDefinition,\n\tActionStatus,\n\tAgentActionPolicyEvaluator,\n\tAgentActionRiskTier,\n\tAgentActionRoute,\n\tActorType,\n\tAdapterCircuitBreakerProvider,\n\tAdapterImplementation,\n\tAssetEventEnvelope,\n\tFabricRuntimeServices,\n\tPolicyOutcome,\n\tPolicyObligation,\n\tPolicyObligationStatus,\n\tExecutionAttestation,\n\tExternalReconciliation,\n\tEvidencePacketReference,\n\tMutationFootprint,\n\tExecutionPrincipal,\n\tMutationGovernanceResolver,\n\tGovernanceRuntimeEvidence,\n\tRuntimePolicyDefinition,\n\tModuleRegistry,\n} from \"@fabricorg/platform\";\nimport type { PlatformHostTelemetry } from \"./observability\";\nimport type { AssemblyLockfile } from \"@fabricorg/assembly\";\n\n/** Durable Host lifecycle generation, independent from the npm package version. */\nexport const PLATFORM_HOST_CONTRACT_VERSION = 2 as const;\n\nexport type InvocationSource = \"ui\" | \"api\" | \"agent\" | \"worker\" | \"system\" | (string & {});\nexport type NamespacedAttributes = Record<string, string>;\nexport interface InvocationProvenance {\n\tsource: InvocationSource;\n\tcorrelationId: string;\n\tcausationId?: string;\n\ttraceAttributes?: NamespacedAttributes;\n\tauditAttributes?: NamespacedAttributes;\n}\n\nexport type AuthorizationGoverningMoment = \"capture\" | \"execution\" | \"both\";\nexport interface AuthorizationBinding {\n\tid: string;\n\ttenantId: string;\n\tactorId: string;\n\tactionId: string;\n\tparameterDigest: string;\n\tresourceScope?: string;\n\tcapturedAt: string;\n\texpiresAt?: string;\n\tgoverningMoment: AuthorizationGoverningMoment;\n}\n\nexport interface IdempotencyConflict {\n\tcode: \"IDEMPOTENCY_CONFLICT\";\n\tidempotencyKey: string;\n\texistingInvocationId: string;\n\treasons: Array<\"actor\" | \"authority_binding\" | \"action_version\" | \"parameters\">;\n}\n\nexport class IdempotencyConflictError extends Error {\n\treadonly code = \"IDEMPOTENCY_CONFLICT\" as const;\n\tconstructor(readonly conflict: IdempotencyConflict) {\n\t\tsuper(`Idempotency key \"${conflict.idempotencyKey}\" conflicts with invocation ${conflict.existingInvocationId}: ${conflict.reasons.join(\", \")}`);\n\t\tthis.name = \"IdempotencyConflictError\";\n\t}\n}\n\n/**\n * Why `submitAction` did not admit a submission of an action that declares\n * `admitSubmission`: `refused`, the check answered `{ admitted: false, code }`\n * with a well-formed code; `failed`, it threw or is not a function;\n * `timed_out`, its answer did not settle within `admissionTimeoutMs`;\n * `invalid_decision`, it answered anything other than `{ admitted: true }`\n * or a well-formed refusal; `invalid_parameters`, the parameters are not a\n * JSON-data object Host could copy at submission (a Proxy, a function, a\n * Date, a typed array or SharedArrayBuffer, a cycle, a getter that throws).\n */\nexport type ActionAdmissionRefusal = \"refused\" | \"failed\" | \"timed_out\" | \"invalid_decision\" | \"invalid_parameters\";\n\n/**\n * Thrown by `submitAction` when a declared admission check did not admit the\n * submission. Host wrote nothing for it: no invocation, idempotency key,\n * event, policy record or error. The message holds the action id, the\n * refusal and, for `refused`, the check's code; never a submitted value or\n * anything the check threw.\n */\nexport class ActionAdmissionError extends Error {\n\treadonly code = \"ACTION_ADMISSION_REFUSED\" as const;\n\tconstructor(\n\t\treadonly actionId: string,\n\t\treadonly refusal: ActionAdmissionRefusal,\n\t\t/** The check's own code, present only for `refused`. */\n\t\treadonly refusalCode?: string,\n\t) {\n\t\tsuper(`Action ${actionId} submission was not admitted (${refusal}${refusalCode ? `: ${refusalCode}` : \"\"}); nothing was recorded.`);\n\t\tthis.name = \"ActionAdmissionError\";\n\t}\n}\n\nexport type ExternalCompletionRefusal =\n\t| \"still_executing\"\n\t| \"not_found\"\n\t| \"not_awaiting\"\n\t| \"immediate_contract\"\n\t| \"reference_mismatch\"\n\t| \"provider_mismatch\"\n\t| \"invalid_completion\"\n\t| \"result_invalid\"\n\t| \"redaction_failed\";\n\n/**\n * Why a completion was not applied, typed so a webhook handler can answer\n * the external system correctly: `retryable` means the invocation is still\n * being finalized and the same callback will be accepted once it parks, so\n * answer with something the sender retries; anything else is permanent and\n * a retry will get the same refusal without a configuration/input change.\n * `redaction_failed` means completion result or error-text redaction failed before writes;\n * it is not retryable.\n */\nexport class ExternalCompletionError extends Error {\n\treadonly code = \"EXTERNAL_COMPLETION_REFUSED\" as const;\n\tconstructor(readonly refusal: ExternalCompletionRefusal, message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"ExternalCompletionError\";\n\t}\n\tget retryable(): boolean {\n\t\treturn this.refusal === \"still_executing\";\n\t}\n}\n\nexport interface PendingAssetEvent {\n\teventType: string;\n\tsubjectType: string;\n\tsubjectId: string;\n\tpayload: unknown;\n\teventSchemaVersion?: number;\n}\n\nexport interface ActionInvocationRecord {\n\tid: string;\n\ttenantId: string;\n\tspaceId: string;\n\tactionId: ActionId;\n\tactionVersion: number;\n\tactorId: string;\n\tactorType: ActorType;\n\tstatus: ActionStatus;\n\tparameters: Record<string, unknown>;\n\tresult: Record<string, unknown>;\n\tcorrelationId: string;\n\tcausationId?: string;\n\tidempotencyKey?: string;\n\tparameterDigest?: string;\n\tparameterDigestAlgorithm?: \"fabric-canonical-json-sha256-v1\";\n\tidempotencyActorId?: string;\n\tidempotencyAuthorizationBindingId?: string;\n\tprovenance?: Omit<InvocationProvenance, \"traceAttributes\">;\n\tauthorizationBinding?: AuthorizationBinding;\n\texecutionReason?: ActionExecutionReason;\n\tauthorizationReconciliation?: AuthorizationReconciliationOutcome;\n\t/** Durable evidence when an adapter returned an ambiguous outcome requiring reconciliation. */\n\tadapterReconciliation?: AdapterReconciliationOutcome;\n\t/**\n\t * Transition Host validated for an idempotent after_adapters action, saved\n\t * after handler/result/event validation inside a mutation transaction, or before\n\t * the handler otherwise. Supports recovered StateTransitioned emission and is\n\t * retained as evidence after completion.\n\t */\n\tpendingStateTransition?: { entityType: string; entityId: string; fromState: string; toState: string };\n\t/**\n\t * A handoff the host is waiting on. While present the invocation is\n\t * `running` without a lease: it is not stuck, it is somebody else's turn,\n\t * and the recovery worker must not re-execute it.\n\t */\n\tpendingCompletion?: PendingExternalCompletion;\n\t/** The completion an external system delivered, kept so a repeat is recognised and a contradiction is caught. */\n\texternalCompletion?: RecordedExternalCompletion;\n\t/** Opaque, non-secret reference used to revalidate delegated execution authority. */\n\tauthorizationBindingId?: string;\n\t/** Worker claims including the first; approval acceptance sets a minimum of 1. */\n\tattemptCount: number;\n\tleaseOwner?: string;\n\tleaseExpiresAt?: Date;\n\t/** Monotonic claim generation used to reject writes from expired workers. */\n\tleaseToken?: number;\n\thitlRoute?: AgentActionRoute;\n\thitlRiskTier?: AgentActionRiskTier;\n\thitlReason?: string;\n\thitlPolicyVersion?: string;\n\tapprovalDecision?: PersistedActionApprovalDecision;\n\tmutationFootprint?: MutationFootprint;\n\texecutionPrincipal?: ExecutionPrincipal;\n\truntimeEvidence?: GovernanceRuntimeEvidence;\n\t/**\n\t * When `submitAction` admitted the submission through the action's\n\t * `admitSubmission` check, set on creation and never patched. Host refuses\n\t * to execute an invocation of an action that declares the check when this\n\t * is absent, and passes it to the handler as `ActionContext.admittedAt`.\n\t */\n\tadmittedAt?: Date;\n\terror?: string;\n\tcreatedAt: Date;\n\tupdatedAt: Date;\n}\n\nexport interface AuthorizationReconciliationOutcome {\n\tkind: \"authorization_expired\" | \"authorization_denied\" | \"authorization_missing_capture_evidence\";\n\tgoverningMoment: AuthorizationGoverningMoment;\n\texecutionReason: ActionExecutionReason;\n\tauthorizationBindingId?: string;\n\tprovenance?: Omit<InvocationProvenance, \"traceAttributes\">;\n\tmessage: string;\n}\n\nexport interface HitlDecisionEvidence {\n\troute: AgentActionRoute;\n\triskTier: AgentActionRiskTier;\n\treason: string;\n\tpolicyVersion?: string;\n\tevaluatedAt: Date;\n}\n\nexport interface ActionApprovalDecision {\n\tapproved: boolean;\n\tapproverId: string;\n\tapproverType: ActorType;\n\treason?: string;\n\teditsReference?: string;\n\tdecidedAt?: Date;\n}\n\nexport interface PersistedActionApprovalDecision\n\textends Omit<ActionApprovalDecision, \"decidedAt\"> {\n\tdecidedAt: Date;\n}\n\nexport interface PolicyEvaluationRecord {\n\tid: string;\n\tactionInvocationId: string;\n\ttenantId: string;\n\tspaceId: string;\n\toutcome: PolicyOutcome;\n\tcreatedAt: Date;\n}\n\nexport interface PolicyObligationRecord extends PolicyObligation {\n\tactionInvocationId: string;\n\ttenantId: string;\n\tspaceId: string;\n\tcreatedAt: Date;\n\tupdatedAt: Date;\n}\n\nexport interface ExecutionAttestationRecord extends ExecutionAttestation {\n\tid: string;\n\tactionInvocationId: string;\n\ttenantId: string;\n\tspaceId: string;\n\tadapterInvocationId?: string;\n\trecordedAt: Date;\n}\n\nexport interface ExternalReconciliationRecord extends ExternalReconciliation {\n\tid: string;\n\tactionInvocationId: string;\n\ttenantId: string;\n\tspaceId: string;\n}\n\nexport interface PendingExternalCompletion {\n\tprovider: string;\n\tadapterType: string;\n\toperation: string;\n\tadapterInvocationId: string;\n\texternalReference: string;\n\tacceptedAt: Date;\n\t/** Past this instant the host moves the invocation to reconciliation. */\n\tdueAt?: Date;\n\t/**\n\t * Set when the invocation finished executing and parked. A handoff is\n\t * recorded before the remaining steps run, so until this is set a\n\t * completion has nothing settled to settle into; it is asked to retry.\n\t */\n\tparkedAt?: Date;\n\t/** Set with the overdue sweep verdict; does not prove execution parked. */\n\toverdueAt?: Date;\n}\n\n/**\n * What an external system reports when it finishes work the host accepted.\n *\n * Matched to the invocation by `externalReference`, never by guesswork: a\n * completion that names a reference the invocation is not waiting on is\n * refused, because completing the wrong invocation is worse than dropping a\n * callback.\n */\nexport interface ExternalCompletion {\n\texternalReference: string;\n\toutcome: \"completed\" | \"failed\";\n\t/** Merged over the handler's result on completion. */\n\tresult?: Record<string, unknown>;\n\terror?: string;\n\tprovider?: string;\n\tevidenceReferences?: EvidencePacketReference[];\n\tobservedAt: Date | string;\n}\n\nexport interface RecordedExternalCompletion extends ExternalCompletion {\n\trecordedAt: Date;\n\t/**\n\t * Canonical digest of provider, reference, outcome, result, error, and\n\t * evidence. A repeat with the same digest is the same news; a repeat with\n\t * the same outcome and a different digest is changed evidence, and is a\n\t * contradiction like a flipped outcome. Observation time is left out,\n\t * since a redelivery legitimately carries a new one.\n\t */\n\tdigest: string;\n}\n\nexport interface ReconcileOverdueCompletionsInput {\n\ttenantId?: string;\n\tspaceId?: string;\n\tlimit?: number;\n\tnow?: Date;\n}\n\nexport type AdapterInvocationStatus = \"running\" | \"succeeded\" | \"failed\" | \"ambiguous\";\n\nexport interface AdapterReconciliationOutcome {\n\tkind: \"adapter_outcome_ambiguous\";\n\tadapterType: string;\n\toperation: string;\n\tvendor: string;\n\tadapterInvocationId: string;\n\treason?: string;\n\t/** Opaque, non-secret reference to external operation state for reconciliation. */\n\texternalReference?: string;\n\tmessage: string;\n}\n\nexport interface AdapterInvocationRecord {\n\tid: string;\n\tactionInvocationId: string;\n\ttenantId: string;\n\tspaceId: string;\n\tadapterType: string;\n\toperation: string;\n\tvendor: string;\n\tstatus: AdapterInvocationStatus;\n\tinput: Record<string, unknown>;\n\toutput?: Record<string, unknown>;\n\terror?: string;\n\t/** Redacted checkpoint for replaying an ambiguous settlement without another provider call. */\n\treconciliation?: AdapterReconciliationOutcome & {\n\t\t/** Original event subject, stored only for settlement recovery. */\n\t\tadapterEventSubject?: { subjectType: string; subjectId: string };\n\t};\n\tattempt: number;\n\tcreatedAt: Date;\n\tupdatedAt: Date;\n}\n\nexport interface CreateActionInvocationInput\n\textends Omit<\n\t\tActionInvocationRecord,\n\t\t\"createdAt\" | \"updatedAt\" | \"attemptCount\" | \"leaseOwner\" | \"leaseExpiresAt\" | \"leaseToken\"\n\t> {}\n\n/** Scope of an adapter checkpoint within its owning action invocation. */\nexport interface AdapterInvocationScope {\n\ttenantId: string;\n\tspaceId: string;\n\tactionInvocationId: string;\n}\n\n/** Authority for an adapter mutation; verdict evidence uses exact status/error equality. */\nexport type AdapterInvocationWriteCondition =\n\t| { kind: \"lease\"; leaseOwner: string; leaseToken: number }\n\t| { kind: \"verdict\"; status: Exclude<ActionInvocationRecord[\"status\"], \"pending\" | \"running\" | \"waiting_for_approval\">; error?: string;\n\t\t/** Absent requires no recorded completion; a digest requires that same completion. */\n\t\texternalCompletionDigest?: string;\n\t\t/** Captured handoff row; other adapter rows need only status/error and row-status fencing.\n\t\t * Omit to retain the conservative completion check for adapter writes. Parent enrichment\n\t\t * compares the completion digest regardless of this member. */\n\t\tcompletionAdapterInvocationId?: string };\n\n/** Conditionally enrich this execution's settled parent without changing its status. */\nexport interface UpdateSettledActionInvocationInput {\n\tid: string;\n\ttenantId: string;\n\tspaceId: string;\n\tcondition: Extract<AdapterInvocationWriteCondition, { kind: \"verdict\" }>;\n\tpatch: Pick<ActionInvocationPatch, \"error\" | \"adapterReconciliation\">;\n}\n\nexport type AdapterInvocationPatch = Partial<Pick<AdapterInvocationRecord,\n\t\"status\" | \"output\" | \"error\" | \"attempt\" | \"updatedAt\" | \"reconciliation\">>;\n\nexport interface AdapterInvocationWriteInput {\n\tscope: AdapterInvocationScope;\n\tcondition: AdapterInvocationWriteCondition;\n\t/** Compare against the current row, inside the same atomic operation. */\n\texpectedStatuses?: readonly AdapterInvocationRecord[\"status\"][];\n\tmutation: { kind: \"create\"; record: AdapterInvocationRecord }\n\t\t| { kind: \"update\"; id: string; patch: AdapterInvocationPatch };\n}\n\nexport interface PlatformHostStore<TDb> {\n\treadonly db: TDb;\n\t/**\n\t * Run against the store's domain handle. This base seam does not promise a\n\t * database transaction. Use `transactionWithEvents` when domain writes,\n\t * canonical events, and invocation state must commit atomically.\n\t */\n\ttransaction<TResult>(run: (db: TDb) => Promise<TResult>): Promise<TResult>;\n\tcreateActionInvocation(input: CreateActionInvocationInput): Promise<ActionInvocationRecord>;\n\tgetActionInvocation(\n\t\tid: string,\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t): Promise<ActionInvocationRecord | undefined>;\n\tupdateActionInvocation(\n\t\tid: string,\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t\tpatch: ActionInvocationPatch,\n\t): Promise<void>;\n\tappendPolicyEvaluation(record: PolicyEvaluationRecord): Promise<void>;\n\tcreateAdapterInvocation(record: AdapterInvocationRecord): Promise<void>;\n\t/**\n\t * Optional atomic parent-authorized adapter create/update. Lease authority\n\t * requires a running parent with the supplied owner/token; verdict authority\n\t * requires the exact parent status/error (undefined error equals no error).\n\t * The completion digest guards the captured completionAdapterInvocationId;\n\t * other rows retain status/error and expectedStatuses checks. Without a captured\n\t * row ID the digest check applies conservatively to the mutation too.\n\t * Match tenant, space and invocation on both rows, locking the parent before\n\t * the adapter. Return false for a predicate miss, missing parent/row, or a\n\t * duplicate create. Updates cannot move succeeded/ambiguous to running/failed,\n\t * even when expectedStatuses is omitted. Creation must match input.scope.\n\t * Transaction implementations recheck predicates at commit or retain locks.\n\t * Host uses unchecked legacy writes when this capability is absent: custom\n\t * stores without it do not protect adapter rows against stale workers.\n\t */\n\twriteAdapterInvocation?(input: AdapterInvocationWriteInput): Promise<boolean>;\n\t/**\n\t * Atomic scoped status/error/completion compare-and-set for post-verdict enrichment.\n\t * Expected alongside writeAdapterInvocation. When absent, Host skips only parent\n\t * enrichment and still attempts the remaining evidence writes. Refusal is telemetry;\n\t * thrown errors join the evidence collector.\n\t */\n\tupdateSettledActionInvocation?(input: UpdateSettledActionInvocationInput): Promise<boolean>;\n\t/**\n\t * Host supplies scope from its store-loaded invocation at adapter call sites.\n\t * When supplied, stores must match tenant, space, and action invocation:\n\t * an out-of-scope record returns undefined. Optional for compatibility with\n\t * existing custom stores and direct callers; tenantIsolationChecks tests\n\t * scoped read and write conformance.\n\t */\n\tgetAdapterInvocation(id: string, scope?: AdapterInvocationScope): Promise<AdapterInvocationRecord | undefined>;\n\t/**\n\t * Match all three scope fields when supplied, changing nothing outside it\n\t * (a not-found error is permitted). Host supplies scope as described above;\n\t * optional only for compatibility with existing stores and direct callers.\n\t */\n\tupdateAdapterInvocation(\n\t\tid: string,\n\t\tpatch: Partial<\n\t\t\tPick<AdapterInvocationRecord, \"status\" | \"output\" | \"error\" | \"attempt\" | \"updatedAt\" | \"reconciliation\">\n\t\t>,\n\t\tscope?: AdapterInvocationScope,\n\t): Promise<void>;\n\tappendEvent(event: AssetEventEnvelope): Promise<void>;\n\tnextEventSequence(tenantId: string, spaceId: string): Promise<number>;\n\t/**\n\t * Return the state and invocation writer of the same event selected by\n\t * getEntityState, scoped to this subject and tenant/space. Return undefined\n\t * when that event or its invocation provenance is unavailable. Transaction\n\t * implementations include pending events visible to getEntityState.\n\t */\n\tgetEntityStateSource?(\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t\tentityType: string,\n\t\tentityId: string,\n\t): Promise<{ state: string; actionInvocationId: string } | undefined>;\n\n\tgetEntityState(\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t\tentityType: string,\n\t\tentityId: string,\n\t): Promise<string | undefined>;\n}\n\n/**\n * Transaction-scoped Host operations used to commit domain writes and their\n * canonical events as one unit of work.\n *\n * The supplied `db` must be bound to the same database transaction as every\n * lifecycle method on this object. Implementations must roll the whole unit\n * back when `run` throws.\n */\nexport interface PlatformHostMutationTransaction<TDb> {\n\treadonly db: TDb;\n\t/**\n\t * Read and lock an invocation until this transaction completes.\n\t * Required by serialized saga parent lifecycle transitions.\n\t */\n\tgetActionInvocationForUpdate?(\n\t\tid: string,\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t): Promise<ActionInvocationRecord | undefined>;\n\t/**\n\t * Read one event by its stable identity inside the transaction.\n\t * Required by serialized saga parent lifecycle transitions.\n\t */\n\tgetEvent?(\n\t\tid: string,\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t): Promise<AssetEventEnvelope | undefined>;\n\tappendEvent(event: AssetEventEnvelope): Promise<void>;\n\tappendEventWithOutbox?(\n\t\tevent: AssetEventEnvelope,\n\t\tmetadata: OutboxEventMetadata,\n\t): Promise<void>;\n\tnextEventSequence(tenantId: string, spaceId: string): Promise<number>;\n\tlistEvents(tenantId: string, spaceId: string): Promise<AssetEventEnvelope[]>;\n\t/**\n\t * Return the state and invocation writer of the same event selected by\n\t * getEntityState, scoped to this subject and tenant/space. Return undefined\n\t * when that event or its invocation provenance is unavailable. Transaction\n\t * implementations include pending events visible to getEntityState.\n\t */\n\tgetEntityStateSource?(\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t\tentityType: string,\n\t\tentityId: string,\n\t): Promise<{ state: string; actionInvocationId: string } | undefined>;\n\n\tgetEntityState?(\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t\tentityType: string,\n\t\tentityId: string,\n\t): Promise<string | undefined>;\n\tupdateActionInvocation(\n\t\tid: string,\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t\tpatch: ActionInvocationPatch,\n\t): Promise<void>;\n\tupdateLeasedActionInvocation?(\n\t\tinput: UpdateLeasedActionInvocationInput,\n\t): Promise<boolean>;\n\t/**\n\t * Update an adapter row in this transaction, with the same optional\n\t * tenant/space/invocation scope semantics as the store method. Host uses\n\t * this to commit degraded adapter evidence and its terminal verdict together.\n\t * Omit this member if the adapter row cannot share this transaction.\n\t */\n\tupdateAdapterInvocation?: PlatformHostStore<TDb>[\"updateAdapterInvocation\"];\n\t/** Same conditional write, sharing this transaction and its rollback. */\n\twriteAdapterInvocation?: PlatformHostStore<TDb>[\"writeAdapterInvocation\"];\n\t/**\n\t * Append governance reconciliation evidence in this transaction. Host uses\n\t * this for overdue sweeps and degraded finalization when adapter output is\n\t * withheld or a handoff is refused. Implement it alongside the transaction's\n\t * invocation row lock; an outer-store append while that lock is held can\n\t * block on a foreign key referencing the invocation. Omit this member if\n\t * governance evidence cannot share the event/verdict transaction.\n\t */\n\tappendExternalReconciliation?: GovernancePlatformHostStore<TDb>[\"appendExternalReconciliation\"];\n}\n\nexport type OutboxStatus = \"pending\" | \"published\" | \"dead_letter\";\nexport type EventPayloadClassification = \"public\" | \"internal\" | \"confidential\" | \"restricted\";\n\nexport interface OutboxEventMetadata {\n\tproducerModuleVersion: string;\n\tpayloadClassification: EventPayloadClassification;\n\ttraceContext?: Record<string, string>;\n\tincludeProvenance?: boolean;\n\t/**\n\t * Only `true` puts the event's `actorId` and `actorType` on the outbox envelope. Absent or any\n\t * other value leaves them off, and the outbox record says the actor was `suppressed`.\n\t */\n\tincludeActor?: boolean;\n}\n\n/**\n * Whether Host put actor identity on an outbox record's envelope, decided by `includeActor` when\n * the record was written. A record has no value when it predates the decision (`legacy`).\n */\nexport type OutboxActorDisclosure = \"included\" | \"suppressed\";\n\n/**\n * What the relay tells a publisher about an envelope's actor identity: the record's\n * `OutboxActorDisclosure`, or `legacy` for a record with none. The memory and PostgreSQL stores\n * hydrate actor identity only for `included` records, so their legacy and suppressed envelopes carry\n * none; a consumer that needs it reads the canonical event.\n */\nexport type EnterpriseEventActorDisclosure = OutboxActorDisclosure | \"legacy\";\n\nexport interface EnterpriseEventEnvelope {\n\teventId: string;\n\teventType: string;\n\teventSchemaVersion: number;\n\ttenantId: string;\n\tspaceId: string;\n\tsubjectType: string;\n\tsubjectId: string;\n\tsequence: number;\n\tactionInvocationId?: string;\n\tcorrelationId: string;\n\tcausationId?: string;\n\t/** Present only when `includeActor` opted this event in; the key is absent otherwise. */\n\tactorId?: string;\n\t/** Present only when `includeActor` opted this event in; the key is absent otherwise. */\n\tactorType?: string;\n\toccurredAt: Date;\n\trecordedAt: Date;\n\tproducerModuleVersion: string;\n\tpayloadClassification: EventPayloadClassification;\n\ttraceContext?: Record<string, string>;\n\tprovenance?: { source: InvocationSource; auditAttributes?: NamespacedAttributes };\n\t/** Present only for events an action declaring provisional consistency emitted. */\n\tconsistency?: \"authoritative-now\" | \"provisional-until-reconciled\";\n\tpayload: unknown;\n}\n\nexport interface OutboxRecord {\n\tid: string;\n\ttenantId: string;\n\tspaceId: string;\n\tevent: EnterpriseEventEnvelope;\n\t/** Absent for a record written before Host recorded the `includeActor` decision. */\n\tactorDisclosure?: OutboxActorDisclosure;\n\tstatus: OutboxStatus;\n\tattemptCount: number;\n\tavailableAt: Date;\n\tleaseOwner?: string;\n\tleaseExpiresAt?: Date;\n\tleaseToken?: number;\n\tlastError?: string;\n\tcreatedAt: Date;\n\tpublishedAt?: Date;\n}\n\nexport interface ClaimOutboxInput {\n\tworkerId: string;\n\tleaseDurationMs: number;\n\tlimit?: number;\n\ttenantId?: string;\n\tspaceId?: string;\n\tnow?: Date;\n}\n\nexport interface OutboxPlatformHostStore<TDb> extends PlatformHostStore<TDb> {\n\t/** True only when transactionWithEvents supplies appendEventWithOutbox in the same unit of work. */\n\treadonly transactionalOutbox?: boolean;\n\tappendEventWithOutbox(event: AssetEventEnvelope, metadata: OutboxEventMetadata): Promise<void>;\n\tclaimOutbox(input: ClaimOutboxInput): Promise<OutboxRecord[]>;\n\tmarkOutboxPublished(id: string, workerId: string, publishedAt: Date, leaseToken?: number): Promise<void>;\n\tmarkOutboxFailed(input: { id: string; workerId: string; leaseToken?: number; error: string; availableAt: Date; deadLetter: boolean }): Promise<void>;\n\trenewOutboxLease(input: { id: string; workerId: string; leaseToken: number; leaseDurationMs: number; now?: Date }): Promise<boolean>;\n\tlistOutbox(input?: { tenantId?: string; spaceId?: string; statuses?: OutboxStatus[] }): Promise<OutboxRecord[]>;\n}\n\n/**\n * Append-only evidence of one operator requeue of a dead-lettered outbox\n * record. The `prior*` fields are the dead-letter state the requeue replaced,\n * so the failure that exhausted the record stays readable after its attempt\n * budget is reset.\n */\nexport interface OutboxRequeueRecord {\n\tid: string;\n\toutboxId: string;\n\ttenantId: string;\n\tspaceId: string;\n\teventId: string;\n\tactorId: string;\n\tactorType: ActorType;\n\t/** Operator-supplied justification, persisted as audit evidence. Must not carry secrets. */\n\treason: string;\n\trequeuedAt: Date;\n\t/** When the requeued record became claimable again. */\n\tavailableAt: Date;\n\tpriorAttemptCount: number;\n\tpriorLastError?: string;\n\tpriorAvailableAt: Date;\n\tpriorLeaseToken: number;\n}\n\nexport interface RequeueOutboxDeadLetterStoreInput {\n\tid: string;\n\ttenantId: string;\n\tspaceId: string;\n\t/** Identity of the evidence row written with the transition. */\n\trequeueId: string;\n\tactorId: string;\n\tactorType: ActorType;\n\treason: string;\n\trequeuedAt: Date;\n\tavailableAt: Date;\n\t/**\n\t * The lease token of the dead letter the caller read and authorized. Every\n\t * claim increments the token and a requeue never lowers it, so a record\n\t * that was requeued, claimed and dead-lettered again carries a higher token\n\t * than the one observed, and the requeue is refused as `stale`.\n\t */\n\texpectedLeaseToken: number;\n}\n\n/**\n * `not_found`: no record with this id in the tenant and space, including a\n * record that exists under another tenant or space. `not_dead_letter`: the\n * record exists but is pending or published, for example because another\n * requeue won the compare-and-set. `stale`: the record is a dead letter\n * again, but not the one the caller observed; read and authorize it afresh.\n */\nexport type OutboxRequeueRefusal = \"not_found\" | \"not_dead_letter\" | \"stale\";\n\nexport type RequeueOutboxDeadLetterStoreResult =\n\t| { applied: true; record: OutboxRecord; requeue: OutboxRequeueRecord }\n\t| { applied: false; refusal: OutboxRequeueRefusal; currentStatus?: OutboxStatus };\n\n/**\n * Optional outbox capability that moves a dead-lettered record back to\n * pending. Kept apart from `OutboxPlatformHostStore` so a custom outbox store\n * that predates it still satisfies that interface.\n */\nexport interface OutboxRequeuePlatformHostStore<TDb> extends OutboxPlatformHostStore<TDb> {\n\tgetOutboxRecord(id: string, tenantId: string, spaceId: string): Promise<OutboxRecord | undefined>;\n\t/**\n\t * Compare-and-set from `dead_letter` at `expectedLeaseToken` to `pending`\n\t * within the tenant and space: resets `attemptCount` to 0, sets\n\t * `availableAt`, clears any lease owner while keeping the lease token,\n\t * keeps `lastError`, and appends one `OutboxRequeueRecord` in the same\n\t * atomic step. A record in any other state, at another lease token, or in\n\t * another scope is refused and nothing is written. The returned requeue\n\t * evidence shares nothing with stored history. The returned outbox record\n\t * has its own Date fields; its event payload and provenance are shallow.\n\t */\n\trequeueOutboxDeadLetter(input: RequeueOutboxDeadLetterStoreInput): Promise<RequeueOutboxDeadLetterStoreResult>;\n\t/** Requeue evidence for a scope, oldest first; `outboxId` narrows it to one record. */\n\tlistOutboxRequeues(input: { tenantId: string; spaceId: string; outboxId?: string }): Promise<OutboxRequeueRecord[]>;\n}\n\nexport interface RequeueOutboxDeadLetterInput {\n\toutboxId: string;\n\ttenantId: string;\n\tspaceId: string;\n\t/** Trusted operator identity from the caller's authenticated session, never from request input. */\n\tactorId: string;\n\tactorType: ActorType;\n\t/** Required justification, at most 1,000 characters, persisted as audit evidence. */\n\treason: string;\n\t/** When the record becomes claimable again; defaults to the host clock. */\n\tavailableAt?: Date;\n}\n\nexport type RequeueOutboxDeadLetterRefusal = OutboxRequeueRefusal | \"not_authorized\";\n\nexport type RequeueOutboxDeadLetterResult =\n\t| { status: \"requeued\"; record: OutboxRecord; requeue: OutboxRequeueRecord }\n\t| {\n\t\tstatus: \"refused\";\n\t\trefusal: RequeueOutboxDeadLetterRefusal;\n\t\t/** Present for `not_dead_letter` and `stale`: the state the record was found in. */\n\t\tcurrentStatus?: OutboxStatus;\n\t\tmessage: string;\n\t};\n\n/** Facts given to `authorizeOutboxRequeue`. `record` is absent when no record with this id exists in the scope. */\nexport interface OutboxRequeueAuthorizationInput {\n\ttenantId: string;\n\tspaceId: string;\n\tactorId: string;\n\tactorType: ActorType;\n\toutboxId: string;\n\treason: string;\n\trecord?: Pick<OutboxRecord[\"event\"], \"eventId\" | \"eventType\" | \"payloadClassification\"> &\n\t\tPick<OutboxRecord, \"status\" | \"attemptCount\">;\n}\n\n/**\n * Optional production capability for atomic domain/event persistence.\n *\n * A mutating Host action uses this capability when available. Stores that do\n * not implement it retain the legacy transaction boundary for compatibility,\n * but cannot claim atomic domain-write/event persistence.\n */\nexport interface AtomicMutationPlatformHostStore<TDb> extends PlatformHostStore<TDb> {\n\ttransactionWithEvents<TResult>(\n\t\trun: (transaction: PlatformHostMutationTransaction<TDb>) => Promise<TResult>,\n\t): Promise<TResult>;\n}\n\nexport interface BeginApprovalDecisionInput {\n\tactionInvocationId: string;\n\ttenantId: string;\n\tspaceId: string;\n\tdecision: PersistedActionApprovalDecision;\n\tleaseOwner: string;\n\tleaseDurationMs: number;\n\tnow: Date;\n}\n\nexport interface ApprovalDecisionTransitionResult {\n\tapplied: boolean;\n\tinvocation?: ActionInvocationRecord;\n}\n\n/** Optional store capability required only when agent HITL or approval resume is used. */\nexport interface ApprovalPlatformHostStore<TDb> extends PlatformHostStore<TDb> {\n\trecordHitlDecision(\n\t\tactionInvocationId: string,\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t\tdecision: HitlDecisionEvidence,\n\t): Promise<ActionInvocationRecord>;\n\tbeginApprovalDecision(\n\t\tinput: BeginApprovalDecisionInput,\n\t): Promise<ApprovalDecisionTransitionResult>;\n}\n\n/** Optional durable capabilities used when external-governance enrichment is configured. */\nexport interface GovernancePlatformHostStore<TDb> extends PlatformHostStore<TDb> {\n\trecordMutationGovernance(\n\t\tactionInvocationId: string,\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t\tcontext: { footprint: MutationFootprint; executionPrincipal: ExecutionPrincipal },\n\t): Promise<ActionInvocationRecord>;\n\tappendPolicyObligations(records: PolicyObligationRecord[]): Promise<void>;\n\tlistPolicyObligations(\n\t\tactionInvocationId: string,\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t): Promise<PolicyObligationRecord[]>;\n\tupdatePolicyObligation(\n\t\tactionInvocationId: string,\n\t\tobligationId: string,\n\t\tstatus: PolicyObligationStatus,\n\t\tevidenceReferences?: PolicyObligation[\"evidenceReferences\"],\n\t): Promise<void>;\n\tappendExecutionAttestation(record: ExecutionAttestationRecord): Promise<void>;\n\tlistExecutionAttestations(\n\t\tactionInvocationId: string,\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t): Promise<ExecutionAttestationRecord[]>;\n\tappendExternalReconciliation(record: ExternalReconciliationRecord): Promise<void>;\n}\n\nexport interface ListActionInvocationsInput {\n\ttenantId?: string;\n\tspaceId?: string;\n\tstatuses?: readonly ActionStatus[];\n\tupdatedBefore?: Date;\n\t/** Only invocations holding a pending external completion. */\n\tawaitingCompletion?: boolean;\n\t/** Only pending completions due at or before this instant. Implies `awaitingCompletion`. */\n\tcompletionDueBefore?: Date;\n\t/** Only invocations no worker holds a lease on. */\n\tunleased?: boolean;\n\tlimit?: number;\n}\n\nexport interface ClaimActionInvocationsInput {\n\tworkerId: string;\n\tleaseDurationMs: number;\n\tlimit?: number;\n\ttenantId?: string;\n\tspaceId?: string;\n\tnow?: Date;\n}\n\n/**\n * What the host writes back to an invocation.\n *\n * Store obligations for `pendingCompletion`, which a custom store must honour\n * or the recovery worker will re-run an external handoff:\n * - a patch that sets `pendingCompletion` together with `status: \"running\"`\n * parks the invocation and must clear its lease;\n * - a patch that sets `pendingCompletion` without a status records the handoff\n * and must leave the lease alone;\n * - a patch with `pendingCompletion: undefined` clears it;\n * - `claimActionInvocations` must never claim a running invocation without a\n * lease, which is what a parked invocation is.\n */\nexport type ActionInvocationPatch = Partial<\n\tPick<ActionInvocationRecord, \"status\" | \"result\" | \"error\" | \"authorizationReconciliation\" | \"adapterReconciliation\" | \"pendingStateTransition\" | \"pendingCompletion\" | \"externalCompletion\">\n>;\n\nexport interface UpdateLeasedActionInvocationInput {\n\tid: string;\n\ttenantId: string;\n\tspaceId: string;\n\tworkerId: string;\n\tleaseToken: number;\n\tpatch: ActionInvocationPatch;\n}\n\nexport interface RenewActionInvocationLeaseInput {\n\tid: string;\n\ttenantId: string;\n\tspaceId: string;\n\tworkerId: string;\n\tleaseToken: number;\n\tleaseDurationMs: number;\n\tnow?: Date;\n}\n\n/** Store capabilities required by the durable polling worker and operator tooling. */\nexport interface RecoverablePlatformHostStore<TDb> extends PlatformHostStore<TDb> {\n\tlistActionInvocations(input?: ListActionInvocationsInput): Promise<ActionInvocationRecord[]>;\n\tclaimActionInvocations(input: ClaimActionInvocationsInput): Promise<ActionInvocationRecord[]>;\n\tupdateLeasedActionInvocation(input: UpdateLeasedActionInvocationInput): Promise<boolean>;\n\trenewActionInvocationLease(input: RenewActionInvocationLeaseInput): Promise<boolean>;\n\tlistEvents(tenantId: string, spaceId: string): Promise<AssetEventEnvelope[]>;\n}\n\nexport interface ActionAuthorizationInput {\n\tactionId: ActionId;\n\tnamespace: string;\n\trequiredPermissions: readonly string[];\n\trequiredRoles: readonly string[];\n\ttenantId: string;\n\tspaceId: string;\n\tactorId: string;\n\tactorType: ActorType;\n}\n\nexport type KnownActionExecutionReason = \"initial\" | \"approval_resume\" | \"recovery\" | \"offline_replay\";\nexport type ActionExecutionReason = KnownActionExecutionReason | (string & {});\n\n/**\n * Trusted execution-boundary authorization input.\n *\n * Parameters are the schema-parsed durable parameters, never caller-supplied\n * transient values. `invocation` is the canonical record that will execute.\n */\nexport interface ActionExecutionAuthorizationInput extends ActionAuthorizationInput {\n\tactionInvocationId: string;\n\tparameters: unknown;\n\tinvocation: Readonly<ActionInvocationRecord>;\n\texecutionReason: ActionExecutionReason;\n}\n\n/**\n * Input to `resolvePolicies`. Carries the invocation identity and the\n * schema-parsed durable (post-redaction) parameters so a resolver can choose\n * the policy snapshot pinned to this specific invocation. Host keeps the first\n * persisted evaluation per invocation and policy, so return the same snapshot\n * for an `actionInvocationId` on every attempt.\n */\nexport interface ResolvePoliciesInput extends ActionExecutionAuthorizationInput {\n\tdeclaredPolicyIds: readonly string[];\n}\n\nexport interface PlatformHostAuthorization {\n\tcheckEntitlement(input: ActionAuthorizationInput): Promise<boolean>;\n\tauthorize(input: ActionAuthorizationInput): Promise<boolean>;\n\t/**\n\t * Optional final authorization immediately before policies and mutation\n\t * execution. When absent, the Host reuses `authorize` at this boundary.\n\t */\n\tauthorizeExecution?(input: ActionExecutionAuthorizationInput): Promise<boolean>;\n\t/** Optional distinct authorization boundary for human/system approval decisions. */\n\tauthorizeApproval?(\n\t\tinput: ActionAuthorizationInput & { decision: ActionApprovalDecision },\n\t): Promise<boolean>;\n\t/**\n\t * Authorization for `requeueOutboxDeadLetter`. There is no action to fall\n\t * back to, so when this is absent every requeue is refused as\n\t * `not_authorized`. A throw propagates and nothing is requeued.\n\t */\n\tauthorizeOutboxRequeue?(input: OutboxRequeueAuthorizationInput): Promise<boolean>;\n}\n\nexport interface DispatchActionInput {\n\tactionInvocationId: string;\n\tactionId: ActionId;\n\ttenantId: string;\n\tspaceId: string;\n\tworkflowId: string;\n}\n\nexport interface DispatchActionResult {\n\tworkflowId: string;\n\trunId?: string;\n}\n\nexport interface PlatformActionDispatcher {\n\tdispatch(input: DispatchActionInput): Promise<DispatchActionResult>;\n}\n\n/**\n * One submission. `submitAction` reads the scalar fields (`actionId`, scope,\n * actor, correlation and causation ids, `executionReason`, `idempotencyKey`,\n * `authorizationBindingId`) exactly once, before its first await, and uses\n * only those values afterwards, so changing them while the call is pending\n * changes no action, scope, actor or key Host authorizes, persists or\n * executes. For an action that declares `admitSubmission`, `parameters`,\n * `provenance` and `authorizationBinding` are also read once there and\n * replaced by Host's own copies. For any other action Host uses those three\n * as the caller's objects, read where and as often as before (README,\n * \"Submission snapshot\").\n */\nexport interface SubmitActionInput {\n\tactionId: ActionId;\n\tparameters: Record<string, unknown>;\n\ttenantId: string;\n\tspaceId: string;\n\tactorId: string;\n\tactorType: ActorType;\n\tcorrelationId?: string;\n\tcausationId?: string;\n\tprovenance?: InvocationProvenance;\n\texecutionReason?: Extract<KnownActionExecutionReason, \"initial\" | \"offline_replay\">;\n\t/** Stable logical command key. Reusing it returns the original invocation; a pending failed dispatch may retry its stable workflow ID. */\n\tidempotencyKey?: string;\n\t/** Opaque, non-secret authorization/admission reference persisted with the invocation. */\n\tauthorizationBindingId?: string;\n\tauthorizationBinding?: AuthorizationBinding;\n}\n\nexport interface SubmitActionResult {\n\tactionInvocationId: string;\n\tstatus: ActionStatus;\n\tworkflowId: string;\n\trunId?: string;\n\tresult?: Record<string, unknown>;\n\terror?: string;\n\treconciliation?: AuthorizationReconciliationOutcome;\n\tadapterReconciliation?: AdapterReconciliationOutcome;\n\t/** Present while the invocation waits for an external system to complete it. */\n\tpendingCompletion?: PendingExternalCompletion;\n\t/** Mirrors the action's declared consistency so a caller knows whether the result is settled. */\n\tconsistency?: \"authoritative-now\" | \"provisional-until-reconciled\";\n\thitlRoute?: AgentActionRoute;\n\thitlRiskTier?: AgentActionRiskTier;\n}\n\nexport interface ExecuteActionResult {\n\tactionInvocationId: string;\n\tstatus: ActionStatus;\n\tresult?: Record<string, unknown>;\n\terror?: string;\n\treconciliation?: AuthorizationReconciliationOutcome;\n\tadapterReconciliation?: AdapterReconciliationOutcome;\n\t/** Present while the invocation waits for an external system to complete it. */\n\tpendingCompletion?: PendingExternalCompletion;\n\t/** Mirrors the action's declared consistency so a caller knows whether the result is settled. */\n\tconsistency?: \"authoritative-now\" | \"provisional-until-reconciled\";\n\thitlRoute?: AgentActionRoute;\n\thitlRiskTier?: AgentActionRiskTier;\n}\n\nexport interface ExecuteInvocationOptions {\n\t/** Required when executing a row already protected by a worker or approval-resume lease. */\n\tleaseOwner?: string;\n\t/** Claim generation paired with leaseOwner; stale generations are rejected. */\n\tleaseToken?: number;\n}\n\nexport interface PlatformActionWorkerOptions<TDb> {\n\thost: GovernedActionHost;\n\tstore: RecoverablePlatformHostStore<TDb>;\n\tworkerId: string;\n\tbatchSize?: number;\n\tleaseDurationMs?: number;\n\tleaseRenewalIntervalMs?: number;\n\tpollIntervalMs?: number;\n\ttenantId?: string;\n\tspaceId?: string;\n\tsignal?: AbortSignal;\n\tonError?: (error: unknown, invocation?: ActionInvocationRecord) => void;\n\ttelemetry?: PlatformHostTelemetry;\n\t/**\n\t * Sweep overdue external handoffs each cycle. Defaults to on. Turn it off\n\t * for a store without the governance seam, where the sweep would refuse\n\t * on every cycle, and run the sweep elsewhere.\n\t */\n\tsweepOverdueCompletions?: boolean;\n}\n\nexport interface PlatformActionWorkerCycleResult {\n\tclaimed: number;\n\tcompleted: number;\n\tfailed: number;\n\t/** Present when claimed agent work was durably parked instead of failing. */\n\twaitingForApproval?: number;\n\t/**\n\t * Present only when > 0: claimed invocations whose execution threw a\n\t * RetryableExecutionError (counted by error type, not by where it was thrown).\n\t * The row stays leased and a later claim retries it; excluded from failed.\n\t */\n\tdeferred?: number;\n}\n\n/** Origin of error text redacted before Host records or returns it. */\nexport interface ErrorTextRedactionContext {\n\tactionId: ActionId;\n\tsource: \"handler\" | \"adapter\" | \"external_completion\" | \"execution\";\n\tadapterType?: string;\n\toperation?: string;\n\t/** Adapter vendor or external completion provider. */\n\tprovider?: string;\n}\n\nexport interface PlatformHostOptions<TDb> {\n\tstore: PlatformHostStore<TDb>;\n\tauthorization: PlatformHostAuthorization;\n\t/** Preferred explicit catalog assembled from this runtime's Fabric modules. */\n\tregistry?: Pick<ModuleRegistry<TDb>, \"resolveAction\" | \"resolvePolicy\" | \"resolveStateMachine\"> &\n\t\tPartial<Pick<ModuleRegistry<TDb>, \"orderedModules\">>;\n\t/** Resolve vertical- or runtime-local actions without mutating the process-wide registry. */\n\tresolveAction?: (actionId: ActionId) => ActionDefinition<TDb> | undefined;\n\tadapters?: readonly AdapterImplementation[];\n\t/**\n\t * Supplies the circuit breaker for each adapter call. Defaults to a new\n\t * `AdapterCircuitBreakerRegistry` per Host instance, which creates one\n\t * in-process breaker per `adapterType:operation` from that adapter's own\n\t * `circuitBreaker` config, on first use, and none for adapters without one.\n\t * Pass a shared registry or a custom provider to share breakers between\n\t * Host instances, receive breaker telemetry, or set manual overrides.\n\t * The default key shares failures across tenants and vendors in a registry.\n\t * Use `new AdapterCircuitBreakerRegistry({ key: scopedAdapterCircuitBreakerKey })`\n\t * for tenant/space/vendor isolation. Host passes trusted tenant/space scope\n\t * to the provider. The registry keeps the first config seen for a key;\n\t * later conflicting configs reuse that breaker without throwing. Breakers\n\t * are never evicted, so scoped keys keep one breaker per scope seen.\n\t */\n\tadapterCircuitBreakers?: AdapterCircuitBreakerProvider;\n\t/**\n\t * Positive integer attempt cap for RetryableExecutionError during governance,\n\t * before policy-evaluation persistence (default 5). A leased, idempotent action\n\t * below the cap is left running for worker reclaim after lease expiry.\n\t * Inline execution, approval resume, exhausted attempts, and non-idempotent\n\t * actions fail. Policy persistence, obligation listing/resolution/persistence, state-machine checks,\n\t * the handler transaction, handlers, adapters, and finalization are excluded;\n\t * their failure/reconciliation/recovery semantics apply, subject to recoveryMaxAttempts.\n\t */\n\tretryableExecutionMaxAttempts?: number;\n\t/**\n\t * Positive integer cap on worker claims for resumed leased running invocations\n\t * including the first (default max(5, retryableExecutionMaxAttempts); Infinity is rejected).\n\t * An explicit value must be at least retryableExecutionMaxAttempts. Claims above\n\t * the cap settle reconciliation_required before\n\t * handler or adapter execution. Inline/direct execution and approval resume\n\t * do not increment this counter. Approval resume is admitted at the cap and settles\n\t * reconciliation above it; approval does not reset the count. Parked handoffs are excluded. A worker dying\n\t * before the check consumes a claim without executing a provider at that point.\n\t */\n\trecoveryMaxAttempts?: number;\n\tdispatcher?: PlatformActionDispatcher;\n\tservices?: FabricRuntimeServices;\n\tidempotency?: {\n\t\tconflictMode?: \"audit-only\" | \"enforce\";\n\t\tonConflict?(conflict: IdempotencyConflict): void;\n\t\tonLegacyRecord?(invocation: ActionInvocationRecord): void;\n\t};\n\tprovenance?: {\n\t\tauditAttributeAllowlist?: readonly string[];\n\t\tmaxAttributes?: number;\n\t\tmaxValueLength?: number;\n\t\tredactAuditAttributes?(attributes: NamespacedAttributes): NamespacedAttributes;\n\t\tonTrace?(provenance: InvocationProvenance): void;\n\t};\n\t/** Requires an outbox-capable store; every canonical event is then appended with delivery state. */\n\toutbox?: {\n\t\tproducerModuleVersion(actionId: ActionId, actionVersion: number): string;\n\t\tclassifyPayload(event: AssetEventEnvelope): EventPayloadClassification;\n\t\tincludeProvenance?(event: AssetEventEnvelope, classification: EventPayloadClassification): boolean;\n\t\t/**\n\t\t * Opt an event's `actorId` and `actorType` into its outbox envelope. Absent, the actor is\n\t\t * excluded for every classification. Only `true` includes it. An included actor reaches every\n\t\t * sink of every relay reading this outbox.\n\t\t */\n\t\tincludeActor?(event: AssetEventEnvelope, classification: EventPayloadClassification): boolean;\n\t\ttraceContext?(event: AssetEventEnvelope): Record<string, string> | undefined;\n\t\t/** Host lifecycle events are excluded by default; opt in only after making their payload audit-safe. */\n\t\tshouldPublish?(event: AssetEventEnvelope): boolean;\n\t};\n\t/** Optional vertical-owned evaluator. When absent, agent behavior is unchanged. */\n\thitlEvaluator?: AgentActionPolicyEvaluator;\n\t/** Durable evaluator/ruleset version recorded with every HITL decision. */\n\thitlPolicyVersion?: string;\n\t/** Optional portable resolver; provider-specific implementations belong in integration packages. */\n\tresolveMutationGovernance?: MutationGovernanceResolver;\n\t/** Translate policy outcomes into durable, enforceable obligations. */\n\tresolvePolicyObligations?: (\n\t\toutcomes: readonly PolicyOutcome[],\n\t) => Promise<PolicyObligation[]> | PolicyObligation[];\n\t/** Translate a successful adapter result into audit-safe evidence. Recovery may call this\n\t * again with stored input/output; return deterministic evidence for the same input. */\n\textractExecutionAttestation?: (input: {\n\t\tactionInvocationId: string;\n\t\tadapterInvocationId: string;\n\t\tadapterType: string;\n\t\toperation: string;\n\t\tvendor: string;\n\t\t/** Audit-safe adapter input after redactAdapterInput has been applied. */\n\t\tinput: Record<string, unknown>;\n\t\tstartedAt: Date;\n\t\tcompletedAt: Date;\n\t\t/** Adapter output after redactAdapterOutput, when configured. */\n\t\toutput: Record<string, unknown>;\n\t}) => Promise<ExecutionAttestation | undefined> | ExecutionAttestation | undefined;\n\t/** Package/provider/ruleset generations persisted with every newly created invocation. */\n\truntimeEvidence?: Partial<GovernanceRuntimeEvidence>;\n\t/**\n\t * Trusted composition identity attached by the Host configuration, never\n\t * accepted directly from submission input. Requires an explicit registry;\n\t * its module namespaces and versions are checked against these identities.\n\t */\n\tcomposition?: {\n\t\tassembly: AssemblyLockfile;\n\t\t/**\n\t\t * Receives a fresh object whose action, scope, actor, correlation,\n\t\t * causation, idempotency key, binding id and execution reason are the\n\t\t * ones Host read at submission and persists, whatever the caller\n\t\t * changed on its own object since. For an action without\n\t\t * `admitSubmission`, its `parameters`, `provenance` and\n\t\t * `authorizationBinding` read and assign the caller's input, as when\n\t\t * the callback was handed that input itself; for an action that\n\t\t * declares it, they are fresh copies of Host's snapshot.\n\t\t */\n\t\tresolveInitiatingReleaseDigest?(\n\t\t\tinput: SubmitActionInput,\n\t\t): Promise<string | undefined> | string | undefined;\n\t};\n\t/** Lease held while an approved invocation resumes; defaults to five minutes. */\n\tapprovalResumeLeaseDurationMs?: number;\n\t/**\n\t * Remove forbidden/sensitive fields before durable invocation persistence.\n\t * For an action without `admitSubmission`, receives the caller's\n\t * parameters object, before provenance normalization and the composition\n\t * callback, as before. For an action that declares it, receives Host's\n\t * copy, after the check admitted the submission.\n\t */\n\tredactActionParameters?: (\n\t\tactionId: ActionId,\n\t\tparameters: Record<string, unknown>,\n\t) => Record<string, unknown>;\n\t/**\n\t * The bound on an action's `admitSubmission` check. An answer that\n\t * settles this many milliseconds or more after the check was called,\n\t * measured on the monotonic clock when its promise settles, is refused as\n\t * `timed_out` and the check's signal is aborted. A whole number from 1 to\n\t * 2 147 483 647 (the timer maximum), or `createGovernedActionHost` throws;\n\t * default 10 000.\n\t */\n\tadmissionTimeoutMs?: number;\n\tresolvePolicies?: (input: ResolvePoliciesInput) => Promise<RuntimePolicyDefinition[]>;\n\textractEvents?: (data: Record<string, unknown>) => PendingAssetEvent[];\n\t/** Handler-result fields consumed by extractEvents and omitted from the durable result. */\n\teventResultFields?: readonly string[];\n\tredactAdapterInput?: (\n\t\tactionId: ActionId,\n\t\tadapterType: string,\n\t\toperation: string,\n\t\tinput: Record<string, unknown>,\n\t) => Record<string, unknown>;\n\t/**\n\t * Redact successful adapter output before row/event persistence and attestation extraction.\n\t * A throwing hook or a null, array or non-object return withholds output and requires reconciliation.\n\t * Class instances and Dates are accepted, matching the adapter output record contract.\n\t * Keep redactors deterministic and stable across deploys.\n\t * Accepted-operation references are read from the original adapter result.\n\t */\n\tredactAdapterOutput?: (\n\t\tactionId: ActionId,\n\t\tadapterType: string,\n\t\toperation: string,\n\t\toutput: Record<string, unknown>,\n\t) => Record<string, unknown>;\n\t/**\n\t * Redact originating handler, adapter, completion and caught execution error text.\n\t * Host-authored fixed text bypasses this hook; circuit and consistency errors use adapter context.\n\t * Empty originating text bypasses the hook unchanged. For non-empty input, throwing or returning\n\t * a non-string or empty string uses a placeholder on execution paths, but refuses a completion\n\t * as redaction_failed before writes. State-machine `transition.error` text uses `source: \"handler\"`.\n\t * Keep redactors deterministic and stable across deploys: changed output can make a repeat\n\t * completion look like different evidence.\n\t */\n\tredactErrorText?: (context: ErrorTextRedactionContext, message: string) => string;\n\t/**\n\t * Redact completion results before merging, schema validation, persistence and digesting.\n\t * Contradiction detection compares retained values; legacy raw digests also match repeats.\n\t * A throwing hook or a null, array or non-object return refuses as redaction_failed before writes.\n\t * Class instances and Dates are accepted by the same record predicate as adapter output.\n\t * Keep redactors deterministic and stable across deploys: changes can make a repeat look like\n\t * different evidence. A matching legacy raw digest is acknowledged before invoking hooks.\n\t */\n\tredactExternalCompletionResult?: (\n\t\tactionId: ActionId,\n\t\tprovider: string,\n\t\tresult: Record<string, unknown>,\n\t) => Record<string, unknown>;\n\tadapterEventSubject?: (\n\t\tactionId: ActionId,\n\t\tparameters: unknown,\n\t\thandlerResult: Record<string, unknown>,\n\t) => { subjectType: string; subjectId: string } | undefined;\n\tnow?: () => Date;\n\t/** Vendor-neutral lifecycle and metric sink. Telemetry is best effort. */\n\ttelemetry?: PlatformHostTelemetry;\n\t/**\n\t * Epoch-millis deadline delivered to every adapter execution context.\n\t * When omitted, no deadline is set and adapters receive no AbortSignal.\n\t */\n\tadapterDeadlineMs?: number;\n}\n\nexport interface GovernedActionHost {\n\tsubmitAction(input: SubmitActionInput): Promise<SubmitActionResult>;\n\texecuteInvocation(\n\t\tactionInvocationId: string,\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t\toptions?: ExecuteInvocationOptions,\n\t): Promise<ExecuteActionResult>;\n\tresumeApprovedInvocation(\n\t\tactionInvocationId: string,\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t\tdecision: ActionApprovalDecision,\n\t): Promise<ExecuteActionResult>;\n\trecordExecutionAttestation(\n\t\tactionInvocationId: string,\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t\tattestation: ExecutionAttestation,\n\t): Promise<void>;\n\trecordExternalReconciliation(\n\t\tactionInvocationId: string,\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t\treconciliation: ExternalReconciliation,\n\t): Promise<void>;\n\t/**\n\t * Complete an invocation an adapter handed off, by the reference the\n\t * external system was given. Idempotent for a repeated identical\n\t * completion; a contradictory one moves the invocation to reconciliation.\n\t */\n\tcompleteExternalInvocation(\n\t\tactionInvocationId: string,\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t\tcompletion: ExternalCompletion,\n\t): Promise<ExecuteActionResult>;\n\t/**\n\t * Move eligible running, unleased overdue handoffs to `reconciliation_required`\n\t * and retain the handoff with overdueAt. A callback can settle that verdict\n\t * only after parking; callbacks for swept unparked invocations record redacted\n\t * evidence without result-schema validation. Parked rows lacking overdueAt\n\t * retain the weaker \"did not complete by\" error-substring fallback.\n\t */\n\treconcileOverdueCompletions(input?: ReconcileOverdueCompletionsInput): Promise<{ overdue: string[] }>;\n}\n\n/**\n * Host operator operations kept outside `GovernedActionHost`, so an existing\n * hand-written `GovernedActionHost` still satisfies that interface.\n * `createGovernedActionHost()` returns both.\n */\nexport interface OutboxRequeueHost {\n\t/**\n\t * Operator replay of a dead-lettered outbox record: authorize the trusted\n\t * actor for the tenant and space against the record as read, then move\n\t * that same dead letter back to pending with a fresh attempt budget and\n\t * append who, when, and why beside the earlier failure. The relay\n\t * republishes it under the same `eventId`. Requires an\n\t * `OutboxRequeuePlatformHostStore`; refusals are returned, not thrown.\n\t */\n\trequeueOutboxDeadLetter(input: RequeueOutboxDeadLetterInput): Promise<RequeueOutboxDeadLetterResult>;\n}\n","import { createHash } from \"node:crypto\";\nimport { canonicalJson } from \"@fabricorg/platform\";\nimport type { InvocationProvenance, InvocationSource, PlatformHostOptions } from \"./types\";\n\nexport const PARAMETER_DIGEST_ALGORITHM = \"fabric-canonical-json-sha256-v1\" as const;\n\n// Canonical JSON is owned by @fabricorg/platform (evidence subpath); Host re-exports it unchanged so\n// its public API and parameter digests stay byte-identical.\nexport { canonicalJson };\n\nexport function digestParameters(parameters: unknown): string {\n\treturn createHash(\"sha256\").update(canonicalJson(parameters)).digest(\"hex\");\n}\n\nconst ATTRIBUTE_NAME = /^[a-z][a-z0-9-]*(?:\\.[A-Za-z][A-Za-z0-9_-]*)+$/;\nconst INVOCATION_SOURCE = /^(?:ui|sdui|api|agent|worker|system|[a-z][a-z0-9-]*(?:\\.[a-z][a-z0-9-]*)+)$/;\n\nexport function normalizeProvenance(\n\tinput: InvocationProvenance | undefined,\n\toptions: PlatformHostOptions<unknown>[\"provenance\"],\n): Omit<InvocationProvenance, \"traceAttributes\"> | undefined {\n\tif (!input) return undefined;\n\tif (!INVOCATION_SOURCE.test(input.source)) throw new Error(`Invalid invocation provenance source: ${input.source}`);\n\tconst maxAttributes = options?.maxAttributes ?? 16;\n\tconst maxValueLength = options?.maxValueLength ?? 256;\n\tconst allowlist = new Set(options?.auditAttributeAllowlist ?? []);\n\tconst validate = (attributes: Record<string, string> | undefined, durable: boolean) => {\n\t\tif (!attributes) return undefined;\n\t\tconst entries = Object.entries(attributes);\n\t\tif (entries.length > maxAttributes) throw new Error(`Invocation provenance exceeds ${maxAttributes} attributes.`);\n\t\tfor (const [key, value] of entries) {\n\t\t\tif (!ATTRIBUTE_NAME.test(key)) throw new Error(`Invalid provenance attribute name: ${key}`);\n\t\t\tif (value.length > maxValueLength) throw new Error(`Invocation provenance attribute \"${key}\" exceeds ${maxValueLength} characters.`);\n\t\t\tif (durable && !allowlist.has(key)) throw new Error(`Audit provenance attribute \"${key}\" is not allowlisted.`);\n\t\t}\n\t\treturn Object.fromEntries(entries);\n\t};\n\tvalidate(input.traceAttributes, false);\n\tconst redactedAuditAttributes = input.auditAttributes\n\t\t? options?.redactAuditAttributes?.({ ...input.auditAttributes }) ?? input.auditAttributes\n\t\t: undefined;\n\tconst auditAttributes = validate(redactedAuditAttributes, true);\n\toptions?.onTrace?.({\n\t\t...input,\n\t\t...(auditAttributes ? { auditAttributes } : { auditAttributes: undefined }),\n\t});\n\treturn {\n\t\tsource: input.source,\n\t\tcorrelationId: input.correlationId,\n\t\t...(input.causationId ? { causationId: input.causationId } : {}),\n\t\t...(auditAttributes ? { auditAttributes } : {}),\n\t};\n}\n","import type {\n\tActionInvocationRecord,\n\tOutboxPlatformHostStore,\n\tPlatformHostStore,\n\tRecoverablePlatformHostStore,\n} from \"./types\";\n\n/** Version of the vendor-neutral health/readiness contract. */\nexport const PLATFORM_HOST_HEALTH_CONTRACT_VERSION = 1 as const;\n\n/**\n * Stable metric names. Adapters may translate these names to a vendor's\n * naming convention, but applications should not derive names from labels.\n */\nexport const PLATFORM_HOST_METRIC_NAMES = {\n\tworkerCyclesStarted: \"fabric.platform.worker.cycles.started\",\n\tworkerCyclesCompleted: \"fabric.platform.worker.cycles.completed\",\n\tworkerCyclesFailed: \"fabric.platform.worker.cycles.failed\",\n\tinvocationSubmitted: \"fabric.platform.invocation.submitted\",\n\tinvocationAdmissionRefused: \"fabric.platform.invocation.admission_refused\",\n\tinvocationExecutionStarted: \"fabric.platform.invocation.execution_started\",\n\tinvocationLeaseClaimed: \"fabric.platform.invocation.lease_claimed\",\n\tinvocationCompleted: \"fabric.platform.invocation.completed\",\n\tinvocationFailed: \"fabric.platform.invocation.failed\",\n\tinvocationPolicyBlocked: \"fabric.platform.invocation.policy_blocked\",\n\tinvocationValidationFailed: \"fabric.platform.invocation.validation_failed\",\n\tinvocationApprovalWaited: \"fabric.platform.invocation.approval_waited\",\n\tinvocationReconciliationRequired: \"fabric.platform.invocation.reconciliation_required\",\n\tadapterEvidenceRefused: \"fabric.platform.invocation.adapter_evidence_refused\",\n\toutboxRelayCyclesStarted: \"fabric.platform.outbox.relay_cycles.started\",\n\toutboxRelayCyclesCompleted: \"fabric.platform.outbox.relay_cycles.completed\",\n\toutboxRelayCyclesFailed: \"fabric.platform.outbox.relay_cycles.failed\",\n\toutboxLeaseClaimed: \"fabric.platform.outbox.lease_claimed\",\n\toutboxPublished: \"fabric.platform.outbox.published\",\n\toutboxFailed: \"fabric.platform.outbox.failed\",\n\toutboxDeadLettered: \"fabric.platform.outbox.dead_lettered\",\n\toutboxRequeued: \"fabric.platform.outbox.requeued\",\n\toutboxRequeueRefused: \"fabric.platform.outbox.requeue_refused\",\n\tinvocationBacklog: \"fabric.platform.invocation.backlog\",\n\tinvocationRunning: \"fabric.platform.invocation.running\",\n\tinvocationExpiredLeases: \"fabric.platform.invocation.expired_leases\",\n\tinvocationApprovalWaits: \"fabric.platform.invocation.approval_waits\",\n\tinvocationReconciliationRequiredGauge: \"fabric.platform.invocation.reconciliation_required.count\",\n\toutboxBacklog: \"fabric.platform.outbox.backlog\",\n\toutboxExpiredLeases: \"fabric.platform.outbox.expired_leases\",\n\toutboxDeadLetters: \"fabric.platform.outbox.dead_letters\",\n} as const;\n\nexport type PlatformHostMetricName =\n\t(typeof PLATFORM_HOST_METRIC_NAMES)[keyof typeof PLATFORM_HOST_METRIC_NAMES];\n\nexport type PlatformHostTelemetryEventName =\n\t| \"worker.cycle.started\"\n\t| \"worker.cycle.completed\"\n\t| \"worker.cycle.failed\"\n\t| \"invocation.submitted\"\n\t| \"invocation.admission_refused\"\n\t| \"invocation.execution_started\"\n\t| \"invocation.lease_claimed\"\n\t| \"invocation.completed\"\n\t| \"invocation.failed\"\n\t| \"invocation.policy_blocked\"\n\t| \"invocation.validation_failed\"\n\t| \"invocation.approval_waited\"\n\t| \"invocation.reconciliation_required\"\n\t| \"invocation.adapter_evidence_refused\"\n\t| \"outbox.relay.started\"\n\t| \"outbox.relay.completed\"\n\t| \"outbox.relay.failed\"\n\t| \"outbox.lease_claimed\"\n\t| \"outbox.published\"\n\t| \"outbox.failed\"\n\t| \"outbox.dead_lettered\"\n\t| \"outbox.requeued\"\n\t| \"outbox.requeue_refused\";\n\nexport type PlatformHostMetricType = \"counter\" | \"gauge\";\nexport type PlatformHostTelemetryAttribute = string | number | boolean;\n\nexport interface PlatformHostLifecycleTelemetry {\n\tkind: \"event\";\n\tname: PlatformHostTelemetryEventName;\n\tmetricName: PlatformHostMetricName;\n\tmetricType: \"counter\";\n\toccurredAt: Date;\n\ttenantId?: string;\n\tspaceId?: string;\n\tattributes?: Readonly<Record<string, PlatformHostTelemetryAttribute>>;\n}\n\nexport interface PlatformHostMetricTelemetry {\n\tkind: \"metric\";\n\tname: PlatformHostMetricName;\n\tmetricType: PlatformHostMetricType;\n\tvalue: number;\n\tobservedAt: Date;\n\ttenantId?: string;\n\tspaceId?: string;\n}\n\nexport type PlatformHostTelemetryRecord =\n\t| PlatformHostLifecycleTelemetry\n\t| PlatformHostMetricTelemetry;\n\nexport type PlatformHostTelemetryHook = (\n\trecord: PlatformHostTelemetryRecord,\n) => void | Promise<void>;\n\n/**\n * A deliberately small sink contract. No OpenTelemetry, Prometheus, or\n * vendor SDK is required by Platform Host.\n */\nexport type PlatformHostTelemetry =\n\t| PlatformHostTelemetryHook\n\t| { record: PlatformHostTelemetryHook };\n\nexport type PlatformHostTelemetryInput =\n\t| Omit<PlatformHostLifecycleTelemetry, \"occurredAt\" | \"metricType\"> & { occurredAt?: Date }\n\t| Omit<PlatformHostMetricTelemetry, \"observedAt\"> & { observedAt?: Date };\n\n/**\n * Telemetry is best effort and must never change governed mutation behavior.\n * Promise-returning hooks are detached and rejected hooks are swallowed.\n */\nexport function emitPlatformHostTelemetry(\n\ttelemetry: PlatformHostTelemetry | undefined,\n\tinput: PlatformHostTelemetryInput,\n): void {\n\tif (!telemetry) return;\n\tconst record = input.kind === \"event\"\n\t\t? { ...input, metricType: \"counter\" as const, occurredAt: input.occurredAt ?? new Date() }\n\t\t: { ...input, observedAt: input.observedAt ?? new Date() };\n\ttry {\n\t\tconst result = typeof telemetry === \"function\"\n\t\t\t? telemetry(record)\n\t\t\t: telemetry.record(record);\n\t\tif (isPromiseLike(result)) void result.catch(() => undefined);\n\t} catch {\n\t\t// Observability outages must not fail a mutation or worker checkpoint.\n\t}\n}\n\nexport interface PlatformHostHealthQuery {\n\ttenantId?: string;\n\tspaceId?: string;\n\tnow: Date;\n}\n\nexport interface PlatformHostHealthCounts {\n\tinvocationBacklog: number;\n\tinvocationRunning: number;\n\tinvocationExpiredLeases: number;\n\tinvocationApprovalWaits: number;\n\tinvocationReconciliationRequired: number;\n\toutboxBacklog: number;\n\toutboxExpiredLeases: number;\n\toutboxDeadLetters: number;\n}\n\nexport interface PlatformHostWorkerHealthInput {\n\tlastHeartbeatAt: Date;\n\tstaleAfterMs: number;\n}\n\nexport interface PlatformHostHealthOptions<TDb> {\n\tstore: PlatformHostStore<TDb>;\n\ttenantId?: string;\n\tspaceId?: string;\n\tnow?: () => Date;\n\t/**\n\t * Worker liveness is supplied by the deployment's supervisor or telemetry\n\t * bridge. Only aggregate healthy/stale counts are returned.\n\t */\n\tworkers?: readonly PlatformHostWorkerHealthInput[];\n\ttelemetry?: PlatformHostTelemetry;\n}\n\nexport interface PlatformHostHealthStore<TDb> extends RecoverablePlatformHostStore<TDb> {\n\tgetHealthCounts(input: PlatformHostHealthQuery): Promise<PlatformHostHealthCounts>;\n}\n\nexport type PlatformHostHealthStatus = \"healthy\" | \"degraded\" | \"unhealthy\";\n\nexport interface PlatformHostHealthSnapshot {\n\tcontractVersion: typeof PLATFORM_HOST_HEALTH_CONTRACT_VERSION;\n\tgeneratedAt: Date;\n\tscope: { tenantId?: string; spaceId?: string };\n\tdataAvailable: boolean;\n\tstatus: PlatformHostHealthStatus;\n\treadiness: {\n\t\tready: boolean;\n\t\treasonCodes: readonly PlatformHostReadinessReason[];\n\t};\n\tworkers: {\n\t\treported: number;\n\t\thealthy: number;\n\t\tstale: number;\n\t};\n\tinvocations: {\n\t\tbacklog: number;\n\t\trunning: number;\n\t\texpiredLeases: number;\n\t\tapprovalWaits: number;\n\t\treconciliationRequired: number;\n\t};\n\toutbox: {\n\t\tbacklog: number;\n\t\texpiredLeases: number;\n\t\tdeadLetters: number;\n\t};\n}\n\nexport type PlatformHostReadinessReason =\n\t| \"health_source_unavailable\"\n\t| \"workers_stale\"\n\t| \"invocation_expired_leases\"\n\t| \"outbox_expired_leases\"\n\t| \"outbox_dead_letters\"\n\t| \"reconciliation_required\";\n\n/**\n * Read tenant/space-scoped operational counts without returning invocation,\n * actor, parameter, error, event, or adapter data.\n */\nexport async function getPlatformHostHealthSnapshot<TDb>(\n\toptions: PlatformHostHealthOptions<TDb>,\n): Promise<PlatformHostHealthSnapshot> {\n\tconst generatedAt = options.now?.() ?? new Date();\n\tconst workerSummary = summarizeWorkers(options.workers ?? [], generatedAt);\n\tconst scope = {\n\t\t...(options.tenantId ? { tenantId: options.tenantId } : {}),\n\t\t...(options.spaceId ? { spaceId: options.spaceId } : {}),\n\t};\n\n\ttry {\n\t\tconst counts = await readHealthCounts(options.store, {\n\t\t\t...(options.tenantId ? { tenantId: options.tenantId } : {}),\n\t\t\t...(options.spaceId ? { spaceId: options.spaceId } : {}),\n\t\t\tnow: generatedAt,\n\t\t});\n\t\tconst snapshot = createHealthSnapshot(\n\t\t\tgeneratedAt,\n\t\t\tscope,\n\t\t\tcounts,\n\t\t\tworkerSummary,\n\t\t\ttrue,\n\t\t);\n\t\temitHealthMetrics(options.telemetry, snapshot);\n\t\treturn snapshot;\n\t} catch {\n\t\tconst snapshot = createHealthSnapshot(\n\t\t\tgeneratedAt,\n\t\t\tscope,\n\t\t\tzeroHealthCounts(),\n\t\t\tworkerSummary,\n\t\t\tfalse,\n\t\t);\n\t\temitHealthMetrics(options.telemetry, snapshot);\n\t\treturn snapshot;\n\t}\n}\n\nasync function readHealthCounts<TDb>(\n\tstore: PlatformHostStore<TDb>,\n\tquery: PlatformHostHealthQuery,\n): Promise<PlatformHostHealthCounts> {\n\tconst candidate = store as PlatformHostStore<TDb> & {\n\t\tgetHealthCounts?: (input: PlatformHostHealthQuery) => Promise<PlatformHostHealthCounts>;\n\t};\n\tif (typeof candidate.getHealthCounts === \"function\") {\n\t\treturn assertHealthCounts(await candidate.getHealthCounts(query));\n\t}\n\n\t// Compatibility fallback for custom stores that predate the aggregate seam.\n\tconst recoverable = store as Partial<RecoverablePlatformHostStore<TDb>>;\n\tconst outbox = store as Partial<OutboxPlatformHostStore<TDb>>;\n\tif (typeof recoverable.listActionInvocations !== \"function\") {\n\t\tthrow new Error(\"Health counts are not supported by this store.\");\n\t}\n\tconst invocations = await recoverable.listActionInvocations({\n\t\t...(query.tenantId ? { tenantId: query.tenantId } : {}),\n\t\t...(query.spaceId ? { spaceId: query.spaceId } : {}),\n\t\tlimit: Number.MAX_SAFE_INTEGER,\n\t});\n\tconst outboxRecords = typeof outbox.listOutbox === \"function\"\n\t\t? await outbox.listOutbox({\n\t\t\t...(query.tenantId ? { tenantId: query.tenantId } : {}),\n\t\t\t...(query.spaceId ? { spaceId: query.spaceId } : {}),\n\t\t})\n\t\t: [];\n\treturn countsFromRecords(invocations, outboxRecords, query.now);\n}\n\nfunction countsFromRecords(\n\tinvocations: readonly ActionInvocationRecord[],\n\toutbox: readonly { status: string; leaseExpiresAt?: Date }[],\n\tnow: Date,\n): PlatformHostHealthCounts {\n\treturn {\n\t\tinvocationBacklog: invocations.filter((item) => item.status === \"pending\").length,\n\t\tinvocationRunning: invocations.filter((item) => item.status === \"running\").length,\n\t\tinvocationExpiredLeases: invocations.filter((item) =>\n\t\t\titem.status === \"running\" &&\n\t\t\titem.leaseExpiresAt !== undefined &&\n\t\t\titem.leaseExpiresAt.getTime() <= now.getTime(),\n\t\t).length,\n\t\tinvocationApprovalWaits: invocations.filter((item) => item.status === \"waiting_for_approval\").length,\n\t\tinvocationReconciliationRequired: invocations.filter((item) => item.status === \"reconciliation_required\").length,\n\t\toutboxBacklog: outbox.filter((item) => item.status === \"pending\").length,\n\t\toutboxExpiredLeases: outbox.filter((item) =>\n\t\t\titem.status === \"pending\" &&\n\t\t\titem.leaseExpiresAt !== undefined &&\n\t\t\titem.leaseExpiresAt.getTime() <= now.getTime(),\n\t\t).length,\n\t\toutboxDeadLetters: outbox.filter((item) => item.status === \"dead_letter\").length,\n\t};\n}\n\nfunction assertHealthCounts(value: PlatformHostHealthCounts): PlatformHostHealthCounts {\n\tfor (const [name, count] of Object.entries(value)) {\n\t\tif (!Number.isSafeInteger(count) || count < 0) {\n\t\t\tthrow new Error(`Invalid health count: ${name}`);\n\t\t}\n\t}\n\treturn value;\n}\n\nfunction zeroHealthCounts(): PlatformHostHealthCounts {\n\treturn {\n\t\tinvocationBacklog: 0,\n\t\tinvocationRunning: 0,\n\t\tinvocationExpiredLeases: 0,\n\t\tinvocationApprovalWaits: 0,\n\t\tinvocationReconciliationRequired: 0,\n\t\toutboxBacklog: 0,\n\t\toutboxExpiredLeases: 0,\n\t\toutboxDeadLetters: 0,\n\t};\n}\n\nfunction summarizeWorkers(\n\tworkers: readonly PlatformHostWorkerHealthInput[],\n\tnow: Date,\n): PlatformHostHealthSnapshot[\"workers\"] {\n\tlet healthy = 0;\n\tlet stale = 0;\n\tfor (const worker of workers) {\n\t\tif (\n\t\t\tNumber.isFinite(worker.staleAfterMs) &&\n\t\t\tworker.staleAfterMs >= 0 &&\n\t\t\tworker.lastHeartbeatAt.getTime() + worker.staleAfterMs >= now.getTime()\n\t\t) healthy += 1;\n\t\telse stale += 1;\n\t}\n\treturn { reported: workers.length, healthy, stale };\n}\n\nfunction createHealthSnapshot(\n\tgeneratedAt: Date,\n\tscope: PlatformHostHealthSnapshot[\"scope\"],\n\tcounts: PlatformHostHealthCounts,\n\tworkers: PlatformHostHealthSnapshot[\"workers\"],\n\tdataAvailable: boolean,\n): PlatformHostHealthSnapshot {\n\tconst reasonCodes: PlatformHostReadinessReason[] = [];\n\tif (!dataAvailable) reasonCodes.push(\"health_source_unavailable\");\n\tif (workers.stale > 0) reasonCodes.push(\"workers_stale\");\n\tif (counts.invocationExpiredLeases > 0) reasonCodes.push(\"invocation_expired_leases\");\n\tif (counts.outboxExpiredLeases > 0) reasonCodes.push(\"outbox_expired_leases\");\n\tif (counts.outboxDeadLetters > 0) reasonCodes.push(\"outbox_dead_letters\");\n\tif (counts.invocationReconciliationRequired > 0) reasonCodes.push(\"reconciliation_required\");\n\tconst unhealthy = !dataAvailable;\n\tconst degraded = unhealthy || reasonCodes.length > 0;\n\treturn {\n\t\tcontractVersion: PLATFORM_HOST_HEALTH_CONTRACT_VERSION,\n\t\tgeneratedAt,\n\t\tscope,\n\t\tdataAvailable,\n\t\tstatus: unhealthy ? \"unhealthy\" : degraded ? \"degraded\" : \"healthy\",\n\t\treadiness: {\n\t\t\tready: dataAvailable && workers.stale === 0,\n\t\t\treasonCodes,\n\t\t},\n\t\tworkers,\n\t\tinvocations: {\n\t\t\tbacklog: counts.invocationBacklog,\n\t\t\trunning: counts.invocationRunning,\n\t\t\texpiredLeases: counts.invocationExpiredLeases,\n\t\t\tapprovalWaits: counts.invocationApprovalWaits,\n\t\t\treconciliationRequired: counts.invocationReconciliationRequired,\n\t\t},\n\t\toutbox: {\n\t\t\tbacklog: counts.outboxBacklog,\n\t\t\texpiredLeases: counts.outboxExpiredLeases,\n\t\t\tdeadLetters: counts.outboxDeadLetters,\n\t\t},\n\t};\n}\n\nfunction emitHealthMetrics(\n\ttelemetry: PlatformHostTelemetry | undefined,\n\tsnapshot: PlatformHostHealthSnapshot,\n): void {\n\tconst scope = {\n\t\t...(snapshot.scope.tenantId ? { tenantId: snapshot.scope.tenantId } : {}),\n\t\t...(snapshot.scope.spaceId ? { spaceId: snapshot.scope.spaceId } : {}),\n\t};\n\tconst metrics: Array<[PlatformHostMetricName, number]> = [\n\t\t[PLATFORM_HOST_METRIC_NAMES.invocationBacklog, snapshot.invocations.backlog],\n\t\t[PLATFORM_HOST_METRIC_NAMES.invocationRunning, snapshot.invocations.running],\n\t\t[PLATFORM_HOST_METRIC_NAMES.invocationExpiredLeases, snapshot.invocations.expiredLeases],\n\t\t[PLATFORM_HOST_METRIC_NAMES.invocationApprovalWaits, snapshot.invocations.approvalWaits],\n\t\t[PLATFORM_HOST_METRIC_NAMES.invocationReconciliationRequiredGauge, snapshot.invocations.reconciliationRequired],\n\t\t[PLATFORM_HOST_METRIC_NAMES.outboxBacklog, snapshot.outbox.backlog],\n\t\t[PLATFORM_HOST_METRIC_NAMES.outboxExpiredLeases, snapshot.outbox.expiredLeases],\n\t\t[PLATFORM_HOST_METRIC_NAMES.outboxDeadLetters, snapshot.outbox.deadLetters],\n\t];\n\tfor (const [name, value] of metrics) {\n\t\temitPlatformHostTelemetry(telemetry, {\n\t\t\tkind: \"metric\",\n\t\t\tname,\n\t\t\tmetricType: \"gauge\",\n\t\t\tvalue,\n\t\t\t...scope,\n\t\t\tobservedAt: snapshot.generatedAt,\n\t\t});\n\t}\n}\n\nfunction isPromiseLike(value: unknown): value is PromiseLike<void> {\n\treturn Boolean(\n\t\tvalue &&\n\t\ttypeof value === \"object\" &&\n\t\t\"then\" in value &&\n\t\ttypeof (value as { then?: unknown }).then === \"function\",\n\t);\n}\n","import type {\n\tActionId,\n\tActionStatus,\n} from \"@fabricorg/platform\";\nimport type {\n\tAtomicMutationPlatformHostStore,\n\tErrorTextRedactionContext,\n\tGovernancePlatformHostStore,\n\tPlatformHostOptions,\n} from \"./types\";\nimport { emitPlatformHostTelemetry, PLATFORM_HOST_METRIC_NAMES } from \"./observability\";\n\n// Helpers the host and its lifecycle modules share. Nothing here is public.\n\nexport function asAtomicMutationStore<TDb>(\n\tstore: PlatformHostOptions<TDb>[\"store\"],\n): AtomicMutationPlatformHostStore<TDb> | undefined {\n\tconst candidate = store as Partial<AtomicMutationPlatformHostStore<TDb>>;\n\treturn typeof candidate.transactionWithEvents === \"function\"\n\t\t? (store as AtomicMutationPlatformHostStore<TDb>)\n\t\t: undefined;\n}\n\nexport function asGovernanceStore<TDb>(\n\tstore: PlatformHostOptions<TDb>[\"store\"],\n): GovernancePlatformHostStore<TDb> | undefined {\n\tconst candidate = store as Partial<GovernancePlatformHostStore<TDb>>;\n\treturn typeof candidate.recordMutationGovernance === \"function\" &&\n\t\ttypeof candidate.appendPolicyObligations === \"function\" &&\n\t\ttypeof candidate.appendExecutionAttestation === \"function\"\n\t\t? (store as GovernancePlatformHostStore<TDb>)\n\t\t: undefined;\n}\n\nexport function withoutPrivateHostFields(\n\tdata: Record<string, unknown>,\n\teventResultFields: readonly string[],\n): Record<string, unknown> {\n\treturn Object.fromEntries(\n\t\tObject.entries(data).filter(([key]) => !eventResultFields.includes(key)),\n\t);\n}\n\nexport function errorMessage(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n\n/** Marks Host-authored error text so a catch does not redact its identifiers. */\nexport class HostError extends Error {}\n\n/** The record predicate used for adapter output construction and redactor returns. */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n\treturn Boolean(value && typeof value === \"object\" && !Array.isArray(value));\n}\n\nexport function tryRedactErrorText(\n\thook: PlatformHostOptions<unknown>[\"redactErrorText\"],\n\tcontext: ErrorTextRedactionContext,\n\tmessage: string,\n): { success: true; text: string } | { success: false } {\n\t// Preserve the no-hook behavior for empty originating errors without invoking the hook.\n\tif (!hook || message === \"\") return { success: true, text: message };\n\ttry {\n\t\tconst text = hook(context, message);\n\t\tif (typeof text === \"string\" && text.length > 0) return { success: true, text };\n\t} catch {\n\t\t// A completion can refuse this input; execution paths need a safe placeholder.\n\t}\n\treturn { success: false };\n}\n\nexport function redactErrorText(\n\thook: PlatformHostOptions<unknown>[\"redactErrorText\"],\n\tcontext: ErrorTextRedactionContext,\n\tmessage: string,\n): string {\n\tconst result = tryRedactErrorText(hook, context, message);\n\treturn result.success ? result.text : \"Error text withheld: the error-text redactor failed.\";\n}\n\nexport function lifecycleId(prefix: string, invocationId: string, key: string): string {\n\tconst safeKey = key.replace(/[^a-zA-Z0-9_-]/g, \"_\").slice(0, 96);\n\treturn `${prefix}_${invocationId}_${safeKey}`;\n}\n\nexport function emitInvocationStatusTelemetry(\n\tinvocation: {\n\t\tid: string;\n\t\ttenantId: string;\n\t\tspaceId: string;\n\t\tactionId?: ActionId;\n\t\tactionVersion?: number;\n\t},\n\tstatus: ActionStatus | undefined,\n\ttelemetry: PlatformHostOptions<unknown>[\"telemetry\"],\n\toccurredAt: Date,\n\tpreviousStatus?: ActionStatus,\n): void {\n\tif (!status || status === previousStatus) return;\n\tconst event = status === \"completed\"\n\t\t? { name: \"invocation.completed\" as const, metricName: PLATFORM_HOST_METRIC_NAMES.invocationCompleted }\n\t\t: status === \"blocked_by_policy\"\n\t\t\t? { name: \"invocation.policy_blocked\" as const, metricName: PLATFORM_HOST_METRIC_NAMES.invocationPolicyBlocked }\n\t\t\t: status === \"validation_failed\"\n\t\t\t\t? { name: \"invocation.validation_failed\" as const, metricName: PLATFORM_HOST_METRIC_NAMES.invocationValidationFailed }\n\t\t\t\t: status === \"waiting_for_approval\"\n\t\t\t\t\t? { name: \"invocation.approval_waited\" as const, metricName: PLATFORM_HOST_METRIC_NAMES.invocationApprovalWaited }\n\t\t\t\t\t: status === \"reconciliation_required\"\n\t\t\t\t\t\t? { name: \"invocation.reconciliation_required\" as const, metricName: PLATFORM_HOST_METRIC_NAMES.invocationReconciliationRequired }\n\t\t\t\t\t\t: status === \"failed\"\n\t\t\t\t\t\t\t? { name: \"invocation.failed\" as const, metricName: PLATFORM_HOST_METRIC_NAMES.invocationFailed }\n\t\t\t\t\t\t\t: undefined;\n\tif (!event) return;\n\temitPlatformHostTelemetry(telemetry, {\n\t\tkind: \"event\",\n\t\tname: event.name,\n\t\tmetricName: event.metricName,\n\t\toccurredAt,\n\t\ttenantId: invocation.tenantId,\n\t\tspaceId: invocation.spaceId,\n\t\tattributes: {\n\t\t\t...(invocation.actionId ? { actionId: invocation.actionId } : {}),\n\t\t\t...(invocation.actionVersion !== undefined ? { actionVersion: invocation.actionVersion } : {}),\n\t\t\t...(previousStatus ? { fromStatus: previousStatus } : {}),\n\t\t},\n\t});\n}\n\nexport class RecoverableFinalizationError extends Error {\n\toverride readonly name = \"RecoverableFinalizationError\";\n}\n\n/** Completion absence is significant: callbacks may retain the same status/error. */\nexport function matchesSettledInvocation(\n\trecord: import(\"./types\").ActionInvocationRecord,\n\tcondition: Extract<import(\"./types\").AdapterInvocationWriteCondition, { kind: \"verdict\" }>,\n\tcheckCompletion = true,\n): boolean {\n\treturn ![\"pending\", \"running\", \"waiting_for_approval\"].includes(condition.status)\n\t\t&& record.status === condition.status && record.error === condition.error\n\t\t&& (!checkCompletion || (condition.externalCompletionDigest === undefined ? record.externalCompletion === undefined\n\t\t\t: record.externalCompletion?.digest === condition.externalCompletionDigest));\n}\n","import { createHash } from \"node:crypto\";\nimport type { ActionDefinition, ActionId } from \"@fabricorg/platform\";\nimport type {\n\tActionInvocationPatch,\n\tActionInvocationRecord,\n\tExecuteActionResult,\n\tExternalCompletion,\n\tPendingAssetEvent,\n\tPlatformHostMutationTransaction,\n\tPlatformHostOptions,\n\tRecordedExternalCompletion,\n\tRecoverablePlatformHostStore,\n\tReconcileOverdueCompletionsInput,\n} from \"./types\";\nimport { ExternalCompletionError } from \"./types\";\nimport { canonicalJson } from \"./command-identity\";\nimport {\n\tasAtomicMutationStore,\n\tasGovernanceStore,\n\temitInvocationStatusTelemetry,\n\tlifecycleId,\n\tHostError,\n\ttryRedactErrorText,\n\tisRecord,\n\twithoutPrivateHostFields,\n} from \"./host-internals\";\n\n// ── External completion lifecycle ───────────────────────────────────────────\n//\n// An adapter hands work to an external system that finishes it later and\n// calls back. This module owns everything after the handoff is recorded:\n// settling the invocation by reference, absorbing repeats, catching\n// contradictions, surfacing overdue handoffs. The host's adapter loop owns\n// the handoff itself, since that happens mid-execution. What is shared with\n// the host is passed in, so the host stays the only thing that writes\n// invocations through a lease.\n\nexport interface ExternalCompletionDeps<TDb> {\n\tstore: PlatformHostOptions<TDb>[\"store\"];\n\ttelemetry: PlatformHostOptions<TDb>[\"telemetry\"];\n\tredactErrorText?: PlatformHostOptions<TDb>[\"redactErrorText\"];\n\tredactExternalCompletionResult?: PlatformHostOptions<TDb>[\"redactExternalCompletionResult\"];\n\teventResultFields: readonly string[];\n\tnow(): Date;\n\tactionResolver(actionId: ActionId): ActionDefinition<TDb> | undefined;\n\tappendEvent(\n\t\tinvocation: ActionInvocationRecord,\n\t\tevent: PendingAssetEvent,\n\t\tdeduplicationKey: string,\n\t\tdefaultEventSchemaVersion?: number,\n\t\ttransaction?: PlatformHostMutationTransaction<TDb>,\n\t): Promise<void>;\n\tactionResult(invocation: ActionInvocationRecord): ExecuteActionResult;\n\twithConsistency<TResult extends { actionInvocationId: string }>(result: TResult, actionId: ActionId): TResult;\n}\n\nexport interface ExternalCompletionLifecycle {\n\tcompleteExternalInvocation(actionInvocationId: string, tenantId: string, spaceId: string, completion: ExternalCompletion): Promise<ExecuteActionResult>;\n\treconcileOverdueCompletions(input?: ReconcileOverdueCompletionsInput): Promise<{ overdue: string[] }>;\n\trecordCompletionReconciliation(\n\t\tinvocation: ActionInvocationRecord,\n\t\tcompletion: Pick<ExternalCompletion, \"externalReference\" | \"evidenceReferences\"> & { provider?: string; kind?: string },\n\t\treason: string,\n\t\ttransaction?: Pick<PlatformHostMutationTransaction<unknown>, \"appendExternalReconciliation\">,\n\t): Promise<void>;\n}\n\nexport function createExternalCompletionLifecycle<TDb>(deps: ExternalCompletionDeps<TDb>): ExternalCompletionLifecycle {\n\tconst { now, actionResolver, appendEvent, actionResult, withConsistency, eventResultFields } = deps;\n\n\tasync function completeExternalInvocation(\n\t\tactionInvocationId: string,\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t\tcompletion: ExternalCompletion,\n\t): Promise<ExecuteActionResult> {\n\t\tif (typeof completion.externalReference !== \"string\" || completion.externalReference.trim() === \"\") {\n\t\t\tthrow new ExternalCompletionError(\"invalid_completion\", \"External completion must name the external reference it completes.\");\n\t\t}\n\t\tif (completion.outcome !== \"completed\" && completion.outcome !== \"failed\") {\n\t\t\tthrow new ExternalCompletionError(\"invalid_completion\", `External completion outcome must be \"completed\" or \"failed\", received \"${String(completion.outcome)}\".`);\n\t\t}\n\t\t// Read, decide, and write under one lock where the store can give one,\n\t\t// so two callbacks racing cannot both read \"nothing recorded yet\" and\n\t\t// both write. A base store without transactions keeps the narrower\n\t\t// read-then-write window; that is a property of the store, not of this\n\t\t// path, and the contract documents it.\n\t\tconst atomicStore = asAtomicMutationStore(deps.store);\n\t\tif (atomicStore) {\n\t\t\treturn atomicStore.transactionWithEvents(async (transaction) => {\n\t\t\t\tconst read = transaction.getActionInvocationForUpdate\n\t\t\t\t\t? await transaction.getActionInvocationForUpdate(actionInvocationId, tenantId, spaceId)\n\t\t\t\t\t: await deps.store.getActionInvocation(actionInvocationId, tenantId, spaceId);\n\t\t\t\treturn settleExternalCompletion(read, actionInvocationId, completion, {\n\t\t\t\t\tupdate: (patch) => transaction.updateActionInvocation(actionInvocationId, tenantId, spaceId, patch),\n\t\t\t\t\ttransaction,\n\t\t\t\t});\n\t\t\t});\n\t\t}\n\t\tconst read = await deps.store.getActionInvocation(actionInvocationId, tenantId, spaceId);\n\t\treturn settleExternalCompletion(read, actionInvocationId, completion, {\n\t\t\tupdate: (patch) => deps.store.updateActionInvocation(actionInvocationId, tenantId, spaceId, patch),\n\t\t});\n\t}\n\n\tasync function settleExternalCompletion(\n\t\tinvocation: ActionInvocationRecord | undefined,\n\t\tactionInvocationId: string,\n\t\tcompletion: ExternalCompletion,\n\t\twriter: {\n\t\t\tupdate: (patch: ActionInvocationPatch) => Promise<void>;\n\t\t\ttransaction?: PlatformHostMutationTransaction<TDb>;\n\t\t},\n\t): Promise<ExecuteActionResult> {\n\t\tif (!invocation) throw new ExternalCompletionError(\"not_found\", `ActionInvocation not found: ${actionInvocationId}`);\n\t\tconst recorded = invocation.externalCompletion;\n\t\tconst stillExecuting = !recorded && (\n\t\t\tinvocation.status === \"pending\"\n\t\t\t|| (invocation.status === \"running\" && (invocation.leaseOwner !== undefined || invocation.pendingCompletion?.parkedAt === undefined))\n\t\t);\n\t\tif (stillExecuting) {\n\t\t\t// The invocation has not parked: it is dispatched and not yet run, a\n\t\t\t// worker still holds it, or an inline execution recorded the handoff\n\t\t\t// and is still running the steps after it. Settling now would report\n\t\t\t// completed while effects are still being applied, and finalization\n\t\t\t// would then overwrite the verdict. The handoff is recorded before\n\t\t\t// the steps after it run, so \"not awaiting\" here means \"not yet\".\n\t\t\t// Callbacks arrive at least once; this one is asked to come back.\n\t\t\tthrow new ExternalCompletionError(\"still_executing\", `ActionInvocation ${actionInvocationId} is still executing; retry the completion after it parks.`);\n\t\t}\n\t\tif (recorded) {\n\t\t\tif (recorded.externalReference !== completion.externalReference) {\n\t\t\t\tthrow new ExternalCompletionError(\"reference_mismatch\", `ActionInvocation ${actionInvocationId} was completed by \"${recorded.externalReference}\", not \"${completion.externalReference}\".`);\n\t\t\t}\n\t\t\tif (completion.provider !== undefined && recorded.provider !== undefined && completion.provider !== recorded.provider) {\n\t\t\t\tthrow new ExternalCompletionError(\"provider_mismatch\", `ActionInvocation ${actionInvocationId} was completed by \"${recorded.provider}\", not \"${completion.provider}\".`);\n\t\t\t}\n\t\t\tconst provider = recorded.provider ?? completion.provider;\n\t\t\t// Compute the legacy comparison before hooks can modify their input. It stays in memory.\n\t\t\tconst rawDigest = completionDigest(completion, provider);\n\t\t\tif (recorded.digest === rawDigest) return withConsistency(actionResult(invocation), invocation.actionId);\n\t\t\tcompletion = redactCompletion(invocation, completion, provider ?? \"external\");\n\t\t\tconst incomingDigest = completionDigest(completion, provider);\n\t\t\tif (recorded.digest === incomingDigest) {\n\t\t\t\t// The same news twice. Callbacks are at-least-once; this is the once.\n\t\t\t\treturn withConsistency(actionResult(invocation), invocation.actionId);\n\t\t\t}\n\t\t\t// The external system contradicted itself, by flipping the outcome or\n\t\t\t// by reporting the same outcome with different evidence. Neither\n\t\t\t// answer can be trusted over the other, so the first stays on\n\t\t\t// record, the second goes to the reconciliation log, and consumers\n\t\t\t// hear about it.\n\t\t\tconst message = recorded.outcome === completion.outcome\n\t\t\t\t? `External operation \"${completion.externalReference}\" reported ${completion.outcome} again with different evidence.`\n\t\t\t\t: `External operation \"${completion.externalReference}\" reported ${completion.outcome} after reporting ${recorded.outcome}.`;\n\t\t\tawait recordCompletionReconciliation(invocation, { ...completion, kind: `contradicted:${incomingDigest.slice(0, 16)}` }, message);\n\t\t\tawait appendEvent(invocation, {\n\t\t\t\teventType: \"ExternalOperationContradicted\",\n\t\t\t\tsubjectType: \"AdapterInvocation\",\n\t\t\t\tsubjectId: invocation.pendingCompletion?.adapterInvocationId ?? actionInvocationId,\n\t\t\t\tpayload: { externalReference: completion.externalReference, recorded: recorded.outcome, reported: completion.outcome },\n\t\t\t}, `external:${completion.externalReference}:contradicted:${completion.outcome}`, 1, writer.transaction);\n\t\t\tawait writer.update({ status: \"reconciliation_required\", error: message });\n\t\t\temitInvocationStatusTelemetry(invocation, \"reconciliation_required\", deps.telemetry, now(), invocation.status);\n\t\t\treturn withConsistency(actionResult({ ...invocation, status: \"reconciliation_required\", error: message }), invocation.actionId);\n\t\t}\n\t\tconst pending = invocation.pendingCompletion;\n\t\tif (!pending) {\n\t\t\tconst action = actionResolver(invocation.actionId);\n\t\t\tif ((action?.execution?.completion ?? \"immediate\") === \"immediate\") {\n\t\t\t\tthrow new ExternalCompletionError(\"immediate_contract\", `Action ${invocation.actionId} declares immediate completion; nothing external completes it.`);\n\t\t\t}\n\t\t\tthrow new ExternalCompletionError(\"not_awaiting\", `ActionInvocation ${actionInvocationId} is not awaiting an external completion.`);\n\t\t}\n\t\tif (pending.externalReference !== completion.externalReference) {\n\t\t\tthrow new ExternalCompletionError(\"reference_mismatch\", `ActionInvocation ${actionInvocationId} awaits \"${pending.externalReference}\", not \"${completion.externalReference}\".`);\n\t\t}\n\t\tif (completion.provider !== undefined && completion.provider !== pending.provider) {\n\t\t\tthrow new ExternalCompletionError(\"provider_mismatch\", `ActionInvocation ${actionInvocationId} awaits completion from \"${pending.provider}\", not \"${completion.provider}\".`);\n\t\t}\n\t\tcompletion = redactCompletion(invocation, completion, completion.provider ?? pending.provider);\n\t\tconst recordedAt = now();\n\t\tconst externalCompletion: RecordedExternalCompletion = {\n\t\t\t// completion has passed the hooks; retain the callback shape for compatibility.\n\t\t\t...completion,\n\t\t\tprovider: completion.provider ?? pending.provider,\n\t\t\tobservedAt: completion.observedAt instanceof Date ? completion.observedAt.toISOString() : completion.observedAt,\n\t\t\trecordedAt,\n\t\t\tdigest: completionDigest(completion, completion.provider ?? pending.provider),\n\t\t};\n\t\tconst subject = { subjectType: \"AdapterInvocation\", subjectId: pending.adapterInvocationId };\n\t\t// Callback adapter writes share the invocation lock and transaction when\n\t\t// its adapter seam is available; legacy stores retain the outer write.\n\t\t// A parked invocation settles by the outcome. One that already ended for\n\t\t// another reason (a later step failed, a contract was violated, a\n\t\t// non-overdue reconciliation was required) keeps its status. The callback\n\t\t// records what happened externally without replacing that verdict.\n\t\tconst settles = (invocation.status === \"running\" && pending.parkedAt !== undefined)\n\t\t\t|| (invocation.status === \"reconciliation_required\" && pending.parkedAt !== undefined\n\t\t\t\t&& (pending.overdueAt !== undefined\n\t\t\t\t\t// 7.x had no typed marker. This weaker compatibility check also\n\t\t\t\t\t// accepts unrelated error text on any parked row lacking the marker.\n\t\t\t\t\t|| invocation.error?.includes(\"did not complete by\") === true));\n\t\tif (completion.outcome === \"completed\") {\n\t\t\tconst action = settles ? actionResolver(invocation.actionId) : undefined;\n\t\t\tconst merged = withoutPrivateHostFields({ ...invocation.result, ...(completion.result ?? {}) }, eventResultFields);\n\t\t\tif (settles && action?.resultSchema) {\n\t\t\t\tconst parsedResult = action.resultSchema.safeParse(merged);\n\t\t\t\tif (!parsedResult.success) {\n\t\t\t\t\tthrow new ExternalCompletionError(\"result_invalid\", `External completion result validation failed at ${parsedResult.error.issues\n\t\t\t\t\t\t.map((issue) => issue.path.map(String).join(\".\") || \"result\")\n\t\t\t\t\t\t.join(\", \")}`);\n\t\t\t\t}\n\t\t\t}\n\t\t\tawait (writer.transaction?.updateAdapterInvocation?.bind(writer.transaction) ?? deps.store.updateAdapterInvocation.bind(deps.store))(pending.adapterInvocationId, {\n\t\t\t\t...(completion.result ? { output: withoutPrivateHostFields(completion.result, eventResultFields) } : {}),\n\t\t\t\tupdatedAt: recordedAt,\n\t\t\t}, { tenantId: invocation.tenantId, spaceId: invocation.spaceId, actionInvocationId: invocation.id });\n\t\t\tawait appendEvent(invocation, {\n\t\t\t\teventType: \"ExternalOperationCompleted\",\n\t\t\t\t...subject,\n\t\t\t\tpayload: { externalReference: pending.externalReference, provider: pending.provider, ...(completion.result ? { result: withoutPrivateHostFields(completion.result, eventResultFields) } : {}) },\n\t\t\t}, `external:${pending.adapterInvocationId}:completed`, 1, writer.transaction);\n\t\t\tconst patch: ActionInvocationPatch = settles\n\t\t\t\t? { status: \"completed\", result: merged, externalCompletion, pendingCompletion: undefined, error: undefined }\n\t\t\t\t: { externalCompletion, pendingCompletion: undefined };\n\t\t\tawait writer.update(patch);\n\t\t\tif (settles) emitInvocationStatusTelemetry(invocation, \"completed\", deps.telemetry, now(), invocation.status);\n\t\t\treturn withConsistency(actionResult({ ...invocation, ...patch, result: settles ? merged : invocation.result, ...(settles ? { error: undefined } : {}) }), invocation.actionId);\n\t\t}\n\t\tconst error = completion.error ?? `External operation \"${pending.externalReference}\" failed.`;\n\t\tawait (writer.transaction?.updateAdapterInvocation?.bind(writer.transaction) ?? deps.store.updateAdapterInvocation.bind(deps.store))(pending.adapterInvocationId, { status: \"failed\", error, updatedAt: recordedAt }, { tenantId: invocation.tenantId, spaceId: invocation.spaceId, actionInvocationId: invocation.id });\n\t\tawait appendEvent(invocation, {\n\t\t\teventType: \"ExternalOperationFailed\",\n\t\t\t...subject,\n\t\t\tpayload: { externalReference: pending.externalReference, provider: pending.provider, error },\n\t\t}, `external:${pending.adapterInvocationId}:failed`, 1, writer.transaction);\n\t\tconst patch: ActionInvocationPatch = settles\n\t\t\t? { status: \"failed\", error, externalCompletion, pendingCompletion: undefined }\n\t\t\t: { externalCompletion, pendingCompletion: undefined };\n\t\tawait writer.update(patch);\n\t\tif (settles) emitInvocationStatusTelemetry(invocation, \"failed\", deps.telemetry, now(), invocation.status);\n\t\treturn withConsistency(actionResult({ ...invocation, ...patch }), invocation.actionId);\n\t}\n\n\tfunction redactCompletion(invocation: ActionInvocationRecord, completion: ExternalCompletion, provider: string): ExternalCompletion {\n\t\tlet result = completion.result;\n\t\tif (result && deps.redactExternalCompletionResult) {\n\t\t\ttry {\n\t\t\t\tresult = deps.redactExternalCompletionResult(invocation.actionId, provider, result);\n\t\t\t\tif (!isRecord(result)) throw new HostError(\"Completion result redactor must return a non-null, non-array object.\");\n\t\t\t} catch {\n\t\t\t\tthrow new ExternalCompletionError(\"redaction_failed\", \"External completion result withheld: the result redactor failed; nothing was recorded.\");\n\t\t\t}\n\t\t}\n\t\tconst error = completion.error == null ? undefined : tryRedactErrorText(deps.redactErrorText,\n\t\t\t{ actionId: invocation.actionId, source: \"external_completion\", provider }, completion.error);\n\t\tif (error && !error.success) {\n\t\t\tthrow new ExternalCompletionError(\"redaction_failed\", \"External completion error withheld: the error-text redactor failed; nothing was recorded.\");\n\t\t}\n\t\treturn {\n\t\t\t...completion,\n\t\t\t...(completion.result !== undefined ? { result } : {}),\n\t\t\t...(error?.success ? { error: error.text } : {}),\n\t\t};\n\t}\n\n\t/** What a completion says, minus when it was said. */\n\tfunction completionDigest(completion: ExternalCompletion, provider: string | undefined): string {\n\t\treturn createHash(\"sha256\").update(canonicalJson({\n\t\t\tprovider: provider ?? null,\n\t\t\texternalReference: completion.externalReference,\n\t\t\toutcome: completion.outcome,\n\t\t\tresult: completion.result ?? null,\n\t\t\terror: completion.error ?? null,\n\t\t\tevidenceReferences: completion.evidenceReferences ?? null,\n\t\t})).digest(\"hex\");\n\t}\n\n\tasync function recordCompletionReconciliation(\n\t\tinvocation: ActionInvocationRecord,\n\t\tcompletion: Pick<ExternalCompletion, \"externalReference\" | \"evidenceReferences\"> & { provider?: string; kind?: string },\n\t\treason: string,\n\t\ttransaction?: Pick<PlatformHostMutationTransaction<unknown>, \"appendExternalReconciliation\">,\n\t): Promise<void> {\n\t\tconst governanceStore = asGovernanceStore(deps.store);\n\t\tif (!governanceStore) throw new HostError(\"External completion reconciliation requires a governance-capable store.\");\n\t\tconst provider = completion.provider ?? invocation.pendingCompletion?.provider ?? invocation.externalCompletion?.provider ?? \"external\";\n\t\t// Deterministic, and hashed so a long vendor reference cannot truncate\n\t\t// two distinct findings into one id.\n\t\tconst seed = createHash(\"sha256\").update(`${provider}\\u0000${completion.externalReference}\\u0000${completion.kind ?? \"refused\"}`).digest(\"hex\").slice(0, 32);\n\t\tconst writer = transaction?.appendExternalReconciliation ? transaction : governanceStore;\n\t\tawait writer.appendExternalReconciliation!({\n\t\t\tid: lifecycleId(\"rec\", invocation.id, `ext:${seed}`),\n\t\t\tactionInvocationId: invocation.id,\n\t\t\ttenantId: invocation.tenantId,\n\t\t\tspaceId: invocation.spaceId,\n\t\t\tstatus: \"pending\",\n\t\t\tprovider,\n\t\t\texternalOperationId: completion.externalReference,\n\t\t\tattempt: 1,\n\t\t\treason,\n\t\t\t...(completion.evidenceReferences ? { evidenceReferences: completion.evidenceReferences } : {}),\n\t\t\tobservedAt: now(),\n\t\t});\n\t}\n\n\tasync function reconcileOverdueCompletions(\n\t\tinput: ReconcileOverdueCompletionsInput = {},\n\t): Promise<{ overdue: string[] }> {\n\t\tconst recoverable = deps.store as Partial<RecoverablePlatformHostStore<TDb>>;\n\t\tif (!recoverable.listActionInvocations) {\n\t\t\tthrow new HostError(\"Overdue completion reconciliation requires a store that can list invocations.\");\n\t\t}\n\t\tif (!asGovernanceStore(deps.store)) {\n\t\t\tthrow new HostError(\"Overdue completion reconciliation requires a governance-capable store to record its findings.\");\n\t\t}\n\t\tconst current = input.now ?? now();\n\t\tconst listed = await recoverable.listActionInvocations({\n\t\t\tstatuses: [\"running\"],\n\t\t\tcompletionDueBefore: current,\n\t\t\tunleased: true,\n\t\t\t...(input.tenantId ? { tenantId: input.tenantId } : {}),\n\t\t\t...(input.spaceId ? { spaceId: input.spaceId } : {}),\n\t\t\tlimit: Math.max(1, Math.min(input.limit ?? 100, 1_000)),\n\t\t});\n\t\t// Memory stores can return live records. Retain the listed handoff's\n\t\t// identity before waiting on a transaction or another candidate.\n\t\tconst candidates = listed.map((invocation) => ({\n\t\t\t...invocation,\n\t\t\tpendingCompletion: invocation.pendingCompletion ? { ...invocation.pendingCompletion } : undefined,\n\t\t}));\n\t\tconst overdue: string[] = [];\n\t\tconst atomicStore = asAtomicMutationStore(deps.store);\n\t\tlet canLock: boolean | undefined;\n\t\tfor (const candidate of candidates) {\n\t\t\tconst reconcile = async (transaction?: PlatformHostMutationTransaction<TDb>): Promise<boolean> => {\n\t\t\t\tconst invocation = transaction?.getActionInvocationForUpdate\n\t\t\t\t\t? await transaction.getActionInvocationForUpdate(candidate.id, candidate.tenantId, candidate.spaceId)\n\t\t\t\t\t: await deps.store.getActionInvocation(candidate.id, candidate.tenantId, candidate.spaceId);\n\t\t\t\tconst pending = invocation?.pendingCompletion;\n\t\t\t\tif (!invocation || invocation.status !== \"running\" || invocation.leaseOwner != null\n\t\t\t\t\t|| !pending?.dueAt || pending.dueAt.getTime() > current.getTime() || pending.overdueAt !== undefined\n\t\t\t\t\t|| pending.adapterInvocationId !== candidate.pendingCompletion?.adapterInvocationId\n\t\t\t\t\t|| pending.externalReference !== candidate.pendingCompletion?.externalReference) return false;\n\t\t\t\t// Unparked rows can be abandoned inline executions. Surface them,\n\t\t\t\t// but retain the absence of parkedAt so callbacks remain evidence-only.\n\t\t\t\tconst message = `External operation \"${pending.externalReference}\" from ${pending.provider} did not complete by ${pending.dueAt.toISOString()}.`;\n\t\t\t\tawait recordCompletionReconciliation(invocation, { externalReference: pending.externalReference, provider: pending.provider, kind: \"overdue\" }, message, transaction);\n\t\t\t\tawait (transaction ?? deps.store).updateActionInvocation(invocation.id, invocation.tenantId, invocation.spaceId, {\n\t\t\t\t\tstatus: \"reconciliation_required\", error: message, pendingCompletion: { ...pending, overdueAt: current },\n\t\t\t\t});\n\t\t\t\treturn true;\n\t\t\t};\n\t\t\tconst lockedResult = atomicStore && canLock !== false\n\t\t\t\t? await atomicStore.transactionWithEvents((transaction) => {\n\t\t\t\t\tcanLock = !!(transaction.getActionInvocationForUpdate && transaction.updateActionInvocation);\n\t\t\t\t\tif (!canLock) return Promise.resolve(undefined);\n\t\t\t\t\treturn reconcile(transaction);\n\t\t\t\t})\n\t\t\t\t: undefined;\n\t\t\tconst reconciled = lockedResult ?? await reconcile();\n\t\t\tif (reconciled) {\n\t\t\t\toverdue.push(candidate.id);\n\t\t\t\temitInvocationStatusTelemetry(candidate, \"reconciliation_required\", deps.telemetry, now(), \"running\");\n\t\t\t}\n\t\t}\n\t\treturn { overdue };\n\t}\n\n\n\treturn { completeExternalInvocation, reconcileOverdueCompletions, recordCompletionReconciliation };\n}\n","import { types as utilTypes } from \"node:util\";\nimport type { ActionId } from \"@fabricorg/platform\";\nimport type { AuthorizationBinding, InvocationProvenance, SubmitActionInput } from \"./types\";\n\n/*\n * The one read of a caller's `SubmitActionInput` scalar fields.\n * `submitAction` calls `snapshotSubmission` before its first await and reads\n * only the result afterwards, so nothing the caller changes on its object\n * while Host awaits entitlement, `authorize`, a composition callback or an\n * admission check changes the action, scope, actor, correlation, causation,\n * idempotency key, binding id or execution reason Host authorizes, persists\n * or executes.\n *\n * `parameters`, `provenance` and `authorizationBinding` depend on the action.\n * For one that declares `admitSubmission`, `privateSubmission` reads each\n * once, also before the first await, and replaces it with Host's own copy.\n * For every other action they are not snapshotted: the snapshot's fields\n * read the caller's input each time Host reads them, at the points and as\n * often as Host read them before this snapshot existed (README, \"Submission\n * snapshot\").\n *\n * Internal: not exported from the package entry.\n */\n\n/** Thrown when a submission field cannot be read; the message is fixed. */\nexport class SubmissionUnreadableError extends Error {\n\toverride readonly name = \"SubmissionUnreadableError\";\n\tconstructor() {\n\t\tsuper(\"Platform Host submission could not be read as plain data; nothing was recorded.\");\n\t}\n}\n\n/**\n * Everything `submitAction` uses from a submission. The scalar fields are\n * primitives read once. `parameters`, `provenance` and `authorizationBinding`\n * read through to the caller's input (`snapshotSubmission`) until\n * `privateSubmission` replaces them with Host's copies.\n */\nexport interface SubmissionSnapshot {\n\treadonly actionId: ActionId;\n\treadonly tenantId: string;\n\treadonly spaceId: string;\n\treadonly actorId: string;\n\treadonly actorType: SubmitActionInput[\"actorType\"];\n\treadonly correlationId?: string;\n\treadonly causationId?: string;\n\treadonly provenance?: InvocationProvenance;\n\treadonly executionReason?: SubmitActionInput[\"executionReason\"];\n\treadonly idempotencyKey?: string;\n\treadonly authorizationBindingId?: string;\n\treadonly authorizationBinding?: AuthorizationBinding;\n\treadonly parameters: Record<string, unknown>;\n\t/** True when `parameters` is Host's own JSON-data copy (`privateSubmission`, when the copy succeeded). */\n\treadonly parametersArePrivate: boolean;\n}\n\ntype Scalars = Omit<SubmissionSnapshot, \"provenance\" | \"authorizationBinding\" | \"parameters\" | \"parametersArePrivate\">;\n\nclass NotJsonData extends Error {}\n\n/** `{ ok: true, value }` with a private copy, or `{ ok: false }` when `value` is not JSON data or a read threw. */\nexport type JsonDataCopy = { readonly ok: true; readonly value: unknown } | { readonly ok: false };\n\n/**\n * Copy a JSON value into fresh objects and arrays that nothing else holds.\n *\n * Accepted: `null`, strings, booleans, finite numbers (`-0` becomes `0`, as\n * JSON text does), dense arrays whose prototype is `Array.prototype`, and\n * objects whose prototype is `Object.prototype` or `null`. Of an object, the\n * own enumerable string-keyed properties are copied, each read exactly once\n * (a getter runs once); a property whose value is `undefined` is left out,\n * as `JSON.stringify` and the PostgreSQL store's `jsonb` column do. Symbol\n * keys and non-enumerable properties are skipped, as `JSON.stringify` skips\n * them.\n *\n * Refused (`{ ok: false }`): Proxies (`util.types.isProxy`), every other\n * prototype (Date, Map, class instances, boxed primitives, ArrayBuffer,\n * SharedArrayBuffer, typed arrays and DataView among them), functions,\n * symbols, bigints, non-finite numbers, array holes and `undefined` array\n * elements, cycles, nesting deep enough to exhaust the stack, and any read\n * that throws. What a read throws is not kept.\n */\nexport function copyJsonData(value: unknown): JsonDataCopy {\n\ttry {\n\t\treturn { ok: true, value: copy(value, new Set()) };\n\t} catch {\n\t\treturn { ok: false };\n\t}\n}\n\nfunction copy(value: unknown, ancestors: Set<object>): unknown {\n\tif (value === null || typeof value === \"string\" || typeof value === \"boolean\") return value;\n\tif (typeof value === \"number\") {\n\t\tif (!Number.isFinite(value)) throw new NotJsonData();\n\t\treturn value === 0 ? 0 : value;\n\t}\n\tif (typeof value !== \"object\") throw new NotJsonData();\n\t// Checked first: every read below (prototype, keys, descriptors) would\n\t// otherwise run the Proxy's traps.\n\tif (utilTypes.isProxy(value)) throw new NotJsonData();\n\tif (ancestors.has(value)) throw new NotJsonData();\n\tconst prototype = Reflect.getPrototypeOf(value);\n\tancestors.add(value);\n\ttry {\n\t\tif (Array.isArray(value)) {\n\t\t\tif (prototype !== Array.prototype) throw new NotJsonData();\n\t\t\tconst length = value.length;\n\t\t\tconst out: unknown[] = [];\n\t\t\tfor (let index = 0; index < length; index += 1) {\n\t\t\t\tconst descriptor = Reflect.getOwnPropertyDescriptor(value, String(index));\n\t\t\t\tif (descriptor === undefined) throw new NotJsonData();\n\t\t\t\tconst item = readOnce(value, descriptor);\n\t\t\t\tif (item === undefined) throw new NotJsonData();\n\t\t\t\tout.push(copy(item, ancestors));\n\t\t\t}\n\t\t\treturn out;\n\t\t}\n\t\tif (prototype !== Object.prototype && prototype !== null) throw new NotJsonData();\n\t\tconst out: Record<string, unknown> = {};\n\t\tfor (const key of Reflect.ownKeys(value)) {\n\t\t\tif (typeof key !== \"string\") continue;\n\t\t\tconst descriptor = Reflect.getOwnPropertyDescriptor(value, key);\n\t\t\tif (descriptor === undefined || descriptor.enumerable !== true) continue;\n\t\t\tconst item = readOnce(value, descriptor);\n\t\t\tif (item === undefined) continue;\n\t\t\t// defineProperty, not assignment, so a \"__proto__\" key stays an own property.\n\t\t\tReflect.defineProperty(out, key, { value: copy(item, ancestors), enumerable: true, writable: true, configurable: true });\n\t\t}\n\t\treturn out;\n\t} finally {\n\t\tancestors.delete(value);\n\t}\n}\n\nfunction readOnce(target: object, descriptor: PropertyDescriptor): unknown {\n\tif (\"value\" in descriptor) return descriptor.value;\n\treturn descriptor.get ? Reflect.apply(descriptor.get, target, []) : undefined;\n}\n\n/**\n * Read a submission's scalar fields once, in a fixed order. A scalar field\n * must hold a primitive (or be absent); one holding an object, a function or\n * a symbol, a read that throws, or an input that is not an object throws\n * `SubmissionUnreadableError`. None of these can happen for input of the\n * declared types. `parameters`, `provenance` and `authorizationBinding` are\n * not read here: the snapshot's fields of those names read the caller's\n * input each time they are read.\n */\nexport function snapshotSubmission(input: SubmitActionInput): SubmissionSnapshot {\n\tif (input === null || typeof input !== \"object\") throw new SubmissionUnreadableError();\n\tconst scalar = (key: keyof SubmitActionInput): unknown => primitiveOrAbsent(readField(input, key));\n\tconst actionId = scalar(\"actionId\");\n\tconst tenantId = scalar(\"tenantId\");\n\tconst spaceId = scalar(\"spaceId\");\n\tconst actorId = scalar(\"actorId\");\n\tconst actorType = scalar(\"actorType\");\n\tconst correlationId = scalar(\"correlationId\");\n\tconst causationId = scalar(\"causationId\");\n\tconst executionReason = scalar(\"executionReason\");\n\tconst idempotencyKey = scalar(\"idempotencyKey\");\n\tconst authorizationBindingId = scalar(\"authorizationBindingId\");\n\tconst scalars: Scalars = {\n\t\tactionId: actionId as ActionId,\n\t\ttenantId: tenantId as string,\n\t\tspaceId: spaceId as string,\n\t\tactorId: actorId as string,\n\t\tactorType: actorType as SubmitActionInput[\"actorType\"],\n\t\t...(correlationId != null ? { correlationId: correlationId as string } : {}),\n\t\t...(causationId != null ? { causationId: causationId as string } : {}),\n\t\t...(executionReason != null ? { executionReason: executionReason as SubmitActionInput[\"executionReason\"] } : {}),\n\t\t...(idempotencyKey != null ? { idempotencyKey: idempotencyKey as string } : {}),\n\t\t...(authorizationBindingId != null ? { authorizationBindingId: authorizationBindingId as string } : {}),\n\t};\n\tconst live = { ...scalars, parametersArePrivate: false } as SubmissionSnapshot;\n\t// Read through, not copied: the previous Host's reads of these fields,\n\t// unchanged for an action without admitSubmission.\n\tObject.defineProperties(live, {\n\t\tparameters: { get: () => input.parameters, enumerable: true },\n\t\tprovenance: { get: () => input.provenance, enumerable: true },\n\t\tauthorizationBinding: { get: () => input.authorizationBinding, enumerable: true },\n\t});\n\treturn Object.freeze(live);\n}\n\nconst PROVENANCE_SCALARS = [\"source\", \"correlationId\", \"causationId\"] as const;\nconst PROVENANCE_ATTRIBUTES = [\"traceAttributes\", \"auditAttributes\"] as const;\nconst BINDING_FIELDS = [\"id\", \"tenantId\", \"actorId\", \"actionId\", \"parameterDigest\", \"resourceScope\", \"capturedAt\", \"expiresAt\", \"governingMoment\"] as const;\n\n/**\n * The snapshot of a submission to an action that declares\n * `admitSubmission`, with Host's own copies of what the caller could still\n * reach. Reads each of the caller's `parameters`, `provenance` and\n * `authorizationBinding` exactly once. The parameters are copied with\n * `copyJsonData`; when that fails, the caller's object is kept,\n * `parametersArePrivate` stays false, and `submitAction` refuses the\n * submission as `invalid_parameters`. `provenance` and `authorizationBinding`\n * are copied field by field: each declared field is read once (an own or\n * inherited property, a getter included, so a class instance is accepted)\n * and undeclared fields are not copied; a scalar field must hold a\n * primitive, an attribute map must be an object whose own enumerable values\n * are primitives, and a read that throws, or anything else, throws\n * `SubmissionUnreadableError`. A falsy `provenance` or binding is absent.\n */\nexport function privateSubmission(snapshot: SubmissionSnapshot): SubmissionSnapshot {\n\tconst parameters = readField(snapshot, \"parameters\");\n\tconst provenanceRead = readField(snapshot, \"provenance\");\n\tconst bindingRead = readField(snapshot, \"authorizationBinding\");\n\tconst copied = copyJsonData(parameters);\n\tconst provenance = provenanceRead ? copyProvenance(provenanceRead) : undefined;\n\tconst authorizationBinding = bindingRead ? copyBinding(bindingRead) : undefined;\n\treturn Object.freeze({\n\t\tactionId: snapshot.actionId,\n\t\ttenantId: snapshot.tenantId,\n\t\tspaceId: snapshot.spaceId,\n\t\tactorId: snapshot.actorId,\n\t\tactorType: snapshot.actorType,\n\t\t...(snapshot.correlationId !== undefined ? { correlationId: snapshot.correlationId } : {}),\n\t\t...(snapshot.causationId !== undefined ? { causationId: snapshot.causationId } : {}),\n\t\t...(snapshot.executionReason !== undefined ? { executionReason: snapshot.executionReason } : {}),\n\t\t...(snapshot.idempotencyKey !== undefined ? { idempotencyKey: snapshot.idempotencyKey } : {}),\n\t\t...(snapshot.authorizationBindingId !== undefined ? { authorizationBindingId: snapshot.authorizationBindingId } : {}),\n\t\t...(provenance ? { provenance } : {}),\n\t\t...(authorizationBinding ? { authorizationBinding } : {}),\n\t\tparameters: (copied.ok ? copied.value : parameters) as Record<string, unknown>,\n\t\tparametersArePrivate: copied.ok,\n\t});\n}\n\nfunction readField(target: object, key: string): unknown {\n\ttry {\n\t\treturn (target as Record<string, unknown>)[key];\n\t} catch {\n\t\tthrow new SubmissionUnreadableError();\n\t}\n}\n\nfunction primitiveOrAbsent(value: unknown): unknown {\n\tif (value !== null && (typeof value === \"object\" || typeof value === \"function\" || typeof value === \"symbol\")) {\n\t\tthrow new SubmissionUnreadableError();\n\t}\n\treturn value;\n}\n\nfunction objectOf(value: unknown): object {\n\tif (value === null || typeof value !== \"object\") throw new SubmissionUnreadableError();\n\treturn value;\n}\n\nfunction copyFields(source: object, fields: readonly string[]): Record<string, unknown> {\n\tconst out: Record<string, unknown> = {};\n\tfor (const field of fields) {\n\t\tconst value = primitiveOrAbsent(readField(source, field));\n\t\tif (value !== undefined) out[field] = value;\n\t}\n\treturn out;\n}\n\nfunction copyAttributes(source: object, field: string): Record<string, string> | undefined {\n\tconst value = readField(source, field);\n\tif (value === undefined || value === null) return undefined;\n\tconst map = objectOf(value);\n\tlet entries: [string, unknown][];\n\ttry {\n\t\tentries = Object.entries(map);\n\t} catch {\n\t\tthrow new SubmissionUnreadableError();\n\t}\n\tconst out: Record<string, string> = {};\n\tfor (const [key, item] of entries) {\n\t\t// defineProperty, not assignment, so a \"__proto__\" key stays an own property.\n\t\tReflect.defineProperty(out, key, { value: primitiveOrAbsent(item), enumerable: true, writable: true, configurable: true });\n\t}\n\treturn out;\n}\n\nfunction copyProvenance(value: unknown): InvocationProvenance {\n\tconst source = objectOf(value);\n\tconst out = copyFields(source, PROVENANCE_SCALARS);\n\tfor (const field of PROVENANCE_ATTRIBUTES) {\n\t\tconst attributes = copyAttributes(source, field);\n\t\tif (attributes !== undefined) out[field] = attributes;\n\t}\n\treturn out as unknown as InvocationProvenance;\n}\n\nfunction copyBinding(value: unknown): AuthorizationBinding {\n\treturn copyFields(objectOf(value), BINDING_FIELDS) as unknown as AuthorizationBinding;\n}\n\n/**\n * A fresh copy of the snapshot's parameters for code that should not reach\n * the copy Host persists (the admission check, a composition callback).\n * Only for a snapshot whose parameters are Host's copy.\n */\nexport function parametersCopy(snapshot: SubmissionSnapshot): Record<string, unknown> {\n\tif (!snapshot.parametersArePrivate) throw new SubmissionUnreadableError();\n\tconst copied = copyJsonData(snapshot.parameters);\n\tif (!copied.ok) throw new SubmissionUnreadableError();\n\treturn copied.value as Record<string, unknown>;\n}\n\n/**\n * The `SubmitActionInput` a callback typed to take one gets for an action\n * WITHOUT `admitSubmission` (`snapshotSubmission`, not `privateSubmission`).\n * Its scalar fields are the snapshot's, so the callback sees the action,\n * scope, actor and ids Host authorizes and persists, whatever the caller\n * changed on its object since submission. `parameters`, `provenance` and\n * `authorizationBinding` are accessors on the caller's input: each read\n * returns what `input[field]` holds at that moment and each write assigns\n * it, so the callback reaches the same objects, with the same reads, as\n * when it was handed the caller's input itself. The view is a new object\n * each call: other properties of the caller's object are not on it, and\n * assigning a scalar field changes only the view.\n */\nexport function liveSubmissionView(snapshot: SubmissionSnapshot, input: SubmitActionInput): SubmitActionInput {\n\tconst view: Record<string, unknown> = {\n\t\tactionId: snapshot.actionId,\n\t\ttenantId: snapshot.tenantId,\n\t\tspaceId: snapshot.spaceId,\n\t\tactorId: snapshot.actorId,\n\t\tactorType: snapshot.actorType,\n\t\t...(snapshot.correlationId !== undefined ? { correlationId: snapshot.correlationId } : {}),\n\t\t...(snapshot.causationId !== undefined ? { causationId: snapshot.causationId } : {}),\n\t\t...(snapshot.executionReason !== undefined ? { executionReason: snapshot.executionReason } : {}),\n\t\t...(snapshot.idempotencyKey !== undefined ? { idempotencyKey: snapshot.idempotencyKey } : {}),\n\t\t...(snapshot.authorizationBindingId !== undefined ? { authorizationBindingId: snapshot.authorizationBindingId } : {}),\n\t};\n\tconst caller = input as unknown as Record<string, unknown>;\n\tfor (const field of [\"parameters\", \"provenance\", \"authorizationBinding\"] as const) {\n\t\tObject.defineProperty(view, field, {\n\t\t\tget: () => caller[field],\n\t\t\tset: (value: unknown) => { caller[field] = value; },\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t});\n\t}\n\treturn view as unknown as SubmitActionInput;\n}\n\n/**\n * A `SubmitActionInput` built from a private snapshot (`privateSubmission`),\n * with fresh copies of its parameters, provenance and binding, for a\n * callback typed to take one.\n */\nexport function submissionView(snapshot: SubmissionSnapshot): SubmitActionInput {\n\tconst fresh = <T>(value: T | undefined): T | undefined => {\n\t\tif (value === undefined) return undefined;\n\t\tconst copied = copyJsonData(value);\n\t\tif (!copied.ok) throw new SubmissionUnreadableError();\n\t\treturn copied.value as T;\n\t};\n\tconst provenance = fresh(snapshot.provenance);\n\tconst authorizationBinding = fresh(snapshot.authorizationBinding);\n\treturn {\n\t\tactionId: snapshot.actionId,\n\t\tparameters: parametersCopy(snapshot),\n\t\ttenantId: snapshot.tenantId,\n\t\tspaceId: snapshot.spaceId,\n\t\tactorId: snapshot.actorId,\n\t\tactorType: snapshot.actorType,\n\t\t...(snapshot.correlationId !== undefined ? { correlationId: snapshot.correlationId } : {}),\n\t\t...(snapshot.causationId !== undefined ? { causationId: snapshot.causationId } : {}),\n\t\t...(provenance ? { provenance } : {}),\n\t\t...(snapshot.executionReason !== undefined ? { executionReason: snapshot.executionReason } : {}),\n\t\t...(snapshot.idempotencyKey !== undefined ? { idempotencyKey: snapshot.idempotencyKey } : {}),\n\t\t...(snapshot.authorizationBindingId !== undefined ? { authorizationBindingId: snapshot.authorizationBindingId } : {}),\n\t\t...(authorizationBinding ? { authorizationBinding } : {}),\n\t};\n}\n","import { createFabricId } from \"@fabricorg/platform\";\nimport type {\n\tOutboxRequeuePlatformHostStore,\n\tOutboxStatus,\n\tPlatformHostOptions,\n\tRequeueOutboxDeadLetterInput,\n\tRequeueOutboxDeadLetterRefusal,\n\tRequeueOutboxDeadLetterResult,\n} from \"./types\";\nimport { emitPlatformHostTelemetry, PLATFORM_HOST_METRIC_NAMES } from \"./observability\";\n\n// ── Outbox dead-letter requeue ──────────────────────────────────────────────\n//\n// An operator moves a dead-lettered outbox record back to pending once the\n// consumer that rejected it is fixed. Authorization runs against the record as\n// read, and the store's compare-and-set accepts only that same dead letter:\n// the read's lease token travels with the write, so a decision cannot carry\n// over to a later dead-letter generation. The store writes the transition and\n// its evidence in one step. Not exported from the package\n// index; the host exposes it as `requeueOutboxDeadLetter`.\n\nconst MAX_REASON_LENGTH = 1_000;\n\nexport interface OutboxRequeueDeps<TDb> {\n\tstore: PlatformHostOptions<TDb>[\"store\"];\n\tauthorization: PlatformHostOptions<TDb>[\"authorization\"];\n\ttelemetry: PlatformHostOptions<TDb>[\"telemetry\"];\n\tnow(): Date;\n}\n\nexport function asOutboxRequeueStore<TDb>(\n\tstore: PlatformHostOptions<TDb>[\"store\"],\n): OutboxRequeuePlatformHostStore<TDb> | undefined {\n\tconst candidate = store as Partial<OutboxRequeuePlatformHostStore<TDb>>;\n\treturn typeof candidate.requeueOutboxDeadLetter === \"function\" &&\n\t\ttypeof candidate.getOutboxRecord === \"function\" &&\n\t\ttypeof candidate.listOutboxRequeues === \"function\"\n\t\t? (store as OutboxRequeuePlatformHostStore<TDb>)\n\t\t: undefined;\n}\n\nexport function createOutboxRequeue<TDb>(\n\tdeps: OutboxRequeueDeps<TDb>,\n): (input: RequeueOutboxDeadLetterInput) => Promise<RequeueOutboxDeadLetterResult> {\n\treturn async function requeueOutboxDeadLetter(input) {\n\t\tfor (const field of [\"outboxId\", \"tenantId\", \"spaceId\", \"actorId\", \"actorType\"] as const) {\n\t\t\tif (typeof input[field] !== \"string\" || input[field].trim() === \"\") {\n\t\t\t\tthrow new Error(`Outbox requeue requires ${field}.`);\n\t\t\t}\n\t\t}\n\t\tif (typeof input.reason !== \"string\" || input.reason.trim() === \"\") {\n\t\t\tthrow new Error(\"Outbox requeue requires a reason.\");\n\t\t}\n\t\tif (input.reason.length > MAX_REASON_LENGTH) {\n\t\t\tthrow new Error(`Outbox requeue reason must be at most ${MAX_REASON_LENGTH} characters.`);\n\t\t}\n\t\tif (input.availableAt !== undefined && !(input.availableAt instanceof Date && Number.isFinite(input.availableAt.getTime()))) {\n\t\t\tthrow new Error(\"Outbox requeue availableAt must be a valid Date.\");\n\t\t}\n\t\tconst store = asOutboxRequeueStore(deps.store);\n\t\tif (!store) throw new Error(\"Outbox requeue requires a store with outbox requeue support.\");\n\n\t\tconst refuse = (\n\t\t\trefusal: RequeueOutboxDeadLetterRefusal,\n\t\t\tmessage: string,\n\t\t\tcurrentStatus?: OutboxStatus,\n\t\t): RequeueOutboxDeadLetterResult => {\n\t\t\temitPlatformHostTelemetry(deps.telemetry, {\n\t\t\t\tkind: \"event\",\n\t\t\t\tname: \"outbox.requeue_refused\",\n\t\t\t\tmetricName: PLATFORM_HOST_METRIC_NAMES.outboxRequeueRefused,\n\t\t\t\toccurredAt: deps.now(),\n\t\t\t\ttenantId: input.tenantId,\n\t\t\t\tspaceId: input.spaceId,\n\t\t\t\tattributes: { refusal },\n\t\t\t});\n\t\t\treturn { status: \"refused\", refusal, message, ...(currentStatus ? { currentStatus } : {}) };\n\t\t};\n\n\t\tconst record = await store.getOutboxRecord(input.outboxId, input.tenantId, input.spaceId);\n\t\t// Authorize before revealing whether the record exists, so a refused actor\n\t\t// learns nothing about the scope. No authorizer means no requeue.\n\t\tconst authorization = deps.authorization;\n\t\tconst hasAuthorizer = typeof authorization.authorizeOutboxRequeue === \"function\";\n\t\t// Called through the authorization object so a class-based authorizer keeps its receiver.\n\t\tconst authorized = hasAuthorizer\n\t\t\t? await authorization.authorizeOutboxRequeue!({\n\t\t\t\ttenantId: input.tenantId,\n\t\t\t\tspaceId: input.spaceId,\n\t\t\t\tactorId: input.actorId,\n\t\t\t\tactorType: input.actorType,\n\t\t\t\toutboxId: input.outboxId,\n\t\t\t\treason: input.reason,\n\t\t\t\t...(record ? {\n\t\t\t\t\trecord: {\n\t\t\t\t\t\teventId: record.event.eventId,\n\t\t\t\t\t\teventType: record.event.eventType,\n\t\t\t\t\t\tpayloadClassification: record.event.payloadClassification,\n\t\t\t\t\t\tstatus: record.status,\n\t\t\t\t\t\tattemptCount: record.attemptCount,\n\t\t\t\t\t},\n\t\t\t\t} : {}),\n\t\t\t})\n\t\t\t: false;\n\t\tif (authorized !== true) {\n\t\t\treturn refuse(\n\t\t\t\t\"not_authorized\",\n\t\t\t\thasAuthorizer\n\t\t\t\t\t? `Actor ${input.actorId} is not authorized to requeue outbox records in this scope.`\n\t\t\t\t\t: \"Outbox requeue is refused because no authorizeOutboxRequeue is configured.\",\n\t\t\t);\n\t\t}\n\t\tif (!record) return refuse(\"not_found\", `Outbox record not found: ${input.outboxId}`);\n\t\tif (record.status !== \"dead_letter\") {\n\t\t\treturn refuse(\"not_dead_letter\", `Outbox record ${input.outboxId} is ${record.status}, not dead_letter.`, record.status);\n\t\t}\n\n\t\t// The compare-and-set is the guard that counts. Another requeue may have\n\t\t// won since the read above, or the record may have been requeued, retried\n\t\t// and dead-lettered again while the authorizer ran; the store refuses\n\t\t// unless the record is still the dead letter at the lease token we read.\n\t\tconst requeuedAt = deps.now();\n\t\tconst result = await store.requeueOutboxDeadLetter({\n\t\t\tid: input.outboxId,\n\t\t\ttenantId: input.tenantId,\n\t\t\tspaceId: input.spaceId,\n\t\t\trequeueId: createFabricId(\"orq\"),\n\t\t\tactorId: input.actorId,\n\t\t\tactorType: input.actorType,\n\t\t\treason: input.reason,\n\t\t\trequeuedAt,\n\t\t\tavailableAt: input.availableAt ?? requeuedAt,\n\t\t\texpectedLeaseToken: record.leaseToken ?? 0,\n\t\t});\n\t\tif (!result.applied) {\n\t\t\tif (result.refusal === \"not_found\") return refuse(\"not_found\", `Outbox record not found: ${input.outboxId}`);\n\t\t\tif (result.refusal === \"stale\") {\n\t\t\t\treturn refuse(\n\t\t\t\t\t\"stale\",\n\t\t\t\t\t`Outbox record ${input.outboxId} changed after it was authorized; read and authorize it again.`,\n\t\t\t\t\tresult.currentStatus,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn refuse(\n\t\t\t\t\"not_dead_letter\",\n\t\t\t\t`Outbox record ${input.outboxId} is ${result.currentStatus ?? \"no longer dead_letter\"}, not dead_letter.`,\n\t\t\t\tresult.currentStatus,\n\t\t\t);\n\t\t}\n\t\temitPlatformHostTelemetry(deps.telemetry, {\n\t\t\tkind: \"event\",\n\t\t\tname: \"outbox.requeued\",\n\t\t\tmetricName: PLATFORM_HOST_METRIC_NAMES.outboxRequeued,\n\t\t\toccurredAt: requeuedAt,\n\t\t\ttenantId: input.tenantId,\n\t\t\tspaceId: input.spaceId,\n\t\t\tattributes: { priorAttempt: result.requeue.priorAttemptCount },\n\t\t});\n\t\treturn { status: \"requeued\", record: result.record, requeue: result.requeue };\n\t};\n}\n","import {\n\tAdapterCircuitBreakerRegistry,\n\tAdapterRegistry,\n\tassertAdapterCircuitBreakerConfig,\n\tisAdapterCircuitOpenError,\n\tisRetryableExecutionError,\n\tisReconciliationRequiredError,\n\taggregatePolicyOutcomes,\n\tcreateFabricId,\n\tevaluatePolicyDefinitions,\n\texecuteWithAdapterRetry,\n\tassertAdapterOutcomeConsistency,\n\tevaluateStateMachineTransition,\n\tassertMutationGovernanceContext,\n\tassertGovernanceRuntimeEvidence,\n\tFABRIC_GOVERNANCE_CONTRACT_VERSION,\n} from \"@fabricorg/platform\";\nimport { performance } from \"node:perf_hooks\";\nimport { assertAssemblyRuntimeCompatible } from \"@fabricorg/assembly\";\nimport type {\n\tActionDefinition,\n\tActionId,\n\tActionStatus,\n\tAssetEventEnvelope,\n\tRuntimePolicyDefinition,\n\tExecutionAttestation,\n\tExternalReconciliation,\n} from \"@fabricorg/platform\";\nimport type {\n\tActionApprovalDecision,\n\tActionAuthorizationInput,\n\tActionExecutionReason,\n\tActionInvocationRecord,\n\tAdapterInvocationRecord,\n\tAdapterReconciliationOutcome,\n\tApprovalPlatformHostStore,\n\tExecuteActionResult,\n\tExecuteInvocationOptions,\n\tGovernedActionHost,\n\tOutboxRequeueHost,\n\tPendingAssetEvent,\n\tOutboxPlatformHostStore,\n\tPlatformHostOptions,\n\tErrorTextRedactionContext,\n\tPlatformHostMutationTransaction,\n\tSubmitActionInput,\n\tSubmitActionResult,\n\tIdempotencyConflict,\n\tRecoverablePlatformHostStore,\n\tActionInvocationPatch,\n\tPendingExternalCompletion,\n} from \"./types\";\nimport { ActionAdmissionError, IdempotencyConflictError, PLATFORM_HOST_CONTRACT_VERSION } from \"./types\";\nimport type { ActionAdmissionRefusal } from \"./types\";\nimport { digestParameters, normalizeProvenance, PARAMETER_DIGEST_ALGORITHM } from \"./command-identity\";\nimport { createExternalCompletionLifecycle } from \"./external-completion\";\nimport { liveSubmissionView, parametersCopy, privateSubmission, snapshotSubmission, submissionView, type SubmissionSnapshot } from \"./submission-snapshot\";\nimport { createOutboxRequeue } from \"./outbox-requeue\";\nimport {\n\tasAtomicMutationStore,\n\tasGovernanceStore,\n\temitInvocationStatusTelemetry,\n\terrorMessage,\n\tHostError,\n\tRecoverableFinalizationError,\n\tredactErrorText,\n\tisRecord,\n\tlifecycleId,\n\twithoutPrivateHostFields,\n} from \"./host-internals\";\nimport {\n\temitPlatformHostTelemetry,\n\tPLATFORM_HOST_METRIC_NAMES,\n} from \"./observability\";\n\nconst DEFAULT_EXTRACT_EVENTS = (data: Record<string, unknown>): PendingAssetEvent[] => {\n\tconst value = data._events;\n\treturn Array.isArray(value) ? (value as PendingAssetEvent[]) : [];\n};\n\n/** After a fallback verdict, attempt independent evidence writes before raising the first failure. */\nasync function attemptEvidenceWrites(writes: Array<() => Promise<void>>): Promise<void> {\n\tlet failure: { error: unknown } | undefined;\n\tfor (const write of writes) {\n\t\ttry { await write(); } catch (error) { failure ??= { error }; }\n\t}\n\tif (failure) throw failure.error;\n}\n\nconst DEFAULT_ADMISSION_TIMEOUT_MS = 10_000;\n/** The largest delay `setTimeout` honours (2^31 - 1 ms); a larger one fires at once. */\nconst MAX_TIMER_MS = 2_147_483_647;\n/** Monotonic milliseconds, captured at module load: the admission deadline is judged on it. */\nconst monotonicNow: () => number = performance.now.bind(performance);\ntype AdmissionOutcome = { kind: \"answered\"; value: unknown } | { kind: \"failed\" } | { kind: \"timed_out\" };\nconst ADMISSION_FAILED: AdmissionOutcome = Object.freeze({ kind: \"failed\" });\nconst ADMISSION_TIMED_OUT: AdmissionOutcome = Object.freeze({ kind: \"timed_out\" });\n/** What an admission refusal's code may look like; anything else is `invalid_decision`. */\nconst ADMISSION_REFUSAL_CODE = /^[a-z][A-Za-z0-9_.:-]{0,127}$/;\n\nexport function createGovernedActionHost<TDb>(\n\toptions: PlatformHostOptions<TDb>,\n): GovernedActionHost & OutboxRequeueHost {\n\tconst retryableExecutionMaxAttempts = options.retryableExecutionMaxAttempts ?? 5;\n\tif (!Number.isInteger(retryableExecutionMaxAttempts) || retryableExecutionMaxAttempts <= 0) {\n\t\tthrow new Error(\"retryableExecutionMaxAttempts must be a positive integer.\");\n\t}\n\tconst recoveryMaxAttempts = options.recoveryMaxAttempts ?? Math.max(5, retryableExecutionMaxAttempts);\n\tif (!Number.isInteger(recoveryMaxAttempts) || recoveryMaxAttempts <= 0) {\n\t\tthrow new Error(\"recoveryMaxAttempts must be a positive integer.\");\n\t}\n\tif (recoveryMaxAttempts < retryableExecutionMaxAttempts) {\n\t\tthrow new Error(\n\t\t\t`recoveryMaxAttempts (${recoveryMaxAttempts}) must be greater than or equal to retryableExecutionMaxAttempts (${retryableExecutionMaxAttempts}); raise recoveryMaxAttempts or lower retryableExecutionMaxAttempts too.`,\n\t\t);\n\t}\n\tif (options.composition) {\n\t\tif (!options.registry?.orderedModules) {\n\t\t\tthrow new Error(\"Composition-bound Platform Host requires an explicit module registry.\");\n\t\t}\n\t\tassertAssemblyRuntimeCompatible(\n\t\t\toptions.composition.assembly,\n\t\t\toptions.registry.orderedModules.map((module) => ({\n\t\t\t\tnamespace: module.namespace,\n\t\t\t\tversion: module.version ?? \"\",\n\t\t\t\tmanifestDigest: module.manifestDigest ?? \"\",\n\t\t\t})),\n\t\t);\n\t}\n\tif (options.outbox) {\n\t\tconst outboxStore = asOutboxStore(options.store);\n\t\tif (!outboxStore || !asAtomicMutationStore(options.store) || outboxStore.transactionalOutbox !== true) {\n\t\t\tthrow new Error(\"Outbox egress requires a store with transactionalOutbox and transactionWithEvents capabilities.\");\n\t\t}\n\t}\n\tconst adapters = new AdapterRegistry();\n\tfor (const adapter of options.adapters ?? []) {\n\t\t// A breaker config was inert before Host read it; refuse a bad one at\n\t\t// construction rather than on the first adapter call.\n\t\tif (adapter.circuitBreaker) assertAdapterCircuitBreakerConfig(adapter.circuitBreaker);\n\t\tadapters.register(adapter);\n\t}\n\tconst now = options.now ?? (() => new Date());\n\t// The default registry creates one breaker per adapterType:operation, on\n\t// first use and only for adapters that declare a circuitBreaker config. An\n\t// injected provider can use the trusted invocation scope passed at the\n\t// adapter boundary.\n\tconst circuitBreakers = options.adapterCircuitBreakers\n\t\t?? new AdapterCircuitBreakerRegistry({ now: () => now().getTime() });\n\tconst extractEvents = options.extractEvents ?? DEFAULT_EXTRACT_EVENTS;\n\tconst configuredActionResolver = options.resolveAction ?? options.registry?.resolveAction;\n\tif (!configuredActionResolver) throw new Error(\"Platform Host requires an explicit module registry or resolveAction function.\");\n\tconst actionResolver: NonNullable<PlatformHostOptions<TDb>[\"resolveAction\"]> = configuredActionResolver;\n\tconst stateMachineResolver = options.registry?.resolveStateMachine ?? (() => undefined);\n\tconst eventResultFields = options.eventResultFields ?? [\"_events\"];\n\tconst admissionTimeoutMs = options.admissionTimeoutMs ?? DEFAULT_ADMISSION_TIMEOUT_MS;\n\tif (typeof admissionTimeoutMs !== \"number\" || !Number.isInteger(admissionTimeoutMs) || admissionTimeoutMs < 1 || admissionTimeoutMs > MAX_TIMER_MS) {\n\t\tthrow new Error(`admissionTimeoutMs must be a whole number of milliseconds from 1 to ${MAX_TIMER_MS}.`);\n\t}\n\n\tfunction caughtError(context: ErrorTextRedactionContext, error: unknown): string {\n\t\treturn error instanceof HostError\n\t\t\t? errorMessage(error)\n\t\t\t: redactErrorText(options.redactErrorText, context, errorMessage(error));\n\t}\n\n\tasync function submitAction(input: SubmitActionInput): Promise<SubmitActionResult> {\n\t\t// The one read of the caller's scalar fields, before the first await.\n\t\t// Every step below reads `submission`, so what the caller changes on its\n\t\t// object while Host awaits cannot change the action, scope, actor, ids\n\t\t// or keys Host authorizes, persists or executes (tests \"the submission\n\t\t// Host authorizes, admits, persists and executes is one private\n\t\t// snapshot\" and \"the identity snapshot still applies …\").\n\t\tconst read = snapshotSubmission(input);\n\t\tif (read.executionReason && ![\"initial\", \"offline_replay\"].includes(read.executionReason)) {\n\t\t\tthrow new Error(`Unsupported submitted execution reason: ${read.executionReason}`);\n\t\t}\n\t\tconst action = actionResolver(read.actionId);\n\t\tif (!action) throw new Error(`Unknown action: ${read.actionId}`);\n\t\t// An action that declares admitSubmission gets Host's own copies of the\n\t\t// parameters, provenance and binding, also before the first await. For\n\t\t// any other action `submission` reads those three from the caller's\n\t\t// input wherever Host reads them below, exactly as before the snapshot\n\t\t// existed (tests \"an action without admitSubmission: everything but the\n\t\t// identity snapshot is as before\").\n\t\tconst declaresAdmission = action.admitSubmission !== undefined;\n\t\tconst submission = declaresAdmission ? privateSubmission(read) : read;\n\t\t// An action that requires connectivity was never eligible to be captured offline.\n\t\tif (action.execution?.connectivity === \"online-required\" && submission.executionReason === \"offline_replay\") {\n\t\t\tthrow new Error(`Action ${submission.actionId} is online-required and cannot be submitted as an offline replay.`);\n\t\t}\n\t\tif (action.execution?.sensitivity === \"restricted\" && Object.keys(submission.provenance?.auditAttributes ?? {}).length > 0) {\n\t\t\tthrow new Error(`Action ${submission.actionId} declares restricted sensitivity; provenance audit attributes must not be durably recorded.`);\n\t\t}\n\t\tconst authorizationInput = toAuthorizationInput(action, submission);\n\t\tif (!(await options.authorization.checkEntitlement(authorizationInput))) {\n\t\t\tthrow new Error(`Module \"${action.namespace}\" is not enabled for tenant ${submission.tenantId}`);\n\t\t}\n\t\tif (!(await options.authorization.authorize(authorizationInput))) {\n\t\t\tthrow new Error(`Actor ${submission.actorId} is not authorized for action ${submission.actionId}`);\n\t\t}\n\t\t// Only JSON data Host copied at submission can be admitted: anything else\n\t\t// could still be changed through a reference the caller holds. Refused\n\t\t// here, before any callback could be handed the caller's object.\n\t\tif (declaresAdmission && (!submission.parametersArePrivate || !isRecord(submission.parameters))) {\n\t\t\trefuseAdmission(action, submission, \"invalid_parameters\");\n\t\t}\n\n\t\tconst actionInvocationId = createFabricId(\"act\");\n\t\tif (submission.correlationId && submission.provenance?.correlationId && submission.correlationId !== submission.provenance.correlationId) throw new Error(\"Invocation provenance correlationId does not match submission correlationId.\");\n\t\tif (submission.causationId && submission.provenance?.causationId && submission.causationId !== submission.provenance.causationId) throw new Error(\"Invocation provenance causationId does not match submission causationId.\");\n\t\tconst correlationId = submission.correlationId ?? submission.provenance?.correlationId ?? createFabricId(\"corr\");\n\t\t// Redaction, the parameter digest and the binding check. For an action\n\t\t// without admitSubmission they run here, before provenance and the\n\t\t// composition callback, as they always did; for one with it, after its\n\t\t// check admitted the submission, on Host's copy.\n\t\t// Each reads `submission.parameters` where and as often as the previous\n\t\t// Host read the caller's: for an action without the check those reads\n\t\t// go to the caller's input (src/submission-snapshot.ts).\n\t\tconst prepare = () => {\n\t\t\tconst durableParameters = options.redactActionParameters\n\t\t\t\t? options.redactActionParameters(submission.actionId, submission.parameters)\n\t\t\t\t: submission.parameters;\n\t\t\tconst parameterDigest = digestParameters(submission.parameters);\n\t\t\tif (submission.authorizationBinding) validateAuthorizationBinding(submission, parameterDigest, action.execution?.authorityMoment, now());\n\t\t\treturn { durableParameters, parameterDigest };\n\t\t};\n\t\tconst early = declaresAdmission ? undefined : prepare();\n\t\tconst durableProvenance = normalizeProvenance(\n\t\t\tsubmission.provenance,\n\t\t\toptions.provenance as PlatformHostOptions<unknown>[\"provenance\"],\n\t\t);\n\t\t// Both views carry the snapshot's identity, so the callback resolves\n\t\t// evidence for the action, scope and actor Host persists. A declaring\n\t\t// action's callback gets fresh copies of Host's parameters, provenance\n\t\t// and binding; any other action's reads and assigns the caller's, as\n\t\t// when it was handed the caller's input (liveSubmissionView).\n\t\tconst initiatingReleaseDigest =\n\t\t\tawait options.composition?.resolveInitiatingReleaseDigest?.(declaresAdmission ? submissionView(submission) : liveSubmissionView(submission, input));\n\t\tconst runtimeEvidence = {\n\t\t\tgovernanceContractVersion: FABRIC_GOVERNANCE_CONTRACT_VERSION,\n\t\t\thostContractVersion: PLATFORM_HOST_CONTRACT_VERSION,\n\t\t\t...options.runtimeEvidence,\n\t\t\t...(options.composition\n\t\t\t\t? { assemblyDigest: options.composition.assembly.assemblyDigest }\n\t\t\t\t: {}),\n\t\t\t...(initiatingReleaseDigest\n\t\t\t\t? { initiatingReleaseDigest }\n\t\t\t\t: {}),\n\t\t};\n\t\tassertGovernanceRuntimeEvidence(runtimeEvidence);\n\t\t// The action's admission check is the last await before the invocation\n\t\t// is created: everything between it and createActionInvocation is\n\t\t// synchronous, and it runs on every submission, including one that\n\t\t// reuses an idempotency key, so a refused submission is never digested,\n\t\t// matched against an existing invocation, redacted or written.\n\t\tconst admission = declaresAdmission\n\t\t\t? await admitSubmission(action, submission)\n\t\t\t: undefined;\n\t\tconst { durableParameters, parameterDigest } = early ?? prepare();\n\t\tconst durableInvocation = await options.store.createActionInvocation({\n\t\t\tid: actionInvocationId,\n\t\t\ttenantId: submission.tenantId,\n\t\t\tspaceId: submission.spaceId,\n\t\t\tactionId: submission.actionId,\n\t\t\tactionVersion: action.version,\n\t\t\tactorId: submission.actorId,\n\t\t\tactorType: submission.actorType,\n\t\t\tstatus: \"pending\",\n\t\t\tparameters: durableParameters,\n\t\t\tresult: {},\n\t\t\truntimeEvidence,\n\t\t\tcorrelationId,\n\t\t\t...((submission.causationId ?? submission.provenance?.causationId) ? { causationId: submission.causationId ?? submission.provenance?.causationId } : {}),\n\t\t\t...(submission.idempotencyKey ? { idempotencyKey: submission.idempotencyKey } : {}),\n\t\t\t...(submission.idempotencyKey ? {\n\t\t\t\tparameterDigest,\n\t\t\t\tparameterDigestAlgorithm: PARAMETER_DIGEST_ALGORITHM,\n\t\t\t\tidempotencyActorId: submission.actorId,\n\t\t\t\t...(submission.authorizationBindingId ? { idempotencyAuthorizationBindingId: submission.authorizationBindingId } : {}),\n\t\t\t} : {}),\n\t\t\t...(durableProvenance ? { provenance: durableProvenance } : {}),\n\t\t\t...(submission.authorizationBinding ? { authorizationBinding: submission.authorizationBinding } : {}),\n\t\t\t...(submission.executionReason ? { executionReason: submission.executionReason } : {}),\n\t\t\t...(submission.authorizationBindingId\n\t\t\t\t? { authorizationBindingId: submission.authorizationBindingId }\n\t\t\t\t: {}),\n\t\t\t...(admission ? { admittedAt: admission.admittedAt } : {}),\n\t\t});\n\t\temitPlatformHostTelemetry(options.telemetry, {\n\t\t\tkind: \"event\",\n\t\t\tname: \"invocation.submitted\",\n\t\t\tmetricName: PLATFORM_HOST_METRIC_NAMES.invocationSubmitted,\n\t\t\toccurredAt: now(),\n\t\t\ttenantId: submission.tenantId,\n\t\t\tspaceId: submission.spaceId,\n\t\t\tattributes: { actionVersion: action.version },\n\t\t});\n\t\tif (durableInvocation.id !== actionInvocationId && submission.idempotencyKey) {\n\t\t\tconst conflict = idempotencyConflict(durableInvocation, {\n\t\t\t\tactorId: submission.actorId,\n\t\t\t\tauthorizationBindingId: submission.authorizationBindingId,\n\t\t\t\tactionVersion: action.version,\n\t\t\t\tparameterDigest,\n\t\t\t\tidempotencyKey: submission.idempotencyKey,\n\t\t\t});\n\t\t\tif (!durableInvocation.parameterDigest) {\n\t\t\t\toptions.idempotency?.onLegacyRecord?.(durableInvocation);\n\t\t\t\tconst enforceableLegacyConflict = conflict && { ...conflict, reasons: conflict.reasons.filter((reason) => reason !== \"parameters\") };\n\t\t\t\tif (enforceableLegacyConflict && enforceableLegacyConflict.reasons.length) {\n\t\t\t\t\toptions.idempotency?.onConflict?.(enforceableLegacyConflict);\n\t\t\t\t\tif ((options.idempotency?.conflictMode ?? \"enforce\") === \"enforce\") throw new IdempotencyConflictError(enforceableLegacyConflict);\n\t\t\t\t}\n\t\t\t} else if (conflict) {\n\t\t\t\toptions.idempotency?.onConflict?.(conflict);\n\t\t\t\tif ((options.idempotency?.conflictMode ?? \"enforce\") === \"enforce\") throw new IdempotencyConflictError(conflict);\n\t\t\t}\n\t\t}\n\t\tconst durableWorkflowId = `action-invocation-${durableInvocation.id}`;\n\t\tif (durableInvocation.id !== actionInvocationId) {\n\t\t\t// A pending dispatch may be retried with the same stable workflow id.\n\t\t\t// Terminal and running invocations report what the original did.\n\t\t\tif (options.dispatcher && durableInvocation.status === \"pending\") {\n\t\t\t\tconst dispatched = await options.dispatcher.dispatch({\n\t\t\t\t\tactionInvocationId: durableInvocation.id,\n\t\t\t\t\tactionId: durableInvocation.actionId,\n\t\t\t\t\ttenantId: submission.tenantId,\n\t\t\t\t\tspaceId: submission.spaceId,\n\t\t\t\t\tworkflowId: durableWorkflowId,\n\t\t\t\t});\n\t\t\t\treturn withConsistency({\n\t\t\t\t\tactionInvocationId: durableInvocation.id,\n\t\t\t\t\tstatus: durableInvocation.status,\n\t\t\t\t\tworkflowId: dispatched.workflowId,\n\t\t\t\t\t...(dispatched.runId ? { runId: dispatched.runId } : {}),\n\t\t\t\t\t...(durableInvocation.hitlRoute ? { hitlRoute: durableInvocation.hitlRoute } : {}),\n\t\t\t\t\t...(durableInvocation.hitlRiskTier\n\t\t\t\t\t\t? { hitlRiskTier: durableInvocation.hitlRiskTier }\n\t\t\t\t\t\t: {}),\n\t\t\t\t}, submission.actionId);\n\t\t\t}\n\t\t\treturn withConsistency({\n\t\t\t\tactionInvocationId: durableInvocation.id,\n\t\t\t\tstatus: durableInvocation.status,\n\t\t\t\tworkflowId: durableWorkflowId,\n\t\t\t\tresult: durableInvocation.result,\n\t\t\t\t...(durableInvocation.error ? { error: durableInvocation.error } : {}),\n\t\t\t\t...(durableInvocation.hitlRoute ? { hitlRoute: durableInvocation.hitlRoute } : {}),\n\t\t\t\t...(durableInvocation.hitlRiskTier\n\t\t\t\t\t? { hitlRiskTier: durableInvocation.hitlRiskTier }\n\t\t\t\t\t: {}),\n\t\t\t\t...(durableInvocation.authorizationReconciliation\n\t\t\t\t\t? { reconciliation: durableInvocation.authorizationReconciliation }\n\t\t\t\t\t: {}),\n\t\t\t\t...(durableInvocation.adapterReconciliation\n\t\t\t\t\t? { adapterReconciliation: durableInvocation.adapterReconciliation }\n\t\t\t\t\t: {}),\n\t\t\t\t...(durableInvocation.pendingCompletion\n\t\t\t\t\t? { pendingCompletion: durableInvocation.pendingCompletion }\n\t\t\t\t\t: {}),\n\t\t\t}, submission.actionId);\n\t\t}\n\n\t\tif (options.dispatcher) {\n\t\t\ttry {\n\t\t\t\tconst dispatched = await options.dispatcher.dispatch({\n\t\t\t\t\tactionInvocationId: durableInvocation.id,\n\t\t\t\t\tactionId: durableInvocation.actionId,\n\t\t\t\t\ttenantId: submission.tenantId,\n\t\t\t\t\tspaceId: submission.spaceId,\n\t\t\t\t\tworkflowId: durableWorkflowId,\n\t\t\t\t});\n\t\t\t\treturn withConsistency({\n\t\t\t\t\tactionInvocationId: durableInvocation.id,\n\t\t\t\t\tstatus: durableInvocation.status,\n\t\t\t\t\tworkflowId: dispatched.workflowId,\n\t\t\t\t\t...(dispatched.runId ? { runId: dispatched.runId } : {}),\n\t\t\t\t\t...(durableInvocation.hitlRoute ? { hitlRoute: durableInvocation.hitlRoute } : {}),\n\t\t\t\t\t...(durableInvocation.hitlRiskTier\n\t\t\t\t\t\t? { hitlRiskTier: durableInvocation.hitlRiskTier }\n\t\t\t\t\t\t: {}),\n\t\t\t\t}, submission.actionId);\n\t\t\t} catch (error) {\n\t\t\t\t// The durable invocation remains pending. A caller can resubmit the\n\t\t\t\t// same idempotency key, or an out-of-band dispatcher can retry the\n\t\t\t\t// stable workflow id without recreating the logical mutation.\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\n\t\tconst executed = await executeInvocation(\n\t\t\tdurableInvocation.id,\n\t\t\tsubmission.tenantId,\n\t\t\tsubmission.spaceId,\n\t\t);\n\t\treturn { ...withConsistency(executed, submission.actionId), workflowId: durableWorkflowId };\n\t}\n\n\t/**\n\t * Run the action's `admitSubmission` check on a copy of the submission\n\t * snapshot's parameters, with the snapshot's scope and actor, bounded by\n\t * `admissionTimeoutMs`. Returns when it was admitted; anything but\n\t * `{ admitted: true }` settled within the bound throws\n\t * ActionAdmissionError before anything durable is written. What the check\n\t * throws is never read.\n\t *\n\t * The bound is judged when the check's promise settles, on the monotonic\n\t * clock (`performance.now()`): an answer that settles `admissionTimeoutMs`\n\t * or more after the call began is `timed_out`, even when its handler runs\n\t * before the timer callback (a check that blocked the event loop past the\n\t * deadline). The timer only ends the wait on a promise that never settles.\n\t * Every `timed_out` refusal aborts the check's signal before it throws.\n\t */\n\tasync function admitSubmission(\n\t\taction: ActionDefinition<TDb>,\n\t\tsubmission: SubmissionSnapshot,\n\t): Promise<{ admittedAt: Date }> {\n\t\tconst refuse = (refusal: ActionAdmissionRefusal, refusalCode?: string): never =>\n\t\t\trefuseAdmission(action, submission, refusal, refusalCode);\n\t\tconst check = action.admitSubmission;\n\t\tif (typeof check !== \"function\") return refuse(\"failed\");\n\t\t// submitAction refused parameters that are not Host's private JSON copy.\n\t\tconst checked = parametersCopy(submission);\n\t\tconst controller = new AbortController();\n\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\t\tconst deadline = new Promise<AdmissionOutcome>((resolve) => {\n\t\t\ttimer = setTimeout(() => {\n\t\t\t\tcontroller.abort();\n\t\t\t\tresolve(ADMISSION_TIMED_OUT);\n\t\t\t}, admissionTimeoutMs);\n\t\t});\n\t\tconst startedAt = monotonicNow();\n\t\tconst settledInTime = (): boolean => monotonicNow() - startedAt < admissionTimeoutMs;\n\t\tlet answered: Promise<AdmissionOutcome>;\n\t\ttry {\n\t\t\tanswered = Promise.resolve(check(Object.freeze({\n\t\t\t\tactionId: action.actionId,\n\t\t\t\ttenantId: submission.tenantId,\n\t\t\t\tspaceId: submission.spaceId,\n\t\t\t\tactorId: submission.actorId,\n\t\t\t\tactorType: submission.actorType,\n\t\t\t\tparameters: checked,\n\t\t\t\tsignal: controller.signal,\n\t\t\t}))).then(\n\t\t\t\t(value: unknown): AdmissionOutcome => settledInTime() ? { kind: \"answered\", value } : ADMISSION_TIMED_OUT,\n\t\t\t\t(): AdmissionOutcome => settledInTime() ? ADMISSION_FAILED : ADMISSION_TIMED_OUT,\n\t\t\t);\n\t\t} catch {\n\t\t\tanswered = Promise.resolve(settledInTime() ? ADMISSION_FAILED : ADMISSION_TIMED_OUT);\n\t\t}\n\t\tlet outcome: AdmissionOutcome;\n\t\ttry {\n\t\t\toutcome = await Promise.race([answered, deadline]);\n\t\t} finally {\n\t\t\tclearTimeout(timer);\n\t\t}\n\t\tif (outcome.kind === \"timed_out\") {\n\t\t\tcontroller.abort();\n\t\t\treturn refuse(\"timed_out\");\n\t\t}\n\t\tif (outcome.kind === \"failed\") return refuse(\"failed\");\n\t\tconst admitted = ownDataProperty(outcome.value, \"admitted\");\n\t\tif (admitted === true) return { admittedAt: now() };\n\t\tconst code = ownDataProperty(outcome.value, \"code\");\n\t\tif (admitted === false && typeof code === \"string\" && ADMISSION_REFUSAL_CODE.test(code)) return refuse(\"refused\", code);\n\t\treturn refuse(\"invalid_decision\");\n\t}\n\n\tfunction refuseAdmission(\n\t\taction: ActionDefinition<TDb>,\n\t\tsubmission: SubmissionSnapshot,\n\t\trefusal: ActionAdmissionRefusal,\n\t\trefusalCode?: string,\n\t): never {\n\t\temitPlatformHostTelemetry(options.telemetry, {\n\t\t\tkind: \"event\",\n\t\t\tname: \"invocation.admission_refused\",\n\t\t\tmetricName: PLATFORM_HOST_METRIC_NAMES.invocationAdmissionRefused,\n\t\t\toccurredAt: now(),\n\t\t\ttenantId: submission.tenantId,\n\t\t\tspaceId: submission.spaceId,\n\t\t\tattributes: { actionVersion: action.version, refusal },\n\t\t});\n\t\tthrow new ActionAdmissionError(action.actionId, refusal, refusalCode);\n\t}\n\n\tasync function executeInvocation(\n\t\tactionInvocationId: string,\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t\texecutionOptions: ExecuteInvocationOptions = {},\n\t\texecutionReasonOverride?: ActionExecutionReason,\n\t): Promise<ExecuteActionResult> {\n\t\tlet preservedReconciliation: ActionInvocationRecord | undefined;\n\t\tconst result = await executeInvocationAttempt(actionInvocationId, tenantId, spaceId, executionOptions, executionReasonOverride,\n\t\t\t(record) => { preservedReconciliation = record; });\n\t\tif (preservedReconciliation) return withConsistency(actionResult(preservedReconciliation), preservedReconciliation.actionId);\n\t\treturn result;\n\t}\n\n\tasync function executeInvocationAttempt(\n\t\tactionInvocationId: string,\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t\texecutionOptions: ExecuteInvocationOptions = {},\n\t\texecutionReasonOverride?: ActionExecutionReason,\n\t\tonPreservedReconciliation?: (record: ActionInvocationRecord) => void,\n\t): Promise<ExecuteActionResult> {\n\t\t// Capture credentials supplied to this execution, never a mutable store record.\n\t\tconst executionLease = executionOptions.leaseOwner !== undefined\n\t\t\t? Object.freeze({ leaseOwner: executionOptions.leaseOwner, leaseToken: executionOptions.leaseToken ?? 0 }) : undefined;\n\t\tconst loadedInvocation = await options.store.getActionInvocation(\n\t\t\tactionInvocationId,\n\t\t\ttenantId,\n\t\t\tspaceId,\n\t\t);\n\t\tif (!loadedInvocation) {\n\t\t\tthrow new Error(`ActionInvocation not found: ${actionInvocationId}`);\n\t\t}\n\t\tconst resumingRunningInvocation = loadedInvocation.status === \"running\";\n\t\tlet invocation: ActionInvocationRecord = { ...loadedInvocation };\n\t\tif (isTerminal(invocation.status) || invocation.status === \"waiting_for_approval\") {\n\t\t\treturn withConsistency(actionResult(invocation), invocation.actionId);\n\t\t}\n\t\tif (\n\t\t\tinvocation.status === \"running\" &&\n\t\t\tinvocation.leaseOwner &&\n\t\t\t(executionLease?.leaseOwner !== invocation.leaseOwner ||\n\t\t\t\t((invocation.leaseToken ?? 0) > 0 &&\n\t\t\t\t\texecutionLease?.leaseToken !== invocation.leaseToken))\n\t\t) {\n\t\t\treturn {\n\t\t\t\t...actionResult(invocation),\n\t\t\t\terror: `Invocation lease is not owned by the supplied worker generation`,\n\t\t\t};\n\t\t}\n\t\tlet ownVerdict: Extract<import(\"./types\").AdapterInvocationWriteCondition, { kind: \"verdict\" }> | undefined;\n\t\tconst adapterStatuses = new Map<string, AdapterInvocationRecord[\"status\"]>();\n\t\tfunction rememberVerdict(patch: ActionInvocationPatch, externalCompletionDigest = invocation.externalCompletion?.digest) {\n\t\t\tconst completionAdapterInvocationId = (patch.pendingCompletion ?? invocation.pendingCompletion)?.adapterInvocationId;\n\t\t\tif (patch.status && isTerminal(patch.status)) ownVerdict = {\n\t\t\t\tkind: \"verdict\", status: patch.status,\n\t\t\t\terror: Object.hasOwn(patch, \"error\") ? patch.error : invocation.error,\n\t\t\t\t...(externalCompletionDigest === undefined ? {} : { externalCompletionDigest }),\n\t\t\t\t...(completionAdapterInvocationId ? { completionAdapterInvocationId } : {}),\n\t\t\t};\n\t\t\tinvocation = { ...invocation, ...patch };\n\t\t}\n\t\tasync function persistExecutionInvocation(record: ActionInvocationRecord, patch: ActionInvocationPatch) {\n\t\t\tconst externalCompletionDigest = record.externalCompletion?.digest;\n\t\t\tconst written = await persistInvocation(record, patch, onPreservedReconciliation, executionLease);\n\t\t\t// A preserving inline write observed another writer's verdict, not ours.\n\t\t\tif (written) rememberVerdict(patch, externalCompletionDigest);\n\t\t}\n\t\tasync function persistExecutionVerdict(\n\t\t\trecord: ActionInvocationRecord,\n\t\t\tpatch: ActionInvocationPatch,\n\t\t\tevidenceWrites: Array<() => Promise<void>> = [],\n\t\t) {\n\t\t\tif (ownVerdict) {\n\t\t\t\tconst verdict = ownVerdict;\n\t\t\t\t// Enrichment has no verdict authority of its own. A refusal or missing\n\t\t\t\t// capability skips this write; store errors join the evidence collector.\n\t\t\t\tawait attemptEvidenceWrites([async () => {\n\t\t\t\t\tif (!options.store.updateSettledActionInvocation) return;\n\t\t\t\t\tconst parentPatch = {\n\t\t\t\t\t\t...(Object.hasOwn(patch, \"error\") ? { error: patch.error } : {}),\n\t\t\t\t\t\t...(Object.hasOwn(patch, \"adapterReconciliation\") ? { adapterReconciliation: patch.adapterReconciliation } : {}),\n\t\t\t\t\t};\n\t\t\t\t\tif (!await options.store.updateSettledActionInvocation({ id: actionInvocationId, tenantId, spaceId, condition: verdict, patch: parentPatch })) {\n\t\t\t\t\t\temitPlatformHostTelemetry(options.telemetry, { kind: \"event\", name: \"invocation.adapter_evidence_refused\",\n\t\t\t\t\t\t\tmetricName: PLATFORM_HOST_METRIC_NAMES.adapterEvidenceRefused, occurredAt: now(), tenantId, spaceId,\n\t\t\t\t\t\t\tattributes: { actionInvocationId, evidence: \"parent_enrichment\", reason: \"verdict_or_row_changed\" } });\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\t// Move our comparison forward only after a successful conditional write.\n\t\t\t\t\townVerdict = { ...verdict, ...(Object.hasOwn(parentPatch, \"error\") ? { error: parentPatch.error } : {}) };\n\t\t\t\t\tinvocation = { ...invocation, ...parentPatch };\n\t\t\t\t}, ...evidenceWrites]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\ttry { await persistExecutionInvocation(record, patch); }\n\t\t\tcatch (error) {\n\t\t\t\tif (error instanceof RecoverableFinalizationError) throw error;\n\t\t\t\tawait persistExecutionInvocation(record, patch);\n\t\t\t}\n\t\t\tawait attemptEvidenceWrites(evidenceWrites);\n\t\t}\n\n\t\tasync function failExecution(record: ActionInvocationRecord, status: \"failed\" | \"blocked_by_policy\" | \"validation_failed\", error: string) {\n\t\t\tawait persistExecutionInvocation(record, { status, error });\n\t\t\treturn { actionInvocationId: record.id, status, error,\n\t\t\t\t...(record.hitlRoute ? { hitlRoute: record.hitlRoute } : {}), ...(record.hitlRiskTier ? { hitlRiskTier: record.hitlRiskTier } : {}) };\n\t\t}\n\t\tasync function writeAdapter(\n\t\t\tid: string, patch: import(\"./types\").AdapterInvocationPatch,\n\t\t\ttransaction?: PlatformHostMutationTransaction<TDb>,\n\t\t): Promise<void> {\n\t\t\tconst condition = ownVerdict ?? (executionLease ? { kind: \"lease\" as const, ...executionLease } : undefined);\n\t\t\tconst writer = transaction ?? options.store;\n\t\t\tif (condition && options.store.writeAdapterInvocation) {\n\t\t\t\tif (!writer.writeAdapterInvocation) throw new HostError(\"Conditional adapter writes require transaction-scoped support.\");\n\t\t\t\tconst expectedStatuses = ownVerdict\n\t\t\t\t\t? [adapterStatuses.get(id) ?? \"running\"]\n\t\t\t\t\t: patch.status === \"ambiguous\" ? [\"running\", \"ambiguous\"] as const : [\"running\", \"failed\"] as const;\n\t\t\t\tconst written = await writer.writeAdapterInvocation({ scope: adapterInvocationScope, condition, expectedStatuses,\n\t\t\t\t\tmutation: { kind: \"update\", id, patch } });\n\t\t\t\tif (!written) {\n\t\t\t\t\tif (!ownVerdict) throw new RecoverableFinalizationError(`Invocation lease or adapter condition lost: ${actionInvocationId}`);\n\t\t\t\t\temitPlatformHostTelemetry(options.telemetry, { kind: \"event\", name: \"invocation.adapter_evidence_refused\",\n\t\t\t\t\t\tmetricName: PLATFORM_HOST_METRIC_NAMES.adapterEvidenceRefused, occurredAt: now(), tenantId, spaceId,\n\t\t\t\t\t\tattributes: { actionInvocationId, adapterInvocationId: id, reason: \"verdict_or_row_changed\" } });\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t} else await writer.updateAdapterInvocation!(id, patch, adapterInvocationScope);\n\t\t\tif (patch.status && !transaction) adapterStatuses.set(id, patch.status);\n\t\t}\n\t\tasync function createAdapter(record: AdapterInvocationRecord) {\n\t\t\tif (executionLease && options.store.writeAdapterInvocation) {\n\t\t\t\tif (!await options.store.writeAdapterInvocation({ scope: adapterInvocationScope, condition: { kind: \"lease\", ...executionLease }, mutation: { kind: \"create\", record } })) {\n\t\t\t\t\tthrow new RecoverableFinalizationError(`Invocation lease or adapter condition lost: ${actionInvocationId}`);\n\t\t\t\t}\n\t\t\t} else await options.store.createAdapterInvocation(record);\n\t\t\tadapterStatuses.set(record.id, record.status);\n\t\t}\n\t\tconst adapterInvocationScope = { tenantId: invocation.tenantId, spaceId: invocation.spaceId, actionInvocationId: invocation.id };\n\t\tlet hasDurableProviderEffect = invocation.pendingCompletion !== undefined;\n\t\t// Protect Host ledger operations; authorization, policy and handler callbacks are not wrapped here.\n\t\tasync function hostOperation<TResult>(operation: () => Promise<TResult>): Promise<TResult> {\n\t\t\ttry { return await operation(); } catch (error) {\n\t\t\t\tif (error instanceof RecoverableFinalizationError || !hasDurableProviderEffect || isReconciliationRequiredError(error)) throw error;\n\t\t\t\tthrow new RecoverableFinalizationError(caughtError({ actionId: invocation.actionId, source: \"execution\" }, error));\n\t\t\t}\n\t\t}\n\t\tasync function settleAppliedEffect(message: string, handoff?: PendingExternalCompletion): Promise<ExecuteActionResult> {\n\t\t\tconst error = ownVerdict?.kind === \"verdict\" ? ownVerdict.error ?? message\n\t\t\t\t: `${message}${message.endsWith(\".\") ? \"\" : \".\"} A provider effect was applied and Host did not finish.${handoff ? ` External reference: ${handoff.externalReference}.` : \"\"}`;\n\t\t\ttry {\n\t\t\t\tawait persistExecutionVerdict(invocation, { status: \"reconciliation_required\", error },\n\t\t\t\t\thandoff && asGovernanceStore(options.store) ? [() => externalCompletion.recordCompletionReconciliation(invocation,\n\t\t\t\t\t\t{ provider: handoff.provider, externalReference: handoff.externalReference, kind: \"interrupted\" }, error)] : []);\n\t\t\t} catch (cause) {\n\t\t\t\tif (cause instanceof RecoverableFinalizationError) throw cause;\n\t\t\t\tthrow new RecoverableFinalizationError(caughtError({ actionId: invocation.actionId, source: \"execution\" }, cause));\n\t\t\t}\n\t\t\treturn withConsistency({ actionInvocationId, status: \"reconciliation_required\" as const, error }, invocation.actionId);\n\t\t}\n\n\t\tif (resumingRunningInvocation && invocation.leaseOwner && invocation.attemptCount > recoveryMaxAttempts) {\n\t\t\tconst message = `recovery attempts exhausted (${invocation.attemptCount}/${recoveryMaxAttempts})`\n\t\t\t\t+ (invocation.pendingCompletion ? `. A provider effect was applied and Host did not finish. External reference: ${invocation.pendingCompletion.externalReference}.` : \"\");\n\t\t\ttry {\n\t\t\t\tawait persistExecutionVerdict(invocation, { status: \"reconciliation_required\", error: message });\n\t\t\t} catch { throw new RecoverableFinalizationError(message); }\n\t\t\t// The verdict released this generation's lease. Evidence enrichment\n\t\t\t// below uses the terminal record, rather than the former lease fence.\n\t\t\tinvocation = { ...invocation, status: \"reconciliation_required\", error: message, leaseOwner: undefined, leaseToken: undefined, leaseExpiresAt: undefined };\n\t\t\tlet uncertain: { stepIndex: number; record: AdapterInvocationRecord } | undefined;\n\t\t\ttry {\n\t\t\t\tconst resolved = actionResolver(invocation.actionId);\n\t\t\t\tfor (const [stepIndex] of (resolved?.adapterSteps ?? []).entries()) {\n\t\t\t\t\tconst record = await options.store.getAdapterInvocation(lifecycleId(\"adp\", actionInvocationId, String(stepIndex)), adapterInvocationScope);\n\t\t\t\t\tif (record) adapterStatuses.set(record.id, record.status);\n\t\t\t\t\tif (record && record.id === invocation.pendingCompletion?.adapterInvocationId) continue;\n\t\t\t\t\tif (record?.status === \"running\" || record?.status === \"ambiguous\") { uncertain = { stepIndex, record }; break; }\n\t\t\t\t}\n\t\t\t} catch { /* The plain verdict is already durable when evidence reads fail. */ }\n\t\t\tif (uncertain) {\n\t\t\t\tconst { stepIndex, record } = uncertain;\n\t\t\t\tadapterStatuses.set(record.id, record.status);\n\t\t\t\tif (record.status === \"ambiguous\") {\n\t\t\t\t\tconst recorded = recordedAdapterReconciliation(record);\n\t\t\t\t\treturn settleUnknownOutcome(stepIndex, { ...recorded, message: `${message}. ${recorded.message}` }, record.reconciliation?.adapterEventSubject);\n\t\t\t\t}\n\t\t\t\treturn settleUnknownOutcome(stepIndex, {\n\t\t\t\t\tkind: \"adapter_outcome_ambiguous\", adapterInvocationId: record.id,\n\t\t\t\t\tadapterType: record.adapterType, operation: record.operation, vendor: record.vendor, message,\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (invocation.pendingCompletion) return settleAppliedEffect(message, invocation.pendingCompletion);\n\t\t\treturn { actionInvocationId, status: \"reconciliation_required\", error: message };\n\t\t}\n\n\t\tasync function settleUnknownOutcome(\n\t\t\tstepIndex: number,\n\t\t\tadapterReconciliation: AdapterReconciliationOutcome,\n\t\t\tadapterEventSubject = { subjectType: \"AdapterInvocation\", subjectId: adapterReconciliation.adapterInvocationId },\n\t\t) {\n\t\t\tconst { message, externalReference, adapterInvocationId, adapterType, operation, vendor } = adapterReconciliation;\n\t\t\tconst patch: ActionInvocationPatch = { status: \"reconciliation_required\", error: message, adapterReconciliation };\n\t\t\tconst governanceStore = asGovernanceStore(options.store);\n\t\t\tasync function checkpoint(transaction?: PlatformHostMutationTransaction<TDb>) {\n\t\t\t\tconst legacyPatch = { status: \"ambiguous\" as const, error: message, updatedAt: now() };\n\t\t\t\ttry {\n\t\t\t\t\tawait writeAdapter(adapterInvocationId, {\n\t\t\t\t\t\t...legacyPatch, reconciliation: { ...adapterReconciliation, adapterEventSubject },\n\t\t\t\t\t}, transaction);\n\t\t\t\t} catch (error) {\n\t\t\t\t\t// PostgreSQL errors abort the transaction: let it roll back, then\n\t\t\t\t\t// use the legacy shape outside it after selecting the fallback.\n\t\t\t\t\tif (transaction || error instanceof RecoverableFinalizationError) throw error;\n\t\t\t\t\tawait writeAdapter(adapterInvocationId, legacyPatch);\n\t\t\t\t}\n\t\t\t}\n\t\t\tasync function evidence(transaction?: PlatformHostMutationTransaction<TDb>) {\n\t\t\t\tconst writes = [\n\t\t\t\t\t() => checkpoint(transaction),\n\t\t\t\t\t() => appendEvent(invocation, {\n\t\t\t\t\t\teventType: \"AdapterInvocationAmbiguous\",\n\t\t\t\t\t\tsubjectType: adapterEventSubject.subjectType,\n\t\t\t\t\t\tsubjectId: adapterEventSubject.subjectId,\n\t\t\t\t\t\tpayload: { adapterType, operation,\n\t\t\t\t\t\t\t...(externalReference ? { externalReference } : {}) },\n\t\t\t\t\t}, `adapter:${stepIndex}:ambiguous`, 1, transaction),\n\t\t\t\t\t...(governanceStore ? [() => (transaction ?? governanceStore).appendExternalReconciliation!({\n\t\t\t\t\t\tid: lifecycleId(\"rec\", actionInvocationId, `${vendor}:${adapterInvocationId}`),\n\t\t\t\t\t\tactionInvocationId, tenantId, spaceId, status: \"pending\", provider: vendor,\n\t\t\t\t\t\t...(externalReference ? { externalOperationId: externalReference } : {}),\n\t\t\t\t\t\tattempt: 1, reason: message, observedAt: now(),\n\t\t\t\t\t})] : []),\n\t\t\t\t];\n\t\t\t\tif (transaction) {\n\t\t\t\t\tfor (const write of writes) await write();\n\t\t\t\t} else {\n\t\t\t\t\tawait attemptEvidenceWrites(writes);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tasync function finalizeAtomically(): Promise<boolean> {\n\t\t\t\tconst atomicStore = asAtomicMutationStore(options.store);\n\t\t\t\tif (!atomicStore || ownVerdict) return false;\n\t\t\t\tconst previousStatus = invocation.status;\n\t\t\t\tlet verdictWritten = false;\n\t\t\t\tconst finalize = () => atomicStore.transactionWithEvents(async transaction => {\n\t\t\t\t\tif (!transaction.updateAdapterInvocation ||\n\t\t\t\t\t\t(options.store.writeAdapterInvocation && (executionLease || ownVerdict) && !transaction.writeAdapterInvocation) ||\n\t\t\t\t\t\t(governanceStore && !transaction.appendExternalReconciliation) ||\n\t\t\t\t\t\t(executionLease && !transaction.updateLeasedActionInvocation)) return false;\n\t\t\t\t\tawait evidence(transaction);\n\t\t\t\t\t// Evidence precedes the verdict, which releases the lease.\n\t\t\t\t\tif (executionLease) {\n\t\t\t\t\t\tconst updated = await transaction.updateLeasedActionInvocation!({\n\t\t\t\t\t\t\tid: actionInvocationId, tenantId, spaceId,\n\t\t\t\t\t\t\tworkerId: executionLease.leaseOwner, leaseToken: executionLease.leaseToken, patch,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (!updated) throw new RecoverableFinalizationError(`Invocation lease lost: ${actionInvocationId}`);\n\t\t\t\t\t\tverdictWritten = true;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tverdictWritten = await writeInlineInvocation(invocation, patch, transaction, onPreservedReconciliation);\n\t\t\t\t\t}\n\t\t\t\t\treturn true;\n\t\t\t\t});\n\t\t\t\tlet committed: boolean;\n\t\t\t\ttry {\n\t\t\t\t\tcommitted = await finalize();\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (error instanceof RecoverableFinalizationError) throw error;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tcommitted = await finalize();\n\t\t\t\t\t} catch (retryError) {\n\t\t\t\t\t\tif (retryError instanceof RecoverableFinalizationError) throw retryError;\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (committed && verdictWritten) {\n\t\t\t\t\trememberVerdict(patch);\n\t\t\t\t\temitInvocationStatusTelemetry(invocation, patch.status, options.telemetry, now(), previousStatus);\n\t\t\t\t}\n\t\t\t\treturn committed;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tif (!await finalizeAtomically()) {\n\t\t\t\t\tawait persistExecutionVerdict(invocation, patch, [() => evidence()]);\n\t\t\t\t}\n\t\t\t\treturn withConsistency(actionResult(invocation), invocation.actionId);\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof RecoverableFinalizationError) throw error;\n\t\t\t\tthrow new RecoverableFinalizationError(caughtError({ actionId: invocation.actionId, source: \"execution\" }, error));\n\t\t\t}\n\t\t}\n\t\tfunction recordedAdapterReconciliation(record: AdapterInvocationRecord): AdapterReconciliationOutcome {\n\t\t\tif (record.reconciliation) {\n\t\t\t\tconst { adapterEventSubject: _subject, ...outcome } = record.reconciliation;\n\t\t\t\treturn outcome;\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tkind: \"adapter_outcome_ambiguous\", adapterType: record.adapterType, operation: record.operation,\n\t\t\t\tvendor: record.vendor, adapterInvocationId: record.id,\n\t\t\t\tmessage: record.error ?? \"Adapter outcome was recorded ambiguous earlier; reconciliation required\",\n\t\t\t\t...(record.error ? { reason: record.error } : {}),\n\t\t\t};\n\t\t}\n\n\t\tconst action = actionResolver(invocation.actionId);\n\t\tif (action && (resumingRunningInvocation || invocation.attemptCount > 1)) {\n\t\t\ttry {\n\t\t\t\t// Reconcile recorded uncertainty before recovery can reject or rerun the action.\n\t\t\t\tfor (const [stepIndex] of (action.adapterSteps ?? []).entries()) {\n\t\t\t\t\tconst record = await options.store.getAdapterInvocation(lifecycleId(\"adp\", actionInvocationId, String(stepIndex)), adapterInvocationScope);\n\t\t\t\t\tif (record) adapterStatuses.set(record.id, record.status);\n\t\t\t\t\tif (record?.status === \"succeeded\") hasDurableProviderEffect = true;\n\t\t\t\t\tif (record?.status !== \"ambiguous\") continue;\n\t\t\t\t\treturn await settleUnknownOutcome(stepIndex, recordedAdapterReconciliation(record),\n\t\t\t\t\t\trecord.reconciliation?.adapterEventSubject);\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof RecoverableFinalizationError) throw error;\n\t\t\t\tthrow new RecoverableFinalizationError(caughtError({ actionId: invocation.actionId, source: \"execution\" }, error));\n\t\t\t}\n\t\t}\n\n\t\tif (invocation.status === \"running\" && invocation.pendingCompletion && !invocation.leaseOwner) {\n\t\t\t// Leased handoffs continue into checkpoint repair; unleased handoffs wait for completion.\n\t\t\treturn withConsistency(actionResult(invocation), invocation.actionId);\n\t\t}\n\t\tif (!action) {\n\t\t\treturn hostOperation(() => failExecution(invocation, \"failed\", `Unknown action: ${invocation.actionId}`));\n\t\t}\n\n\t\tif (action.admitSubmission !== undefined && !isAdmissionTime(invocation.admittedAt)) {\n\t\t\t// Created without this host's admission: by an older host, a direct\n\t\t\t// store write, or before the action declared its check.\n\t\t\treturn hostOperation(() => failExecution(\n\t\t\t\tinvocation,\n\t\t\t\t\"failed\",\n\t\t\t\t`Invocation of ${action.actionId} was not admitted at submission; an action that declares admitSubmission runs only on invocations its check admitted.`,\n\t\t\t));\n\t\t}\n\t\tif (action.kind === \"saga\") {\n\t\t\treturn hostOperation(() => failExecution(\n\t\t\t\tinvocation,\n\t\t\t\t\"failed\",\n\t\t\t\t`Saga action ${invocation.actionId} requires a durable PlatformActionDispatcher and cannot execute as an atomic Host action.`,\n\t\t\t));\n\t\t}\n\t\tasync function interruptedNonIdempotent(message: string): Promise<ExecuteActionResult> {\n\t\t\ttry {\n\t\t\t\tlet succeeded = invocation.pendingCompletion !== undefined;\n\t\t\t\tfor (const [stepIndex] of (action!.adapterSteps ?? []).entries()) {\n\t\t\t\t\tconst record = await options.store.getAdapterInvocation(lifecycleId(\"adp\", actionInvocationId, String(stepIndex)), adapterInvocationScope);\n\t\t\t\t\tif (record) adapterStatuses.set(record.id, record.status);\n\t\t\t\t\tif (record && record.id === invocation.pendingCompletion?.adapterInvocationId) continue;\n\t\t\t\t\tif (record?.status === \"running\") {\n\t\t\t\t\t\treturn await settleUnknownOutcome(stepIndex, {\n\t\t\t\t\t\t\tkind: \"adapter_outcome_ambiguous\", adapterInvocationId: record.id,\n\t\t\t\t\t\t\tadapterType: record.adapterType, operation: record.operation, vendor: record.vendor,\n\t\t\t\t\t\t\tmessage: `${message} Provider outcome was not recorded.`,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tsucceeded ||= record?.status === \"succeeded\";\n\t\t\t\t}\n\t\t\t\tif (succeeded) return await settleAppliedEffect(message, invocation.pendingCompletion);\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof RecoverableFinalizationError) throw error;\n\t\t\t\tthrow new RecoverableFinalizationError(caughtError({ actionId: invocation.actionId, source: \"execution\" }, error));\n\t\t\t}\n\t\t\treturn hostOperation(() => failExecution(invocation, \"failed\", message));\n\t\t}\n\n\t\tif (\n\t\t\tresumingRunningInvocation &&\n\t\t\tinvocation.attemptCount === 0 &&\n\t\t\t!invocation.leaseOwner &&\n\t\t\t!action.idempotent\n\t\t) {\n\t\t\treturn interruptedNonIdempotent(\n\t\t\t\t`Interrupted inline action ${invocation.actionId} is not declared idempotent; manual reconciliation is required.`,\n\t\t\t);\n\t\t}\n\t\tif (invocation.attemptCount > 1 && !action.idempotent) {\n\t\t\treturn interruptedNonIdempotent(\n\t\t\t\t`Interrupted action ${invocation.actionId} is not declared idempotent; manual reconciliation is required.`,\n\t\t\t);\n\t\t}\n\t\tif (invocation.status !== \"running\") {\n\t\t\tawait hostOperation(() => options.store.updateActionInvocation(actionInvocationId, tenantId, spaceId, {\n\t\t\t\tstatus: \"running\",\n\t\t\t}));\n\t\t}\n\t\temitPlatformHostTelemetry(options.telemetry, {\n\t\t\tkind: \"event\",\n\t\t\tname: \"invocation.execution_started\",\n\t\t\tmetricName: PLATFORM_HOST_METRIC_NAMES.invocationExecutionStarted,\n\t\t\toccurredAt: now(),\n\t\t\ttenantId,\n\t\t\tspaceId,\n\t\t\tattributes: { actionVersion: invocation.actionVersion },\n\t\t});\n\t\tlet retryableGovernance = true;\n\t\ttry {\n\n\t\tconst parsed = action.schema.safeParse(invocation.parameters);\n\t\tif (!parsed.success) {\n\t\t\tconst message = parsed.error.issues\n\t\t\t\t.map((issue) => `${issue.path.join(\".\") || \"(root)\"}: ${issue.message}`)\n\t\t\t\t.join(\"; \");\n\t\t\treturn hostOperation(() => failExecution(invocation, \"validation_failed\", message));\n\t\t}\n\n\t\tif (options.resolveMutationGovernance && !invocation.mutationFootprint) {\n\t\t\tconst governanceStore = asGovernanceStore(options.store);\n\t\t\tif (!governanceStore) {\n\t\t\t\treturn hostOperation(() => failExecution(invocation, \"failed\", \"The configured mutation-governance resolver requires a governance-capable store.\"));\n\t\t\t}\n\t\t\tconst context = await options.resolveMutationGovernance({\n\t\t\t\tactionInvocationId, actionId: action.actionId, tenantId, spaceId,\n\t\t\t\tactorId: invocation.actorId, actorType: invocation.actorType, parameters: parsed.data,\n\t\t\t});\n\t\t\tassertMutationGovernanceContext(context);\n\t\t\tinvocation = { ...await hostOperation(() => governanceStore.recordMutationGovernance(actionInvocationId, tenantId, spaceId, context)) };\n\t\t}\n\n\t\tif (invocation.actorType === \"agent\" && options.hitlEvaluator) {\n\t\t\tconst hitlParameters = isRecord(parsed.data) ? parsed.data : invocation.parameters;\n\t\t\tconst approvalStore = asApprovalStore(options.store);\n\t\t\tif (!approvalStore) {\n\t\t\t\treturn hostOperation(() => failExecution(\n\t\t\t\t\tinvocation,\n\t\t\t\t\t\"failed\",\n\t\t\t\t\t\"The configured HITL evaluator requires a store with approval persistence support.\",\n\t\t\t\t));\n\t\t\t}\n\t\t\tif (!invocation.hitlRoute) {\n\t\t\t\tconst decision = await options.hitlEvaluator({\n\t\t\t\t\tactionId: action.actionId,\n\t\t\t\t\tactorId: invocation.actorId,\n\t\t\t\t\tactorType: invocation.actorType,\n\t\t\t\t\ttenantId,\n\t\t\t\t\tspaceId,\n\t\t\t\t\tparameters: hitlParameters,\n\t\t\t\t\t...(numberValue(hitlParameters.confidence) !== undefined\n\t\t\t\t\t\t? { confidence: numberValue(hitlParameters.confidence) }\n\t\t\t\t\t\t: {}),\n\t\t\t\t\t...(isRiskTier(hitlParameters.riskTier)\n\t\t\t\t\t\t? { riskTier: hitlParameters.riskTier }\n\t\t\t\t\t\t: {}),\n\t\t\t\t\t...(stringValue(hitlParameters.agentSessionId)\n\t\t\t\t\t\t? { agentSessionId: stringValue(hitlParameters.agentSessionId) }\n\t\t\t\t\t\t: {}),\n\t\t\t\t\t...(stringValue(hitlParameters.agentRunId)\n\t\t\t\t\t\t? { agentRunId: stringValue(hitlParameters.agentRunId) }\n\t\t\t\t\t\t: {}),\n\t\t\t\t});\n\t\t\t\tinvocation = { ...await hostOperation(() => approvalStore.recordHitlDecision(\n\t\t\t\t\tactionInvocationId,\n\t\t\t\t\ttenantId,\n\t\t\t\t\tspaceId,\n\t\t\t\t\t{\n\t\t\t\t\t\t...decision,\n\t\t\t\t\t\t...(options.hitlPolicyVersion\n\t\t\t\t\t\t\t? { policyVersion: options.hitlPolicyVersion }\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\tevaluatedAt: now(),\n\t\t\t\t\t},\n\t\t\t\t)) };\n\t\t\t}\n\t\t\tif (invocation.hitlRoute === \"rejected\") {\n\t\t\t\treturn hostOperation(() => failExecution(\n\t\t\t\t\tinvocation,\n\t\t\t\t\t\"failed\",\n\t\t\t\t\t`HITL rejected: ${invocation.hitlReason ?? \"no reason provided\"}`,\n\t\t\t\t));\n\t\t\t}\n\t\t\tif (\n\t\t\t\t(invocation.hitlRoute === \"needs-approval\" ||\n\t\t\t\t\tinvocation.hitlRoute === \"escalate\") &&\n\t\t\t\t!invocation.approvalDecision?.approved\n\t\t\t) {\n\t\t\t\tawait hostOperation(() => persistExecutionInvocation(invocation, {\n\t\t\t\t\tstatus: \"waiting_for_approval\",\n\t\t\t\t}));\n\t\t\t\treturn {\n\t\t\t\t\t...actionResult(invocation),\n\t\t\t\t\tstatus: \"waiting_for_approval\",\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\tconst authorizationInput = toAuthorizationInput(action, invocation);\n\t\tconst executionReason = executionReasonOverride ??\n\t\t\t(invocation.attemptCount > 1 || (resumingRunningInvocation && invocation.attemptCount === 0)\n\t\t\t\t? \"recovery\"\n\t\t\t\t: invocation.executionReason ?? \"initial\");\n\t\tif (!(await options.authorization.checkEntitlement(authorizationInput))) {\n\t\t\treturn hostOperation(() => failExecution(\n\t\t\t\tinvocation,\n\t\t\t\t\"failed\",\n\t\t\t\t`Module \"${action.namespace}\" is no longer enabled for tenant ${tenantId}`,\n\t\t\t));\n\t\t}\n\t\tconst authorityMoment = action.execution?.authorityMoment;\n\t\tif (authorityMoment === \"capture\" && !invocation.authorizationBinding) {\n\t\t\tconst reconciliation = {\n\t\t\t\tkind: \"authorization_missing_capture_evidence\" as const,\n\t\t\t\tgoverningMoment: authorityMoment,\n\t\t\t\texecutionReason,\n\t\t\t\t...(invocation.provenance ? { provenance: invocation.provenance } : {}),\n\t\t\t\tmessage: `Action ${action.actionId} requires durable capture-time authorization evidence`,\n\t\t\t};\n\t\t\tawait hostOperation(() => persistExecutionInvocation(invocation, { status: \"reconciliation_required\", error: reconciliation.message, authorizationReconciliation: reconciliation }));\n\t\t\treturn withConsistency({ actionInvocationId, status: \"reconciliation_required\" as const, error: reconciliation.message, reconciliation }, action.actionId);\n\t\t}\n\t\tconst bindingExpired = authorityMoment !== \"capture\" && invocation.authorizationBinding?.expiresAt !== undefined &&\n\t\t\tDate.parse(invocation.authorizationBinding.expiresAt) <= now().getTime();\n\t\tif (bindingExpired) {\n\t\t\tconst reconciliation = {\n\t\t\t\tkind: \"authorization_expired\" as const,\n\t\t\t\tgoverningMoment: authorityMoment ?? \"both\",\n\t\t\t\texecutionReason,\n\t\t\t\t...(invocation.authorizationBindingId ? { authorizationBindingId: invocation.authorizationBindingId } : {}),\n\t\t\t\t...(invocation.provenance ? { provenance: invocation.provenance } : {}),\n\t\t\t\tmessage: `Authorization binding for action ${action.actionId} expired before execution`,\n\t\t\t};\n\t\t\tawait hostOperation(() => persistExecutionInvocation(invocation, { status: \"reconciliation_required\", error: reconciliation.message, authorizationReconciliation: reconciliation }));\n\t\t\treturn withConsistency({ actionInvocationId, status: \"reconciliation_required\" as const, error: reconciliation.message, reconciliation }, action.actionId);\n\t\t}\n\t\tconst executionAuthorized = authorityMoment === \"capture\"\n\t\t\t? invocation.authorizationBinding !== undefined\n\t\t\t: options.authorization.authorizeExecution\n\t\t\t\t? await options.authorization.authorizeExecution({\n\t\t\t\t\t...authorizationInput,\n\t\t\t\t\tactionInvocationId,\n\t\t\t\t\tparameters: parsed.data,\n\t\t\t\t\tinvocation,\n\t\t\t\t\texecutionReason,\n\t\t\t\t})\n\t\t\t\t: await options.authorization.authorize(authorizationInput);\n\t\tif (!executionAuthorized) {\n\t\t\tif (!action.execution) {\n\t\t\t\treturn hostOperation(() => failExecution(invocation, \"failed\", `Actor ${invocation.actorId} is not authorized to execute action ${action.actionId}`));\n\t\t\t}\n\t\t\tconst reconciliation = {\n\t\t\t\tkind: \"authorization_denied\" as const,\n\t\t\t\tgoverningMoment: action.execution?.authorityMoment ?? \"both\",\n\t\t\t\texecutionReason,\n\t\t\t\t...(invocation.authorizationBindingId ? { authorizationBindingId: invocation.authorizationBindingId } : {}),\n\t\t\t\t...(invocation.provenance ? { provenance: invocation.provenance } : {}),\n\t\t\t\tmessage: `Actor ${invocation.actorId} is not authorized to execute action ${action.actionId}`,\n\t\t\t};\n\t\t\tawait hostOperation(() => persistExecutionInvocation(invocation, { status: \"reconciliation_required\", error: reconciliation.message, authorizationReconciliation: reconciliation }));\n\t\t\treturn withConsistency({ actionInvocationId, status: \"reconciliation_required\" as const, error: reconciliation.message, reconciliation }, action.actionId);\n\t\t}\n\t\tconst definitions = options.resolvePolicies\n\t\t\t? await options.resolvePolicies({\n\t\t\t\t\t...authorizationInput,\n\t\t\t\t\tactionInvocationId,\n\t\t\t\t\tparameters: parsed.data,\n\t\t\t\t\tinvocation,\n\t\t\t\t\texecutionReason,\n\t\t\t\t\tdeclaredPolicyIds: action.policies ?? [],\n\t\t\t\t})\n\t\t\t: declaredPolicies(action.policies ?? []);\n\t\tconst outcomes = await evaluatePolicyDefinitions(definitions, {\n\t\t\ttenantId,\n\t\t\tspaceId,\n\t\t\tactionInvocationId,\n\t\t\tactionId: action.actionId,\n\t\t\tactorId: invocation.actorId,\n\t\t\tactorType: invocation.actorType,\n\t\t\tparameters: parsed.data,\n\t\t\tdb: options.store.db,\n\t\t\tservices: options.services,\n\t\t\tresolveCodePolicy: options.registry?.resolvePolicy,\n\t\t\tmode: \"execute\",\n\t\t\tnow: now(),\n\t\t});\n\t\t// End deferral before policy evidence can fix a decision for this attempt.\n\t\tretryableGovernance = false;\n\t\tfor (const outcome of outcomes) {\n\t\t\tawait hostOperation(() => options.store.appendPolicyEvaluation({\n\t\t\t\tid: lifecycleId(\"pol\", actionInvocationId, outcome.policyId),\n\t\t\t\tactionInvocationId,\n\t\t\t\ttenantId,\n\t\t\t\tspaceId,\n\t\t\t\toutcome,\n\t\t\t\tcreatedAt: now(),\n\t\t\t}));\n\t\t}\n\t\tconst aggregate = aggregatePolicyOutcomes(outcomes);\n\t\tif (aggregate?.result === \"block\") {\n\t\t\tconst reason = aggregate.reason ?? `Blocked by policy ${aggregate.policyId}`;\n\t\t\tawait hostOperation(() => appendEvent(invocation, {\n\t\t\t\teventType: \"ComplianceBlocked\",\n\t\t\t\tsubjectType: \"ActionInvocation\",\n\t\t\t\tsubjectId: actionInvocationId,\n\t\t\t\tpayload: { actionId: action.actionId, policyId: aggregate.policyId, reason },\n\t\t\t}, `compliance:${aggregate.policyId}`));\n\t\t\treturn hostOperation(() => failExecution(invocation, \"blocked_by_policy\", reason));\n\t\t}\n\t\tif (options.resolvePolicyObligations) {\n\t\t\tconst governanceStore = asGovernanceStore(options.store);\n\t\t\tif (!governanceStore) {\n\t\t\t\treturn hostOperation(() => failExecution(invocation, \"failed\", \"Policy obligations require a governance-capable store.\"));\n\t\t\t}\n\t\t\tconst existing = await hostOperation(() => governanceStore.listPolicyObligations(actionInvocationId, tenantId, spaceId));\n\t\t\tif (existing.length === 0) {\n\t\t\t\tconst createdAt = now();\n\t\t\t\tconst obligations = await options.resolvePolicyObligations(outcomes);\n\t\t\t\tawait hostOperation(() => governanceStore.appendPolicyObligations(obligations.map((obligation) => ({\n\t\t\t\t\t...obligation, status: obligation.status ?? \"pending\", actionInvocationId,\n\t\t\t\t\ttenantId, spaceId, createdAt, updatedAt: createdAt,\n\t\t\t\t}))));\n\t\t\t}\n\t\t}\n\n\t\tlet data: Record<string, unknown>;\n\t\tlet domainEvents: PendingAssetEvent[] = [];\n\t\tlet pendingTransitionEvent: PendingAssetEvent | undefined;\n\t\ttry {\n\t\t\tconst runHandler = async (\n\t\t\t\tdb: TDb,\n\t\t\t\ttransaction?: PlatformHostMutationTransaction<TDb>,\n\t\t\t) => {\n\t\t\t\tif (options.outbox && !transaction?.appendEventWithOutbox) {\n\t\t\t\t\tthrow new HostError(\"Outbox egress requires transactionWithEvents to provide appendEventWithOutbox before handler execution.\");\n\t\t\t\t}\n\t\t\t\tconst binding = action.stateMachine;\n\t\t\t\tlet replayedTransition: ActionInvocationRecord[\"pendingStateTransition\"];\n\t\t\t\tlet pendingStateTransition: ActionInvocationRecord[\"pendingStateTransition\"];\n\t\t\t\tlet validatedTransition: {\n\t\t\t\t\tentityId: string | undefined;\n\t\t\t\t\tcurrentState: string;\n\t\t\t\t\ttargetState: string;\n\t\t\t\t\tvalid: boolean;\n\t\t\t\t} | undefined;\n\t\t\t\tif (binding) {\n\t\t\t\t\tconst machine = stateMachineResolver(binding.entityType);\n\t\t\t\t\tconst entityId = binding.getEntityId(parsed.data);\n\t\t\t\t\tconst getEntityState = transaction?.getEntityState\n\t\t\t\t\t\t? transaction.getEntityState.bind(transaction)\n\t\t\t\t\t\t: options.store.getEntityState.bind(options.store);\n\t\t\t\t\tconst currentState = entityId\n\t\t\t\t\t\t? ((await hostOperation(() => getEntityState(\n\t\t\t\t\t\t\t\ttenantId,\n\t\t\t\t\t\t\t\tspaceId,\n\t\t\t\t\t\t\t\tbinding.entityType,\n\t\t\t\t\t\t\t\tentityId,\n\t\t\t\t\t\t\t))) ?? initialState(machine))\n\t\t\t\t\t\t: initialState(machine);\n\t\t\t\t\tconst targetState =\n\t\t\t\t\t\ttypeof binding.targetState === \"function\"\n\t\t\t\t\t\t\t? binding.targetState(parsed.data)\n\t\t\t\t\t\t\t: binding.targetState;\n\t\t\t\t\tif (targetState !== \"\") {\n\t\t\t\t\t\tconst transition = await evaluateStateMachineTransition(\n\t\t\t\t\t\t\tmachine,\n\t\t\t\t\t\t\tbinding.entityType,\n\t\t\t\t\t\t\tcurrentState,\n\t\t\t\t\t\t\ttargetState,\n\t\t\t\t\t\t\taction.actionId,\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tentity: {\n\t\t\t\t\t\t\t\t\t...(entityId ? { id: entityId } : {}),\n\t\t\t\t\t\t\t\t\tstate: currentState,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tactionInvocationId,\n\t\t\t\t\t\t\t\tactorId: invocation.actorId,\n\t\t\t\t\t\t\t\tparameters: parsed.data,\n\t\t\t\t\t\t\t\tdb,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t);\n\t\t\t\t\t\tvalidatedTransition = { entityId, currentState, targetState, valid: transition.valid };\n\t\t\t\t\t\tlet replayingAppliedTransition = false;\n\t\t\t\t\t\tif (action.idempotent && currentState === targetState && !transition.valid && entityId) {\n\t\t\t\t\t\t\tlet source: { state: string; actionInvocationId: string } | undefined;\n\t\t\t\t\t\t\tif (transaction?.getEntityStateSource) {\n\t\t\t\t\t\t\t\tsource = await hostOperation(() => transaction.getEntityStateSource!(tenantId, spaceId, binding.entityType, entityId));\n\t\t\t\t\t\t\t} else if (options.store.getEntityStateSource) {\n\t\t\t\t\t\t\t\tsource = await hostOperation(() => options.store.getEntityStateSource!(tenantId, spaceId, binding.entityType, entityId));\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tconst eventStore = options.store as typeof options.store & {\n\t\t\t\t\t\t\t\t\tlistEvents?: (tenantId: string, spaceId: string) => Promise<AssetEventEnvelope[]>;\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\tconst listEvents = transaction?.listEvents?.bind(transaction) ?? eventStore.listEvents?.bind(eventStore);\n\t\t\t\t\t\t\t\tconst events = listEvents ? await hostOperation(() => listEvents(tenantId, spaceId)) : [];\n\t\t\t\t\t\t\t\tlet latest: AssetEventEnvelope | undefined;\n\t\t\t\t\t\t\t\tfor (const event of events) {\n\t\t\t\t\t\t\t\t\tif (event.tenantId === tenantId && event.spaceId === spaceId &&\n\t\t\t\t\t\t\t\t\t\tevent.subjectType === binding.entityType && event.subjectId === entityId &&\n\t\t\t\t\t\t\t\t\t\ttypeof (event.payload as { toState?: unknown } | undefined)?.toState === \"string\" &&\n\t\t\t\t\t\t\t\t\t\t(!latest || event.sequence > latest.sequence)) latest = event;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (latest && typeof latest.actionInvocationId === \"string\") {\n\t\t\t\t\t\t\t\t\tsource = { state: (latest.payload as { toState: string }).toState, actionInvocationId: latest.actionInvocationId };\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treplayingAppliedTransition = source?.actionInvocationId === actionInvocationId && source.state === currentState;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst pending = invocation.pendingStateTransition;\n\t\t\t\t\t\tif (replayingAppliedTransition && pending &&\n\t\t\t\t\t\t\tpending.entityType === binding.entityType && pending.entityId === entityId &&\n\t\t\t\t\t\t\tpending.toState === currentState) {\n\t\t\t\t\t\t\treplayedTransition = pending;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (action.idempotent && transition.valid && entityId && action.eventPhase === \"after_adapters\") {\n\t\t\t\t\t\t\tpendingStateTransition = {\n\t\t\t\t\t\t\t\tentityType: binding.entityType, entityId, fromState: currentState, toState: targetState,\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tif (!transaction) {\n\t\t\t\t\t\t\t\tawait hostOperation(() => options.store.updateActionInvocation(actionInvocationId, tenantId, spaceId, { pendingStateTransition }));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!transition.valid && !replayingAppliedTransition) {\n\t\t\t\t\t\t\tthrow transition.error != null ? new Error(transition.error) : new HostError(\"Invalid state transition\");\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst handlerResult = action.handler\n\t\t\t\t\t? await action.handler(\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tactionInvocationId,\n\t\t\t\t\t\t\t\ttenantId,\n\t\t\t\t\t\t\t\tspaceId,\n\t\t\t\t\t\t\t\tactorId: invocation.actorId,\n\t\t\t\t\t\t\t\tactorType: invocation.actorType,\n\t\t\t\t\t\t\t\tcorrelationId: invocation.correlationId,\n\t\t\t\t\t\t\t\t...(invocation.causationId ? { causationId: invocation.causationId } : {}),\n\t\t\t\t\t\t\t\t...(invocation.provenance ? { provenance: invocation.provenance } : {}),\n\t\t\t\t\t\t\t\t...(isAdmissionTime(invocation.admittedAt) ? { admittedAt: invocation.admittedAt } : {}),\n\t\t\t\t\t\t\t\tdb,\n\t\t\t\t\t\t\t\tservices: options.services,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tparsed.data,\n\t\t\t\t\t\t)\n\t\t\t\t\t: { success: true as const, data: {} };\n\t\t\t\tif (!handlerResult.success) {\n\t\t\t\t\tthrow handlerResult.error != null ? new Error(handlerResult.error) : new HostError(\"Action handler failed\");\n\t\t\t\t}\n\t\t\t\tconst handlerData = handlerResult.data ?? {};\n\t\t\t\tif (action.resultSchema) {\n\t\t\t\t\tconst publicResult = withoutPrivateHostFields(handlerData, eventResultFields);\n\t\t\t\t\tconst parsedResult = action.resultSchema.safeParse(publicResult);\n\t\t\t\t\tif (!parsedResult.success) {\n\t\t\t\t\t\tthrow new HostError(`Action result validation failed at ${parsedResult.error.issues\n\t\t\t\t\t\t\t.map((issue) => issue.path.map(String).join(\".\") || \"result\")\n\t\t\t\t\t\t\t.join(\", \")}`);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst events = extractEvents(handlerData);\n\t\t\t\tconst undeclaredEvent = events.find(\n\t\t\t\t\t(event) => !action.emitsEvents.includes(event.eventType),\n\t\t\t\t);\n\t\t\t\tif (undeclaredEvent) {\n\t\t\t\t\tthrow new HostError(\n\t\t\t\t\t\t`${action.actionId} emitted undeclared event type ${undeclaredEvent.eventType}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (action.eventPhase !== \"after_adapters\") {\n\t\t\t\t\tfor (const [index, event] of events.entries()) {\n\t\t\t\t\t\tawait hostOperation(() => appendEvent(\n\t\t\t\t\t\t\tinvocation,\n\t\t\t\t\t\t\tevent,\n\t\t\t\t\t\t\t`domain:${index}`,\n\t\t\t\t\t\t\taction.version,\n\t\t\t\t\t\t\ttransaction,\n\t\t\t\t\t\t));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tlet transitionEvent: PendingAssetEvent | undefined;\n\t\t\t\tif (binding && validatedTransition?.entityId && (validatedTransition.valid || replayedTransition)) {\n\t\t\t\t\tconst { entityId, currentState, targetState } = validatedTransition;\n\t\t\t\t\tconst handlerEmittedTransition = events.some((event) =>\n\t\t\t\t\t\tevent.eventType === \"StateTransitioned\" &&\n\t\t\t\t\t\tevent.subjectType === binding.entityType && event.subjectId === entityId);\n\t\t\t\t\tif (!handlerEmittedTransition) {\n\t\t\t\t\t\ttransitionEvent = {\n\t\t\t\t\t\t\teventType: \"StateTransitioned\",\n\t\t\t\t\t\t\tsubjectType: binding.entityType,\n\t\t\t\t\t\t\tsubjectId: entityId,\n\t\t\t\t\t\t\tpayload: {\n\t\t\t\t\t\t\t\tentityType: binding.entityType, entityId, fromState: replayedTransition?.fromState ?? currentState,\n\t\t\t\t\t\t\t\ttoState: targetState, causedByAction: action.actionId,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (transitionEvent && action.eventPhase !== \"after_adapters\") {\n\t\t\t\t\tawait hostOperation(() => appendEvent(invocation, transitionEvent, \"state:transition\", 1, transaction));\n\t\t\t\t}\n\t\t\t\tif (transaction && pendingStateTransition) {\n\t\t\t\t\tawait hostOperation(() => transaction.updateActionInvocation(actionInvocationId, tenantId, spaceId, { pendingStateTransition }));\n\t\t\t\t}\n\t\t\t\treturn { data: handlerData, domainEvents: events, pendingTransitionEvent: transitionEvent };\n\t\t\t};\n\t\t\tconst atomicStore = asAtomicMutationStore(options.store);\n\t\t\t// A failed callback is a handler outcome; an entry/commit error belongs to the store.\n\t\t\t// A store may rethrow the callback's error wrapped, so classify by where it failed,\n\t\t\t// not by identity, and rethrow the callback's own error.\n\t\t\tlet callbackFailure: { error: unknown } | undefined;\n\t\t\tconst run = async (db: TDb, transaction?: PlatformHostMutationTransaction<TDb>) => {\n\t\t\t\tcallbackFailure = undefined;\n\t\t\t\ttry { return await runHandler(db, transaction); }\n\t\t\t\tcatch (error) { callbackFailure = { error }; throw error; }\n\t\t\t};\n\t\t\tconst executed = await (async () => {\n\t\t\t\ttry {\n\t\t\t\t\treturn atomicStore\n\t\t\t\t\t\t? await atomicStore.transactionWithEvents(transaction => run(transaction.db, transaction))\n\t\t\t\t\t\t: await options.store.transaction(db => run(db));\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (callbackFailure) throw callbackFailure.error;\n\t\t\t\t\treturn hostOperation(() => Promise.reject(error));\n\t\t\t\t}\n\t\t\t})();\n\t\t\tdata = executed.data;\n\t\t\tdomainEvents = executed.domainEvents;\n\t\t\tpendingTransitionEvent = executed.pendingTransitionEvent;\n\t\t} catch (error) {\n\t\t\tif (error instanceof RecoverableFinalizationError) throw error;\n\t\t\tif (isReconciliationRequiredError(error)) {\n\t\t\t\tconst message = caughtError({ actionId: invocation.actionId, source: \"handler\" }, error);\n\t\t\t\tawait hostOperation(() => persistExecutionInvocation(invocation, { status: \"reconciliation_required\", error: message }));\n\t\t\t\treturn withConsistency({\n\t\t\t\t\tactionInvocationId,\n\t\t\t\t\tstatus: \"reconciliation_required\" as const,\n\t\t\t\t\terror: message,\n\t\t\t\t\t...(invocation.hitlRoute ? { hitlRoute: invocation.hitlRoute } : {}),\n\t\t\t\t\t...(invocation.hitlRiskTier ? { hitlRiskTier: invocation.hitlRiskTier } : {}),\n\t\t\t\t}, action.actionId);\n\t\t\t}\n\t\t\treturn hostOperation(() => failExecution(invocation, \"failed\", caughtError({ actionId: invocation.actionId, source: \"handler\" }, error)));\n\t\t}\n\n\t\t// At most one adapter step may hand the work off to finish elsewhere. Two\n\t\t// would leave the invocation waiting on two references with one status.\n\t\t// A handoff is persisted the moment it is accepted, before the step is\n\t\t// marked done, so a crash between the two leaves the handoff and not\n\t\t// the marker: on re-execution the step is skipped and the handoff kept.\n\t\tlet pendingHandoff: PendingExternalCompletion | undefined = invocation.pendingCompletion;\n\t\tfor (const [stepIndex, step] of (action.adapterSteps ?? []).entries()) {\n\t\t\tconst adapterInvocationId = lifecycleId(\"adp\", actionInvocationId, String(stepIndex));\n\t\t\tlet previousAdapterInvocation: AdapterInvocationRecord | undefined;\n\t\t\ttry {\n\t\t\t\tpreviousAdapterInvocation = await options.store.getAdapterInvocation(adapterInvocationId, adapterInvocationScope);\n\t\t\t\tif (previousAdapterInvocation) adapterStatuses.set(adapterInvocationId, previousAdapterInvocation.status);\n\t\t\t\tconst handoff = pendingHandoff?.adapterInvocationId === adapterInvocationId ? pendingHandoff : undefined;\n\t\t\t\tif (previousAdapterInvocation?.status === \"succeeded\" || handoff) {\n\t\t\t\t\thasDurableProviderEffect = true;\n\t\t\t\t\tif (!previousAdapterInvocation) throw new HostError(\"Durable handoff has no adapter checkpoint; evidence repair requires reconciliation.\");\n\t\t\t\t\tconst row = previousAdapterInvocation;\n\t\t\t\t\tconst subject = options.adapterEventSubject?.(action.actionId, parsed.data, data)\n\t\t\t\t\t\t?? { subjectType: \"AdapterInvocation\", subjectId: adapterInvocationId };\n\t\t\t\t\tif (row.status !== \"succeeded\") {\n\t\t\t\t\t\tawait writeAdapter(adapterInvocationId, { status: \"succeeded\", updatedAt: now() });\n\t\t\t\t\t}\n\t\t\t\t\tif (handoff) await appendEvent(invocation, {\n\t\t\t\t\t\teventType: \"ExternalOperationAccepted\", ...subject,\n\t\t\t\t\t\tpayload: { adapterType: row.adapterType, operation: row.operation, externalReference: handoff.externalReference,\n\t\t\t\t\t\t\t...(handoff.dueAt ? { dueAt: handoff.dueAt.toISOString() } : {}) },\n\t\t\t\t\t}, `adapter:${stepIndex}:accepted`);\n\t\t\t\t\tconst governanceStore = asGovernanceStore(options.store);\n\t\t\t\t\tconst attestationId = lifecycleId(\"att\", actionInvocationId, adapterInvocationId);\n\t\t\t\t\tconst existing = governanceStore\n\t\t\t\t\t\t? (await governanceStore.listExecutionAttestations(actionInvocationId, tenantId, spaceId)).find(item => item.id === attestationId)\n\t\t\t\t\t\t: undefined;\n\t\t\t\t\tif (existing) {\n\t\t\t\t\t\tfor (const obligationId of existing.satisfiesObligations ?? []) {\n\t\t\t\t\t\t\tawait governanceStore!.updatePolicyObligation(actionInvocationId, obligationId, \"satisfied\", existing.evidenceReferences);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (options.extractExecutionAttestation && row.output !== undefined) {\n\t\t\t\t\t\tconst attestation = await options.extractExecutionAttestation({\n\t\t\t\t\t\t\tactionInvocationId, adapterInvocationId, adapterType: row.adapterType, operation: row.operation,\n\t\t\t\t\t\t\tvendor: row.vendor, input: row.input, output: row.output, startedAt: row.createdAt, completedAt: row.updatedAt,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (attestation) await recordExecutionAttestation(actionInvocationId, tenantId, spaceId, attestation, adapterInvocationId);\n\t\t\t\t\t}\n\t\t\t\t\tawait appendEvent(invocation, {\n\t\t\t\t\t\teventType: \"AdapterInvocationSucceeded\", ...subject,\n\t\t\t\t\t\tpayload: { adapterType: row.adapterType, operation: row.operation, input: row.input,\n\t\t\t\t\t\t\t...(row.output !== undefined ? { output: row.output } : {}), recovered: true },\n\t\t\t\t\t}, `adapter:${stepIndex}:succeeded`);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof RecoverableFinalizationError) throw error;\n\t\t\t\tthrow new RecoverableFinalizationError(caughtError({ actionId: invocation.actionId, source: \"execution\" }, error));\n\t\t\t}\n\t\t\tif (previousAdapterInvocation?.status === \"ambiguous\") {\n\t\t\t\treturn await settleUnknownOutcome(stepIndex, recordedAdapterReconciliation(previousAdapterInvocation),\n\t\t\t\t\tpreviousAdapterInvocation.reconciliation?.adapterEventSubject);\n\t\t\t}\n\t\t\tconst input = step.getInput(parsed.data, data);\n\t\t\tif (!input) continue;\n\t\t\tconst adapter = adapters.require(step.adapterType, step.operation);\n\t\t\tconst adapterEventSubject = options.adapterEventSubject?.(\n\t\t\t\taction.actionId,\n\t\t\t\tparsed.data,\n\t\t\t\tdata,\n\t\t\t) ?? { subjectType: \"AdapterInvocation\", subjectId: adapterInvocationId };\n\t\t\tconst settleStepUnknownOutcome = (reconciliation: AdapterReconciliationOutcome) =>\n\t\t\t\tsettleUnknownOutcome(stepIndex, reconciliation, adapterEventSubject);\n\t\t\tconst recordedInput = options.redactAdapterInput\n\t\t\t\t? options.redactAdapterInput(\n\t\t\t\t\t\taction.actionId,\n\t\t\t\t\t\tstep.adapterType,\n\t\t\t\t\t\tstep.operation,\n\t\t\t\t\t\tinput,\n\t\t\t\t\t)\n\t\t\t\t: input;\n\t\t\tconst startedAt = now();\n\t\t\tconst record: AdapterInvocationRecord = {\n\t\t\t\tid: adapterInvocationId,\n\t\t\t\t...adapterInvocationScope,\n\t\t\t\tadapterType: step.adapterType,\n\t\t\t\toperation: step.operation,\n\t\t\t\tvendor: adapter.vendor,\n\t\t\t\tstatus: \"running\",\n\t\t\t\tinput: recordedInput,\n\t\t\t\tattempt: 1,\n\t\t\t\tcreatedAt: startedAt,\n\t\t\t\tupdatedAt: startedAt,\n\t\t\t};\n\t\t\tif (!previousAdapterInvocation || !executionLease || !options.store.writeAdapterInvocation) await hostOperation(() => createAdapter(record));\n\t\t\tawait hostOperation(() => appendEvent(invocation, {\n\t\t\t\teventType: \"AdapterInvocationStarted\",\n\t\t\t\tsubjectType: adapterEventSubject.subjectType,\n\t\t\t\tsubjectId: adapterEventSubject.subjectId,\n\t\t\t\tpayload: { adapterType: step.adapterType, operation: step.operation },\n\t\t\t}, `adapter:${stepIndex}:started`));\n\t\t\tasync function appendDegradedAdapterEvidence(\n\t\t\t\toutputWithheld: boolean,\n\t\t\t\tmessage: string,\n\t\t\t\taccepted?: PendingExternalCompletion,\n\t\t\t\toutput?: Record<string, unknown>,\n\t\t\t\texternalReference?: string,\n\t\t\t\ttransaction?: PlatformHostMutationTransaction<TDb>,\n\t\t\t): Promise<void> {\n\t\t\t\tconst writes: Array<() => Promise<void>> = [];\n\t\t\t\tif (accepted) {\n\t\t\t\t\twrites.push(() => appendEvent(invocation, {\n\t\t\t\t\t\teventType: \"ExternalOperationAccepted\",\n\t\t\t\t\t\tsubjectType: adapterEventSubject.subjectType,\n\t\t\t\t\t\tsubjectId: adapterEventSubject.subjectId,\n\t\t\t\t\t\tpayload: { adapterType: step.adapterType, operation: step.operation, externalReference: accepted.externalReference,\n\t\t\t\t\t\t\t...(accepted.dueAt ? { dueAt: accepted.dueAt.toISOString() } : {}) },\n\t\t\t\t\t}, `adapter:${stepIndex}:accepted`, 1, transaction));\n\t\t\t\t}\n\t\t\t\twrites.push(() => appendEvent(invocation, {\n\t\t\t\t\teventType: \"AdapterInvocationSucceeded\",\n\t\t\t\t\tsubjectType: adapterEventSubject.subjectType,\n\t\t\t\t\tsubjectId: adapterEventSubject.subjectId,\n\t\t\t\t\tpayload: { adapterType: step.adapterType, operation: step.operation, input: recordedInput,\n\t\t\t\t\t\t...(!outputWithheld && externalReference ? { externalReference } : {}),\n\t\t\t\t\t\t...(outputWithheld ? { outputWithheld: true } : { output }) },\n\t\t\t\t}, `adapter:${stepIndex}:succeeded`, 1, transaction));\n\t\t\t\tconst governanceStore = asGovernanceStore(options.store);\n\t\t\t\tif (!outputWithheld && externalReference && governanceStore) {\n\t\t\t\t\twrites.push(() => externalCompletion.recordCompletionReconciliation(invocation,\n\t\t\t\t\t\t{ externalReference, provider: adapter.vendor }, message, transaction));\n\t\t\t\t}\n\t\t\t\tif (outputWithheld && governanceStore) {\n\t\t\t\t\twrites.push(() => (transaction ?? governanceStore).appendExternalReconciliation!({\n\t\t\t\t\t\tid: lifecycleId(\"rec\", actionInvocationId, `${adapter.vendor}:${adapterInvocationId}`),\n\t\t\t\t\t\tactionInvocationId, tenantId, spaceId, status: \"pending\", provider: adapter.vendor,\n\t\t\t\t\t\t...((externalReference ?? accepted?.externalReference) ? { externalOperationId: externalReference ?? accepted?.externalReference } : {}),\n\t\t\t\t\t\tattempt: 1, reason: message, observedAt: now(),\n\t\t\t\t\t}));\n\t\t\t\t}\n\t\t\t\tif (transaction) {\n\t\t\t\t\tfor (const write of writes) await write();\n\t\t\t\t} else {\n\t\t\t\t\tawait attemptEvidenceWrites(writes);\n\t\t\t\t}\n\t\t\t}\n\t\t\tasync function finalizeDegradedAdapterAtomically(\n\t\t\t\tpatch: ActionInvocationPatch,\n\t\t\t\toutputWithheld: boolean,\n\t\t\t\tmessage: string,\n\t\t\t\taccepted?: PendingExternalCompletion,\n\t\t\t\toutput?: Record<string, unknown>,\n\t\t\t\texternalReference?: string,\n\t\t\t): Promise<boolean> {\n\t\t\t\tconst atomicStore = asAtomicMutationStore(options.store);\n\t\t\t\tif (!atomicStore) return false;\n\t\t\t\tconst needsReconciliation = (outputWithheld || !!externalReference) && !!asGovernanceStore(options.store);\n\t\t\t\tconst previousStatus = invocation.status;\n\t\t\t\tlet verdictWritten = false;\n\t\t\t\tconst finalize = () => atomicStore.transactionWithEvents(async (transaction) => {\n\t\t\t\t\t// Probe before writing anything. Older/custom transactions keep the\n\t\t\t\t\t// verdict-first fallback unless they can commit all required evidence.\n\t\t\t\t\tif (!transaction.updateAdapterInvocation ||\n\t\t\t\t\t\t(options.store.writeAdapterInvocation && (executionLease || ownVerdict) && !transaction.writeAdapterInvocation) ||\n\t\t\t\t\t\t(needsReconciliation && !transaction.appendExternalReconciliation) ||\n\t\t\t\t\t\t(executionLease && !transaction.updateLeasedActionInvocation)) return false;\n\t\t\t\t\tawait appendDegradedAdapterEvidence(outputWithheld, message, accepted, output, externalReference, transaction);\n\t\t\t\t\tawait writeAdapter(adapterInvocationId, {\n\t\t\t\t\t\tstatus: \"succeeded\", ...(outputWithheld ? {} : { output }), updatedAt: now(),\n\t\t\t\t\t}, transaction);\n\t\t\t\t\t// The terminal update releases the lease. Keep it last so stores\n\t\t\t\t\t// fencing evidence on a live invocation can admit preceding writes.\n\t\t\t\t\tif (executionLease) {\n\t\t\t\t\t\tif (!transaction.updateLeasedActionInvocation) {\n\t\t\t\t\t\t\tthrow new HostError(\"Leased atomic finalization requires transaction-scoped fencing support.\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst updated = await transaction.updateLeasedActionInvocation({\n\t\t\t\t\t\t\tid: actionInvocationId, tenantId, spaceId,\n\t\t\t\t\t\t\tworkerId: executionLease.leaseOwner, leaseToken: executionLease.leaseToken, patch,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (!updated) throw new RecoverableFinalizationError(`Invocation lease lost: ${actionInvocationId}`);\n\t\t\t\t\t\tverdictWritten = true;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tverdictWritten = await writeInlineInvocation(invocation, patch, transaction, onPreservedReconciliation);\n\t\t\t\t\t}\n\t\t\t\t\treturn true;\n\t\t\t\t});\n\t\t\t\tlet committed: boolean;\n\t\t\t\ttry {\n\t\t\t\t\tcommitted = await finalize();\n\t\t\t\t} catch (error) {\n\t\t\t\t\t// Retry the whole rolled-back unit once, matching verdict retry\n\t\t\t\t\t// semantics. Lease loss must retain its fence and is not retried.\n\t\t\t\t\tif (error instanceof RecoverableFinalizationError) throw error;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tcommitted = await finalize();\n\t\t\t\t\t} catch (retryError) {\n\t\t\t\t\t\tif (retryError instanceof RecoverableFinalizationError) throw retryError;\n\t\t\t\t\t\t// Repeated non-lease failures select the verdict-first fallback\n\t\t\t\t\t\t// so recovery does not keep repeating the applied adapter effect.\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (committed) {\n\t\t\t\t\tif (verdictWritten) rememberVerdict(patch);\n\t\t\t\t\tmarkerDurable = true;\n\t\t\t\t\thasDurableProviderEffect = true;\n\t\t\t\t\thandoffDurable = accepted !== undefined;\n\t\t\t\t\tif (verdictWritten) emitInvocationStatusTelemetry(invocation, patch.status, options.telemetry, now(), previousStatus);\n\t\t\t\t}\n\t\t\t\treturn committed;\n\t\t\t}\n\t\t\tconst adapterErrorContext: ErrorTextRedactionContext = { actionId: action.actionId, source: \"adapter\", adapterType: step.adapterType, operation: step.operation, provider: adapter.vendor };\n\t\t\tconst executionErrorContext: ErrorTextRedactionContext = { actionId: action.actionId, source: \"execution\" };\n\t\t\tlet errorContext = executionErrorContext;\n\t\t\tlet adapterCallThrew = false;\n\t\t\tlet providerReturned = false;\n\t\t\tlet providerOutcome: import(\"@fabricorg/platform\").AdapterOutcomeKind | undefined;\n\t\t\tlet finalizingProviderResult = false;\n\t\t\tlet providerReportedSuccess = false;\n\t\t\tlet handoffDurable = false;\n\t\t\tlet markerDurable = false;\n\t\t\tlet successOutput: Record<string, unknown> | undefined;\n\t\t\tasync function writeSuccessCheckpoint(write: () => Promise<void>): Promise<void> {\n\t\t\t\ttry { await write(); } catch (error) {\n\t\t\t\t\tif (error instanceof RecoverableFinalizationError || handoffDurable || markerDurable) throw error;\n\t\t\t\t\tawait write();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlet thrownOutcome: import(\"@fabricorg/platform\").AdapterOutcomeKind | undefined;\n\t\t\tlet adapterDeadlineTimer: ReturnType<typeof setTimeout> | undefined;\n\t\t\ttry {\n\t\t\t\tconst adapterController = options.adapterDeadlineMs\n\t\t\t\t\t? new AbortController()\n\t\t\t\t\t: undefined;\n\t\t\t\tconst deadlineMs = options.adapterDeadlineMs\n\t\t\t\t\t? now().getTime() + options.adapterDeadlineMs\n\t\t\t\t\t: undefined;\n\t\t\t\tif (adapterController && deadlineMs) {\n\t\t\t\t\tconst remaining = deadlineMs - now().getTime();\n\t\t\t\t\tif (remaining <= 0) {\n\t\t\t\t\t\tthrow new HostError(`Adapter deadline already expired before execution: ${step.adapterType}:${step.operation}`);\n\t\t\t\t\t}\n\t\t\t\t\tadapterDeadlineTimer = setTimeout(\n\t\t\t\t\t\t() => adapterController.abort(new HostError(\"Adapter deadline exceeded\")),\n\t\t\t\t\t\tremaining,\n\t\t\t\t\t);\n\t\t\t\t\tadapterDeadlineTimer.unref?.();\n\t\t\t\t}\n\t\t\t\tconst circuitBreaker = circuitBreakers.forAdapter(adapter, { tenantId, spaceId });\n\t\t\t\tconst result = await executeWithAdapterRetry({\n\t\t\t\t\t...(circuitBreaker ? { circuitBreaker } : {}),\n\t\t\t\t\tpolicy: step.retryPolicy ?? adapter.retryPolicy,\n\t\t\t\t\tdefaultIdempotent: adapter.idempotent,\n\t\t\t\t\t// Every await before the call happens here, before breaker\n\t\t\t\t\t// admission, so nothing awaits between admission and the adapter.\n\t\t\t\t\tprepareAttempt: async (attempt) => {\n\t\t\t\t\t\tadapterCallThrew = false;\n\t\t\t\t\t\tproviderReturned = false;\n\t\t\t\t\t\tproviderOutcome = undefined;\n\t\t\t\t\t\tthrownOutcome = undefined;\n\t\t\t\t\t\terrorContext = executionErrorContext;\n\t\t\t\t\t\tawait hostOperation(() => writeAdapter(adapterInvocationId, {\n\t\t\t\t\t\t\tstatus: \"running\", error: undefined, attempt,\n\t\t\t\t\t\t\tupdatedAt: now(),\n\t\t\t\t\t\t}));\n\t\t\t\t\t\tif (adapterController?.signal.aborted) {\n\t\t\t\t\t\t\tthrow new HostError(`Adapter deadline already expired before execution: ${step.adapterType}:${step.operation}`);\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\texecute: async (attempt, maxAttempts) => {\n\t\t\t\t\t\terrorContext = adapterErrorContext;\n\t\t\t\t\t\tlet adapterResult: import(\"@fabricorg/platform\").AdapterExecutionResult;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tadapterResult = await adapter.execute(input, {\n\t\t\t\t\t\t\t\ttenantId,\n\t\t\t\t\t\t\t\tspaceId,\n\t\t\t\t\t\t\t\tactionInvocationId,\n\t\t\t\t\t\t\t\tadapterInvocationId,\n\t\t\t\t\t\t\t\tcorrelationId: invocation.correlationId,\n\t\t\t\t\t\t\t\t...(invocation.causationId\n\t\t\t\t\t\t\t\t\t? { causationId: invocation.causationId }\n\t\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t\t\tattempt,\n\t\t\t\t\t\t\t\tmaxAttempts,\n\t\t\t\t\t\t\t\t...(deadlineMs ? { deadlineMs } : {}),\n\t\t\t\t\t\t\t\t...(adapterController ? { signal: adapterController.signal } : {}),\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tadapterCallThrew = true;\n\t\t\t\t\t\t\tthrow error;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tproviderReturned = true;\n\t\t\t\t\t\tif (!isRecord(adapterResult)) {\n\t\t\t\t\t\t\tthrow new HostError(\"Adapter returned an uninterpretable reply; external outcome requires reconciliation.\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Snapshot top-level fields before the retry helper or Host interprets\n\t\t\t\t\t\t// them. Preserve enumerability for the legacy output fallback, and\n\t\t\t\t\t\t// read each getter only once, including non-enumerable contract fields.\n\t\t\t\t\t\tconst source = adapterResult as unknown as Record<string, unknown>;\n\t\t\t\t\t\tconst reply = Object.fromEntries(Object.keys(source).map(key => [key, source[key]]));\n\t\t\t\t\t\tfor (const key of [\"success\", \"outcome\", \"error\", \"outcomeEvidence\", \"output\", \"acceptedExternalOperation\"]) {\n\t\t\t\t\t\t\tif (!Object.hasOwn(reply, key)) Object.defineProperty(reply, key, { value: source[key] });\n\t\t\t\t\t\t}\n\t\t\t\t\t\terrorContext = executionErrorContext;\n\t\t\t\t\t\treturn reply as unknown as import(\"@fabricorg/platform\").AdapterExecutionResult;\n\t\t\t\t\t},\n\t\t\t\t\tisSuccessful: (result) => result.success,\n\t\t\t\t\tgetError: (result) => result.error,\n\t\t\t\t\tclassifyOutcome: (result) => {\n\t\t\t\t\t\tconst outcome = result.outcome ?? \"transient_failure\";\n\t\t\t\t\t\tproviderOutcome = isKnownAdapterOutcome(outcome) && outcome !== \"success\" ? outcome : \"ambiguous\";\n\t\t\t\t\t\treturn providerOutcome;\n\t\t\t\t\t},\n\t\t\t\t\tclassifyThrownError: (error) => {\n\t\t\t\t\t\tif (error instanceof RecoverableFinalizationError) throw error;\n\t\t\t\t\t\tif (providerReturned && providerOutcome === undefined) return \"ambiguous\";\n\t\t\t\t\t\tif (isAdapterCircuitOpenError(error)) return \"transient_failure\";\n\t\t\t\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\t\t\t\tconst outcome = adapterController?.signal.aborted || /timeout|deadline|timed?\\s*out/i.test(message)\n\t\t\t\t\t\t\t? \"timeout\" : \"transient_failure\";\n\t\t\t\t\t\tif (adapterCallThrew) thrownOutcome = outcome;\n\t\t\t\t\t\t// A Host-side error after a reply must not retry the provider.\n\t\t\t\t\t\treturn providerReturned ? \"ambiguous\" : outcome;\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t\tfinalizingProviderResult = true;\n\t\t\t\t// The consistency message interpolates the provider's outcome.\n\t\t\t\terrorContext = adapterErrorContext;\n\t\t\t\ttry {\n\t\t\t\t\tassertAdapterOutcomeConsistency(result as import(\"@fabricorg/platform\").AdapterExecutionResult);\n\t\t\t\t\tif (!result.success && result.outcome === \"success\") {\n\t\t\t\t\t\tthrow new HostError('Adapter returned success=false with contradictory outcome \"success\"; external outcome requires reconciliation.');\n\t\t\t\t\t}\n\t\t\t\t\tconst outcome = result.outcome;\n\t\t\t\t\tif (outcome != null && !isKnownAdapterOutcome(outcome)) {\n\t\t\t\t\t\tthrow new HostError(\"Adapter returned an unrecognised outcome; external outcome requires reconciliation.\");\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\tconst message = caughtError(adapterErrorContext, error);\n\t\t\t\t\treturn await settleStepUnknownOutcome({\n\t\t\t\t\t\tkind: \"adapter_outcome_ambiguous\", adapterType: step.adapterType, operation: step.operation,\n\t\t\t\t\t\tvendor: adapter.vendor, adapterInvocationId, message, reason: message,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\terrorContext = executionErrorContext;\n\t\t\t\tif (!result.success) {\n\t\t\t\t\tconst resultError = result.error == null ? result.error : redactErrorText(options.redactErrorText, adapterErrorContext, result.error);\n\t\t\t\t\tconst outcome = result.outcome ?? \"transient_failure\";\n\t\t\t\t\tif (outcome === \"ambiguous\" || outcome === \"timeout\") {\n\t\t\t\t\t\tconst evidence = result.outcomeEvidence;\n\t\t\t\t\t\tconst reason = evidence?.reason == null ? resultError : redactErrorText(options.redactErrorText, adapterErrorContext, evidence.reason);\n\t\t\t\t\t\treturn await settleStepUnknownOutcome({\n\t\t\t\t\t\t\tkind: \"adapter_outcome_ambiguous\", adapterType: step.adapterType, operation: step.operation,\n\t\t\t\t\t\t\tvendor: adapter.vendor, adapterInvocationId,\n\t\t\t\t\t\t\t...(evidence?.reason ?? result.error ? { reason } : {}),\n\t\t\t\t\t\t\t...(evidence?.externalReference ? { externalReference: evidence.externalReference } : {}),\n\t\t\t\t\t\t\tmessage: resultError ?? \"Adapter outcome is ambiguous; external effect may or may not have been applied\",\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tawait hostOperation(() => writeAdapter(adapterInvocationId, {\n\t\t\t\t\t\tstatus: \"failed\",\n\t\t\t\t\t\terror: resultError ?? \"Adapter failed\",\n\t\t\t\t\t\tupdatedAt: now(),\n\t\t\t\t\t}));\n\t\t\t\t\tawait hostOperation(() => appendEvent(invocation, {\n\t\t\t\t\t\teventType: \"AdapterInvocationFailed\",\n\t\t\t\t\t\tsubjectType: adapterEventSubject.subjectType,\n\t\t\t\t\t\tsubjectId: adapterEventSubject.subjectId,\n\t\t\t\t\t\tpayload: { adapterType: step.adapterType, operation: step.operation },\n\t\t\t\t\t}, `adapter:${stepIndex}:failed`));\n\t\t\t\t\treturn hostOperation(() => failExecution(invocation, \"failed\", resultError ?? \"Adapter failed\"));\n\t\t\t\t}\n\t\t\t\tproviderReportedSuccess = true;\n\t\t\t\tconst resultRecord = result as unknown as Record<string, unknown>;\n\t\t\t\tlet output = isRecord(resultRecord.output)\n\t\t\t\t\t? resultRecord.output\n\t\t\t\t\t: Object.fromEntries(\n\t\t\t\t\t\t\tObject.entries(resultRecord).filter(\n\t\t\t\t\t\t\t\t([key]) => key !== \"success\" && key !== \"error\",\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\tconst handoff = (result as import(\"@fabricorg/platform\").AdapterExecutionResult).acceptedExternalOperation;\n\t\t\t\tif (options.redactAdapterOutput) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\toutput = options.redactAdapterOutput(action.actionId, step.adapterType, step.operation, output);\n\t\t\t\t\t\tif (!isRecord(output)) throw new HostError(\"Adapter output redactor must return a non-null, non-array object.\");\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// The provider succeeded. Withhold output and preserve a callback\n\t\t\t\t\t\t// reference for reconciliation when finalization commits.\n\t\t\t\t\t\tconst message = \"Adapter output withheld: the output redactor failed after the external effect; reconciliation required.\";\n\t\t\t\t\t\tconst reference = typeof handoff?.externalReference === \"string\" ? handoff.externalReference.trim() : \"\";\n\t\t\t\t\t\tconst acceptedAt = now();\n\t\t\t\t\t\tconst deadlineMs = action.execution?.completionDeadlineMs;\n\t\t\t\t\t\tconst pendingCompletion = pendingHandoff ?? (reference ? {\n\t\t\t\t\t\t\tprovider: adapter.vendor, adapterType: step.adapterType, operation: step.operation,\n\t\t\t\t\t\t\tadapterInvocationId, externalReference: reference, acceptedAt,\n\t\t\t\t\t\t\t...(deadlineMs ? { dueAt: new Date(acceptedAt.getTime() + deadlineMs) } : {}),\n\t\t\t\t\t\t} : undefined);\n\t\t\t\t\t\tconst patch: ActionInvocationPatch = { status: \"reconciliation_required\", error: message, ...(pendingCompletion ? { pendingCompletion } : {}) };\n\t\t\t\t\t\tconst accepted = pendingCompletion?.adapterInvocationId === adapterInvocationId ? pendingCompletion : undefined;\n\t\t\t\t\t\tlet adapterFinalizedAtomically: boolean;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tadapterFinalizedAtomically = await finalizeDegradedAdapterAtomically(patch, true, message, accepted, undefined, reference || undefined);\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\tthrow new RecoverableFinalizationError(message);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!adapterFinalizedAtomically) {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tawait persistExecutionVerdict(invocation, patch, [\n\t\t\t\t\t\t\t\t\t() => appendDegradedAdapterEvidence(true, message, accepted, undefined, reference || undefined),\n\t\t\t\t\t\t\t\t\t() => writeAdapter(adapterInvocationId, { status: \"succeeded\", updatedAt: now() }),\n\t\t\t\t\t\t\t\t]);\n\t\t\t\t\t\t\t} catch (cause) {\n\t\t\t\t\t\t\t\tthrow new RecoverableFinalizationError(`${message} ${caughtError({ actionId: invocation.actionId, source: \"execution\" }, cause)}`);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn withConsistency({ actionInvocationId, status: \"reconciliation_required\" as const, error: message, ...(pendingCompletion ? { pendingCompletion } : {}) }, action.actionId);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tsuccessOutput = output;\n\t\t\t\tif (handoff) {\n\t\t\t\t\tconst reference = typeof handoff.externalReference === \"string\" ? handoff.externalReference.trim() : \"\";\n\t\t\t\t\tif (reference === \"\") {\n\t\t\t\t\t\t// Without a reference Host cannot match an external completion.\n\t\t\t\t\t\tconst message = `Adapter ${step.adapterType}:${step.operation} accepted an external operation without a reference to complete it by; the external effect may be in flight.`;\n\t\t\t\t\t\ttry { await persistExecutionVerdict(invocation, { status: \"reconciliation_required\", error: message }); }\n\t\t\t\t\t\tcatch { throw new RecoverableFinalizationError(message); }\n\t\t\t\t\t\treturn withConsistency({ actionInvocationId, status: \"reconciliation_required\" as const, error: message }, action.actionId);\n\t\t\t\t\t}\n\t\t\t\t\tconst acceptedAt = now();\n\t\t\t\t\tconst deadlineMs = action.execution?.completionDeadlineMs;\n\t\t\t\t\tconst accepted: PendingExternalCompletion = {\n\t\t\t\t\t\tprovider: adapter.vendor,\n\t\t\t\t\t\tadapterType: step.adapterType,\n\t\t\t\t\t\toperation: step.operation,\n\t\t\t\t\t\tadapterInvocationId,\n\t\t\t\t\t\texternalReference: reference,\n\t\t\t\t\t\tacceptedAt,\n\t\t\t\t\t\t...(deadlineMs ? { dueAt: new Date(acceptedAt.getTime() + deadlineMs) } : {}),\n\t\t\t\t\t};\n\t\t\t\t\tconst completion = action.execution?.completion ?? \"immediate\";\n\t\t\t\t\tconst refuse = completion === \"immediate\"\n\t\t\t\t\t\t? `Adapter ${step.adapterType}:${step.operation} handed off external operation \"${reference}\" but ${action.actionId} declares immediate completion; the external effect may be in flight.`\n\t\t\t\t\t\t: pendingHandoff\n\t\t\t\t\t\t\t? `Adapter ${step.adapterType}:${step.operation} handed off a second external operation \"${reference}\" while \"${pendingHandoff.externalReference}\" is already pending; one invocation waits on one completion.`\n\t\t\t\t\t\t\t: undefined;\n\t\t\t\t\tif (refuse) {\n\t\t\t\t\t\t// The handoff already happened, so this is not a clean failure:\n\t\t\t\t\t\t// somebody has to look, with the reference in hand. The first\n\t\t\t\t\t\t// reference is kept on the invocation so its callback can still\n\t\t\t\t\t\t// land as evidence; the refused one goes to the reconciliation\n\t\t\t\t\t\t// log. Capable transactions commit evidence and verdict together;\n\t\t\t\t\t\t// the fallback keeps the verdict first to prevent completion on reclaim.\n\t\t\t\t\t\tlet adapterFinalizedAtomically = false;\n\t\t\t\t\t\tlet error = refuse;\n\t\t\t\t\t\tconst recordRefusal = async () => {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tawait externalCompletion.recordCompletionReconciliation(invocation, { externalReference: reference, provider: adapter.vendor }, refuse);\n\t\t\t\t\t\t\t} catch (logError) {\n\t\t\t\t\t\t\t\t// The lease is already gone with the terminal status above, so\n\t\t\t\t\t\t\t\t// this write must not fence on it.\n\t\t\t\t\t\t\t\terror = `${refuse} Reconciliation log unavailable: ${caughtError({ actionId: invocation.actionId, source: \"execution\" }, logError)}`;\n\t\t\t\t\t\t\t\tif (adapterFinalizedAtomically) {\n\t\t\t\t\t\t\t\t\tif (ownVerdict) await hostOperation(() => persistExecutionVerdict(invocation, { error }));\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t// Keep the first failure even if its diagnostic annotation fails.\n\t\t\t\t\t\t\t\t\ttry { if (ownVerdict) await hostOperation(() => persistExecutionVerdict(invocation, { error })); }\n\t\t\t\t\t\t\t\t\tcatch { /* The reconciliation append is the first failure. */ }\n\t\t\t\t\t\t\t\t\tthrow logError;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconst patch: ActionInvocationPatch = {\n\t\t\t\t\t\t\tstatus: \"reconciliation_required\", error: refuse,\n\t\t\t\t\t\t\t...(pendingHandoff ? {} : { pendingCompletion: accepted }),\n\t\t\t\t\t\t};\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tadapterFinalizedAtomically = await finalizeDegradedAdapterAtomically(patch, false, refuse, pendingHandoff ? undefined : accepted, output, reference);\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\tthrow new RecoverableFinalizationError(refuse);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!adapterFinalizedAtomically) {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tawait persistExecutionVerdict(invocation, patch, [\n\t\t\t\t\t\t\t\t\t() => appendDegradedAdapterEvidence(false, refuse, pendingHandoff ? undefined : accepted, output, reference),\n\t\t\t\t\t\t\t\t\trecordRefusal,\n\t\t\t\t\t\t\t\t\t() => writeAdapter(adapterInvocationId, { status: \"succeeded\", output, updatedAt: now() }),\n\t\t\t\t\t\t\t\t]);\n\t\t\t\t\t\t\t} catch (cause) {\n\t\t\t\t\t\t\t\tthrow new RecoverableFinalizationError(`${refuse} ${caughtError({ actionId: invocation.actionId, source: \"execution\" }, cause)}`);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (adapterFinalizedAtomically) await recordRefusal();\n\t\t\t\t\t\treturn withConsistency({\n\t\t\t\t\t\t\tactionInvocationId, status: \"reconciliation_required\" as const, error,\n\t\t\t\t\t\t\t...(pendingHandoff ? { pendingCompletion: pendingHandoff } : { pendingCompletion: accepted }),\n\t\t\t\t\t\t}, action.actionId);\n\t\t\t\t\t}\n\t\t\t\t\tpendingHandoff = accepted;\n\t\t\t\t\t// Durable before the step is marked done: see the note above the loop.\n\t\t\t\t\tawait writeSuccessCheckpoint(() => persistExecutionInvocation(invocation, { pendingCompletion: accepted }));\n\t\t\t\t\thandoffDurable = true;\n\t\t\t\t\thasDurableProviderEffect = true;\n\t\t\t\t\tinvocation = { ...invocation, pendingCompletion: accepted };\n\t\t\t\t\tawait appendEvent(invocation, {\n\t\t\t\t\t\teventType: \"ExternalOperationAccepted\",\n\t\t\t\t\t\tsubjectType: adapterEventSubject.subjectType,\n\t\t\t\t\t\tsubjectId: adapterEventSubject.subjectId,\n\t\t\t\t\t\tpayload: {\n\t\t\t\t\t\t\tadapterType: step.adapterType,\n\t\t\t\t\t\t\toperation: step.operation,\n\t\t\t\t\t\t\texternalReference: reference,\n\t\t\t\t\t\t\t...(accepted.dueAt ? { dueAt: accepted.dueAt.toISOString() } : {}),\n\t\t\t\t\t\t},\n\t\t\t\t\t}, `adapter:${stepIndex}:accepted`);\n\t\t\t\t}\n\t\t\t\tawait writeSuccessCheckpoint(() => writeAdapter(adapterInvocationId, {\n\t\t\t\t\tstatus: \"succeeded\", output, updatedAt: now(),\n\t\t\t\t}));\n\t\t\t\tmarkerDurable = true;\n\t\t\t\thasDurableProviderEffect = true;\n\t\t\t\tif (options.extractExecutionAttestation) {\n\t\t\t\t\tconst attestation = await options.extractExecutionAttestation({\n\t\t\t\t\t\tactionInvocationId, adapterInvocationId, adapterType: step.adapterType,\n\t\t\t\t\t\toperation: step.operation, vendor: adapter.vendor, input: recordedInput,\n\t\t\t\t\t\tstartedAt, completedAt: now(), output,\n\t\t\t\t\t});\n\t\t\t\t\tif (attestation) {\n\t\t\t\t\t\tawait recordExecutionAttestation(actionInvocationId, tenantId, spaceId, attestation, adapterInvocationId);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tawait appendEvent(invocation, {\n\t\t\t\t\teventType: \"AdapterInvocationSucceeded\",\n\t\t\t\t\tsubjectType: adapterEventSubject.subjectType,\n\t\t\t\t\tsubjectId: adapterEventSubject.subjectId,\n\t\t\t\t\tpayload: {\n\t\t\t\t\t\tadapterType: step.adapterType,\n\t\t\t\t\t\toperation: step.operation,\n\t\t\t\t\t\tinput: recordedInput,\n\t\t\t\t\t\toutput,\n\t\t\t\t\t},\n\t\t\t\t}, `adapter:${stepIndex}:succeeded`);\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof RecoverableFinalizationError) throw error;\n\t\t\t\tif (providerReportedSuccess) {\n\t\t\t\t\tconst message = `Provider reported success but Host could not record it; reconciliation required. ${caughtError(executionErrorContext, error)}`;\n\t\t\t\t\tif (handoffDurable || markerDurable) throw new RecoverableFinalizationError(message);\n\t\t\t\t\tconst accepted = pendingHandoff?.adapterInvocationId === adapterInvocationId ? pendingHandoff : undefined;\n\t\t\t\t\tconst patch: ActionInvocationPatch = { status: \"reconciliation_required\" as const, error: message,\n\t\t\t\t\t\t...(accepted ? { pendingCompletion: accepted } : {}) };\n\t\t\t\t\tif (!await finalizeDegradedAdapterAtomically(patch, false, message, accepted, successOutput)) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tawait persistExecutionVerdict(invocation, patch, [\n\t\t\t\t\t\t\t\t() => writeAdapter(adapterInvocationId, {\n\t\t\t\t\t\t\t\t\tstatus: \"succeeded\", ...(successOutput !== undefined ? { output: successOutput } : {}), updatedAt: now(),\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t() => appendDegradedAdapterEvidence(false, message, accepted, successOutput),\n\t\t\t\t\t\t\t]);\n\t\t\t\t\t\t} catch (cause) {\n\t\t\t\t\t\t\tthrow new RecoverableFinalizationError(`${message} ${caughtError(executionErrorContext, cause)}`);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn withConsistency({ actionInvocationId, status: \"reconciliation_required\" as const, error: message,\n\t\t\t\t\t\t...(accepted ? { pendingCompletion: accepted } : {}) }, action.actionId);\n\t\t\t\t}\n\n\t\t\t\tconst message = caughtError(isAdapterCircuitOpenError(error) || (!finalizingProviderResult && providerReturned) ? adapterErrorContext : errorContext, error);\n\t\t\t\tif ((providerReturned && !finalizingProviderResult && (!isAdapterCircuitOpenError(error) || providerOutcome === undefined)) ||\n\t\t\t\t\t(adapterCallThrew && thrownOutcome === \"timeout\")) {\n\t\t\t\t\treturn await settleStepUnknownOutcome({\n\t\t\t\t\t\tkind: \"adapter_outcome_ambiguous\", adapterType: step.adapterType, operation: step.operation,\n\t\t\t\t\t\tvendor: adapter.vendor, adapterInvocationId, message, reason: message,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tawait hostOperation(() => writeAdapter(adapterInvocationId, {\n\t\t\t\t\tstatus: \"failed\",\n\t\t\t\t\terror: message,\n\t\t\t\t\tupdatedAt: now(),\n\t\t\t\t}));\n\t\t\t\tif (isAdapterCircuitOpenError(error)) {\n\t\t\t\t\t// Retain the existing circuit-error classification and event shape.\n\t\t\t\t\t// Adapter-thrown lookalikes use this path too; their text is redacted above.\n\t\t\t\t\tawait hostOperation(() => appendEvent(invocation, {\n\t\t\t\t\t\teventType: \"AdapterInvocationFailed\",\n\t\t\t\t\t\tsubjectType: adapterEventSubject.subjectType,\n\t\t\t\t\t\tsubjectId: adapterEventSubject.subjectId,\n\t\t\t\t\t\tpayload: {\n\t\t\t\t\t\t\tadapterType: step.adapterType,\n\t\t\t\t\t\t\toperation: step.operation,\n\t\t\t\t\t\t\treason: \"circuit_open\",\n\t\t\t\t\t\t\t...(error.retryAfterMs !== undefined ? { retryAfterMs: error.retryAfterMs } : {}),\n\t\t\t\t\t\t},\n\t\t\t\t\t}, `adapter:${stepIndex}:failed`));\n\t\t\t\t}\n\t\t\t\treturn hostOperation(() => failExecution(invocation, \"failed\", message));\n\t\t\t} finally {\n\t\t\t\tif (adapterDeadlineTimer) clearTimeout(adapterDeadlineTimer);\n\t\t\t}\n\t\t}\n\n\t\tconst governanceStore = asGovernanceStore(options.store);\n\t\tif (governanceStore && options.resolvePolicyObligations) {\n\t\t\tconst obligations = await hostOperation(() => governanceStore.listPolicyObligations(actionInvocationId, tenantId, spaceId));\n\t\t\tconst unsatisfied = obligations.filter((obligation) => (obligation.required ?? true) && obligation.status !== \"satisfied\" && obligation.status !== \"waived\");\n\t\t\tif (unsatisfied.length > 0) {\n\t\t\t\tconst message = `Unsatisfied policy obligations: ${unsatisfied.map((item) => item.id).join(\", \")}`;\n\t\t\t\tif (pendingHandoff) {\n\t\t\t\t\t// The external effect is in flight and the evidence that would\n\t\t\t\t\t// have satisfied these may have died with a worker; somebody\n\t\t\t\t\t// has to look rather than the row saying it failed cleanly.\n\t\t\t\t\tawait hostOperation(() => persistExecutionInvocation(invocation, { status: \"reconciliation_required\", error: message }));\n\t\t\t\t\tlet error = message;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait externalCompletion.recordCompletionReconciliation(invocation, { externalReference: pendingHandoff.externalReference, provider: pendingHandoff.provider, kind: \"obligations\" }, message);\n\t\t\t\t\t} catch (logError) {\n\t\t\t\t\t\terror = `${message} Reconciliation log unavailable: ${caughtError({ actionId: invocation.actionId, source: \"execution\" }, logError)}`;\n\t\t\t\t\t\tif (ownVerdict) await hostOperation(() => persistExecutionVerdict(invocation, { error }));\n\t\t\t\t\t}\n\t\t\t\t\treturn withConsistency({ actionInvocationId, status: \"reconciliation_required\" as const, error, pendingCompletion: pendingHandoff }, action.actionId);\n\t\t\t\t}\n\t\t\t\treturn hostOperation(() => failExecution(invocation, \"failed\", message));\n\t\t\t}\n\t\t}\n\n\t\tconst result = withoutPrivateHostFields(data, eventResultFields);\n\t\t// A handoff leaves the invocation running, without a lease, until the\n\t\t// external system completes it by reference. Domain events still go out\n\t\t// now: the handler's writes committed, and what is pending is the\n\t\t// external outcome, not the domain state.\n\t\tconst parked: PendingExternalCompletion | undefined = pendingHandoff ? { ...pendingHandoff, parkedAt: now() } : undefined;\n\t\tconst finalPatch: ActionInvocationPatch = parked\n\t\t\t? { status: \"running\", result, pendingCompletion: parked }\n\t\t\t: { status: \"completed\", result };\n\t\tlet verdictWritten = true;\n\t\ttry {\n\t\t\tconst atomicStore = asAtomicMutationStore(options.store);\n\t\t\tif (action.eventPhase === \"after_adapters\" && atomicStore) {\n\t\t\t\tawait hostOperation(() => atomicStore.transactionWithEvents(async (transaction) => {\n\t\t\t\t\tfor (const [index, event] of domainEvents.entries()) {\n\t\t\t\t\t\tawait appendEvent(\n\t\t\t\t\t\t\tinvocation,\n\t\t\t\t\t\t\tevent,\n\t\t\t\t\t\t\t`domain:${index}`,\n\t\t\t\t\t\t\taction.version,\n\t\t\t\t\t\t\ttransaction,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tif (pendingTransitionEvent) {\n\t\t\t\t\t\tawait appendEvent(invocation, pendingTransitionEvent, \"state:transition\", 1, transaction);\n\t\t\t\t\t}\n\t\t\t\t\tif (executionLease) {\n\t\t\t\t\t\tif (!transaction.updateLeasedActionInvocation) {\n\t\t\t\t\t\t\tthrow new HostError(\"Leased atomic finalization requires transaction-scoped fencing support.\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst updated = await transaction.updateLeasedActionInvocation({\n\t\t\t\t\t\t\tid: actionInvocationId, tenantId, spaceId,\n\t\t\t\t\t\t\tworkerId: executionLease.leaseOwner, leaseToken: executionLease.leaseToken,\n\t\t\t\t\t\t\tpatch: finalPatch,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (!updated) throw new RecoverableFinalizationError(`Invocation lease lost: ${actionInvocationId}`);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tverdictWritten = await writeInlineInvocation(invocation, finalPatch, transaction, onPreservedReconciliation);\n\t\t\t\t\t}\n\t\t\t\t}));\n\t\t\t\tif (!pendingHandoff && verdictWritten) {\n\t\t\t\t\temitInvocationStatusTelemetry(\n\t\t\t\t\t\tinvocation,\n\t\t\t\t\t\t\"completed\",\n\t\t\t\t\t\toptions.telemetry,\n\t\t\t\t\t\tnow(),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (action.eventPhase === \"after_adapters\") {\n\t\t\t\t\tfor (const [index, event] of domainEvents.entries()) {\n\t\t\t\t\t\tawait hostOperation(() => appendEvent(invocation, event, `domain:${index}`, action.version));\n\t\t\t\t\t}\n\t\t\t\t\tif (pendingTransitionEvent) {\n\t\t\t\t\t\tawait hostOperation(() => appendEvent(invocation, pendingTransitionEvent, \"state:transition\", 1));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tawait hostOperation(() => persistExecutionInvocation(invocation, finalPatch));\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (action.eventPhase === \"after_adapters\") {\n\t\t\t\tthrow new RecoverableFinalizationError(errorMessage(error));\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t\treturn {\n\t\t\tactionInvocationId,\n\t\t\tstatus: parked ? \"running\" : \"completed\",\n\t\t\tresult,\n\t\t\t...(parked ? { pendingCompletion: parked } : {}),\n\t\t\t...(invocation.hitlRoute ? { hitlRoute: invocation.hitlRoute } : {}),\n\t\t\t...(invocation.hitlRiskTier ? { hitlRiskTier: invocation.hitlRiskTier } : {}),\n\t\t};\n\t\t} catch (error) {\n\t\t\tif (error instanceof RecoverableFinalizationError) throw error;\n\t\t\tif (retryableGovernance && isRetryableExecutionError(error)) {\n\t\t\t\tconst reason = executionReasonOverride === \"approval_resume\"\n\t\t\t\t\t? \"approval resume\"\n\t\t\t\t\t: !invocation.leaseOwner || invocation.leaseToken === undefined\n\t\t\t\t\t\t? \"not leased\"\n\t\t\t\t\t\t: !action.idempotent\n\t\t\t\t\t\t\t? \"action not idempotent\"\n\t\t\t\t\t\t\t: invocation.attemptCount >= retryableExecutionMaxAttempts\n\t\t\t\t\t\t\t\t? `attempts exhausted (${invocation.attemptCount}/${retryableExecutionMaxAttempts})`\n\t\t\t\t\t\t\t\t: undefined;\n\t\t\t\tif (!reason) throw error;\n\t\t\t\treturn hostOperation(() => failExecution(invocation, \"failed\", caughtError(\n\t\t\t\t\t{ actionId: invocation.actionId, source: \"execution\" },\n\t\t\t\t\tnew Error(`Retryable execution not retried: ${reason}; ${errorMessage(error)}`),\n\t\t\t\t)));\n\t\t\t}\n\t\t\treturn hostOperation(() => failExecution(invocation, \"failed\", caughtError({ actionId: invocation.actionId, source: \"execution\" }, error)));\n\t\t}\n\t}\n\n\tasync function resumeApprovedInvocation(\n\t\tactionInvocationId: string,\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t\tdecision: ActionApprovalDecision,\n\t): Promise<ExecuteActionResult> {\n\t\tif (!decision.approverId.trim()) throw new Error(\"approverId is required\");\n\t\tconst invocation = await options.store.getActionInvocation(\n\t\t\tactionInvocationId,\n\t\t\ttenantId,\n\t\t\tspaceId,\n\t\t);\n\t\tif (!invocation) throw new Error(`ActionInvocation not found: ${actionInvocationId}`);\n\t\tif (isTerminal(invocation.status)) return withConsistency(actionResult(invocation), invocation.actionId);\n\t\tif (invocation.status !== \"waiting_for_approval\") {\n\t\t\treturn {\n\t\t\t\t...actionResult(invocation),\n\t\t\t\terror: `Invocation is not waiting for approval (status: ${invocation.status})`,\n\t\t\t};\n\t\t}\n\t\tconst action = actionResolver(invocation.actionId);\n\t\tif (!action) return fail(invocation, \"failed\", `Unknown action: ${invocation.actionId}`);\n\t\tconst approvalAuthorizationInput = toAuthorizationInput(action, {\n\t\t\ttenantId,\n\t\t\tspaceId,\n\t\t\tactorId: decision.approverId,\n\t\t\tactorType: decision.approverType,\n\t\t});\n\t\tconst entitled = await options.authorization.checkEntitlement(\n\t\t\tapprovalAuthorizationInput,\n\t\t);\n\t\tconst authorized = options.authorization.authorizeApproval\n\t\t\t? await options.authorization.authorizeApproval({\n\t\t\t\t\t...approvalAuthorizationInput,\n\t\t\t\t\tdecision,\n\t\t\t\t})\n\t\t\t: await options.authorization.authorize(approvalAuthorizationInput);\n\t\tif (!entitled || !authorized) {\n\t\t\treturn {\n\t\t\t\t...actionResult(invocation),\n\t\t\t\terror: `Actor ${decision.approverId} is not authorized to decide this approval`,\n\t\t\t};\n\t\t}\n\t\tconst approvalStore = asApprovalStore(options.store);\n\t\tif (!approvalStore) {\n\t\t\treturn {\n\t\t\t\t...actionResult(invocation),\n\t\t\t\terror: \"Approval resume requires a store with approval persistence support.\",\n\t\t\t};\n\t\t}\n\t\tconst transitionStartedAt = now();\n\t\tconst decidedAt = decision.decidedAt ?? transitionStartedAt;\n\t\tconst leaseOwner = `approval-resume-${createFabricId(\"lease\")}`;\n\t\tconst transition = await approvalStore.beginApprovalDecision({\n\t\t\tactionInvocationId,\n\t\t\ttenantId,\n\t\t\tspaceId,\n\t\t\tdecision: { ...decision, decidedAt },\n\t\t\tleaseOwner,\n\t\t\tleaseDurationMs: options.approvalResumeLeaseDurationMs ?? 5 * 60_000,\n\t\t\tnow: transitionStartedAt,\n\t\t});\n\t\tconst transitioned =\n\t\t\ttransition.invocation ??\n\t\t\t(await options.store.getActionInvocation(actionInvocationId, tenantId, spaceId));\n\t\tif (!transition.applied || !transitioned) {\n\t\t\tif (!transitioned) throw new Error(`ActionInvocation not found: ${actionInvocationId}`);\n\t\t\treturn withConsistency(actionResult(transitioned), transitioned.actionId);\n\t\t}\n\t\tif (!decision.approved) {\n\t\t\temitInvocationStatusTelemetry(\n\t\t\t\ttransitioned,\n\t\t\t\t\"failed\",\n\t\t\t\toptions.telemetry,\n\t\t\t\tnow(),\n\t\t\t\t\"waiting_for_approval\",\n\t\t\t);\n\t\t\treturn withConsistency(actionResult(transitioned), transitioned.actionId);\n\t\t}\n\t\treturn executeInvocation(\n\t\t\tactionInvocationId,\n\t\t\ttenantId,\n\t\t\tspaceId,\n\t\t\t{ leaseOwner, leaseToken: transitioned.leaseToken },\n\t\t\t\"approval_resume\",\n\t\t);\n\t}\n\n\tasync function recordExecutionAttestation(\n\t\tactionInvocationId: string,\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t\tattestation: ExecutionAttestation,\n\t\tadapterInvocationId?: string,\n\t): Promise<void> {\n\t\tconst governanceStore = asGovernanceStore(options.store);\n\t\tif (!governanceStore) throw new HostError(\"Execution attestations require a governance-capable store.\");\n\t\tconst invocation = await options.store.getActionInvocation(actionInvocationId, tenantId, spaceId);\n\t\tif (!invocation) throw new HostError(`ActionInvocation not found: ${actionInvocationId}`);\n\t\tconst id = lifecycleId(\"att\", actionInvocationId, adapterInvocationId ?? `${attestation.provider}:${attestation.operation}:${attestation.externalOperationId ?? \"external\"}`);\n\t\tawait governanceStore.appendExecutionAttestation({\n\t\t\t...attestation, id, actionInvocationId, tenantId, spaceId,\n\t\t\t...(adapterInvocationId ? { adapterInvocationId } : {}), recordedAt: now(),\n\t\t});\n\t\tfor (const obligationId of attestation.satisfiesObligations ?? []) {\n\t\t\tawait governanceStore.updatePolicyObligation(actionInvocationId, obligationId, \"satisfied\", attestation.evidenceReferences);\n\t\t}\n\t}\n\n\tasync function recordExternalReconciliation(\n\t\tactionInvocationId: string,\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t\treconciliation: ExternalReconciliation,\n\t): Promise<void> {\n\t\tconst governanceStore = asGovernanceStore(options.store);\n\t\tif (!governanceStore) throw new Error(\"External reconciliation requires a governance-capable store.\");\n\t\tconst invocation = await options.store.getActionInvocation(actionInvocationId, tenantId, spaceId);\n\t\tif (!invocation) throw new Error(`ActionInvocation not found: ${actionInvocationId}`);\n\t\tawait governanceStore.appendExternalReconciliation({\n\t\t\t...reconciliation,\n\t\t\tid: lifecycleId(\"rec\", actionInvocationId, `${reconciliation.provider}:${reconciliation.attempt}`),\n\t\t\tactionInvocationId, tenantId, spaceId,\n\t\t});\n\t}\n\n\t/** Consistency is a property of the action, not of the invocation, so it is read rather than stored. */\n\tfunction declaredConsistency(actionId: ActionId): \"authoritative-now\" | \"provisional-until-reconciled\" | undefined {\n\t\treturn actionResolver(actionId)?.execution?.consistency;\n\t}\n\n\t/**\n\t * Decorates every result leaving the Host, not only a freshly executed one, so an\n\t * idempotent replay reports the same consistency as the original submission.\n\t */\n\tfunction withConsistency<TResult extends { actionInvocationId: string }>(result: TResult, actionId: ActionId): TResult {\n\t\tconst consistency = declaredConsistency(actionId);\n\t\treturn consistency ? { ...result, consistency } : result;\n\t}\n\n\tasync function appendEvent(\n\t\tinvocation: {\n\t\t\tid: string;\n\t\t\tactionId: ActionId;\n\t\t\tactionVersion: number;\n\t\t\ttenantId: string;\n\t\t\tspaceId: string;\n\t\t\tactorId: string;\n\t\t\tactorType: string;\n\t\t\tcorrelationId: string;\n\t\t\tcausationId?: string;\n\t\t\tprovenance?: ActionInvocationRecord[\"provenance\"];\n\t\t},\n\t\tevent: PendingAssetEvent,\n\t\tdeduplicationKey: string,\n\t\tdefaultEventSchemaVersion = 1,\n\t\ttransaction?: PlatformHostMutationTransaction<TDb>,\n\t): Promise<void> {\n\t\tconst timestamp = now();\n\t\tconst envelope: AssetEventEnvelope = {\n\t\t\tid: lifecycleId(\"evt\", invocation.id, deduplicationKey),\n\t\t\ttenantId: invocation.tenantId,\n\t\t\tspaceId: invocation.spaceId,\n\t\t\teventType: event.eventType,\n\t\t\teventSchemaVersion: event.eventSchemaVersion ?? defaultEventSchemaVersion,\n\t\t\tsubjectType: event.subjectType,\n\t\t\tsubjectId: event.subjectId,\n\t\t\tactorId: invocation.actorId,\n\t\t\tactorType: invocation.actorType,\n\t\t\tactionInvocationId: invocation.id,\n\t\t\tpayload: event.payload,\n\t\t\tsequence: await (transaction ?? options.store).nextEventSequence(\n\t\t\t\tinvocation.tenantId,\n\t\t\t\tinvocation.spaceId,\n\t\t\t),\n\t\t\toccurredAt: timestamp,\n\t\t\trecordedAt: timestamp,\n\t\t\tcorrelationId: invocation.correlationId,\n\t\t\t...(invocation.causationId ? { causationId: invocation.causationId } : {}),\n\t\t\t...(invocation.provenance ? { provenance: { source: invocation.provenance.source, ...(invocation.provenance.auditAttributes ? { auditAttributes: invocation.provenance.auditAttributes } : {}) } } : {}),\n\t\t\t...(declaredConsistency(invocation.actionId) === \"provisional-until-reconciled\" ? { consistency: \"provisional-until-reconciled\" as const } : {}),\n\t\t};\n\t\tif (options.outbox) {\n\t\t\tconst hostLifecycleEvent = new Set([\"AdapterInvocationStarted\", \"AdapterInvocationSucceeded\", \"AdapterInvocationFailed\", \"ExternalOperationAccepted\", \"ExternalOperationCompleted\", \"ExternalOperationFailed\", \"ExternalOperationContradicted\", \"ComplianceBlocked\"]).has(envelope.eventType);\n\t\t\tconst shouldPublish = options.outbox.shouldPublish?.(envelope) ?? !hostLifecycleEvent;\n\t\t\tif (!shouldPublish) {\n\t\t\t\tawait (transaction ?? options.store).appendEvent(envelope);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst traceContext = options.outbox.traceContext?.(envelope);\n\t\t\tconst payloadClassification = options.outbox.classifyPayload(envelope);\n\t\t\tconst metadata = {\n\t\t\t\tproducerModuleVersion: options.outbox.producerModuleVersion(invocation.actionId, invocation.actionVersion),\n\t\t\t\tpayloadClassification,\n\t\t\t\tincludeProvenance: options.outbox.includeProvenance?.(envelope, payloadClassification) ?? payloadClassification !== \"restricted\",\n\t\t\t\t// Actor identity is excluded for every classification unless the application opts in.\n\t\t\t\tincludeActor: options.outbox.includeActor?.(envelope, payloadClassification) === true,\n\t\t\t\t...(traceContext ? { traceContext } : {}),\n\t\t\t};\n\t\t\tif (transaction) {\n\t\t\t\tif (!transaction.appendEventWithOutbox) throw new HostError(\"Outbox egress requires an atomic transaction with appendEventWithOutbox.\");\n\t\t\t\tawait transaction.appendEventWithOutbox(envelope, metadata);\n\t\t\t} else {\n\t\t\t\tconst outboxStore = asOutboxStore(options.store);\n\t\t\t\tif (!outboxStore) throw new HostError(\"Outbox egress requires an outbox-capable Platform Host store.\");\n\t\t\t\tawait outboxStore.appendEventWithOutbox(envelope, metadata);\n\t\t\t}\n\t\t} else {\n\t\t\tawait (transaction ?? options.store).appendEvent(envelope);\n\t\t}\n\t}\n\n\tasync function fail(\n\t\tinvocation: {\n\t\t\tid: string;\n\t\t\ttenantId: string;\n\t\t\tspaceId: string;\n\t\t\thitlRoute?: ActionInvocationRecord[\"hitlRoute\"];\n\t\t\thitlRiskTier?: ActionInvocationRecord[\"hitlRiskTier\"];\n\t\t},\n\t\tstatus: Extract<ActionStatus, \"failed\" | \"blocked_by_policy\" | \"validation_failed\">,\n\t\terror: string,\n\t\tonPreservedReconciliation?: (record: ActionInvocationRecord) => void,\n\t): Promise<ExecuteActionResult> {\n\t\tawait persistInvocation(invocation as ActionInvocationRecord, { status, error }, onPreservedReconciliation);\n\t\treturn {\n\t\t\tactionInvocationId: invocation.id,\n\t\t\tstatus,\n\t\t\terror,\n\t\t\t...(invocation.hitlRoute ? { hitlRoute: invocation.hitlRoute } : {}),\n\t\t\t...(invocation.hitlRiskTier ? { hitlRiskTier: invocation.hitlRiskTier } : {}),\n\t\t};\n\t}\n\n\tasync function writeInlineInvocation(\n\t\tinvocation: ActionInvocationRecord,\n\t\tpatch: ActionInvocationPatch,\n\t\ttransaction?: PlatformHostMutationTransaction<TDb>,\n\t\tonPreservedReconciliation?: (record: ActionInvocationRecord) => void,\n\t): Promise<boolean> {\n\t\tif (!invocation.pendingCompletion && !patch.pendingCompletion) {\n\t\t\tawait (transaction ?? options.store).updateActionInvocation(invocation.id, invocation.tenantId, invocation.spaceId, patch);\n\t\t\treturn true;\n\t\t}\n\t\tlet evidenceOnly = false;\n\t\tlet preserved: ActionInvocationRecord | undefined;\n\t\tconst current = transaction?.getActionInvocationForUpdate\n\t\t\t? await transaction.getActionInvocationForUpdate(invocation.id, invocation.tenantId, invocation.spaceId)\n\t\t\t: await options.store.getActionInvocation(invocation.id, invocation.tenantId, invocation.spaceId);\n\t\t// Budget exhaustion first commits a plain verdict, then enriches it.\n\t\t// Admit only that same terminal snapshot; never replace a sweep verdict.\n\t\tconst enrichingOwnVerdict = invocation.status === \"reconciliation_required\"\n\t\t\t&& patch.status === \"reconciliation_required\" && current?.status === \"reconciliation_required\"\n\t\t\t&& current.error === invocation.error && current.pendingCompletion?.overdueAt === undefined;\n\t\tif (current?.status === \"reconciliation_required\" && !enrichingOwnVerdict) {\n\t\t\tconst observed = {\n\t\t\t\t...current,\n\t\t\t\t...(current.result ? { result: { ...current.result } } : {}),\n\t\t\t\t...(current.pendingCompletion ? { pendingCompletion: { ...current.pendingCompletion } } : {}),\n\t\t\t};\n\t\t\t// Keep the existing verdict, including its error and overdue marker.\n\t\t\t// Reconciliation paths can still commit their independent evidence.\n\t\t\tconst parking = patch.status === \"running\" ? patch.pendingCompletion : undefined;\n\t\t\tif (parking?.parkedAt === undefined && patch.status !== \"completed\") {\n\t\t\t\tonPreservedReconciliation?.(observed);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tconst pending = current.pendingCompletion;\n\t\t\tpatch = {\n\t\t\t\tresult: patch.result,\n\t\t\t\t...(parking?.parkedAt !== undefined && pending?.overdueAt !== undefined\n\t\t\t\t\t&& pending.adapterInvocationId === parking.adapterInvocationId\n\t\t\t\t\t&& pending.externalReference === parking.externalReference\n\t\t\t\t\t? { pendingCompletion: { ...pending, parkedAt: parking.parkedAt } } : {}),\n\t\t\t};\n\t\t\tpreserved = { ...observed, ...patch };\n\t\t\tevidenceOnly = true;\n\t\t} else if (!enrichingOwnVerdict && (invocation.pendingCompletion || patch.status === \"completed\") && current?.status !== \"running\") {\n\t\t\tthrow new RecoverableFinalizationError(`Invocation is no longer running: ${invocation.id}`);\n\t\t}\n\t\tawait (transaction ?? options.store).updateActionInvocation(invocation.id, invocation.tenantId, invocation.spaceId, patch);\n\t\tif (preserved) onPreservedReconciliation?.(preserved);\n\t\treturn !evidenceOnly;\n\t}\n\n\tasync function persistInvocation(\n\t\tinvocation: ActionInvocationRecord,\n\t\tpatch: import(\"./types\").ActionInvocationPatch,\n\t\tonPreservedReconciliation?: (record: ActionInvocationRecord) => void,\n\t\tlease?: { leaseOwner: string; leaseToken: number },\n\t): Promise<boolean> {\n\t\tconst previousStatus = invocation.status;\n\t\tconst identity = lease ?? (invocation.leaseOwner && invocation.leaseToken !== undefined ? { leaseOwner: invocation.leaseOwner, leaseToken: invocation.leaseToken } : undefined);\n\t\tif (identity) {\n\t\t\tconst recoverable = options.store as Partial<RecoverablePlatformHostStore<TDb>>;\n\t\t\tif (!recoverable.updateLeasedActionInvocation) {\n\t\t\t\tthrow new HostError(\"Leased execution requires a fencing-capable PlatformHostStore.\");\n\t\t\t}\n\t\t\tconst updated = await recoverable.updateLeasedActionInvocation({\n\t\t\t\tid: invocation.id,\n\t\t\t\ttenantId: invocation.tenantId,\n\t\t\t\tspaceId: invocation.spaceId,\n\t\t\t\tworkerId: identity.leaseOwner,\n\t\t\t\tleaseToken: identity.leaseToken,\n\t\t\t\tpatch,\n\t\t\t});\n\t\t\tif (!updated) throw new RecoverableFinalizationError(`Invocation lease lost: ${invocation.id}`);\n\t\t\temitInvocationStatusTelemetry(invocation, patch.status, options.telemetry, now(), previousStatus);\n\t\t\treturn true;\n\t\t}\n\t\tconst write = (transaction?: PlatformHostMutationTransaction<TDb>) => writeInlineInvocation(invocation, patch, transaction, onPreservedReconciliation);\n\t\tconst atomicStore = invocation.pendingCompletion || patch.pendingCompletion ? asAtomicMutationStore(options.store) : undefined;\n\t\tconst updated = atomicStore ? await atomicStore.transactionWithEvents(write) : await write();\n\t\tif (updated) emitInvocationStatusTelemetry(invocation, patch.status, options.telemetry, now(), previousStatus);\n\t\treturn updated;\n\t}\n\n\tconst externalCompletion = createExternalCompletionLifecycle<TDb>({\n\t\tstore: options.store,\n\t\ttelemetry: options.telemetry,\n\t\tredactErrorText: options.redactErrorText,\n\t\tredactExternalCompletionResult: options.redactExternalCompletionResult,\n\t\teventResultFields,\n\t\tnow,\n\t\tactionResolver,\n\t\tappendEvent,\n\t\tactionResult,\n\t\twithConsistency,\n\t});\n\n\treturn {\n\t\tsubmitAction,\n\t\texecuteInvocation,\n\t\tresumeApprovedInvocation,\n\t\trecordExecutionAttestation,\n\t\trecordExternalReconciliation,\n\t\tcompleteExternalInvocation: externalCompletion.completeExternalInvocation,\n\t\treconcileOverdueCompletions: externalCompletion.reconcileOverdueCompletions,\n\t\trequeueOutboxDeadLetter: createOutboxRequeue<TDb>({\n\t\t\tstore: options.store,\n\t\t\tauthorization: options.authorization,\n\t\t\ttelemetry: options.telemetry,\n\t\t\tnow,\n\t\t}),\n\t};\n}\n\nfunction actionResult(invocation: ActionInvocationRecord): ExecuteActionResult {\n\treturn {\n\t\tactionInvocationId: invocation.id,\n\t\tstatus: invocation.status,\n\t\tresult: invocation.result,\n\t\t...(invocation.error ? { error: invocation.error } : {}),\n\t\t...(invocation.hitlRoute ? { hitlRoute: invocation.hitlRoute } : {}),\n\t\t...(invocation.hitlRiskTier ? { hitlRiskTier: invocation.hitlRiskTier } : {}),\n\t\t...(invocation.authorizationReconciliation ? { reconciliation: invocation.authorizationReconciliation } : {}),\n\t\t...(invocation.adapterReconciliation ? { adapterReconciliation: invocation.adapterReconciliation } : {}),\n\t\t...(invocation.pendingCompletion ? { pendingCompletion: invocation.pendingCompletion } : {}),\n\t};\n}\n\nfunction asApprovalStore<TDb>(\n\tstore: PlatformHostOptions<TDb>[\"store\"],\n): ApprovalPlatformHostStore<TDb> | undefined {\n\tconst candidate = store as Partial<ApprovalPlatformHostStore<TDb>>;\n\treturn typeof candidate.recordHitlDecision === \"function\" &&\n\t\ttypeof candidate.beginApprovalDecision === \"function\"\n\t\t? (store as ApprovalPlatformHostStore<TDb>)\n\t\t: undefined;\n}\n\nfunction asOutboxStore<TDb>(\n\tstore: PlatformHostOptions<TDb>[\"store\"],\n): OutboxPlatformHostStore<TDb> | undefined {\n\tconst candidate = store as Partial<OutboxPlatformHostStore<TDb>>;\n\treturn typeof candidate.appendEventWithOutbox === \"function\" &&\n\t\ttypeof candidate.claimOutbox === \"function\"\n\t\t? (store as OutboxPlatformHostStore<TDb>)\n\t\t: undefined;\n}\n\nfunction numberValue(value: unknown): number | undefined {\n\treturn typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n}\n\nfunction stringValue(value: unknown): string | undefined {\n\treturn typeof value === \"string\" && value.length > 0 ? value : undefined;\n}\n\nfunction isRiskTier(value: unknown): value is \"low\" | \"medium\" | \"high\" {\n\treturn value === \"low\" || value === \"medium\" || value === \"high\";\n}\n\nfunction toAuthorizationInput<TDb>(\n\taction: ActionDefinition<TDb>,\n\tinput: {\n\t\ttenantId: string;\n\t\tspaceId: string;\n\t\tactorId: string;\n\t\tactorType: import(\"@fabricorg/platform\").ActorType;\n\t},\n): ActionAuthorizationInput {\n\treturn {\n\t\tactionId: action.actionId,\n\t\tnamespace: action.namespace,\n\t\trequiredPermissions: action.requiredPermissions ?? [],\n\t\trequiredRoles: action.requiredRoles ?? [],\n\t\ttenantId: input.tenantId,\n\t\tspaceId: input.spaceId,\n\t\tactorId: input.actorId,\n\t\tactorType: input.actorType,\n\t};\n}\n\nfunction declaredPolicies(policyIds: readonly string[]): RuntimePolicyDefinition[] {\n\treturn policyIds.map((policyId) => ({\n\t\tpolicyId: policyId as `${string}.v${number}`,\n\t\tpolicyVersion: Number(policyId.split(\".v\").at(-1) ?? 1),\n\t\tkind: \"code\",\n\t\tcodeEvaluatorPolicyId: policyId as `${string}.v${number}`,\n\t}));\n}\n\nfunction initialState(machine: import(\"@fabricorg/platform\").StateMachineDefinition | undefined): string {\n\treturn Object.values(machine?.states ?? {}).find((state) => state.stateClass === \"initial\")?.id ?? \"none\";\n}\n\nfunction isTerminal(status: ActionStatus): status is Exclude<ActionStatus, \"pending\" | \"running\" | \"waiting_for_approval\"> {\n\treturn [\"completed\", \"failed\", \"blocked_by_policy\", \"reconciliation_required\", \"validation_failed\"].includes(status);\n}\n\nfunction isAdmissionTime(value: unknown): value is Date {\n\treturn value instanceof Date && Number.isFinite(value.getTime());\n}\n\n/** An own data property of `value`, or `undefined`; a getter is not run and a throwing Proxy trap reads as `undefined`. */\nfunction ownDataProperty(value: unknown, key: string): unknown {\n\tif (value === null || typeof value !== \"object\") return undefined;\n\ttry {\n\t\tconst descriptor = Reflect.getOwnPropertyDescriptor(value, key);\n\t\treturn descriptor && \"value\" in descriptor ? descriptor.value : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction validateAuthorizationBinding(\n\tinput: SubmissionSnapshot,\n\tparameterDigest: string,\n\tauthorityMoment?: \"capture\" | \"execution\" | \"both\",\n\tcurrentTime = new Date(),\n): void {\n\tconst binding = input.authorizationBinding!;\n\tif (binding.id !== input.authorizationBindingId && input.authorizationBindingId) throw new Error(\"Authorization binding ID does not match authorizationBindingId.\");\n\tif (binding.tenantId !== input.tenantId || binding.actorId !== input.actorId || binding.actionId !== input.actionId || binding.parameterDigest !== parameterDigest) {\n\t\tthrow new Error(\"Authorization binding does not match the submitted command identity.\");\n\t}\n\tif (authorityMoment && binding.governingMoment !== authorityMoment) throw new Error(\"Authorization binding governingMoment does not match the action execution contract.\");\n\tconst capturedAt = Date.parse(binding.capturedAt);\n\tconst expiresAt = binding.expiresAt === undefined ? undefined : Date.parse(binding.expiresAt);\n\tif (!Number.isFinite(capturedAt) || (expiresAt !== undefined && !Number.isFinite(expiresAt))) {\n\t\tthrow new Error(\"Authorization binding timestamps must be valid ISO-8601 values.\");\n\t}\n\tif (expiresAt !== undefined && (expiresAt <= capturedAt || (authorityMoment === \"capture\" && expiresAt <= currentTime.getTime()))) {\n\t\tthrow new Error(\"Authorization binding must be unexpired at capture and expire after capturedAt.\");\n\t}\n}\n\nfunction idempotencyConflict(\n\texisting: ActionInvocationRecord,\n\tincoming: { actorId: string; authorizationBindingId?: string; actionVersion: number; parameterDigest: string; idempotencyKey: string },\n): IdempotencyConflict | undefined {\n\tconst reasons: IdempotencyConflict[\"reasons\"] = [];\n\tif ((existing.idempotencyActorId ?? existing.actorId) !== incoming.actorId) reasons.push(\"actor\");\n\tif ((existing.idempotencyAuthorizationBindingId ?? existing.authorizationBindingId) !== incoming.authorizationBindingId) reasons.push(\"authority_binding\");\n\tif (existing.actionVersion !== incoming.actionVersion) reasons.push(\"action_version\");\n\tif (existing.parameterDigest !== incoming.parameterDigest) reasons.push(\"parameters\");\n\treturn reasons.length ? { code: \"IDEMPOTENCY_CONFLICT\", idempotencyKey: incoming.idempotencyKey, existingInvocationId: existing.id, reasons } : undefined;\n}\n\nfunction isKnownAdapterOutcome(outcome: unknown): outcome is import(\"@fabricorg/platform\").AdapterOutcomeKind {\n\treturn outcome === \"success\" || outcome === \"transient_failure\" || outcome === \"permanent_failure\" ||\n\t\toutcome === \"timeout\" || outcome === \"ambiguous\";\n}\n","import type { AssetEventEnvelope } from \"@fabricorg/platform\";\nimport type {\n\tEnterpriseEventActorDisclosure,\n\tEnterpriseEventEnvelope,\n\tOutboxActorDisclosure,\n\tOutboxEventMetadata,\n\tOutboxPlatformHostStore,\n\tOutboxRecord,\n} from \"./types\";\nimport {\n\temitPlatformHostTelemetry,\n\tPLATFORM_HOST_METRIC_NAMES,\n\ttype PlatformHostTelemetry,\n\ttype PlatformHostTelemetryEventName,\n} from \"./observability\";\n\nexport function toEnterpriseEventEnvelope(\n\tevent: AssetEventEnvelope,\n\tmetadata: OutboxEventMetadata,\n): EnterpriseEventEnvelope {\n\treturn {\n\t\teventId: event.id,\n\t\teventType: event.eventType,\n\t\teventSchemaVersion: event.eventSchemaVersion,\n\t\ttenantId: event.tenantId,\n\t\tspaceId: event.spaceId,\n\t\tsubjectType: event.subjectType,\n\t\tsubjectId: event.subjectId,\n\t\tsequence: event.sequence,\n\t\t...(event.actionInvocationId ? { actionInvocationId: event.actionInvocationId } : {}),\n\t\tcorrelationId: event.correlationId,\n\t\t...(event.causationId ? { causationId: event.causationId } : {}),\n\t\t// Opt-in only: without it the keys are absent, so existing publishers see an unchanged envelope.\n\t\t...(includesActor(metadata) && event.actorId ? { actorId: event.actorId } : {}),\n\t\t...(includesActor(metadata) && event.actorType ? { actorType: event.actorType } : {}),\n\t\toccurredAt: event.occurredAt,\n\t\trecordedAt: event.recordedAt,\n\t\tproducerModuleVersion: metadata.producerModuleVersion,\n\t\tpayloadClassification: metadata.payloadClassification,\n\t\t...(metadata.traceContext ? { traceContext: { ...metadata.traceContext } } : {}),\n\t\t...(metadata.includeProvenance && event.provenance ? { provenance: event.provenance } : {}),\n\t\t// A provisional fact must stay marked as provisional once it leaves the platform.\n\t\t...(event.consistency ? { consistency: event.consistency } : {}),\n\t\tpayload: event.payload,\n\t};\n}\n\n/** The `includeActor` decision a store records with the outbox record it writes from `metadata`. */\nexport function outboxActorDisclosure(metadata: OutboxEventMetadata): OutboxActorDisclosure {\n\treturn includesActor(metadata) ? \"included\" : \"suppressed\";\n}\n\nfunction includesActor(metadata: OutboxEventMetadata): boolean {\n\treturn metadata.includeActor === true;\n}\n\nexport interface EnterpriseEventPublishContext {\n\tsignal: AbortSignal;\n\t/**\n\t * Why the envelope does or does not carry `actorId`/`actorType`. `runOutboxRelayCycle()` always\n\t * sets it; a caller other than the relay may omit it, which a consumer should treat like `legacy`.\n\t */\n\tactorDisclosure?: EnterpriseEventActorDisclosure;\n}\n\nexport interface EnterpriseEventPublisher {\n\tpublish(event: EnterpriseEventEnvelope, context?: EnterpriseEventPublishContext): Promise<void>;\n}\n\nexport interface OutboxRelayOptions<TDb> {\n\tstore: OutboxPlatformHostStore<TDb>;\n\tpublisher: EnterpriseEventPublisher;\n\tworkerId: string;\n\tleaseDurationMs?: number;\n\tleaseRenewalIntervalMs?: number;\n\tpublishTimeoutMs?: number;\n\tbatchSize?: number;\n\tmaxAttempts?: number;\n\tretryDelayMs?: (attempt: number) => number;\n\tnow?: () => Date;\n\ttelemetry?: PlatformHostTelemetry;\n}\n\nexport interface OutboxRelayResult {\n\tclaimed: number;\n\tpublished: number;\n\tfailed: number;\n\tdeadLettered: number;\n}\n\nexport async function runOutboxRelayCycle<TDb>(\n\toptions: OutboxRelayOptions<TDb>,\n): Promise<OutboxRelayResult> {\n\tconst now = options.now ?? (() => new Date());\n\tconst maxAttempts = options.maxAttempts ?? 10;\n\tconst leaseDurationMs = options.leaseDurationMs ?? 30_000;\n\temitRelayTelemetry(options.telemetry, \"outbox.relay.started\", now(), options.workerId);\n\tlet records: OutboxRecord[];\n\ttry {\n\t\trecords = await options.store.claimOutbox({\n\t\t\tworkerId: options.workerId,\n\t\t\tleaseDurationMs,\n\t\t\tlimit: options.batchSize ?? 100,\n\t\t\tnow: now(),\n\t\t});\n\t} catch (error) {\n\t\temitRelayTelemetry(options.telemetry, \"outbox.relay.failed\", now(), options.workerId);\n\t\tthrow error;\n\t}\n\tfor (const record of records) {\n\t\temitPlatformHostTelemetry(options.telemetry, {\n\t\t\tkind: \"event\",\n\t\t\tname: \"outbox.lease_claimed\",\n\t\t\tmetricName: PLATFORM_HOST_METRIC_NAMES.outboxLeaseClaimed,\n\t\t\toccurredAt: now(),\n\t\t\ttenantId: record.tenantId,\n\t\t\tspaceId: record.spaceId,\n\t\t\tattributes: { attempt: record.attemptCount },\n\t\t});\n\t}\n\tconst result: OutboxRelayResult = { claimed: records.length, published: 0, failed: 0, deadLettered: 0 };\n\tfor (const record of records) {\n\t\tconst stopHeartbeat = startOutboxHeartbeat(options, record, leaseDurationMs);\n\t\ttry {\n\t\t\tawait publishWithTimeout(\n\t\t\t\toptions.publisher,\n\t\t\t\trecord,\n\t\t\t\toptions.publishTimeoutMs ?? 10_000,\n\t\t\t);\n\t\t\tawait stopHeartbeat();\n\t\t\ttry {\n\t\t\t\tawait options.store.markOutboxPublished(record.id, options.workerId, now(), record.leaseToken);\n\t\t\t} catch {\n\t\t\t\t// Publishing may already have succeeded. Leave the row for lease expiry and\n\t\t\t\t// replay with the same immutable event ID; do not claim completion.\n\t\t\t\tresult.failed += 1;\n\t\t\t\temitPlatformHostTelemetry(options.telemetry, {\n\t\t\t\t\tkind: \"event\",\n\t\t\t\t\tname: \"outbox.failed\",\n\t\t\t\t\tmetricName: PLATFORM_HOST_METRIC_NAMES.outboxFailed,\n\t\t\t\t\toccurredAt: now(),\n\t\t\t\t\ttenantId: record.tenantId,\n\t\t\t\t\tspaceId: record.spaceId,\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tresult.published += 1;\n\t\t\temitPlatformHostTelemetry(options.telemetry, {\n\t\t\t\tkind: \"event\",\n\t\t\t\tname: \"outbox.published\",\n\t\t\t\tmetricName: PLATFORM_HOST_METRIC_NAMES.outboxPublished,\n\t\t\t\toccurredAt: now(),\n\t\t\t\ttenantId: record.tenantId,\n\t\t\t\tspaceId: record.spaceId,\n\t\t\t});\n\t\t} catch {\n\t\t\tawait stopHeartbeat();\n\t\t\tconst deadLetter = record.attemptCount >= maxAttempts;\n\t\t\ttry {\n\t\t\t\tawait options.store.markOutboxFailed({\n\t\t\t\t\tid: record.id,\n\t\t\t\t\tworkerId: options.workerId,\n\t\t\t\t\tleaseToken: record.leaseToken,\n\t\t\t\t\terror: \"Event publisher failed\",\n\t\t\t\t\tavailableAt: new Date(now().getTime() + (options.retryDelayMs?.(record.attemptCount) ?? 1_000)),\n\t\t\t\t\tdeadLetter,\n\t\t\t\t});\n\t\t\t} catch {\n\t\t\t\t// Lease loss is recoverable by a later relay; continue the current batch.\n\t\t\t}\n\t\t\tresult.failed += 1;\n\t\t\tif (deadLetter) result.deadLettered += 1;\n\t\t\temitPlatformHostTelemetry(options.telemetry, {\n\t\t\t\tkind: \"event\",\n\t\t\t\tname: deadLetter ? \"outbox.dead_lettered\" : \"outbox.failed\",\n\t\t\t\tmetricName: deadLetter\n\t\t\t\t\t? PLATFORM_HOST_METRIC_NAMES.outboxDeadLettered\n\t\t\t\t\t: PLATFORM_HOST_METRIC_NAMES.outboxFailed,\n\t\t\t\toccurredAt: now(),\n\t\t\t\ttenantId: record.tenantId,\n\t\t\t\tspaceId: record.spaceId,\n\t\t\t\tattributes: { attempt: record.attemptCount },\n\t\t\t});\n\t\t}\n\t}\n\temitRelayTelemetry(options.telemetry, \"outbox.relay.completed\", now(), options.workerId, {\n\t\tclaimed: result.claimed,\n\t\tpublished: result.published,\n\t\tfailed: result.failed,\n\t\tdeadLettered: result.deadLettered,\n\t});\n\treturn result;\n}\n\nasync function publishWithTimeout(\n\tpublisher: EnterpriseEventPublisher,\n\trecord: OutboxRecord,\n\ttimeoutMs: number,\n): Promise<void> {\n\tif (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {\n\t\tthrow new Error(\"publishTimeoutMs must be a positive finite number\");\n\t}\n\tconst controller = new AbortController();\n\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\tconst timeout = new Promise<never>((_, reject) => {\n\t\ttimer = setTimeout(() => {\n\t\t\tconst error = new Error(`Event publisher timed out after ${timeoutMs}ms`);\n\t\t\tcontroller.abort(error);\n\t\t\treject(error);\n\t\t}, timeoutMs);\n\t});\n\ttry {\n\t\tconst context: EnterpriseEventPublishContext = {\n\t\t\tsignal: controller.signal,\n\t\t\tactorDisclosure: record.actorDisclosure ?? \"legacy\",\n\t\t};\n\t\tawait Promise.race([publisher.publish(record.event, context), timeout]);\n\t} finally {\n\t\tif (timer) clearTimeout(timer);\n\t}\n}\n\nfunction startOutboxHeartbeat<TDb>(\n\toptions: OutboxRelayOptions<TDb>,\n\trecord: OutboxRecord,\n\tleaseDurationMs: number,\n): () => Promise<void> {\n\tif (!record.leaseToken) return async () => undefined;\n\tconst intervalMs = options.leaseRenewalIntervalMs ??\n\t\tMath.max(1, Math.floor(leaseDurationMs / 3));\n\tlet stopped = false;\n\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\tlet running: Promise<void> | undefined;\n\tconst schedule = () => {\n\t\tif (!stopped) timer = setTimeout(tick, intervalMs);\n\t};\n\tconst tick = () => {\n\t\trunning = options.store.renewOutboxLease({\n\t\t\tid: record.id,\n\t\t\tworkerId: options.workerId,\n\t\t\tleaseToken: record.leaseToken!,\n\t\t\tleaseDurationMs,\n\t\t}).then(() => undefined).catch(() => undefined).finally(schedule);\n\t};\n\tschedule();\n\treturn async () => {\n\t\tstopped = true;\n\t\tif (timer) clearTimeout(timer);\n\t\tawait running;\n\t};\n}\n\n/**\n * A copy with its own Date fields and trace context. The event payload and\n * provenance are shallow: the copy shares them with the record, as before.\n */\nexport function cloneOutboxRecord(record: OutboxRecord): OutboxRecord {\n\tconst event: EnterpriseEventEnvelope = {\n\t\t...record.event,\n\t\toccurredAt: new Date(record.event.occurredAt),\n\t\trecordedAt: new Date(record.event.recordedAt),\n\t\t...(record.event.traceContext ? { traceContext: { ...record.event.traceContext } } : {}),\n\t};\n\t// Same rule as PostgreSQL hydration: only a record recorded as included yields actor identity,\n\t// whatever its stored envelope holds. The keys are removed, not set to undefined.\n\tif (record.actorDisclosure !== \"included\") {\n\t\tdelete event.actorId;\n\t\tdelete event.actorType;\n\t}\n\treturn {\n\t\t...record,\n\t\tavailableAt: new Date(record.availableAt),\n\t\tcreatedAt: new Date(record.createdAt),\n\t\t...(record.leaseExpiresAt ? { leaseExpiresAt: new Date(record.leaseExpiresAt) } : {}),\n\t\t...(record.publishedAt ? { publishedAt: new Date(record.publishedAt) } : {}),\n\t\tevent,\n\t};\n}\n\nfunction emitRelayTelemetry(\n\ttelemetry: PlatformHostTelemetry | undefined,\n\tname: Extract<PlatformHostTelemetryEventName, `outbox.relay.${string}`>,\n\toccurredAt: Date,\n\tworkerId: string,\n\tattributes?: Record<string, number>,\n): void {\n\tconst metricName = name === \"outbox.relay.started\"\n\t\t? PLATFORM_HOST_METRIC_NAMES.outboxRelayCyclesStarted\n\t\t: name === \"outbox.relay.completed\"\n\t\t\t? PLATFORM_HOST_METRIC_NAMES.outboxRelayCyclesCompleted\n\t\t\t: PLATFORM_HOST_METRIC_NAMES.outboxRelayCyclesFailed;\n\temitPlatformHostTelemetry(telemetry, {\n\t\tkind: \"event\",\n\t\tname,\n\t\tmetricName,\n\t\toccurredAt,\n\t\tattributes: { workerId, ...attributes },\n\t});\n}\n","import { RecoverableFinalizationError, matchesSettledInvocation } from \"./host-internals\";\nimport type { AssetEventEnvelope } from \"@fabricorg/platform\";\nimport type {\n\tApprovalDecisionTransitionResult,\n\tApprovalPlatformHostStore,\n\tActionInvocationRecord,\n\tActionInvocationPatch,\n\tAdapterInvocationRecord,\n\tAdapterInvocationScope,\n\tAdapterInvocationWriteInput,\n\tBeginApprovalDecisionInput,\n\tClaimActionInvocationsInput,\n\tCreateActionInvocationInput,\n\tHitlDecisionEvidence,\n\tGovernancePlatformHostStore,\n\tPolicyObligationRecord,\n\tExecutionAttestationRecord,\n\tExternalReconciliationRecord,\n\tListActionInvocationsInput,\n\tPolicyEvaluationRecord,\n\tRecoverablePlatformHostStore,\n\tOutboxPlatformHostStore,\n\tOutboxRecord,\n\tOutboxRequeuePlatformHostStore,\n\tOutboxRequeueRecord,\n\tRequeueOutboxDeadLetterStoreInput,\n\tRequeueOutboxDeadLetterStoreResult,\n\tOutboxEventMetadata,\n\tClaimOutboxInput,\n\tOutboxStatus,\n\tPlatformHostMutationTransaction,\n} from \"./types\";\nimport { cloneOutboxRecord, outboxActorDisclosure, toEnterpriseEventEnvelope } from \"./outbox\";\nimport type { PlatformHostHealthCounts, PlatformHostHealthQuery } from \"./observability\";\n\nexport interface MemoryPlatformHostTransactionProvider<TDb> {\n\tsnapshot(db: TDb): TDb;\n\trestore(db: TDb, snapshot: TDb): void;\n}\n\nexport class MemoryPlatformHostStore<TDb>\n\timplements RecoverablePlatformHostStore<TDb>, ApprovalPlatformHostStore<TDb>, GovernancePlatformHostStore<TDb>, OutboxPlatformHostStore<TDb>, OutboxRequeuePlatformHostStore<TDb> {\n\treadonly transactionalOutbox: boolean;\n\tdeclare transactionWithEvents?: <TResult>(run: (transaction: PlatformHostMutationTransaction<TDb>) => Promise<TResult>) => Promise<TResult>;\n\tprivate adapterCommit: Promise<void> | undefined;\n\tprivate transactionTail: Promise<void> = Promise.resolve();\n\treadonly invocations: ActionInvocationRecord[] = [];\n\treadonly policyEvaluations: PolicyEvaluationRecord[] = [];\n\treadonly adapterInvocations: AdapterInvocationRecord[] = [];\n\treadonly events: AssetEventEnvelope[] = [];\n\treadonly policyObligations: PolicyObligationRecord[] = [];\n\treadonly executionAttestations: ExecutionAttestationRecord[] = [];\n\treadonly externalReconciliations: ExternalReconciliationRecord[] = [];\n\treadonly outbox: OutboxRecord[] = [];\n\t/**\n\t * Requeue evidence is append-only audit history, so unlike the ledger\n\t * arrays above, which tests have always inspected and seeded directly, it\n\t * is not public: `listOutboxRequeues` returns copies with their own Dates. TypeScript\n\t * `private`, as for the store's other internals, is a compile-time guard.\n\t */\n\tprivate readonly outboxRequeues: OutboxRequeueRecord[] = [];\n\n\tconstructor(\n\t\treadonly db: TDb,\n\t\ttransactionProvider?: MemoryPlatformHostTransactionProvider<TDb>,\n\t) {\n\t\tthis.transactionalOutbox = transactionProvider !== undefined;\n\t\tif (transactionProvider) this.transactionWithEvents = (run) => this.runTransactionWithEvents(run, transactionProvider);\n\t}\n\n\tasync transaction<TResult>(run: (db: TDb) => Promise<TResult>): Promise<TResult> {\n\t\treturn run(this.db);\n\t}\n\n\tprivate async runTransactionWithEvents<TResult>(\n\t\trun: (transaction: PlatformHostMutationTransaction<TDb>) => Promise<TResult>,\n\t\ttransactionProvider: MemoryPlatformHostTransactionProvider<TDb>,\n\t): Promise<TResult> {\n\t\tlet release!: () => void;\n\t\tconst previous = this.transactionTail;\n\t\tthis.transactionTail = new Promise<void>((resolve) => { release = resolve; });\n\t\tawait previous;\n\t\tlet domainSnapshot: TDb | undefined;\n\t\tlet snapshotCreated = false;\n\t\tlet finishCommit: (() => void) | undefined;\n\t\tconst undoLedgerWrites: Array<() => void> = [];\n\t\ttry {\n\t\t\tdomainSnapshot = transactionProvider.snapshot(this.db);\n\t\t\tsnapshotCreated = true;\n\t\t\tconst pendingEvents: Array<{ event: AssetEventEnvelope; metadata?: OutboxEventMetadata }> = [];\n\t\t\tconst pendingUpdates: Array<{ id: string; tenantId: string; spaceId: string; patch: ActionInvocationPatch }> = [];\n\t\t\tconst pendingAdapterUpdates: Array<Parameters<NonNullable<PlatformHostMutationTransaction<TDb>[\"updateAdapterInvocation\"]>>> = [];\n\t\t\tconst conditionalAdapters: AdapterInvocationWriteInput[] = [];\n\t\t\tconst leasedUpdates: import(\"./types\").UpdateLeasedActionInvocationInput[] = [];\n\t\t\tconst pendingReconciliations: ExternalReconciliationRecord[] = [];\n\t\t\tconst appendPending = async (event: AssetEventEnvelope, metadata?: OutboxEventMetadata) => {\n\t\t\t\tif (this.events.some((candidate) => candidate.id === event.id) || pendingEvents.some((candidate) => candidate.event.id === event.id)) return;\n\t\t\t\tpendingEvents.push({ event, ...(metadata ? { metadata } : {}) });\n\t\t\t};\n\t\t\tconst result = await run({\n\t\t\t\tdb: this.db,\n\t\t\t\tgetActionInvocationForUpdate: async (id, tenantId, spaceId) => {\n\t\t\t\t\tconst record = await this.getActionInvocation(id, tenantId, spaceId);\n\t\t\t\t\treturn record ? structuredClone(record) : undefined;\n\t\t\t\t},\n\t\t\t\tgetEvent: async (id, tenantId, spaceId) =>\n\t\t\t\t\tpendingEvents.find((candidate) =>\n\t\t\t\t\t\tcandidate.event.id === id &&\n\t\t\t\t\t\tcandidate.event.tenantId === tenantId &&\n\t\t\t\t\t\tcandidate.event.spaceId === spaceId)?.event ??\n\t\t\t\t\tthis.events.find((event) =>\n\t\t\t\t\t\tevent.id === id &&\n\t\t\t\t\t\tevent.tenantId === tenantId &&\n\t\t\t\t\t\tevent.spaceId === spaceId),\n\t\t\t\tappendEvent: (event) => appendPending(event),\n\t\t\t\tappendEventWithOutbox: (event, metadata) => appendPending(event, metadata),\n\t\t\t\tnextEventSequence: async (tenantId, spaceId) => (await this.listEvents(tenantId, spaceId)).length + pendingEvents.filter((candidate) => candidate.event.tenantId === tenantId && candidate.event.spaceId === spaceId).length + 1,\n\t\t\t\tlistEvents: async (tenantId, spaceId) => [...await this.listEvents(tenantId, spaceId), ...pendingEvents.map((candidate) => candidate.event).filter((event) => event.tenantId === tenantId && event.spaceId === spaceId)],\n\t\t\t\tgetEntityStateSource: async (tenantId, spaceId, entityType, entityId) => {\n\t\t\t\t\tlet source = await this.getEntityStateSource(tenantId, spaceId, entityType, entityId);\n\t\t\t\t\tfor (const { event } of pendingEvents) {\n\t\t\t\t\t\tif (event.tenantId !== tenantId || event.spaceId !== spaceId ||\n\t\t\t\t\t\t\tevent.subjectType !== entityType || event.subjectId !== entityId) continue;\n\t\t\t\t\t\tconst state = (event.payload as { toState?: unknown } | undefined)?.toState;\n\t\t\t\t\t\tif (typeof state === \"string\") source = typeof event.actionInvocationId === \"string\"\n\t\t\t\t\t\t\t? { state, actionInvocationId: event.actionInvocationId } : undefined;\n\t\t\t\t\t}\n\t\t\t\t\treturn source;\n\t\t\t\t},\n\t\t\t\tgetEntityState: async (tenantId, spaceId, entityType, entityId) => {\n\t\t\t\t\tlet state = await this.getEntityState(tenantId, spaceId, entityType, entityId);\n\t\t\t\t\tfor (const pending of pendingEvents) {\n\t\t\t\t\t\tconst event = pending.event;\n\t\t\t\t\t\tif (event.tenantId !== tenantId || event.spaceId !== spaceId || event.subjectType !== entityType || event.subjectId !== entityId) continue;\n\t\t\t\t\t\tconst candidate = (event.payload as { toState?: unknown } | undefined)?.toState;\n\t\t\t\t\t\tif (typeof candidate === \"string\") state = candidate;\n\t\t\t\t\t}\n\t\t\t\t\treturn state;\n\t\t\t\t},\n\t\t\t\tupdateAdapterInvocation: async (id, patch, scope) => {\n\t\t\t\t\tif (!await this.getAdapterInvocation(id, scope)) throw new Error(`AdapterInvocation not found: ${id}`);\n\t\t\t\t\tpendingAdapterUpdates.push([id, patch, scope]);\n\t\t\t\t},\n\t\t\t\twriteAdapterInvocation: async input => {\n\t\t\t\t\tif (!this.adapterWriteMatches(input)) return false;\n\t\t\t\t\tconditionalAdapters.push(structuredClone(input));\n\t\t\t\t\treturn true;\n\t\t\t\t},\n\t\t\t\tappendExternalReconciliation: async (record) => { pendingReconciliations.push(record); },\n\t\t\t\tupdateActionInvocation: async (id, tenantId, spaceId, patch) => { pendingUpdates.push({ id, tenantId, spaceId, patch: copyInvocationPatch(patch) }); },\n\t\t\t\tupdateLeasedActionInvocation: async (input) => {\n\t\t\t\t\tconst record = await this.getActionInvocation(input.id, input.tenantId, input.spaceId);\n\t\t\t\t\tif (!record || record.status !== \"running\" || record.leaseOwner !== input.workerId ||\n\t\t\t\t\t\trecord.leaseToken !== input.leaseToken) return false;\n\t\t\t\t\tleasedUpdates.push(structuredClone(input));\n\t\t\t\t\tpendingUpdates.push({ id: input.id, tenantId: input.tenantId, spaceId: input.spaceId, patch: copyInvocationPatch(input.patch) });\n\t\t\t\t\treturn true;\n\t\t\t\t},\n\t\t\t});\n\t\t\tthis.adapterCommit = new Promise<void>(resolve => { finishCommit = resolve; });\n\t\t\t// The commit lock excludes claims and conditional writes until all buffered\n\t\t\t// writes finish. Recheck before touching any ledger, including events.\n\t\t\tfor (const input of leasedUpdates) {\n\t\t\t\tconst row = this.invocations.find(row => row.id === input.id && row.tenantId === input.tenantId && row.spaceId === input.spaceId);\n\t\t\t\tif (!row || row.status !== \"running\" || row.leaseOwner !== input.workerId || row.leaseToken !== input.leaseToken) throw leaseWriteLost(input.id);\n\t\t\t}\n\t\t\tfor (const input of conditionalAdapters) if (!this.adapterWriteMatches(input)) throw leaseWriteLost(input.scope.actionInvocationId);\n\t\t\tfor (const update of pendingUpdates) {\n\t\t\t\tif (!await this.getActionInvocation(update.id, update.tenantId, update.spaceId)) throw new Error(`ActionInvocation not found: ${update.id}`);\n\t\t\t}\n\t\t\t// Journal only this commit's writes, after run has finished, so rollback\n\t\t\t// preserves lifecycle writes made outside the transaction while it ran.\n\t\t\tconst rememberRecord = (record: object) => {\n\t\t\t\tconst before = { ...record };\n\t\t\t\tundoLedgerWrites.push(() => {\n\t\t\t\t\tfor (const key of Object.keys(record)) Reflect.deleteProperty(record, key);\n\t\t\t\t\tObject.assign(record, before);\n\t\t\t\t});\n\t\t\t};\n\t\t\tconst rememberAppend = <T extends { id: string }>(rows: T[], id: string) => {\n\t\t\t\tif (!rows.some((row) => row.id === id)) undoLedgerWrites.push(() => {\n\t\t\t\t\tconst index = rows.findIndex((row) => row.id === id);\n\t\t\t\t\tif (index !== -1) rows.splice(index, 1);\n\t\t\t\t});\n\t\t\t};\n\t\t\tfor (const pending of pendingEvents) {\n\t\t\t\trememberAppend(this.events, pending.event.id);\n\t\t\t\trememberAppend(this.outbox, pending.event.id);\n\t\t\t\tif (pending.metadata) await this.appendEventWithOutbox(pending.event, pending.metadata);\n\t\t\t\telse await this.appendEvent(pending.event);\n\t\t\t}\n\t\t\tfor (const record of pendingReconciliations) {\n\t\t\t\trememberAppend(this.externalReconciliations, record.id);\n\t\t\t\tawait this.appendExternalReconciliation(record);\n\t\t\t}\n\t\t\tfor (const [id, patch, scope] of pendingAdapterUpdates) {\n\t\t\t\tconst record = await this.getAdapterInvocation(id, scope);\n\t\t\t\tif (!record) throw new Error(`AdapterInvocation not found: ${id}`);\n\t\t\t\trememberRecord(record);\n\t\t\t\tawait this.updateAdapterInvocation(id, patch, scope);\n\t\t\t}\n\t\t\tfor (const input of conditionalAdapters) {\n\t\t\t\tif (!this.adapterWriteMatches(input)) throw leaseWriteLost(input.scope.actionInvocationId);\n\t\t\t\tif (input.mutation.kind === \"create\") {\n\t\t\t\t\trememberAppend(this.adapterInvocations, input.mutation.record.id);\n\t\t\t\t\tawait this.createAdapterInvocation(input.mutation.record);\n\t\t\t\t} else {\n\t\t\t\t\tconst { id } = input.mutation;\n\t\t\t\t\tconst row = this.adapterInvocations.find(row => row.id === id)!;\n\t\t\t\t\trememberRecord(row);\n\t\t\t\t\tawait this.updateAdapterInvocation(input.mutation.id, input.mutation.patch, input.scope);\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (const update of pendingUpdates) {\n\t\t\t\trememberRecord((await this.getActionInvocation(update.id, update.tenantId, update.spaceId))!);\n\t\t\t\tawait this.updateActionInvocation(update.id, update.tenantId, update.spaceId, update.patch);\n\t\t\t}\n\t\t\treturn result;\n\t\t} catch (error) {\n\t\t\tfor (const undo of undoLedgerWrites.reverse()) undo();\n\t\t\tif (snapshotCreated) transactionProvider.restore(this.db, domainSnapshot!);\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tif (finishCommit) { this.adapterCommit = undefined; finishCommit(); }\n\t\t\trelease();\n\t\t}\n\t}\n\n\tasync createActionInvocation(\n\t\tinput: CreateActionInvocationInput,\n\t): Promise<ActionInvocationRecord> {\n\t\tif (input.idempotencyKey) {\n\t\t\tconst existing = this.invocations.find(\n\t\t\t\t(record) =>\n\t\t\t\t\trecord.tenantId === input.tenantId &&\n\t\t\t\t\trecord.spaceId === input.spaceId &&\n\t\t\t\t\trecord.actionId === input.actionId &&\n\t\t\t\t\trecord.idempotencyKey === input.idempotencyKey,\n\t\t\t);\n\t\t\tif (existing) return existing;\n\t\t}\n\t\tconst now = new Date();\n\t\tconst record = { ...input, attemptCount: 0, leaseToken: 0, createdAt: now, updatedAt: now };\n\t\tthis.invocations.push(record);\n\t\treturn record;\n\t}\n\n\tasync getActionInvocation(\n\t\tid: string,\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t): Promise<ActionInvocationRecord | undefined> {\n\t\treturn this.invocations.find(\n\t\t\t(record) => record.id === id && record.tenantId === tenantId && record.spaceId === spaceId,\n\t\t);\n\t}\n\n\tasync updateActionInvocation(\n\t\tid: string,\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t\tpatch: ActionInvocationPatch,\n\t): Promise<void> {\n\t\tconst record = this.invocations.find(row => row.id === id && row.tenantId === tenantId && row.spaceId === spaceId);\n\t\tif (!record) throw new Error(`ActionInvocation not found: ${id}`);\n\t\tObject.assign(record, patch, { updatedAt: new Date() });\n\t\tif (Object.hasOwn(patch, \"pendingStateTransition\")) {\n\t\t\tif (patch.pendingStateTransition) record.pendingStateTransition = { ...patch.pendingStateTransition };\n\t\t\telse delete record.pendingStateTransition;\n\t\t}\n\t\tif (Object.hasOwn(patch, \"pendingCompletion\") && patch.pendingCompletion === undefined) delete record.pendingCompletion;\n\t\tif (Object.hasOwn(patch, \"externalCompletion\") && patch.externalCompletion === undefined) delete record.externalCompletion;\n\t\tif (Object.hasOwn(patch, \"error\") && patch.error === undefined) delete record.error;\n\t\tif (patch.pendingCompletion && patch.status === \"running\") {\n\t\t\t// Parked: waiting on an external system is not holding a lease. A\n\t\t\t// handoff recorded mid-execution (no status) keeps the lease so the\n\t\t\t// executing worker can still finalize.\n\t\t\tdelete record.leaseOwner;\n\t\t\tdelete record.leaseExpiresAt;\n\t\t}\n\t\tif (\n\t\t\tpatch.status === \"waiting_for_approval\" ||\n\t\t\tpatch.status === \"completed\" ||\n\t\t\tpatch.status === \"failed\" ||\n\t\t\tpatch.status === \"blocked_by_policy\" ||\n\t\t\tpatch.status === \"reconciliation_required\" ||\n\t\t\tpatch.status === \"validation_failed\"\n\t\t) {\n\t\t\tdelete record.leaseOwner;\n\t\t\tdelete record.leaseExpiresAt;\n\t\t}\n\t}\n\n\tasync recordHitlDecision(\n\t\tactionInvocationId: string,\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t\tdecision: HitlDecisionEvidence,\n\t): Promise<ActionInvocationRecord> {\n\t\tconst record = await this.getActionInvocation(actionInvocationId, tenantId, spaceId);\n\t\tif (!record) throw new Error(`ActionInvocation not found: ${actionInvocationId}`);\n\t\trecord.hitlRoute = decision.route;\n\t\trecord.hitlRiskTier = decision.riskTier;\n\t\trecord.hitlReason = decision.reason;\n\t\tif (decision.policyVersion) record.hitlPolicyVersion = decision.policyVersion;\n\t\trecord.updatedAt = decision.evaluatedAt;\n\t\treturn record;\n\t}\n\n\tasync beginApprovalDecision(\n\t\tinput: BeginApprovalDecisionInput,\n\t): Promise<ApprovalDecisionTransitionResult> {\n\t\tconst record = await this.getActionInvocation(\n\t\t\tinput.actionInvocationId,\n\t\t\tinput.tenantId,\n\t\t\tinput.spaceId,\n\t\t);\n\t\tif (!record || record.status !== \"waiting_for_approval\") {\n\t\t\treturn { applied: false, ...(record ? { invocation: record } : {}) };\n\t\t}\n\t\trecord.approvalDecision = input.decision;\n\t\trecord.updatedAt = input.now;\n\t\tif (!input.decision.approved) {\n\t\t\trecord.status = \"failed\";\n\t\t\trecord.error = `Approval rejected: ${input.decision.reason ?? \"no reason provided\"}`;\n\t\t\tdelete record.leaseOwner;\n\t\t\tdelete record.leaseExpiresAt;\n\t\t\treturn { applied: true, invocation: record };\n\t\t}\n\t\trecord.status = \"running\";\n\t\trecord.error = undefined;\n\t\trecord.leaseOwner = input.leaseOwner;\n\t\trecord.leaseExpiresAt = new Date(input.now.getTime() + input.leaseDurationMs);\n\t\trecord.leaseToken = (record.leaseToken ?? 0) + 1;\n\t\trecord.attemptCount = Math.max(record.attemptCount, 1);\n\t\treturn { applied: true, invocation: record };\n\t}\n\n\tasync appendPolicyEvaluation(record: PolicyEvaluationRecord): Promise<void> {\n\t\tif (this.policyEvaluations.some((candidate) => candidate.id === record.id)) return;\n\t\tthis.policyEvaluations.push(record);\n\t}\n\n\tasync recordMutationGovernance(\n\t\tactionInvocationId: string,\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t\tcontext: Pick<ActionInvocationRecord, \"mutationFootprint\" | \"executionPrincipal\"> & {\n\t\t\tfootprint: NonNullable<ActionInvocationRecord[\"mutationFootprint\"]>;\n\t\t\texecutionPrincipal: NonNullable<ActionInvocationRecord[\"executionPrincipal\"]>;\n\t\t},\n\t): Promise<ActionInvocationRecord> {\n\t\tconst record = await this.getActionInvocation(actionInvocationId, tenantId, spaceId);\n\t\tif (!record) throw new Error(`ActionInvocation not found: ${actionInvocationId}`);\n\t\trecord.mutationFootprint = context.footprint;\n\t\trecord.executionPrincipal = context.executionPrincipal;\n\t\trecord.updatedAt = new Date();\n\t\treturn record;\n\t}\n\n\tasync appendPolicyObligations(records: PolicyObligationRecord[]): Promise<void> {\n\t\tfor (const record of records) {\n\t\t\tif (!this.policyObligations.some((candidate) => candidate.actionInvocationId === record.actionInvocationId && candidate.id === record.id)) {\n\t\t\t\tthis.policyObligations.push(record);\n\t\t\t}\n\t\t}\n\t}\n\n\tasync listPolicyObligations(actionInvocationId: string, tenantId: string, spaceId: string) {\n\t\treturn this.policyObligations.filter((record) => record.actionInvocationId === actionInvocationId && record.tenantId === tenantId && record.spaceId === spaceId);\n\t}\n\n\tasync updatePolicyObligation(actionInvocationId: string, obligationId: string, status: PolicyObligationRecord[\"status\"], evidenceReferences?: PolicyObligationRecord[\"evidenceReferences\"]): Promise<void> {\n\t\tconst record = this.policyObligations.find((candidate) => candidate.actionInvocationId === actionInvocationId && candidate.id === obligationId);\n\t\tif (!record) throw new Error(`Policy obligation not found: ${obligationId}`);\n\t\trecord.status = status;\n\t\tif (evidenceReferences) record.evidenceReferences = evidenceReferences;\n\t\trecord.updatedAt = new Date();\n\t}\n\n\tasync appendExecutionAttestation(record: ExecutionAttestationRecord): Promise<void> {\n\t\tif (!this.executionAttestations.some((candidate) => candidate.id === record.id)) this.executionAttestations.push(record);\n\t}\n\n\tasync listExecutionAttestations(actionInvocationId: string, tenantId: string, spaceId: string) {\n\t\treturn this.executionAttestations.filter((record) => record.actionInvocationId === actionInvocationId && record.tenantId === tenantId && record.spaceId === spaceId);\n\t}\n\n\tasync appendExternalReconciliation(record: ExternalReconciliationRecord): Promise<void> {\n\t\tif (!this.externalReconciliations.some((candidate) => candidate.id === record.id)) this.externalReconciliations.push(record);\n\t}\n\n\tprivate adapterWriteMatches(input: AdapterInvocationWriteInput): boolean {\n\t\tconst { scope, condition, mutation } = input;\n\t\tif (condition.kind === \"verdict\" && [\"pending\", \"running\", \"waiting_for_approval\"].includes(condition.status)) return false;\n\t\tconst parent = this.invocations.find(row => row.id === scope.actionInvocationId && row.tenantId === scope.tenantId && row.spaceId === scope.spaceId);\n\t\tif (!parent || (condition.kind === \"lease\"\n\t\t\t? parent.status !== \"running\" || parent.leaseOwner !== condition.leaseOwner || parent.leaseToken !== condition.leaseToken\n\t\t\t: !matchesSettledInvocation(parent, condition,\n\t\t\t\tcondition.completionAdapterInvocationId === undefined\n\t\t\t\t|| condition.completionAdapterInvocationId === (mutation.kind === \"create\" ? mutation.record.id : mutation.id)))) return false;\n\t\tif (mutation.kind === \"create\") {\n\t\t\tconst row = mutation.record;\n\t\t\treturn row.tenantId === scope.tenantId && row.spaceId === scope.spaceId && row.actionInvocationId === scope.actionInvocationId\n\t\t\t\t&& !this.adapterInvocations.some(existing => existing.id === row.id);\n\t\t}\n\t\tconst row = this.adapterInvocations.find(row => row.id === mutation.id && row.tenantId === scope.tenantId && row.spaceId === scope.spaceId && row.actionInvocationId === scope.actionInvocationId);\n\t\treturn !!row && (!input.expectedStatuses || input.expectedStatuses.includes(row.status))\n\t\t\t&& !((row.status === \"succeeded\" || row.status === \"ambiguous\") && (mutation.patch.status === \"running\" || mutation.patch.status === \"failed\"));\n\t}\n\n\tasync updateSettledActionInvocation(input: import(\"./types\").UpdateSettledActionInvocationInput): Promise<boolean> {\n\t\twhile (this.adapterCommit) await this.adapterCommit;\n\t\tconst record = this.invocations.find(row => row.id === input.id && row.tenantId === input.tenantId && row.spaceId === input.spaceId);\n\t\tif (!record || !matchesSettledInvocation(record, input.condition)) return false;\n\t\t// No await between the verdict/completion comparison and its annotation.\n\t\tObject.assign(record, {\n\t\t\t...(Object.hasOwn(input.patch, \"error\") ? { error: input.patch.error } : {}),\n\t\t\t...(Object.hasOwn(input.patch, \"adapterReconciliation\") ? { adapterReconciliation: structuredClone(input.patch.adapterReconciliation) } : {}),\n\t\t\tupdatedAt: new Date(),\n\t\t});\n\t\tif (Object.hasOwn(input.patch, \"error\") && input.patch.error === undefined) delete record.error;\n\t\treturn true;\n\t}\n\n\tasync writeAdapterInvocation(input: AdapterInvocationWriteInput): Promise<boolean> {\n\t\twhile (this.adapterCommit) await this.adapterCommit;\n\t\t// No await between checking authority/status and applying the mutation.\n\t\tif (!this.adapterWriteMatches(input)) return false;\n\t\tif (input.mutation.kind === \"create\") this.adapterInvocations.push(structuredClone(input.mutation.record));\n\t\telse {\n\t\t\tconst { id, patch } = input.mutation;\n\t\t\tObject.assign(this.adapterInvocations.find(row => row.id === id)!, structuredClone(patch));\n\t\t}\n\t\treturn true;\n\t}\n\n\tasync createAdapterInvocation(record: AdapterInvocationRecord): Promise<void> {\n\t\tif (this.adapterInvocations.some((candidate) => candidate.id === record.id)) return;\n\t\tthis.adapterInvocations.push(record);\n\t}\n\n\tasync getAdapterInvocation(id: string, scope?: AdapterInvocationScope): Promise<AdapterInvocationRecord | undefined> {\n\t\treturn this.adapterInvocations.find((candidate) => candidate.id === id\n\t\t\t&& (scope === undefined || (candidate.tenantId === scope.tenantId\n\t\t\t\t&& candidate.spaceId === scope.spaceId && candidate.actionInvocationId === scope.actionInvocationId)));\n\t}\n\n\tasync updateAdapterInvocation(\n\t\tid: string,\n\t\tpatch: Partial<\n\t\t\tPick<AdapterInvocationRecord, \"status\" | \"output\" | \"error\" | \"attempt\" | \"updatedAt\" | \"reconciliation\">\n\t\t>,\n\t\tscope?: AdapterInvocationScope,\n\t): Promise<void> {\n\t\tconst record = this.adapterInvocations.find((candidate) => candidate.id === id\n\t\t\t&& (scope === undefined || (candidate.tenantId === scope.tenantId\n\t\t\t\t&& candidate.spaceId === scope.spaceId && candidate.actionInvocationId === scope.actionInvocationId)));\n\t\tif (!record) throw new Error(`AdapterInvocation not found: ${id}`);\n\t\tObject.assign(record, patch);\n\t}\n\n\tasync appendEvent(event: AssetEventEnvelope): Promise<void> {\n\t\tif (this.events.some((candidate) => candidate.id === event.id)) return;\n\t\tthis.events.push(event);\n\t}\n\n\tasync appendEventWithOutbox(event: AssetEventEnvelope, metadata: OutboxEventMetadata): Promise<void> {\n\t\tif (this.events.some((candidate) => candidate.id === event.id)) return;\n\t\tconst createdAt = new Date(event.recordedAt);\n\t\tthis.events.push(event);\n\t\tthis.outbox.push({\n\t\t\tid: event.id,\n\t\t\ttenantId: event.tenantId,\n\t\t\tspaceId: event.spaceId,\n\t\t\tevent: toEnterpriseEventEnvelope(event, metadata),\n\t\t\tactorDisclosure: outboxActorDisclosure(metadata),\n\t\t\tstatus: \"pending\",\n\t\t\tattemptCount: 0,\n\t\t\tavailableAt: createdAt,\n\t\t\tcreatedAt,\n\t\t});\n\t}\n\n\tasync claimOutbox(input: ClaimOutboxInput): Promise<OutboxRecord[]> {\n\t\tconst current = input.now ?? new Date();\n\t\treturn this.outbox\n\t\t\t.filter((record) => record.status === \"pending\" && record.availableAt <= current && (!record.leaseExpiresAt || record.leaseExpiresAt <= current) && (!input.tenantId || record.tenantId === input.tenantId) && (!input.spaceId || record.spaceId === input.spaceId))\n\t\t\t.sort((left, right) => left.createdAt.getTime() - right.createdAt.getTime() || left.id.localeCompare(right.id))\n\t\t\t.slice(0, Math.max(1, Math.min(input.limit ?? 100, 1_000)))\n\t\t\t.map((record) => {\n\t\t\t\trecord.leaseOwner = input.workerId;\n\t\t\t\trecord.leaseExpiresAt = new Date(current.getTime() + input.leaseDurationMs);\n\t\t\t\trecord.leaseToken = (record.leaseToken ?? 0) + 1;\n\t\t\t\trecord.attemptCount += 1;\n\t\t\t\treturn cloneOutboxRecord(record);\n\t\t\t});\n\t}\n\n\tasync markOutboxPublished(id: string, workerId: string, publishedAt: Date, leaseToken?: number): Promise<void> {\n\t\tconst record = this.requireLeasedOutbox(id, workerId, leaseToken);\n\t\trecord.status = \"published\";\n\t\trecord.publishedAt = publishedAt;\n\t\tdelete record.leaseOwner;\n\t\tdelete record.leaseExpiresAt;\n\t}\n\n\tasync markOutboxFailed(input: { id: string; workerId: string; leaseToken?: number; error: string; availableAt: Date; deadLetter: boolean }): Promise<void> {\n\t\tconst record = this.requireLeasedOutbox(input.id, input.workerId, input.leaseToken);\n\t\trecord.status = input.deadLetter ? \"dead_letter\" : \"pending\";\n\t\trecord.lastError = input.error;\n\t\trecord.availableAt = input.availableAt;\n\t\tdelete record.leaseOwner;\n\t\tdelete record.leaseExpiresAt;\n\t}\n\n\tasync renewOutboxLease(input: { id: string; workerId: string; leaseToken: number; leaseDurationMs: number; now?: Date }): Promise<boolean> {\n\t\tconst record = this.outbox.find((candidate) => candidate.id === input.id);\n\t\tconst current = input.now ?? new Date();\n\t\tif (!record || record.status !== \"pending\" || record.leaseOwner !== input.workerId ||\n\t\t\trecord.leaseToken !== input.leaseToken || !record.leaseExpiresAt ||\n\t\t\trecord.leaseExpiresAt <= current) return false;\n\t\trecord.leaseExpiresAt = new Date(current.getTime() + input.leaseDurationMs);\n\t\treturn true;\n\t}\n\n\tasync listOutbox(input: { tenantId?: string; spaceId?: string; statuses?: OutboxStatus[] } = {}): Promise<OutboxRecord[]> {\n\t\treturn this.outbox.filter((record) => (!input.tenantId || record.tenantId === input.tenantId) && (!input.spaceId || record.spaceId === input.spaceId) && (!input.statuses?.length || input.statuses.includes(record.status))).map(cloneOutboxRecord);\n\t}\n\n\tasync getOutboxRecord(id: string, tenantId: string, spaceId: string): Promise<OutboxRecord | undefined> {\n\t\tconst record = this.outbox.find((candidate) => candidate.id === id && candidate.tenantId === tenantId && candidate.spaceId === spaceId);\n\t\treturn record ? cloneOutboxRecord(record) : undefined;\n\t}\n\n\tasync requeueOutboxDeadLetter(input: RequeueOutboxDeadLetterStoreInput): Promise<RequeueOutboxDeadLetterStoreResult> {\n\t\t// No await between the check and the writes, so the compare-and-set and\n\t\t// its evidence are one step for every other caller of this store.\n\t\tconst record = this.outbox.find((candidate) => candidate.id === input.id && candidate.tenantId === input.tenantId && candidate.spaceId === input.spaceId);\n\t\tif (!record) return { applied: false, refusal: \"not_found\" };\n\t\tif (record.status !== \"dead_letter\") return { applied: false, refusal: \"not_dead_letter\", currentStatus: record.status };\n\t\tif ((record.leaseToken ?? 0) !== input.expectedLeaseToken) return { applied: false, refusal: \"stale\", currentStatus: record.status };\n\t\tconst requeue: OutboxRequeueRecord = {\n\t\t\tid: input.requeueId,\n\t\t\toutboxId: record.id,\n\t\t\ttenantId: record.tenantId,\n\t\t\tspaceId: record.spaceId,\n\t\t\teventId: record.event.eventId,\n\t\t\tactorId: input.actorId,\n\t\t\tactorType: input.actorType,\n\t\t\treason: input.reason,\n\t\t\trequeuedAt: new Date(input.requeuedAt),\n\t\t\tavailableAt: new Date(input.availableAt),\n\t\t\tpriorAttemptCount: record.attemptCount,\n\t\t\t...(record.lastError !== undefined ? { priorLastError: record.lastError } : {}),\n\t\t\tpriorAvailableAt: new Date(record.availableAt),\n\t\t\tpriorLeaseToken: record.leaseToken ?? 0,\n\t\t};\n\t\trecord.status = \"pending\";\n\t\trecord.attemptCount = 0;\n\t\trecord.availableAt = new Date(input.availableAt);\n\t\tdelete record.leaseOwner;\n\t\tdelete record.leaseExpiresAt;\n\t\tthis.outboxRequeues.push(requeue);\n\t\treturn { applied: true, record: cloneOutboxRecord(record), requeue: cloneOutboxRequeue(requeue) };\n\t}\n\n\tasync listOutboxRequeues(input: { tenantId: string; spaceId: string; outboxId?: string }): Promise<OutboxRequeueRecord[]> {\n\t\treturn this.outboxRequeues\n\t\t\t.filter((requeue) => requeue.tenantId === input.tenantId && requeue.spaceId === input.spaceId && (input.outboxId === undefined || requeue.outboxId === input.outboxId))\n\t\t\t.sort((left, right) => left.requeuedAt.getTime() - right.requeuedAt.getTime() || left.id.localeCompare(right.id))\n\t\t\t.map(cloneOutboxRequeue);\n\t}\n\n\tprivate requireLeasedOutbox(id: string, workerId: string, leaseToken?: number): OutboxRecord {\n\t\tconst record = this.outbox.find((candidate) => candidate.id === id);\n\t\tif (!record || record.leaseOwner !== workerId ||\n\t\t\t(record.leaseToken ?? 0) !== (leaseToken ?? 0)) {\n\t\t\tthrow new Error(`Outbox record ${id} is not leased by ${workerId}.`);\n\t\t}\n\t\treturn record;\n\t}\n\n\tasync nextEventSequence(tenantId: string, spaceId: string): Promise<number> {\n\t\treturn (\n\t\t\tthis.events.filter((event) => event.tenantId === tenantId && event.spaceId === spaceId)\n\t\t\t\t.length + 1\n\t\t);\n\t}\n\n\tasync getEntityStateSource(\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t\tentityType: string,\n\t\tentityId: string,\n\t): Promise<{ state: string; actionInvocationId: string } | undefined> {\n\t\tlet source: { state: string; actionInvocationId: string } | undefined;\n\t\tfor (const event of this.events) {\n\t\t\tif (event.tenantId !== tenantId || event.spaceId !== spaceId ||\n\t\t\t\tevent.subjectType !== entityType || event.subjectId !== entityId) continue;\n\t\t\tconst state = (event.payload as { toState?: unknown } | undefined)?.toState;\n\t\t\tif (typeof state === \"string\") source = typeof event.actionInvocationId === \"string\"\n\t\t\t\t? { state, actionInvocationId: event.actionInvocationId } : undefined;\n\t\t}\n\t\treturn source;\n\t}\n\n\tasync getEntityState(\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t\tentityType: string,\n\t\tentityId: string,\n\t): Promise<string | undefined> {\n\t\tlet state: string | undefined;\n\t\tfor (const event of this.events) {\n\t\t\tif (\n\t\t\t\tevent.tenantId !== tenantId ||\n\t\t\t\tevent.spaceId !== spaceId ||\n\t\t\t\tevent.subjectType !== entityType ||\n\t\t\t\tevent.subjectId !== entityId\n\t\t\t) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst candidate = (event.payload as { toState?: unknown } | undefined)?.toState;\n\t\t\tif (typeof candidate === \"string\") state = candidate;\n\t\t}\n\t\treturn state;\n\t}\n\n\tasync listActionInvocations(\n\t\tinput: ListActionInvocationsInput = {},\n\t): Promise<ActionInvocationRecord[]> {\n\t\treturn this.invocations\n\t\t\t.filter(\n\t\t\t\t(record) =>\n\t\t\t\t\t(!input.tenantId || record.tenantId === input.tenantId) &&\n\t\t\t\t\t(!input.spaceId || record.spaceId === input.spaceId) &&\n\t\t\t\t\t(!input.statuses?.length || input.statuses.includes(record.status)) &&\n\t\t\t\t\t(!input.updatedBefore || record.updatedAt < input.updatedBefore) &&\n\t\t\t\t\t(!(input.awaitingCompletion || input.completionDueBefore) || record.pendingCompletion !== undefined) &&\n\t\t\t\t\t(!input.completionDueBefore || (record.pendingCompletion?.dueAt !== undefined && record.pendingCompletion.dueAt <= input.completionDueBefore)) &&\n\t\t\t\t\t(!input.unleased || record.leaseOwner === undefined),\n\t\t\t)\n\t\t\t.sort((left, right) => left.createdAt.getTime() - right.createdAt.getTime())\n\t\t\t.slice(0, input.limit ?? 100);\n\t}\n\n\tasync getHealthCounts(input: PlatformHostHealthQuery): Promise<PlatformHostHealthCounts> {\n\t\tconst invocations = this.invocations.filter(\n\t\t\t(record) =>\n\t\t\t\t(!input.tenantId || record.tenantId === input.tenantId) &&\n\t\t\t\t(!input.spaceId || record.spaceId === input.spaceId),\n\t\t);\n\t\tconst outbox = this.outbox.filter(\n\t\t\t(record) =>\n\t\t\t\t(!input.tenantId || record.tenantId === input.tenantId) &&\n\t\t\t\t(!input.spaceId || record.spaceId === input.spaceId),\n\t\t);\n\t\treturn {\n\t\t\tinvocationBacklog: invocations.filter((item) => item.status === \"pending\").length,\n\t\t\tinvocationRunning: invocations.filter((item) => item.status === \"running\").length,\n\t\t\tinvocationExpiredLeases: invocations.filter((item) =>\n\t\t\t\titem.status === \"running\" &&\n\t\t\t\titem.leaseExpiresAt !== undefined &&\n\t\t\t\titem.leaseExpiresAt.getTime() <= input.now.getTime(),\n\t\t\t).length,\n\t\t\tinvocationApprovalWaits: invocations.filter((item) => item.status === \"waiting_for_approval\").length,\n\t\t\tinvocationReconciliationRequired: invocations.filter((item) => item.status === \"reconciliation_required\").length,\n\t\t\toutboxBacklog: outbox.filter((item) => item.status === \"pending\").length,\n\t\t\toutboxExpiredLeases: outbox.filter((item) =>\n\t\t\t\titem.status === \"pending\" &&\n\t\t\t\titem.leaseExpiresAt !== undefined &&\n\t\t\t\titem.leaseExpiresAt.getTime() <= input.now.getTime(),\n\t\t\t).length,\n\t\t\toutboxDeadLetters: outbox.filter((item) => item.status === \"dead_letter\").length,\n\t\t};\n\t}\n\n\tasync claimActionInvocations(\n\t\tinput: ClaimActionInvocationsInput,\n\t): Promise<ActionInvocationRecord[]> {\n\t\twhile (this.adapterCommit) await this.adapterCommit;\n\t\tconst current = input.now ?? new Date();\n\t\tconst eligible = this.invocations\n\t\t\t.filter(\n\t\t\t\t(record) =>\n\t\t\t\t\t(!input.tenantId || record.tenantId === input.tenantId) &&\n\t\t\t\t\t(!input.spaceId || record.spaceId === input.spaceId) &&\n\t\t\t\t\t(record.status === \"pending\" ||\n\t\t\t\t\t\t(record.status === \"running\" &&\n\t\t\t\t\t\t\trecord.leaseExpiresAt !== undefined &&\n\t\t\t\t\t\t\trecord.leaseExpiresAt <= current)),\n\t\t\t)\n\t\t\t.sort((left, right) => left.createdAt.getTime() - right.createdAt.getTime())\n\t\t\t.slice(0, input.limit ?? 10);\n\t\tfor (const record of eligible) {\n\t\t\trecord.status = \"running\";\n\t\t\trecord.leaseOwner = input.workerId;\n\t\t\trecord.leaseExpiresAt = new Date(current.getTime() + input.leaseDurationMs);\n\t\t\trecord.leaseToken = (record.leaseToken ?? 0) + 1;\n\t\t\trecord.attemptCount += 1;\n\t\t\trecord.updatedAt = current;\n\t\t}\n\t\treturn eligible.map((record) => structuredClone(record));\n\t}\n\n\tasync updateLeasedActionInvocation(input: import(\"./types\").UpdateLeasedActionInvocationInput): Promise<boolean> {\n\t\twhile (this.adapterCommit) await this.adapterCommit;\n\t\tconst record = this.invocations.find(row => row.id === input.id && row.tenantId === input.tenantId && row.spaceId === input.spaceId);\n\t\tif (!record || record.status !== \"running\" || record.leaseOwner !== input.workerId ||\n\t\t\trecord.leaseToken !== input.leaseToken) return false;\n\t\tawait this.updateActionInvocation(input.id, input.tenantId, input.spaceId, input.patch);\n\t\treturn true;\n\t}\n\n\tasync renewActionInvocationLease(input: import(\"./types\").RenewActionInvocationLeaseInput): Promise<boolean> {\n\t\tconst record = await this.getActionInvocation(input.id, input.tenantId, input.spaceId);\n\t\tconst current = input.now ?? new Date();\n\t\tif (!record || record.status !== \"running\" || record.leaseOwner !== input.workerId ||\n\t\t\trecord.leaseToken !== input.leaseToken || !record.leaseExpiresAt ||\n\t\t\trecord.leaseExpiresAt <= current) return false;\n\t\trecord.leaseExpiresAt = new Date(current.getTime() + input.leaseDurationMs);\n\t\trecord.updatedAt = current;\n\t\treturn true;\n\t}\n\n\tasync listEvents(tenantId: string, spaceId: string): Promise<AssetEventEnvelope[]> {\n\t\treturn this.events\n\t\t\t.filter((event) => event.tenantId === tenantId && event.spaceId === spaceId)\n\t\t\t.sort((left, right) => left.sequence - right.sequence);\n\t}\n}\n\nfunction cloneOutboxRequeue(requeue: OutboxRequeueRecord): OutboxRequeueRecord {\n\treturn {\n\t\t...requeue,\n\t\trequeuedAt: new Date(requeue.requeuedAt),\n\t\tavailableAt: new Date(requeue.availableAt),\n\t\tpriorAvailableAt: new Date(requeue.priorAvailableAt),\n\t};\n}\n\nfunction copyInvocationPatch(patch: ActionInvocationPatch): ActionInvocationPatch {\n\treturn { ...patch, ...(patch.pendingStateTransition ? { pendingStateTransition: { ...patch.pendingStateTransition } } : {}) };\n}\n\nfunction leaseWriteLost(id: string): Error {\n\treturn new RecoverableFinalizationError(`Invocation lease or adapter condition lost at commit: ${id}`);\n}\n","import { createHash } from \"node:crypto\";\nimport type { PlatformHostSqlClient } from \"./postgres-store\";\n\nexport interface PostgresMigration {\n\tversion: number;\n\tname: string;\n\tsql: string;\n}\n\n/**\n * Applies an immutable, ordered migration set in one PostgreSQL transaction.\n *\n * The transaction-scoped advisory lock serializes migrators. A previously\n * applied version may be presented again only when its checksum is unchanged.\n */\nexport async function applyPostgresMigrations(\n\tclient: PlatformHostSqlClient,\n\tmigrations: readonly PostgresMigration[],\n): Promise<void> {\n\tconst ordered = validateMigrations(migrations);\n\tconst statements = ordered.map((migration) => migrationStatement(migration));\n\n\tawait client.query(`\n\t\tBEGIN;\n\t\tSELECT pg_advisory_xact_lock(hashtext('fabric_platform.schema_migrations'));\n\t\tCREATE SCHEMA IF NOT EXISTS fabric_platform;\n\t\tCREATE TABLE IF NOT EXISTS fabric_platform.schema_migrations (\n\t\t\tversion integer PRIMARY KEY,\n\t\t\tname text NOT NULL,\n\t\t\tchecksum text NOT NULL,\n\t\t\tapplied_at timestamptz NOT NULL DEFAULT now()\n\t\t);\n\t\t${statements.join(\"\\n\")}\n\t\tCOMMIT;\n\t`);\n}\n\nfunction validateMigrations(\n\tmigrations: readonly PostgresMigration[],\n): PostgresMigration[] {\n\tconst ordered = [...migrations].sort((left, right) => left.version - right.version);\n\tconst versions = new Set<number>();\n\n\tfor (const migration of ordered) {\n\t\tif (!Number.isSafeInteger(migration.version) || migration.version < 1) {\n\t\t\tthrow new Error(`Migration version must be a positive safe integer: ${migration.version}`);\n\t\t}\n\t\tif (versions.has(migration.version)) {\n\t\t\tthrow new Error(`Duplicate migration version: ${migration.version}`);\n\t\t}\n\t\tif (!/^[a-z][a-z0-9_]*$/.test(migration.name)) {\n\t\t\tthrow new Error(`Invalid migration name: ${migration.name}`);\n\t\t}\n\t\tif (migration.sql.trim().length === 0) {\n\t\t\tthrow new Error(`Migration ${migration.version} has no SQL`);\n\t\t}\n\t\tversions.add(migration.version);\n\t}\n\n\treturn ordered;\n}\n\nfunction migrationStatement(migration: PostgresMigration): string {\n\tconst checksum = createHash(\"sha256\").update(migration.sql).digest(\"hex\");\n\tconst delimiter = `$fabric_platform_migration_${migration.version}$`;\n\tif (migration.sql.includes(delimiter)) {\n\t\tthrow new Error(`Migration ${migration.version} contains its reserved SQL delimiter`);\n\t}\n\n\treturn `\n\t\tDO ${delimiter}\n\t\tDECLARE\n\t\t\trecorded_checksum text;\n\t\tBEGIN\n\t\t\tSELECT checksum INTO recorded_checksum\n\t\t\tFROM fabric_platform.schema_migrations\n\t\t\tWHERE version = ${migration.version};\n\n\t\t\tIF FOUND THEN\n\t\t\t\tIF recorded_checksum <> ${sqlLiteral(checksum)} THEN\n\t\t\t\t\tRAISE EXCEPTION 'Migration checksum mismatch for version ${migration.version}';\n\t\t\t\tEND IF;\n\t\t\tELSE\n\t\t\t\t${migration.sql}\n\t\t\t\tINSERT INTO fabric_platform.schema_migrations (version, name, checksum)\n\t\t\t\tVALUES (${migration.version}, ${sqlLiteral(migration.name)}, ${sqlLiteral(checksum)});\n\t\t\tEND IF;\n\t\tEND\n\t\t${delimiter};`;\n}\n\nfunction sqlLiteral(value: string): string {\n\treturn `'${value.replaceAll(\"'\", \"''\")}'`;\n}\n","import type { AssetEventEnvelope } from \"@fabricorg/platform\";\nimport type {\n\tActionInvocationPatch,\n\tApprovalDecisionTransitionResult,\n\tApprovalPlatformHostStore,\n\tActionInvocationRecord,\n\tAdapterInvocationRecord,\n\tAdapterInvocationScope,\n\tAdapterInvocationWriteInput,\n\tAtomicMutationPlatformHostStore,\n\tBeginApprovalDecisionInput,\n\tClaimActionInvocationsInput,\n\tCreateActionInvocationInput,\n\tHitlDecisionEvidence,\n\tGovernancePlatformHostStore,\n\tPolicyObligationRecord,\n\tExecutionAttestationRecord,\n\tExternalReconciliationRecord,\n\tListActionInvocationsInput,\n\tPolicyEvaluationRecord,\n\tPlatformHostMutationTransaction,\n\tRecoverablePlatformHostStore,\n\tOutboxPlatformHostStore,\n\tOutboxEventMetadata,\n\tOutboxRecord,\n\tOutboxRequeuePlatformHostStore,\n\tOutboxRequeueRecord,\n\tRequeueOutboxDeadLetterStoreInput,\n\tRequeueOutboxDeadLetterStoreResult,\n\tClaimOutboxInput,\n\tOutboxStatus,\n\tEnterpriseEventEnvelope,\n} from \"./types\";\nimport { outboxActorDisclosure, toEnterpriseEventEnvelope } from \"./outbox\";\nimport { applyPostgresMigrations } from \"./postgres-migrations\";\nimport type { PlatformHostHealthCounts, PlatformHostHealthQuery } from \"./observability\";\n\nexport interface PlatformHostSqlResult<Row = Record<string, unknown>> {\n\trows: Row[];\n}\n\n/** Structural subset implemented by `pg.Pool` and Lakebase-compatible clients. */\nexport interface PlatformHostSqlClient {\n\tquery<Row = Record<string, unknown>>(\n\t\tsql: string,\n\t\tvalues?: unknown[],\n\t): Promise<PlatformHostSqlResult<Row>>;\n}\n\nexport interface PostgresPlatformHostTransactionContext<TDb> {\n\tdb: TDb;\n\tsql: PlatformHostSqlClient;\n}\n\n/**\n * Application-owned transaction binder.\n *\n * Platform Host cannot infer how an application's `TDb` is rebound to a\n * `pg.PoolClient`. Production applications provide this adapter so domain\n * methods and Host ledger writes share one PostgreSQL transaction.\n */\nexport interface PostgresPlatformHostTransactionProvider<TDb> {\n\trun<TResult>(\n\t\trun: (context: PostgresPlatformHostTransactionContext<TDb>) => Promise<TResult>,\n\t): Promise<TResult>;\n}\n\n/** Durable mutation-pipeline ledger for Databricks Lakebase or standard Postgres. */\nexport class PostgresPlatformHostStore<TDb>\n\timplements RecoverablePlatformHostStore<TDb>, ApprovalPlatformHostStore<TDb>, GovernancePlatformHostStore<TDb>, OutboxPlatformHostStore<TDb>, OutboxRequeuePlatformHostStore<TDb> {\n\treadonly transactionWithEvents?: AtomicMutationPlatformHostStore<TDb>[\"transactionWithEvents\"];\n\treadonly transactionalOutbox: boolean;\n\n\tconstructor(\n\t\treadonly db: TDb,\n\t\tprivate readonly sql: PlatformHostSqlClient,\n\t\ttransactionProvider?: PostgresPlatformHostTransactionProvider<TDb>,\n\t) {\n\t\tthis.transactionalOutbox = transactionProvider !== undefined;\n\t\tif (transactionProvider) {\n\t\t\tthis.transactionWithEvents = async <TResult>(\n\t\t\t\trun: (transaction: PlatformHostMutationTransaction<TDb>) => Promise<TResult>,\n\t\t\t): Promise<TResult> =>\n\t\t\t\ttransactionProvider.run(async ({ db, sql }) => {\n\t\t\t\t\tconst scoped = new PostgresPlatformHostStore(db, sql);\n\t\t\t\t\treturn run({\n\t\t\t\t\t\tdb,\n\t\t\t\t\t\tgetActionInvocationForUpdate: async (id, tenantId, spaceId) => {\n\t\t\t\t\t\t\tconst result = await sql.query<Record<string, unknown>>(\n\t\t\t\t\t\t\t\t`SELECT * FROM fabric_platform.action_invocations\n\t\t\t\t\t\t\t\t WHERE id=$1 AND tenant_id=$2 AND space_id=$3\n\t\t\t\t\t\t\t\t FOR UPDATE`,\n\t\t\t\t\t\t\t\t[id, tenantId, spaceId],\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\treturn result.rows[0] ? toActionRecord(result.rows[0]) : undefined;\n\t\t\t\t\t\t},\n\t\t\t\t\t\tgetEvent: (id, tenantId, spaceId) =>\n\t\t\t\t\t\t\tscoped.getEvent(id, tenantId, spaceId),\n\t\t\t\t\t\tappendEvent: (event) => scoped.appendEvent(event),\n\t\t\t\t\t\tappendEventWithOutbox: (event, metadata) => scoped.appendEventWithOutbox(event, metadata),\n\t\t\t\t\t\tnextEventSequence: (tenantId, spaceId) =>\n\t\t\t\t\t\t\tscoped.nextEventSequence(tenantId, spaceId),\n\t\t\t\t\t\tlistEvents: (tenantId, spaceId) =>\n\t\t\t\t\t\t\tscoped.listEvents(tenantId, spaceId),\n\t\t\t\t\t\tgetEntityStateSource: (tenantId, spaceId, entityType, entityId) =>\n\t\t\t\t\t\t\tscoped.getEntityStateSource(tenantId, spaceId, entityType, entityId),\n\t\t\t\t\t\tgetEntityState: (tenantId, spaceId, entityType, entityId) =>\n\t\t\t\t\t\t\tscoped.getEntityState(tenantId, spaceId, entityType, entityId),\n\t\t\t\t\t\tupdateActionInvocation: (id, tenantId, spaceId, patch) =>\n\t\t\t\t\t\t\tscoped.updateActionInvocation(id, tenantId, spaceId, patch),\n\t\t\t\t\t\tupdateLeasedActionInvocation: (input) =>\n\t\t\t\t\t\t\tscoped.updateLeasedActionInvocation(input),\n\t\t\t\t\t\tupdateAdapterInvocation: (id, patch, scope) =>\n\t\t\t\t\t\t\tscoped.updateAdapterInvocation(id, patch, scope),\n\t\t\t\t\t\twriteAdapterInvocation: input => scoped.writeAdapterInvocation(input),\n\t\t\t\t\t\tappendExternalReconciliation: (record) =>\n\t\t\t\t\t\t\tscoped.appendExternalReconciliation(record),\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t}\n\t}\n\n\tasync ensureSchema(): Promise<void> {\n\t\tawait applyPostgresMigrations(this.sql, [{\n\t\t\tversion: 1,\n\t\t\tname: \"host_ledger_baseline\",\n\t\t\tsql: `\n\t\t\tCREATE SCHEMA IF NOT EXISTS fabric_platform;\n\t\t\tCREATE TABLE IF NOT EXISTS fabric_platform.action_invocations (\n\t\t\t\tid text PRIMARY KEY, tenant_id text NOT NULL, space_id text NOT NULL,\n\t\t\t\taction_id text NOT NULL, action_version integer NOT NULL,\n\t\t\t\tactor_id text NOT NULL, actor_type text NOT NULL, status text NOT NULL,\n\t\t\t\tparameters jsonb NOT NULL, result jsonb NOT NULL DEFAULT '{}'::jsonb,\n\t\t\t\tcorrelation_id text NOT NULL, causation_id text, idempotency_key text,\n\t\t\t\tparameter_digest text, parameter_digest_algorithm text, idempotency_actor_id text,\n\t\t\t\tidempotency_authorization_binding_id text, invocation_provenance jsonb,\n\t\t\t\tauthorization_binding jsonb, execution_reason text, authorization_reconciliation jsonb,\n\t\t\t\tadapter_reconciliation jsonb, authorization_binding_id text, error text,\n\t\t\t\tattempt_count integer NOT NULL DEFAULT 0, lease_owner text,\n\t\t\t\tlease_expires_at timestamptz, hitl_route text, hitl_risk_tier text,\n\t\t\t\thitl_reason text, hitl_policy_version text, approval_decision jsonb,\n\t\t\t\tmutation_footprint jsonb, execution_principal jsonb, runtime_evidence jsonb,\n\t\t\t\tcreated_at timestamptz NOT NULL, updated_at timestamptz NOT NULL\n\t\t\t);\n\t\t\tALTER TABLE fabric_platform.action_invocations\n\t\t\t\tADD COLUMN IF NOT EXISTS idempotency_key text,\n\t\t\t\tADD COLUMN IF NOT EXISTS parameter_digest text,\n\t\t\t\tADD COLUMN IF NOT EXISTS parameter_digest_algorithm text,\n\t\t\t\tADD COLUMN IF NOT EXISTS idempotency_actor_id text,\n\t\t\t\tADD COLUMN IF NOT EXISTS idempotency_authorization_binding_id text,\n\t\t\t\tADD COLUMN IF NOT EXISTS invocation_provenance jsonb,\n\t\t\t\tADD COLUMN IF NOT EXISTS authorization_binding jsonb,\n\t\t\t\tADD COLUMN IF NOT EXISTS execution_reason text,\n\t\t\t\tADD COLUMN IF NOT EXISTS authorization_reconciliation jsonb,\n\t\t\t\tADD COLUMN IF NOT EXISTS adapter_reconciliation jsonb,\n\t\t\t\tADD COLUMN IF NOT EXISTS authorization_binding_id text,\n\t\t\t\tADD COLUMN IF NOT EXISTS attempt_count integer NOT NULL DEFAULT 0,\n\t\t\t\tADD COLUMN IF NOT EXISTS lease_owner text,\n\t\t\t\tADD COLUMN IF NOT EXISTS lease_expires_at timestamptz,\n\t\t\t\tADD COLUMN IF NOT EXISTS hitl_route text,\n\t\t\t\tADD COLUMN IF NOT EXISTS hitl_risk_tier text,\n\t\t\t\tADD COLUMN IF NOT EXISTS hitl_reason text,\n\t\t\t\tADD COLUMN IF NOT EXISTS hitl_policy_version text,\n\t\t\t\tADD COLUMN IF NOT EXISTS approval_decision jsonb,\n\t\t\t\tADD COLUMN IF NOT EXISTS mutation_footprint jsonb,\n\t\t\t\tADD COLUMN IF NOT EXISTS execution_principal jsonb,\n\t\t\t\tADD COLUMN IF NOT EXISTS runtime_evidence jsonb;\n\t\t\tCREATE UNIQUE INDEX IF NOT EXISTS action_invocations_idempotency_idx\n\t\t\t\tON fabric_platform.action_invocations\n\t\t\t\t(tenant_id, space_id, action_id, idempotency_key)\n\t\t\t\tWHERE idempotency_key IS NOT NULL;\n\t\t\tCREATE INDEX IF NOT EXISTS action_invocations_parameter_digest_idx\n\t\t\t\tON fabric_platform.action_invocations (tenant_id, parameter_digest)\n\t\t\t\tWHERE parameter_digest IS NOT NULL;\n\t\t\tCREATE INDEX IF NOT EXISTS action_invocations_authority_binding_idx\n\t\t\t\tON fabric_platform.action_invocations (tenant_id, authorization_binding_id)\n\t\t\t\tWHERE authorization_binding_id IS NOT NULL;\n\t\t\tCREATE INDEX IF NOT EXISTS action_invocations_worker_idx\n\t\t\t\tON fabric_platform.action_invocations (status, lease_expires_at, created_at);\n\t\t\tCREATE TABLE IF NOT EXISTS fabric_platform.policy_evaluations (\n\t\t\t\tid text PRIMARY KEY, action_invocation_id text NOT NULL,\n\t\t\t\ttenant_id text NOT NULL, space_id text NOT NULL, outcome jsonb NOT NULL,\n\t\t\t\tcreated_at timestamptz NOT NULL\n\t\t\t);\n\t\t\tCREATE TABLE IF NOT EXISTS fabric_platform.adapter_invocations (\n\t\t\t\tid text PRIMARY KEY, action_invocation_id text NOT NULL,\n\t\t\t\ttenant_id text NOT NULL, space_id text NOT NULL, adapter_type text NOT NULL,\n\t\t\t\toperation text NOT NULL, vendor text NOT NULL, status text NOT NULL,\n\t\t\t\tinput jsonb NOT NULL, output jsonb, error text, attempt integer NOT NULL,\n\t\t\t\tcreated_at timestamptz NOT NULL, updated_at timestamptz NOT NULL\n\t\t\t);\n\t\t\tCREATE TABLE IF NOT EXISTS fabric_platform.policy_obligations (\n\t\t\t\taction_invocation_id text NOT NULL, id text NOT NULL,\n\t\t\t\ttenant_id text NOT NULL, space_id text NOT NULL, type text NOT NULL,\n\t\t\t\tstatus text NOT NULL, required boolean NOT NULL DEFAULT true,\n\t\t\t\tdescription text, evidence_references jsonb, metadata jsonb,\n\t\t\t\tcreated_at timestamptz NOT NULL, updated_at timestamptz NOT NULL,\n\t\t\t\tPRIMARY KEY (action_invocation_id,id)\n\t\t\t);\n\t\t\tCREATE TABLE IF NOT EXISTS fabric_platform.execution_attestations (\n\t\t\t\tid text PRIMARY KEY, action_invocation_id text NOT NULL,\n\t\t\t\ttenant_id text NOT NULL, space_id text NOT NULL, adapter_invocation_id text,\n\t\t\t\tattestation jsonb NOT NULL, recorded_at timestamptz NOT NULL\n\t\t\t);\n\t\t\tCREATE TABLE IF NOT EXISTS fabric_platform.external_reconciliations (\n\t\t\t\tid text PRIMARY KEY, action_invocation_id text NOT NULL,\n\t\t\t\ttenant_id text NOT NULL, space_id text NOT NULL,\n\t\t\t\treconciliation jsonb NOT NULL\n\t\t\t);\n\t\t\tCREATE TABLE IF NOT EXISTS fabric_platform.event_sequences (\n\t\t\t\ttenant_id text NOT NULL, space_id text NOT NULL, next_sequence bigint NOT NULL,\n\t\t\t\tPRIMARY KEY (tenant_id, space_id)\n\t\t\t);\n\t\t\tCREATE TABLE IF NOT EXISTS fabric_platform.asset_events (\n\t\t\t\tid text PRIMARY KEY, tenant_id text NOT NULL, space_id text NOT NULL,\n\t\t\t\tevent_type text NOT NULL, event_schema_version integer NOT NULL,\n\t\t\t\tsubject_type text NOT NULL, subject_id text NOT NULL,\n\t\t\t\tactor_id text NOT NULL, actor_type text NOT NULL, action_invocation_id text,\n\t\t\t\tpayload jsonb NOT NULL, sequence bigint NOT NULL,\n\t\t\t\toccurred_at timestamptz NOT NULL, recorded_at timestamptz NOT NULL,\n\t\t\t\tcorrelation_id text NOT NULL, causation_id text, provenance jsonb, consistency text,\n\t\t\t\tUNIQUE (tenant_id, space_id, sequence)\n\t\t\t);\n\t\t\tALTER TABLE fabric_platform.asset_events ADD COLUMN IF NOT EXISTS provenance jsonb;\n\t\t\tALTER TABLE fabric_platform.asset_events ADD COLUMN IF NOT EXISTS consistency text;\n\t\t\tCREATE INDEX IF NOT EXISTS asset_events_subject_idx\n\t\t\t\tON fabric_platform.asset_events\n\t\t\t\t(tenant_id, space_id, subject_type, subject_id, sequence);\n\t\t\tCREATE TABLE IF NOT EXISTS fabric_platform.event_outbox (\n\t\t\t\tid text PRIMARY KEY, tenant_id text NOT NULL, space_id text NOT NULL,\n\t\t\t\tevent jsonb NOT NULL, status text NOT NULL DEFAULT 'pending',\n\t\t\t\tattempt_count integer NOT NULL DEFAULT 0, available_at timestamptz NOT NULL,\n\t\t\t\tlease_owner text, lease_expires_at timestamptz, last_error text,\n\t\t\t\tcreated_at timestamptz NOT NULL, published_at timestamptz\n\t\t\t);\n\t\t\tCREATE INDEX IF NOT EXISTS event_outbox_claim_idx\n\t\t\t\tON fabric_platform.event_outbox (status, available_at, lease_expires_at, created_at);\n\t\t\t`,\n\t\t}, {\n\t\t\tversion: 2,\n\t\t\tname: \"lease_fencing\",\n\t\t\tsql: `\n\t\t\t\tALTER TABLE fabric_platform.action_invocations\n\t\t\t\t\tADD COLUMN lease_token bigint NOT NULL DEFAULT 0;\n\t\t\t\tALTER TABLE fabric_platform.event_outbox\n\t\t\t\t\tADD COLUMN lease_token bigint NOT NULL DEFAULT 0;\n\t\t\t`,\n\t\t}, {\n\t\t\tversion: 3,\n\t\t\tname: \"external_completion\",\n\t\t\tsql: `\n\t\t\t\tALTER TABLE fabric_platform.action_invocations\n\t\t\t\t\tADD COLUMN pending_completion jsonb,\n\t\t\t\t\tADD COLUMN external_completion jsonb,\n\t\t\t\t\tADD COLUMN completion_due_at timestamptz;\n\t\t\t\tCREATE INDEX action_invocations_completion_due_idx\n\t\t\t\t\tON fabric_platform.action_invocations (completion_due_at)\n\t\t\t\t\tWHERE completion_due_at IS NOT NULL;\n\t\t\t`,\n\t\t}, {\n\t\t\tversion: 4,\n\t\t\tname: \"outbox_actor_disclosure\",\n\t\t\t// Nullable with no default, so rows written before this migration stay NULL and read back\n\t\t\t// as legacy. NOT VALID skips scanning existing rows; the check still applies to every\n\t\t\t// insert and update from here on.\n\t\t\tsql: `\n\t\t\t\tALTER TABLE fabric_platform.event_outbox\n\t\t\t\t\tADD COLUMN actor_disclosure text;\n\t\t\t\tALTER TABLE fabric_platform.event_outbox\n\t\t\t\t\tADD CONSTRAINT event_outbox_actor_disclosure_check\n\t\t\t\t\tCHECK (actor_disclosure IN ('included', 'suppressed')) NOT VALID;\n\t\t\t`,\n\t\t}, {\n\t\t\tversion: 5,\n\t\t\tname: \"outbox_requeue\",\n\t\t\tsql: `\n\t\t\t\tCREATE TABLE fabric_platform.event_outbox_requeues (\n\t\t\t\t\tid text PRIMARY KEY, outbox_id text NOT NULL,\n\t\t\t\t\ttenant_id text NOT NULL, space_id text NOT NULL, event_id text NOT NULL,\n\t\t\t\t\tactor_id text NOT NULL, actor_type text NOT NULL, reason text NOT NULL,\n\t\t\t\t\trequeued_at timestamptz NOT NULL, available_at timestamptz NOT NULL,\n\t\t\t\t\tprior_attempt_count integer NOT NULL, prior_last_error text,\n\t\t\t\t\tprior_available_at timestamptz NOT NULL, prior_lease_token bigint NOT NULL\n\t\t\t\t);\n\t\t\t\tCREATE INDEX event_outbox_requeues_record_idx\n\t\t\t\t\tON fabric_platform.event_outbox_requeues (tenant_id, space_id, outbox_id, requeued_at);\n\t\t\t`,\n\t\t}, {\n\t\t\tversion: 6,\n\t\t\tname: \"invocation_admission\",\n\t\t\t// Nullable with no default: rows written before this migration, and\n\t\t\t// rows of actions that declare no admission check, stay NULL.\n\t\t\tsql: `\n\t\t\t\tALTER TABLE fabric_platform.action_invocations\n\t\t\t\t\tADD COLUMN admitted_at timestamptz;\n\t\t\t`,\n\t\t}, {\n\t\t\tversion: 7,\n\t\t\tname: \"pending_state_transition\",\n\t\t\tsql: `\n\t\t\t\tALTER TABLE fabric_platform.action_invocations\n\t\t\t\t\tADD COLUMN IF NOT EXISTS pending_state_transition jsonb;\n\t\t\t`,\n\t\t}, {\n\t\t\tversion: 8,\n\t\t\tname: \"adapter_reconciliation_checkpoint\",\n\t\t\tsql: `\n\t\t\t\tALTER TABLE fabric_platform.adapter_invocations ADD COLUMN IF NOT EXISTS reconciliation jsonb;\n\t\t\t`,\n\t\t}]);\n\t}\n\n\tasync transaction<TResult>(run: (db: TDb) => Promise<TResult>): Promise<TResult> {\n\t\treturn run(this.db);\n\t}\n\n\tasync createActionInvocation(\n\t\tinput: CreateActionInvocationInput,\n\t): Promise<ActionInvocationRecord> {\n\t\tconst now = new Date();\n\t\t// `admitted_at` (migration 6) is named only for an admitted invocation,\n\t\t// so an invocation of an action without admitSubmission is written with\n\t\t// the same statement as before migration 6 and needs no new column.\n\t\tconst admitted = input.admittedAt !== undefined;\n\t\tconst admittedColumn = admitted ? \"admitted_at,\" : \"\";\n\t\tconst admittedValue = admitted ? \"$25,\" : \"\";\n\t\tlet result;\n\t\ttry {\n\t\t\tresult = await this.sql.query<Record<string, unknown>>(\n\t\t\t\t`INSERT INTO fabric_platform.action_invocations\n\t\t\t\t (id,tenant_id,space_id,action_id,action_version,actor_id,actor_type,status,\n\t\t\t\t\t parameters,result,correlation_id,causation_id,idempotency_key,\n\t\t\t\t\t parameter_digest,parameter_digest_algorithm,idempotency_actor_id,\n\t\t\t\t\t idempotency_authorization_binding_id,invocation_provenance,authorization_binding,execution_reason,\n\t\t\t\t\t authorization_binding_id,error,runtime_evidence,${admittedColumn}created_at,updated_at)\n\t\t\t\t\t VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9::jsonb,$10::jsonb,$11,$12,$13,$14,$15,$16,$17,$18::jsonb,$19::jsonb,$20,$21,$22,$23::jsonb,${admittedValue}$24,$24)\n\t\t\t\t ON CONFLICT (tenant_id,space_id,action_id,idempotency_key)\n\t\t\t\t WHERE idempotency_key IS NOT NULL DO UPDATE SET id=fabric_platform.action_invocations.id\n\t\t\t\t RETURNING *`,\n\t\t\t\t[\n\t\t\t\t\tinput.id, input.tenantId, input.spaceId, input.actionId, input.actionVersion,\n\t\t\t\t\tinput.actorId, input.actorType, input.status, JSON.stringify(input.parameters),\n\t\t\t\t\tJSON.stringify(input.result), input.correlationId, input.causationId ?? null,\n\t\t\t\t\tinput.idempotencyKey ?? null, input.parameterDigest ?? null,\n\t\t\t\t\tinput.parameterDigestAlgorithm ?? null, input.idempotencyActorId ?? null,\n\t\t\t\t\tinput.idempotencyAuthorizationBindingId ?? null,\n\t\t\t\t\tinput.provenance ? JSON.stringify(input.provenance) : null,\n\t\t\t\t\tinput.authorizationBinding ? JSON.stringify(input.authorizationBinding) : null,\n\t\t\t\t\tinput.executionReason ?? null, input.authorizationBindingId ?? null,\n\t\t\t\t\tinput.error ?? null, input.runtimeEvidence ? JSON.stringify(input.runtimeEvidence) : null, now,\n\t\t\t\t\t...(admitted ? [input.admittedAt] : []),\n\t\t\t\t],\n\t\t\t);\n\t\t} catch (error) {\n\t\t\t// 42703 undefined_column: the schema predates migration 6.\n\t\t\tif (admitted && (error as { code?: unknown } | null)?.code === \"42703\") {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"An admitted invocation needs the action_invocations.admitted_at column; run ensureSchema() to apply PostgreSQL migration 6 (invocation_admission) before submitting actions that declare admitSubmission.\",\n\t\t\t\t\t{ cause: error },\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t\treturn toActionRecord(result.rows[0]!);\n\t}\n\n\tasync getActionInvocation(id: string, tenantId: string, spaceId: string) {\n\t\tconst result = await this.sql.query<Record<string, unknown>>(\n\t\t\t`SELECT * FROM fabric_platform.action_invocations\n\t\t\t WHERE id=$1 AND tenant_id=$2 AND space_id=$3`,\n\t\t\t[id, tenantId, spaceId],\n\t\t);\n\t\treturn result.rows[0] ? toActionRecord(result.rows[0]) : undefined;\n\t}\n\n\tasync updateActionInvocation(\n\t\tid: string,\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t\tpatch: ActionInvocationPatch,\n\t): Promise<void> {\n\t\tawait this.sql.query(\n\t\t\t`UPDATE fabric_platform.action_invocations SET\n\t\t\t status=COALESCE($4,status), result=COALESCE($5::jsonb,result),\n\t\t\t error=CASE WHEN $6::boolean THEN $7 ELSE error END,\n\t\t\t authorization_reconciliation=CASE WHEN $8::boolean THEN $9::jsonb ELSE authorization_reconciliation END,\n\t\t\t adapter_reconciliation=CASE WHEN $10::boolean THEN $11::jsonb ELSE adapter_reconciliation END,\n\t\t\t pending_completion=CASE WHEN $12::boolean THEN $13::jsonb ELSE pending_completion END,\n\t\t\t completion_due_at=CASE WHEN $12::boolean THEN ($13::jsonb->>'dueAt')::timestamptz ELSE completion_due_at END,\n\t\t\t external_completion=CASE WHEN $14::boolean THEN $15::jsonb ELSE external_completion END,\n\t\t\t pending_state_transition=CASE WHEN $16::boolean THEN $17::jsonb ELSE pending_state_transition END,\n\t\t\t lease_owner=CASE WHEN ($13::jsonb IS NOT NULL AND $4='running') OR $4 IN ('waiting_for_approval','completed','failed','blocked_by_policy','reconciliation_required','validation_failed')\n\t\t\t THEN NULL ELSE lease_owner END,\n\t\t\t lease_expires_at=CASE WHEN ($13::jsonb IS NOT NULL AND $4='running') OR $4 IN ('waiting_for_approval','completed','failed','blocked_by_policy','reconciliation_required','validation_failed')\n\t\t\t THEN NULL ELSE lease_expires_at END,\n\t\t\t updated_at=now()\n\t\t\t WHERE id=$1 AND tenant_id=$2 AND space_id=$3`,\n\t\t\t[id, tenantId, spaceId, patch.status ?? null,\n\t\t\t patch.result === undefined ? null : JSON.stringify(patch.result),\n\t\t\t Object.hasOwn(patch, \"error\"), patch.error ?? null,\n\t\t\t Object.hasOwn(patch, \"authorizationReconciliation\"),\n\t\t\t patch.authorizationReconciliation ? JSON.stringify(patch.authorizationReconciliation) : null,\n\t\t\t Object.hasOwn(patch, \"adapterReconciliation\"),\n\t\t\t patch.adapterReconciliation ? JSON.stringify(patch.adapterReconciliation) : null,\n\t\t\t Object.hasOwn(patch, \"pendingCompletion\"),\n\t\t\t patch.pendingCompletion ? JSON.stringify(patch.pendingCompletion) : null,\n\t\t\t Object.hasOwn(patch, \"externalCompletion\"),\n\t\t\t patch.externalCompletion ? JSON.stringify(patch.externalCompletion) : null,\n\t\t\t Object.hasOwn(patch, \"pendingStateTransition\"),\n\t\t\t patch.pendingStateTransition ? JSON.stringify(patch.pendingStateTransition) : null],\n\t\t);\n\t}\n\n\tasync recordHitlDecision(\n\t\tactionInvocationId: string,\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t\tdecision: HitlDecisionEvidence,\n\t): Promise<ActionInvocationRecord> {\n\t\tconst result = await this.sql.query<Record<string, unknown>>(\n\t\t\t`UPDATE fabric_platform.action_invocations SET\n\t\t\t hitl_route=$4, hitl_risk_tier=$5, hitl_reason=$6,\n\t\t\t hitl_policy_version=$7, updated_at=$8\n\t\t\t WHERE id=$1 AND tenant_id=$2 AND space_id=$3\n\t\t\t RETURNING *`,\n\t\t\t[\n\t\t\t\tactionInvocationId,\n\t\t\t\ttenantId,\n\t\t\t\tspaceId,\n\t\t\t\tdecision.route,\n\t\t\t\tdecision.riskTier,\n\t\t\t\tdecision.reason,\n\t\t\t\tdecision.policyVersion ?? null,\n\t\t\t\tdecision.evaluatedAt,\n\t\t\t],\n\t\t);\n\t\tconst row = result.rows[0];\n\t\tif (!row) throw new Error(`ActionInvocation not found: ${actionInvocationId}`);\n\t\treturn toActionRecord(row);\n\t}\n\n\tasync beginApprovalDecision(\n\t\tinput: BeginApprovalDecisionInput,\n\t): Promise<ApprovalDecisionTransitionResult> {\n\t\tconst result = await this.sql.query<Record<string, unknown>>(\n\t\t\t`UPDATE fabric_platform.action_invocations SET\n\t\t\t approval_decision=$4::jsonb,\n\t\t\t status=CASE WHEN $5::boolean THEN 'running' ELSE 'failed' END,\n\t\t\t error=CASE WHEN $5::boolean THEN NULL ELSE $6 END,\n\t\t\t lease_owner=CASE WHEN $5::boolean THEN $7 ELSE NULL END,\n\t\t\t lease_expires_at=CASE WHEN $5::boolean THEN $8::timestamptz ELSE NULL END,\n\t\t\t lease_token=CASE WHEN $5::boolean THEN lease_token+1 ELSE lease_token END,\n\t\t\t attempt_count=CASE WHEN $5::boolean THEN GREATEST(attempt_count,1) ELSE attempt_count END,\n\t\t\t updated_at=$9\n\t\t\t WHERE id=$1 AND tenant_id=$2 AND space_id=$3 AND status='waiting_for_approval'\n\t\t\t RETURNING *`,\n\t\t\t[\n\t\t\t\tinput.actionInvocationId,\n\t\t\t\tinput.tenantId,\n\t\t\t\tinput.spaceId,\n\t\t\t\tJSON.stringify({ ...input.decision, decidedAt: input.decision.decidedAt.toISOString() }),\n\t\t\t\tinput.decision.approved,\n\t\t\t\t`Approval rejected: ${input.decision.reason ?? \"no reason provided\"}`,\n\t\t\t\tinput.leaseOwner,\n\t\t\t\tnew Date(input.now.getTime() + input.leaseDurationMs),\n\t\t\t\tinput.now,\n\t\t\t],\n\t\t);\n\t\treturn result.rows[0]\n\t\t\t? { applied: true, invocation: toActionRecord(result.rows[0]) }\n\t\t\t: { applied: false };\n\t}\n\n\tasync appendPolicyEvaluation(record: PolicyEvaluationRecord): Promise<void> {\n\t\tawait this.sql.query(\n\t\t\t`INSERT INTO fabric_platform.policy_evaluations\n\t\t\t (id,action_invocation_id,tenant_id,space_id,outcome,created_at)\n\t\t\t VALUES ($1,$2,$3,$4,$5::jsonb,$6) ON CONFLICT (id) DO NOTHING`,\n\t\t\t[record.id, record.actionInvocationId, record.tenantId, record.spaceId,\n\t\t\t JSON.stringify(record.outcome), record.createdAt],\n\t\t);\n\t}\n\n\tasync recordMutationGovernance(actionInvocationId: string, tenantId: string, spaceId: string, context: { footprint: NonNullable<ActionInvocationRecord[\"mutationFootprint\"]>; executionPrincipal: NonNullable<ActionInvocationRecord[\"executionPrincipal\"]> }): Promise<ActionInvocationRecord> {\n\t\tconst result = await this.sql.query<Record<string, unknown>>(\n\t\t\t`UPDATE fabric_platform.action_invocations SET mutation_footprint=$4::jsonb,\n\t\t\t execution_principal=$5::jsonb, updated_at=now()\n\t\t\t WHERE id=$1 AND tenant_id=$2 AND space_id=$3 RETURNING *`,\n\t\t\t[actionInvocationId, tenantId, spaceId, JSON.stringify(context.footprint), JSON.stringify(context.executionPrincipal)],\n\t\t);\n\t\tif (!result.rows[0]) throw new Error(`ActionInvocation not found: ${actionInvocationId}`);\n\t\treturn toActionRecord(result.rows[0]);\n\t}\n\n\tasync appendPolicyObligations(records: PolicyObligationRecord[]): Promise<void> {\n\t\tfor (const record of records) {\n\t\t\tawait this.sql.query(\n\t\t\t\t`INSERT INTO fabric_platform.policy_obligations\n\t\t\t\t (action_invocation_id,id,tenant_id,space_id,type,status,required,description,evidence_references,metadata,created_at,updated_at)\n\t\t\t\t VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9::jsonb,$10::jsonb,$11,$12)\n\t\t\t\t ON CONFLICT (action_invocation_id,id) DO NOTHING`,\n\t\t\t\t[record.actionInvocationId, record.id, record.tenantId, record.spaceId, record.type, record.status,\n\t\t\t\t record.required ?? true, record.description ?? null,\n\t\t\t\t record.evidenceReferences ? JSON.stringify(record.evidenceReferences) : null,\n\t\t\t\t record.metadata ? JSON.stringify(record.metadata) : null, record.createdAt, record.updatedAt],\n\t\t\t);\n\t\t}\n\t}\n\n\tasync listPolicyObligations(actionInvocationId: string, tenantId: string, spaceId: string): Promise<PolicyObligationRecord[]> {\n\t\tconst result = await this.sql.query<Record<string, unknown>>(\n\t\t\t`SELECT * FROM fabric_platform.policy_obligations WHERE action_invocation_id=$1 AND tenant_id=$2 AND space_id=$3 ORDER BY created_at,id`,\n\t\t\t[actionInvocationId, tenantId, spaceId],\n\t\t);\n\t\treturn result.rows.map(toObligationRecord);\n\t}\n\n\tasync updatePolicyObligation(actionInvocationId: string, obligationId: string, status: PolicyObligationRecord[\"status\"], evidenceReferences?: PolicyObligationRecord[\"evidenceReferences\"]): Promise<void> {\n\t\tawait this.sql.query(\n\t\t\t`UPDATE fabric_platform.policy_obligations SET status=$3,\n\t\t\t evidence_references=COALESCE($4::jsonb,evidence_references), updated_at=now()\n\t\t\t WHERE action_invocation_id=$1 AND id=$2`,\n\t\t\t[actionInvocationId, obligationId, status, evidenceReferences ? JSON.stringify(evidenceReferences) : null],\n\t\t);\n\t}\n\n\tasync appendExecutionAttestation(record: ExecutionAttestationRecord): Promise<void> {\n\t\tconst { id, actionInvocationId, tenantId, spaceId, adapterInvocationId, recordedAt, ...attestation } = record;\n\t\tawait this.sql.query(\n\t\t\t`INSERT INTO fabric_platform.execution_attestations\n\t\t\t (id,action_invocation_id,tenant_id,space_id,adapter_invocation_id,attestation,recorded_at)\n\t\t\t VALUES ($1,$2,$3,$4,$5,$6::jsonb,$7) ON CONFLICT (id) DO NOTHING`,\n\t\t\t[id, actionInvocationId, tenantId, spaceId, adapterInvocationId ?? null, JSON.stringify(attestation), recordedAt],\n\t\t);\n\t}\n\n\tasync listExecutionAttestations(actionInvocationId: string, tenantId: string, spaceId: string): Promise<ExecutionAttestationRecord[]> {\n\t\tconst result = await this.sql.query<Record<string, unknown>>(\n\t\t\t`SELECT * FROM fabric_platform.execution_attestations WHERE action_invocation_id=$1 AND tenant_id=$2 AND space_id=$3 ORDER BY recorded_at,id`,\n\t\t\t[actionInvocationId, tenantId, spaceId],\n\t\t);\n\t\treturn result.rows.map(toAttestationRecord);\n\t}\n\n\tasync appendExternalReconciliation(record: ExternalReconciliationRecord): Promise<void> {\n\t\tconst { id, actionInvocationId, tenantId, spaceId, ...reconciliation } = record;\n\t\tawait this.sql.query(\n\t\t\t`INSERT INTO fabric_platform.external_reconciliations\n\t\t\t (id,action_invocation_id,tenant_id,space_id,reconciliation)\n\t\t\t VALUES ($1,$2,$3,$4,$5::jsonb) ON CONFLICT (id) DO NOTHING`,\n\t\t\t[id, actionInvocationId, tenantId, spaceId, JSON.stringify(reconciliation)],\n\t\t);\n\t}\n\n\tasync updateSettledActionInvocation(input: import(\"./types\").UpdateSettledActionInvocationInput): Promise<boolean> {\n\t\tconst { condition, patch } = input;\n\t\tif ([\"pending\", \"running\", \"waiting_for_approval\"].includes(condition.status)) return false;\n\t\tconst result = await this.sql.query(\n\t\t\t`UPDATE fabric_platform.action_invocations SET\n\t\t\t error=CASE WHEN $7::boolean THEN $8 ELSE error END,\n\t\t\t adapter_reconciliation=CASE WHEN $9::boolean THEN $10::jsonb ELSE adapter_reconciliation END,\n\t\t\t updated_at=now()\n\t\t\t WHERE id=$1 AND tenant_id=$2 AND space_id=$3 AND status=$4\n\t\t\t AND error IS NOT DISTINCT FROM $5::text\n\t\t\t AND ((external_completion IS NULL AND $6::text IS NULL)\n\t\t\t OR ($6::text IS NOT NULL AND external_completion->>'digest'=$6)) RETURNING id`,\n\t\t\t[input.id, input.tenantId, input.spaceId, condition.status, condition.error ?? null,\n\t\t\t condition.externalCompletionDigest ?? null, Object.hasOwn(patch, \"error\"), patch.error ?? null,\n\t\t\t Object.hasOwn(patch, \"adapterReconciliation\"), patch.adapterReconciliation === undefined ? null : JSON.stringify(patch.adapterReconciliation)],\n\t\t);\n\t\treturn result.rows.length === 1;\n\t}\n\n\tasync writeAdapterInvocation(input: AdapterInvocationWriteInput): Promise<boolean> {\n\t\tconst { scope, condition, mutation } = input;\n\t\tif (condition.kind === \"verdict\" && [\"pending\", \"running\", \"waiting_for_approval\"].includes(condition.status)) return false;\n\t\t// FOR UPDATE precedes the child mutation. READ COMMITTED re-evaluates the\n\t\t// predicate on a parent changed by a claimant while this lock waited.\n\t\tconst values: unknown[] = [scope.actionInvocationId, scope.tenantId, scope.spaceId];\n\t\tconst checkCompletion = condition.kind === \"verdict\" && (condition.completionAdapterInvocationId === undefined\n\t\t\t|| condition.completionAdapterInvocationId === (mutation.kind === \"create\" ? mutation.record.id : mutation.id));\n\t\tconst authority = condition.kind === \"lease\"\n\t\t\t? \"status='running' AND lease_owner=$4 AND lease_token=$5\"\n\t\t\t: \"status=$4 AND error IS NOT DISTINCT FROM $5::text\"\n\t\t\t\t+ (checkCompletion ? \" AND ((external_completion IS NULL AND $DIGEST::text IS NULL) OR ($DIGEST::text IS NOT NULL AND external_completion->>'digest'=$DIGEST))\" : \"\");\n\t\tvalues.push(...(condition.kind === \"lease\" ? [condition.leaseOwner, condition.leaseToken] : [condition.status, condition.error ?? null]));\n\t\tconst parent = `WITH parent AS MATERIALIZED (\n\t\t\tSELECT id FROM fabric_platform.action_invocations\n\t\t\tWHERE id=$1 AND tenant_id=$2 AND space_id=$3 AND ${authority} FOR UPDATE\n\t\t)`;\n\t\tlet sql: string;\n\t\tif (mutation.kind === \"create\") {\n\t\t\tconst row = mutation.record;\n\t\t\tif (row.actionInvocationId !== scope.actionInvocationId || row.tenantId !== scope.tenantId || row.spaceId !== scope.spaceId) return false;\n\t\t\tconst hasReconciliation = row.reconciliation !== undefined;\n\t\t\tsql = `${parent} INSERT INTO fabric_platform.adapter_invocations\n\t\t\t\t(id,action_invocation_id,tenant_id,space_id,adapter_type,operation,vendor,status,input,output,error,attempt,created_at,updated_at${hasReconciliation ? \",reconciliation\" : \"\"})\n\t\t\t\tSELECT $6,parent.id,$2,$3,$7,$8,$9,$10,$11::jsonb,$12::jsonb,$13,$14,$15,$16${hasReconciliation ? \",$17::jsonb\" : \"\"} FROM parent\n\t\t\t\tON CONFLICT (id) DO NOTHING RETURNING id`;\n\t\t\tvalues.push(row.id, row.adapterType, row.operation, row.vendor, row.status, JSON.stringify(row.input),\n\t\t\t\trow.output === undefined ? null : JSON.stringify(row.output), row.error ?? null, row.attempt, row.createdAt, row.updatedAt,\n\t\t\t\t...(hasReconciliation ? [JSON.stringify(row.reconciliation)] : []));\n\t\t} else {\n\t\t\tconst { patch } = mutation;\n\t\t\tconst hasReconciliation = patch.reconciliation !== undefined;\n\t\t\tsql = `${parent} UPDATE fabric_platform.adapter_invocations AS adapter SET\n\t\t\t\tstatus=COALESCE($7,status),output=COALESCE($8::jsonb,output),\n\t\t\t\terror=CASE WHEN $9::boolean THEN $10 ELSE error END,\n\t\t\t\tattempt=COALESCE($11,attempt),updated_at=COALESCE($12,now())${hasReconciliation ? \",reconciliation=COALESCE($14::jsonb,reconciliation)\" : \"\"}\n\t\t\t\tFROM parent WHERE adapter.id=$6 AND adapter.action_invocation_id=parent.id AND adapter.tenant_id=$2 AND adapter.space_id=$3\n\t\t\t\tAND ($13::text[] IS NULL OR adapter.status=ANY($13::text[]))\n\t\t\t\tAND NOT (adapter.status IN ('succeeded','ambiguous') AND COALESCE($7,adapter.status) IN ('running','failed'))\n\t\t\t\tRETURNING adapter.id`;\n\t\t\tvalues.push(mutation.id, patch.status ?? null, patch.output === undefined ? null : JSON.stringify(patch.output),\n\t\t\t\tObject.hasOwn(patch, \"error\"), patch.error ?? null, patch.attempt ?? null, patch.updatedAt ?? null,\n\t\t\t\tinput.expectedStatuses ?? null, ...(hasReconciliation ? [JSON.stringify(patch.reconciliation)] : []));\n\t\t}\n\t\tif (condition.kind === \"verdict\" && checkCompletion) {\n\t\t\tvalues.push(condition.externalCompletionDigest ?? null);\n\t\t\tsql = sql.replaceAll(\"$DIGEST\", () => `$${values.length}`);\n\t\t}\n\t\treturn (await this.sql.query(sql, values)).rows.length === 1;\n\t}\n\n\tasync createAdapterInvocation(record: AdapterInvocationRecord): Promise<void> {\n\t\tconst hasReconciliation = record.reconciliation !== undefined;\n\t\tawait this.sql.query(\n\t\t\t`INSERT INTO fabric_platform.adapter_invocations\n\t\t\t (id,action_invocation_id,tenant_id,space_id,adapter_type,operation,vendor,status,\n\t\t\t input,output,error,attempt,created_at,updated_at${hasReconciliation ? \",reconciliation\" : \"\"})\n\t\t\t VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9::jsonb,$10::jsonb,$11,$12,$13,$14${hasReconciliation ? \",$15::jsonb\" : \"\"})\n\t\t\t ON CONFLICT (id) DO NOTHING`,\n\t\t\t[record.id, record.actionInvocationId, record.tenantId, record.spaceId,\n\t\t\t record.adapterType, record.operation, record.vendor, record.status,\n\t\t\t JSON.stringify(record.input), record.output ? JSON.stringify(record.output) : null,\n\t\t\t record.error ?? null, record.attempt, record.createdAt, record.updatedAt,\n\t\t\t ...(hasReconciliation ? [JSON.stringify(record.reconciliation)] : [])],\n\t\t);\n\t}\n\n\tasync getAdapterInvocation(id: string, scope?: AdapterInvocationScope): Promise<AdapterInvocationRecord | undefined> {\n\t\tconst result = await this.sql.query<Record<string, unknown>>(\n\t\t\t`SELECT * FROM fabric_platform.adapter_invocations WHERE id=$1${scope ? \" AND tenant_id=$2 AND space_id=$3 AND action_invocation_id=$4\" : \"\"}`,\n\t\t\t[id, ...(scope ? [scope.tenantId, scope.spaceId, scope.actionInvocationId] : [])],\n\t\t);\n\t\treturn result.rows[0] ? toAdapterRecord(result.rows[0]) : undefined;\n\t}\n\n\tasync updateAdapterInvocation(\n\t\tid: string,\n\t\tpatch: Partial<\n\t\t\tPick<AdapterInvocationRecord, \"status\" | \"output\" | \"error\" | \"attempt\" | \"updatedAt\" | \"reconciliation\">\n\t\t>,\n\t\tscope?: AdapterInvocationScope,\n\t): Promise<void> {\n\t\tconst hasReconciliation = patch.reconciliation !== undefined;\n\t\tawait this.sql.query(\n\t\t\t`UPDATE fabric_platform.adapter_invocations SET\n\t\t\t status=COALESCE($2,status), output=COALESCE($3::jsonb,output),\n\t\t\t error=CASE WHEN $4::boolean THEN $5 ELSE error END,\n\t\t\t attempt=COALESCE($6,attempt), updated_at=COALESCE($7,now())${hasReconciliation ? `,\n\t\t\t reconciliation=COALESCE($${scope ? 11 : 8}::jsonb,reconciliation)` : \"\"} WHERE id=$1${scope ? \" AND tenant_id=$8 AND space_id=$9 AND action_invocation_id=$10\" : \"\"}`,\n\t\t\t[id, patch.status ?? null,\n\t\t\t patch.output === undefined ? null : JSON.stringify(patch.output),\n\t\t\t Object.hasOwn(patch, \"error\"), patch.error ?? null, patch.attempt ?? null,\n\t\t\t patch.updatedAt ?? null, ...(scope ? [scope.tenantId, scope.spaceId, scope.actionInvocationId] : []),\n\t\t\t ...(hasReconciliation ? [JSON.stringify(patch.reconciliation)] : [])],\n\t\t);\n\t}\n\n\tasync appendEvent(event: AssetEventEnvelope): Promise<void> {\n\t\tawait this.sql.query(\n\t\t\t`INSERT INTO fabric_platform.asset_events\n\t\t\t (id,tenant_id,space_id,event_type,event_schema_version,subject_type,subject_id,\n\t\t\t actor_id,actor_type,action_invocation_id,payload,sequence,occurred_at,recorded_at,\n\t\t\t correlation_id,causation_id,provenance,consistency)\n\t\t\t\t VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11::jsonb,$12,$13,$14,$15,$16,$17::jsonb,$18)\n\t\t\t\t ON CONFLICT (id) DO NOTHING`,\n\t\t\t[event.id, event.tenantId, event.spaceId, event.eventType, event.eventSchemaVersion,\n\t\t\t event.subjectType, event.subjectId, event.actorId, event.actorType,\n\t\t\t event.actionInvocationId ?? null, JSON.stringify(event.payload), event.sequence,\n\t\t\t event.occurredAt, event.recordedAt, event.correlationId, event.causationId ?? null,\n\t\t\t event.provenance ? JSON.stringify(event.provenance) : null, event.consistency ?? null],\n\t\t);\n\t}\n\n\tasync appendEventWithOutbox(event: AssetEventEnvelope, metadata: OutboxEventMetadata): Promise<void> {\n\t\tconst envelope = toEnterpriseEventEnvelope(event, metadata);\n\t\tawait this.sql.query(\n\t\t\t`WITH inserted_event AS (\n\t\t\t\tINSERT INTO fabric_platform.asset_events\n\t\t\t\t (id,tenant_id,space_id,event_type,event_schema_version,subject_type,subject_id,\n\t\t\t\t actor_id,actor_type,action_invocation_id,payload,sequence,occurred_at,recorded_at,\n\t\t\t\t correlation_id,causation_id,provenance,consistency)\n\t\t\t\t VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11::jsonb,$12,$13,$14,$15,$16,$17::jsonb,$19)\n\t\t\t\t ON CONFLICT (id) DO NOTHING RETURNING id\n\t\t\t)\n\t\t\tINSERT INTO fabric_platform.event_outbox\n\t\t\t (id,tenant_id,space_id,event,actor_disclosure,status,attempt_count,available_at,created_at)\n\t\t\tSELECT $1,$2,$3,$18::jsonb,$20,'pending',0,$14,$14 FROM inserted_event\n\t\t\tON CONFLICT (id) DO NOTHING`,\n\t\t\t[event.id, event.tenantId, event.spaceId, event.eventType, event.eventSchemaVersion,\n\t\t\t event.subjectType, event.subjectId, event.actorId, event.actorType,\n\t\t\t event.actionInvocationId ?? null, JSON.stringify(event.payload), event.sequence,\n\t\t\t event.occurredAt, event.recordedAt, event.correlationId, event.causationId ?? null,\n\t\t\t event.provenance ? JSON.stringify(event.provenance) : null, JSON.stringify(envelope), event.consistency ?? null,\n\t\t\t outboxActorDisclosure(metadata)],\n\t\t);\n\t}\n\n\tasync claimOutbox(input: ClaimOutboxInput): Promise<OutboxRecord[]> {\n\t\tconst current = input.now ?? new Date();\n\t\tconst leaseExpiresAt = new Date(current.getTime() + input.leaseDurationMs);\n\t\tconst result = await this.sql.query<Record<string, unknown>>(\n\t\t\t`WITH claimable AS (\n\t\t\t\tSELECT id FROM fabric_platform.event_outbox\n\t\t\t\tWHERE status='pending' AND available_at <= $1\n\t\t\t\t AND (lease_expires_at IS NULL OR lease_expires_at <= $1)\n\t\t\t\t AND ($2::text IS NULL OR tenant_id=$2)\n\t\t\t\t AND ($3::text IS NULL OR space_id=$3)\n\t\t\t\tORDER BY created_at,id FOR UPDATE SKIP LOCKED LIMIT $4\n\t\t\t)\n\t\t\tUPDATE fabric_platform.event_outbox AS item\n\t\t\tSET lease_owner=$5, lease_expires_at=$6, lease_token=lease_token+1,\n\t\t\t attempt_count=attempt_count+1\n\t\t\tFROM claimable WHERE item.id=claimable.id RETURNING item.*`,\n\t\t\t[current, input.tenantId ?? null, input.spaceId ?? null, Math.max(1, Math.min(input.limit ?? 100, 1_000)), input.workerId, leaseExpiresAt],\n\t\t);\n\t\treturn result.rows.map(toOutboxRecord);\n\t}\n\n\tasync markOutboxPublished(id: string, workerId: string, publishedAt: Date, leaseToken?: number): Promise<void> {\n\t\tconst result = await this.sql.query(\n\t\t\t`UPDATE fabric_platform.event_outbox SET status='published',published_at=$3,\n\t\t\t lease_owner=NULL,lease_expires_at=NULL\n\t\t\t WHERE id=$1 AND lease_owner=$2 AND lease_token=COALESCE($4,0) RETURNING id`,\n\t\t\t[id, workerId, publishedAt, leaseToken ?? null],\n\t\t);\n\t\tif (result.rows.length === 0) throw new Error(`Outbox record ${id} is not leased by ${workerId}.`);\n\t}\n\n\tasync markOutboxFailed(input: { id: string; workerId: string; leaseToken?: number; error: string; availableAt: Date; deadLetter: boolean }): Promise<void> {\n\t\tconst result = await this.sql.query(\n\t\t\t`UPDATE fabric_platform.event_outbox SET status=$3,last_error=$4,available_at=$5,\n\t\t\t lease_owner=NULL,lease_expires_at=NULL\n\t\t\t WHERE id=$1 AND lease_owner=$2 AND lease_token=COALESCE($6,0) RETURNING id`,\n\t\t\t[input.id, input.workerId, input.deadLetter ? \"dead_letter\" : \"pending\", input.error, input.availableAt, input.leaseToken ?? null],\n\t\t);\n\t\tif (result.rows.length === 0) throw new Error(`Outbox record ${input.id} is not leased by ${input.workerId}.`);\n\t}\n\n\tasync renewOutboxLease(input: { id: string; workerId: string; leaseToken: number; leaseDurationMs: number; now?: Date }): Promise<boolean> {\n\t\tconst current = input.now ?? new Date();\n\t\tconst result = await this.sql.query(\n\t\t\t`UPDATE fabric_platform.event_outbox SET lease_expires_at=$5\n\t\t\t WHERE id=$1 AND status='pending' AND lease_owner=$2 AND lease_token=$3\n\t\t\t AND lease_expires_at > $4\n\t\t\t RETURNING id`,\n\t\t\t[input.id, input.workerId, input.leaseToken,\n\t\t\t\tcurrent, new Date(current.getTime() + input.leaseDurationMs)],\n\t\t);\n\t\treturn result.rows.length === 1;\n\t}\n\n\tasync listOutbox(input: { tenantId?: string; spaceId?: string; statuses?: OutboxStatus[] } = {}): Promise<OutboxRecord[]> {\n\t\tconst result = await this.sql.query<Record<string, unknown>>(\n\t\t\t`SELECT * FROM fabric_platform.event_outbox\n\t\t\t WHERE ($1::text IS NULL OR tenant_id=$1) AND ($2::text IS NULL OR space_id=$2)\n\t\t\t AND ($3::text[] IS NULL OR status=ANY($3::text[])) ORDER BY created_at,id`,\n\t\t\t[input.tenantId ?? null, input.spaceId ?? null, input.statuses?.length ? input.statuses : null],\n\t\t);\n\t\treturn result.rows.map(toOutboxRecord);\n\t}\n\n\tasync getOutboxRecord(id: string, tenantId: string, spaceId: string): Promise<OutboxRecord | undefined> {\n\t\tconst result = await this.sql.query<Record<string, unknown>>(\n\t\t\t`SELECT * FROM fabric_platform.event_outbox\n\t\t\t WHERE id=$1 AND tenant_id=$2 AND space_id=$3`,\n\t\t\t[id, tenantId, spaceId],\n\t\t);\n\t\treturn result.rows[0] ? toOutboxRecord(result.rows[0]) : undefined;\n\t}\n\n\tasync requeueOutboxDeadLetter(input: RequeueOutboxDeadLetterStoreInput): Promise<RequeueOutboxDeadLetterStoreResult> {\n\t\t// One statement, so the transition and its evidence commit together. The\n\t\t// row lock re-reads status and lease token after a concurrent writer\n\t\t// commits, so of two racing requeues exactly one sees the dead letter it\n\t\t// was authorized for; the other writes nothing. Every claim increments\n\t\t// lease_token, so a record dead-lettered again since the caller read it\n\t\t// no longer matches.\n\t\tconst result = await this.sql.query<Record<string, unknown>>(\n\t\t\t`WITH prior AS (\n\t\t\t\tSELECT id, tenant_id, space_id, event->>'eventId' AS event_id,\n\t\t\t\t attempt_count, last_error, available_at, lease_token\n\t\t\t\tFROM fabric_platform.event_outbox\n\t\t\t\tWHERE id=$1 AND tenant_id=$2 AND space_id=$3 AND status='dead_letter'\n\t\t\t\t AND lease_token=$10\n\t\t\t\tFOR UPDATE\n\t\t\t), requeued AS (\n\t\t\t\tUPDATE fabric_platform.event_outbox AS item\n\t\t\t\tSET status='pending', attempt_count=0, available_at=$9,\n\t\t\t\t lease_owner=NULL, lease_expires_at=NULL\n\t\t\t\tFROM prior WHERE item.id=prior.id\n\t\t\t\tRETURNING item.*\n\t\t\t), evidence AS (\n\t\t\t\tINSERT INTO fabric_platform.event_outbox_requeues\n\t\t\t\t (id,outbox_id,tenant_id,space_id,event_id,actor_id,actor_type,reason,\n\t\t\t\t requeued_at,available_at,prior_attempt_count,prior_last_error,\n\t\t\t\t prior_available_at,prior_lease_token)\n\t\t\t\tSELECT $4,prior.id,prior.tenant_id,prior.space_id,prior.event_id,$5,$6,$7,\n\t\t\t\t $8,$9,prior.attempt_count,prior.last_error,prior.available_at,prior.lease_token\n\t\t\t\tFROM prior JOIN requeued ON requeued.id=prior.id\n\t\t\t\tRETURNING *\n\t\t\t)\n\t\t\tSELECT requeued.*,\n\t\t\t evidence.id AS requeue_id, evidence.outbox_id AS requeue_outbox_id,\n\t\t\t evidence.tenant_id AS requeue_tenant_id, evidence.space_id AS requeue_space_id,\n\t\t\t evidence.event_id AS requeue_event_id, evidence.actor_id AS requeue_actor_id,\n\t\t\t evidence.actor_type AS requeue_actor_type, evidence.reason AS requeue_reason,\n\t\t\t evidence.requeued_at AS requeue_requeued_at, evidence.available_at AS requeue_available_at,\n\t\t\t evidence.prior_attempt_count AS requeue_prior_attempt_count,\n\t\t\t evidence.prior_last_error AS requeue_prior_last_error,\n\t\t\t evidence.prior_available_at AS requeue_prior_available_at,\n\t\t\t evidence.prior_lease_token AS requeue_prior_lease_token\n\t\t\tFROM requeued JOIN evidence ON evidence.outbox_id=requeued.id`,\n\t\t\t[input.id, input.tenantId, input.spaceId, input.requeueId, input.actorId,\n\t\t\t input.actorType, input.reason, input.requeuedAt, input.availableAt, input.expectedLeaseToken],\n\t\t);\n\t\tconst row = result.rows[0];\n\t\tif (row) {\n\t\t\treturn {\n\t\t\t\tapplied: true,\n\t\t\t\trecord: toOutboxRecord(row),\n\t\t\t\trequeue: toOutboxRequeueRecord(row, \"requeue_\"),\n\t\t\t};\n\t\t}\n\t\tconst current = await this.sql.query<{ status: string }>(\n\t\t\t`SELECT status FROM fabric_platform.event_outbox\n\t\t\t WHERE id=$1 AND tenant_id=$2 AND space_id=$3`,\n\t\t\t[input.id, input.tenantId, input.spaceId],\n\t\t);\n\t\tconst found = current.rows[0];\n\t\tif (!found) return { applied: false, refusal: \"not_found\" };\n\t\tconst status = found.status as OutboxStatus;\n\t\t// The statement refused, yet the row is a dead letter: it is a later\n\t\t// generation, since a record only returns to dead_letter through a claim\n\t\t// and every claim moves the lease token past the one the caller read.\n\t\treturn status === \"dead_letter\"\n\t\t\t? { applied: false, refusal: \"stale\", currentStatus: status }\n\t\t\t: { applied: false, refusal: \"not_dead_letter\", currentStatus: status };\n\t}\n\n\tasync listOutboxRequeues(input: { tenantId: string; spaceId: string; outboxId?: string }): Promise<OutboxRequeueRecord[]> {\n\t\tconst result = await this.sql.query<Record<string, unknown>>(\n\t\t\t`SELECT * FROM fabric_platform.event_outbox_requeues\n\t\t\t WHERE tenant_id=$1 AND space_id=$2 AND ($3::text IS NULL OR outbox_id=$3)\n\t\t\t ORDER BY requeued_at,id`,\n\t\t\t[input.tenantId, input.spaceId, input.outboxId ?? null],\n\t\t);\n\t\treturn result.rows.map((row) => toOutboxRequeueRecord(row, \"\"));\n\t}\n\n\tasync nextEventSequence(tenantId: string, spaceId: string): Promise<number> {\n\t\tconst result = await this.sql.query<{ next_sequence: string | number }>(\n\t\t\t`INSERT INTO fabric_platform.event_sequences (tenant_id,space_id,next_sequence)\n\t\t\t VALUES ($1,$2,1) ON CONFLICT (tenant_id,space_id) DO UPDATE\n\t\t\t SET next_sequence=fabric_platform.event_sequences.next_sequence+1\n\t\t\t RETURNING next_sequence`,\n\t\t\t[tenantId, spaceId],\n\t\t);\n\t\treturn Number(result.rows[0]!.next_sequence);\n\t}\n\n\tasync getEntityStateSource(\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t\tentityType: string,\n\t\tentityId: string,\n\t): Promise<{ state: string; actionInvocationId: string } | undefined> {\n\t\tconst result = await this.sql.query<{ state?: string; action_invocation_id?: string }>(\n\t\t\t`SELECT payload->>'toState' AS state, action_invocation_id FROM fabric_platform.asset_events\n\t\t\t WHERE tenant_id=$1 AND space_id=$2 AND subject_type=$3 AND subject_id=$4\n\t\t\t AND payload ? 'toState' ORDER BY sequence DESC LIMIT 1`,\n\t\t\t[tenantId, spaceId, entityType, entityId],\n\t\t);\n\t\tconst row = result.rows[0];\n\t\treturn typeof row?.state === \"string\" && typeof row.action_invocation_id === \"string\"\n\t\t\t? { state: row.state, actionInvocationId: row.action_invocation_id } : undefined;\n\t}\n\n\tasync getEntityState(\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t\tentityType: string,\n\t\tentityId: string,\n\t) {\n\t\tconst result = await this.sql.query<{ state?: string }>(\n\t\t\t`SELECT payload->>'toState' AS state FROM fabric_platform.asset_events\n\t\t\t WHERE tenant_id=$1 AND space_id=$2 AND subject_type=$3 AND subject_id=$4\n\t\t\t AND payload ? 'toState' ORDER BY sequence DESC LIMIT 1`,\n\t\t\t[tenantId, spaceId, entityType, entityId],\n\t\t);\n\t\treturn result.rows[0]?.state;\n\t}\n\n\tasync listActionInvocations(\n\t\tinput: ListActionInvocationsInput = {},\n\t): Promise<ActionInvocationRecord[]> {\n\t\tconst conditions: string[] = [];\n\t\tconst values: unknown[] = [];\n\t\tconst add = (condition: string, value: unknown) => {\n\t\t\tvalues.push(value);\n\t\t\tconditions.push(condition.replace(\"?\", `$${values.length}`));\n\t\t};\n\t\tif (input.tenantId) add(\"tenant_id=?\", input.tenantId);\n\t\tif (input.spaceId) add(\"space_id=?\", input.spaceId);\n\t\tif (input.statuses?.length) add(\"status = ANY(?::text[])\", [...input.statuses]);\n\t\tif (input.updatedBefore) add(\"updated_at<?\", input.updatedBefore);\n\t\tif (input.awaitingCompletion || input.completionDueBefore) conditions.push(\"pending_completion IS NOT NULL\");\n\t\tif (input.completionDueBefore) add(\"completion_due_at <= ?\", input.completionDueBefore);\n\t\tif (input.unleased) conditions.push(\"lease_owner IS NULL\");\n\t\tvalues.push(Math.max(1, Math.min(input.limit ?? 100, 1_000)));\n\t\tconst where = conditions.length ? `WHERE ${conditions.join(\" AND \")}` : \"\";\n\t\tconst result = await this.sql.query<Record<string, unknown>>(\n\t\t\t`SELECT * FROM fabric_platform.action_invocations ${where}\n\t\t\t ORDER BY created_at LIMIT $${values.length}`,\n\t\t\tvalues,\n\t\t);\n\t\treturn result.rows.map(toActionRecord);\n\t}\n\n\tasync getHealthCounts(input: PlatformHostHealthQuery): Promise<PlatformHostHealthCounts> {\n\t\tconst result = await this.sql.query<Record<string, string | number>>(\n\t\t\t`SELECT\n\t\t\t\t(SELECT COUNT(*) FROM fabric_platform.action_invocations\n\t\t\t\t WHERE status='pending'\n\t\t\t\t AND ($1::text IS NULL OR tenant_id=$1)\n\t\t\t\t AND ($2::text IS NULL OR space_id=$2)) AS invocation_backlog,\n\t\t\t\t(SELECT COUNT(*) FROM fabric_platform.action_invocations\n\t\t\t\t WHERE status='running'\n\t\t\t\t AND ($1::text IS NULL OR tenant_id=$1)\n\t\t\t\t AND ($2::text IS NULL OR space_id=$2)) AS invocation_running,\n\t\t\t\t(SELECT COUNT(*) FROM fabric_platform.action_invocations\n\t\t\t\t WHERE status='running' AND lease_expires_at IS NOT NULL AND lease_expires_at <= $3\n\t\t\t\t AND ($1::text IS NULL OR tenant_id=$1)\n\t\t\t\t AND ($2::text IS NULL OR space_id=$2)) AS invocation_expired_leases,\n\t\t\t\t(SELECT COUNT(*) FROM fabric_platform.action_invocations\n\t\t\t\t WHERE status='waiting_for_approval'\n\t\t\t\t AND ($1::text IS NULL OR tenant_id=$1)\n\t\t\t\t AND ($2::text IS NULL OR space_id=$2)) AS invocation_approval_waits,\n\t\t\t\t(SELECT COUNT(*) FROM fabric_platform.action_invocations\n\t\t\t\t WHERE status='reconciliation_required'\n\t\t\t\t AND ($1::text IS NULL OR tenant_id=$1)\n\t\t\t\t AND ($2::text IS NULL OR space_id=$2)) AS invocation_reconciliation_required,\n\t\t\t\t(SELECT COUNT(*) FROM fabric_platform.event_outbox\n\t\t\t\t WHERE status='pending'\n\t\t\t\t AND ($1::text IS NULL OR tenant_id=$1)\n\t\t\t\t AND ($2::text IS NULL OR space_id=$2)) AS outbox_backlog,\n\t\t\t\t(SELECT COUNT(*) FROM fabric_platform.event_outbox\n\t\t\t\t WHERE status='pending' AND lease_expires_at IS NOT NULL AND lease_expires_at <= $3\n\t\t\t\t AND ($1::text IS NULL OR tenant_id=$1)\n\t\t\t\t AND ($2::text IS NULL OR space_id=$2)) AS outbox_expired_leases,\n\t\t\t\t(SELECT COUNT(*) FROM fabric_platform.event_outbox\n\t\t\t\t WHERE status='dead_letter'\n\t\t\t\t AND ($1::text IS NULL OR tenant_id=$1)\n\t\t\t\t AND ($2::text IS NULL OR space_id=$2)) AS outbox_dead_letters`,\n\t\t\t[input.tenantId ?? null, input.spaceId ?? null, input.now],\n\t\t);\n\t\tconst row = result.rows[0] ?? {};\n\t\treturn {\n\t\t\tinvocationBacklog: Number(row.invocation_backlog ?? 0),\n\t\t\tinvocationRunning: Number(row.invocation_running ?? 0),\n\t\t\tinvocationExpiredLeases: Number(row.invocation_expired_leases ?? 0),\n\t\t\tinvocationApprovalWaits: Number(row.invocation_approval_waits ?? 0),\n\t\t\tinvocationReconciliationRequired: Number(row.invocation_reconciliation_required ?? 0),\n\t\t\toutboxBacklog: Number(row.outbox_backlog ?? 0),\n\t\t\toutboxExpiredLeases: Number(row.outbox_expired_leases ?? 0),\n\t\t\toutboxDeadLetters: Number(row.outbox_dead_letters ?? 0),\n\t\t};\n\t}\n\n\tasync claimActionInvocations(\n\t\tinput: ClaimActionInvocationsInput,\n\t): Promise<ActionInvocationRecord[]> {\n\t\tconst current = input.now ?? new Date();\n\t\tconst limit = Math.max(1, Math.min(input.limit ?? 10, 100));\n\t\tconst leaseExpiresAt = new Date(current.getTime() + input.leaseDurationMs);\n\t\tconst result = await this.sql.query<Record<string, unknown>>(\n\t\t\t`WITH claimable AS (\n\t\t\t\tSELECT id FROM fabric_platform.action_invocations\n\t\t\t\tWHERE (status='pending' OR\n\t\t\t\t (status='running' AND lease_expires_at IS NOT NULL AND lease_expires_at <= $1))\n\t\t\t\t AND ($2::text IS NULL OR tenant_id=$2)\n\t\t\t\t AND ($3::text IS NULL OR space_id=$3)\n\t\t\t\tORDER BY created_at\n\t\t\t\tFOR UPDATE SKIP LOCKED\n\t\t\t\tLIMIT $4\n\t\t\t)\n\t\t\tUPDATE fabric_platform.action_invocations AS invocation\n\t\t\tSET status='running', lease_owner=$5, lease_expires_at=$6,\n\t\t\t lease_token=lease_token+1, attempt_count=attempt_count+1, updated_at=$1\n\t\t\tFROM claimable WHERE invocation.id=claimable.id\n\t\t\tRETURNING invocation.*`,\n\t\t\t[current, input.tenantId ?? null, input.spaceId ?? null, limit, input.workerId,\n\t\t\t leaseExpiresAt],\n\t\t);\n\t\treturn result.rows.map(toActionRecord);\n\t}\n\n\tasync updateLeasedActionInvocation(input: import(\"./types\").UpdateLeasedActionInvocationInput): Promise<boolean> {\n\t\tconst patch = input.patch;\n\t\tconst result = await this.sql.query(\n\t\t\t`UPDATE fabric_platform.action_invocations SET\n\t\t\t status=COALESCE($6,status), result=COALESCE($7::jsonb,result),\n\t\t\t error=CASE WHEN $8::boolean THEN $9 ELSE error END,\n\t\t\t authorization_reconciliation=CASE WHEN $10::boolean THEN $11::jsonb ELSE authorization_reconciliation END,\n\t\t\t adapter_reconciliation=CASE WHEN $12::boolean THEN $13::jsonb ELSE adapter_reconciliation END,\n\t\t\t pending_completion=CASE WHEN $14::boolean THEN $15::jsonb ELSE pending_completion END,\n\t\t\t completion_due_at=CASE WHEN $14::boolean THEN ($15::jsonb->>'dueAt')::timestamptz ELSE completion_due_at END,\n\t\t\t external_completion=CASE WHEN $16::boolean THEN $17::jsonb ELSE external_completion END,\n\t\t\t pending_state_transition=CASE WHEN $18::boolean THEN $19::jsonb ELSE pending_state_transition END,\n\t\t\t lease_owner=CASE WHEN ($15::jsonb IS NOT NULL AND $6='running') OR $6 IN ('waiting_for_approval','completed','failed','blocked_by_policy','reconciliation_required','validation_failed')\n\t\t\t THEN NULL ELSE lease_owner END,\n\t\t\t lease_expires_at=CASE WHEN ($15::jsonb IS NOT NULL AND $6='running') OR $6 IN ('waiting_for_approval','completed','failed','blocked_by_policy','reconciliation_required','validation_failed')\n\t\t\t THEN NULL ELSE lease_expires_at END,\n\t\t\t updated_at=now()\n\t\t\t WHERE id=$1 AND tenant_id=$2 AND space_id=$3\n\t\t\t AND status='running' AND lease_owner=$4 AND lease_token=$5\n\t\t\t RETURNING id`,\n\t\t\t[input.id, input.tenantId, input.spaceId, input.workerId, input.leaseToken,\n\t\t\t\tpatch.status ?? null,\n\t\t\t\tpatch.result === undefined ? null : JSON.stringify(patch.result),\n\t\t\t\tObject.hasOwn(patch, \"error\"), patch.error ?? null,\n\t\t\t\tObject.hasOwn(patch, \"authorizationReconciliation\"),\n\t\t\t\tpatch.authorizationReconciliation ? JSON.stringify(patch.authorizationReconciliation) : null,\n\t\t\t\tObject.hasOwn(patch, \"adapterReconciliation\"),\n\t\t\t\tpatch.adapterReconciliation ? JSON.stringify(patch.adapterReconciliation) : null,\n\t\t\t\tObject.hasOwn(patch, \"pendingCompletion\"),\n\t\t\t\tpatch.pendingCompletion ? JSON.stringify(patch.pendingCompletion) : null,\n\t\t\t\tObject.hasOwn(patch, \"externalCompletion\"),\n\t\t\t\tpatch.externalCompletion ? JSON.stringify(patch.externalCompletion) : null,\n\t\t\t\tObject.hasOwn(patch, \"pendingStateTransition\"),\n\t\t\t\tpatch.pendingStateTransition ? JSON.stringify(patch.pendingStateTransition) : null],\n\t\t);\n\t\treturn result.rows.length === 1;\n\t}\n\n\tasync renewActionInvocationLease(input: import(\"./types\").RenewActionInvocationLeaseInput): Promise<boolean> {\n\t\tconst current = input.now ?? new Date();\n\t\tconst result = await this.sql.query(\n\t\t\t`UPDATE fabric_platform.action_invocations\n\t\t\t SET lease_expires_at=$6,updated_at=$5\n\t\t\t WHERE id=$1 AND tenant_id=$2 AND space_id=$3\n\t\t\t AND status='running' AND lease_owner=$4 AND lease_token=$7\n\t\t\t AND lease_expires_at > $5\n\t\t\t RETURNING id`,\n\t\t\t[input.id, input.tenantId, input.spaceId, input.workerId, current,\n\t\t\t\tnew Date(current.getTime() + input.leaseDurationMs), input.leaseToken],\n\t\t);\n\t\treturn result.rows.length === 1;\n\t}\n\n\tasync listEvents(tenantId: string, spaceId: string): Promise<AssetEventEnvelope[]> {\n\t\tconst result = await this.sql.query<Record<string, unknown>>(\n\t\t\t`SELECT * FROM fabric_platform.asset_events\n\t\t\t WHERE tenant_id=$1 AND space_id=$2 ORDER BY sequence`,\n\t\t\t[tenantId, spaceId],\n\t\t);\n\t\treturn result.rows.map(toEventRecord);\n\t}\n\n\tasync getEvent(\n\t\tid: string,\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t): Promise<AssetEventEnvelope | undefined> {\n\t\tconst result = await this.sql.query<Record<string, unknown>>(\n\t\t\t`SELECT * FROM fabric_platform.asset_events\n\t\t\t WHERE id=$1 AND tenant_id=$2 AND space_id=$3`,\n\t\t\t[id, tenantId, spaceId],\n\t\t);\n\t\treturn result.rows[0] ? toEventRecord(result.rows[0]) : undefined;\n\t}\n}\n\nfunction toAdapterRecord(row: Record<string, unknown>): AdapterInvocationRecord {\n\treturn {\n\t\tid: String(row.id),\n\t\tactionInvocationId: String(row.action_invocation_id),\n\t\ttenantId: String(row.tenant_id),\n\t\tspaceId: String(row.space_id),\n\t\tadapterType: String(row.adapter_type),\n\t\toperation: String(row.operation),\n\t\tvendor: String(row.vendor),\n\t\tstatus: String(row.status) as AdapterInvocationRecord[\"status\"],\n\t\tinput: row.input as Record<string, unknown>,\n\t\t...(row.output ? { output: row.output as Record<string, unknown> } : {}),\n\t\t...(row.error ? { error: String(row.error) } : {}),\n\t\t...(row.reconciliation ? { reconciliation: row.reconciliation as AdapterInvocationRecord[\"reconciliation\"] } : {}),\n\t\tattempt: Number(row.attempt),\n\t\tcreatedAt: new Date(row.created_at as string | Date),\n\t\tupdatedAt: new Date(row.updated_at as string | Date),\n\t};\n}\n\nfunction toPendingCompletion(value: Record<string, unknown>): NonNullable<ActionInvocationRecord[\"pendingCompletion\"]> {\n\treturn {\n\t\t...(value as unknown as NonNullable<ActionInvocationRecord[\"pendingCompletion\"]>),\n\t\tacceptedAt: new Date(value.acceptedAt as string),\n\t\t...(value.dueAt ? { dueAt: new Date(value.dueAt as string) } : {}),\n\t\t...(value.parkedAt ? { parkedAt: new Date(value.parkedAt as string) } : {}),\n\t\t...(value.overdueAt ? { overdueAt: new Date(value.overdueAt as string) } : {}),\n\t};\n}\n\nfunction toExternalCompletion(value: Record<string, unknown>): NonNullable<ActionInvocationRecord[\"externalCompletion\"]> {\n\treturn {\n\t\t...(value as unknown as NonNullable<ActionInvocationRecord[\"externalCompletion\"]>),\n\t\trecordedAt: new Date(value.recordedAt as string),\n\t};\n}\n\nfunction toActionRecord(row: Record<string, unknown>): ActionInvocationRecord {\n\treturn {\n\t\tid: String(row.id), tenantId: String(row.tenant_id), spaceId: String(row.space_id),\n\t\tactionId: String(row.action_id) as ActionInvocationRecord[\"actionId\"],\n\t\tactionVersion: Number(row.action_version),\n\t\tactorId: String(row.actor_id),\n\t\tactorType: String(row.actor_type) as ActionInvocationRecord[\"actorType\"],\n\t\tstatus: String(row.status) as ActionInvocationRecord[\"status\"],\n\t\tparameters: row.parameters as Record<string, unknown>,\n\t\tresult: row.result as Record<string, unknown>, correlationId: String(row.correlation_id),\n\t\t...(row.causation_id ? { causationId: String(row.causation_id) } : {}),\n\t\t...(row.idempotency_key ? { idempotencyKey: String(row.idempotency_key) } : {}),\n\t\t...(row.parameter_digest ? { parameterDigest: String(row.parameter_digest) } : {}),\n\t\t...(row.parameter_digest_algorithm ? { parameterDigestAlgorithm: String(row.parameter_digest_algorithm) as ActionInvocationRecord[\"parameterDigestAlgorithm\"] } : {}),\n\t\t...(row.idempotency_actor_id ? { idempotencyActorId: String(row.idempotency_actor_id) } : {}),\n\t\t...(row.idempotency_authorization_binding_id ? { idempotencyAuthorizationBindingId: String(row.idempotency_authorization_binding_id) } : {}),\n\t\t...(row.invocation_provenance ? { provenance: row.invocation_provenance as NonNullable<ActionInvocationRecord[\"provenance\"]> } : {}),\n\t\t...(row.authorization_binding ? { authorizationBinding: row.authorization_binding as NonNullable<ActionInvocationRecord[\"authorizationBinding\"]> } : {}),\n\t\t...(row.execution_reason ? { executionReason: String(row.execution_reason) } : {}),\n\t\t...(row.authorization_reconciliation ? { authorizationReconciliation: row.authorization_reconciliation as NonNullable<ActionInvocationRecord[\"authorizationReconciliation\"]> } : {}),\n\t\t...(row.adapter_reconciliation ? { adapterReconciliation: row.adapter_reconciliation as NonNullable<ActionInvocationRecord[\"adapterReconciliation\"]> } : {}),\n\t\t...(row.pending_state_transition ? { pendingStateTransition: row.pending_state_transition as NonNullable<ActionInvocationRecord[\"pendingStateTransition\"]> } : {}),\n\t\t...(row.pending_completion ? { pendingCompletion: toPendingCompletion(row.pending_completion as Record<string, unknown>) } : {}),\n\t\t...(row.external_completion ? { externalCompletion: toExternalCompletion(row.external_completion as Record<string, unknown>) } : {}),\n\t\t...(row.authorization_binding_id\n\t\t\t? { authorizationBindingId: String(row.authorization_binding_id) }\n\t\t\t: {}),\n\t\tattemptCount: Number(row.attempt_count ?? 0),\n\t\tleaseToken: Number(row.lease_token ?? 0),\n\t\t...(row.lease_owner ? { leaseOwner: String(row.lease_owner) } : {}),\n\t\t...(row.lease_expires_at\n\t\t\t? { leaseExpiresAt: new Date(row.lease_expires_at as string | Date) }\n\t\t\t: {}),\n\t\t...(row.hitl_route\n\t\t\t? { hitlRoute: String(row.hitl_route) as ActionInvocationRecord[\"hitlRoute\"] }\n\t\t\t: {}),\n\t\t...(row.hitl_risk_tier\n\t\t\t? { hitlRiskTier: String(row.hitl_risk_tier) as ActionInvocationRecord[\"hitlRiskTier\"] }\n\t\t\t: {}),\n\t\t...(row.hitl_reason ? { hitlReason: String(row.hitl_reason) } : {}),\n\t\t...(row.hitl_policy_version\n\t\t\t? { hitlPolicyVersion: String(row.hitl_policy_version) }\n\t\t\t: {}),\n\t\t...(row.approval_decision\n\t\t\t? { approvalDecision: toApprovalDecision(row.approval_decision) }\n\t\t\t: {}),\n\t\t...(row.mutation_footprint\n\t\t\t? { mutationFootprint: row.mutation_footprint as NonNullable<ActionInvocationRecord[\"mutationFootprint\"]> }\n\t\t\t: {}),\n\t\t...(row.execution_principal\n\t\t\t? { executionPrincipal: row.execution_principal as NonNullable<ActionInvocationRecord[\"executionPrincipal\"]> }\n\t\t\t: {}),\n\t\t...(row.runtime_evidence\n\t\t\t? { runtimeEvidence: row.runtime_evidence as NonNullable<ActionInvocationRecord[\"runtimeEvidence\"]> }\n\t\t\t: {}),\n\t\t...(row.admitted_at ? { admittedAt: new Date(row.admitted_at as string | Date) } : {}),\n\t\t...(row.error ? { error: String(row.error) } : {}),\n\t\tcreatedAt: new Date(row.created_at as string | Date),\n\t\tupdatedAt: new Date(row.updated_at as string | Date),\n\t};\n}\n\nfunction toObligationRecord(row: Record<string, unknown>): PolicyObligationRecord {\n\treturn {\n\t\tid: String(row.id), actionInvocationId: String(row.action_invocation_id),\n\t\ttenantId: String(row.tenant_id), spaceId: String(row.space_id), type: String(row.type),\n\t\tstatus: String(row.status) as PolicyObligationRecord[\"status\"], required: Boolean(row.required),\n\t\t...(row.description ? { description: String(row.description) } : {}),\n\t\t...(row.evidence_references ? { evidenceReferences: row.evidence_references as NonNullable<PolicyObligationRecord[\"evidenceReferences\"]> } : {}),\n\t\t...(row.metadata ? { metadata: row.metadata as Record<string, unknown> } : {}),\n\t\tcreatedAt: new Date(row.created_at as string | Date), updatedAt: new Date(row.updated_at as string | Date),\n\t};\n}\n\nfunction toAttestationRecord(row: Record<string, unknown>): ExecutionAttestationRecord {\n\tconst attestation = row.attestation as Omit<ExecutionAttestationRecord, \"id\" | \"actionInvocationId\" | \"tenantId\" | \"spaceId\" | \"adapterInvocationId\" | \"recordedAt\">;\n\treturn {\n\t\t...attestation, id: String(row.id), actionInvocationId: String(row.action_invocation_id),\n\t\ttenantId: String(row.tenant_id), spaceId: String(row.space_id),\n\t\t...(row.adapter_invocation_id ? { adapterInvocationId: String(row.adapter_invocation_id) } : {}),\n\t\trecordedAt: new Date(row.recorded_at as string | Date),\n\t};\n}\n\nfunction toApprovalDecision(value: unknown): NonNullable<ActionInvocationRecord[\"approvalDecision\"]> {\n\tconst decision = value as Record<string, unknown>;\n\treturn {\n\t\tapproved: Boolean(decision.approved),\n\t\tapproverId: String(decision.approverId),\n\t\tapproverType: String(decision.approverType) as NonNullable<\n\t\t\tActionInvocationRecord[\"approvalDecision\"]\n\t\t>[\"approverType\"],\n\t\t...(decision.reason ? { reason: String(decision.reason) } : {}),\n\t\t...(decision.editsReference\n\t\t\t? { editsReference: String(decision.editsReference) }\n\t\t\t: {}),\n\t\tdecidedAt: new Date(decision.decidedAt as string | Date),\n\t};\n}\n\nfunction toEventRecord(row: Record<string, unknown>): AssetEventEnvelope {\n\treturn {\n\t\tid: String(row.id), tenantId: String(row.tenant_id), spaceId: String(row.space_id),\n\t\teventType: String(row.event_type), eventSchemaVersion: Number(row.event_schema_version),\n\t\tsubjectType: String(row.subject_type), subjectId: String(row.subject_id),\n\t\tactorId: String(row.actor_id), actorType: String(row.actor_type),\n\t\t...(row.action_invocation_id\n\t\t\t? { actionInvocationId: String(row.action_invocation_id) }\n\t\t\t: {}),\n\t\tpayload: row.payload, sequence: Number(row.sequence),\n\t\toccurredAt: new Date(row.occurred_at as string | Date),\n\t\trecordedAt: new Date(row.recorded_at as string | Date),\n\t\tcorrelationId: String(row.correlation_id),\n\t\t...(row.causation_id ? { causationId: String(row.causation_id) } : {}),\n\t\t...(row.provenance ? { provenance: row.provenance as NonNullable<AssetEventEnvelope[\"provenance\"]> } : {}),\n\t\t...(row.consistency ? { consistency: row.consistency as NonNullable<AssetEventEnvelope[\"consistency\"]> } : {}),\n\t};\n}\n\nfunction toOutboxRecord(row: Record<string, unknown>): OutboxRecord {\n\tconst event = row.event as Record<string, unknown>;\n\t// NULL is a row written before migration 4 (legacy). The column, not the JSON, decides whether\n\t// actor identity is hydrated, so a row that was not opted in never yields an actor.\n\tconst actorDisclosure = row.actor_disclosure === \"included\" || row.actor_disclosure === \"suppressed\"\n\t\t? row.actor_disclosure\n\t\t: undefined;\n\tconst actorIncluded = actorDisclosure === \"included\";\n\treturn {\n\t\tid: String(row.id),\n\t\ttenantId: String(row.tenant_id),\n\t\tspaceId: String(row.space_id),\n\t\t...(actorDisclosure ? { actorDisclosure } : {}),\n\t\tevent: {\n\t\t\teventId: String(event.eventId),\n\t\t\teventType: String(event.eventType),\n\t\t\teventSchemaVersion: Number(event.eventSchemaVersion),\n\t\t\ttenantId: String(event.tenantId),\n\t\t\tspaceId: String(event.spaceId),\n\t\t\tsubjectType: String(event.subjectType),\n\t\t\tsubjectId: String(event.subjectId),\n\t\t\tsequence: Number(event.sequence),\n\t\t\t...(event.actionInvocationId ? { actionInvocationId: String(event.actionInvocationId) } : {}),\n\t\t\tcorrelationId: String(event.correlationId),\n\t\t\t...(event.causationId ? { causationId: String(event.causationId) } : {}),\n\t\t\t...(actorIncluded && event.actorId ? { actorId: String(event.actorId) } : {}),\n\t\t\t...(actorIncluded && event.actorType ? { actorType: String(event.actorType) } : {}),\n\t\t\t...(event.provenance ? { provenance: event.provenance as NonNullable<EnterpriseEventEnvelope[\"provenance\"]> } : {}),\n\t\t\t...(event.consistency ? { consistency: event.consistency as NonNullable<EnterpriseEventEnvelope[\"consistency\"]> } : {}),\n\t\t\toccurredAt: new Date(event.occurredAt as string | Date),\n\t\t\trecordedAt: new Date(event.recordedAt as string | Date),\n\t\t\tproducerModuleVersion: String(event.producerModuleVersion),\n\t\t\tpayloadClassification: String(event.payloadClassification) as OutboxRecord[\"event\"][\"payloadClassification\"],\n\t\t\t...(event.traceContext ? { traceContext: event.traceContext as Record<string, string> } : {}),\n\t\t\tpayload: event.payload,\n\t\t},\n\t\tstatus: String(row.status) as OutboxStatus,\n\t\tattemptCount: Number(row.attempt_count),\n\t\tavailableAt: new Date(row.available_at as string | Date),\n\t\t...(row.lease_owner ? { leaseOwner: String(row.lease_owner) } : {}),\n\t\t...(row.lease_expires_at ? { leaseExpiresAt: new Date(row.lease_expires_at as string | Date) } : {}),\n\t\tleaseToken: Number(row.lease_token ?? 0),\n\t\t...(row.last_error ? { lastError: String(row.last_error) } : {}),\n\t\tcreatedAt: new Date(row.created_at as string | Date),\n\t\t...(row.published_at ? { publishedAt: new Date(row.published_at as string | Date) } : {}),\n\t};\n}\n\nfunction toOutboxRequeueRecord(row: Record<string, unknown>, prefix: string): OutboxRequeueRecord {\n\tconst field = (name: string) => row[`${prefix}${name}`];\n\tconst priorLastError = field(\"prior_last_error\");\n\treturn {\n\t\tid: String(field(\"id\")),\n\t\toutboxId: String(field(\"outbox_id\")),\n\t\ttenantId: String(field(\"tenant_id\")),\n\t\tspaceId: String(field(\"space_id\")),\n\t\teventId: String(field(\"event_id\")),\n\t\tactorId: String(field(\"actor_id\")),\n\t\tactorType: String(field(\"actor_type\")) as OutboxRequeueRecord[\"actorType\"],\n\t\treason: String(field(\"reason\")),\n\t\trequeuedAt: new Date(field(\"requeued_at\") as string | Date),\n\t\tavailableAt: new Date(field(\"available_at\") as string | Date),\n\t\tpriorAttemptCount: Number(field(\"prior_attempt_count\")),\n\t\t...(priorLastError !== null && priorLastError !== undefined ? { priorLastError: String(priorLastError) } : {}),\n\t\tpriorAvailableAt: new Date(field(\"prior_available_at\") as string | Date),\n\t\tpriorLeaseToken: Number(field(\"prior_lease_token\")),\n\t};\n}\n","import { isRetryableExecutionError } from \"@fabricorg/platform\";\nimport type {\n\tActionInvocationRecord,\n\tPlatformActionDispatcher,\n\tPlatformActionWorkerCycleResult,\n\tPlatformActionWorkerOptions,\n} from \"./types\";\nimport {\n\temitPlatformHostTelemetry,\n\tPLATFORM_HOST_METRIC_NAMES,\n\ttype PlatformHostTelemetry,\n\ttype PlatformHostTelemetryAttribute,\n} from \"./observability\";\n\nconst DEFAULT_BATCH_SIZE = 10;\nconst DEFAULT_LEASE_DURATION_MS = 5 * 60_000;\nconst DEFAULT_POLL_INTERVAL_MS = 1_000;\n\n/**\n * Durable store-backed dispatch: the pending invocation row is the queue item.\n * Repeated dispatches are safe because the workflow id is stable per invocation.\n */\nexport function createStoreBackedActionDispatcher(): PlatformActionDispatcher {\n\treturn {\n\t\tdispatch: async (input) => ({ workflowId: input.workflowId }),\n\t};\n}\n\n/** Claim and execute one bounded batch. Safe to run concurrently across workers. */\nexport async function runPlatformActionWorkerCycle<TDb>(\n\toptions: PlatformActionWorkerOptions<TDb>,\n): Promise<PlatformActionWorkerCycleResult> {\n\tconst leaseDurationMs = options.leaseDurationMs ?? DEFAULT_LEASE_DURATION_MS;\n\temitWorkerTelemetry(options.telemetry, \"worker.cycle.started\", options.workerId);\n\t// Handoffs past their deadline are findings, not work to claim. The sweep\n\t// runs before the claim so a failure in it strands nothing, and so an\n\t// overdue callback is surfaced even on a cycle that claims nothing.\n\tif (options.sweepOverdueCompletions !== false && typeof options.host.reconcileOverdueCompletions === \"function\") {\n\t\ttry {\n\t\t\tawait options.host.reconcileOverdueCompletions({\n\t\t\t\t...(options.tenantId ? { tenantId: options.tenantId } : {}),\n\t\t\t\t...(options.spaceId ? { spaceId: options.spaceId } : {}),\n\t\t\t});\n\t\t} catch (error) {\n\t\t\toptions.onError?.(error);\n\t\t}\n\t}\n\tlet claimed: ActionInvocationRecord[];\n\ttry {\n\t\tclaimed = await options.store.claimActionInvocations({\n\t\t\tworkerId: options.workerId,\n\t\t\tlimit: options.batchSize ?? DEFAULT_BATCH_SIZE,\n\t\t\tleaseDurationMs,\n\t\t\t...(options.tenantId ? { tenantId: options.tenantId } : {}),\n\t\t\t...(options.spaceId ? { spaceId: options.spaceId } : {}),\n\t\t});\n\t} catch (error) {\n\t\temitWorkerTelemetry(options.telemetry, \"worker.cycle.failed\", options.workerId);\n\t\tthrow error;\n\t}\n\tfor (const invocation of claimed) {\n\t\temitPlatformHostTelemetry(options.telemetry, {\n\t\t\tkind: \"event\",\n\t\t\tname: \"invocation.lease_claimed\",\n\t\t\tmetricName: PLATFORM_HOST_METRIC_NAMES.invocationLeaseClaimed,\n\t\t\toccurredAt: new Date(),\n\t\t\ttenantId: invocation.tenantId,\n\t\t\tspaceId: invocation.spaceId,\n\t\t\tattributes: { attempt: invocation.attemptCount },\n\t\t});\n\t}\n\tlet completed = 0;\n\tlet failed = 0;\n\tlet waitingForApproval = 0;\n\tlet deferred = 0;\n\tfor (const invocation of claimed) {\n\t\tconst stopHeartbeat = startLeaseHeartbeat(options, invocation, leaseDurationMs);\n\t\ttry {\n\t\t\tconst result = await options.host.executeInvocation(\n\t\t\t\tinvocation.id,\n\t\t\t\tinvocation.tenantId,\n\t\t\t\tinvocation.spaceId,\n\t\t\t\t{ leaseOwner: options.workerId, leaseToken: invocation.leaseToken },\n\t\t\t);\n\t\t\tif (result.status === \"completed\") completed += 1;\n\t\t\telse if (result.status === \"waiting_for_approval\") waitingForApproval += 1;\n\t\t\telse failed += 1;\n\t\t} catch (error) {\n\t\t\tif (isRetryableExecutionError(error)) deferred += 1;\n\t\t\telse failed += 1;\n\t\t\toptions.onError?.(error, invocation);\n\t\t} finally {\n\t\t\tawait stopHeartbeat();\n\t\t}\n\t}\n\tconst result = {\n\t\tclaimed: claimed.length,\n\t\tcompleted,\n\t\tfailed,\n\t\t...(waitingForApproval > 0 ? { waitingForApproval } : {}),\n\t\t...(deferred > 0 ? { deferred } : {}),\n\t};\n\temitWorkerTelemetry(options.telemetry, \"worker.cycle.completed\", options.workerId, result);\n\treturn result;\n}\n\nfunction startLeaseHeartbeat<TDb>(\n\toptions: PlatformActionWorkerOptions<TDb>,\n\tinvocation: ActionInvocationRecord,\n\tleaseDurationMs: number,\n): () => Promise<void> {\n\tif (!invocation?.leaseToken) return async () => undefined;\n\tconst intervalMs = options.leaseRenewalIntervalMs ??\n\t\tMath.max(1, Math.floor(leaseDurationMs / 3));\n\tlet stopped = false;\n\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\tlet running: Promise<void> | undefined;\n\tconst schedule = () => {\n\t\tif (!stopped) timer = setTimeout(tick, intervalMs);\n\t};\n\tconst tick = () => {\n\t\trunning = options.store.renewActionInvocationLease({\n\t\t\tid: invocation.id,\n\t\t\ttenantId: invocation.tenantId,\n\t\t\tspaceId: invocation.spaceId,\n\t\t\tworkerId: options.workerId,\n\t\t\tleaseToken: invocation.leaseToken!,\n\t\t\tleaseDurationMs,\n\t\t}).then((renewed) => {\n\t\t\tif (!renewed) options.onError?.(\n\t\t\t\tnew Error(`Invocation lease lost: ${invocation.id}`),\n\t\t\t\tinvocation,\n\t\t\t);\n\t\t}).catch((error: unknown) => options.onError?.(error, invocation))\n\t\t\t.finally(schedule);\n\t};\n\tschedule();\n\treturn async () => {\n\t\tstopped = true;\n\t\tif (timer) clearTimeout(timer);\n\t\tawait running;\n\t};\n}\n\n/** Poll until aborted. Each iteration is bounded and waits without busy-spinning. */\nexport async function runPlatformActionWorker<TDb>(\n\toptions: PlatformActionWorkerOptions<TDb>,\n): Promise<void> {\n\twhile (!options.signal?.aborted) {\n\t\ttry {\n\t\t\tawait runPlatformActionWorkerCycle(options);\n\t\t} catch (error) {\n\t\t\toptions.onError?.(error);\n\t\t}\n\t\tawait abortableDelay(options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS, options.signal);\n\t}\n}\n\nasync function abortableDelay(milliseconds: number, signal?: AbortSignal): Promise<void> {\n\tif (signal?.aborted) return;\n\tawait new Promise<void>((resolve) => {\n\t\tconst timeout = setTimeout(resolve, milliseconds);\n\t\tsignal?.addEventListener(\n\t\t\t\"abort\",\n\t\t\t() => {\n\t\t\t\tclearTimeout(timeout);\n\t\t\t\tresolve();\n\t\t\t},\n\t\t\t{ once: true },\n\t\t);\n\t});\n}\n\nfunction emitWorkerTelemetry(\n\ttelemetry: PlatformHostTelemetry | undefined,\n\tname: \"worker.cycle.started\" | \"worker.cycle.completed\" | \"worker.cycle.failed\",\n\tworkerId: string,\n\tattributes?: Record<string, PlatformHostTelemetryAttribute>,\n): void {\n\tconst metricName = name === \"worker.cycle.started\"\n\t\t? PLATFORM_HOST_METRIC_NAMES.workerCyclesStarted\n\t\t: name === \"worker.cycle.completed\"\n\t\t\t? PLATFORM_HOST_METRIC_NAMES.workerCyclesCompleted\n\t\t\t: PLATFORM_HOST_METRIC_NAMES.workerCyclesFailed;\n\temitPlatformHostTelemetry(telemetry, {\n\t\tkind: \"event\",\n\t\tname,\n\t\tmetricName,\n\t\toccurredAt: new Date(),\n\t\tattributes: { workerId, ...attributes },\n\t});\n}\n","import { digestParameters } from \"./command-identity\";\nimport type {\n\tActionInvocationRecord,\n\tAtomicMutationPlatformHostStore,\n\tPlatformHostStore,\n} from \"./types\";\n\nconst TERMINAL_PARENT_STATUSES = new Set<ActionInvocationRecord[\"status\"]>([\n\t\"completed\",\n\t\"failed\",\n\t\"blocked_by_policy\",\n\t\"reconciliation_required\",\n\t\"validation_failed\",\n]);\n\ninterface HostSagaParentLifecycleIdentity {\n\t/** Stable identity shared by every retry of the same lifecycle transition. */\n\tlifecycleId?: string;\n}\n\n/**\n * Durable record of a single step completing within a saga parent.\n * Structurally compatible with {@link import(\"@fabricorg/platform-temporal\").SagaParentProgressRecord}.\n */\nexport interface HostSagaParentProgressRecord {\n\tstepId: string;\n\tindex: number;\n\ttotal: number;\n\tcompletedAt: string;\n}\n\nexport interface HostSagaParentProgressInput extends HostSagaParentLifecycleIdentity {\n\tparentInvocationId: string;\n\ttenantId: string;\n\tspaceId: string;\n\tprogress: HostSagaParentProgressRecord;\n}\n\nexport interface HostSagaParentApprovalInput extends HostSagaParentLifecycleIdentity {\n\tparentInvocationId: string;\n\ttenantId: string;\n\tspaceId: string;\n\tstepId: string;\n\tapprovalId: string;\n\treason: string;\n}\n\nexport interface HostSagaParentCancellationInput extends HostSagaParentLifecycleIdentity {\n\tparentInvocationId: string;\n\ttenantId: string;\n\tspaceId: string;\n\treason: string;\n\tactorId: string;\n}\n\nexport interface HostSagaParentCompletionInput extends HostSagaParentLifecycleIdentity {\n\tparentInvocationId: string;\n\ttenantId: string;\n\tspaceId: string;\n\tresult: Record<string, unknown>;\n}\n\nexport interface HostSagaParentFailureInput extends HostSagaParentLifecycleIdentity {\n\tparentInvocationId: string;\n\ttenantId: string;\n\tspaceId: string;\n\terror: string;\n\tcompensation: HostCompensationRecord[];\n}\n\nexport interface HostCompensationRecord {\n\tstepId: string;\n\tactionId: string;\n\terror?: string;\n}\n\n/**\n * Durable saga parent lifecycle contract backed by a Platform Host store.\n *\n * Structurally compatible with {@link import(\"@fabricorg/platform-temporal\").SagaParentLifecycle}\n * so an instance can be passed directly to\n * {@link import(\"@fabricorg/platform-temporal\").createSagaParentActivities}.\n *\n * Every transition is durable: the parent invocation row is the authoritative\n * state, and lifecycle events are the audit trail. A worker that rolls over\n * mid-saga can create a fresh adapter pointing at the same store and observe\n * the persisted progress, approval park, cancellation, completion, or failure\n * without in-memory state.\n */\nexport interface HostSagaParentLifecycle {\n\trecordProgress(input: HostSagaParentProgressInput): Promise<void>;\n\tparkApproval(input: HostSagaParentApprovalInput): Promise<void>;\n\tcancel(input: HostSagaParentCancellationInput): Promise<void>;\n\tcomplete(input: HostSagaParentCompletionInput): Promise<void>;\n\tfail(input: HostSagaParentFailureInput): Promise<void>;\n}\n\nexport interface CreateDurableSagaParentLifecycleOptions<TDb> {\n\tstore: PlatformHostStore<TDb>;\n\t/** Optional clock for deterministic tests. */\n\tnow?: () => Date;\n}\n\n/**\n * Create a {@link HostSagaParentLifecycle} backed by a Platform Host store.\n *\n * The parent invocation must already exist in the store (created by\n * `submitAction` or `createActionInvocation`). Each method appends a typed\n * lifecycle event and transitions the parent invocation to the appropriate\n * status so a fresh worker can observe the persisted state after a rollover.\n */\nexport function createDurableSagaParentLifecycle<TDb>(\n\toptions: CreateDurableSagaParentLifecycleOptions<TDb>,\n): HostSagaParentLifecycle {\n\tconst store = options.store;\n\tconst now = options.now ?? (() => new Date());\n\tconst transactionWithEvents = (\n\t\tstore as PlatformHostStore<TDb> & Partial<AtomicMutationPlatformHostStore<TDb>>\n\t).transactionWithEvents?.bind(store);\n\tif (!transactionWithEvents) {\n\t\tthrow new Error(\n\t\t\t\"Durable saga parent lifecycle requires store.transactionWithEvents for atomic event and parent updates.\",\n\t\t);\n\t}\n\tconst runInTransaction = transactionWithEvents;\n\n\tasync function applyLifecycleTransition(\n\t\tinput: {\n\t\t\ttenantId: string;\n\t\t\tspaceId: string;\n\t\t\tparentInvocationId: string;\n\t\t\tlifecycleId?: string;\n\t\t},\n\t\tlifecycleId: string,\n\t\teventType: string,\n\t\tpayload: Record<string, unknown>,\n\t\tpatch?: Partial<Pick<ActionInvocationRecord, \"status\" | \"result\" | \"error\">>,\n\t): Promise<void> {\n\t\tconst eventId = `sagapar_${digestParameters({\n\t\t\tparentInvocationId: input.parentInvocationId,\n\t\t\tlifecycleId,\n\t\t}).slice(0, 40)}`;\n\t\tawait runInTransaction(async (transaction) => {\n\t\t\tif (!transaction.getActionInvocationForUpdate) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Durable saga parent lifecycle requires transaction.getActionInvocationForUpdate for serialization.\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (!transaction.getEvent) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Durable saga parent lifecycle requires transaction.getEvent for identity-scoped evidence lookup.\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst parent = await transaction.getActionInvocationForUpdate(\n\t\t\t\tinput.parentInvocationId,\n\t\t\t\tinput.tenantId,\n\t\t\t\tinput.spaceId,\n\t\t\t);\n\t\t\tif (!parent) {\n\t\t\t\tthrow new Error(`Saga parent invocation not found: ${input.parentInvocationId}`);\n\t\t\t}\n\t\t\tconst prior = await transaction.getEvent(eventId, input.tenantId, input.spaceId);\n\t\t\tif (prior) {\n\t\t\t\tif (prior.eventType !== eventType ||\n\t\t\t\t\tdigestParameters(prior.payload) !== digestParameters(payload)) {\n\t\t\t\t\tthrow new Error(`Saga lifecycle identity ${lifecycleId} has contradictory evidence.`);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (TERMINAL_PARENT_STATUSES.has(parent.status)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Saga parent invocation ${input.parentInvocationId} is already terminal (${parent.status}).`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst sequence = await transaction.nextEventSequence(input.tenantId, input.spaceId);\n\t\t\tconst timestamp = now();\n\t\t\tawait transaction.appendEvent({\n\t\t\t\tid: eventId,\n\t\t\t\ttenantId: input.tenantId,\n\t\t\t\tspaceId: input.spaceId,\n\t\t\t\teventType,\n\t\t\t\teventSchemaVersion: 1,\n\t\t\t\tsubjectType: \"ActionInvocation\",\n\t\t\t\tsubjectId: input.parentInvocationId,\n\t\t\t\tactorId: \"system\",\n\t\t\t\tactorType: \"system\",\n\t\t\t\tactionInvocationId: input.parentInvocationId,\n\t\t\t\tpayload,\n\t\t\t\tsequence,\n\t\t\t\toccurredAt: timestamp,\n\t\t\t\trecordedAt: timestamp,\n\t\t\t\tcorrelationId: input.parentInvocationId,\n\t\t\t\tcausationId: lifecycleId,\n\t\t\t});\n\t\t\tif (patch) {\n\t\t\t\tawait transaction.updateActionInvocation(\n\t\t\t\t\tinput.parentInvocationId,\n\t\t\t\t\tinput.tenantId,\n\t\t\t\t\tinput.spaceId,\n\t\t\t\t\tpatch,\n\t\t\t\t);\n\t\t\t}\n\t\t});\n\t}\n\n\treturn {\n\t\tasync recordProgress(input) {\n\t\t\tawait applyLifecycleTransition(\n\t\t\t\tinput,\n\t\t\t\tinput.lifecycleId ?? `host:${input.parentInvocationId}:progress:${input.progress.stepId}:${input.progress.index}`,\n\t\t\t\t\"SagaParentProgress\",\n\t\t\t\t{\n\t\t\t\t\tstepId: input.progress.stepId,\n\t\t\t\t\tindex: input.progress.index,\n\t\t\t\t\ttotal: input.progress.total,\n\t\t\t\t\tcompletedAt: input.progress.completedAt,\n\t\t\t\t},\n\t\t\t);\n\t\t},\n\n\t\tasync parkApproval(input) {\n\t\t\tawait applyLifecycleTransition(\n\t\t\t\tinput,\n\t\t\t\tinput.lifecycleId ?? `host:${input.parentInvocationId}:approval:${input.approvalId}`,\n\t\t\t\t\"SagaParentApprovalParked\",\n\t\t\t\t{\n\t\t\t\t\tstepId: input.stepId,\n\t\t\t\t\tapprovalId: input.approvalId,\n\t\t\t\t\treason: input.reason,\n\t\t\t\t},\n\t\t\t\t{ status: \"waiting_for_approval\" },\n\t\t\t);\n\t\t},\n\n\t\tasync cancel(input) {\n\t\t\tawait applyLifecycleTransition(\n\t\t\t\tinput,\n\t\t\t\tinput.lifecycleId ?? `host:${input.parentInvocationId}:cancel`,\n\t\t\t\t\"SagaParentCancelled\",\n\t\t\t\t{ reason: input.reason, actorId: input.actorId },\n\t\t\t\t{ status: \"failed\", error: `Saga cancelled: ${input.reason}` },\n\t\t\t);\n\t\t},\n\n\t\tasync complete(input) {\n\t\t\tawait applyLifecycleTransition(\n\t\t\t\tinput,\n\t\t\t\tinput.lifecycleId ?? `host:${input.parentInvocationId}:complete`,\n\t\t\t\t\"SagaParentCompleted\",\n\t\t\t\t{ result: input.result },\n\t\t\t\t{ status: \"completed\", result: input.result },\n\t\t\t);\n\t\t},\n\n\t\tasync fail(input) {\n\t\t\tawait applyLifecycleTransition(\n\t\t\t\tinput,\n\t\t\t\tinput.lifecycleId ?? `host:${input.parentInvocationId}:fail`,\n\t\t\t\t\"SagaParentFailed\",\n\t\t\t\t{ error: input.error, compensation: input.compensation },\n\t\t\t\t{ status: \"failed\", error: input.error },\n\t\t\t);\n\t\t},\n\t};\n}\n","import type { ActionId, ActorType } from \"@fabricorg/platform\";\nimport type { AdapterInvocationScope, GovernedActionHost, RecoverablePlatformHostStore } from \"./types\";\n\n// ── Tenant isolation conformance ────────────────────────────────────────────\n//\n// Every other seam ships an executable definition of correct. Isolation was\n// the guarantee every document asked for and every vertical tested itself.\n// These checks prove the kernel's part of it: a tenant's scope is a key on\n// the reads and writes these checks probe — invocations, claims, completions,\n// events, adapter checkpoints — not a filter somebody remembered to add. What the\n// vertical's identity adapter derives into that scope is the identity port's\n// business, and its suite; what a projection authorizes is the projection\n// host's authorize hook, and the subject may lend one for the projection check.\n\nexport interface TenantIsolationScope {\n\ttenantId: string;\n\tspaceId: string;\n\tactorId: string;\n\tactorType: ActorType;\n}\n\nexport interface TenantIsolationSubject<TDb = unknown> {\n\thost: GovernedActionHost;\n\tstore: RecoverablePlatformHostStore<TDb>;\n\t/** A governed action registered on the host, and parameters it accepts. */\n\tactionId: ActionId;\n\tparameters?: Record<string, unknown>;\n\t/** Two scopes in different tenants. */\n\tours: TenantIsolationScope;\n\ttheirs: TenantIsolationScope;\n\t/**\n\t * Optional: a governed read the subject exposes, scoped as the projection\n\t * host scopes it. Returns what a viewer in `scope` sees for the view. Every\n\t * row must carry the `tenantId` it belongs to, so the check can tell a row\n\t * of ours from a row of theirs that merely looks the same; two tenants may\n\t * legitimately hold equal-looking rows.\n\t */\n\tread?(scope: TenantIsolationScope): Promise<{ allowed: boolean; rows: readonly { tenantId: string }[] }>;\n\t/**\n\t * Optional: put the host and store back to a known state before a check.\n\t * The checks tolerate accumulated state, and each retires any row it\n\t * creates directly, so this exists for subjects whose store is shared.\n\t */\n\treset?(): Promise<void> | void;\n}\n\nexport interface TenantIsolationCheck {\n\tid:\n\t\t| \"fabric.tenancy.invocation-scoped-read.v1\"\n\t\t| \"fabric.tenancy.idempotency-key-scoped.v1\"\n\t\t| \"fabric.tenancy.events-scoped.v1\"\n\t\t| \"fabric.tenancy.worker-claim-scoped.v1\"\n\t\t| \"fabric.tenancy.completion-scoped.v1\"\n\t\t| \"fabric.tenancy.projection-scoped.v1\"\n\t\t| \"fabric.tenancy.adapter-invocation-read-scoped.v1\"\n\t\t| \"fabric.tenancy.adapter-invocation-write-scoped.v1\";\n\trun(subject: TenantIsolationSubject): Promise<string[]>;\n}\n\nexport interface TenantIsolationResult {\n\tpassed: boolean;\n\tchecks: Array<{ id: TenantIsolationCheck[\"id\"]; status: \"passed\" | \"failed\" | \"skipped\"; evidence: string[]; error?: string }>;\n}\n\nfunction fail(message: string): never {\n\tthrow new Error(message);\n}\n\nfunction submitInput(subject: TenantIsolationSubject, scope: TenantIsolationScope, idempotencyKey: string) {\n\treturn {\n\t\tactionId: subject.actionId,\n\t\tparameters: subject.parameters ?? {},\n\t\ttenantId: scope.tenantId,\n\t\tspaceId: scope.spaceId,\n\t\tactorId: scope.actorId,\n\t\tactorType: scope.actorType,\n\t\tidempotencyKey,\n\t};\n}\n\nasync function adapterProbe(subject: TenantIsolationSubject) {\n\tawait subject.reset?.();\n\tif (subject.ours.tenantId === subject.theirs.tenantId) fail(\"the two scopes must be in different tenants\");\n\tconst suffix = globalThis.crypto.randomUUID();\n\tconst scope: AdapterInvocationScope = {\n\t\ttenantId: subject.ours.tenantId, spaceId: `iso-probe-${suffix}`, actionInvocationId: `iso_act_${suffix}`,\n\t};\n\tconst id = `iso_adp_${suffix}`;\n\tconst condition = { kind: \"verdict\" as const, status: \"reconciliation_required\" as const, error: \"isolation probe\" };\n\tconst parentCreated = !!subject.store.writeAdapterInvocation;\n\tif (parentCreated) await subject.store.createActionInvocation({\n\t\tid: scope.actionInvocationId, tenantId: scope.tenantId, spaceId: scope.spaceId,\n\t\tactionId: subject.actionId, actionVersion: 1, actorId: subject.ours.actorId, actorType: subject.ours.actorType,\n\t\tstatus: condition.status, error: condition.error, parameters: {}, result: {}, correlationId: suffix,\n\t});\n\tconst now = new Date();\n\ttry {\n\t\tawait subject.store.createAdapterInvocation({\n\t\t\tid, ...scope, adapterType: \"iso\", operation: \"probe\", vendor: \"iso\",\n\t\t\tstatus: \"running\", input: {}, output: { probe: true }, attempt: 1, createdAt: now, updatedAt: now,\n\t\t});\n\t} catch (error) {\n\t\tif (parentCreated) await subject.store.updateActionInvocation(scope.actionInvocationId, scope.tenantId, scope.spaceId, { status: \"failed\", error: \"tenant isolation probe; setup failed\" });\n\t\tthrow error;\n\t}\n\tconst retire = async () => {\n\t\ttry { await subject.store.updateAdapterInvocation(id, { status: \"failed\", error: \"tenant isolation probe; retired\", updatedAt: new Date() }, scope); }\n\t\tfinally {\n\t\t\tif (parentCreated) await subject.store.updateActionInvocation(scope.actionInvocationId, scope.tenantId, scope.spaceId, { status: \"failed\", error: \"tenant isolation probe; never executed\" });\n\t\t}\n\t};\n\treturn { id, scope, condition, retire };\n}\n\n/**\n * The suite any deployment of the host must pass before it claims isolation.\n *\n * Eight checks: an invocation cannot be read, executed, or completed under\n * another tenant's scope; an idempotency key is a tenant's own, so the same\n * key in two tenants is two invocations; a tenant's event stream carries no\n * other tenant's events; a worker scoped to one tenant does not claim another's\n * work; an adapter checkpoint cannot be read or written under another tenant,\n * space, or owning invocation; and, when the subject lends a read, a viewer in\n * the other tenant sees nothing of ours.\n */\nexport function tenantIsolationChecks(): readonly TenantIsolationCheck[] {\n\treturn [\n\t\t{\n\t\t\tid: \"fabric.tenancy.invocation-scoped-read.v1\",\n\t\t\tasync run(subject) {\n\t\t\t\tawait subject.reset?.();\n\t\t\t\tif (subject.ours.tenantId === subject.theirs.tenantId) fail(\"the two scopes must be in different tenants\");\n\t\t\t\tconst ours = await subject.host.submitAction(submitInput(subject, subject.ours, \"iso:read\"));\n\t\t\t\tconst crossRead = await subject.store.getActionInvocation(ours.actionInvocationId, subject.theirs.tenantId, subject.theirs.spaceId);\n\t\t\t\tif (crossRead !== undefined) fail(\"an invocation was readable under another tenant's scope\");\n\t\t\t\tconst shape = (record: { status?: unknown; result?: unknown; error?: unknown; attemptCount?: unknown; updatedAt?: unknown } | undefined) =>\n\t\t\t\t\tJSON.stringify({ status: record?.status, result: record?.result, error: record?.error, attemptCount: record?.attemptCount, updatedAt: record?.updatedAt });\n\t\t\t\tconst before = await subject.store.getActionInvocation(ours.actionInvocationId, subject.ours.tenantId, subject.ours.spaceId);\n\t\t\t\tif (!before) fail(\"our own invocation was not readable under our scope, so the check proves nothing\");\n\t\t\t\t// Snapshotted now: a store may hand back its live record.\n\t\t\t\tconst untouched = shape(before);\n\t\t\t\tlet crossExecute: unknown;\n\t\t\t\ttry {\n\t\t\t\t\tcrossExecute = await subject.host.executeInvocation(ours.actionInvocationId, subject.theirs.tenantId, subject.theirs.spaceId);\n\t\t\t\t} catch {\n\t\t\t\t\tcrossExecute = undefined;\n\t\t\t\t}\n\t\t\t\tif (crossExecute !== undefined) fail(\"an invocation was executable under another tenant's scope\");\n\t\t\t\t// Inert means untouched, not merely that nothing came back: a host\n\t\t\t\t// that read and wrote cross-tenant and then threw would otherwise pass.\n\t\t\t\tconst after = await subject.store.getActionInvocation(ours.actionInvocationId, subject.ours.tenantId, subject.ours.spaceId);\n\t\t\t\tif (untouched !== shape(after)) fail(\"an execution attempted under another tenant's scope changed our invocation\");\n\t\t\t\treturn [\"invocation readable under our scope, invisible and untouched under the other tenant's\"];\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tid: \"fabric.tenancy.idempotency-key-scoped.v1\",\n\t\t\tasync run(subject) {\n\t\t\t\tawait subject.reset?.();\n\t\t\t\tconst ours = await subject.host.submitAction(submitInput(subject, subject.ours, \"iso:shared-key\"));\n\t\t\t\tconst again = await subject.host.submitAction(submitInput(subject, subject.ours, \"iso:shared-key\"));\n\t\t\t\tif (ours.actionInvocationId !== again.actionInvocationId) fail(\"the same idempotency key in one tenant produced two invocations, so the key is not doing anything and the check proves nothing\");\n\t\t\t\tconst theirs = await subject.host.submitAction(submitInput(subject, subject.theirs, \"iso:shared-key\"));\n\t\t\t\tif (ours.actionInvocationId === theirs.actionInvocationId) fail(\"the same idempotency key in two tenants resolved to one invocation\");\n\t\t\t\treturn [\"one idempotency key: one invocation within a tenant, two across tenants\"];\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tid: \"fabric.tenancy.events-scoped.v1\",\n\t\t\tasync run(subject) {\n\t\t\t\tawait subject.reset?.();\n\t\t\t\tconst ours = await subject.host.submitAction(submitInput(subject, subject.ours, \"iso:events\"));\n\t\t\t\tconst theirEvents = await subject.store.listEvents(subject.theirs.tenantId, subject.theirs.spaceId);\n\t\t\t\tconst leaked = theirEvents.filter((event) => event.tenantId === subject.ours.tenantId || event.actionInvocationId === ours.actionInvocationId);\n\t\t\t\tif (leaked.length > 0) fail(`${leaked.length} of our events appeared in the other tenant's stream`);\n\t\t\t\tconst ourEvents = await subject.store.listEvents(subject.ours.tenantId, subject.ours.spaceId);\n\t\t\t\tif (!ourEvents.some((event) => event.actionInvocationId === ours.actionInvocationId)) fail(\"our own stream does not carry the event we just caused, so the check proves nothing\");\n\t\t\t\tif (ourEvents.some((event) => event.tenantId !== subject.ours.tenantId)) fail(\"another tenant's event appeared in our stream\");\n\t\t\t\treturn [\"event streams carry their own tenant's events and only those\"];\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tid: \"fabric.tenancy.worker-claim-scoped.v1\",\n\t\t\tasync run(subject) {\n\t\t\t\tawait subject.reset?.();\n\t\t\t\t// A pending row in a space of our own that nothing else uses, so a\n\t\t\t\t// backlog cannot push it past the claim limit, and a claim scoped to\n\t\t\t\t// it cannot sweep up real work. The row is retired afterwards so a\n\t\t\t\t// live worker never runs it.\n\t\t\t\tconst probeSpace = `iso-probe-${Date.now()}`;\n\t\t\t\tconst created = await subject.store.createActionInvocation({\n\t\t\t\t\tid: `iso_pending_${Date.now()}`,\n\t\t\t\t\ttenantId: subject.ours.tenantId,\n\t\t\t\t\tspaceId: probeSpace,\n\t\t\t\t\tactionId: subject.actionId,\n\t\t\t\t\tactionVersion: 1,\n\t\t\t\t\tactorId: subject.ours.actorId,\n\t\t\t\t\tactorType: subject.ours.actorType,\n\t\t\t\t\tstatus: \"pending\",\n\t\t\t\t\tparameters: subject.parameters ?? {},\n\t\t\t\t\tresult: {},\n\t\t\t\t\tcorrelationId: `iso-corr-${Date.now()}`,\n\t\t\t\t});\n\t\t\t\ttry {\n\t\t\t\t\tconst theirs = await subject.store.claimActionInvocations({\n\t\t\t\t\t\tworkerId: \"iso-worker\", leaseDurationMs: 1_000, limit: 1_000,\n\t\t\t\t\t\ttenantId: subject.theirs.tenantId, spaceId: probeSpace,\n\t\t\t\t\t});\n\t\t\t\t\tif (theirs.some((row) => row.id === created.id)) fail(\"a worker scoped to another tenant claimed our pending invocation\");\n\t\t\t\t\tconst ours = await subject.store.claimActionInvocations({\n\t\t\t\t\t\tworkerId: \"iso-worker\", leaseDurationMs: 1_000, limit: 1_000,\n\t\t\t\t\t\ttenantId: subject.ours.tenantId, spaceId: probeSpace,\n\t\t\t\t\t});\n\t\t\t\t\tif (!ours.some((row) => row.id === created.id)) fail(\"a worker scoped to our own tenant did not claim our pending invocation, so the check proves nothing\");\n\t\t\t\t} finally {\n\t\t\t\t\tawait subject.store.updateActionInvocation(created.id, subject.ours.tenantId, probeSpace, {\n\t\t\t\t\t\tstatus: \"failed\", error: \"tenant isolation probe; never executed\",\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\treturn [\"tenant-scoped claim takes our work and leaves other tenants' alone\"];\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tid: \"fabric.tenancy.completion-scoped.v1\",\n\t\t\tasync run(subject) {\n\t\t\t\tawait subject.reset?.();\n\t\t\t\tconst ours = await subject.host.submitAction(submitInput(subject, subject.ours, \"iso:complete\"));\n\t\t\t\tlet outcome: string;\n\t\t\t\ttry {\n\t\t\t\t\tawait subject.host.completeExternalInvocation(ours.actionInvocationId, subject.theirs.tenantId, subject.theirs.spaceId, {\n\t\t\t\t\t\texternalReference: \"iso-ref\", outcome: \"completed\", observedAt: new Date().toISOString(),\n\t\t\t\t\t});\n\t\t\t\t\toutcome = \"accepted\";\n\t\t\t\t} catch (error) {\n\t\t\t\t\tconst refusal = (error as { refusal?: string }).refusal;\n\t\t\t\t\toutcome = refusal ?? \"threw\";\n\t\t\t\t}\n\t\t\t\tif (outcome !== \"not_found\") fail(`a completion under another tenant's scope was ${outcome}; it must be refused as not_found`);\n\t\t\t\t// And under our own scope the invocation is found, whatever else it says.\n\t\t\t\tlet mine: string;\n\t\t\t\ttry {\n\t\t\t\t\tawait subject.host.completeExternalInvocation(ours.actionInvocationId, subject.ours.tenantId, subject.ours.spaceId, {\n\t\t\t\t\t\texternalReference: \"iso-ref\", outcome: \"completed\", observedAt: new Date().toISOString(),\n\t\t\t\t\t});\n\t\t\t\t\tmine = \"accepted\";\n\t\t\t\t} catch (error) {\n\t\t\t\t\tmine = (error as { refusal?: string }).refusal ?? \"threw\";\n\t\t\t\t}\n\t\t\t\tif (mine === \"not_found\") fail(\"a completion under our own scope was refused as not_found, so the check proves nothing\");\n\t\t\t\treturn [\"completion under the other tenant's scope refused as not_found; found under ours\"];\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tid: \"fabric.tenancy.projection-scoped.v1\",\n\t\t\tasync run(subject) {\n\t\t\t\tif (!subject.read) return [\"skipped: subject lends no read\"];\n\t\t\t\tawait subject.reset?.();\n\t\t\t\tawait subject.host.submitAction(submitInput(subject, subject.ours, \"iso:projection\"));\n\t\t\t\tconst ours = await subject.read(subject.ours);\n\t\t\t\tconst theirs = await subject.read(subject.theirs);\n\t\t\t\tif (!ours.allowed) fail(\"our own viewer was denied the read\");\n\t\t\t\tif (ours.rows.length === 0) fail(\"our own viewer saw nothing, so the check proves nothing\");\n\t\t\t\tif (ours.rows.some((row) => row?.tenantId !== subject.ours.tenantId)) fail(\"our own viewer saw rows that are not ours, or rows carrying no tenant\");\n\t\t\t\t// The other tenant may have rows of its own; what it must not have\n\t\t\t\t// is any of ours. Rows say whose they are, so two tenants holding\n\t\t\t\t// equal-looking rows is not a leak.\n\t\t\t\tconst leaked = theirs.allowed ? theirs.rows.filter((row) => row?.tenantId === subject.ours.tenantId) : [];\n\t\t\t\tif (leaked.length > 0) fail(`a viewer in the other tenant saw ${leaked.length} of our rows`);\n\t\t\t\treturn [theirs.allowed ? \"other tenant's viewer sees none of our rows\" : \"other tenant's viewer is denied\"];\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tid: \"fabric.tenancy.adapter-invocation-read-scoped.v1\",\n\t\t\tasync run(subject) {\n\t\t\t\tconst { id, scope, retire } = await adapterProbe(subject);\n\t\t\t\ttry {\n\t\t\t\t\tconst theirs = { ...scope, tenantId: subject.theirs.tenantId, spaceId: subject.theirs.spaceId };\n\t\t\t\t\tif (await subject.store.getAdapterInvocation(id, { ...scope, tenantId: subject.theirs.tenantId })) fail(\"an adapter invocation was readable under another tenant's scope\");\n\t\t\t\t\tif (await subject.store.getAdapterInvocation(id, theirs)) fail(\"an adapter invocation was readable under another tenant's scope\");\n\t\t\t\t\tif (await subject.store.getAdapterInvocation(id, { ...scope, spaceId: `${scope.spaceId}-other` })) fail(\"an adapter invocation was readable under another space's scope\");\n\t\t\t\t\tif (await subject.store.getAdapterInvocation(id, { ...scope, actionInvocationId: `${scope.actionInvocationId}-other` })) fail(\"an adapter invocation was readable under another action invocation's scope\");\n\t\t\t\t\tconst ours = await subject.store.getAdapterInvocation(id, scope);\n\t\t\t\t\tif (!ours || ours.id !== id || ours.tenantId !== scope.tenantId || ours.spaceId !== scope.spaceId || ours.actionInvocationId !== scope.actionInvocationId) fail(\"our own adapter invocation was not readable under our scope, so the check proves nothing\");\n\t\t\t\t} finally {\n\t\t\t\t\tawait retire();\n\t\t\t\t}\n\t\t\t\treturn [\"adapter invocation readable under our scope and invisible outside it\"];\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tid: \"fabric.tenancy.adapter-invocation-write-scoped.v1\",\n\t\t\tasync run(subject) {\n\t\t\t\tconst { id, scope, condition, retire } = await adapterProbe(subject);\n\t\t\t\tconst shape = (record: { status: unknown; error?: unknown; output?: unknown; attempt: unknown }) =>\n\t\t\t\t\tJSON.stringify({ status: record.status, error: record.error, output: record.output, attempt: record.attempt });\n\t\t\t\ttry {\n\t\t\t\t\tconst before = await subject.store.getAdapterInvocation(id, scope);\n\t\t\t\t\tif (!before) fail(\"our own adapter invocation was not readable under our scope, so the check proves nothing\");\n\t\t\t\t\t// Snapshot before writing: the memory store returns its live row.\n\t\t\t\t\tconst untouched = shape(before);\n\t\t\t\t\tfor (const other of [\n\t\t\t\t\t\t{ ...scope, tenantId: subject.theirs.tenantId, spaceId: subject.theirs.spaceId },\n\t\t\t\t\t\t{ ...scope, tenantId: subject.theirs.tenantId },\n\t\t\t\t\t\t{ ...scope, spaceId: `${scope.spaceId}-other` },\n\t\t\t\t\t\t{ ...scope, actionInvocationId: `${scope.actionInvocationId}-other` },\n\t\t\t\t\t]) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tawait subject.store.updateAdapterInvocation(id, { status: \"failed\", error: \"iso probe\", updatedAt: new Date() }, other);\n\t\t\t\t\t\t} catch { /* A not-found error is an acceptable refusal. */ }\n\t\t\t\t\t\tif (subject.store.writeAdapterInvocation) {\n\t\t\t\t\t\t\tif (subject.store.updateSettledActionInvocation && await subject.store.updateSettledActionInvocation({ id: other.actionInvocationId, tenantId: other.tenantId, spaceId: other.spaceId, condition, patch: { error: \"out-of-scope parent\" } })) fail(\"a settled parent update admitted another scope\");\n\t\t\t\t\t\t\tif (await subject.store.writeAdapterInvocation({ scope: other, condition, mutation: { kind: \"update\", id, patch: { status: \"failed\", error: \"iso probe\" } } })) fail(\"a conditional adapter update admitted another scope\");\n\t\t\t\t\t\t\tconst row = await subject.store.getAdapterInvocation(id, scope);\n\t\t\t\t\t\t\tif (!row) fail(\"our adapter row disappeared\");\n\t\t\t\t\t\t\tif (await subject.store.writeAdapterInvocation({ scope: other, condition, mutation: { kind: \"create\", record: { ...row!, id: `${id}-other` } } })) fail(\"a conditional adapter create admitted another scope\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst after = await subject.store.getAdapterInvocation(id, scope);\n\t\t\t\t\t\tif (!after || shape(after) !== untouched) fail(\"an adapter invocation changed under another scope\");\n\t\t\t\t\t}\n\t\t\t\t\tif (subject.store.writeAdapterInvocation && !await subject.store.writeAdapterInvocation({ scope, condition, expectedStatuses: [\"running\"], mutation: { kind: \"update\", id, patch: { attempt: 2 } } })) fail(\"our conditional adapter update was refused, so the check proves nothing\");\n\t\t\t\t\tawait subject.store.updateAdapterInvocation(id, { status: \"succeeded\", updatedAt: new Date() }, scope);\n\t\t\t\t\tif ((await subject.store.getAdapterInvocation(id, scope))?.status !== \"succeeded\") fail(\"our own adapter invocation was not updated under our scope, so the check proves nothing\");\n\t\t\t\t} finally {\n\t\t\t\t\tawait retire();\n\t\t\t\t}\n\t\t\t\treturn [\"adapter invocation untouched outside our scope and writable under ours\"];\n\t\t\t},\n\t\t},\n\t];\n}\n\n/** Run every check, returning each result rather than throwing on the first. */\nexport async function runTenantIsolationChecks(subject: TenantIsolationSubject): Promise<TenantIsolationResult> {\n\tconst checks: TenantIsolationResult[\"checks\"] = [];\n\tfor (const check of tenantIsolationChecks()) {\n\t\ttry {\n\t\t\tconst evidence = await check.run(subject);\n\t\t\tchecks.push({ id: check.id, status: evidence[0]?.startsWith(\"skipped\") ? \"skipped\" : \"passed\", evidence });\n\t\t} catch (error) {\n\t\t\tchecks.push({ id: check.id, status: \"failed\", evidence: [], error: error instanceof Error ? error.message : String(error) });\n\t\t}\n\t}\n\treturn { passed: checks.every((check) => check.status !== \"failed\"), checks };\n}\n"],"mappings":";;;;;;;;AA6BA,MAAa,iCAAiC;AAgC9C,IAAa,2BAAb,cAA8C,MAAM;CAE9B;CADrB,OAAgB;CAChB,YAAY,UAAwC;EACnD,MAAM,oBAAoB,SAAS,eAAe,8BAA8B,SAAS,qBAAqB,IAAI,SAAS,QAAQ,KAAK,IAAI,GAAG;EAD3H,KAAA,WAAA;EAEpB,KAAK,OAAO;CACb;AACD;;;;;;;;AAqBA,IAAa,uBAAb,cAA0C,MAAM;CAGrC;CACA;CAEA;CALV,OAAgB;CAChB,YACC,UACA,SAEA,aACC;EACD,MAAM,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Q,MAAM,uBAAuB;MAAE;MAAO;MAAW,kBAAkB,CAAC,SAAS;MAAG,UAAU;OAAE,MAAM;OAAU;OAAI,OAAO,EAAE,SAAS,EAAE;MAAE;KAAE,CAAC,GAAG,KAAK,yEAAyE;KACrR,MAAM,QAAQ,MAAM,wBAAwB,IAAI;MAAE,QAAQ;MAAa,2BAAW,IAAI,KAAK;KAAE,GAAG,KAAK;KACrG,KAAK,MAAM,QAAQ,MAAM,qBAAqB,IAAI,KAAK,EAAA,EAAI,WAAW,aAAa,KAAK,yFAAyF;IAClL,UAAU;KACT,MAAM,OAAO;IACd;IACA,OAAO,CAAC,wEAAwE;GACjF;EACD;CACD;AACD;;AAGA,eAAsB,yBAAyB,SAAiE;CAC/G,MAAM,SAA0C,CAAC;CACjD,KAAK,MAAM,SAAS,sBAAsB,GACzC,IAAI;EACH,MAAM,WAAW,MAAM,MAAM,IAAI,OAAO;EACxC,OAAO,KAAK;GAAE,IAAI,MAAM;GAAI,QAAQ,SAAS,EAAE,EAAE,WAAW,SAAS,IAAI,YAAY;GAAU;EAAS,CAAC;CAC1G,SAAS,OAAO;EACf,OAAO,KAAK;GAAE,IAAI,MAAM;GAAI,QAAQ;GAAU,UAAU,CAAC;GAAG,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;EAAE,CAAC;CAC5H;CAED,OAAO;EAAE,QAAQ,OAAO,OAAO,UAAU,MAAM,WAAW,QAAQ;EAAG;CAAO;AAC7E"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["createHash","canonicalJson","candidate","createHash","createHash","canonicalJson","utilTypes","createFabricId","performance","AdapterRegistry","AdapterCircuitBreakerRegistry","createFabricId","FABRIC_GOVERNANCE_CONTRACT_VERSION","isReconciliationRequiredError","evaluatePolicyDefinitions","aggregatePolicyOutcomes","evaluateStateMachineTransition","executeWithAdapterRetry","isAdapterCircuitOpenError","isRetryableExecutionError","createHash","isRetryableExecutionError","fail"],"sources":["../src/types.ts","../src/command-identity.ts","../src/observability.ts","../src/host-internals.ts","../src/external-completion.ts","../src/submission-snapshot.ts","../src/outbox-requeue.ts","../src/host.ts","../src/outbox.ts","../src/memory-store.ts","../src/postgres-migrations.ts","../src/postgres-store.ts","../src/worker.ts","../src/saga-parent-lifecycle.ts","../src/tenant-isolation.ts","../src/event-append-conformance.ts"],"sourcesContent":["import type {\n\tActionId,\n\tActionDefinition,\n\tActionStatus,\n\tAgentActionPolicyEvaluator,\n\tAgentActionRiskTier,\n\tAgentActionRoute,\n\tActorType,\n\tAdapterCircuitBreakerProvider,\n\tAdapterImplementation,\n\tAssetEventEnvelope,\n\tFabricRuntimeServices,\n\tPolicyOutcome,\n\tPolicyObligation,\n\tPolicyObligationStatus,\n\tExecutionAttestation,\n\tExternalReconciliation,\n\tEvidencePacketReference,\n\tMutationFootprint,\n\tExecutionPrincipal,\n\tMutationGovernanceResolver,\n\tGovernanceRuntimeEvidence,\n\tRuntimePolicyDefinition,\n\tModuleRegistry,\n} from \"@fabricorg/platform\";\nimport type { PlatformHostTelemetry } from \"./observability\";\nimport type { AssemblyLockfile } from \"@fabricorg/assembly\";\n\n/** Durable Host lifecycle generation, independent from the npm package version. */\nexport const PLATFORM_HOST_CONTRACT_VERSION = 2 as const;\n\nexport type InvocationSource = \"ui\" | \"api\" | \"agent\" | \"worker\" | \"system\" | (string & {});\nexport type NamespacedAttributes = Record<string, string>;\nexport interface InvocationProvenance {\n\tsource: InvocationSource;\n\tcorrelationId: string;\n\tcausationId?: string;\n\ttraceAttributes?: NamespacedAttributes;\n\tauditAttributes?: NamespacedAttributes;\n}\n\nexport type AuthorizationGoverningMoment = \"capture\" | \"execution\" | \"both\";\nexport interface AuthorizationBinding {\n\tid: string;\n\ttenantId: string;\n\tactorId: string;\n\tactionId: string;\n\tparameterDigest: string;\n\tresourceScope?: string;\n\tcapturedAt: string;\n\texpiresAt?: string;\n\tgoverningMoment: AuthorizationGoverningMoment;\n}\n\nexport interface IdempotencyConflict {\n\tcode: \"IDEMPOTENCY_CONFLICT\";\n\tidempotencyKey: string;\n\texistingInvocationId: string;\n\treasons: Array<\"actor\" | \"authority_binding\" | \"action_version\" | \"parameters\">;\n}\n\nexport class IdempotencyConflictError extends Error {\n\treadonly code = \"IDEMPOTENCY_CONFLICT\" as const;\n\tconstructor(readonly conflict: IdempotencyConflict) {\n\t\tsuper(`Idempotency key \"${conflict.idempotencyKey}\" conflicts with invocation ${conflict.existingInvocationId}: ${conflict.reasons.join(\", \")}`);\n\t\tthis.name = \"IdempotencyConflictError\";\n\t}\n}\n\n/**\n * Why `submitAction` did not admit a submission of an action that declares\n * `admitSubmission`: `refused`, the check answered `{ admitted: false, code }`\n * with a well-formed code; `failed`, it threw or is not a function;\n * `timed_out`, its answer did not settle within `admissionTimeoutMs`;\n * `invalid_decision`, it answered anything other than `{ admitted: true }`\n * or a well-formed refusal; `invalid_parameters`, the parameters are not a\n * JSON-data object Host could copy at submission (a Proxy, a function, a\n * Date, a typed array or SharedArrayBuffer, a cycle, a getter that throws).\n */\nexport type ActionAdmissionRefusal = \"refused\" | \"failed\" | \"timed_out\" | \"invalid_decision\" | \"invalid_parameters\";\n\n/**\n * Thrown by `submitAction` when a declared admission check did not admit the\n * submission. Host wrote nothing for it: no invocation, idempotency key,\n * event, policy record or error. The message holds the action id, the\n * refusal and, for `refused`, the check's code; never a submitted value or\n * anything the check threw.\n */\nexport class ActionAdmissionError extends Error {\n\treadonly code = \"ACTION_ADMISSION_REFUSED\" as const;\n\tconstructor(\n\t\treadonly actionId: string,\n\t\treadonly refusal: ActionAdmissionRefusal,\n\t\t/** The check's own code, present only for `refused`. */\n\t\treadonly refusalCode?: string,\n\t) {\n\t\tsuper(`Action ${actionId} submission was not admitted (${refusal}${refusalCode ? `: ${refusalCode}` : \"\"}); nothing was recorded.`);\n\t\tthis.name = \"ActionAdmissionError\";\n\t}\n}\n\nexport type ExternalCompletionRefusal =\n\t| \"still_executing\"\n\t| \"not_found\"\n\t| \"not_awaiting\"\n\t| \"immediate_contract\"\n\t| \"reference_mismatch\"\n\t| \"provider_mismatch\"\n\t| \"invalid_completion\"\n\t| \"result_invalid\"\n\t| \"redaction_failed\";\n\n/**\n * Why a completion was not applied, typed so a webhook handler can answer\n * the external system correctly: `retryable` means the invocation is still\n * being finalized and the same callback will be accepted once it parks, so\n * answer with something the sender retries; anything else is permanent and\n * a retry will get the same refusal without a configuration/input change.\n * `redaction_failed` means completion result or error-text redaction failed before writes;\n * it is not retryable.\n */\nexport class ExternalCompletionError extends Error {\n\treadonly code = \"EXTERNAL_COMPLETION_REFUSED\" as const;\n\tconstructor(readonly refusal: ExternalCompletionRefusal, message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"ExternalCompletionError\";\n\t}\n\tget retryable(): boolean {\n\t\treturn this.refusal === \"still_executing\";\n\t}\n}\n\nexport interface PendingAssetEvent {\n\teventType: string;\n\tsubjectType: string;\n\tsubjectId: string;\n\tpayload: unknown;\n\teventSchemaVersion?: number;\n}\n\nexport interface ActionInvocationRecord {\n\tid: string;\n\ttenantId: string;\n\tspaceId: string;\n\tactionId: ActionId;\n\tactionVersion: number;\n\tactorId: string;\n\tactorType: ActorType;\n\tstatus: ActionStatus;\n\tparameters: Record<string, unknown>;\n\tresult: Record<string, unknown>;\n\tcorrelationId: string;\n\tcausationId?: string;\n\tidempotencyKey?: string;\n\tparameterDigest?: string;\n\tparameterDigestAlgorithm?: \"fabric-canonical-json-sha256-v1\";\n\tidempotencyActorId?: string;\n\tidempotencyAuthorizationBindingId?: string;\n\tprovenance?: Omit<InvocationProvenance, \"traceAttributes\">;\n\tauthorizationBinding?: AuthorizationBinding;\n\texecutionReason?: ActionExecutionReason;\n\tauthorizationReconciliation?: AuthorizationReconciliationOutcome;\n\t/** Durable evidence when an adapter returned an ambiguous outcome requiring reconciliation. */\n\tadapterReconciliation?: AdapterReconciliationOutcome;\n\t/**\n\t * Transition Host validated for an idempotent after_adapters action, saved\n\t * after handler/result/event validation inside a mutation transaction, or before\n\t * the handler otherwise. Supports recovered StateTransitioned emission and is\n\t * retained as evidence after completion.\n\t */\n\tpendingStateTransition?: { entityType: string; entityId: string; fromState: string; toState: string };\n\t/**\n\t * A handoff the host is waiting on. While present the invocation is\n\t * `running` without a lease: it is not stuck, it is somebody else's turn,\n\t * and the recovery worker must not re-execute it.\n\t */\n\tpendingCompletion?: PendingExternalCompletion;\n\t/** The completion an external system delivered, kept so a repeat is recognised and a contradiction is caught. */\n\texternalCompletion?: RecordedExternalCompletion;\n\t/** Opaque, non-secret reference used to revalidate delegated execution authority. */\n\tauthorizationBindingId?: string;\n\t/** Worker claims including the first; approval acceptance sets a minimum of 1. */\n\tattemptCount: number;\n\tleaseOwner?: string;\n\tleaseExpiresAt?: Date;\n\t/** Monotonic claim generation used to reject writes from expired workers. */\n\tleaseToken?: number;\n\thitlRoute?: AgentActionRoute;\n\thitlRiskTier?: AgentActionRiskTier;\n\thitlReason?: string;\n\thitlPolicyVersion?: string;\n\tapprovalDecision?: PersistedActionApprovalDecision;\n\tmutationFootprint?: MutationFootprint;\n\texecutionPrincipal?: ExecutionPrincipal;\n\truntimeEvidence?: GovernanceRuntimeEvidence;\n\t/**\n\t * When `submitAction` admitted the submission through the action's\n\t * `admitSubmission` check, set on creation and never patched. Host refuses\n\t * to execute an invocation of an action that declares the check when this\n\t * is absent, and passes it to the handler as `ActionContext.admittedAt`.\n\t */\n\tadmittedAt?: Date;\n\terror?: string;\n\tcreatedAt: Date;\n\tupdatedAt: Date;\n}\n\nexport interface AuthorizationReconciliationOutcome {\n\tkind: \"authorization_expired\" | \"authorization_denied\" | \"authorization_missing_capture_evidence\";\n\tgoverningMoment: AuthorizationGoverningMoment;\n\texecutionReason: ActionExecutionReason;\n\tauthorizationBindingId?: string;\n\tprovenance?: Omit<InvocationProvenance, \"traceAttributes\">;\n\tmessage: string;\n}\n\nexport interface HitlDecisionEvidence {\n\troute: AgentActionRoute;\n\triskTier: AgentActionRiskTier;\n\treason: string;\n\tpolicyVersion?: string;\n\tevaluatedAt: Date;\n}\n\nexport interface ActionApprovalDecision {\n\tapproved: boolean;\n\tapproverId: string;\n\tapproverType: ActorType;\n\treason?: string;\n\teditsReference?: string;\n\tdecidedAt?: Date;\n}\n\nexport interface PersistedActionApprovalDecision\n\textends Omit<ActionApprovalDecision, \"decidedAt\"> {\n\tdecidedAt: Date;\n}\n\nexport interface PolicyEvaluationRecord {\n\tid: string;\n\tactionInvocationId: string;\n\ttenantId: string;\n\tspaceId: string;\n\toutcome: PolicyOutcome;\n\tcreatedAt: Date;\n}\n\nexport interface PolicyObligationRecord extends PolicyObligation {\n\tactionInvocationId: string;\n\ttenantId: string;\n\tspaceId: string;\n\tcreatedAt: Date;\n\tupdatedAt: Date;\n}\n\nexport interface ExecutionAttestationRecord extends ExecutionAttestation {\n\tid: string;\n\tactionInvocationId: string;\n\ttenantId: string;\n\tspaceId: string;\n\tadapterInvocationId?: string;\n\trecordedAt: Date;\n}\n\nexport interface ExternalReconciliationRecord extends ExternalReconciliation {\n\tid: string;\n\tactionInvocationId: string;\n\ttenantId: string;\n\tspaceId: string;\n}\n\nexport interface PendingExternalCompletion {\n\tprovider: string;\n\tadapterType: string;\n\toperation: string;\n\tadapterInvocationId: string;\n\texternalReference: string;\n\tacceptedAt: Date;\n\t/** Past this instant the host moves the invocation to reconciliation. */\n\tdueAt?: Date;\n\t/**\n\t * Set when the invocation finished executing and parked. A handoff is\n\t * recorded before the remaining steps run, so until this is set a\n\t * completion has nothing settled to settle into; it is asked to retry.\n\t */\n\tparkedAt?: Date;\n\t/** Set with the overdue sweep verdict; does not prove execution parked. */\n\toverdueAt?: Date;\n}\n\n/**\n * What an external system reports when it finishes work the host accepted.\n *\n * Matched to the invocation by `externalReference`, never by guesswork: a\n * completion that names a reference the invocation is not waiting on is\n * refused, because completing the wrong invocation is worse than dropping a\n * callback.\n */\nexport interface ExternalCompletion {\n\texternalReference: string;\n\toutcome: \"completed\" | \"failed\";\n\t/** Merged over the handler's result on completion. */\n\tresult?: Record<string, unknown>;\n\terror?: string;\n\tprovider?: string;\n\tevidenceReferences?: EvidencePacketReference[];\n\tobservedAt: Date | string;\n}\n\nexport interface RecordedExternalCompletion extends ExternalCompletion {\n\trecordedAt: Date;\n\t/**\n\t * Canonical digest of provider, reference, outcome, result, error, and\n\t * evidence. A repeat with the same digest is the same news; a repeat with\n\t * the same outcome and a different digest is changed evidence, and is a\n\t * contradiction like a flipped outcome. Observation time is left out,\n\t * since a redelivery legitimately carries a new one.\n\t */\n\tdigest: string;\n}\n\nexport interface ReconcileOverdueCompletionsInput {\n\ttenantId?: string;\n\tspaceId?: string;\n\tlimit?: number;\n\tnow?: Date;\n}\n\nexport type AdapterInvocationStatus = \"running\" | \"succeeded\" | \"failed\" | \"ambiguous\";\n\nexport interface AdapterReconciliationOutcome {\n\tkind: \"adapter_outcome_ambiguous\";\n\tadapterType: string;\n\toperation: string;\n\tvendor: string;\n\tadapterInvocationId: string;\n\treason?: string;\n\t/** Opaque, non-secret reference to external operation state for reconciliation. */\n\texternalReference?: string;\n\tmessage: string;\n}\n\nexport interface AdapterInvocationRecord {\n\tid: string;\n\tactionInvocationId: string;\n\ttenantId: string;\n\tspaceId: string;\n\tadapterType: string;\n\toperation: string;\n\tvendor: string;\n\tstatus: AdapterInvocationStatus;\n\tinput: Record<string, unknown>;\n\toutput?: Record<string, unknown>;\n\terror?: string;\n\t/** Redacted checkpoint for replaying an ambiguous settlement without another provider call. */\n\treconciliation?: AdapterReconciliationOutcome & {\n\t\t/** Original event subject, stored only for settlement recovery. */\n\t\tadapterEventSubject?: { subjectType: string; subjectId: string };\n\t};\n\tattempt: number;\n\tcreatedAt: Date;\n\tupdatedAt: Date;\n}\n\nexport interface CreateActionInvocationInput\n\textends Omit<\n\t\tActionInvocationRecord,\n\t\t\"createdAt\" | \"updatedAt\" | \"attemptCount\" | \"leaseOwner\" | \"leaseExpiresAt\" | \"leaseToken\"\n\t> {}\n\n/** Scope of an adapter checkpoint within its owning action invocation. */\nexport interface AdapterInvocationScope {\n\ttenantId: string;\n\tspaceId: string;\n\tactionInvocationId: string;\n}\n\n/** Authority for an adapter mutation; verdict evidence uses exact status/error equality. */\nexport type AdapterInvocationWriteCondition =\n\t| { kind: \"lease\"; leaseOwner: string; leaseToken: number }\n\t| { kind: \"verdict\"; status: Exclude<ActionInvocationRecord[\"status\"], \"pending\" | \"running\" | \"waiting_for_approval\">; error?: string;\n\t\t/** Absent requires no recorded completion; a digest requires that same completion. */\n\t\texternalCompletionDigest?: string;\n\t\t/** Captured handoff row; other adapter rows need only status/error and row-status fencing.\n\t\t * Omit to retain the conservative completion check for adapter writes. Parent enrichment\n\t\t * compares the completion digest regardless of this member. */\n\t\tcompletionAdapterInvocationId?: string };\n\n/** Conditionally enrich this execution's settled parent without changing its status. */\nexport interface UpdateSettledActionInvocationInput {\n\tid: string;\n\ttenantId: string;\n\tspaceId: string;\n\tcondition: Extract<AdapterInvocationWriteCondition, { kind: \"verdict\" }>;\n\tpatch: Pick<ActionInvocationPatch, \"error\" | \"adapterReconciliation\">;\n}\n\nexport type AdapterInvocationPatch = Partial<Pick<AdapterInvocationRecord,\n\t\"status\" | \"output\" | \"error\" | \"attempt\" | \"updatedAt\" | \"reconciliation\">>;\n\nexport interface AdapterInvocationWriteInput {\n\tscope: AdapterInvocationScope;\n\tcondition: AdapterInvocationWriteCondition;\n\t/** Compare against the current row, inside the same atomic operation. */\n\texpectedStatuses?: readonly AdapterInvocationRecord[\"status\"][];\n\tmutation: { kind: \"create\"; record: AdapterInvocationRecord }\n\t\t| { kind: \"update\"; id: string; patch: AdapterInvocationPatch };\n}\n\nexport interface PlatformHostStore<TDb> {\n\treadonly db: TDb;\n\t/**\n\t * Run against the store's domain handle. This base seam does not promise a\n\t * database transaction. Use `transactionWithEvents` when domain writes,\n\t * canonical events, and invocation state must commit atomically.\n\t */\n\ttransaction<TResult>(run: (db: TDb) => Promise<TResult>): Promise<TResult>;\n\tcreateActionInvocation(input: CreateActionInvocationInput): Promise<ActionInvocationRecord>;\n\tgetActionInvocation(\n\t\tid: string,\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t): Promise<ActionInvocationRecord | undefined>;\n\tupdateActionInvocation(\n\t\tid: string,\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t\tpatch: ActionInvocationPatch,\n\t): Promise<void>;\n\tappendPolicyEvaluation(record: PolicyEvaluationRecord): Promise<void>;\n\tcreateAdapterInvocation(record: AdapterInvocationRecord): Promise<void>;\n\t/**\n\t * Optional atomic parent-authorized adapter create/update. Lease authority\n\t * requires a running parent with the supplied owner/token; verdict authority\n\t * requires the exact parent status/error (undefined error equals no error).\n\t * The completion digest guards the captured completionAdapterInvocationId;\n\t * other rows retain status/error and expectedStatuses checks. Without a captured\n\t * row ID the digest check applies conservatively to the mutation too.\n\t * Match tenant, space and invocation on both rows, locking the parent before\n\t * the adapter. Return false for a predicate miss, missing parent/row, or a\n\t * duplicate create. Updates cannot move succeeded/ambiguous to running/failed,\n\t * even when expectedStatuses is omitted. Creation must match input.scope.\n\t * Transaction implementations recheck predicates at commit or retain locks.\n\t * Host uses unchecked legacy writes when this capability is absent: custom\n\t * stores without it do not protect adapter rows against stale workers.\n\t */\n\twriteAdapterInvocation?(input: AdapterInvocationWriteInput): Promise<boolean>;\n\t/**\n\t * Atomic scoped status/error/completion compare-and-set for post-verdict enrichment.\n\t * Expected alongside writeAdapterInvocation. When absent, Host skips only parent\n\t * enrichment and still attempts the remaining evidence writes. Refusal is telemetry;\n\t * thrown errors join the evidence collector.\n\t */\n\tupdateSettledActionInvocation?(input: UpdateSettledActionInvocationInput): Promise<boolean>;\n\t/**\n\t * Host supplies scope from its store-loaded invocation at adapter call sites.\n\t * When supplied, stores must match tenant, space, and action invocation:\n\t * an out-of-scope record returns undefined. Optional for compatibility with\n\t * existing custom stores and direct callers; tenantIsolationChecks tests\n\t * scoped read and write conformance.\n\t */\n\tgetAdapterInvocation(id: string, scope?: AdapterInvocationScope): Promise<AdapterInvocationRecord | undefined>;\n\t/**\n\t * Match all three scope fields when supplied, changing nothing outside it\n\t * (a not-found error is permitted). Host supplies scope as described above;\n\t * optional only for compatibility with existing stores and direct callers.\n\t */\n\tupdateAdapterInvocation(\n\t\tid: string,\n\t\tpatch: Partial<\n\t\t\tPick<AdapterInvocationRecord, \"status\" | \"output\" | \"error\" | \"attempt\" | \"updatedAt\" | \"reconciliation\">\n\t\t>,\n\t\tscope?: AdapterInvocationScope,\n\t): Promise<void>;\n\t/**\n\t * First-write-wins: an event ID the store already holds, in any tenant or space, is a no-op\n\t * that keeps the first event. Do not throw, replace or merge it, regardless of\n\t * the later payload, sequence or timestamps. Host re-appends lifecycle events\n\t * under stable IDs on retry/recovery with fresh sequences and timestamps and\n\t * potentially different payloads.\n\t */\n\tappendEvent(event: AssetEventEnvelope): Promise<void>;\n\tnextEventSequence(tenantId: string, spaceId: string): Promise<number>;\n\t/**\n\t * Return the state and invocation writer of the same event selected by\n\t * getEntityState, scoped to this subject and tenant/space. Return undefined\n\t * when that event or its invocation provenance is unavailable. Transaction\n\t * implementations include pending events visible to getEntityState.\n\t */\n\tgetEntityStateSource?(\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t\tentityType: string,\n\t\tentityId: string,\n\t): Promise<{ state: string; actionInvocationId: string } | undefined>;\n\n\tgetEntityState(\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t\tentityType: string,\n\t\tentityId: string,\n\t): Promise<string | undefined>;\n}\n\n/**\n * Transaction-scoped Host operations used to commit domain writes and their\n * canonical events as one unit of work.\n *\n * The supplied `db` must be bound to the same database transaction as every\n * lifecycle method on this object. Implementations must roll the whole unit\n * back when `run` throws.\n */\nexport interface PlatformHostMutationTransaction<TDb> {\n\treadonly db: TDb;\n\t/**\n\t * Read and lock an invocation until this transaction completes.\n\t * Required by serialized saga parent lifecycle transitions.\n\t */\n\tgetActionInvocationForUpdate?(\n\t\tid: string,\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t): Promise<ActionInvocationRecord | undefined>;\n\t/**\n\t * Read one event by its stable identity inside the transaction.\n\t * Required by serialized saga parent lifecycle transitions.\n\t */\n\tgetEvent?(\n\t\tid: string,\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t): Promise<AssetEventEnvelope | undefined>;\n\t/**\n\t * First-write-wins: an event ID the store already holds, in any tenant or space, is a no-op\n\t * that keeps the first event. Do not throw, replace or merge it, regardless of\n\t * the later payload, sequence or timestamps. Host re-appends lifecycle events\n\t * under stable IDs on retry/recovery with fresh sequences and timestamps and\n\t * potentially different payloads.\n\t */\n\tappendEvent(event: AssetEventEnvelope): Promise<void>;\n\t/**\n\t * First-write-wins: an event ID the store already holds, in any tenant or space, is a no-op\n\t * that keeps the first event and adds no outbox row, even when the\n\t * first append had none. Do not throw,\n\t * replace or merge it, regardless of the later payload, sequence or timestamps.\n\t * Host re-appends lifecycle events under stable IDs on retry/recovery with fresh\n\t * sequences and timestamps and potentially different payloads.\n\t */\n\tappendEventWithOutbox?(\n\t\tevent: AssetEventEnvelope,\n\t\tmetadata: OutboxEventMetadata,\n\t): Promise<void>;\n\tnextEventSequence(tenantId: string, spaceId: string): Promise<number>;\n\tlistEvents(tenantId: string, spaceId: string): Promise<AssetEventEnvelope[]>;\n\t/**\n\t * Return the state and invocation writer of the same event selected by\n\t * getEntityState, scoped to this subject and tenant/space. Return undefined\n\t * when that event or its invocation provenance is unavailable. Transaction\n\t * implementations include pending events visible to getEntityState.\n\t */\n\tgetEntityStateSource?(\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t\tentityType: string,\n\t\tentityId: string,\n\t): Promise<{ state: string; actionInvocationId: string } | undefined>;\n\n\tgetEntityState?(\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t\tentityType: string,\n\t\tentityId: string,\n\t): Promise<string | undefined>;\n\tupdateActionInvocation(\n\t\tid: string,\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t\tpatch: ActionInvocationPatch,\n\t): Promise<void>;\n\tupdateLeasedActionInvocation?(\n\t\tinput: UpdateLeasedActionInvocationInput,\n\t): Promise<boolean>;\n\t/**\n\t * Update an adapter row in this transaction, with the same optional\n\t * tenant/space/invocation scope semantics as the store method. Host uses\n\t * this to commit degraded adapter evidence and its terminal verdict together.\n\t * Omit this member if the adapter row cannot share this transaction.\n\t */\n\tupdateAdapterInvocation?: PlatformHostStore<TDb>[\"updateAdapterInvocation\"];\n\t/** Same conditional write, sharing this transaction and its rollback. */\n\twriteAdapterInvocation?: PlatformHostStore<TDb>[\"writeAdapterInvocation\"];\n\t/**\n\t * Append governance reconciliation evidence in this transaction. Host uses\n\t * this for overdue sweeps and degraded finalization when adapter output is\n\t * withheld or a handoff is refused. Implement it alongside the transaction's\n\t * invocation row lock; an outer-store append while that lock is held can\n\t * block on a foreign key referencing the invocation. Omit this member if\n\t * governance evidence cannot share the event/verdict transaction.\n\t */\n\tappendExternalReconciliation?: GovernancePlatformHostStore<TDb>[\"appendExternalReconciliation\"];\n}\n\nexport type OutboxStatus = \"pending\" | \"published\" | \"dead_letter\";\nexport type EventPayloadClassification = \"public\" | \"internal\" | \"confidential\" | \"restricted\";\n\nexport interface OutboxEventMetadata {\n\tproducerModuleVersion: string;\n\tpayloadClassification: EventPayloadClassification;\n\ttraceContext?: Record<string, string>;\n\tincludeProvenance?: boolean;\n\t/**\n\t * Only `true` puts the event's `actorId` and `actorType` on the outbox envelope. Absent or any\n\t * other value leaves them off, and the outbox record says the actor was `suppressed`.\n\t */\n\tincludeActor?: boolean;\n}\n\n/**\n * Whether Host put actor identity on an outbox record's envelope, decided by `includeActor` when\n * the record was written. A record has no value when it predates the decision (`legacy`).\n */\nexport type OutboxActorDisclosure = \"included\" | \"suppressed\";\n\n/**\n * What the relay tells a publisher about an envelope's actor identity: the record's\n * `OutboxActorDisclosure`, or `legacy` for a record with none. The memory and PostgreSQL stores\n * hydrate actor identity only for `included` records, so their legacy and suppressed envelopes carry\n * none; a consumer that needs it reads the canonical event.\n */\nexport type EnterpriseEventActorDisclosure = OutboxActorDisclosure | \"legacy\";\n\nexport interface EnterpriseEventEnvelope {\n\teventId: string;\n\teventType: string;\n\teventSchemaVersion: number;\n\ttenantId: string;\n\tspaceId: string;\n\tsubjectType: string;\n\tsubjectId: string;\n\tsequence: number;\n\tactionInvocationId?: string;\n\tcorrelationId: string;\n\tcausationId?: string;\n\t/** Present only when `includeActor` opted this event in; the key is absent otherwise. */\n\tactorId?: string;\n\t/** Present only when `includeActor` opted this event in; the key is absent otherwise. */\n\tactorType?: string;\n\toccurredAt: Date;\n\trecordedAt: Date;\n\tproducerModuleVersion: string;\n\tpayloadClassification: EventPayloadClassification;\n\ttraceContext?: Record<string, string>;\n\tprovenance?: { source: InvocationSource; auditAttributes?: NamespacedAttributes };\n\t/** Present only for events an action declaring provisional consistency emitted. */\n\tconsistency?: \"authoritative-now\" | \"provisional-until-reconciled\";\n\tpayload: unknown;\n}\n\nexport interface OutboxRecord {\n\tid: string;\n\ttenantId: string;\n\tspaceId: string;\n\tevent: EnterpriseEventEnvelope;\n\t/** Absent for a record written before Host recorded the `includeActor` decision. */\n\tactorDisclosure?: OutboxActorDisclosure;\n\tstatus: OutboxStatus;\n\tattemptCount: number;\n\tavailableAt: Date;\n\tleaseOwner?: string;\n\tleaseExpiresAt?: Date;\n\tleaseToken?: number;\n\tlastError?: string;\n\tcreatedAt: Date;\n\tpublishedAt?: Date;\n}\n\nexport interface ClaimOutboxInput {\n\tworkerId: string;\n\tleaseDurationMs: number;\n\tlimit?: number;\n\ttenantId?: string;\n\tspaceId?: string;\n\tnow?: Date;\n}\n\nexport interface OutboxPlatformHostStore<TDb> extends PlatformHostStore<TDb> {\n\t/** True only when transactionWithEvents supplies appendEventWithOutbox in the same unit of work. */\n\treadonly transactionalOutbox?: boolean;\n\t/**\n\t * First-write-wins: an event ID the store already holds, in any tenant or space, is a no-op\n\t * that keeps the first event and adds no outbox row, even when the\n\t * first append had none. Do not throw,\n\t * replace or merge it, regardless of the later payload, sequence or timestamps.\n\t * Host re-appends lifecycle events under stable IDs on retry/recovery with fresh\n\t * sequences and timestamps and potentially different payloads.\n\t */\n\tappendEventWithOutbox(event: AssetEventEnvelope, metadata: OutboxEventMetadata): Promise<void>;\n\tclaimOutbox(input: ClaimOutboxInput): Promise<OutboxRecord[]>;\n\tmarkOutboxPublished(id: string, workerId: string, publishedAt: Date, leaseToken?: number): Promise<void>;\n\tmarkOutboxFailed(input: { id: string; workerId: string; leaseToken?: number; error: string; availableAt: Date; deadLetter: boolean }): Promise<void>;\n\trenewOutboxLease(input: { id: string; workerId: string; leaseToken: number; leaseDurationMs: number; now?: Date }): Promise<boolean>;\n\tlistOutbox(input?: { tenantId?: string; spaceId?: string; statuses?: OutboxStatus[] }): Promise<OutboxRecord[]>;\n}\n\n/**\n * Append-only evidence of one operator requeue of a dead-lettered outbox\n * record. The `prior*` fields are the dead-letter state the requeue replaced,\n * so the failure that exhausted the record stays readable after its attempt\n * budget is reset.\n */\nexport interface OutboxRequeueRecord {\n\tid: string;\n\toutboxId: string;\n\ttenantId: string;\n\tspaceId: string;\n\teventId: string;\n\tactorId: string;\n\tactorType: ActorType;\n\t/** Operator-supplied justification, persisted as audit evidence. Must not carry secrets. */\n\treason: string;\n\trequeuedAt: Date;\n\t/** When the requeued record became claimable again. */\n\tavailableAt: Date;\n\tpriorAttemptCount: number;\n\tpriorLastError?: string;\n\tpriorAvailableAt: Date;\n\tpriorLeaseToken: number;\n}\n\nexport interface RequeueOutboxDeadLetterStoreInput {\n\tid: string;\n\ttenantId: string;\n\tspaceId: string;\n\t/** Identity of the evidence row written with the transition. */\n\trequeueId: string;\n\tactorId: string;\n\tactorType: ActorType;\n\treason: string;\n\trequeuedAt: Date;\n\tavailableAt: Date;\n\t/**\n\t * The lease token of the dead letter the caller read and authorized. Every\n\t * claim increments the token and a requeue never lowers it, so a record\n\t * that was requeued, claimed and dead-lettered again carries a higher token\n\t * than the one observed, and the requeue is refused as `stale`.\n\t */\n\texpectedLeaseToken: number;\n}\n\n/**\n * `not_found`: no record with this id in the tenant and space, including a\n * record that exists under another tenant or space. `not_dead_letter`: the\n * record exists but is pending or published, for example because another\n * requeue won the compare-and-set. `stale`: the record is a dead letter\n * again, but not the one the caller observed; read and authorize it afresh.\n */\nexport type OutboxRequeueRefusal = \"not_found\" | \"not_dead_letter\" | \"stale\";\n\nexport type RequeueOutboxDeadLetterStoreResult =\n\t| { applied: true; record: OutboxRecord; requeue: OutboxRequeueRecord }\n\t| { applied: false; refusal: OutboxRequeueRefusal; currentStatus?: OutboxStatus };\n\n/**\n * Optional outbox capability that moves a dead-lettered record back to\n * pending. Kept apart from `OutboxPlatformHostStore` so a custom outbox store\n * that predates it still satisfies that interface.\n */\nexport interface OutboxRequeuePlatformHostStore<TDb> extends OutboxPlatformHostStore<TDb> {\n\tgetOutboxRecord(id: string, tenantId: string, spaceId: string): Promise<OutboxRecord | undefined>;\n\t/**\n\t * Compare-and-set from `dead_letter` at `expectedLeaseToken` to `pending`\n\t * within the tenant and space: resets `attemptCount` to 0, sets\n\t * `availableAt`, clears any lease owner while keeping the lease token,\n\t * keeps `lastError`, and appends one `OutboxRequeueRecord` in the same\n\t * atomic step. A record in any other state, at another lease token, or in\n\t * another scope is refused and nothing is written. The returned requeue\n\t * evidence shares nothing with stored history. The returned outbox record\n\t * has its own Date fields; its event payload and provenance are shallow.\n\t */\n\trequeueOutboxDeadLetter(input: RequeueOutboxDeadLetterStoreInput): Promise<RequeueOutboxDeadLetterStoreResult>;\n\t/** Requeue evidence for a scope, oldest first; `outboxId` narrows it to one record. */\n\tlistOutboxRequeues(input: { tenantId: string; spaceId: string; outboxId?: string }): Promise<OutboxRequeueRecord[]>;\n}\n\nexport interface RequeueOutboxDeadLetterInput {\n\toutboxId: string;\n\ttenantId: string;\n\tspaceId: string;\n\t/** Trusted operator identity from the caller's authenticated session, never from request input. */\n\tactorId: string;\n\tactorType: ActorType;\n\t/** Required justification, at most 1,000 characters, persisted as audit evidence. */\n\treason: string;\n\t/** When the record becomes claimable again; defaults to the host clock. */\n\tavailableAt?: Date;\n}\n\nexport type RequeueOutboxDeadLetterRefusal = OutboxRequeueRefusal | \"not_authorized\";\n\nexport type RequeueOutboxDeadLetterResult =\n\t| { status: \"requeued\"; record: OutboxRecord; requeue: OutboxRequeueRecord }\n\t| {\n\t\tstatus: \"refused\";\n\t\trefusal: RequeueOutboxDeadLetterRefusal;\n\t\t/** Present for `not_dead_letter` and `stale`: the state the record was found in. */\n\t\tcurrentStatus?: OutboxStatus;\n\t\tmessage: string;\n\t};\n\n/** Facts given to `authorizeOutboxRequeue`. `record` is absent when no record with this id exists in the scope. */\nexport interface OutboxRequeueAuthorizationInput {\n\ttenantId: string;\n\tspaceId: string;\n\tactorId: string;\n\tactorType: ActorType;\n\toutboxId: string;\n\treason: string;\n\trecord?: Pick<OutboxRecord[\"event\"], \"eventId\" | \"eventType\" | \"payloadClassification\"> &\n\t\tPick<OutboxRecord, \"status\" | \"attemptCount\">;\n}\n\n/**\n * Optional production capability for atomic domain/event persistence.\n *\n * A mutating Host action uses this capability when available. Stores that do\n * not implement it retain the legacy transaction boundary for compatibility,\n * but cannot claim atomic domain-write/event persistence.\n */\nexport interface AtomicMutationPlatformHostStore<TDb> extends PlatformHostStore<TDb> {\n\ttransactionWithEvents<TResult>(\n\t\trun: (transaction: PlatformHostMutationTransaction<TDb>) => Promise<TResult>,\n\t): Promise<TResult>;\n}\n\nexport interface BeginApprovalDecisionInput {\n\tactionInvocationId: string;\n\ttenantId: string;\n\tspaceId: string;\n\tdecision: PersistedActionApprovalDecision;\n\tleaseOwner: string;\n\tleaseDurationMs: number;\n\tnow: Date;\n}\n\nexport interface ApprovalDecisionTransitionResult {\n\tapplied: boolean;\n\tinvocation?: ActionInvocationRecord;\n}\n\n/** Optional store capability required only when agent HITL or approval resume is used. */\nexport interface ApprovalPlatformHostStore<TDb> extends PlatformHostStore<TDb> {\n\trecordHitlDecision(\n\t\tactionInvocationId: string,\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t\tdecision: HitlDecisionEvidence,\n\t): Promise<ActionInvocationRecord>;\n\tbeginApprovalDecision(\n\t\tinput: BeginApprovalDecisionInput,\n\t): Promise<ApprovalDecisionTransitionResult>;\n}\n\n/** Optional durable capabilities used when external-governance enrichment is configured. */\nexport interface GovernancePlatformHostStore<TDb> extends PlatformHostStore<TDb> {\n\trecordMutationGovernance(\n\t\tactionInvocationId: string,\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t\tcontext: { footprint: MutationFootprint; executionPrincipal: ExecutionPrincipal },\n\t): Promise<ActionInvocationRecord>;\n\tappendPolicyObligations(records: PolicyObligationRecord[]): Promise<void>;\n\tlistPolicyObligations(\n\t\tactionInvocationId: string,\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t): Promise<PolicyObligationRecord[]>;\n\tupdatePolicyObligation(\n\t\tactionInvocationId: string,\n\t\tobligationId: string,\n\t\tstatus: PolicyObligationStatus,\n\t\tevidenceReferences?: PolicyObligation[\"evidenceReferences\"],\n\t): Promise<void>;\n\tappendExecutionAttestation(record: ExecutionAttestationRecord): Promise<void>;\n\tlistExecutionAttestations(\n\t\tactionInvocationId: string,\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t): Promise<ExecutionAttestationRecord[]>;\n\tappendExternalReconciliation(record: ExternalReconciliationRecord): Promise<void>;\n}\n\nexport interface ListActionInvocationsInput {\n\ttenantId?: string;\n\tspaceId?: string;\n\tstatuses?: readonly ActionStatus[];\n\tupdatedBefore?: Date;\n\t/** Only invocations holding a pending external completion. */\n\tawaitingCompletion?: boolean;\n\t/** Only pending completions due at or before this instant. Implies `awaitingCompletion`. */\n\tcompletionDueBefore?: Date;\n\t/** Only invocations no worker holds a lease on. */\n\tunleased?: boolean;\n\tlimit?: number;\n}\n\nexport interface ClaimActionInvocationsInput {\n\tworkerId: string;\n\tleaseDurationMs: number;\n\tlimit?: number;\n\ttenantId?: string;\n\tspaceId?: string;\n\tnow?: Date;\n}\n\n/**\n * What the host writes back to an invocation.\n *\n * Store obligations for `pendingCompletion`, which a custom store must honour\n * or the recovery worker will re-run an external handoff:\n * - a patch that sets `pendingCompletion` together with `status: \"running\"`\n * parks the invocation and must clear its lease;\n * - a patch that sets `pendingCompletion` without a status records the handoff\n * and must leave the lease alone;\n * - a patch with `pendingCompletion: undefined` clears it;\n * - `claimActionInvocations` must never claim a running invocation without a\n * lease, which is what a parked invocation is.\n */\nexport type ActionInvocationPatch = Partial<\n\tPick<ActionInvocationRecord, \"status\" | \"result\" | \"error\" | \"authorizationReconciliation\" | \"adapterReconciliation\" | \"pendingStateTransition\" | \"pendingCompletion\" | \"externalCompletion\">\n>;\n\nexport interface UpdateLeasedActionInvocationInput {\n\tid: string;\n\ttenantId: string;\n\tspaceId: string;\n\tworkerId: string;\n\tleaseToken: number;\n\tpatch: ActionInvocationPatch;\n}\n\nexport interface RenewActionInvocationLeaseInput {\n\tid: string;\n\ttenantId: string;\n\tspaceId: string;\n\tworkerId: string;\n\tleaseToken: number;\n\tleaseDurationMs: number;\n\tnow?: Date;\n}\n\n/** Store capabilities required by the durable polling worker and operator tooling. */\nexport interface RecoverablePlatformHostStore<TDb> extends PlatformHostStore<TDb> {\n\tlistActionInvocations(input?: ListActionInvocationsInput): Promise<ActionInvocationRecord[]>;\n\tclaimActionInvocations(input: ClaimActionInvocationsInput): Promise<ActionInvocationRecord[]>;\n\tupdateLeasedActionInvocation(input: UpdateLeasedActionInvocationInput): Promise<boolean>;\n\trenewActionInvocationLease(input: RenewActionInvocationLeaseInput): Promise<boolean>;\n\tlistEvents(tenantId: string, spaceId: string): Promise<AssetEventEnvelope[]>;\n}\n\nexport interface ActionAuthorizationInput {\n\tactionId: ActionId;\n\tnamespace: string;\n\trequiredPermissions: readonly string[];\n\trequiredRoles: readonly string[];\n\ttenantId: string;\n\tspaceId: string;\n\tactorId: string;\n\tactorType: ActorType;\n}\n\nexport type KnownActionExecutionReason = \"initial\" | \"approval_resume\" | \"recovery\" | \"offline_replay\";\nexport type ActionExecutionReason = KnownActionExecutionReason | (string & {});\n\n/**\n * Trusted execution-boundary authorization input.\n *\n * Parameters are the schema-parsed durable parameters, never caller-supplied\n * transient values. `invocation` is the canonical record that will execute.\n */\nexport interface ActionExecutionAuthorizationInput extends ActionAuthorizationInput {\n\tactionInvocationId: string;\n\tparameters: unknown;\n\tinvocation: Readonly<ActionInvocationRecord>;\n\texecutionReason: ActionExecutionReason;\n}\n\n/**\n * Input to `resolvePolicies`. Carries the invocation identity and the\n * schema-parsed durable (post-redaction) parameters so a resolver can choose\n * the policy snapshot pinned to this specific invocation. Host keeps the first\n * persisted evaluation per invocation and policy, so return the same snapshot\n * for an `actionInvocationId` on every attempt.\n */\nexport interface ResolvePoliciesInput extends ActionExecutionAuthorizationInput {\n\tdeclaredPolicyIds: readonly string[];\n}\n\nexport interface PlatformHostAuthorization {\n\tcheckEntitlement(input: ActionAuthorizationInput): Promise<boolean>;\n\tauthorize(input: ActionAuthorizationInput): Promise<boolean>;\n\t/**\n\t * Optional final authorization immediately before policies and mutation\n\t * execution. When absent, the Host reuses `authorize` at this boundary.\n\t */\n\tauthorizeExecution?(input: ActionExecutionAuthorizationInput): Promise<boolean>;\n\t/** Optional distinct authorization boundary for human/system approval decisions. */\n\tauthorizeApproval?(\n\t\tinput: ActionAuthorizationInput & { decision: ActionApprovalDecision },\n\t): Promise<boolean>;\n\t/**\n\t * Authorization for `requeueOutboxDeadLetter`. There is no action to fall\n\t * back to, so when this is absent every requeue is refused as\n\t * `not_authorized`. A throw propagates and nothing is requeued.\n\t */\n\tauthorizeOutboxRequeue?(input: OutboxRequeueAuthorizationInput): Promise<boolean>;\n}\n\nexport interface DispatchActionInput {\n\tactionInvocationId: string;\n\tactionId: ActionId;\n\ttenantId: string;\n\tspaceId: string;\n\tworkflowId: string;\n}\n\nexport interface DispatchActionResult {\n\tworkflowId: string;\n\trunId?: string;\n}\n\nexport interface PlatformActionDispatcher {\n\tdispatch(input: DispatchActionInput): Promise<DispatchActionResult>;\n}\n\n/**\n * One submission. `submitAction` reads the scalar fields (`actionId`, scope,\n * actor, correlation and causation ids, `executionReason`, `idempotencyKey`,\n * `authorizationBindingId`) exactly once, before its first await, and uses\n * only those values afterwards, so changing them while the call is pending\n * changes no action, scope, actor or key Host authorizes, persists or\n * executes. For an action that declares `admitSubmission`, `parameters`,\n * `provenance` and `authorizationBinding` are also read once there and\n * replaced by Host's own copies. For any other action Host uses those three\n * as the caller's objects, read where and as often as before (README,\n * \"Submission snapshot\").\n */\nexport interface SubmitActionInput {\n\tactionId: ActionId;\n\tparameters: Record<string, unknown>;\n\ttenantId: string;\n\tspaceId: string;\n\tactorId: string;\n\tactorType: ActorType;\n\tcorrelationId?: string;\n\tcausationId?: string;\n\tprovenance?: InvocationProvenance;\n\texecutionReason?: Extract<KnownActionExecutionReason, \"initial\" | \"offline_replay\">;\n\t/** Stable logical command key. Reusing it returns the original invocation; a pending failed dispatch may retry its stable workflow ID. */\n\tidempotencyKey?: string;\n\t/** Opaque, non-secret authorization/admission reference persisted with the invocation. */\n\tauthorizationBindingId?: string;\n\tauthorizationBinding?: AuthorizationBinding;\n}\n\nexport interface SubmitActionResult {\n\tactionInvocationId: string;\n\tstatus: ActionStatus;\n\tworkflowId: string;\n\trunId?: string;\n\tresult?: Record<string, unknown>;\n\terror?: string;\n\treconciliation?: AuthorizationReconciliationOutcome;\n\tadapterReconciliation?: AdapterReconciliationOutcome;\n\t/** Present while the invocation waits for an external system to complete it. */\n\tpendingCompletion?: PendingExternalCompletion;\n\t/** Mirrors the action's declared consistency so a caller knows whether the result is settled. */\n\tconsistency?: \"authoritative-now\" | \"provisional-until-reconciled\";\n\thitlRoute?: AgentActionRoute;\n\thitlRiskTier?: AgentActionRiskTier;\n}\n\nexport interface ExecuteActionResult {\n\tactionInvocationId: string;\n\tstatus: ActionStatus;\n\tresult?: Record<string, unknown>;\n\terror?: string;\n\treconciliation?: AuthorizationReconciliationOutcome;\n\tadapterReconciliation?: AdapterReconciliationOutcome;\n\t/** Present while the invocation waits for an external system to complete it. */\n\tpendingCompletion?: PendingExternalCompletion;\n\t/** Mirrors the action's declared consistency so a caller knows whether the result is settled. */\n\tconsistency?: \"authoritative-now\" | \"provisional-until-reconciled\";\n\thitlRoute?: AgentActionRoute;\n\thitlRiskTier?: AgentActionRiskTier;\n}\n\nexport interface ExecuteInvocationOptions {\n\t/** Required when executing a row already protected by a worker or approval-resume lease. */\n\tleaseOwner?: string;\n\t/** Claim generation paired with leaseOwner; stale generations are rejected. */\n\tleaseToken?: number;\n}\n\nexport interface PlatformActionWorkerOptions<TDb> {\n\thost: GovernedActionHost;\n\tstore: RecoverablePlatformHostStore<TDb>;\n\tworkerId: string;\n\tbatchSize?: number;\n\tleaseDurationMs?: number;\n\tleaseRenewalIntervalMs?: number;\n\tpollIntervalMs?: number;\n\ttenantId?: string;\n\tspaceId?: string;\n\tsignal?: AbortSignal;\n\tonError?: (error: unknown, invocation?: ActionInvocationRecord) => void;\n\ttelemetry?: PlatformHostTelemetry;\n\t/**\n\t * Sweep overdue external handoffs each cycle. Defaults to on. Turn it off\n\t * for a store without the governance seam, where the sweep would refuse\n\t * on every cycle, and run the sweep elsewhere.\n\t */\n\tsweepOverdueCompletions?: boolean;\n}\n\nexport interface PlatformActionWorkerCycleResult {\n\tclaimed: number;\n\tcompleted: number;\n\tfailed: number;\n\t/** Present when claimed agent work was durably parked instead of failing. */\n\twaitingForApproval?: number;\n\t/**\n\t * Present only when > 0: claimed invocations whose execution threw a\n\t * RetryableExecutionError (counted by error type, not by where it was thrown).\n\t * The row stays leased and a later claim retries it; excluded from failed.\n\t */\n\tdeferred?: number;\n}\n\n/** Origin of error text redacted before Host records or returns it. */\nexport interface ErrorTextRedactionContext {\n\tactionId: ActionId;\n\tsource: \"handler\" | \"adapter\" | \"external_completion\" | \"execution\";\n\tadapterType?: string;\n\toperation?: string;\n\t/** Adapter vendor or external completion provider. */\n\tprovider?: string;\n}\n\nexport interface PlatformHostOptions<TDb> {\n\tstore: PlatformHostStore<TDb>;\n\tauthorization: PlatformHostAuthorization;\n\t/** Preferred explicit catalog assembled from this runtime's Fabric modules. */\n\tregistry?: Pick<ModuleRegistry<TDb>, \"resolveAction\" | \"resolvePolicy\" | \"resolveStateMachine\"> &\n\t\tPartial<Pick<ModuleRegistry<TDb>, \"orderedModules\">>;\n\t/** Resolve vertical- or runtime-local actions without mutating the process-wide registry. */\n\tresolveAction?: (actionId: ActionId) => ActionDefinition<TDb> | undefined;\n\tadapters?: readonly AdapterImplementation[];\n\t/**\n\t * Supplies the circuit breaker for each adapter call. Defaults to a new\n\t * `AdapterCircuitBreakerRegistry` per Host instance, which creates one\n\t * in-process breaker per `adapterType:operation` from that adapter's own\n\t * `circuitBreaker` config, on first use, and none for adapters without one.\n\t * Pass a shared registry or a custom provider to share breakers between\n\t * Host instances, receive breaker telemetry, or set manual overrides.\n\t * The default key shares failures across tenants and vendors in a registry.\n\t * Use `new AdapterCircuitBreakerRegistry({ key: scopedAdapterCircuitBreakerKey })`\n\t * for tenant/space/vendor isolation. Host passes trusted tenant/space scope\n\t * to the provider. The registry keeps the first config seen for a key;\n\t * later conflicting configs reuse that breaker without throwing. Breakers\n\t * are never evicted, so scoped keys keep one breaker per scope seen.\n\t */\n\tadapterCircuitBreakers?: AdapterCircuitBreakerProvider;\n\t/**\n\t * Positive integer attempt cap for RetryableExecutionError during governance,\n\t * before policy-evaluation persistence (default 5). A leased, idempotent action\n\t * below the cap is left running for worker reclaim after lease expiry.\n\t * Inline execution, approval resume, exhausted attempts, and non-idempotent\n\t * actions fail. Policy persistence, obligation listing/resolution/persistence, state-machine checks,\n\t * the handler transaction, handlers, adapters, and finalization are excluded;\n\t * their failure/reconciliation/recovery semantics apply, subject to recoveryMaxAttempts.\n\t */\n\tretryableExecutionMaxAttempts?: number;\n\t/**\n\t * Positive integer cap on worker claims for resumed leased running invocations\n\t * including the first (default max(5, retryableExecutionMaxAttempts); Infinity is rejected).\n\t * An explicit value must be at least retryableExecutionMaxAttempts. Claims above\n\t * the cap settle reconciliation_required before\n\t * handler or adapter execution. Inline/direct execution and approval resume\n\t * do not increment this counter. Approval resume is admitted at the cap and settles\n\t * reconciliation above it; approval does not reset the count. Parked handoffs are excluded. A worker dying\n\t * before the check consumes a claim without executing a provider at that point.\n\t */\n\trecoveryMaxAttempts?: number;\n\tdispatcher?: PlatformActionDispatcher;\n\tservices?: FabricRuntimeServices;\n\tidempotency?: {\n\t\tconflictMode?: \"audit-only\" | \"enforce\";\n\t\tonConflict?(conflict: IdempotencyConflict): void;\n\t\tonLegacyRecord?(invocation: ActionInvocationRecord): void;\n\t};\n\tprovenance?: {\n\t\tauditAttributeAllowlist?: readonly string[];\n\t\tmaxAttributes?: number;\n\t\tmaxValueLength?: number;\n\t\tredactAuditAttributes?(attributes: NamespacedAttributes): NamespacedAttributes;\n\t\tonTrace?(provenance: InvocationProvenance): void;\n\t};\n\t/** Requires an outbox-capable store; every canonical event is then appended with delivery state. */\n\toutbox?: {\n\t\tproducerModuleVersion(actionId: ActionId, actionVersion: number): string;\n\t\tclassifyPayload(event: AssetEventEnvelope): EventPayloadClassification;\n\t\tincludeProvenance?(event: AssetEventEnvelope, classification: EventPayloadClassification): boolean;\n\t\t/**\n\t\t * Opt an event's `actorId` and `actorType` into its outbox envelope. Absent, the actor is\n\t\t * excluded for every classification. Only `true` includes it. An included actor reaches every\n\t\t * sink of every relay reading this outbox.\n\t\t */\n\t\tincludeActor?(event: AssetEventEnvelope, classification: EventPayloadClassification): boolean;\n\t\ttraceContext?(event: AssetEventEnvelope): Record<string, string> | undefined;\n\t\t/** Host lifecycle events are excluded by default; opt in only after making their payload audit-safe. */\n\t\tshouldPublish?(event: AssetEventEnvelope): boolean;\n\t};\n\t/** Optional vertical-owned evaluator. When absent, agent behavior is unchanged. */\n\thitlEvaluator?: AgentActionPolicyEvaluator;\n\t/** Durable evaluator/ruleset version recorded with every HITL decision. */\n\thitlPolicyVersion?: string;\n\t/** Optional portable resolver; provider-specific implementations belong in integration packages. */\n\tresolveMutationGovernance?: MutationGovernanceResolver;\n\t/** Translate policy outcomes into durable, enforceable obligations. */\n\tresolvePolicyObligations?: (\n\t\toutcomes: readonly PolicyOutcome[],\n\t) => Promise<PolicyObligation[]> | PolicyObligation[];\n\t/** Translate a successful adapter result into audit-safe evidence. Recovery may call this\n\t * again with stored input/output; return deterministic evidence for the same input. */\n\textractExecutionAttestation?: (input: {\n\t\tactionInvocationId: string;\n\t\tadapterInvocationId: string;\n\t\tadapterType: string;\n\t\toperation: string;\n\t\tvendor: string;\n\t\t/** Audit-safe adapter input after redactAdapterInput has been applied. */\n\t\tinput: Record<string, unknown>;\n\t\tstartedAt: Date;\n\t\tcompletedAt: Date;\n\t\t/** Adapter output after redactAdapterOutput, when configured. */\n\t\toutput: Record<string, unknown>;\n\t}) => Promise<ExecutionAttestation | undefined> | ExecutionAttestation | undefined;\n\t/** Package/provider/ruleset generations persisted with every newly created invocation. */\n\truntimeEvidence?: Partial<GovernanceRuntimeEvidence>;\n\t/**\n\t * Trusted composition identity attached by the Host configuration, never\n\t * accepted directly from submission input. Requires an explicit registry;\n\t * its module namespaces and versions are checked against these identities.\n\t */\n\tcomposition?: {\n\t\tassembly: AssemblyLockfile;\n\t\t/**\n\t\t * Receives a fresh object whose action, scope, actor, correlation,\n\t\t * causation, idempotency key, binding id and execution reason are the\n\t\t * ones Host read at submission and persists, whatever the caller\n\t\t * changed on its own object since. For an action without\n\t\t * `admitSubmission`, its `parameters`, `provenance` and\n\t\t * `authorizationBinding` read and assign the caller's input, as when\n\t\t * the callback was handed that input itself; for an action that\n\t\t * declares it, they are fresh copies of Host's snapshot.\n\t\t */\n\t\tresolveInitiatingReleaseDigest?(\n\t\t\tinput: SubmitActionInput,\n\t\t): Promise<string | undefined> | string | undefined;\n\t};\n\t/** Lease held while an approved invocation resumes; defaults to five minutes. */\n\tapprovalResumeLeaseDurationMs?: number;\n\t/**\n\t * Remove forbidden/sensitive fields before durable invocation persistence.\n\t * For an action without `admitSubmission`, receives the caller's\n\t * parameters object, before provenance normalization and the composition\n\t * callback, as before. For an action that declares it, receives Host's\n\t * copy, after the check admitted the submission.\n\t */\n\tredactActionParameters?: (\n\t\tactionId: ActionId,\n\t\tparameters: Record<string, unknown>,\n\t) => Record<string, unknown>;\n\t/**\n\t * The bound on an action's `admitSubmission` check. An answer that\n\t * settles this many milliseconds or more after the check was called,\n\t * measured on the monotonic clock when its promise settles, is refused as\n\t * `timed_out` and the check's signal is aborted. A whole number from 1 to\n\t * 2 147 483 647 (the timer maximum), or `createGovernedActionHost` throws;\n\t * default 10 000.\n\t */\n\tadmissionTimeoutMs?: number;\n\tresolvePolicies?: (input: ResolvePoliciesInput) => Promise<RuntimePolicyDefinition[]>;\n\textractEvents?: (data: Record<string, unknown>) => PendingAssetEvent[];\n\t/** Handler-result fields consumed by extractEvents and omitted from the durable result. */\n\teventResultFields?: readonly string[];\n\tredactAdapterInput?: (\n\t\tactionId: ActionId,\n\t\tadapterType: string,\n\t\toperation: string,\n\t\tinput: Record<string, unknown>,\n\t) => Record<string, unknown>;\n\t/**\n\t * Redact successful adapter output before row/event persistence and attestation extraction.\n\t * A throwing hook or a null, array or non-object return withholds output and requires reconciliation.\n\t * Class instances and Dates are accepted, matching the adapter output record contract.\n\t * Keep redactors deterministic and stable across deploys.\n\t * Accepted-operation references are read from the original adapter result.\n\t */\n\tredactAdapterOutput?: (\n\t\tactionId: ActionId,\n\t\tadapterType: string,\n\t\toperation: string,\n\t\toutput: Record<string, unknown>,\n\t) => Record<string, unknown>;\n\t/**\n\t * Redact originating handler, adapter, completion and caught execution error text.\n\t * Host-authored fixed text bypasses this hook; circuit and consistency errors use adapter context.\n\t * Empty originating text bypasses the hook unchanged. For non-empty input, throwing or returning\n\t * a non-string or empty string uses a placeholder on execution paths, but refuses a completion\n\t * as redaction_failed before writes. State-machine `transition.error` text uses `source: \"handler\"`.\n\t * Keep redactors deterministic and stable across deploys: changed output can make a repeat\n\t * completion look like different evidence.\n\t */\n\tredactErrorText?: (context: ErrorTextRedactionContext, message: string) => string;\n\t/**\n\t * Redact completion results before merging, schema validation, persistence and digesting.\n\t * Contradiction detection compares retained values; legacy raw digests also match repeats.\n\t * A throwing hook or a null, array or non-object return refuses as redaction_failed before writes.\n\t * Class instances and Dates are accepted by the same record predicate as adapter output.\n\t * Keep redactors deterministic and stable across deploys: changes can make a repeat look like\n\t * different evidence. A matching legacy raw digest is acknowledged before invoking hooks.\n\t */\n\tredactExternalCompletionResult?: (\n\t\tactionId: ActionId,\n\t\tprovider: string,\n\t\tresult: Record<string, unknown>,\n\t) => Record<string, unknown>;\n\tadapterEventSubject?: (\n\t\tactionId: ActionId,\n\t\tparameters: unknown,\n\t\thandlerResult: Record<string, unknown>,\n\t) => { subjectType: string; subjectId: string } | undefined;\n\tnow?: () => Date;\n\t/** Vendor-neutral lifecycle and metric sink. Telemetry is best effort. */\n\ttelemetry?: PlatformHostTelemetry;\n\t/**\n\t * Epoch-millis deadline delivered to every adapter execution context.\n\t * When omitted, no deadline is set and adapters receive no AbortSignal.\n\t */\n\tadapterDeadlineMs?: number;\n}\n\nexport interface GovernedActionHost {\n\tsubmitAction(input: SubmitActionInput): Promise<SubmitActionResult>;\n\texecuteInvocation(\n\t\tactionInvocationId: string,\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t\toptions?: ExecuteInvocationOptions,\n\t): Promise<ExecuteActionResult>;\n\tresumeApprovedInvocation(\n\t\tactionInvocationId: string,\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t\tdecision: ActionApprovalDecision,\n\t): Promise<ExecuteActionResult>;\n\trecordExecutionAttestation(\n\t\tactionInvocationId: string,\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t\tattestation: ExecutionAttestation,\n\t): Promise<void>;\n\trecordExternalReconciliation(\n\t\tactionInvocationId: string,\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t\treconciliation: ExternalReconciliation,\n\t): Promise<void>;\n\t/**\n\t * Complete an invocation an adapter handed off, by the reference the\n\t * external system was given. Idempotent for a repeated identical\n\t * completion; a contradictory one moves the invocation to reconciliation.\n\t */\n\tcompleteExternalInvocation(\n\t\tactionInvocationId: string,\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t\tcompletion: ExternalCompletion,\n\t): Promise<ExecuteActionResult>;\n\t/**\n\t * Move eligible running, unleased overdue handoffs to `reconciliation_required`\n\t * and retain the handoff with overdueAt. A callback can settle that verdict\n\t * only after parking; callbacks for swept unparked invocations record redacted\n\t * evidence without result-schema validation. Parked rows lacking overdueAt\n\t * retain the weaker \"did not complete by\" error-substring fallback.\n\t */\n\treconcileOverdueCompletions(input?: ReconcileOverdueCompletionsInput): Promise<{ overdue: string[] }>;\n}\n\n/**\n * Host operator operations kept outside `GovernedActionHost`, so an existing\n * hand-written `GovernedActionHost` still satisfies that interface.\n * `createGovernedActionHost()` returns both.\n */\nexport interface OutboxRequeueHost {\n\t/**\n\t * Operator replay of a dead-lettered outbox record: authorize the trusted\n\t * actor for the tenant and space against the record as read, then move\n\t * that same dead letter back to pending with a fresh attempt budget and\n\t * append who, when, and why beside the earlier failure. The relay\n\t * republishes it under the same `eventId`. Requires an\n\t * `OutboxRequeuePlatformHostStore`; refusals are returned, not thrown.\n\t */\n\trequeueOutboxDeadLetter(input: RequeueOutboxDeadLetterInput): Promise<RequeueOutboxDeadLetterResult>;\n}\n","import { createHash } from \"node:crypto\";\nimport { canonicalJson } from \"@fabricorg/platform\";\nimport type { InvocationProvenance, InvocationSource, PlatformHostOptions } from \"./types\";\n\nexport const PARAMETER_DIGEST_ALGORITHM = \"fabric-canonical-json-sha256-v1\" as const;\n\n// Canonical JSON is owned by @fabricorg/platform (evidence subpath); Host re-exports it unchanged so\n// its public API and parameter digests stay byte-identical.\nexport { canonicalJson };\n\nexport function digestParameters(parameters: unknown): string {\n\treturn createHash(\"sha256\").update(canonicalJson(parameters)).digest(\"hex\");\n}\n\nconst ATTRIBUTE_NAME = /^[a-z][a-z0-9-]*(?:\\.[A-Za-z][A-Za-z0-9_-]*)+$/;\nconst INVOCATION_SOURCE = /^(?:ui|sdui|api|agent|worker|system|[a-z][a-z0-9-]*(?:\\.[a-z][a-z0-9-]*)+)$/;\n\nexport function normalizeProvenance(\n\tinput: InvocationProvenance | undefined,\n\toptions: PlatformHostOptions<unknown>[\"provenance\"],\n): Omit<InvocationProvenance, \"traceAttributes\"> | undefined {\n\tif (!input) return undefined;\n\tif (!INVOCATION_SOURCE.test(input.source)) throw new Error(`Invalid invocation provenance source: ${input.source}`);\n\tconst maxAttributes = options?.maxAttributes ?? 16;\n\tconst maxValueLength = options?.maxValueLength ?? 256;\n\tconst allowlist = new Set(options?.auditAttributeAllowlist ?? []);\n\tconst validate = (attributes: Record<string, string> | undefined, durable: boolean) => {\n\t\tif (!attributes) return undefined;\n\t\tconst entries = Object.entries(attributes);\n\t\tif (entries.length > maxAttributes) throw new Error(`Invocation provenance exceeds ${maxAttributes} attributes.`);\n\t\tfor (const [key, value] of entries) {\n\t\t\tif (!ATTRIBUTE_NAME.test(key)) throw new Error(`Invalid provenance attribute name: ${key}`);\n\t\t\tif (value.length > maxValueLength) throw new Error(`Invocation provenance attribute \"${key}\" exceeds ${maxValueLength} characters.`);\n\t\t\tif (durable && !allowlist.has(key)) throw new Error(`Audit provenance attribute \"${key}\" is not allowlisted.`);\n\t\t}\n\t\treturn Object.fromEntries(entries);\n\t};\n\tvalidate(input.traceAttributes, false);\n\tconst redactedAuditAttributes = input.auditAttributes\n\t\t? options?.redactAuditAttributes?.({ ...input.auditAttributes }) ?? input.auditAttributes\n\t\t: undefined;\n\tconst auditAttributes = validate(redactedAuditAttributes, true);\n\toptions?.onTrace?.({\n\t\t...input,\n\t\t...(auditAttributes ? { auditAttributes } : { auditAttributes: undefined }),\n\t});\n\treturn {\n\t\tsource: input.source,\n\t\tcorrelationId: input.correlationId,\n\t\t...(input.causationId ? { causationId: input.causationId } : {}),\n\t\t...(auditAttributes ? { auditAttributes } : {}),\n\t};\n}\n","import type {\n\tActionInvocationRecord,\n\tOutboxPlatformHostStore,\n\tPlatformHostStore,\n\tRecoverablePlatformHostStore,\n} from \"./types\";\n\n/** Version of the vendor-neutral health/readiness contract. */\nexport const PLATFORM_HOST_HEALTH_CONTRACT_VERSION = 1 as const;\n\n/**\n * Stable metric names. Adapters may translate these names to a vendor's\n * naming convention, but applications should not derive names from labels.\n */\nexport const PLATFORM_HOST_METRIC_NAMES = {\n\tworkerCyclesStarted: \"fabric.platform.worker.cycles.started\",\n\tworkerCyclesCompleted: \"fabric.platform.worker.cycles.completed\",\n\tworkerCyclesFailed: \"fabric.platform.worker.cycles.failed\",\n\tinvocationSubmitted: \"fabric.platform.invocation.submitted\",\n\tinvocationAdmissionRefused: \"fabric.platform.invocation.admission_refused\",\n\tinvocationExecutionStarted: \"fabric.platform.invocation.execution_started\",\n\tinvocationLeaseClaimed: \"fabric.platform.invocation.lease_claimed\",\n\tinvocationCompleted: \"fabric.platform.invocation.completed\",\n\tinvocationFailed: \"fabric.platform.invocation.failed\",\n\tinvocationPolicyBlocked: \"fabric.platform.invocation.policy_blocked\",\n\tinvocationValidationFailed: \"fabric.platform.invocation.validation_failed\",\n\tinvocationApprovalWaited: \"fabric.platform.invocation.approval_waited\",\n\tinvocationReconciliationRequired: \"fabric.platform.invocation.reconciliation_required\",\n\tadapterEvidenceRefused: \"fabric.platform.invocation.adapter_evidence_refused\",\n\toutboxRelayCyclesStarted: \"fabric.platform.outbox.relay_cycles.started\",\n\toutboxRelayCyclesCompleted: \"fabric.platform.outbox.relay_cycles.completed\",\n\toutboxRelayCyclesFailed: \"fabric.platform.outbox.relay_cycles.failed\",\n\toutboxLeaseClaimed: \"fabric.platform.outbox.lease_claimed\",\n\toutboxPublished: \"fabric.platform.outbox.published\",\n\toutboxFailed: \"fabric.platform.outbox.failed\",\n\toutboxDeadLettered: \"fabric.platform.outbox.dead_lettered\",\n\toutboxRequeued: \"fabric.platform.outbox.requeued\",\n\toutboxRequeueRefused: \"fabric.platform.outbox.requeue_refused\",\n\tinvocationBacklog: \"fabric.platform.invocation.backlog\",\n\tinvocationRunning: \"fabric.platform.invocation.running\",\n\tinvocationExpiredLeases: \"fabric.platform.invocation.expired_leases\",\n\tinvocationApprovalWaits: \"fabric.platform.invocation.approval_waits\",\n\tinvocationReconciliationRequiredGauge: \"fabric.platform.invocation.reconciliation_required.count\",\n\toutboxBacklog: \"fabric.platform.outbox.backlog\",\n\toutboxExpiredLeases: \"fabric.platform.outbox.expired_leases\",\n\toutboxDeadLetters: \"fabric.platform.outbox.dead_letters\",\n} as const;\n\nexport type PlatformHostMetricName =\n\t(typeof PLATFORM_HOST_METRIC_NAMES)[keyof typeof PLATFORM_HOST_METRIC_NAMES];\n\nexport type PlatformHostTelemetryEventName =\n\t| \"worker.cycle.started\"\n\t| \"worker.cycle.completed\"\n\t| \"worker.cycle.failed\"\n\t| \"invocation.submitted\"\n\t| \"invocation.admission_refused\"\n\t| \"invocation.execution_started\"\n\t| \"invocation.lease_claimed\"\n\t| \"invocation.completed\"\n\t| \"invocation.failed\"\n\t| \"invocation.policy_blocked\"\n\t| \"invocation.validation_failed\"\n\t| \"invocation.approval_waited\"\n\t| \"invocation.reconciliation_required\"\n\t| \"invocation.adapter_evidence_refused\"\n\t| \"outbox.relay.started\"\n\t| \"outbox.relay.completed\"\n\t| \"outbox.relay.failed\"\n\t| \"outbox.lease_claimed\"\n\t| \"outbox.published\"\n\t| \"outbox.failed\"\n\t| \"outbox.dead_lettered\"\n\t| \"outbox.requeued\"\n\t| \"outbox.requeue_refused\";\n\nexport type PlatformHostMetricType = \"counter\" | \"gauge\";\nexport type PlatformHostTelemetryAttribute = string | number | boolean;\n\nexport interface PlatformHostLifecycleTelemetry {\n\tkind: \"event\";\n\tname: PlatformHostTelemetryEventName;\n\tmetricName: PlatformHostMetricName;\n\tmetricType: \"counter\";\n\toccurredAt: Date;\n\ttenantId?: string;\n\tspaceId?: string;\n\tattributes?: Readonly<Record<string, PlatformHostTelemetryAttribute>>;\n}\n\nexport interface PlatformHostMetricTelemetry {\n\tkind: \"metric\";\n\tname: PlatformHostMetricName;\n\tmetricType: PlatformHostMetricType;\n\tvalue: number;\n\tobservedAt: Date;\n\ttenantId?: string;\n\tspaceId?: string;\n}\n\nexport type PlatformHostTelemetryRecord =\n\t| PlatformHostLifecycleTelemetry\n\t| PlatformHostMetricTelemetry;\n\nexport type PlatformHostTelemetryHook = (\n\trecord: PlatformHostTelemetryRecord,\n) => void | Promise<void>;\n\n/**\n * A deliberately small sink contract. No OpenTelemetry, Prometheus, or\n * vendor SDK is required by Platform Host.\n */\nexport type PlatformHostTelemetry =\n\t| PlatformHostTelemetryHook\n\t| { record: PlatformHostTelemetryHook };\n\nexport type PlatformHostTelemetryInput =\n\t| Omit<PlatformHostLifecycleTelemetry, \"occurredAt\" | \"metricType\"> & { occurredAt?: Date }\n\t| Omit<PlatformHostMetricTelemetry, \"observedAt\"> & { observedAt?: Date };\n\n/**\n * Telemetry is best effort and must never change governed mutation behavior.\n * Promise-returning hooks are detached and rejected hooks are swallowed.\n */\nexport function emitPlatformHostTelemetry(\n\ttelemetry: PlatformHostTelemetry | undefined,\n\tinput: PlatformHostTelemetryInput,\n): void {\n\tif (!telemetry) return;\n\tconst record = input.kind === \"event\"\n\t\t? { ...input, metricType: \"counter\" as const, occurredAt: input.occurredAt ?? new Date() }\n\t\t: { ...input, observedAt: input.observedAt ?? new Date() };\n\ttry {\n\t\tconst result = typeof telemetry === \"function\"\n\t\t\t? telemetry(record)\n\t\t\t: telemetry.record(record);\n\t\tif (isPromiseLike(result)) void result.catch(() => undefined);\n\t} catch {\n\t\t// Observability outages must not fail a mutation or worker checkpoint.\n\t}\n}\n\nexport interface PlatformHostHealthQuery {\n\ttenantId?: string;\n\tspaceId?: string;\n\tnow: Date;\n}\n\nexport interface PlatformHostHealthCounts {\n\tinvocationBacklog: number;\n\tinvocationRunning: number;\n\tinvocationExpiredLeases: number;\n\tinvocationApprovalWaits: number;\n\tinvocationReconciliationRequired: number;\n\toutboxBacklog: number;\n\toutboxExpiredLeases: number;\n\toutboxDeadLetters: number;\n}\n\nexport interface PlatformHostWorkerHealthInput {\n\tlastHeartbeatAt: Date;\n\tstaleAfterMs: number;\n}\n\nexport interface PlatformHostHealthOptions<TDb> {\n\tstore: PlatformHostStore<TDb>;\n\ttenantId?: string;\n\tspaceId?: string;\n\tnow?: () => Date;\n\t/**\n\t * Worker liveness is supplied by the deployment's supervisor or telemetry\n\t * bridge. Only aggregate healthy/stale counts are returned.\n\t */\n\tworkers?: readonly PlatformHostWorkerHealthInput[];\n\ttelemetry?: PlatformHostTelemetry;\n}\n\nexport interface PlatformHostHealthStore<TDb> extends RecoverablePlatformHostStore<TDb> {\n\tgetHealthCounts(input: PlatformHostHealthQuery): Promise<PlatformHostHealthCounts>;\n}\n\nexport type PlatformHostHealthStatus = \"healthy\" | \"degraded\" | \"unhealthy\";\n\nexport interface PlatformHostHealthSnapshot {\n\tcontractVersion: typeof PLATFORM_HOST_HEALTH_CONTRACT_VERSION;\n\tgeneratedAt: Date;\n\tscope: { tenantId?: string; spaceId?: string };\n\tdataAvailable: boolean;\n\tstatus: PlatformHostHealthStatus;\n\treadiness: {\n\t\tready: boolean;\n\t\treasonCodes: readonly PlatformHostReadinessReason[];\n\t};\n\tworkers: {\n\t\treported: number;\n\t\thealthy: number;\n\t\tstale: number;\n\t};\n\tinvocations: {\n\t\tbacklog: number;\n\t\trunning: number;\n\t\texpiredLeases: number;\n\t\tapprovalWaits: number;\n\t\treconciliationRequired: number;\n\t};\n\toutbox: {\n\t\tbacklog: number;\n\t\texpiredLeases: number;\n\t\tdeadLetters: number;\n\t};\n}\n\nexport type PlatformHostReadinessReason =\n\t| \"health_source_unavailable\"\n\t| \"workers_stale\"\n\t| \"invocation_expired_leases\"\n\t| \"outbox_expired_leases\"\n\t| \"outbox_dead_letters\"\n\t| \"reconciliation_required\";\n\n/**\n * Read tenant/space-scoped operational counts without returning invocation,\n * actor, parameter, error, event, or adapter data.\n */\nexport async function getPlatformHostHealthSnapshot<TDb>(\n\toptions: PlatformHostHealthOptions<TDb>,\n): Promise<PlatformHostHealthSnapshot> {\n\tconst generatedAt = options.now?.() ?? new Date();\n\tconst workerSummary = summarizeWorkers(options.workers ?? [], generatedAt);\n\tconst scope = {\n\t\t...(options.tenantId ? { tenantId: options.tenantId } : {}),\n\t\t...(options.spaceId ? { spaceId: options.spaceId } : {}),\n\t};\n\n\ttry {\n\t\tconst counts = await readHealthCounts(options.store, {\n\t\t\t...(options.tenantId ? { tenantId: options.tenantId } : {}),\n\t\t\t...(options.spaceId ? { spaceId: options.spaceId } : {}),\n\t\t\tnow: generatedAt,\n\t\t});\n\t\tconst snapshot = createHealthSnapshot(\n\t\t\tgeneratedAt,\n\t\t\tscope,\n\t\t\tcounts,\n\t\t\tworkerSummary,\n\t\t\ttrue,\n\t\t);\n\t\temitHealthMetrics(options.telemetry, snapshot);\n\t\treturn snapshot;\n\t} catch {\n\t\tconst snapshot = createHealthSnapshot(\n\t\t\tgeneratedAt,\n\t\t\tscope,\n\t\t\tzeroHealthCounts(),\n\t\t\tworkerSummary,\n\t\t\tfalse,\n\t\t);\n\t\temitHealthMetrics(options.telemetry, snapshot);\n\t\treturn snapshot;\n\t}\n}\n\nasync function readHealthCounts<TDb>(\n\tstore: PlatformHostStore<TDb>,\n\tquery: PlatformHostHealthQuery,\n): Promise<PlatformHostHealthCounts> {\n\tconst candidate = store as PlatformHostStore<TDb> & {\n\t\tgetHealthCounts?: (input: PlatformHostHealthQuery) => Promise<PlatformHostHealthCounts>;\n\t};\n\tif (typeof candidate.getHealthCounts === \"function\") {\n\t\treturn assertHealthCounts(await candidate.getHealthCounts(query));\n\t}\n\n\t// Compatibility fallback for custom stores that predate the aggregate seam.\n\tconst recoverable = store as Partial<RecoverablePlatformHostStore<TDb>>;\n\tconst outbox = store as Partial<OutboxPlatformHostStore<TDb>>;\n\tif (typeof recoverable.listActionInvocations !== \"function\") {\n\t\tthrow new Error(\"Health counts are not supported by this store.\");\n\t}\n\tconst invocations = await recoverable.listActionInvocations({\n\t\t...(query.tenantId ? { tenantId: query.tenantId } : {}),\n\t\t...(query.spaceId ? { spaceId: query.spaceId } : {}),\n\t\tlimit: Number.MAX_SAFE_INTEGER,\n\t});\n\tconst outboxRecords = typeof outbox.listOutbox === \"function\"\n\t\t? await outbox.listOutbox({\n\t\t\t...(query.tenantId ? { tenantId: query.tenantId } : {}),\n\t\t\t...(query.spaceId ? { spaceId: query.spaceId } : {}),\n\t\t})\n\t\t: [];\n\treturn countsFromRecords(invocations, outboxRecords, query.now);\n}\n\nfunction countsFromRecords(\n\tinvocations: readonly ActionInvocationRecord[],\n\toutbox: readonly { status: string; leaseExpiresAt?: Date }[],\n\tnow: Date,\n): PlatformHostHealthCounts {\n\treturn {\n\t\tinvocationBacklog: invocations.filter((item) => item.status === \"pending\").length,\n\t\tinvocationRunning: invocations.filter((item) => item.status === \"running\").length,\n\t\tinvocationExpiredLeases: invocations.filter((item) =>\n\t\t\titem.status === \"running\" &&\n\t\t\titem.leaseExpiresAt !== undefined &&\n\t\t\titem.leaseExpiresAt.getTime() <= now.getTime(),\n\t\t).length,\n\t\tinvocationApprovalWaits: invocations.filter((item) => item.status === \"waiting_for_approval\").length,\n\t\tinvocationReconciliationRequired: invocations.filter((item) => item.status === \"reconciliation_required\").length,\n\t\toutboxBacklog: outbox.filter((item) => item.status === \"pending\").length,\n\t\toutboxExpiredLeases: outbox.filter((item) =>\n\t\t\titem.status === \"pending\" &&\n\t\t\titem.leaseExpiresAt !== undefined &&\n\t\t\titem.leaseExpiresAt.getTime() <= now.getTime(),\n\t\t).length,\n\t\toutboxDeadLetters: outbox.filter((item) => item.status === \"dead_letter\").length,\n\t};\n}\n\nfunction assertHealthCounts(value: PlatformHostHealthCounts): PlatformHostHealthCounts {\n\tfor (const [name, count] of Object.entries(value)) {\n\t\tif (!Number.isSafeInteger(count) || count < 0) {\n\t\t\tthrow new Error(`Invalid health count: ${name}`);\n\t\t}\n\t}\n\treturn value;\n}\n\nfunction zeroHealthCounts(): PlatformHostHealthCounts {\n\treturn {\n\t\tinvocationBacklog: 0,\n\t\tinvocationRunning: 0,\n\t\tinvocationExpiredLeases: 0,\n\t\tinvocationApprovalWaits: 0,\n\t\tinvocationReconciliationRequired: 0,\n\t\toutboxBacklog: 0,\n\t\toutboxExpiredLeases: 0,\n\t\toutboxDeadLetters: 0,\n\t};\n}\n\nfunction summarizeWorkers(\n\tworkers: readonly PlatformHostWorkerHealthInput[],\n\tnow: Date,\n): PlatformHostHealthSnapshot[\"workers\"] {\n\tlet healthy = 0;\n\tlet stale = 0;\n\tfor (const worker of workers) {\n\t\tif (\n\t\t\tNumber.isFinite(worker.staleAfterMs) &&\n\t\t\tworker.staleAfterMs >= 0 &&\n\t\t\tworker.lastHeartbeatAt.getTime() + worker.staleAfterMs >= now.getTime()\n\t\t) healthy += 1;\n\t\telse stale += 1;\n\t}\n\treturn { reported: workers.length, healthy, stale };\n}\n\nfunction createHealthSnapshot(\n\tgeneratedAt: Date,\n\tscope: PlatformHostHealthSnapshot[\"scope\"],\n\tcounts: PlatformHostHealthCounts,\n\tworkers: PlatformHostHealthSnapshot[\"workers\"],\n\tdataAvailable: boolean,\n): PlatformHostHealthSnapshot {\n\tconst reasonCodes: PlatformHostReadinessReason[] = [];\n\tif (!dataAvailable) reasonCodes.push(\"health_source_unavailable\");\n\tif (workers.stale > 0) reasonCodes.push(\"workers_stale\");\n\tif (counts.invocationExpiredLeases > 0) reasonCodes.push(\"invocation_expired_leases\");\n\tif (counts.outboxExpiredLeases > 0) reasonCodes.push(\"outbox_expired_leases\");\n\tif (counts.outboxDeadLetters > 0) reasonCodes.push(\"outbox_dead_letters\");\n\tif (counts.invocationReconciliationRequired > 0) reasonCodes.push(\"reconciliation_required\");\n\tconst unhealthy = !dataAvailable;\n\tconst degraded = unhealthy || reasonCodes.length > 0;\n\treturn {\n\t\tcontractVersion: PLATFORM_HOST_HEALTH_CONTRACT_VERSION,\n\t\tgeneratedAt,\n\t\tscope,\n\t\tdataAvailable,\n\t\tstatus: unhealthy ? \"unhealthy\" : degraded ? \"degraded\" : \"healthy\",\n\t\treadiness: {\n\t\t\tready: dataAvailable && workers.stale === 0,\n\t\t\treasonCodes,\n\t\t},\n\t\tworkers,\n\t\tinvocations: {\n\t\t\tbacklog: counts.invocationBacklog,\n\t\t\trunning: counts.invocationRunning,\n\t\t\texpiredLeases: counts.invocationExpiredLeases,\n\t\t\tapprovalWaits: counts.invocationApprovalWaits,\n\t\t\treconciliationRequired: counts.invocationReconciliationRequired,\n\t\t},\n\t\toutbox: {\n\t\t\tbacklog: counts.outboxBacklog,\n\t\t\texpiredLeases: counts.outboxExpiredLeases,\n\t\t\tdeadLetters: counts.outboxDeadLetters,\n\t\t},\n\t};\n}\n\nfunction emitHealthMetrics(\n\ttelemetry: PlatformHostTelemetry | undefined,\n\tsnapshot: PlatformHostHealthSnapshot,\n): void {\n\tconst scope = {\n\t\t...(snapshot.scope.tenantId ? { tenantId: snapshot.scope.tenantId } : {}),\n\t\t...(snapshot.scope.spaceId ? { spaceId: snapshot.scope.spaceId } : {}),\n\t};\n\tconst metrics: Array<[PlatformHostMetricName, number]> = [\n\t\t[PLATFORM_HOST_METRIC_NAMES.invocationBacklog, snapshot.invocations.backlog],\n\t\t[PLATFORM_HOST_METRIC_NAMES.invocationRunning, snapshot.invocations.running],\n\t\t[PLATFORM_HOST_METRIC_NAMES.invocationExpiredLeases, snapshot.invocations.expiredLeases],\n\t\t[PLATFORM_HOST_METRIC_NAMES.invocationApprovalWaits, snapshot.invocations.approvalWaits],\n\t\t[PLATFORM_HOST_METRIC_NAMES.invocationReconciliationRequiredGauge, snapshot.invocations.reconciliationRequired],\n\t\t[PLATFORM_HOST_METRIC_NAMES.outboxBacklog, snapshot.outbox.backlog],\n\t\t[PLATFORM_HOST_METRIC_NAMES.outboxExpiredLeases, snapshot.outbox.expiredLeases],\n\t\t[PLATFORM_HOST_METRIC_NAMES.outboxDeadLetters, snapshot.outbox.deadLetters],\n\t];\n\tfor (const [name, value] of metrics) {\n\t\temitPlatformHostTelemetry(telemetry, {\n\t\t\tkind: \"metric\",\n\t\t\tname,\n\t\t\tmetricType: \"gauge\",\n\t\t\tvalue,\n\t\t\t...scope,\n\t\t\tobservedAt: snapshot.generatedAt,\n\t\t});\n\t}\n}\n\nfunction isPromiseLike(value: unknown): value is PromiseLike<void> {\n\treturn Boolean(\n\t\tvalue &&\n\t\ttypeof value === \"object\" &&\n\t\t\"then\" in value &&\n\t\ttypeof (value as { then?: unknown }).then === \"function\",\n\t);\n}\n","import { createHash } from \"node:crypto\";\nimport type {\n\tActionId,\n\tActionStatus,\n} from \"@fabricorg/platform\";\nimport type {\n\tAtomicMutationPlatformHostStore,\n\tErrorTextRedactionContext,\n\tGovernancePlatformHostStore,\n\tPlatformHostOptions,\n} from \"./types\";\nimport { emitPlatformHostTelemetry, PLATFORM_HOST_METRIC_NAMES } from \"./observability\";\n\n// Helpers the host and its lifecycle modules share. Nothing here is public.\n\nexport function asAtomicMutationStore<TDb>(\n\tstore: PlatformHostOptions<TDb>[\"store\"],\n): AtomicMutationPlatformHostStore<TDb> | undefined {\n\tconst candidate = store as Partial<AtomicMutationPlatformHostStore<TDb>>;\n\treturn typeof candidate.transactionWithEvents === \"function\"\n\t\t? (store as AtomicMutationPlatformHostStore<TDb>)\n\t\t: undefined;\n}\n\nexport function asGovernanceStore<TDb>(\n\tstore: PlatformHostOptions<TDb>[\"store\"],\n): GovernancePlatformHostStore<TDb> | undefined {\n\tconst candidate = store as Partial<GovernancePlatformHostStore<TDb>>;\n\treturn typeof candidate.recordMutationGovernance === \"function\" &&\n\t\ttypeof candidate.appendPolicyObligations === \"function\" &&\n\t\ttypeof candidate.appendExecutionAttestation === \"function\"\n\t\t? (store as GovernancePlatformHostStore<TDb>)\n\t\t: undefined;\n}\n\nexport function withoutPrivateHostFields(\n\tdata: Record<string, unknown>,\n\teventResultFields: readonly string[],\n): Record<string, unknown> {\n\treturn Object.fromEntries(\n\t\tObject.entries(data).filter(([key]) => !eventResultFields.includes(key)),\n\t);\n}\n\nexport function errorMessage(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n\n/** Marks Host-authored error text so a catch does not redact its identifiers. */\nexport class HostError extends Error {}\n\n/** The record predicate used for adapter output construction and redactor returns. */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n\treturn Boolean(value && typeof value === \"object\" && !Array.isArray(value));\n}\n\nexport function tryRedactErrorText(\n\thook: PlatformHostOptions<unknown>[\"redactErrorText\"],\n\tcontext: ErrorTextRedactionContext,\n\tmessage: string,\n): { success: true; text: string } | { success: false } {\n\t// Preserve the no-hook behavior for empty originating errors without invoking the hook.\n\tif (!hook || message === \"\") return { success: true, text: message };\n\ttry {\n\t\tconst text = hook(context, message);\n\t\tif (typeof text === \"string\" && text.length > 0) return { success: true, text };\n\t} catch {\n\t\t// A completion can refuse this input; execution paths need a safe placeholder.\n\t}\n\treturn { success: false };\n}\n\nexport function redactErrorText(\n\thook: PlatformHostOptions<unknown>[\"redactErrorText\"],\n\tcontext: ErrorTextRedactionContext,\n\tmessage: string,\n): string {\n\tconst result = tryRedactErrorText(hook, context, message);\n\treturn result.success ? result.text : \"Error text withheld: the error-text redactor failed.\";\n}\n\n// A key longer than this is cut, and two keys that differ only after the cut\n// would share an id, so the cut key ends in a digest of the whole raw key.\n// Keys within the limit keep the ids they always had, so records written by\n// earlier releases still match on retry and recovery. A cut key is one\n// character longer than the limit, so no key that fits can spell it.\nconst LIFECYCLE_KEY_LIMIT = 96;\n\nexport function lifecycleId(prefix: string, invocationId: string, key: string): string {\n\tconst safeKey = key.replace(/[^a-zA-Z0-9_-]/g, \"_\");\n\tif (safeKey.length <= LIFECYCLE_KEY_LIMIT) return `${prefix}_${invocationId}_${safeKey}`;\n\tconst digest = createHash(\"sha256\").update(key).digest(\"hex\").slice(0, 32);\n\treturn `${prefix}_${invocationId}_${safeKey.slice(0, LIFECYCLE_KEY_LIMIT - digest.length)}_${digest}`;\n}\n\nexport function emitInvocationStatusTelemetry(\n\tinvocation: {\n\t\tid: string;\n\t\ttenantId: string;\n\t\tspaceId: string;\n\t\tactionId?: ActionId;\n\t\tactionVersion?: number;\n\t},\n\tstatus: ActionStatus | undefined,\n\ttelemetry: PlatformHostOptions<unknown>[\"telemetry\"],\n\toccurredAt: Date,\n\tpreviousStatus?: ActionStatus,\n): void {\n\tif (!status || status === previousStatus) return;\n\tconst event = status === \"completed\"\n\t\t? { name: \"invocation.completed\" as const, metricName: PLATFORM_HOST_METRIC_NAMES.invocationCompleted }\n\t\t: status === \"blocked_by_policy\"\n\t\t\t? { name: \"invocation.policy_blocked\" as const, metricName: PLATFORM_HOST_METRIC_NAMES.invocationPolicyBlocked }\n\t\t\t: status === \"validation_failed\"\n\t\t\t\t? { name: \"invocation.validation_failed\" as const, metricName: PLATFORM_HOST_METRIC_NAMES.invocationValidationFailed }\n\t\t\t\t: status === \"waiting_for_approval\"\n\t\t\t\t\t? { name: \"invocation.approval_waited\" as const, metricName: PLATFORM_HOST_METRIC_NAMES.invocationApprovalWaited }\n\t\t\t\t\t: status === \"reconciliation_required\"\n\t\t\t\t\t\t? { name: \"invocation.reconciliation_required\" as const, metricName: PLATFORM_HOST_METRIC_NAMES.invocationReconciliationRequired }\n\t\t\t\t\t\t: status === \"failed\"\n\t\t\t\t\t\t\t? { name: \"invocation.failed\" as const, metricName: PLATFORM_HOST_METRIC_NAMES.invocationFailed }\n\t\t\t\t\t\t\t: undefined;\n\tif (!event) return;\n\temitPlatformHostTelemetry(telemetry, {\n\t\tkind: \"event\",\n\t\tname: event.name,\n\t\tmetricName: event.metricName,\n\t\toccurredAt,\n\t\ttenantId: invocation.tenantId,\n\t\tspaceId: invocation.spaceId,\n\t\tattributes: {\n\t\t\t...(invocation.actionId ? { actionId: invocation.actionId } : {}),\n\t\t\t...(invocation.actionVersion !== undefined ? { actionVersion: invocation.actionVersion } : {}),\n\t\t\t...(previousStatus ? { fromStatus: previousStatus } : {}),\n\t\t},\n\t});\n}\n\nexport class RecoverableFinalizationError extends Error {\n\toverride readonly name = \"RecoverableFinalizationError\";\n}\n\n/** Completion absence is significant: callbacks may retain the same status/error. */\nexport function matchesSettledInvocation(\n\trecord: import(\"./types\").ActionInvocationRecord,\n\tcondition: Extract<import(\"./types\").AdapterInvocationWriteCondition, { kind: \"verdict\" }>,\n\tcheckCompletion = true,\n): boolean {\n\treturn ![\"pending\", \"running\", \"waiting_for_approval\"].includes(condition.status)\n\t\t&& record.status === condition.status && record.error === condition.error\n\t\t&& (!checkCompletion || (condition.externalCompletionDigest === undefined ? record.externalCompletion === undefined\n\t\t\t: record.externalCompletion?.digest === condition.externalCompletionDigest));\n}\n","import { createHash } from \"node:crypto\";\nimport type { ActionDefinition, ActionId } from \"@fabricorg/platform\";\nimport type {\n\tActionInvocationPatch,\n\tActionInvocationRecord,\n\tExecuteActionResult,\n\tExternalCompletion,\n\tPendingAssetEvent,\n\tPlatformHostMutationTransaction,\n\tPlatformHostOptions,\n\tRecordedExternalCompletion,\n\tRecoverablePlatformHostStore,\n\tReconcileOverdueCompletionsInput,\n} from \"./types\";\nimport { ExternalCompletionError } from \"./types\";\nimport { canonicalJson } from \"./command-identity\";\nimport {\n\tasAtomicMutationStore,\n\tasGovernanceStore,\n\temitInvocationStatusTelemetry,\n\tlifecycleId,\n\tHostError,\n\ttryRedactErrorText,\n\tisRecord,\n\twithoutPrivateHostFields,\n} from \"./host-internals\";\n\n// ── External completion lifecycle ───────────────────────────────────────────\n//\n// An adapter hands work to an external system that finishes it later and\n// calls back. This module owns everything after the handoff is recorded:\n// settling the invocation by reference, absorbing repeats, catching\n// contradictions, surfacing overdue handoffs. The host's adapter loop owns\n// the handoff itself, since that happens mid-execution. What is shared with\n// the host is passed in, so the host stays the only thing that writes\n// invocations through a lease.\n\nexport interface ExternalCompletionDeps<TDb> {\n\tstore: PlatformHostOptions<TDb>[\"store\"];\n\ttelemetry: PlatformHostOptions<TDb>[\"telemetry\"];\n\tredactErrorText?: PlatformHostOptions<TDb>[\"redactErrorText\"];\n\tredactExternalCompletionResult?: PlatformHostOptions<TDb>[\"redactExternalCompletionResult\"];\n\teventResultFields: readonly string[];\n\tnow(): Date;\n\tactionResolver(actionId: ActionId): ActionDefinition<TDb> | undefined;\n\tappendEvent(\n\t\tinvocation: ActionInvocationRecord,\n\t\tevent: PendingAssetEvent,\n\t\tdeduplicationKey: string,\n\t\tdefaultEventSchemaVersion?: number,\n\t\ttransaction?: PlatformHostMutationTransaction<TDb>,\n\t): Promise<void>;\n\tactionResult(invocation: ActionInvocationRecord): ExecuteActionResult;\n\twithConsistency<TResult extends { actionInvocationId: string }>(result: TResult, actionId: ActionId): TResult;\n}\n\nexport interface ExternalCompletionLifecycle {\n\tcompleteExternalInvocation(actionInvocationId: string, tenantId: string, spaceId: string, completion: ExternalCompletion): Promise<ExecuteActionResult>;\n\treconcileOverdueCompletions(input?: ReconcileOverdueCompletionsInput): Promise<{ overdue: string[] }>;\n\trecordCompletionReconciliation(\n\t\tinvocation: ActionInvocationRecord,\n\t\tcompletion: Pick<ExternalCompletion, \"externalReference\" | \"evidenceReferences\"> & { provider?: string; kind?: string },\n\t\treason: string,\n\t\ttransaction?: Pick<PlatformHostMutationTransaction<unknown>, \"appendExternalReconciliation\">,\n\t): Promise<void>;\n}\n\nexport function createExternalCompletionLifecycle<TDb>(deps: ExternalCompletionDeps<TDb>): ExternalCompletionLifecycle {\n\tconst { now, actionResolver, appendEvent, actionResult, withConsistency, eventResultFields } = deps;\n\n\tasync function completeExternalInvocation(\n\t\tactionInvocationId: string,\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t\tcompletion: ExternalCompletion,\n\t): Promise<ExecuteActionResult> {\n\t\tif (typeof completion.externalReference !== \"string\" || completion.externalReference.trim() === \"\") {\n\t\t\tthrow new ExternalCompletionError(\"invalid_completion\", \"External completion must name the external reference it completes.\");\n\t\t}\n\t\tif (completion.outcome !== \"completed\" && completion.outcome !== \"failed\") {\n\t\t\tthrow new ExternalCompletionError(\"invalid_completion\", `External completion outcome must be \"completed\" or \"failed\", received \"${String(completion.outcome)}\".`);\n\t\t}\n\t\t// Read, decide, and write under one lock where the store can give one,\n\t\t// so two callbacks racing cannot both read \"nothing recorded yet\" and\n\t\t// both write. A base store without transactions keeps the narrower\n\t\t// read-then-write window; that is a property of the store, not of this\n\t\t// path, and the contract documents it.\n\t\tconst atomicStore = asAtomicMutationStore(deps.store);\n\t\tif (atomicStore) {\n\t\t\treturn atomicStore.transactionWithEvents(async (transaction) => {\n\t\t\t\tconst read = transaction.getActionInvocationForUpdate\n\t\t\t\t\t? await transaction.getActionInvocationForUpdate(actionInvocationId, tenantId, spaceId)\n\t\t\t\t\t: await deps.store.getActionInvocation(actionInvocationId, tenantId, spaceId);\n\t\t\t\treturn settleExternalCompletion(read, actionInvocationId, completion, {\n\t\t\t\t\tupdate: (patch) => transaction.updateActionInvocation(actionInvocationId, tenantId, spaceId, patch),\n\t\t\t\t\ttransaction,\n\t\t\t\t});\n\t\t\t});\n\t\t}\n\t\tconst read = await deps.store.getActionInvocation(actionInvocationId, tenantId, spaceId);\n\t\treturn settleExternalCompletion(read, actionInvocationId, completion, {\n\t\t\tupdate: (patch) => deps.store.updateActionInvocation(actionInvocationId, tenantId, spaceId, patch),\n\t\t});\n\t}\n\n\tasync function settleExternalCompletion(\n\t\tinvocation: ActionInvocationRecord | undefined,\n\t\tactionInvocationId: string,\n\t\tcompletion: ExternalCompletion,\n\t\twriter: {\n\t\t\tupdate: (patch: ActionInvocationPatch) => Promise<void>;\n\t\t\ttransaction?: PlatformHostMutationTransaction<TDb>;\n\t\t},\n\t): Promise<ExecuteActionResult> {\n\t\tif (!invocation) throw new ExternalCompletionError(\"not_found\", `ActionInvocation not found: ${actionInvocationId}`);\n\t\tconst recorded = invocation.externalCompletion;\n\t\tconst stillExecuting = !recorded && (\n\t\t\tinvocation.status === \"pending\"\n\t\t\t|| (invocation.status === \"running\" && (invocation.leaseOwner !== undefined || invocation.pendingCompletion?.parkedAt === undefined))\n\t\t);\n\t\tif (stillExecuting) {\n\t\t\t// The invocation has not parked: it is dispatched and not yet run, a\n\t\t\t// worker still holds it, or an inline execution recorded the handoff\n\t\t\t// and is still running the steps after it. Settling now would report\n\t\t\t// completed while effects are still being applied, and finalization\n\t\t\t// would then overwrite the verdict. The handoff is recorded before\n\t\t\t// the steps after it run, so \"not awaiting\" here means \"not yet\".\n\t\t\t// Callbacks arrive at least once; this one is asked to come back.\n\t\t\tthrow new ExternalCompletionError(\"still_executing\", `ActionInvocation ${actionInvocationId} is still executing; retry the completion after it parks.`);\n\t\t}\n\t\tif (recorded) {\n\t\t\tif (recorded.externalReference !== completion.externalReference) {\n\t\t\t\tthrow new ExternalCompletionError(\"reference_mismatch\", `ActionInvocation ${actionInvocationId} was completed by \"${recorded.externalReference}\", not \"${completion.externalReference}\".`);\n\t\t\t}\n\t\t\tif (completion.provider !== undefined && recorded.provider !== undefined && completion.provider !== recorded.provider) {\n\t\t\t\tthrow new ExternalCompletionError(\"provider_mismatch\", `ActionInvocation ${actionInvocationId} was completed by \"${recorded.provider}\", not \"${completion.provider}\".`);\n\t\t\t}\n\t\t\tconst provider = recorded.provider ?? completion.provider;\n\t\t\t// Compute the legacy comparison before hooks can modify their input. It stays in memory.\n\t\t\tconst rawDigest = completionDigest(completion, provider);\n\t\t\tif (recorded.digest === rawDigest) return withConsistency(actionResult(invocation), invocation.actionId);\n\t\t\tcompletion = redactCompletion(invocation, completion, provider ?? \"external\");\n\t\t\tconst incomingDigest = completionDigest(completion, provider);\n\t\t\tif (recorded.digest === incomingDigest) {\n\t\t\t\t// The same news twice. Callbacks are at-least-once; this is the once.\n\t\t\t\treturn withConsistency(actionResult(invocation), invocation.actionId);\n\t\t\t}\n\t\t\t// The external system contradicted itself, by flipping the outcome or\n\t\t\t// by reporting the same outcome with different evidence. Neither\n\t\t\t// answer can be trusted over the other, so the first stays on\n\t\t\t// record, the second goes to the reconciliation log, and consumers\n\t\t\t// hear about it.\n\t\t\tconst message = recorded.outcome === completion.outcome\n\t\t\t\t? `External operation \"${completion.externalReference}\" reported ${completion.outcome} again with different evidence.`\n\t\t\t\t: `External operation \"${completion.externalReference}\" reported ${completion.outcome} after reporting ${recorded.outcome}.`;\n\t\t\tawait recordCompletionReconciliation(invocation, { ...completion, kind: `contradicted:${incomingDigest.slice(0, 16)}` }, message);\n\t\t\tawait appendEvent(invocation, {\n\t\t\t\teventType: \"ExternalOperationContradicted\",\n\t\t\t\tsubjectType: \"AdapterInvocation\",\n\t\t\t\tsubjectId: invocation.pendingCompletion?.adapterInvocationId ?? actionInvocationId,\n\t\t\t\tpayload: { externalReference: completion.externalReference, recorded: recorded.outcome, reported: completion.outcome },\n\t\t\t}, `external:${completion.externalReference}:contradicted:${completion.outcome}`, 1, writer.transaction);\n\t\t\tawait writer.update({ status: \"reconciliation_required\", error: message });\n\t\t\temitInvocationStatusTelemetry(invocation, \"reconciliation_required\", deps.telemetry, now(), invocation.status);\n\t\t\treturn withConsistency(actionResult({ ...invocation, status: \"reconciliation_required\", error: message }), invocation.actionId);\n\t\t}\n\t\tconst pending = invocation.pendingCompletion;\n\t\tif (!pending) {\n\t\t\tconst action = actionResolver(invocation.actionId);\n\t\t\tif ((action?.execution?.completion ?? \"immediate\") === \"immediate\") {\n\t\t\t\tthrow new ExternalCompletionError(\"immediate_contract\", `Action ${invocation.actionId} declares immediate completion; nothing external completes it.`);\n\t\t\t}\n\t\t\tthrow new ExternalCompletionError(\"not_awaiting\", `ActionInvocation ${actionInvocationId} is not awaiting an external completion.`);\n\t\t}\n\t\tif (pending.externalReference !== completion.externalReference) {\n\t\t\tthrow new ExternalCompletionError(\"reference_mismatch\", `ActionInvocation ${actionInvocationId} awaits \"${pending.externalReference}\", not \"${completion.externalReference}\".`);\n\t\t}\n\t\tif (completion.provider !== undefined && completion.provider !== pending.provider) {\n\t\t\tthrow new ExternalCompletionError(\"provider_mismatch\", `ActionInvocation ${actionInvocationId} awaits completion from \"${pending.provider}\", not \"${completion.provider}\".`);\n\t\t}\n\t\tcompletion = redactCompletion(invocation, completion, completion.provider ?? pending.provider);\n\t\tconst recordedAt = now();\n\t\tconst externalCompletion: RecordedExternalCompletion = {\n\t\t\t// completion has passed the hooks; retain the callback shape for compatibility.\n\t\t\t...completion,\n\t\t\tprovider: completion.provider ?? pending.provider,\n\t\t\tobservedAt: completion.observedAt instanceof Date ? completion.observedAt.toISOString() : completion.observedAt,\n\t\t\trecordedAt,\n\t\t\tdigest: completionDigest(completion, completion.provider ?? pending.provider),\n\t\t};\n\t\tconst subject = { subjectType: \"AdapterInvocation\", subjectId: pending.adapterInvocationId };\n\t\t// Callback adapter writes share the invocation lock and transaction when\n\t\t// its adapter seam is available; legacy stores retain the outer write.\n\t\t// A parked invocation settles by the outcome. One that already ended for\n\t\t// another reason (a later step failed, a contract was violated, a\n\t\t// non-overdue reconciliation was required) keeps its status. The callback\n\t\t// records what happened externally without replacing that verdict.\n\t\tconst settles = (invocation.status === \"running\" && pending.parkedAt !== undefined)\n\t\t\t|| (invocation.status === \"reconciliation_required\" && pending.parkedAt !== undefined\n\t\t\t\t&& (pending.overdueAt !== undefined\n\t\t\t\t\t// 7.x had no typed marker. This weaker compatibility check also\n\t\t\t\t\t// accepts unrelated error text on any parked row lacking the marker.\n\t\t\t\t\t|| invocation.error?.includes(\"did not complete by\") === true));\n\t\tif (completion.outcome === \"completed\") {\n\t\t\tconst action = settles ? actionResolver(invocation.actionId) : undefined;\n\t\t\tconst merged = withoutPrivateHostFields({ ...invocation.result, ...(completion.result ?? {}) }, eventResultFields);\n\t\t\tif (settles && action?.resultSchema) {\n\t\t\t\tconst parsedResult = action.resultSchema.safeParse(merged);\n\t\t\t\tif (!parsedResult.success) {\n\t\t\t\t\tthrow new ExternalCompletionError(\"result_invalid\", `External completion result validation failed at ${parsedResult.error.issues\n\t\t\t\t\t\t.map((issue) => issue.path.map(String).join(\".\") || \"result\")\n\t\t\t\t\t\t.join(\", \")}`);\n\t\t\t\t}\n\t\t\t}\n\t\t\tawait (writer.transaction?.updateAdapterInvocation?.bind(writer.transaction) ?? deps.store.updateAdapterInvocation.bind(deps.store))(pending.adapterInvocationId, {\n\t\t\t\t...(completion.result ? { output: withoutPrivateHostFields(completion.result, eventResultFields) } : {}),\n\t\t\t\tupdatedAt: recordedAt,\n\t\t\t}, { tenantId: invocation.tenantId, spaceId: invocation.spaceId, actionInvocationId: invocation.id });\n\t\t\tawait appendEvent(invocation, {\n\t\t\t\teventType: \"ExternalOperationCompleted\",\n\t\t\t\t...subject,\n\t\t\t\tpayload: { externalReference: pending.externalReference, provider: pending.provider, ...(completion.result ? { result: withoutPrivateHostFields(completion.result, eventResultFields) } : {}) },\n\t\t\t}, `external:${pending.adapterInvocationId}:completed`, 1, writer.transaction);\n\t\t\tconst patch: ActionInvocationPatch = settles\n\t\t\t\t? { status: \"completed\", result: merged, externalCompletion, pendingCompletion: undefined, error: undefined }\n\t\t\t\t: { externalCompletion, pendingCompletion: undefined };\n\t\t\tawait writer.update(patch);\n\t\t\tif (settles) emitInvocationStatusTelemetry(invocation, \"completed\", deps.telemetry, now(), invocation.status);\n\t\t\treturn withConsistency(actionResult({ ...invocation, ...patch, result: settles ? merged : invocation.result, ...(settles ? { error: undefined } : {}) }), invocation.actionId);\n\t\t}\n\t\tconst error = completion.error ?? `External operation \"${pending.externalReference}\" failed.`;\n\t\tawait (writer.transaction?.updateAdapterInvocation?.bind(writer.transaction) ?? deps.store.updateAdapterInvocation.bind(deps.store))(pending.adapterInvocationId, { status: \"failed\", error, updatedAt: recordedAt }, { tenantId: invocation.tenantId, spaceId: invocation.spaceId, actionInvocationId: invocation.id });\n\t\tawait appendEvent(invocation, {\n\t\t\teventType: \"ExternalOperationFailed\",\n\t\t\t...subject,\n\t\t\tpayload: { externalReference: pending.externalReference, provider: pending.provider, error },\n\t\t}, `external:${pending.adapterInvocationId}:failed`, 1, writer.transaction);\n\t\tconst patch: ActionInvocationPatch = settles\n\t\t\t? { status: \"failed\", error, externalCompletion, pendingCompletion: undefined }\n\t\t\t: { externalCompletion, pendingCompletion: undefined };\n\t\tawait writer.update(patch);\n\t\tif (settles) emitInvocationStatusTelemetry(invocation, \"failed\", deps.telemetry, now(), invocation.status);\n\t\treturn withConsistency(actionResult({ ...invocation, ...patch }), invocation.actionId);\n\t}\n\n\tfunction redactCompletion(invocation: ActionInvocationRecord, completion: ExternalCompletion, provider: string): ExternalCompletion {\n\t\tlet result = completion.result;\n\t\tif (result && deps.redactExternalCompletionResult) {\n\t\t\ttry {\n\t\t\t\tresult = deps.redactExternalCompletionResult(invocation.actionId, provider, result);\n\t\t\t\tif (!isRecord(result)) throw new HostError(\"Completion result redactor must return a non-null, non-array object.\");\n\t\t\t} catch {\n\t\t\t\tthrow new ExternalCompletionError(\"redaction_failed\", \"External completion result withheld: the result redactor failed; nothing was recorded.\");\n\t\t\t}\n\t\t}\n\t\tconst error = completion.error == null ? undefined : tryRedactErrorText(deps.redactErrorText,\n\t\t\t{ actionId: invocation.actionId, source: \"external_completion\", provider }, completion.error);\n\t\tif (error && !error.success) {\n\t\t\tthrow new ExternalCompletionError(\"redaction_failed\", \"External completion error withheld: the error-text redactor failed; nothing was recorded.\");\n\t\t}\n\t\treturn {\n\t\t\t...completion,\n\t\t\t...(completion.result !== undefined ? { result } : {}),\n\t\t\t...(error?.success ? { error: error.text } : {}),\n\t\t};\n\t}\n\n\t/** What a completion says, minus when it was said. */\n\tfunction completionDigest(completion: ExternalCompletion, provider: string | undefined): string {\n\t\treturn createHash(\"sha256\").update(canonicalJson({\n\t\t\tprovider: provider ?? null,\n\t\t\texternalReference: completion.externalReference,\n\t\t\toutcome: completion.outcome,\n\t\t\tresult: completion.result ?? null,\n\t\t\terror: completion.error ?? null,\n\t\t\tevidenceReferences: completion.evidenceReferences ?? null,\n\t\t})).digest(\"hex\");\n\t}\n\n\tasync function recordCompletionReconciliation(\n\t\tinvocation: ActionInvocationRecord,\n\t\tcompletion: Pick<ExternalCompletion, \"externalReference\" | \"evidenceReferences\"> & { provider?: string; kind?: string },\n\t\treason: string,\n\t\ttransaction?: Pick<PlatformHostMutationTransaction<unknown>, \"appendExternalReconciliation\">,\n\t): Promise<void> {\n\t\tconst governanceStore = asGovernanceStore(deps.store);\n\t\tif (!governanceStore) throw new HostError(\"External completion reconciliation requires a governance-capable store.\");\n\t\tconst provider = completion.provider ?? invocation.pendingCompletion?.provider ?? invocation.externalCompletion?.provider ?? \"external\";\n\t\t// Deterministic, and hashed so a long vendor reference cannot truncate\n\t\t// two distinct findings into one id.\n\t\tconst seed = createHash(\"sha256\").update(`${provider}\\u0000${completion.externalReference}\\u0000${completion.kind ?? \"refused\"}`).digest(\"hex\").slice(0, 32);\n\t\tconst writer = transaction?.appendExternalReconciliation ? transaction : governanceStore;\n\t\tawait writer.appendExternalReconciliation!({\n\t\t\tid: lifecycleId(\"rec\", invocation.id, `ext:${seed}`),\n\t\t\tactionInvocationId: invocation.id,\n\t\t\ttenantId: invocation.tenantId,\n\t\t\tspaceId: invocation.spaceId,\n\t\t\tstatus: \"pending\",\n\t\t\tprovider,\n\t\t\texternalOperationId: completion.externalReference,\n\t\t\tattempt: 1,\n\t\t\treason,\n\t\t\t...(completion.evidenceReferences ? { evidenceReferences: completion.evidenceReferences } : {}),\n\t\t\tobservedAt: now(),\n\t\t});\n\t}\n\n\tasync function reconcileOverdueCompletions(\n\t\tinput: ReconcileOverdueCompletionsInput = {},\n\t): Promise<{ overdue: string[] }> {\n\t\tconst recoverable = deps.store as Partial<RecoverablePlatformHostStore<TDb>>;\n\t\tif (!recoverable.listActionInvocations) {\n\t\t\tthrow new HostError(\"Overdue completion reconciliation requires a store that can list invocations.\");\n\t\t}\n\t\tif (!asGovernanceStore(deps.store)) {\n\t\t\tthrow new HostError(\"Overdue completion reconciliation requires a governance-capable store to record its findings.\");\n\t\t}\n\t\tconst current = input.now ?? now();\n\t\tconst listed = await recoverable.listActionInvocations({\n\t\t\tstatuses: [\"running\"],\n\t\t\tcompletionDueBefore: current,\n\t\t\tunleased: true,\n\t\t\t...(input.tenantId ? { tenantId: input.tenantId } : {}),\n\t\t\t...(input.spaceId ? { spaceId: input.spaceId } : {}),\n\t\t\tlimit: Math.max(1, Math.min(input.limit ?? 100, 1_000)),\n\t\t});\n\t\t// Memory stores can return live records. Retain the listed handoff's\n\t\t// identity before waiting on a transaction or another candidate.\n\t\tconst candidates = listed.map((invocation) => ({\n\t\t\t...invocation,\n\t\t\tpendingCompletion: invocation.pendingCompletion ? { ...invocation.pendingCompletion } : undefined,\n\t\t}));\n\t\tconst overdue: string[] = [];\n\t\tconst atomicStore = asAtomicMutationStore(deps.store);\n\t\tlet canLock: boolean | undefined;\n\t\tfor (const candidate of candidates) {\n\t\t\tconst reconcile = async (transaction?: PlatformHostMutationTransaction<TDb>): Promise<boolean> => {\n\t\t\t\tconst invocation = transaction?.getActionInvocationForUpdate\n\t\t\t\t\t? await transaction.getActionInvocationForUpdate(candidate.id, candidate.tenantId, candidate.spaceId)\n\t\t\t\t\t: await deps.store.getActionInvocation(candidate.id, candidate.tenantId, candidate.spaceId);\n\t\t\t\tconst pending = invocation?.pendingCompletion;\n\t\t\t\tif (!invocation || invocation.status !== \"running\" || invocation.leaseOwner != null\n\t\t\t\t\t|| !pending?.dueAt || pending.dueAt.getTime() > current.getTime() || pending.overdueAt !== undefined\n\t\t\t\t\t|| pending.adapterInvocationId !== candidate.pendingCompletion?.adapterInvocationId\n\t\t\t\t\t|| pending.externalReference !== candidate.pendingCompletion?.externalReference) return false;\n\t\t\t\t// Unparked rows can be abandoned inline executions. Surface them,\n\t\t\t\t// but retain the absence of parkedAt so callbacks remain evidence-only.\n\t\t\t\tconst message = `External operation \"${pending.externalReference}\" from ${pending.provider} did not complete by ${pending.dueAt.toISOString()}.`;\n\t\t\t\tawait recordCompletionReconciliation(invocation, { externalReference: pending.externalReference, provider: pending.provider, kind: \"overdue\" }, message, transaction);\n\t\t\t\tawait (transaction ?? deps.store).updateActionInvocation(invocation.id, invocation.tenantId, invocation.spaceId, {\n\t\t\t\t\tstatus: \"reconciliation_required\", error: message, pendingCompletion: { ...pending, overdueAt: current },\n\t\t\t\t});\n\t\t\t\treturn true;\n\t\t\t};\n\t\t\tconst lockedResult = atomicStore && canLock !== false\n\t\t\t\t? await atomicStore.transactionWithEvents((transaction) => {\n\t\t\t\t\tcanLock = !!(transaction.getActionInvocationForUpdate && transaction.updateActionInvocation);\n\t\t\t\t\tif (!canLock) return Promise.resolve(undefined);\n\t\t\t\t\treturn reconcile(transaction);\n\t\t\t\t})\n\t\t\t\t: undefined;\n\t\t\tconst reconciled = lockedResult ?? await reconcile();\n\t\t\tif (reconciled) {\n\t\t\t\toverdue.push(candidate.id);\n\t\t\t\temitInvocationStatusTelemetry(candidate, \"reconciliation_required\", deps.telemetry, now(), \"running\");\n\t\t\t}\n\t\t}\n\t\treturn { overdue };\n\t}\n\n\n\treturn { completeExternalInvocation, reconcileOverdueCompletions, recordCompletionReconciliation };\n}\n","import { types as utilTypes } from \"node:util\";\nimport type { ActionId } from \"@fabricorg/platform\";\nimport type { AuthorizationBinding, InvocationProvenance, SubmitActionInput } from \"./types\";\n\n/*\n * The one read of a caller's `SubmitActionInput` scalar fields.\n * `submitAction` calls `snapshotSubmission` before its first await and reads\n * only the result afterwards, so nothing the caller changes on its object\n * while Host awaits entitlement, `authorize`, a composition callback or an\n * admission check changes the action, scope, actor, correlation, causation,\n * idempotency key, binding id or execution reason Host authorizes, persists\n * or executes.\n *\n * `parameters`, `provenance` and `authorizationBinding` depend on the action.\n * For one that declares `admitSubmission`, `privateSubmission` reads each\n * once, also before the first await, and replaces it with Host's own copy.\n * For every other action they are not snapshotted: the snapshot's fields\n * read the caller's input each time Host reads them, at the points and as\n * often as Host read them before this snapshot existed (README, \"Submission\n * snapshot\").\n *\n * Internal: not exported from the package entry.\n */\n\n/** Thrown when a submission field cannot be read; the message is fixed. */\nexport class SubmissionUnreadableError extends Error {\n\toverride readonly name = \"SubmissionUnreadableError\";\n\tconstructor() {\n\t\tsuper(\"Platform Host submission could not be read as plain data; nothing was recorded.\");\n\t}\n}\n\n/**\n * Everything `submitAction` uses from a submission. The scalar fields are\n * primitives read once. `parameters`, `provenance` and `authorizationBinding`\n * read through to the caller's input (`snapshotSubmission`) until\n * `privateSubmission` replaces them with Host's copies.\n */\nexport interface SubmissionSnapshot {\n\treadonly actionId: ActionId;\n\treadonly tenantId: string;\n\treadonly spaceId: string;\n\treadonly actorId: string;\n\treadonly actorType: SubmitActionInput[\"actorType\"];\n\treadonly correlationId?: string;\n\treadonly causationId?: string;\n\treadonly provenance?: InvocationProvenance;\n\treadonly executionReason?: SubmitActionInput[\"executionReason\"];\n\treadonly idempotencyKey?: string;\n\treadonly authorizationBindingId?: string;\n\treadonly authorizationBinding?: AuthorizationBinding;\n\treadonly parameters: Record<string, unknown>;\n\t/** True when `parameters` is Host's own JSON-data copy (`privateSubmission`, when the copy succeeded). */\n\treadonly parametersArePrivate: boolean;\n}\n\ntype Scalars = Omit<SubmissionSnapshot, \"provenance\" | \"authorizationBinding\" | \"parameters\" | \"parametersArePrivate\">;\n\nclass NotJsonData extends Error {}\n\n/** `{ ok: true, value }` with a private copy, or `{ ok: false }` when `value` is not JSON data or a read threw. */\nexport type JsonDataCopy = { readonly ok: true; readonly value: unknown } | { readonly ok: false };\n\n/**\n * Copy a JSON value into fresh objects and arrays that nothing else holds.\n *\n * Accepted: `null`, strings, booleans, finite numbers (`-0` becomes `0`, as\n * JSON text does), dense arrays whose prototype is `Array.prototype`, and\n * objects whose prototype is `Object.prototype` or `null`. Of an object, the\n * own enumerable string-keyed properties are copied, each read exactly once\n * (a getter runs once); a property whose value is `undefined` is left out,\n * as `JSON.stringify` and the PostgreSQL store's `jsonb` column do. Symbol\n * keys and non-enumerable properties are skipped, as `JSON.stringify` skips\n * them.\n *\n * Refused (`{ ok: false }`): Proxies (`util.types.isProxy`), every other\n * prototype (Date, Map, class instances, boxed primitives, ArrayBuffer,\n * SharedArrayBuffer, typed arrays and DataView among them), functions,\n * symbols, bigints, non-finite numbers, array holes and `undefined` array\n * elements, cycles, nesting deep enough to exhaust the stack, and any read\n * that throws. What a read throws is not kept.\n */\nexport function copyJsonData(value: unknown): JsonDataCopy {\n\ttry {\n\t\treturn { ok: true, value: copy(value, new Set()) };\n\t} catch {\n\t\treturn { ok: false };\n\t}\n}\n\nfunction copy(value: unknown, ancestors: Set<object>): unknown {\n\tif (value === null || typeof value === \"string\" || typeof value === \"boolean\") return value;\n\tif (typeof value === \"number\") {\n\t\tif (!Number.isFinite(value)) throw new NotJsonData();\n\t\treturn value === 0 ? 0 : value;\n\t}\n\tif (typeof value !== \"object\") throw new NotJsonData();\n\t// Checked first: every read below (prototype, keys, descriptors) would\n\t// otherwise run the Proxy's traps.\n\tif (utilTypes.isProxy(value)) throw new NotJsonData();\n\tif (ancestors.has(value)) throw new NotJsonData();\n\tconst prototype = Reflect.getPrototypeOf(value);\n\tancestors.add(value);\n\ttry {\n\t\tif (Array.isArray(value)) {\n\t\t\tif (prototype !== Array.prototype) throw new NotJsonData();\n\t\t\tconst length = value.length;\n\t\t\tconst out: unknown[] = [];\n\t\t\tfor (let index = 0; index < length; index += 1) {\n\t\t\t\tconst descriptor = Reflect.getOwnPropertyDescriptor(value, String(index));\n\t\t\t\tif (descriptor === undefined) throw new NotJsonData();\n\t\t\t\tconst item = readOnce(value, descriptor);\n\t\t\t\tif (item === undefined) throw new NotJsonData();\n\t\t\t\tout.push(copy(item, ancestors));\n\t\t\t}\n\t\t\treturn out;\n\t\t}\n\t\tif (prototype !== Object.prototype && prototype !== null) throw new NotJsonData();\n\t\tconst out: Record<string, unknown> = {};\n\t\tfor (const key of Reflect.ownKeys(value)) {\n\t\t\tif (typeof key !== \"string\") continue;\n\t\t\tconst descriptor = Reflect.getOwnPropertyDescriptor(value, key);\n\t\t\tif (descriptor === undefined || descriptor.enumerable !== true) continue;\n\t\t\tconst item = readOnce(value, descriptor);\n\t\t\tif (item === undefined) continue;\n\t\t\t// defineProperty, not assignment, so a \"__proto__\" key stays an own property.\n\t\t\tReflect.defineProperty(out, key, { value: copy(item, ancestors), enumerable: true, writable: true, configurable: true });\n\t\t}\n\t\treturn out;\n\t} finally {\n\t\tancestors.delete(value);\n\t}\n}\n\nfunction readOnce(target: object, descriptor: PropertyDescriptor): unknown {\n\tif (\"value\" in descriptor) return descriptor.value;\n\treturn descriptor.get ? Reflect.apply(descriptor.get, target, []) : undefined;\n}\n\n/**\n * Read a submission's scalar fields once, in a fixed order. A scalar field\n * must hold a primitive (or be absent); one holding an object, a function or\n * a symbol, a read that throws, or an input that is not an object throws\n * `SubmissionUnreadableError`. None of these can happen for input of the\n * declared types. `parameters`, `provenance` and `authorizationBinding` are\n * not read here: the snapshot's fields of those names read the caller's\n * input each time they are read.\n */\nexport function snapshotSubmission(input: SubmitActionInput): SubmissionSnapshot {\n\tif (input === null || typeof input !== \"object\") throw new SubmissionUnreadableError();\n\tconst scalar = (key: keyof SubmitActionInput): unknown => primitiveOrAbsent(readField(input, key));\n\tconst actionId = scalar(\"actionId\");\n\tconst tenantId = scalar(\"tenantId\");\n\tconst spaceId = scalar(\"spaceId\");\n\tconst actorId = scalar(\"actorId\");\n\tconst actorType = scalar(\"actorType\");\n\tconst correlationId = scalar(\"correlationId\");\n\tconst causationId = scalar(\"causationId\");\n\tconst executionReason = scalar(\"executionReason\");\n\tconst idempotencyKey = scalar(\"idempotencyKey\");\n\tconst authorizationBindingId = scalar(\"authorizationBindingId\");\n\tconst scalars: Scalars = {\n\t\tactionId: actionId as ActionId,\n\t\ttenantId: tenantId as string,\n\t\tspaceId: spaceId as string,\n\t\tactorId: actorId as string,\n\t\tactorType: actorType as SubmitActionInput[\"actorType\"],\n\t\t...(correlationId != null ? { correlationId: correlationId as string } : {}),\n\t\t...(causationId != null ? { causationId: causationId as string } : {}),\n\t\t...(executionReason != null ? { executionReason: executionReason as SubmitActionInput[\"executionReason\"] } : {}),\n\t\t...(idempotencyKey != null ? { idempotencyKey: idempotencyKey as string } : {}),\n\t\t...(authorizationBindingId != null ? { authorizationBindingId: authorizationBindingId as string } : {}),\n\t};\n\tconst live = { ...scalars, parametersArePrivate: false } as SubmissionSnapshot;\n\t// Read through, not copied: the previous Host's reads of these fields,\n\t// unchanged for an action without admitSubmission.\n\tObject.defineProperties(live, {\n\t\tparameters: { get: () => input.parameters, enumerable: true },\n\t\tprovenance: { get: () => input.provenance, enumerable: true },\n\t\tauthorizationBinding: { get: () => input.authorizationBinding, enumerable: true },\n\t});\n\treturn Object.freeze(live);\n}\n\nconst PROVENANCE_SCALARS = [\"source\", \"correlationId\", \"causationId\"] as const;\nconst PROVENANCE_ATTRIBUTES = [\"traceAttributes\", \"auditAttributes\"] as const;\nconst BINDING_FIELDS = [\"id\", \"tenantId\", \"actorId\", \"actionId\", \"parameterDigest\", \"resourceScope\", \"capturedAt\", \"expiresAt\", \"governingMoment\"] as const;\n\n/**\n * The snapshot of a submission to an action that declares\n * `admitSubmission`, with Host's own copies of what the caller could still\n * reach. Reads each of the caller's `parameters`, `provenance` and\n * `authorizationBinding` exactly once. The parameters are copied with\n * `copyJsonData`; when that fails, the caller's object is kept,\n * `parametersArePrivate` stays false, and `submitAction` refuses the\n * submission as `invalid_parameters`. `provenance` and `authorizationBinding`\n * are copied field by field: each declared field is read once (an own or\n * inherited property, a getter included, so a class instance is accepted)\n * and undeclared fields are not copied; a scalar field must hold a\n * primitive, an attribute map must be an object whose own enumerable values\n * are primitives, and a read that throws, or anything else, throws\n * `SubmissionUnreadableError`. A falsy `provenance` or binding is absent.\n */\nexport function privateSubmission(snapshot: SubmissionSnapshot): SubmissionSnapshot {\n\tconst parameters = readField(snapshot, \"parameters\");\n\tconst provenanceRead = readField(snapshot, \"provenance\");\n\tconst bindingRead = readField(snapshot, \"authorizationBinding\");\n\tconst copied = copyJsonData(parameters);\n\tconst provenance = provenanceRead ? copyProvenance(provenanceRead) : undefined;\n\tconst authorizationBinding = bindingRead ? copyBinding(bindingRead) : undefined;\n\treturn Object.freeze({\n\t\tactionId: snapshot.actionId,\n\t\ttenantId: snapshot.tenantId,\n\t\tspaceId: snapshot.spaceId,\n\t\tactorId: snapshot.actorId,\n\t\tactorType: snapshot.actorType,\n\t\t...(snapshot.correlationId !== undefined ? { correlationId: snapshot.correlationId } : {}),\n\t\t...(snapshot.causationId !== undefined ? { causationId: snapshot.causationId } : {}),\n\t\t...(snapshot.executionReason !== undefined ? { executionReason: snapshot.executionReason } : {}),\n\t\t...(snapshot.idempotencyKey !== undefined ? { idempotencyKey: snapshot.idempotencyKey } : {}),\n\t\t...(snapshot.authorizationBindingId !== undefined ? { authorizationBindingId: snapshot.authorizationBindingId } : {}),\n\t\t...(provenance ? { provenance } : {}),\n\t\t...(authorizationBinding ? { authorizationBinding } : {}),\n\t\tparameters: (copied.ok ? copied.value : parameters) as Record<string, unknown>,\n\t\tparametersArePrivate: copied.ok,\n\t});\n}\n\nfunction readField(target: object, key: string): unknown {\n\ttry {\n\t\treturn (target as Record<string, unknown>)[key];\n\t} catch {\n\t\tthrow new SubmissionUnreadableError();\n\t}\n}\n\nfunction primitiveOrAbsent(value: unknown): unknown {\n\tif (value !== null && (typeof value === \"object\" || typeof value === \"function\" || typeof value === \"symbol\")) {\n\t\tthrow new SubmissionUnreadableError();\n\t}\n\treturn value;\n}\n\nfunction objectOf(value: unknown): object {\n\tif (value === null || typeof value !== \"object\") throw new SubmissionUnreadableError();\n\treturn value;\n}\n\nfunction copyFields(source: object, fields: readonly string[]): Record<string, unknown> {\n\tconst out: Record<string, unknown> = {};\n\tfor (const field of fields) {\n\t\tconst value = primitiveOrAbsent(readField(source, field));\n\t\tif (value !== undefined) out[field] = value;\n\t}\n\treturn out;\n}\n\nfunction copyAttributes(source: object, field: string): Record<string, string> | undefined {\n\tconst value = readField(source, field);\n\tif (value === undefined || value === null) return undefined;\n\tconst map = objectOf(value);\n\tlet entries: [string, unknown][];\n\ttry {\n\t\tentries = Object.entries(map);\n\t} catch {\n\t\tthrow new SubmissionUnreadableError();\n\t}\n\tconst out: Record<string, string> = {};\n\tfor (const [key, item] of entries) {\n\t\t// defineProperty, not assignment, so a \"__proto__\" key stays an own property.\n\t\tReflect.defineProperty(out, key, { value: primitiveOrAbsent(item), enumerable: true, writable: true, configurable: true });\n\t}\n\treturn out;\n}\n\nfunction copyProvenance(value: unknown): InvocationProvenance {\n\tconst source = objectOf(value);\n\tconst out = copyFields(source, PROVENANCE_SCALARS);\n\tfor (const field of PROVENANCE_ATTRIBUTES) {\n\t\tconst attributes = copyAttributes(source, field);\n\t\tif (attributes !== undefined) out[field] = attributes;\n\t}\n\treturn out as unknown as InvocationProvenance;\n}\n\nfunction copyBinding(value: unknown): AuthorizationBinding {\n\treturn copyFields(objectOf(value), BINDING_FIELDS) as unknown as AuthorizationBinding;\n}\n\n/**\n * A fresh copy of the snapshot's parameters for code that should not reach\n * the copy Host persists (the admission check, a composition callback).\n * Only for a snapshot whose parameters are Host's copy.\n */\nexport function parametersCopy(snapshot: SubmissionSnapshot): Record<string, unknown> {\n\tif (!snapshot.parametersArePrivate) throw new SubmissionUnreadableError();\n\tconst copied = copyJsonData(snapshot.parameters);\n\tif (!copied.ok) throw new SubmissionUnreadableError();\n\treturn copied.value as Record<string, unknown>;\n}\n\n/**\n * The `SubmitActionInput` a callback typed to take one gets for an action\n * WITHOUT `admitSubmission` (`snapshotSubmission`, not `privateSubmission`).\n * Its scalar fields are the snapshot's, so the callback sees the action,\n * scope, actor and ids Host authorizes and persists, whatever the caller\n * changed on its object since submission. `parameters`, `provenance` and\n * `authorizationBinding` are accessors on the caller's input: each read\n * returns what `input[field]` holds at that moment and each write assigns\n * it, so the callback reaches the same objects, with the same reads, as\n * when it was handed the caller's input itself. The view is a new object\n * each call: other properties of the caller's object are not on it, and\n * assigning a scalar field changes only the view.\n */\nexport function liveSubmissionView(snapshot: SubmissionSnapshot, input: SubmitActionInput): SubmitActionInput {\n\tconst view: Record<string, unknown> = {\n\t\tactionId: snapshot.actionId,\n\t\ttenantId: snapshot.tenantId,\n\t\tspaceId: snapshot.spaceId,\n\t\tactorId: snapshot.actorId,\n\t\tactorType: snapshot.actorType,\n\t\t...(snapshot.correlationId !== undefined ? { correlationId: snapshot.correlationId } : {}),\n\t\t...(snapshot.causationId !== undefined ? { causationId: snapshot.causationId } : {}),\n\t\t...(snapshot.executionReason !== undefined ? { executionReason: snapshot.executionReason } : {}),\n\t\t...(snapshot.idempotencyKey !== undefined ? { idempotencyKey: snapshot.idempotencyKey } : {}),\n\t\t...(snapshot.authorizationBindingId !== undefined ? { authorizationBindingId: snapshot.authorizationBindingId } : {}),\n\t};\n\tconst caller = input as unknown as Record<string, unknown>;\n\tfor (const field of [\"parameters\", \"provenance\", \"authorizationBinding\"] as const) {\n\t\tObject.defineProperty(view, field, {\n\t\t\tget: () => caller[field],\n\t\t\tset: (value: unknown) => { caller[field] = value; },\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t});\n\t}\n\treturn view as unknown as SubmitActionInput;\n}\n\n/**\n * A `SubmitActionInput` built from a private snapshot (`privateSubmission`),\n * with fresh copies of its parameters, provenance and binding, for a\n * callback typed to take one.\n */\nexport function submissionView(snapshot: SubmissionSnapshot): SubmitActionInput {\n\tconst fresh = <T>(value: T | undefined): T | undefined => {\n\t\tif (value === undefined) return undefined;\n\t\tconst copied = copyJsonData(value);\n\t\tif (!copied.ok) throw new SubmissionUnreadableError();\n\t\treturn copied.value as T;\n\t};\n\tconst provenance = fresh(snapshot.provenance);\n\tconst authorizationBinding = fresh(snapshot.authorizationBinding);\n\treturn {\n\t\tactionId: snapshot.actionId,\n\t\tparameters: parametersCopy(snapshot),\n\t\ttenantId: snapshot.tenantId,\n\t\tspaceId: snapshot.spaceId,\n\t\tactorId: snapshot.actorId,\n\t\tactorType: snapshot.actorType,\n\t\t...(snapshot.correlationId !== undefined ? { correlationId: snapshot.correlationId } : {}),\n\t\t...(snapshot.causationId !== undefined ? { causationId: snapshot.causationId } : {}),\n\t\t...(provenance ? { provenance } : {}),\n\t\t...(snapshot.executionReason !== undefined ? { executionReason: snapshot.executionReason } : {}),\n\t\t...(snapshot.idempotencyKey !== undefined ? { idempotencyKey: snapshot.idempotencyKey } : {}),\n\t\t...(snapshot.authorizationBindingId !== undefined ? { authorizationBindingId: snapshot.authorizationBindingId } : {}),\n\t\t...(authorizationBinding ? { authorizationBinding } : {}),\n\t};\n}\n","import { createFabricId } from \"@fabricorg/platform\";\nimport type {\n\tOutboxRequeuePlatformHostStore,\n\tOutboxStatus,\n\tPlatformHostOptions,\n\tRequeueOutboxDeadLetterInput,\n\tRequeueOutboxDeadLetterRefusal,\n\tRequeueOutboxDeadLetterResult,\n} from \"./types\";\nimport { emitPlatformHostTelemetry, PLATFORM_HOST_METRIC_NAMES } from \"./observability\";\n\n// ── Outbox dead-letter requeue ──────────────────────────────────────────────\n//\n// An operator moves a dead-lettered outbox record back to pending once the\n// consumer that rejected it is fixed. Authorization runs against the record as\n// read, and the store's compare-and-set accepts only that same dead letter:\n// the read's lease token travels with the write, so a decision cannot carry\n// over to a later dead-letter generation. The store writes the transition and\n// its evidence in one step. Not exported from the package\n// index; the host exposes it as `requeueOutboxDeadLetter`.\n\nconst MAX_REASON_LENGTH = 1_000;\n\nexport interface OutboxRequeueDeps<TDb> {\n\tstore: PlatformHostOptions<TDb>[\"store\"];\n\tauthorization: PlatformHostOptions<TDb>[\"authorization\"];\n\ttelemetry: PlatformHostOptions<TDb>[\"telemetry\"];\n\tnow(): Date;\n}\n\nexport function asOutboxRequeueStore<TDb>(\n\tstore: PlatformHostOptions<TDb>[\"store\"],\n): OutboxRequeuePlatformHostStore<TDb> | undefined {\n\tconst candidate = store as Partial<OutboxRequeuePlatformHostStore<TDb>>;\n\treturn typeof candidate.requeueOutboxDeadLetter === \"function\" &&\n\t\ttypeof candidate.getOutboxRecord === \"function\" &&\n\t\ttypeof candidate.listOutboxRequeues === \"function\"\n\t\t? (store as OutboxRequeuePlatformHostStore<TDb>)\n\t\t: undefined;\n}\n\nexport function createOutboxRequeue<TDb>(\n\tdeps: OutboxRequeueDeps<TDb>,\n): (input: RequeueOutboxDeadLetterInput) => Promise<RequeueOutboxDeadLetterResult> {\n\treturn async function requeueOutboxDeadLetter(input) {\n\t\tfor (const field of [\"outboxId\", \"tenantId\", \"spaceId\", \"actorId\", \"actorType\"] as const) {\n\t\t\tif (typeof input[field] !== \"string\" || input[field].trim() === \"\") {\n\t\t\t\tthrow new Error(`Outbox requeue requires ${field}.`);\n\t\t\t}\n\t\t}\n\t\tif (typeof input.reason !== \"string\" || input.reason.trim() === \"\") {\n\t\t\tthrow new Error(\"Outbox requeue requires a reason.\");\n\t\t}\n\t\tif (input.reason.length > MAX_REASON_LENGTH) {\n\t\t\tthrow new Error(`Outbox requeue reason must be at most ${MAX_REASON_LENGTH} characters.`);\n\t\t}\n\t\tif (input.availableAt !== undefined && !(input.availableAt instanceof Date && Number.isFinite(input.availableAt.getTime()))) {\n\t\t\tthrow new Error(\"Outbox requeue availableAt must be a valid Date.\");\n\t\t}\n\t\tconst store = asOutboxRequeueStore(deps.store);\n\t\tif (!store) throw new Error(\"Outbox requeue requires a store with outbox requeue support.\");\n\n\t\tconst refuse = (\n\t\t\trefusal: RequeueOutboxDeadLetterRefusal,\n\t\t\tmessage: string,\n\t\t\tcurrentStatus?: OutboxStatus,\n\t\t): RequeueOutboxDeadLetterResult => {\n\t\t\temitPlatformHostTelemetry(deps.telemetry, {\n\t\t\t\tkind: \"event\",\n\t\t\t\tname: \"outbox.requeue_refused\",\n\t\t\t\tmetricName: PLATFORM_HOST_METRIC_NAMES.outboxRequeueRefused,\n\t\t\t\toccurredAt: deps.now(),\n\t\t\t\ttenantId: input.tenantId,\n\t\t\t\tspaceId: input.spaceId,\n\t\t\t\tattributes: { refusal },\n\t\t\t});\n\t\t\treturn { status: \"refused\", refusal, message, ...(currentStatus ? { currentStatus } : {}) };\n\t\t};\n\n\t\tconst record = await store.getOutboxRecord(input.outboxId, input.tenantId, input.spaceId);\n\t\t// Authorize before revealing whether the record exists, so a refused actor\n\t\t// learns nothing about the scope. No authorizer means no requeue.\n\t\tconst authorization = deps.authorization;\n\t\tconst hasAuthorizer = typeof authorization.authorizeOutboxRequeue === \"function\";\n\t\t// Called through the authorization object so a class-based authorizer keeps its receiver.\n\t\tconst authorized = hasAuthorizer\n\t\t\t? await authorization.authorizeOutboxRequeue!({\n\t\t\t\ttenantId: input.tenantId,\n\t\t\t\tspaceId: input.spaceId,\n\t\t\t\tactorId: input.actorId,\n\t\t\t\tactorType: input.actorType,\n\t\t\t\toutboxId: input.outboxId,\n\t\t\t\treason: input.reason,\n\t\t\t\t...(record ? {\n\t\t\t\t\trecord: {\n\t\t\t\t\t\teventId: record.event.eventId,\n\t\t\t\t\t\teventType: record.event.eventType,\n\t\t\t\t\t\tpayloadClassification: record.event.payloadClassification,\n\t\t\t\t\t\tstatus: record.status,\n\t\t\t\t\t\tattemptCount: record.attemptCount,\n\t\t\t\t\t},\n\t\t\t\t} : {}),\n\t\t\t})\n\t\t\t: false;\n\t\tif (authorized !== true) {\n\t\t\treturn refuse(\n\t\t\t\t\"not_authorized\",\n\t\t\t\thasAuthorizer\n\t\t\t\t\t? `Actor ${input.actorId} is not authorized to requeue outbox records in this scope.`\n\t\t\t\t\t: \"Outbox requeue is refused because no authorizeOutboxRequeue is configured.\",\n\t\t\t);\n\t\t}\n\t\tif (!record) return refuse(\"not_found\", `Outbox record not found: ${input.outboxId}`);\n\t\tif (record.status !== \"dead_letter\") {\n\t\t\treturn refuse(\"not_dead_letter\", `Outbox record ${input.outboxId} is ${record.status}, not dead_letter.`, record.status);\n\t\t}\n\n\t\t// The compare-and-set is the guard that counts. Another requeue may have\n\t\t// won since the read above, or the record may have been requeued, retried\n\t\t// and dead-lettered again while the authorizer ran; the store refuses\n\t\t// unless the record is still the dead letter at the lease token we read.\n\t\tconst requeuedAt = deps.now();\n\t\tconst result = await store.requeueOutboxDeadLetter({\n\t\t\tid: input.outboxId,\n\t\t\ttenantId: input.tenantId,\n\t\t\tspaceId: input.spaceId,\n\t\t\trequeueId: createFabricId(\"orq\"),\n\t\t\tactorId: input.actorId,\n\t\t\tactorType: input.actorType,\n\t\t\treason: input.reason,\n\t\t\trequeuedAt,\n\t\t\tavailableAt: input.availableAt ?? requeuedAt,\n\t\t\texpectedLeaseToken: record.leaseToken ?? 0,\n\t\t});\n\t\tif (!result.applied) {\n\t\t\tif (result.refusal === \"not_found\") return refuse(\"not_found\", `Outbox record not found: ${input.outboxId}`);\n\t\t\tif (result.refusal === \"stale\") {\n\t\t\t\treturn refuse(\n\t\t\t\t\t\"stale\",\n\t\t\t\t\t`Outbox record ${input.outboxId} changed after it was authorized; read and authorize it again.`,\n\t\t\t\t\tresult.currentStatus,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn refuse(\n\t\t\t\t\"not_dead_letter\",\n\t\t\t\t`Outbox record ${input.outboxId} is ${result.currentStatus ?? \"no longer dead_letter\"}, not dead_letter.`,\n\t\t\t\tresult.currentStatus,\n\t\t\t);\n\t\t}\n\t\temitPlatformHostTelemetry(deps.telemetry, {\n\t\t\tkind: \"event\",\n\t\t\tname: \"outbox.requeued\",\n\t\t\tmetricName: PLATFORM_HOST_METRIC_NAMES.outboxRequeued,\n\t\t\toccurredAt: requeuedAt,\n\t\t\ttenantId: input.tenantId,\n\t\t\tspaceId: input.spaceId,\n\t\t\tattributes: { priorAttempt: result.requeue.priorAttemptCount },\n\t\t});\n\t\treturn { status: \"requeued\", record: result.record, requeue: result.requeue };\n\t};\n}\n","import {\n\tAdapterCircuitBreakerRegistry,\n\tAdapterRegistry,\n\tassertAdapterCircuitBreakerConfig,\n\tisAdapterCircuitOpenError,\n\tisRetryableExecutionError,\n\tisReconciliationRequiredError,\n\taggregatePolicyOutcomes,\n\tcreateFabricId,\n\tevaluatePolicyDefinitions,\n\texecuteWithAdapterRetry,\n\tassertAdapterOutcomeConsistency,\n\tevaluateStateMachineTransition,\n\tassertMutationGovernanceContext,\n\tassertGovernanceRuntimeEvidence,\n\tFABRIC_GOVERNANCE_CONTRACT_VERSION,\n} from \"@fabricorg/platform\";\nimport { performance } from \"node:perf_hooks\";\nimport { assertAssemblyRuntimeCompatible } from \"@fabricorg/assembly\";\nimport type {\n\tActionDefinition,\n\tActionId,\n\tActionStatus,\n\tAssetEventEnvelope,\n\tRuntimePolicyDefinition,\n\tExecutionAttestation,\n\tExternalReconciliation,\n} from \"@fabricorg/platform\";\nimport type {\n\tActionApprovalDecision,\n\tActionAuthorizationInput,\n\tActionExecutionReason,\n\tActionInvocationRecord,\n\tAdapterInvocationRecord,\n\tAdapterReconciliationOutcome,\n\tApprovalPlatformHostStore,\n\tExecuteActionResult,\n\tExecuteInvocationOptions,\n\tGovernedActionHost,\n\tOutboxRequeueHost,\n\tPendingAssetEvent,\n\tOutboxPlatformHostStore,\n\tPlatformHostOptions,\n\tErrorTextRedactionContext,\n\tPlatformHostMutationTransaction,\n\tSubmitActionInput,\n\tSubmitActionResult,\n\tIdempotencyConflict,\n\tRecoverablePlatformHostStore,\n\tActionInvocationPatch,\n\tPendingExternalCompletion,\n} from \"./types\";\nimport { ActionAdmissionError, IdempotencyConflictError, PLATFORM_HOST_CONTRACT_VERSION } from \"./types\";\nimport type { ActionAdmissionRefusal } from \"./types\";\nimport { digestParameters, normalizeProvenance, PARAMETER_DIGEST_ALGORITHM } from \"./command-identity\";\nimport { createExternalCompletionLifecycle } from \"./external-completion\";\nimport { liveSubmissionView, parametersCopy, privateSubmission, snapshotSubmission, submissionView, type SubmissionSnapshot } from \"./submission-snapshot\";\nimport { createOutboxRequeue } from \"./outbox-requeue\";\nimport {\n\tasAtomicMutationStore,\n\tasGovernanceStore,\n\temitInvocationStatusTelemetry,\n\terrorMessage,\n\tHostError,\n\tRecoverableFinalizationError,\n\tredactErrorText,\n\tisRecord,\n\tlifecycleId,\n\twithoutPrivateHostFields,\n} from \"./host-internals\";\nimport {\n\temitPlatformHostTelemetry,\n\tPLATFORM_HOST_METRIC_NAMES,\n} from \"./observability\";\n\nconst DEFAULT_EXTRACT_EVENTS = (data: Record<string, unknown>): PendingAssetEvent[] => {\n\tconst value = data._events;\n\treturn Array.isArray(value) ? (value as PendingAssetEvent[]) : [];\n};\n\n/** After a fallback verdict, attempt independent evidence writes before raising the first failure. */\nasync function attemptEvidenceWrites(writes: Array<() => Promise<void>>): Promise<void> {\n\tlet failure: { error: unknown } | undefined;\n\tfor (const write of writes) {\n\t\ttry { await write(); } catch (error) { failure ??= { error }; }\n\t}\n\tif (failure) throw failure.error;\n}\n\nconst DEFAULT_ADMISSION_TIMEOUT_MS = 10_000;\n/** The largest delay `setTimeout` honours (2^31 - 1 ms); a larger one fires at once. */\nconst MAX_TIMER_MS = 2_147_483_647;\n/** Monotonic milliseconds, captured at module load: the admission deadline is judged on it. */\nconst monotonicNow: () => number = performance.now.bind(performance);\ntype AdmissionOutcome = { kind: \"answered\"; value: unknown } | { kind: \"failed\" } | { kind: \"timed_out\" };\nconst ADMISSION_FAILED: AdmissionOutcome = Object.freeze({ kind: \"failed\" });\nconst ADMISSION_TIMED_OUT: AdmissionOutcome = Object.freeze({ kind: \"timed_out\" });\n/** What an admission refusal's code may look like; anything else is `invalid_decision`. */\nconst ADMISSION_REFUSAL_CODE = /^[a-z][A-Za-z0-9_.:-]{0,127}$/;\n\nexport function createGovernedActionHost<TDb>(\n\toptions: PlatformHostOptions<TDb>,\n): GovernedActionHost & OutboxRequeueHost {\n\tconst retryableExecutionMaxAttempts = options.retryableExecutionMaxAttempts ?? 5;\n\tif (!Number.isInteger(retryableExecutionMaxAttempts) || retryableExecutionMaxAttempts <= 0) {\n\t\tthrow new Error(\"retryableExecutionMaxAttempts must be a positive integer.\");\n\t}\n\tconst recoveryMaxAttempts = options.recoveryMaxAttempts ?? Math.max(5, retryableExecutionMaxAttempts);\n\tif (!Number.isInteger(recoveryMaxAttempts) || recoveryMaxAttempts <= 0) {\n\t\tthrow new Error(\"recoveryMaxAttempts must be a positive integer.\");\n\t}\n\tif (recoveryMaxAttempts < retryableExecutionMaxAttempts) {\n\t\tthrow new Error(\n\t\t\t`recoveryMaxAttempts (${recoveryMaxAttempts}) must be greater than or equal to retryableExecutionMaxAttempts (${retryableExecutionMaxAttempts}); raise recoveryMaxAttempts or lower retryableExecutionMaxAttempts too.`,\n\t\t);\n\t}\n\tif (options.composition) {\n\t\tif (!options.registry?.orderedModules) {\n\t\t\tthrow new Error(\"Composition-bound Platform Host requires an explicit module registry.\");\n\t\t}\n\t\tassertAssemblyRuntimeCompatible(\n\t\t\toptions.composition.assembly,\n\t\t\toptions.registry.orderedModules.map((module) => ({\n\t\t\t\tnamespace: module.namespace,\n\t\t\t\tversion: module.version ?? \"\",\n\t\t\t\tmanifestDigest: module.manifestDigest ?? \"\",\n\t\t\t})),\n\t\t);\n\t}\n\tif (options.outbox) {\n\t\tconst outboxStore = asOutboxStore(options.store);\n\t\tif (!outboxStore || !asAtomicMutationStore(options.store) || outboxStore.transactionalOutbox !== true) {\n\t\t\tthrow new Error(\"Outbox egress requires a store with transactionalOutbox and transactionWithEvents capabilities.\");\n\t\t}\n\t}\n\tconst adapters = new AdapterRegistry();\n\tfor (const adapter of options.adapters ?? []) {\n\t\t// A breaker config was inert before Host read it; refuse a bad one at\n\t\t// construction rather than on the first adapter call.\n\t\tif (adapter.circuitBreaker) assertAdapterCircuitBreakerConfig(adapter.circuitBreaker);\n\t\tadapters.register(adapter);\n\t}\n\tconst now = options.now ?? (() => new Date());\n\t// The default registry creates one breaker per adapterType:operation, on\n\t// first use and only for adapters that declare a circuitBreaker config. An\n\t// injected provider can use the trusted invocation scope passed at the\n\t// adapter boundary.\n\tconst circuitBreakers = options.adapterCircuitBreakers\n\t\t?? new AdapterCircuitBreakerRegistry({ now: () => now().getTime() });\n\tconst extractEvents = options.extractEvents ?? DEFAULT_EXTRACT_EVENTS;\n\tconst configuredActionResolver = options.resolveAction ?? options.registry?.resolveAction;\n\tif (!configuredActionResolver) throw new Error(\"Platform Host requires an explicit module registry or resolveAction function.\");\n\tconst actionResolver: NonNullable<PlatformHostOptions<TDb>[\"resolveAction\"]> = configuredActionResolver;\n\tconst stateMachineResolver = options.registry?.resolveStateMachine ?? (() => undefined);\n\tconst eventResultFields = options.eventResultFields ?? [\"_events\"];\n\tconst admissionTimeoutMs = options.admissionTimeoutMs ?? DEFAULT_ADMISSION_TIMEOUT_MS;\n\tif (typeof admissionTimeoutMs !== \"number\" || !Number.isInteger(admissionTimeoutMs) || admissionTimeoutMs < 1 || admissionTimeoutMs > MAX_TIMER_MS) {\n\t\tthrow new Error(`admissionTimeoutMs must be a whole number of milliseconds from 1 to ${MAX_TIMER_MS}.`);\n\t}\n\n\tfunction caughtError(context: ErrorTextRedactionContext, error: unknown): string {\n\t\treturn error instanceof HostError\n\t\t\t? errorMessage(error)\n\t\t\t: redactErrorText(options.redactErrorText, context, errorMessage(error));\n\t}\n\n\tasync function submitAction(input: SubmitActionInput): Promise<SubmitActionResult> {\n\t\t// The one read of the caller's scalar fields, before the first await.\n\t\t// Every step below reads `submission`, so what the caller changes on its\n\t\t// object while Host awaits cannot change the action, scope, actor, ids\n\t\t// or keys Host authorizes, persists or executes (tests \"the submission\n\t\t// Host authorizes, admits, persists and executes is one private\n\t\t// snapshot\" and \"the identity snapshot still applies …\").\n\t\tconst read = snapshotSubmission(input);\n\t\tif (read.executionReason && ![\"initial\", \"offline_replay\"].includes(read.executionReason)) {\n\t\t\tthrow new Error(`Unsupported submitted execution reason: ${read.executionReason}`);\n\t\t}\n\t\tconst action = actionResolver(read.actionId);\n\t\tif (!action) throw new Error(`Unknown action: ${read.actionId}`);\n\t\t// An action that declares admitSubmission gets Host's own copies of the\n\t\t// parameters, provenance and binding, also before the first await. For\n\t\t// any other action `submission` reads those three from the caller's\n\t\t// input wherever Host reads them below, exactly as before the snapshot\n\t\t// existed (tests \"an action without admitSubmission: everything but the\n\t\t// identity snapshot is as before\").\n\t\tconst declaresAdmission = action.admitSubmission !== undefined;\n\t\tconst submission = declaresAdmission ? privateSubmission(read) : read;\n\t\t// An action that requires connectivity was never eligible to be captured offline.\n\t\tif (action.execution?.connectivity === \"online-required\" && submission.executionReason === \"offline_replay\") {\n\t\t\tthrow new Error(`Action ${submission.actionId} is online-required and cannot be submitted as an offline replay.`);\n\t\t}\n\t\tif (action.execution?.sensitivity === \"restricted\" && Object.keys(submission.provenance?.auditAttributes ?? {}).length > 0) {\n\t\t\tthrow new Error(`Action ${submission.actionId} declares restricted sensitivity; provenance audit attributes must not be durably recorded.`);\n\t\t}\n\t\tconst authorizationInput = toAuthorizationInput(action, submission);\n\t\tif (!(await options.authorization.checkEntitlement(authorizationInput))) {\n\t\t\tthrow new Error(`Module \"${action.namespace}\" is not enabled for tenant ${submission.tenantId}`);\n\t\t}\n\t\tif (!(await options.authorization.authorize(authorizationInput))) {\n\t\t\tthrow new Error(`Actor ${submission.actorId} is not authorized for action ${submission.actionId}`);\n\t\t}\n\t\t// Only JSON data Host copied at submission can be admitted: anything else\n\t\t// could still be changed through a reference the caller holds. Refused\n\t\t// here, before any callback could be handed the caller's object.\n\t\tif (declaresAdmission && (!submission.parametersArePrivate || !isRecord(submission.parameters))) {\n\t\t\trefuseAdmission(action, submission, \"invalid_parameters\");\n\t\t}\n\n\t\tconst actionInvocationId = createFabricId(\"act\");\n\t\tif (submission.correlationId && submission.provenance?.correlationId && submission.correlationId !== submission.provenance.correlationId) throw new Error(\"Invocation provenance correlationId does not match submission correlationId.\");\n\t\tif (submission.causationId && submission.provenance?.causationId && submission.causationId !== submission.provenance.causationId) throw new Error(\"Invocation provenance causationId does not match submission causationId.\");\n\t\tconst correlationId = submission.correlationId ?? submission.provenance?.correlationId ?? createFabricId(\"corr\");\n\t\t// Redaction, the parameter digest and the binding check. For an action\n\t\t// without admitSubmission they run here, before provenance and the\n\t\t// composition callback, as they always did; for one with it, after its\n\t\t// check admitted the submission, on Host's copy.\n\t\t// Each reads `submission.parameters` where and as often as the previous\n\t\t// Host read the caller's: for an action without the check those reads\n\t\t// go to the caller's input (src/submission-snapshot.ts).\n\t\tconst prepare = () => {\n\t\t\tconst durableParameters = options.redactActionParameters\n\t\t\t\t? options.redactActionParameters(submission.actionId, submission.parameters)\n\t\t\t\t: submission.parameters;\n\t\t\tconst parameterDigest = digestParameters(submission.parameters);\n\t\t\tif (submission.authorizationBinding) validateAuthorizationBinding(submission, parameterDigest, action.execution?.authorityMoment, now());\n\t\t\treturn { durableParameters, parameterDigest };\n\t\t};\n\t\tconst early = declaresAdmission ? undefined : prepare();\n\t\tconst durableProvenance = normalizeProvenance(\n\t\t\tsubmission.provenance,\n\t\t\toptions.provenance as PlatformHostOptions<unknown>[\"provenance\"],\n\t\t);\n\t\t// Both views carry the snapshot's identity, so the callback resolves\n\t\t// evidence for the action, scope and actor Host persists. A declaring\n\t\t// action's callback gets fresh copies of Host's parameters, provenance\n\t\t// and binding; any other action's reads and assigns the caller's, as\n\t\t// when it was handed the caller's input (liveSubmissionView).\n\t\tconst initiatingReleaseDigest =\n\t\t\tawait options.composition?.resolveInitiatingReleaseDigest?.(declaresAdmission ? submissionView(submission) : liveSubmissionView(submission, input));\n\t\tconst runtimeEvidence = {\n\t\t\tgovernanceContractVersion: FABRIC_GOVERNANCE_CONTRACT_VERSION,\n\t\t\thostContractVersion: PLATFORM_HOST_CONTRACT_VERSION,\n\t\t\t...options.runtimeEvidence,\n\t\t\t...(options.composition\n\t\t\t\t? { assemblyDigest: options.composition.assembly.assemblyDigest }\n\t\t\t\t: {}),\n\t\t\t...(initiatingReleaseDigest\n\t\t\t\t? { initiatingReleaseDigest }\n\t\t\t\t: {}),\n\t\t};\n\t\tassertGovernanceRuntimeEvidence(runtimeEvidence);\n\t\t// The action's admission check is the last await before the invocation\n\t\t// is created: everything between it and createActionInvocation is\n\t\t// synchronous, and it runs on every submission, including one that\n\t\t// reuses an idempotency key, so a refused submission is never digested,\n\t\t// matched against an existing invocation, redacted or written.\n\t\tconst admission = declaresAdmission\n\t\t\t? await admitSubmission(action, submission)\n\t\t\t: undefined;\n\t\tconst { durableParameters, parameterDigest } = early ?? prepare();\n\t\tconst durableInvocation = await options.store.createActionInvocation({\n\t\t\tid: actionInvocationId,\n\t\t\ttenantId: submission.tenantId,\n\t\t\tspaceId: submission.spaceId,\n\t\t\tactionId: submission.actionId,\n\t\t\tactionVersion: action.version,\n\t\t\tactorId: submission.actorId,\n\t\t\tactorType: submission.actorType,\n\t\t\tstatus: \"pending\",\n\t\t\tparameters: durableParameters,\n\t\t\tresult: {},\n\t\t\truntimeEvidence,\n\t\t\tcorrelationId,\n\t\t\t...((submission.causationId ?? submission.provenance?.causationId) ? { causationId: submission.causationId ?? submission.provenance?.causationId } : {}),\n\t\t\t...(submission.idempotencyKey ? { idempotencyKey: submission.idempotencyKey } : {}),\n\t\t\t...(submission.idempotencyKey ? {\n\t\t\t\tparameterDigest,\n\t\t\t\tparameterDigestAlgorithm: PARAMETER_DIGEST_ALGORITHM,\n\t\t\t\tidempotencyActorId: submission.actorId,\n\t\t\t\t...(submission.authorizationBindingId ? { idempotencyAuthorizationBindingId: submission.authorizationBindingId } : {}),\n\t\t\t} : {}),\n\t\t\t...(durableProvenance ? { provenance: durableProvenance } : {}),\n\t\t\t...(submission.authorizationBinding ? { authorizationBinding: submission.authorizationBinding } : {}),\n\t\t\t...(submission.executionReason ? { executionReason: submission.executionReason } : {}),\n\t\t\t...(submission.authorizationBindingId\n\t\t\t\t? { authorizationBindingId: submission.authorizationBindingId }\n\t\t\t\t: {}),\n\t\t\t...(admission ? { admittedAt: admission.admittedAt } : {}),\n\t\t});\n\t\temitPlatformHostTelemetry(options.telemetry, {\n\t\t\tkind: \"event\",\n\t\t\tname: \"invocation.submitted\",\n\t\t\tmetricName: PLATFORM_HOST_METRIC_NAMES.invocationSubmitted,\n\t\t\toccurredAt: now(),\n\t\t\ttenantId: submission.tenantId,\n\t\t\tspaceId: submission.spaceId,\n\t\t\tattributes: { actionVersion: action.version },\n\t\t});\n\t\tif (durableInvocation.id !== actionInvocationId && submission.idempotencyKey) {\n\t\t\tconst conflict = idempotencyConflict(durableInvocation, {\n\t\t\t\tactorId: submission.actorId,\n\t\t\t\tauthorizationBindingId: submission.authorizationBindingId,\n\t\t\t\tactionVersion: action.version,\n\t\t\t\tparameterDigest,\n\t\t\t\tidempotencyKey: submission.idempotencyKey,\n\t\t\t});\n\t\t\tif (!durableInvocation.parameterDigest) {\n\t\t\t\toptions.idempotency?.onLegacyRecord?.(durableInvocation);\n\t\t\t\tconst enforceableLegacyConflict = conflict && { ...conflict, reasons: conflict.reasons.filter((reason) => reason !== \"parameters\") };\n\t\t\t\tif (enforceableLegacyConflict && enforceableLegacyConflict.reasons.length) {\n\t\t\t\t\toptions.idempotency?.onConflict?.(enforceableLegacyConflict);\n\t\t\t\t\tif ((options.idempotency?.conflictMode ?? \"enforce\") === \"enforce\") throw new IdempotencyConflictError(enforceableLegacyConflict);\n\t\t\t\t}\n\t\t\t} else if (conflict) {\n\t\t\t\toptions.idempotency?.onConflict?.(conflict);\n\t\t\t\tif ((options.idempotency?.conflictMode ?? \"enforce\") === \"enforce\") throw new IdempotencyConflictError(conflict);\n\t\t\t}\n\t\t}\n\t\tconst durableWorkflowId = `action-invocation-${durableInvocation.id}`;\n\t\tif (durableInvocation.id !== actionInvocationId) {\n\t\t\t// A pending dispatch may be retried with the same stable workflow id.\n\t\t\t// Terminal and running invocations report what the original did.\n\t\t\tif (options.dispatcher && durableInvocation.status === \"pending\") {\n\t\t\t\tconst dispatched = await options.dispatcher.dispatch({\n\t\t\t\t\tactionInvocationId: durableInvocation.id,\n\t\t\t\t\tactionId: durableInvocation.actionId,\n\t\t\t\t\ttenantId: submission.tenantId,\n\t\t\t\t\tspaceId: submission.spaceId,\n\t\t\t\t\tworkflowId: durableWorkflowId,\n\t\t\t\t});\n\t\t\t\treturn withConsistency({\n\t\t\t\t\tactionInvocationId: durableInvocation.id,\n\t\t\t\t\tstatus: durableInvocation.status,\n\t\t\t\t\tworkflowId: dispatched.workflowId,\n\t\t\t\t\t...(dispatched.runId ? { runId: dispatched.runId } : {}),\n\t\t\t\t\t...(durableInvocation.hitlRoute ? { hitlRoute: durableInvocation.hitlRoute } : {}),\n\t\t\t\t\t...(durableInvocation.hitlRiskTier\n\t\t\t\t\t\t? { hitlRiskTier: durableInvocation.hitlRiskTier }\n\t\t\t\t\t\t: {}),\n\t\t\t\t}, submission.actionId);\n\t\t\t}\n\t\t\treturn withConsistency({\n\t\t\t\tactionInvocationId: durableInvocation.id,\n\t\t\t\tstatus: durableInvocation.status,\n\t\t\t\tworkflowId: durableWorkflowId,\n\t\t\t\tresult: durableInvocation.result,\n\t\t\t\t...(durableInvocation.error ? { error: durableInvocation.error } : {}),\n\t\t\t\t...(durableInvocation.hitlRoute ? { hitlRoute: durableInvocation.hitlRoute } : {}),\n\t\t\t\t...(durableInvocation.hitlRiskTier\n\t\t\t\t\t? { hitlRiskTier: durableInvocation.hitlRiskTier }\n\t\t\t\t\t: {}),\n\t\t\t\t...(durableInvocation.authorizationReconciliation\n\t\t\t\t\t? { reconciliation: durableInvocation.authorizationReconciliation }\n\t\t\t\t\t: {}),\n\t\t\t\t...(durableInvocation.adapterReconciliation\n\t\t\t\t\t? { adapterReconciliation: durableInvocation.adapterReconciliation }\n\t\t\t\t\t: {}),\n\t\t\t\t...(durableInvocation.pendingCompletion\n\t\t\t\t\t? { pendingCompletion: durableInvocation.pendingCompletion }\n\t\t\t\t\t: {}),\n\t\t\t}, submission.actionId);\n\t\t}\n\n\t\tif (options.dispatcher) {\n\t\t\ttry {\n\t\t\t\tconst dispatched = await options.dispatcher.dispatch({\n\t\t\t\t\tactionInvocationId: durableInvocation.id,\n\t\t\t\t\tactionId: durableInvocation.actionId,\n\t\t\t\t\ttenantId: submission.tenantId,\n\t\t\t\t\tspaceId: submission.spaceId,\n\t\t\t\t\tworkflowId: durableWorkflowId,\n\t\t\t\t});\n\t\t\t\treturn withConsistency({\n\t\t\t\t\tactionInvocationId: durableInvocation.id,\n\t\t\t\t\tstatus: durableInvocation.status,\n\t\t\t\t\tworkflowId: dispatched.workflowId,\n\t\t\t\t\t...(dispatched.runId ? { runId: dispatched.runId } : {}),\n\t\t\t\t\t...(durableInvocation.hitlRoute ? { hitlRoute: durableInvocation.hitlRoute } : {}),\n\t\t\t\t\t...(durableInvocation.hitlRiskTier\n\t\t\t\t\t\t? { hitlRiskTier: durableInvocation.hitlRiskTier }\n\t\t\t\t\t\t: {}),\n\t\t\t\t}, submission.actionId);\n\t\t\t} catch (error) {\n\t\t\t\t// The durable invocation remains pending. A caller can resubmit the\n\t\t\t\t// same idempotency key, or an out-of-band dispatcher can retry the\n\t\t\t\t// stable workflow id without recreating the logical mutation.\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\n\t\tconst executed = await executeInvocation(\n\t\t\tdurableInvocation.id,\n\t\t\tsubmission.tenantId,\n\t\t\tsubmission.spaceId,\n\t\t);\n\t\treturn { ...withConsistency(executed, submission.actionId), workflowId: durableWorkflowId };\n\t}\n\n\t/**\n\t * Run the action's `admitSubmission` check on a copy of the submission\n\t * snapshot's parameters, with the snapshot's scope and actor, bounded by\n\t * `admissionTimeoutMs`. Returns when it was admitted; anything but\n\t * `{ admitted: true }` settled within the bound throws\n\t * ActionAdmissionError before anything durable is written. What the check\n\t * throws is never read.\n\t *\n\t * The bound is judged when the check's promise settles, on the monotonic\n\t * clock (`performance.now()`): an answer that settles `admissionTimeoutMs`\n\t * or more after the call began is `timed_out`, even when its handler runs\n\t * before the timer callback (a check that blocked the event loop past the\n\t * deadline). The timer only ends the wait on a promise that never settles.\n\t * Every `timed_out` refusal aborts the check's signal before it throws.\n\t */\n\tasync function admitSubmission(\n\t\taction: ActionDefinition<TDb>,\n\t\tsubmission: SubmissionSnapshot,\n\t): Promise<{ admittedAt: Date }> {\n\t\tconst refuse = (refusal: ActionAdmissionRefusal, refusalCode?: string): never =>\n\t\t\trefuseAdmission(action, submission, refusal, refusalCode);\n\t\tconst check = action.admitSubmission;\n\t\tif (typeof check !== \"function\") return refuse(\"failed\");\n\t\t// submitAction refused parameters that are not Host's private JSON copy.\n\t\tconst checked = parametersCopy(submission);\n\t\tconst controller = new AbortController();\n\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\t\tconst deadline = new Promise<AdmissionOutcome>((resolve) => {\n\t\t\ttimer = setTimeout(() => {\n\t\t\t\tcontroller.abort();\n\t\t\t\tresolve(ADMISSION_TIMED_OUT);\n\t\t\t}, admissionTimeoutMs);\n\t\t});\n\t\tconst startedAt = monotonicNow();\n\t\tconst settledInTime = (): boolean => monotonicNow() - startedAt < admissionTimeoutMs;\n\t\tlet answered: Promise<AdmissionOutcome>;\n\t\ttry {\n\t\t\tanswered = Promise.resolve(check(Object.freeze({\n\t\t\t\tactionId: action.actionId,\n\t\t\t\ttenantId: submission.tenantId,\n\t\t\t\tspaceId: submission.spaceId,\n\t\t\t\tactorId: submission.actorId,\n\t\t\t\tactorType: submission.actorType,\n\t\t\t\tparameters: checked,\n\t\t\t\tsignal: controller.signal,\n\t\t\t}))).then(\n\t\t\t\t(value: unknown): AdmissionOutcome => settledInTime() ? { kind: \"answered\", value } : ADMISSION_TIMED_OUT,\n\t\t\t\t(): AdmissionOutcome => settledInTime() ? ADMISSION_FAILED : ADMISSION_TIMED_OUT,\n\t\t\t);\n\t\t} catch {\n\t\t\tanswered = Promise.resolve(settledInTime() ? ADMISSION_FAILED : ADMISSION_TIMED_OUT);\n\t\t}\n\t\tlet outcome: AdmissionOutcome;\n\t\ttry {\n\t\t\toutcome = await Promise.race([answered, deadline]);\n\t\t} finally {\n\t\t\tclearTimeout(timer);\n\t\t}\n\t\tif (outcome.kind === \"timed_out\") {\n\t\t\tcontroller.abort();\n\t\t\treturn refuse(\"timed_out\");\n\t\t}\n\t\tif (outcome.kind === \"failed\") return refuse(\"failed\");\n\t\tconst admitted = ownDataProperty(outcome.value, \"admitted\");\n\t\tif (admitted === true) return { admittedAt: now() };\n\t\tconst code = ownDataProperty(outcome.value, \"code\");\n\t\tif (admitted === false && typeof code === \"string\" && ADMISSION_REFUSAL_CODE.test(code)) return refuse(\"refused\", code);\n\t\treturn refuse(\"invalid_decision\");\n\t}\n\n\tfunction refuseAdmission(\n\t\taction: ActionDefinition<TDb>,\n\t\tsubmission: SubmissionSnapshot,\n\t\trefusal: ActionAdmissionRefusal,\n\t\trefusalCode?: string,\n\t): never {\n\t\temitPlatformHostTelemetry(options.telemetry, {\n\t\t\tkind: \"event\",\n\t\t\tname: \"invocation.admission_refused\",\n\t\t\tmetricName: PLATFORM_HOST_METRIC_NAMES.invocationAdmissionRefused,\n\t\t\toccurredAt: now(),\n\t\t\ttenantId: submission.tenantId,\n\t\t\tspaceId: submission.spaceId,\n\t\t\tattributes: { actionVersion: action.version, refusal },\n\t\t});\n\t\tthrow new ActionAdmissionError(action.actionId, refusal, refusalCode);\n\t}\n\n\tasync function executeInvocation(\n\t\tactionInvocationId: string,\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t\texecutionOptions: ExecuteInvocationOptions = {},\n\t\texecutionReasonOverride?: ActionExecutionReason,\n\t): Promise<ExecuteActionResult> {\n\t\tlet preservedReconciliation: ActionInvocationRecord | undefined;\n\t\tconst result = await executeInvocationAttempt(actionInvocationId, tenantId, spaceId, executionOptions, executionReasonOverride,\n\t\t\t(record) => { preservedReconciliation = record; });\n\t\tif (preservedReconciliation) return withConsistency(actionResult(preservedReconciliation), preservedReconciliation.actionId);\n\t\treturn result;\n\t}\n\n\tasync function executeInvocationAttempt(\n\t\tactionInvocationId: string,\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t\texecutionOptions: ExecuteInvocationOptions = {},\n\t\texecutionReasonOverride?: ActionExecutionReason,\n\t\tonPreservedReconciliation?: (record: ActionInvocationRecord) => void,\n\t): Promise<ExecuteActionResult> {\n\t\t// Capture credentials supplied to this execution, never a mutable store record.\n\t\tconst executionLease = executionOptions.leaseOwner !== undefined\n\t\t\t? Object.freeze({ leaseOwner: executionOptions.leaseOwner, leaseToken: executionOptions.leaseToken ?? 0 }) : undefined;\n\t\tconst loadedInvocation = await options.store.getActionInvocation(\n\t\t\tactionInvocationId,\n\t\t\ttenantId,\n\t\t\tspaceId,\n\t\t);\n\t\tif (!loadedInvocation) {\n\t\t\tthrow new Error(`ActionInvocation not found: ${actionInvocationId}`);\n\t\t}\n\t\tconst resumingRunningInvocation = loadedInvocation.status === \"running\";\n\t\tlet invocation: ActionInvocationRecord = { ...loadedInvocation };\n\t\tif (isTerminal(invocation.status) || invocation.status === \"waiting_for_approval\") {\n\t\t\treturn withConsistency(actionResult(invocation), invocation.actionId);\n\t\t}\n\t\tif (\n\t\t\tinvocation.status === \"running\" &&\n\t\t\tinvocation.leaseOwner &&\n\t\t\t(executionLease?.leaseOwner !== invocation.leaseOwner ||\n\t\t\t\t((invocation.leaseToken ?? 0) > 0 &&\n\t\t\t\t\texecutionLease?.leaseToken !== invocation.leaseToken))\n\t\t) {\n\t\t\treturn {\n\t\t\t\t...actionResult(invocation),\n\t\t\t\terror: `Invocation lease is not owned by the supplied worker generation`,\n\t\t\t};\n\t\t}\n\t\tlet ownVerdict: Extract<import(\"./types\").AdapterInvocationWriteCondition, { kind: \"verdict\" }> | undefined;\n\t\tconst adapterStatuses = new Map<string, AdapterInvocationRecord[\"status\"]>();\n\t\tfunction rememberVerdict(patch: ActionInvocationPatch, externalCompletionDigest = invocation.externalCompletion?.digest) {\n\t\t\tconst completionAdapterInvocationId = (patch.pendingCompletion ?? invocation.pendingCompletion)?.adapterInvocationId;\n\t\t\tif (patch.status && isTerminal(patch.status)) ownVerdict = {\n\t\t\t\tkind: \"verdict\", status: patch.status,\n\t\t\t\terror: Object.hasOwn(patch, \"error\") ? patch.error : invocation.error,\n\t\t\t\t...(externalCompletionDigest === undefined ? {} : { externalCompletionDigest }),\n\t\t\t\t...(completionAdapterInvocationId ? { completionAdapterInvocationId } : {}),\n\t\t\t};\n\t\t\tinvocation = { ...invocation, ...patch };\n\t\t}\n\t\tasync function persistExecutionInvocation(record: ActionInvocationRecord, patch: ActionInvocationPatch) {\n\t\t\tconst externalCompletionDigest = record.externalCompletion?.digest;\n\t\t\tconst written = await persistInvocation(record, patch, onPreservedReconciliation, executionLease);\n\t\t\t// A preserving inline write observed another writer's verdict, not ours.\n\t\t\tif (written) rememberVerdict(patch, externalCompletionDigest);\n\t\t}\n\t\tasync function persistExecutionVerdict(\n\t\t\trecord: ActionInvocationRecord,\n\t\t\tpatch: ActionInvocationPatch,\n\t\t\tevidenceWrites: Array<() => Promise<void>> = [],\n\t\t) {\n\t\t\tif (ownVerdict) {\n\t\t\t\tconst verdict = ownVerdict;\n\t\t\t\t// Enrichment has no verdict authority of its own. A refusal or missing\n\t\t\t\t// capability skips this write; store errors join the evidence collector.\n\t\t\t\tawait attemptEvidenceWrites([async () => {\n\t\t\t\t\tif (!options.store.updateSettledActionInvocation) return;\n\t\t\t\t\tconst parentPatch = {\n\t\t\t\t\t\t...(Object.hasOwn(patch, \"error\") ? { error: patch.error } : {}),\n\t\t\t\t\t\t...(Object.hasOwn(patch, \"adapterReconciliation\") ? { adapterReconciliation: patch.adapterReconciliation } : {}),\n\t\t\t\t\t};\n\t\t\t\t\tif (!await options.store.updateSettledActionInvocation({ id: actionInvocationId, tenantId, spaceId, condition: verdict, patch: parentPatch })) {\n\t\t\t\t\t\temitPlatformHostTelemetry(options.telemetry, { kind: \"event\", name: \"invocation.adapter_evidence_refused\",\n\t\t\t\t\t\t\tmetricName: PLATFORM_HOST_METRIC_NAMES.adapterEvidenceRefused, occurredAt: now(), tenantId, spaceId,\n\t\t\t\t\t\t\tattributes: { actionInvocationId, evidence: \"parent_enrichment\", reason: \"verdict_or_row_changed\" } });\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\t// Move our comparison forward only after a successful conditional write.\n\t\t\t\t\townVerdict = { ...verdict, ...(Object.hasOwn(parentPatch, \"error\") ? { error: parentPatch.error } : {}) };\n\t\t\t\t\tinvocation = { ...invocation, ...parentPatch };\n\t\t\t\t}, ...evidenceWrites]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\ttry { await persistExecutionInvocation(record, patch); }\n\t\t\tcatch (error) {\n\t\t\t\tif (error instanceof RecoverableFinalizationError) throw error;\n\t\t\t\tawait persistExecutionInvocation(record, patch);\n\t\t\t}\n\t\t\tawait attemptEvidenceWrites(evidenceWrites);\n\t\t}\n\n\t\tasync function failExecution(record: ActionInvocationRecord, status: \"failed\" | \"blocked_by_policy\" | \"validation_failed\", error: string) {\n\t\t\tawait persistExecutionInvocation(record, { status, error });\n\t\t\treturn { actionInvocationId: record.id, status, error,\n\t\t\t\t...(record.hitlRoute ? { hitlRoute: record.hitlRoute } : {}), ...(record.hitlRiskTier ? { hitlRiskTier: record.hitlRiskTier } : {}) };\n\t\t}\n\t\tasync function writeAdapter(\n\t\t\tid: string, patch: import(\"./types\").AdapterInvocationPatch,\n\t\t\ttransaction?: PlatformHostMutationTransaction<TDb>,\n\t\t): Promise<void> {\n\t\t\tconst condition = ownVerdict ?? (executionLease ? { kind: \"lease\" as const, ...executionLease } : undefined);\n\t\t\tconst writer = transaction ?? options.store;\n\t\t\tif (condition && options.store.writeAdapterInvocation) {\n\t\t\t\tif (!writer.writeAdapterInvocation) throw new HostError(\"Conditional adapter writes require transaction-scoped support.\");\n\t\t\t\tconst expectedStatuses = ownVerdict\n\t\t\t\t\t? [adapterStatuses.get(id) ?? \"running\"]\n\t\t\t\t\t: patch.status === \"ambiguous\" ? [\"running\", \"ambiguous\"] as const : [\"running\", \"failed\"] as const;\n\t\t\t\tconst written = await writer.writeAdapterInvocation({ scope: adapterInvocationScope, condition, expectedStatuses,\n\t\t\t\t\tmutation: { kind: \"update\", id, patch } });\n\t\t\t\tif (!written) {\n\t\t\t\t\tif (!ownVerdict) throw new RecoverableFinalizationError(`Invocation lease or adapter condition lost: ${actionInvocationId}`);\n\t\t\t\t\temitPlatformHostTelemetry(options.telemetry, { kind: \"event\", name: \"invocation.adapter_evidence_refused\",\n\t\t\t\t\t\tmetricName: PLATFORM_HOST_METRIC_NAMES.adapterEvidenceRefused, occurredAt: now(), tenantId, spaceId,\n\t\t\t\t\t\tattributes: { actionInvocationId, adapterInvocationId: id, reason: \"verdict_or_row_changed\" } });\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t} else await writer.updateAdapterInvocation!(id, patch, adapterInvocationScope);\n\t\t\tif (patch.status && !transaction) adapterStatuses.set(id, patch.status);\n\t\t}\n\t\tasync function createAdapter(record: AdapterInvocationRecord) {\n\t\t\tif (executionLease && options.store.writeAdapterInvocation) {\n\t\t\t\tif (!await options.store.writeAdapterInvocation({ scope: adapterInvocationScope, condition: { kind: \"lease\", ...executionLease }, mutation: { kind: \"create\", record } })) {\n\t\t\t\t\tthrow new RecoverableFinalizationError(`Invocation lease or adapter condition lost: ${actionInvocationId}`);\n\t\t\t\t}\n\t\t\t} else await options.store.createAdapterInvocation(record);\n\t\t\tadapterStatuses.set(record.id, record.status);\n\t\t}\n\t\tconst adapterInvocationScope = { tenantId: invocation.tenantId, spaceId: invocation.spaceId, actionInvocationId: invocation.id };\n\t\tlet hasDurableProviderEffect = invocation.pendingCompletion !== undefined;\n\t\t// Protect Host ledger operations; authorization, policy and handler callbacks are not wrapped here.\n\t\tasync function hostOperation<TResult>(operation: () => Promise<TResult>): Promise<TResult> {\n\t\t\ttry { return await operation(); } catch (error) {\n\t\t\t\tif (error instanceof RecoverableFinalizationError || !hasDurableProviderEffect || isReconciliationRequiredError(error)) throw error;\n\t\t\t\tthrow new RecoverableFinalizationError(caughtError({ actionId: invocation.actionId, source: \"execution\" }, error));\n\t\t\t}\n\t\t}\n\t\tasync function settleAppliedEffect(message: string, handoff?: PendingExternalCompletion): Promise<ExecuteActionResult> {\n\t\t\tconst error = ownVerdict?.kind === \"verdict\" ? ownVerdict.error ?? message\n\t\t\t\t: `${message}${message.endsWith(\".\") ? \"\" : \".\"} A provider effect was applied and Host did not finish.${handoff ? ` External reference: ${handoff.externalReference}.` : \"\"}`;\n\t\t\ttry {\n\t\t\t\tawait persistExecutionVerdict(invocation, { status: \"reconciliation_required\", error },\n\t\t\t\t\thandoff && asGovernanceStore(options.store) ? [() => externalCompletion.recordCompletionReconciliation(invocation,\n\t\t\t\t\t\t{ provider: handoff.provider, externalReference: handoff.externalReference, kind: \"interrupted\" }, error)] : []);\n\t\t\t} catch (cause) {\n\t\t\t\tif (cause instanceof RecoverableFinalizationError) throw cause;\n\t\t\t\tthrow new RecoverableFinalizationError(caughtError({ actionId: invocation.actionId, source: \"execution\" }, cause));\n\t\t\t}\n\t\t\treturn withConsistency({ actionInvocationId, status: \"reconciliation_required\" as const, error }, invocation.actionId);\n\t\t}\n\n\t\tif (resumingRunningInvocation && invocation.leaseOwner && invocation.attemptCount > recoveryMaxAttempts) {\n\t\t\tconst message = `recovery attempts exhausted (${invocation.attemptCount}/${recoveryMaxAttempts})`\n\t\t\t\t+ (invocation.pendingCompletion ? `. A provider effect was applied and Host did not finish. External reference: ${invocation.pendingCompletion.externalReference}.` : \"\");\n\t\t\ttry {\n\t\t\t\tawait persistExecutionVerdict(invocation, { status: \"reconciliation_required\", error: message });\n\t\t\t} catch { throw new RecoverableFinalizationError(message); }\n\t\t\t// The verdict released this generation's lease. Evidence enrichment\n\t\t\t// below uses the terminal record, rather than the former lease fence.\n\t\t\tinvocation = { ...invocation, status: \"reconciliation_required\", error: message, leaseOwner: undefined, leaseToken: undefined, leaseExpiresAt: undefined };\n\t\t\tlet uncertain: { stepIndex: number; record: AdapterInvocationRecord } | undefined;\n\t\t\ttry {\n\t\t\t\tconst resolved = actionResolver(invocation.actionId);\n\t\t\t\tfor (const [stepIndex] of (resolved?.adapterSteps ?? []).entries()) {\n\t\t\t\t\tconst record = await options.store.getAdapterInvocation(lifecycleId(\"adp\", actionInvocationId, String(stepIndex)), adapterInvocationScope);\n\t\t\t\t\tif (record) adapterStatuses.set(record.id, record.status);\n\t\t\t\t\tif (record && record.id === invocation.pendingCompletion?.adapterInvocationId) continue;\n\t\t\t\t\tif (record?.status === \"running\" || record?.status === \"ambiguous\") { uncertain = { stepIndex, record }; break; }\n\t\t\t\t}\n\t\t\t} catch { /* The plain verdict is already durable when evidence reads fail. */ }\n\t\t\tif (uncertain) {\n\t\t\t\tconst { stepIndex, record } = uncertain;\n\t\t\t\tadapterStatuses.set(record.id, record.status);\n\t\t\t\tif (record.status === \"ambiguous\") {\n\t\t\t\t\tconst recorded = recordedAdapterReconciliation(record);\n\t\t\t\t\treturn settleUnknownOutcome(stepIndex, { ...recorded, message: `${message}. ${recorded.message}` }, record.reconciliation?.adapterEventSubject);\n\t\t\t\t}\n\t\t\t\treturn settleUnknownOutcome(stepIndex, {\n\t\t\t\t\tkind: \"adapter_outcome_ambiguous\", adapterInvocationId: record.id,\n\t\t\t\t\tadapterType: record.adapterType, operation: record.operation, vendor: record.vendor, message,\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (invocation.pendingCompletion) return settleAppliedEffect(message, invocation.pendingCompletion);\n\t\t\treturn { actionInvocationId, status: \"reconciliation_required\", error: message };\n\t\t}\n\n\t\tasync function settleUnknownOutcome(\n\t\t\tstepIndex: number,\n\t\t\tadapterReconciliation: AdapterReconciliationOutcome,\n\t\t\tadapterEventSubject = { subjectType: \"AdapterInvocation\", subjectId: adapterReconciliation.adapterInvocationId },\n\t\t) {\n\t\t\tconst { message, externalReference, adapterInvocationId, adapterType, operation, vendor } = adapterReconciliation;\n\t\t\tconst patch: ActionInvocationPatch = { status: \"reconciliation_required\", error: message, adapterReconciliation };\n\t\t\tconst governanceStore = asGovernanceStore(options.store);\n\t\t\tasync function checkpoint(transaction?: PlatformHostMutationTransaction<TDb>) {\n\t\t\t\tconst legacyPatch = { status: \"ambiguous\" as const, error: message, updatedAt: now() };\n\t\t\t\ttry {\n\t\t\t\t\tawait writeAdapter(adapterInvocationId, {\n\t\t\t\t\t\t...legacyPatch, reconciliation: { ...adapterReconciliation, adapterEventSubject },\n\t\t\t\t\t}, transaction);\n\t\t\t\t} catch (error) {\n\t\t\t\t\t// PostgreSQL errors abort the transaction: let it roll back, then\n\t\t\t\t\t// use the legacy shape outside it after selecting the fallback.\n\t\t\t\t\tif (transaction || error instanceof RecoverableFinalizationError) throw error;\n\t\t\t\t\tawait writeAdapter(adapterInvocationId, legacyPatch);\n\t\t\t\t}\n\t\t\t}\n\t\t\tasync function evidence(transaction?: PlatformHostMutationTransaction<TDb>) {\n\t\t\t\tconst writes = [\n\t\t\t\t\t() => checkpoint(transaction),\n\t\t\t\t\t() => appendEvent(invocation, {\n\t\t\t\t\t\teventType: \"AdapterInvocationAmbiguous\",\n\t\t\t\t\t\tsubjectType: adapterEventSubject.subjectType,\n\t\t\t\t\t\tsubjectId: adapterEventSubject.subjectId,\n\t\t\t\t\t\tpayload: { adapterType, operation,\n\t\t\t\t\t\t\t...(externalReference ? { externalReference } : {}) },\n\t\t\t\t\t}, `adapter:${stepIndex}:ambiguous`, 1, transaction),\n\t\t\t\t\t...(governanceStore ? [() => (transaction ?? governanceStore).appendExternalReconciliation!({\n\t\t\t\t\t\tid: lifecycleId(\"rec\", actionInvocationId, `${vendor}:${adapterInvocationId}`),\n\t\t\t\t\t\tactionInvocationId, tenantId, spaceId, status: \"pending\", provider: vendor,\n\t\t\t\t\t\t...(externalReference ? { externalOperationId: externalReference } : {}),\n\t\t\t\t\t\tattempt: 1, reason: message, observedAt: now(),\n\t\t\t\t\t})] : []),\n\t\t\t\t];\n\t\t\t\tif (transaction) {\n\t\t\t\t\tfor (const write of writes) await write();\n\t\t\t\t} else {\n\t\t\t\t\tawait attemptEvidenceWrites(writes);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tasync function finalizeAtomically(): Promise<boolean> {\n\t\t\t\tconst atomicStore = asAtomicMutationStore(options.store);\n\t\t\t\tif (!atomicStore || ownVerdict) return false;\n\t\t\t\tconst previousStatus = invocation.status;\n\t\t\t\tlet verdictWritten = false;\n\t\t\t\tconst finalize = () => atomicStore.transactionWithEvents(async transaction => {\n\t\t\t\t\tif (!transaction.updateAdapterInvocation ||\n\t\t\t\t\t\t(options.store.writeAdapterInvocation && (executionLease || ownVerdict) && !transaction.writeAdapterInvocation) ||\n\t\t\t\t\t\t(governanceStore && !transaction.appendExternalReconciliation) ||\n\t\t\t\t\t\t(executionLease && !transaction.updateLeasedActionInvocation)) return false;\n\t\t\t\t\tawait evidence(transaction);\n\t\t\t\t\t// Evidence precedes the verdict, which releases the lease.\n\t\t\t\t\tif (executionLease) {\n\t\t\t\t\t\tconst updated = await transaction.updateLeasedActionInvocation!({\n\t\t\t\t\t\t\tid: actionInvocationId, tenantId, spaceId,\n\t\t\t\t\t\t\tworkerId: executionLease.leaseOwner, leaseToken: executionLease.leaseToken, patch,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (!updated) throw new RecoverableFinalizationError(`Invocation lease lost: ${actionInvocationId}`);\n\t\t\t\t\t\tverdictWritten = true;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tverdictWritten = await writeInlineInvocation(invocation, patch, transaction, onPreservedReconciliation);\n\t\t\t\t\t}\n\t\t\t\t\treturn true;\n\t\t\t\t});\n\t\t\t\tlet committed: boolean;\n\t\t\t\ttry {\n\t\t\t\t\tcommitted = await finalize();\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (error instanceof RecoverableFinalizationError) throw error;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tcommitted = await finalize();\n\t\t\t\t\t} catch (retryError) {\n\t\t\t\t\t\tif (retryError instanceof RecoverableFinalizationError) throw retryError;\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (committed && verdictWritten) {\n\t\t\t\t\trememberVerdict(patch);\n\t\t\t\t\temitInvocationStatusTelemetry(invocation, patch.status, options.telemetry, now(), previousStatus);\n\t\t\t\t}\n\t\t\t\treturn committed;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tif (!await finalizeAtomically()) {\n\t\t\t\t\tawait persistExecutionVerdict(invocation, patch, [() => evidence()]);\n\t\t\t\t}\n\t\t\t\treturn withConsistency(actionResult(invocation), invocation.actionId);\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof RecoverableFinalizationError) throw error;\n\t\t\t\tthrow new RecoverableFinalizationError(caughtError({ actionId: invocation.actionId, source: \"execution\" }, error));\n\t\t\t}\n\t\t}\n\t\tfunction recordedAdapterReconciliation(record: AdapterInvocationRecord): AdapterReconciliationOutcome {\n\t\t\tif (record.reconciliation) {\n\t\t\t\tconst { adapterEventSubject: _subject, ...outcome } = record.reconciliation;\n\t\t\t\treturn outcome;\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tkind: \"adapter_outcome_ambiguous\", adapterType: record.adapterType, operation: record.operation,\n\t\t\t\tvendor: record.vendor, adapterInvocationId: record.id,\n\t\t\t\tmessage: record.error ?? \"Adapter outcome was recorded ambiguous earlier; reconciliation required\",\n\t\t\t\t...(record.error ? { reason: record.error } : {}),\n\t\t\t};\n\t\t}\n\n\t\tconst action = actionResolver(invocation.actionId);\n\t\tif (action && (resumingRunningInvocation || invocation.attemptCount > 1)) {\n\t\t\ttry {\n\t\t\t\t// Reconcile recorded uncertainty before recovery can reject or rerun the action.\n\t\t\t\tfor (const [stepIndex] of (action.adapterSteps ?? []).entries()) {\n\t\t\t\t\tconst record = await options.store.getAdapterInvocation(lifecycleId(\"adp\", actionInvocationId, String(stepIndex)), adapterInvocationScope);\n\t\t\t\t\tif (record) adapterStatuses.set(record.id, record.status);\n\t\t\t\t\tif (record?.status === \"succeeded\") hasDurableProviderEffect = true;\n\t\t\t\t\tif (record?.status !== \"ambiguous\") continue;\n\t\t\t\t\treturn await settleUnknownOutcome(stepIndex, recordedAdapterReconciliation(record),\n\t\t\t\t\t\trecord.reconciliation?.adapterEventSubject);\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof RecoverableFinalizationError) throw error;\n\t\t\t\tthrow new RecoverableFinalizationError(caughtError({ actionId: invocation.actionId, source: \"execution\" }, error));\n\t\t\t}\n\t\t}\n\n\t\tif (invocation.status === \"running\" && invocation.pendingCompletion && !invocation.leaseOwner) {\n\t\t\t// Leased handoffs continue into checkpoint repair; unleased handoffs wait for completion.\n\t\t\treturn withConsistency(actionResult(invocation), invocation.actionId);\n\t\t}\n\t\tif (!action) {\n\t\t\treturn hostOperation(() => failExecution(invocation, \"failed\", `Unknown action: ${invocation.actionId}`));\n\t\t}\n\n\t\tif (action.admitSubmission !== undefined && !isAdmissionTime(invocation.admittedAt)) {\n\t\t\t// Created without this host's admission: by an older host, a direct\n\t\t\t// store write, or before the action declared its check.\n\t\t\treturn hostOperation(() => failExecution(\n\t\t\t\tinvocation,\n\t\t\t\t\"failed\",\n\t\t\t\t`Invocation of ${action.actionId} was not admitted at submission; an action that declares admitSubmission runs only on invocations its check admitted.`,\n\t\t\t));\n\t\t}\n\t\tif (action.kind === \"saga\") {\n\t\t\treturn hostOperation(() => failExecution(\n\t\t\t\tinvocation,\n\t\t\t\t\"failed\",\n\t\t\t\t`Saga action ${invocation.actionId} requires a durable PlatformActionDispatcher and cannot execute as an atomic Host action.`,\n\t\t\t));\n\t\t}\n\t\tasync function interruptedNonIdempotent(message: string): Promise<ExecuteActionResult> {\n\t\t\ttry {\n\t\t\t\tlet succeeded = invocation.pendingCompletion !== undefined;\n\t\t\t\tfor (const [stepIndex] of (action!.adapterSteps ?? []).entries()) {\n\t\t\t\t\tconst record = await options.store.getAdapterInvocation(lifecycleId(\"adp\", actionInvocationId, String(stepIndex)), adapterInvocationScope);\n\t\t\t\t\tif (record) adapterStatuses.set(record.id, record.status);\n\t\t\t\t\tif (record && record.id === invocation.pendingCompletion?.adapterInvocationId) continue;\n\t\t\t\t\tif (record?.status === \"running\") {\n\t\t\t\t\t\treturn await settleUnknownOutcome(stepIndex, {\n\t\t\t\t\t\t\tkind: \"adapter_outcome_ambiguous\", adapterInvocationId: record.id,\n\t\t\t\t\t\t\tadapterType: record.adapterType, operation: record.operation, vendor: record.vendor,\n\t\t\t\t\t\t\tmessage: `${message} Provider outcome was not recorded.`,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tsucceeded ||= record?.status === \"succeeded\";\n\t\t\t\t}\n\t\t\t\tif (succeeded) return await settleAppliedEffect(message, invocation.pendingCompletion);\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof RecoverableFinalizationError) throw error;\n\t\t\t\tthrow new RecoverableFinalizationError(caughtError({ actionId: invocation.actionId, source: \"execution\" }, error));\n\t\t\t}\n\t\t\treturn hostOperation(() => failExecution(invocation, \"failed\", message));\n\t\t}\n\n\t\tif (\n\t\t\tresumingRunningInvocation &&\n\t\t\tinvocation.attemptCount === 0 &&\n\t\t\t!invocation.leaseOwner &&\n\t\t\t!action.idempotent\n\t\t) {\n\t\t\treturn interruptedNonIdempotent(\n\t\t\t\t`Interrupted inline action ${invocation.actionId} is not declared idempotent; manual reconciliation is required.`,\n\t\t\t);\n\t\t}\n\t\tif (invocation.attemptCount > 1 && !action.idempotent) {\n\t\t\treturn interruptedNonIdempotent(\n\t\t\t\t`Interrupted action ${invocation.actionId} is not declared idempotent; manual reconciliation is required.`,\n\t\t\t);\n\t\t}\n\t\tif (invocation.status !== \"running\") {\n\t\t\tawait hostOperation(() => options.store.updateActionInvocation(actionInvocationId, tenantId, spaceId, {\n\t\t\t\tstatus: \"running\",\n\t\t\t}));\n\t\t}\n\t\temitPlatformHostTelemetry(options.telemetry, {\n\t\t\tkind: \"event\",\n\t\t\tname: \"invocation.execution_started\",\n\t\t\tmetricName: PLATFORM_HOST_METRIC_NAMES.invocationExecutionStarted,\n\t\t\toccurredAt: now(),\n\t\t\ttenantId,\n\t\t\tspaceId,\n\t\t\tattributes: { actionVersion: invocation.actionVersion },\n\t\t});\n\t\tlet retryableGovernance = true;\n\t\ttry {\n\n\t\tconst parsed = action.schema.safeParse(invocation.parameters);\n\t\tif (!parsed.success) {\n\t\t\tconst message = parsed.error.issues\n\t\t\t\t.map((issue) => `${issue.path.join(\".\") || \"(root)\"}: ${issue.message}`)\n\t\t\t\t.join(\"; \");\n\t\t\treturn hostOperation(() => failExecution(invocation, \"validation_failed\", message));\n\t\t}\n\n\t\tif (options.resolveMutationGovernance && !invocation.mutationFootprint) {\n\t\t\tconst governanceStore = asGovernanceStore(options.store);\n\t\t\tif (!governanceStore) {\n\t\t\t\treturn hostOperation(() => failExecution(invocation, \"failed\", \"The configured mutation-governance resolver requires a governance-capable store.\"));\n\t\t\t}\n\t\t\tconst context = await options.resolveMutationGovernance({\n\t\t\t\tactionInvocationId, actionId: action.actionId, tenantId, spaceId,\n\t\t\t\tactorId: invocation.actorId, actorType: invocation.actorType, parameters: parsed.data,\n\t\t\t});\n\t\t\tassertMutationGovernanceContext(context);\n\t\t\tinvocation = { ...await hostOperation(() => governanceStore.recordMutationGovernance(actionInvocationId, tenantId, spaceId, context)) };\n\t\t}\n\n\t\tif (invocation.actorType === \"agent\" && options.hitlEvaluator) {\n\t\t\tconst hitlParameters = isRecord(parsed.data) ? parsed.data : invocation.parameters;\n\t\t\tconst approvalStore = asApprovalStore(options.store);\n\t\t\tif (!approvalStore) {\n\t\t\t\treturn hostOperation(() => failExecution(\n\t\t\t\t\tinvocation,\n\t\t\t\t\t\"failed\",\n\t\t\t\t\t\"The configured HITL evaluator requires a store with approval persistence support.\",\n\t\t\t\t));\n\t\t\t}\n\t\t\tif (!invocation.hitlRoute) {\n\t\t\t\tconst decision = await options.hitlEvaluator({\n\t\t\t\t\tactionId: action.actionId,\n\t\t\t\t\tactorId: invocation.actorId,\n\t\t\t\t\tactorType: invocation.actorType,\n\t\t\t\t\ttenantId,\n\t\t\t\t\tspaceId,\n\t\t\t\t\tparameters: hitlParameters,\n\t\t\t\t\t...(numberValue(hitlParameters.confidence) !== undefined\n\t\t\t\t\t\t? { confidence: numberValue(hitlParameters.confidence) }\n\t\t\t\t\t\t: {}),\n\t\t\t\t\t...(isRiskTier(hitlParameters.riskTier)\n\t\t\t\t\t\t? { riskTier: hitlParameters.riskTier }\n\t\t\t\t\t\t: {}),\n\t\t\t\t\t...(stringValue(hitlParameters.agentSessionId)\n\t\t\t\t\t\t? { agentSessionId: stringValue(hitlParameters.agentSessionId) }\n\t\t\t\t\t\t: {}),\n\t\t\t\t\t...(stringValue(hitlParameters.agentRunId)\n\t\t\t\t\t\t? { agentRunId: stringValue(hitlParameters.agentRunId) }\n\t\t\t\t\t\t: {}),\n\t\t\t\t});\n\t\t\t\tinvocation = { ...await hostOperation(() => approvalStore.recordHitlDecision(\n\t\t\t\t\tactionInvocationId,\n\t\t\t\t\ttenantId,\n\t\t\t\t\tspaceId,\n\t\t\t\t\t{\n\t\t\t\t\t\t...decision,\n\t\t\t\t\t\t...(options.hitlPolicyVersion\n\t\t\t\t\t\t\t? { policyVersion: options.hitlPolicyVersion }\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\tevaluatedAt: now(),\n\t\t\t\t\t},\n\t\t\t\t)) };\n\t\t\t}\n\t\t\tif (invocation.hitlRoute === \"rejected\") {\n\t\t\t\treturn hostOperation(() => failExecution(\n\t\t\t\t\tinvocation,\n\t\t\t\t\t\"failed\",\n\t\t\t\t\t`HITL rejected: ${invocation.hitlReason ?? \"no reason provided\"}`,\n\t\t\t\t));\n\t\t\t}\n\t\t\tif (\n\t\t\t\t(invocation.hitlRoute === \"needs-approval\" ||\n\t\t\t\t\tinvocation.hitlRoute === \"escalate\") &&\n\t\t\t\t!invocation.approvalDecision?.approved\n\t\t\t) {\n\t\t\t\tawait hostOperation(() => persistExecutionInvocation(invocation, {\n\t\t\t\t\tstatus: \"waiting_for_approval\",\n\t\t\t\t}));\n\t\t\t\treturn {\n\t\t\t\t\t...actionResult(invocation),\n\t\t\t\t\tstatus: \"waiting_for_approval\",\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\tconst authorizationInput = toAuthorizationInput(action, invocation);\n\t\tconst executionReason = executionReasonOverride ??\n\t\t\t(invocation.attemptCount > 1 || (resumingRunningInvocation && invocation.attemptCount === 0)\n\t\t\t\t? \"recovery\"\n\t\t\t\t: invocation.executionReason ?? \"initial\");\n\t\tif (!(await options.authorization.checkEntitlement(authorizationInput))) {\n\t\t\treturn hostOperation(() => failExecution(\n\t\t\t\tinvocation,\n\t\t\t\t\"failed\",\n\t\t\t\t`Module \"${action.namespace}\" is no longer enabled for tenant ${tenantId}`,\n\t\t\t));\n\t\t}\n\t\tconst authorityMoment = action.execution?.authorityMoment;\n\t\tif (authorityMoment === \"capture\" && !invocation.authorizationBinding) {\n\t\t\tconst reconciliation = {\n\t\t\t\tkind: \"authorization_missing_capture_evidence\" as const,\n\t\t\t\tgoverningMoment: authorityMoment,\n\t\t\t\texecutionReason,\n\t\t\t\t...(invocation.provenance ? { provenance: invocation.provenance } : {}),\n\t\t\t\tmessage: `Action ${action.actionId} requires durable capture-time authorization evidence`,\n\t\t\t};\n\t\t\tawait hostOperation(() => persistExecutionInvocation(invocation, { status: \"reconciliation_required\", error: reconciliation.message, authorizationReconciliation: reconciliation }));\n\t\t\treturn withConsistency({ actionInvocationId, status: \"reconciliation_required\" as const, error: reconciliation.message, reconciliation }, action.actionId);\n\t\t}\n\t\tconst bindingExpired = authorityMoment !== \"capture\" && invocation.authorizationBinding?.expiresAt !== undefined &&\n\t\t\tDate.parse(invocation.authorizationBinding.expiresAt) <= now().getTime();\n\t\tif (bindingExpired) {\n\t\t\tconst reconciliation = {\n\t\t\t\tkind: \"authorization_expired\" as const,\n\t\t\t\tgoverningMoment: authorityMoment ?? \"both\",\n\t\t\t\texecutionReason,\n\t\t\t\t...(invocation.authorizationBindingId ? { authorizationBindingId: invocation.authorizationBindingId } : {}),\n\t\t\t\t...(invocation.provenance ? { provenance: invocation.provenance } : {}),\n\t\t\t\tmessage: `Authorization binding for action ${action.actionId} expired before execution`,\n\t\t\t};\n\t\t\tawait hostOperation(() => persistExecutionInvocation(invocation, { status: \"reconciliation_required\", error: reconciliation.message, authorizationReconciliation: reconciliation }));\n\t\t\treturn withConsistency({ actionInvocationId, status: \"reconciliation_required\" as const, error: reconciliation.message, reconciliation }, action.actionId);\n\t\t}\n\t\tconst executionAuthorized = authorityMoment === \"capture\"\n\t\t\t? invocation.authorizationBinding !== undefined\n\t\t\t: options.authorization.authorizeExecution\n\t\t\t\t? await options.authorization.authorizeExecution({\n\t\t\t\t\t...authorizationInput,\n\t\t\t\t\tactionInvocationId,\n\t\t\t\t\tparameters: parsed.data,\n\t\t\t\t\tinvocation,\n\t\t\t\t\texecutionReason,\n\t\t\t\t})\n\t\t\t\t: await options.authorization.authorize(authorizationInput);\n\t\tif (!executionAuthorized) {\n\t\t\tif (!action.execution) {\n\t\t\t\treturn hostOperation(() => failExecution(invocation, \"failed\", `Actor ${invocation.actorId} is not authorized to execute action ${action.actionId}`));\n\t\t\t}\n\t\t\tconst reconciliation = {\n\t\t\t\tkind: \"authorization_denied\" as const,\n\t\t\t\tgoverningMoment: action.execution?.authorityMoment ?? \"both\",\n\t\t\t\texecutionReason,\n\t\t\t\t...(invocation.authorizationBindingId ? { authorizationBindingId: invocation.authorizationBindingId } : {}),\n\t\t\t\t...(invocation.provenance ? { provenance: invocation.provenance } : {}),\n\t\t\t\tmessage: `Actor ${invocation.actorId} is not authorized to execute action ${action.actionId}`,\n\t\t\t};\n\t\t\tawait hostOperation(() => persistExecutionInvocation(invocation, { status: \"reconciliation_required\", error: reconciliation.message, authorizationReconciliation: reconciliation }));\n\t\t\treturn withConsistency({ actionInvocationId, status: \"reconciliation_required\" as const, error: reconciliation.message, reconciliation }, action.actionId);\n\t\t}\n\t\tconst definitions = options.resolvePolicies\n\t\t\t? await options.resolvePolicies({\n\t\t\t\t\t...authorizationInput,\n\t\t\t\t\tactionInvocationId,\n\t\t\t\t\tparameters: parsed.data,\n\t\t\t\t\tinvocation,\n\t\t\t\t\texecutionReason,\n\t\t\t\t\tdeclaredPolicyIds: action.policies ?? [],\n\t\t\t\t})\n\t\t\t: declaredPolicies(action.policies ?? []);\n\t\tconst outcomes = await evaluatePolicyDefinitions(definitions, {\n\t\t\ttenantId,\n\t\t\tspaceId,\n\t\t\tactionInvocationId,\n\t\t\tactionId: action.actionId,\n\t\t\tactorId: invocation.actorId,\n\t\t\tactorType: invocation.actorType,\n\t\t\tparameters: parsed.data,\n\t\t\tdb: options.store.db,\n\t\t\tservices: options.services,\n\t\t\tresolveCodePolicy: options.registry?.resolvePolicy,\n\t\t\tmode: \"execute\",\n\t\t\tnow: now(),\n\t\t});\n\t\t// End deferral before policy evidence can fix a decision for this attempt.\n\t\tretryableGovernance = false;\n\t\tfor (const outcome of outcomes) {\n\t\t\tawait hostOperation(() => options.store.appendPolicyEvaluation({\n\t\t\t\tid: lifecycleId(\"pol\", actionInvocationId, outcome.policyId),\n\t\t\t\tactionInvocationId,\n\t\t\t\ttenantId,\n\t\t\t\tspaceId,\n\t\t\t\toutcome,\n\t\t\t\tcreatedAt: now(),\n\t\t\t}));\n\t\t}\n\t\tconst aggregate = aggregatePolicyOutcomes(outcomes);\n\t\tif (aggregate?.result === \"block\") {\n\t\t\tconst reason = aggregate.reason ?? `Blocked by policy ${aggregate.policyId}`;\n\t\t\tawait hostOperation(() => appendEvent(invocation, {\n\t\t\t\teventType: \"ComplianceBlocked\",\n\t\t\t\tsubjectType: \"ActionInvocation\",\n\t\t\t\tsubjectId: actionInvocationId,\n\t\t\t\tpayload: { actionId: action.actionId, policyId: aggregate.policyId, reason },\n\t\t\t}, `compliance:${aggregate.policyId}`));\n\t\t\treturn hostOperation(() => failExecution(invocation, \"blocked_by_policy\", reason));\n\t\t}\n\t\tif (options.resolvePolicyObligations) {\n\t\t\tconst governanceStore = asGovernanceStore(options.store);\n\t\t\tif (!governanceStore) {\n\t\t\t\treturn hostOperation(() => failExecution(invocation, \"failed\", \"Policy obligations require a governance-capable store.\"));\n\t\t\t}\n\t\t\tconst existing = await hostOperation(() => governanceStore.listPolicyObligations(actionInvocationId, tenantId, spaceId));\n\t\t\tif (existing.length === 0) {\n\t\t\t\tconst createdAt = now();\n\t\t\t\tconst obligations = await options.resolvePolicyObligations(outcomes);\n\t\t\t\tawait hostOperation(() => governanceStore.appendPolicyObligations(obligations.map((obligation) => ({\n\t\t\t\t\t...obligation, status: obligation.status ?? \"pending\", actionInvocationId,\n\t\t\t\t\ttenantId, spaceId, createdAt, updatedAt: createdAt,\n\t\t\t\t}))));\n\t\t\t}\n\t\t}\n\n\t\tlet data: Record<string, unknown>;\n\t\tlet domainEvents: PendingAssetEvent[] = [];\n\t\tlet pendingTransitionEvent: PendingAssetEvent | undefined;\n\t\ttry {\n\t\t\tconst runHandler = async (\n\t\t\t\tdb: TDb,\n\t\t\t\ttransaction?: PlatformHostMutationTransaction<TDb>,\n\t\t\t) => {\n\t\t\t\tif (options.outbox && !transaction?.appendEventWithOutbox) {\n\t\t\t\t\tthrow new HostError(\"Outbox egress requires transactionWithEvents to provide appendEventWithOutbox before handler execution.\");\n\t\t\t\t}\n\t\t\t\tconst binding = action.stateMachine;\n\t\t\t\tlet replayedTransition: ActionInvocationRecord[\"pendingStateTransition\"];\n\t\t\t\tlet pendingStateTransition: ActionInvocationRecord[\"pendingStateTransition\"];\n\t\t\t\tlet validatedTransition: {\n\t\t\t\t\tentityId: string | undefined;\n\t\t\t\t\tcurrentState: string;\n\t\t\t\t\ttargetState: string;\n\t\t\t\t\tvalid: boolean;\n\t\t\t\t} | undefined;\n\t\t\t\tif (binding) {\n\t\t\t\t\tconst machine = stateMachineResolver(binding.entityType);\n\t\t\t\t\tconst entityId = binding.getEntityId(parsed.data);\n\t\t\t\t\tconst getEntityState = transaction?.getEntityState\n\t\t\t\t\t\t? transaction.getEntityState.bind(transaction)\n\t\t\t\t\t\t: options.store.getEntityState.bind(options.store);\n\t\t\t\t\tconst currentState = entityId\n\t\t\t\t\t\t? ((await hostOperation(() => getEntityState(\n\t\t\t\t\t\t\t\ttenantId,\n\t\t\t\t\t\t\t\tspaceId,\n\t\t\t\t\t\t\t\tbinding.entityType,\n\t\t\t\t\t\t\t\tentityId,\n\t\t\t\t\t\t\t))) ?? initialState(machine))\n\t\t\t\t\t\t: initialState(machine);\n\t\t\t\t\tconst targetState =\n\t\t\t\t\t\ttypeof binding.targetState === \"function\"\n\t\t\t\t\t\t\t? binding.targetState(parsed.data)\n\t\t\t\t\t\t\t: binding.targetState;\n\t\t\t\t\tif (targetState !== \"\") {\n\t\t\t\t\t\tconst transition = await evaluateStateMachineTransition(\n\t\t\t\t\t\t\tmachine,\n\t\t\t\t\t\t\tbinding.entityType,\n\t\t\t\t\t\t\tcurrentState,\n\t\t\t\t\t\t\ttargetState,\n\t\t\t\t\t\t\taction.actionId,\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tentity: {\n\t\t\t\t\t\t\t\t\t...(entityId ? { id: entityId } : {}),\n\t\t\t\t\t\t\t\t\tstate: currentState,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tactionInvocationId,\n\t\t\t\t\t\t\t\tactorId: invocation.actorId,\n\t\t\t\t\t\t\t\tparameters: parsed.data,\n\t\t\t\t\t\t\t\tdb,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t);\n\t\t\t\t\t\tvalidatedTransition = { entityId, currentState, targetState, valid: transition.valid };\n\t\t\t\t\t\tlet replayingAppliedTransition = false;\n\t\t\t\t\t\tif (action.idempotent && currentState === targetState && !transition.valid && entityId) {\n\t\t\t\t\t\t\tlet source: { state: string; actionInvocationId: string } | undefined;\n\t\t\t\t\t\t\tif (transaction?.getEntityStateSource) {\n\t\t\t\t\t\t\t\tsource = await hostOperation(() => transaction.getEntityStateSource!(tenantId, spaceId, binding.entityType, entityId));\n\t\t\t\t\t\t\t} else if (options.store.getEntityStateSource) {\n\t\t\t\t\t\t\t\tsource = await hostOperation(() => options.store.getEntityStateSource!(tenantId, spaceId, binding.entityType, entityId));\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tconst eventStore = options.store as typeof options.store & {\n\t\t\t\t\t\t\t\t\tlistEvents?: (tenantId: string, spaceId: string) => Promise<AssetEventEnvelope[]>;\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\tconst listEvents = transaction?.listEvents?.bind(transaction) ?? eventStore.listEvents?.bind(eventStore);\n\t\t\t\t\t\t\t\tconst events = listEvents ? await hostOperation(() => listEvents(tenantId, spaceId)) : [];\n\t\t\t\t\t\t\t\tlet latest: AssetEventEnvelope | undefined;\n\t\t\t\t\t\t\t\tfor (const event of events) {\n\t\t\t\t\t\t\t\t\tif (event.tenantId === tenantId && event.spaceId === spaceId &&\n\t\t\t\t\t\t\t\t\t\tevent.subjectType === binding.entityType && event.subjectId === entityId &&\n\t\t\t\t\t\t\t\t\t\ttypeof (event.payload as { toState?: unknown } | undefined)?.toState === \"string\" &&\n\t\t\t\t\t\t\t\t\t\t(!latest || event.sequence > latest.sequence)) latest = event;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (latest && typeof latest.actionInvocationId === \"string\") {\n\t\t\t\t\t\t\t\t\tsource = { state: (latest.payload as { toState: string }).toState, actionInvocationId: latest.actionInvocationId };\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treplayingAppliedTransition = source?.actionInvocationId === actionInvocationId && source.state === currentState;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst pending = invocation.pendingStateTransition;\n\t\t\t\t\t\tif (replayingAppliedTransition && pending &&\n\t\t\t\t\t\t\tpending.entityType === binding.entityType && pending.entityId === entityId &&\n\t\t\t\t\t\t\tpending.toState === currentState) {\n\t\t\t\t\t\t\treplayedTransition = pending;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (action.idempotent && transition.valid && entityId && action.eventPhase === \"after_adapters\") {\n\t\t\t\t\t\t\tpendingStateTransition = {\n\t\t\t\t\t\t\t\tentityType: binding.entityType, entityId, fromState: currentState, toState: targetState,\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tif (!transaction) {\n\t\t\t\t\t\t\t\tawait hostOperation(() => options.store.updateActionInvocation(actionInvocationId, tenantId, spaceId, { pendingStateTransition }));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!transition.valid && !replayingAppliedTransition) {\n\t\t\t\t\t\t\tthrow transition.error != null ? new Error(transition.error) : new HostError(\"Invalid state transition\");\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst handlerResult = action.handler\n\t\t\t\t\t? await action.handler(\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tactionInvocationId,\n\t\t\t\t\t\t\t\ttenantId,\n\t\t\t\t\t\t\t\tspaceId,\n\t\t\t\t\t\t\t\tactorId: invocation.actorId,\n\t\t\t\t\t\t\t\tactorType: invocation.actorType,\n\t\t\t\t\t\t\t\tcorrelationId: invocation.correlationId,\n\t\t\t\t\t\t\t\t...(invocation.causationId ? { causationId: invocation.causationId } : {}),\n\t\t\t\t\t\t\t\t...(invocation.provenance ? { provenance: invocation.provenance } : {}),\n\t\t\t\t\t\t\t\t...(isAdmissionTime(invocation.admittedAt) ? { admittedAt: invocation.admittedAt } : {}),\n\t\t\t\t\t\t\t\tdb,\n\t\t\t\t\t\t\t\tservices: options.services,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tparsed.data,\n\t\t\t\t\t\t)\n\t\t\t\t\t: { success: true as const, data: {} };\n\t\t\t\tif (!handlerResult.success) {\n\t\t\t\t\tthrow handlerResult.error != null ? new Error(handlerResult.error) : new HostError(\"Action handler failed\");\n\t\t\t\t}\n\t\t\t\tconst handlerData = handlerResult.data ?? {};\n\t\t\t\tif (action.resultSchema) {\n\t\t\t\t\tconst publicResult = withoutPrivateHostFields(handlerData, eventResultFields);\n\t\t\t\t\tconst parsedResult = action.resultSchema.safeParse(publicResult);\n\t\t\t\t\tif (!parsedResult.success) {\n\t\t\t\t\t\tthrow new HostError(`Action result validation failed at ${parsedResult.error.issues\n\t\t\t\t\t\t\t.map((issue) => issue.path.map(String).join(\".\") || \"result\")\n\t\t\t\t\t\t\t.join(\", \")}`);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst events = extractEvents(handlerData);\n\t\t\t\tconst undeclaredEvent = events.find(\n\t\t\t\t\t(event) => !action.emitsEvents.includes(event.eventType),\n\t\t\t\t);\n\t\t\t\tif (undeclaredEvent) {\n\t\t\t\t\tthrow new HostError(\n\t\t\t\t\t\t`${action.actionId} emitted undeclared event type ${undeclaredEvent.eventType}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (action.eventPhase !== \"after_adapters\") {\n\t\t\t\t\tfor (const [index, event] of events.entries()) {\n\t\t\t\t\t\tawait hostOperation(() => appendEvent(\n\t\t\t\t\t\t\tinvocation,\n\t\t\t\t\t\t\tevent,\n\t\t\t\t\t\t\t`domain:${index}`,\n\t\t\t\t\t\t\taction.version,\n\t\t\t\t\t\t\ttransaction,\n\t\t\t\t\t\t));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tlet transitionEvent: PendingAssetEvent | undefined;\n\t\t\t\tif (binding && validatedTransition?.entityId && (validatedTransition.valid || replayedTransition)) {\n\t\t\t\t\tconst { entityId, currentState, targetState } = validatedTransition;\n\t\t\t\t\tconst handlerEmittedTransition = events.some((event) =>\n\t\t\t\t\t\tevent.eventType === \"StateTransitioned\" &&\n\t\t\t\t\t\tevent.subjectType === binding.entityType && event.subjectId === entityId);\n\t\t\t\t\tif (!handlerEmittedTransition) {\n\t\t\t\t\t\ttransitionEvent = {\n\t\t\t\t\t\t\teventType: \"StateTransitioned\",\n\t\t\t\t\t\t\tsubjectType: binding.entityType,\n\t\t\t\t\t\t\tsubjectId: entityId,\n\t\t\t\t\t\t\tpayload: {\n\t\t\t\t\t\t\t\tentityType: binding.entityType, entityId, fromState: replayedTransition?.fromState ?? currentState,\n\t\t\t\t\t\t\t\ttoState: targetState, causedByAction: action.actionId,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (transitionEvent && action.eventPhase !== \"after_adapters\") {\n\t\t\t\t\tawait hostOperation(() => appendEvent(invocation, transitionEvent, \"state:transition\", 1, transaction));\n\t\t\t\t}\n\t\t\t\tif (transaction && pendingStateTransition) {\n\t\t\t\t\tawait hostOperation(() => transaction.updateActionInvocation(actionInvocationId, tenantId, spaceId, { pendingStateTransition }));\n\t\t\t\t}\n\t\t\t\treturn { data: handlerData, domainEvents: events, pendingTransitionEvent: transitionEvent };\n\t\t\t};\n\t\t\tconst atomicStore = asAtomicMutationStore(options.store);\n\t\t\t// A failed callback is a handler outcome; an entry/commit error belongs to the store.\n\t\t\t// A store may rethrow the callback's error wrapped, so classify by where it failed,\n\t\t\t// not by identity, and rethrow the callback's own error.\n\t\t\tlet callbackFailure: { error: unknown } | undefined;\n\t\t\tconst run = async (db: TDb, transaction?: PlatformHostMutationTransaction<TDb>) => {\n\t\t\t\tcallbackFailure = undefined;\n\t\t\t\ttry { return await runHandler(db, transaction); }\n\t\t\t\tcatch (error) { callbackFailure = { error }; throw error; }\n\t\t\t};\n\t\t\tconst executed = await (async () => {\n\t\t\t\ttry {\n\t\t\t\t\treturn atomicStore\n\t\t\t\t\t\t? await atomicStore.transactionWithEvents(transaction => run(transaction.db, transaction))\n\t\t\t\t\t\t: await options.store.transaction(db => run(db));\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (callbackFailure) throw callbackFailure.error;\n\t\t\t\t\treturn hostOperation(() => Promise.reject(error));\n\t\t\t\t}\n\t\t\t})();\n\t\t\tdata = executed.data;\n\t\t\tdomainEvents = executed.domainEvents;\n\t\t\tpendingTransitionEvent = executed.pendingTransitionEvent;\n\t\t} catch (error) {\n\t\t\tif (error instanceof RecoverableFinalizationError) throw error;\n\t\t\tif (isReconciliationRequiredError(error)) {\n\t\t\t\tconst message = caughtError({ actionId: invocation.actionId, source: \"handler\" }, error);\n\t\t\t\tawait hostOperation(() => persistExecutionInvocation(invocation, { status: \"reconciliation_required\", error: message }));\n\t\t\t\treturn withConsistency({\n\t\t\t\t\tactionInvocationId,\n\t\t\t\t\tstatus: \"reconciliation_required\" as const,\n\t\t\t\t\terror: message,\n\t\t\t\t\t...(invocation.hitlRoute ? { hitlRoute: invocation.hitlRoute } : {}),\n\t\t\t\t\t...(invocation.hitlRiskTier ? { hitlRiskTier: invocation.hitlRiskTier } : {}),\n\t\t\t\t}, action.actionId);\n\t\t\t}\n\t\t\treturn hostOperation(() => failExecution(invocation, \"failed\", caughtError({ actionId: invocation.actionId, source: \"handler\" }, error)));\n\t\t}\n\n\t\t// At most one adapter step may hand the work off to finish elsewhere. Two\n\t\t// would leave the invocation waiting on two references with one status.\n\t\t// A handoff is persisted the moment it is accepted, before the step is\n\t\t// marked done, so a crash between the two leaves the handoff and not\n\t\t// the marker: on re-execution the step is skipped and the handoff kept.\n\t\tlet pendingHandoff: PendingExternalCompletion | undefined = invocation.pendingCompletion;\n\t\tfor (const [stepIndex, step] of (action.adapterSteps ?? []).entries()) {\n\t\t\tconst adapterInvocationId = lifecycleId(\"adp\", actionInvocationId, String(stepIndex));\n\t\t\tlet previousAdapterInvocation: AdapterInvocationRecord | undefined;\n\t\t\ttry {\n\t\t\t\tpreviousAdapterInvocation = await options.store.getAdapterInvocation(adapterInvocationId, adapterInvocationScope);\n\t\t\t\tif (previousAdapterInvocation) adapterStatuses.set(adapterInvocationId, previousAdapterInvocation.status);\n\t\t\t\tconst handoff = pendingHandoff?.adapterInvocationId === adapterInvocationId ? pendingHandoff : undefined;\n\t\t\t\tif (previousAdapterInvocation?.status === \"succeeded\" || handoff) {\n\t\t\t\t\thasDurableProviderEffect = true;\n\t\t\t\t\tif (!previousAdapterInvocation) throw new HostError(\"Durable handoff has no adapter checkpoint; evidence repair requires reconciliation.\");\n\t\t\t\t\tconst row = previousAdapterInvocation;\n\t\t\t\t\tconst subject = options.adapterEventSubject?.(action.actionId, parsed.data, data)\n\t\t\t\t\t\t?? { subjectType: \"AdapterInvocation\", subjectId: adapterInvocationId };\n\t\t\t\t\tif (row.status !== \"succeeded\") {\n\t\t\t\t\t\tawait writeAdapter(adapterInvocationId, { status: \"succeeded\", updatedAt: now() });\n\t\t\t\t\t}\n\t\t\t\t\tif (handoff) await appendEvent(invocation, {\n\t\t\t\t\t\teventType: \"ExternalOperationAccepted\", ...subject,\n\t\t\t\t\t\tpayload: { adapterType: row.adapterType, operation: row.operation, externalReference: handoff.externalReference,\n\t\t\t\t\t\t\t...(handoff.dueAt ? { dueAt: handoff.dueAt.toISOString() } : {}) },\n\t\t\t\t\t}, `adapter:${stepIndex}:accepted`);\n\t\t\t\t\tconst governanceStore = asGovernanceStore(options.store);\n\t\t\t\t\tconst attestationId = lifecycleId(\"att\", actionInvocationId, adapterInvocationId);\n\t\t\t\t\tconst existing = governanceStore\n\t\t\t\t\t\t? (await governanceStore.listExecutionAttestations(actionInvocationId, tenantId, spaceId)).find(item => item.id === attestationId)\n\t\t\t\t\t\t: undefined;\n\t\t\t\t\tif (existing) {\n\t\t\t\t\t\tfor (const obligationId of existing.satisfiesObligations ?? []) {\n\t\t\t\t\t\t\tawait governanceStore!.updatePolicyObligation(actionInvocationId, obligationId, \"satisfied\", existing.evidenceReferences);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (options.extractExecutionAttestation && row.output !== undefined) {\n\t\t\t\t\t\tconst attestation = await options.extractExecutionAttestation({\n\t\t\t\t\t\t\tactionInvocationId, adapterInvocationId, adapterType: row.adapterType, operation: row.operation,\n\t\t\t\t\t\t\tvendor: row.vendor, input: row.input, output: row.output, startedAt: row.createdAt, completedAt: row.updatedAt,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (attestation) await recordExecutionAttestation(actionInvocationId, tenantId, spaceId, attestation, adapterInvocationId);\n\t\t\t\t\t}\n\t\t\t\t\tawait appendEvent(invocation, {\n\t\t\t\t\t\teventType: \"AdapterInvocationSucceeded\", ...subject,\n\t\t\t\t\t\tpayload: { adapterType: row.adapterType, operation: row.operation, input: row.input,\n\t\t\t\t\t\t\t...(row.output !== undefined ? { output: row.output } : {}), recovered: true },\n\t\t\t\t\t}, `adapter:${stepIndex}:succeeded`);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof RecoverableFinalizationError) throw error;\n\t\t\t\tthrow new RecoverableFinalizationError(caughtError({ actionId: invocation.actionId, source: \"execution\" }, error));\n\t\t\t}\n\t\t\tif (previousAdapterInvocation?.status === \"ambiguous\") {\n\t\t\t\treturn await settleUnknownOutcome(stepIndex, recordedAdapterReconciliation(previousAdapterInvocation),\n\t\t\t\t\tpreviousAdapterInvocation.reconciliation?.adapterEventSubject);\n\t\t\t}\n\t\t\tconst input = step.getInput(parsed.data, data);\n\t\t\tif (!input) continue;\n\t\t\tconst adapter = adapters.require(step.adapterType, step.operation);\n\t\t\tconst adapterEventSubject = options.adapterEventSubject?.(\n\t\t\t\taction.actionId,\n\t\t\t\tparsed.data,\n\t\t\t\tdata,\n\t\t\t) ?? { subjectType: \"AdapterInvocation\", subjectId: adapterInvocationId };\n\t\t\tconst settleStepUnknownOutcome = (reconciliation: AdapterReconciliationOutcome) =>\n\t\t\t\tsettleUnknownOutcome(stepIndex, reconciliation, adapterEventSubject);\n\t\t\tconst recordedInput = options.redactAdapterInput\n\t\t\t\t? options.redactAdapterInput(\n\t\t\t\t\t\taction.actionId,\n\t\t\t\t\t\tstep.adapterType,\n\t\t\t\t\t\tstep.operation,\n\t\t\t\t\t\tinput,\n\t\t\t\t\t)\n\t\t\t\t: input;\n\t\t\tconst startedAt = now();\n\t\t\tconst record: AdapterInvocationRecord = {\n\t\t\t\tid: adapterInvocationId,\n\t\t\t\t...adapterInvocationScope,\n\t\t\t\tadapterType: step.adapterType,\n\t\t\t\toperation: step.operation,\n\t\t\t\tvendor: adapter.vendor,\n\t\t\t\tstatus: \"running\",\n\t\t\t\tinput: recordedInput,\n\t\t\t\tattempt: 1,\n\t\t\t\tcreatedAt: startedAt,\n\t\t\t\tupdatedAt: startedAt,\n\t\t\t};\n\t\t\tif (!previousAdapterInvocation || !executionLease || !options.store.writeAdapterInvocation) await hostOperation(() => createAdapter(record));\n\t\t\tawait hostOperation(() => appendEvent(invocation, {\n\t\t\t\teventType: \"AdapterInvocationStarted\",\n\t\t\t\tsubjectType: adapterEventSubject.subjectType,\n\t\t\t\tsubjectId: adapterEventSubject.subjectId,\n\t\t\t\tpayload: { adapterType: step.adapterType, operation: step.operation },\n\t\t\t}, `adapter:${stepIndex}:started`));\n\t\t\tasync function appendDegradedAdapterEvidence(\n\t\t\t\toutputWithheld: boolean,\n\t\t\t\tmessage: string,\n\t\t\t\taccepted?: PendingExternalCompletion,\n\t\t\t\toutput?: Record<string, unknown>,\n\t\t\t\texternalReference?: string,\n\t\t\t\ttransaction?: PlatformHostMutationTransaction<TDb>,\n\t\t\t): Promise<void> {\n\t\t\t\tconst writes: Array<() => Promise<void>> = [];\n\t\t\t\tif (accepted) {\n\t\t\t\t\twrites.push(() => appendEvent(invocation, {\n\t\t\t\t\t\teventType: \"ExternalOperationAccepted\",\n\t\t\t\t\t\tsubjectType: adapterEventSubject.subjectType,\n\t\t\t\t\t\tsubjectId: adapterEventSubject.subjectId,\n\t\t\t\t\t\tpayload: { adapterType: step.adapterType, operation: step.operation, externalReference: accepted.externalReference,\n\t\t\t\t\t\t\t...(accepted.dueAt ? { dueAt: accepted.dueAt.toISOString() } : {}) },\n\t\t\t\t\t}, `adapter:${stepIndex}:accepted`, 1, transaction));\n\t\t\t\t}\n\t\t\t\twrites.push(() => appendEvent(invocation, {\n\t\t\t\t\teventType: \"AdapterInvocationSucceeded\",\n\t\t\t\t\tsubjectType: adapterEventSubject.subjectType,\n\t\t\t\t\tsubjectId: adapterEventSubject.subjectId,\n\t\t\t\t\tpayload: { adapterType: step.adapterType, operation: step.operation, input: recordedInput,\n\t\t\t\t\t\t...(!outputWithheld && externalReference ? { externalReference } : {}),\n\t\t\t\t\t\t...(outputWithheld ? { outputWithheld: true } : { output }) },\n\t\t\t\t}, `adapter:${stepIndex}:succeeded`, 1, transaction));\n\t\t\t\tconst governanceStore = asGovernanceStore(options.store);\n\t\t\t\tif (!outputWithheld && externalReference && governanceStore) {\n\t\t\t\t\twrites.push(() => externalCompletion.recordCompletionReconciliation(invocation,\n\t\t\t\t\t\t{ externalReference, provider: adapter.vendor }, message, transaction));\n\t\t\t\t}\n\t\t\t\tif (outputWithheld && governanceStore) {\n\t\t\t\t\twrites.push(() => (transaction ?? governanceStore).appendExternalReconciliation!({\n\t\t\t\t\t\tid: lifecycleId(\"rec\", actionInvocationId, `${adapter.vendor}:${adapterInvocationId}`),\n\t\t\t\t\t\tactionInvocationId, tenantId, spaceId, status: \"pending\", provider: adapter.vendor,\n\t\t\t\t\t\t...((externalReference ?? accepted?.externalReference) ? { externalOperationId: externalReference ?? accepted?.externalReference } : {}),\n\t\t\t\t\t\tattempt: 1, reason: message, observedAt: now(),\n\t\t\t\t\t}));\n\t\t\t\t}\n\t\t\t\tif (transaction) {\n\t\t\t\t\tfor (const write of writes) await write();\n\t\t\t\t} else {\n\t\t\t\t\tawait attemptEvidenceWrites(writes);\n\t\t\t\t}\n\t\t\t}\n\t\t\tasync function finalizeDegradedAdapterAtomically(\n\t\t\t\tpatch: ActionInvocationPatch,\n\t\t\t\toutputWithheld: boolean,\n\t\t\t\tmessage: string,\n\t\t\t\taccepted?: PendingExternalCompletion,\n\t\t\t\toutput?: Record<string, unknown>,\n\t\t\t\texternalReference?: string,\n\t\t\t): Promise<boolean> {\n\t\t\t\tconst atomicStore = asAtomicMutationStore(options.store);\n\t\t\t\tif (!atomicStore) return false;\n\t\t\t\tconst needsReconciliation = (outputWithheld || !!externalReference) && !!asGovernanceStore(options.store);\n\t\t\t\tconst previousStatus = invocation.status;\n\t\t\t\tlet verdictWritten = false;\n\t\t\t\tconst finalize = () => atomicStore.transactionWithEvents(async (transaction) => {\n\t\t\t\t\t// Probe before writing anything. Older/custom transactions keep the\n\t\t\t\t\t// verdict-first fallback unless they can commit all required evidence.\n\t\t\t\t\tif (!transaction.updateAdapterInvocation ||\n\t\t\t\t\t\t(options.store.writeAdapterInvocation && (executionLease || ownVerdict) && !transaction.writeAdapterInvocation) ||\n\t\t\t\t\t\t(needsReconciliation && !transaction.appendExternalReconciliation) ||\n\t\t\t\t\t\t(executionLease && !transaction.updateLeasedActionInvocation)) return false;\n\t\t\t\t\tawait appendDegradedAdapterEvidence(outputWithheld, message, accepted, output, externalReference, transaction);\n\t\t\t\t\tawait writeAdapter(adapterInvocationId, {\n\t\t\t\t\t\tstatus: \"succeeded\", ...(outputWithheld ? {} : { output }), updatedAt: now(),\n\t\t\t\t\t}, transaction);\n\t\t\t\t\t// The terminal update releases the lease. Keep it last so stores\n\t\t\t\t\t// fencing evidence on a live invocation can admit preceding writes.\n\t\t\t\t\tif (executionLease) {\n\t\t\t\t\t\tif (!transaction.updateLeasedActionInvocation) {\n\t\t\t\t\t\t\tthrow new HostError(\"Leased atomic finalization requires transaction-scoped fencing support.\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst updated = await transaction.updateLeasedActionInvocation({\n\t\t\t\t\t\t\tid: actionInvocationId, tenantId, spaceId,\n\t\t\t\t\t\t\tworkerId: executionLease.leaseOwner, leaseToken: executionLease.leaseToken, patch,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (!updated) throw new RecoverableFinalizationError(`Invocation lease lost: ${actionInvocationId}`);\n\t\t\t\t\t\tverdictWritten = true;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tverdictWritten = await writeInlineInvocation(invocation, patch, transaction, onPreservedReconciliation);\n\t\t\t\t\t}\n\t\t\t\t\treturn true;\n\t\t\t\t});\n\t\t\t\tlet committed: boolean;\n\t\t\t\ttry {\n\t\t\t\t\tcommitted = await finalize();\n\t\t\t\t} catch (error) {\n\t\t\t\t\t// Retry the whole rolled-back unit once, matching verdict retry\n\t\t\t\t\t// semantics. Lease loss must retain its fence and is not retried.\n\t\t\t\t\tif (error instanceof RecoverableFinalizationError) throw error;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tcommitted = await finalize();\n\t\t\t\t\t} catch (retryError) {\n\t\t\t\t\t\tif (retryError instanceof RecoverableFinalizationError) throw retryError;\n\t\t\t\t\t\t// Repeated non-lease failures select the verdict-first fallback\n\t\t\t\t\t\t// so recovery does not keep repeating the applied adapter effect.\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (committed) {\n\t\t\t\t\tif (verdictWritten) rememberVerdict(patch);\n\t\t\t\t\tmarkerDurable = true;\n\t\t\t\t\thasDurableProviderEffect = true;\n\t\t\t\t\thandoffDurable = accepted !== undefined;\n\t\t\t\t\tif (verdictWritten) emitInvocationStatusTelemetry(invocation, patch.status, options.telemetry, now(), previousStatus);\n\t\t\t\t}\n\t\t\t\treturn committed;\n\t\t\t}\n\t\t\tconst adapterErrorContext: ErrorTextRedactionContext = { actionId: action.actionId, source: \"adapter\", adapterType: step.adapterType, operation: step.operation, provider: adapter.vendor };\n\t\t\tconst executionErrorContext: ErrorTextRedactionContext = { actionId: action.actionId, source: \"execution\" };\n\t\t\tlet errorContext = executionErrorContext;\n\t\t\tlet adapterCallThrew = false;\n\t\t\tlet providerReturned = false;\n\t\t\tlet providerOutcome: import(\"@fabricorg/platform\").AdapterOutcomeKind | undefined;\n\t\t\tlet finalizingProviderResult = false;\n\t\t\tlet providerReportedSuccess = false;\n\t\t\tlet handoffDurable = false;\n\t\t\tlet markerDurable = false;\n\t\t\tlet successOutput: Record<string, unknown> | undefined;\n\t\t\tasync function writeSuccessCheckpoint(write: () => Promise<void>): Promise<void> {\n\t\t\t\ttry { await write(); } catch (error) {\n\t\t\t\t\tif (error instanceof RecoverableFinalizationError || handoffDurable || markerDurable) throw error;\n\t\t\t\t\tawait write();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlet thrownOutcome: import(\"@fabricorg/platform\").AdapterOutcomeKind | undefined;\n\t\t\tlet adapterDeadlineTimer: ReturnType<typeof setTimeout> | undefined;\n\t\t\ttry {\n\t\t\t\tconst adapterController = options.adapterDeadlineMs\n\t\t\t\t\t? new AbortController()\n\t\t\t\t\t: undefined;\n\t\t\t\tconst deadlineMs = options.adapterDeadlineMs\n\t\t\t\t\t? now().getTime() + options.adapterDeadlineMs\n\t\t\t\t\t: undefined;\n\t\t\t\tif (adapterController && deadlineMs) {\n\t\t\t\t\tconst remaining = deadlineMs - now().getTime();\n\t\t\t\t\tif (remaining <= 0) {\n\t\t\t\t\t\tthrow new HostError(`Adapter deadline already expired before execution: ${step.adapterType}:${step.operation}`);\n\t\t\t\t\t}\n\t\t\t\t\tadapterDeadlineTimer = setTimeout(\n\t\t\t\t\t\t() => adapterController.abort(new HostError(\"Adapter deadline exceeded\")),\n\t\t\t\t\t\tremaining,\n\t\t\t\t\t);\n\t\t\t\t\tadapterDeadlineTimer.unref?.();\n\t\t\t\t}\n\t\t\t\tconst circuitBreaker = circuitBreakers.forAdapter(adapter, { tenantId, spaceId });\n\t\t\t\tconst result = await executeWithAdapterRetry({\n\t\t\t\t\t...(circuitBreaker ? { circuitBreaker } : {}),\n\t\t\t\t\tpolicy: step.retryPolicy ?? adapter.retryPolicy,\n\t\t\t\t\tdefaultIdempotent: adapter.idempotent,\n\t\t\t\t\t// Every await before the call happens here, before breaker\n\t\t\t\t\t// admission, so nothing awaits between admission and the adapter.\n\t\t\t\t\tprepareAttempt: async (attempt) => {\n\t\t\t\t\t\tadapterCallThrew = false;\n\t\t\t\t\t\tproviderReturned = false;\n\t\t\t\t\t\tproviderOutcome = undefined;\n\t\t\t\t\t\tthrownOutcome = undefined;\n\t\t\t\t\t\terrorContext = executionErrorContext;\n\t\t\t\t\t\tawait hostOperation(() => writeAdapter(adapterInvocationId, {\n\t\t\t\t\t\t\tstatus: \"running\", error: undefined, attempt,\n\t\t\t\t\t\t\tupdatedAt: now(),\n\t\t\t\t\t\t}));\n\t\t\t\t\t\tif (adapterController?.signal.aborted) {\n\t\t\t\t\t\t\tthrow new HostError(`Adapter deadline already expired before execution: ${step.adapterType}:${step.operation}`);\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\texecute: async (attempt, maxAttempts) => {\n\t\t\t\t\t\terrorContext = adapterErrorContext;\n\t\t\t\t\t\tlet adapterResult: import(\"@fabricorg/platform\").AdapterExecutionResult;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tadapterResult = await adapter.execute(input, {\n\t\t\t\t\t\t\t\ttenantId,\n\t\t\t\t\t\t\t\tspaceId,\n\t\t\t\t\t\t\t\tactionInvocationId,\n\t\t\t\t\t\t\t\tadapterInvocationId,\n\t\t\t\t\t\t\t\tcorrelationId: invocation.correlationId,\n\t\t\t\t\t\t\t\t...(invocation.causationId\n\t\t\t\t\t\t\t\t\t? { causationId: invocation.causationId }\n\t\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t\t\tattempt,\n\t\t\t\t\t\t\t\tmaxAttempts,\n\t\t\t\t\t\t\t\t...(deadlineMs ? { deadlineMs } : {}),\n\t\t\t\t\t\t\t\t...(adapterController ? { signal: adapterController.signal } : {}),\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tadapterCallThrew = true;\n\t\t\t\t\t\t\tthrow error;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tproviderReturned = true;\n\t\t\t\t\t\tif (!isRecord(adapterResult)) {\n\t\t\t\t\t\t\tthrow new HostError(\"Adapter returned an uninterpretable reply; external outcome requires reconciliation.\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Snapshot top-level fields before the retry helper or Host interprets\n\t\t\t\t\t\t// them. Preserve enumerability for the legacy output fallback, and\n\t\t\t\t\t\t// read each getter only once, including non-enumerable contract fields.\n\t\t\t\t\t\tconst source = adapterResult as unknown as Record<string, unknown>;\n\t\t\t\t\t\tconst reply = Object.fromEntries(Object.keys(source).map(key => [key, source[key]]));\n\t\t\t\t\t\tfor (const key of [\"success\", \"outcome\", \"error\", \"outcomeEvidence\", \"output\", \"acceptedExternalOperation\"]) {\n\t\t\t\t\t\t\tif (!Object.hasOwn(reply, key)) Object.defineProperty(reply, key, { value: source[key] });\n\t\t\t\t\t\t}\n\t\t\t\t\t\terrorContext = executionErrorContext;\n\t\t\t\t\t\treturn reply as unknown as import(\"@fabricorg/platform\").AdapterExecutionResult;\n\t\t\t\t\t},\n\t\t\t\t\tisSuccessful: (result) => result.success,\n\t\t\t\t\tgetError: (result) => result.error,\n\t\t\t\t\tclassifyOutcome: (result) => {\n\t\t\t\t\t\tconst outcome = result.outcome ?? \"transient_failure\";\n\t\t\t\t\t\tproviderOutcome = isKnownAdapterOutcome(outcome) && outcome !== \"success\" ? outcome : \"ambiguous\";\n\t\t\t\t\t\treturn providerOutcome;\n\t\t\t\t\t},\n\t\t\t\t\tclassifyThrownError: (error) => {\n\t\t\t\t\t\tif (error instanceof RecoverableFinalizationError) throw error;\n\t\t\t\t\t\tif (providerReturned && providerOutcome === undefined) return \"ambiguous\";\n\t\t\t\t\t\tif (isAdapterCircuitOpenError(error)) return \"transient_failure\";\n\t\t\t\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\t\t\t\tconst outcome = adapterController?.signal.aborted || /timeout|deadline|timed?\\s*out/i.test(message)\n\t\t\t\t\t\t\t? \"timeout\" : \"transient_failure\";\n\t\t\t\t\t\tif (adapterCallThrew) thrownOutcome = outcome;\n\t\t\t\t\t\t// A Host-side error after a reply must not retry the provider.\n\t\t\t\t\t\treturn providerReturned ? \"ambiguous\" : outcome;\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t\tfinalizingProviderResult = true;\n\t\t\t\t// The consistency message interpolates the provider's outcome.\n\t\t\t\terrorContext = adapterErrorContext;\n\t\t\t\ttry {\n\t\t\t\t\tassertAdapterOutcomeConsistency(result as import(\"@fabricorg/platform\").AdapterExecutionResult);\n\t\t\t\t\tif (!result.success && result.outcome === \"success\") {\n\t\t\t\t\t\tthrow new HostError('Adapter returned success=false with contradictory outcome \"success\"; external outcome requires reconciliation.');\n\t\t\t\t\t}\n\t\t\t\t\tconst outcome = result.outcome;\n\t\t\t\t\tif (outcome != null && !isKnownAdapterOutcome(outcome)) {\n\t\t\t\t\t\tthrow new HostError(\"Adapter returned an unrecognised outcome; external outcome requires reconciliation.\");\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\tconst message = caughtError(adapterErrorContext, error);\n\t\t\t\t\treturn await settleStepUnknownOutcome({\n\t\t\t\t\t\tkind: \"adapter_outcome_ambiguous\", adapterType: step.adapterType, operation: step.operation,\n\t\t\t\t\t\tvendor: adapter.vendor, adapterInvocationId, message, reason: message,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\terrorContext = executionErrorContext;\n\t\t\t\tif (!result.success) {\n\t\t\t\t\tconst resultError = result.error == null ? result.error : redactErrorText(options.redactErrorText, adapterErrorContext, result.error);\n\t\t\t\t\tconst outcome = result.outcome ?? \"transient_failure\";\n\t\t\t\t\tif (outcome === \"ambiguous\" || outcome === \"timeout\") {\n\t\t\t\t\t\tconst evidence = result.outcomeEvidence;\n\t\t\t\t\t\tconst reason = evidence?.reason == null ? resultError : redactErrorText(options.redactErrorText, adapterErrorContext, evidence.reason);\n\t\t\t\t\t\treturn await settleStepUnknownOutcome({\n\t\t\t\t\t\t\tkind: \"adapter_outcome_ambiguous\", adapterType: step.adapterType, operation: step.operation,\n\t\t\t\t\t\t\tvendor: adapter.vendor, adapterInvocationId,\n\t\t\t\t\t\t\t...(evidence?.reason ?? result.error ? { reason } : {}),\n\t\t\t\t\t\t\t...(evidence?.externalReference ? { externalReference: evidence.externalReference } : {}),\n\t\t\t\t\t\t\tmessage: resultError ?? \"Adapter outcome is ambiguous; external effect may or may not have been applied\",\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tawait hostOperation(() => writeAdapter(adapterInvocationId, {\n\t\t\t\t\t\tstatus: \"failed\",\n\t\t\t\t\t\terror: resultError ?? \"Adapter failed\",\n\t\t\t\t\t\tupdatedAt: now(),\n\t\t\t\t\t}));\n\t\t\t\t\tawait hostOperation(() => appendEvent(invocation, {\n\t\t\t\t\t\teventType: \"AdapterInvocationFailed\",\n\t\t\t\t\t\tsubjectType: adapterEventSubject.subjectType,\n\t\t\t\t\t\tsubjectId: adapterEventSubject.subjectId,\n\t\t\t\t\t\tpayload: { adapterType: step.adapterType, operation: step.operation },\n\t\t\t\t\t}, `adapter:${stepIndex}:failed`));\n\t\t\t\t\treturn hostOperation(() => failExecution(invocation, \"failed\", resultError ?? \"Adapter failed\"));\n\t\t\t\t}\n\t\t\t\tproviderReportedSuccess = true;\n\t\t\t\tconst resultRecord = result as unknown as Record<string, unknown>;\n\t\t\t\tlet output = isRecord(resultRecord.output)\n\t\t\t\t\t? resultRecord.output\n\t\t\t\t\t: Object.fromEntries(\n\t\t\t\t\t\t\tObject.entries(resultRecord).filter(\n\t\t\t\t\t\t\t\t([key]) => key !== \"success\" && key !== \"error\",\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\tconst handoff = (result as import(\"@fabricorg/platform\").AdapterExecutionResult).acceptedExternalOperation;\n\t\t\t\tif (options.redactAdapterOutput) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\toutput = options.redactAdapterOutput(action.actionId, step.adapterType, step.operation, output);\n\t\t\t\t\t\tif (!isRecord(output)) throw new HostError(\"Adapter output redactor must return a non-null, non-array object.\");\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// The provider succeeded. Withhold output and preserve a callback\n\t\t\t\t\t\t// reference for reconciliation when finalization commits.\n\t\t\t\t\t\tconst message = \"Adapter output withheld: the output redactor failed after the external effect; reconciliation required.\";\n\t\t\t\t\t\tconst reference = typeof handoff?.externalReference === \"string\" ? handoff.externalReference.trim() : \"\";\n\t\t\t\t\t\tconst acceptedAt = now();\n\t\t\t\t\t\tconst deadlineMs = action.execution?.completionDeadlineMs;\n\t\t\t\t\t\tconst pendingCompletion = pendingHandoff ?? (reference ? {\n\t\t\t\t\t\t\tprovider: adapter.vendor, adapterType: step.adapterType, operation: step.operation,\n\t\t\t\t\t\t\tadapterInvocationId, externalReference: reference, acceptedAt,\n\t\t\t\t\t\t\t...(deadlineMs ? { dueAt: new Date(acceptedAt.getTime() + deadlineMs) } : {}),\n\t\t\t\t\t\t} : undefined);\n\t\t\t\t\t\tconst patch: ActionInvocationPatch = { status: \"reconciliation_required\", error: message, ...(pendingCompletion ? { pendingCompletion } : {}) };\n\t\t\t\t\t\tconst accepted = pendingCompletion?.adapterInvocationId === adapterInvocationId ? pendingCompletion : undefined;\n\t\t\t\t\t\tlet adapterFinalizedAtomically: boolean;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tadapterFinalizedAtomically = await finalizeDegradedAdapterAtomically(patch, true, message, accepted, undefined, reference || undefined);\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\tthrow new RecoverableFinalizationError(message);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!adapterFinalizedAtomically) {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tawait persistExecutionVerdict(invocation, patch, [\n\t\t\t\t\t\t\t\t\t() => appendDegradedAdapterEvidence(true, message, accepted, undefined, reference || undefined),\n\t\t\t\t\t\t\t\t\t() => writeAdapter(adapterInvocationId, { status: \"succeeded\", updatedAt: now() }),\n\t\t\t\t\t\t\t\t]);\n\t\t\t\t\t\t\t} catch (cause) {\n\t\t\t\t\t\t\t\tthrow new RecoverableFinalizationError(`${message} ${caughtError({ actionId: invocation.actionId, source: \"execution\" }, cause)}`);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn withConsistency({ actionInvocationId, status: \"reconciliation_required\" as const, error: message, ...(pendingCompletion ? { pendingCompletion } : {}) }, action.actionId);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tsuccessOutput = output;\n\t\t\t\tif (handoff) {\n\t\t\t\t\tconst reference = typeof handoff.externalReference === \"string\" ? handoff.externalReference.trim() : \"\";\n\t\t\t\t\tif (reference === \"\") {\n\t\t\t\t\t\t// Without a reference Host cannot match an external completion.\n\t\t\t\t\t\tconst message = `Adapter ${step.adapterType}:${step.operation} accepted an external operation without a reference to complete it by; the external effect may be in flight.`;\n\t\t\t\t\t\ttry { await persistExecutionVerdict(invocation, { status: \"reconciliation_required\", error: message }); }\n\t\t\t\t\t\tcatch { throw new RecoverableFinalizationError(message); }\n\t\t\t\t\t\treturn withConsistency({ actionInvocationId, status: \"reconciliation_required\" as const, error: message }, action.actionId);\n\t\t\t\t\t}\n\t\t\t\t\tconst acceptedAt = now();\n\t\t\t\t\tconst deadlineMs = action.execution?.completionDeadlineMs;\n\t\t\t\t\tconst accepted: PendingExternalCompletion = {\n\t\t\t\t\t\tprovider: adapter.vendor,\n\t\t\t\t\t\tadapterType: step.adapterType,\n\t\t\t\t\t\toperation: step.operation,\n\t\t\t\t\t\tadapterInvocationId,\n\t\t\t\t\t\texternalReference: reference,\n\t\t\t\t\t\tacceptedAt,\n\t\t\t\t\t\t...(deadlineMs ? { dueAt: new Date(acceptedAt.getTime() + deadlineMs) } : {}),\n\t\t\t\t\t};\n\t\t\t\t\tconst completion = action.execution?.completion ?? \"immediate\";\n\t\t\t\t\tconst refuse = completion === \"immediate\"\n\t\t\t\t\t\t? `Adapter ${step.adapterType}:${step.operation} handed off external operation \"${reference}\" but ${action.actionId} declares immediate completion; the external effect may be in flight.`\n\t\t\t\t\t\t: pendingHandoff\n\t\t\t\t\t\t\t? `Adapter ${step.adapterType}:${step.operation} handed off a second external operation \"${reference}\" while \"${pendingHandoff.externalReference}\" is already pending; one invocation waits on one completion.`\n\t\t\t\t\t\t\t: undefined;\n\t\t\t\t\tif (refuse) {\n\t\t\t\t\t\t// The handoff already happened, so this is not a clean failure:\n\t\t\t\t\t\t// somebody has to look, with the reference in hand. The first\n\t\t\t\t\t\t// reference is kept on the invocation so its callback can still\n\t\t\t\t\t\t// land as evidence; the refused one goes to the reconciliation\n\t\t\t\t\t\t// log. Capable transactions commit evidence and verdict together;\n\t\t\t\t\t\t// the fallback keeps the verdict first to prevent completion on reclaim.\n\t\t\t\t\t\tlet adapterFinalizedAtomically = false;\n\t\t\t\t\t\tlet error = refuse;\n\t\t\t\t\t\tconst recordRefusal = async () => {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tawait externalCompletion.recordCompletionReconciliation(invocation, { externalReference: reference, provider: adapter.vendor }, refuse);\n\t\t\t\t\t\t\t} catch (logError) {\n\t\t\t\t\t\t\t\t// The lease is already gone with the terminal status above, so\n\t\t\t\t\t\t\t\t// this write must not fence on it.\n\t\t\t\t\t\t\t\terror = `${refuse} Reconciliation log unavailable: ${caughtError({ actionId: invocation.actionId, source: \"execution\" }, logError)}`;\n\t\t\t\t\t\t\t\tif (adapterFinalizedAtomically) {\n\t\t\t\t\t\t\t\t\tif (ownVerdict) await hostOperation(() => persistExecutionVerdict(invocation, { error }));\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t// Keep the first failure even if its diagnostic annotation fails.\n\t\t\t\t\t\t\t\t\ttry { if (ownVerdict) await hostOperation(() => persistExecutionVerdict(invocation, { error })); }\n\t\t\t\t\t\t\t\t\tcatch { /* The reconciliation append is the first failure. */ }\n\t\t\t\t\t\t\t\t\tthrow logError;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconst patch: ActionInvocationPatch = {\n\t\t\t\t\t\t\tstatus: \"reconciliation_required\", error: refuse,\n\t\t\t\t\t\t\t...(pendingHandoff ? {} : { pendingCompletion: accepted }),\n\t\t\t\t\t\t};\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tadapterFinalizedAtomically = await finalizeDegradedAdapterAtomically(patch, false, refuse, pendingHandoff ? undefined : accepted, output, reference);\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\tthrow new RecoverableFinalizationError(refuse);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!adapterFinalizedAtomically) {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tawait persistExecutionVerdict(invocation, patch, [\n\t\t\t\t\t\t\t\t\t() => appendDegradedAdapterEvidence(false, refuse, pendingHandoff ? undefined : accepted, output, reference),\n\t\t\t\t\t\t\t\t\trecordRefusal,\n\t\t\t\t\t\t\t\t\t() => writeAdapter(adapterInvocationId, { status: \"succeeded\", output, updatedAt: now() }),\n\t\t\t\t\t\t\t\t]);\n\t\t\t\t\t\t\t} catch (cause) {\n\t\t\t\t\t\t\t\tthrow new RecoverableFinalizationError(`${refuse} ${caughtError({ actionId: invocation.actionId, source: \"execution\" }, cause)}`);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (adapterFinalizedAtomically) await recordRefusal();\n\t\t\t\t\t\treturn withConsistency({\n\t\t\t\t\t\t\tactionInvocationId, status: \"reconciliation_required\" as const, error,\n\t\t\t\t\t\t\t...(pendingHandoff ? { pendingCompletion: pendingHandoff } : { pendingCompletion: accepted }),\n\t\t\t\t\t\t}, action.actionId);\n\t\t\t\t\t}\n\t\t\t\t\tpendingHandoff = accepted;\n\t\t\t\t\t// Durable before the step is marked done: see the note above the loop.\n\t\t\t\t\tawait writeSuccessCheckpoint(() => persistExecutionInvocation(invocation, { pendingCompletion: accepted }));\n\t\t\t\t\thandoffDurable = true;\n\t\t\t\t\thasDurableProviderEffect = true;\n\t\t\t\t\tinvocation = { ...invocation, pendingCompletion: accepted };\n\t\t\t\t\tawait appendEvent(invocation, {\n\t\t\t\t\t\teventType: \"ExternalOperationAccepted\",\n\t\t\t\t\t\tsubjectType: adapterEventSubject.subjectType,\n\t\t\t\t\t\tsubjectId: adapterEventSubject.subjectId,\n\t\t\t\t\t\tpayload: {\n\t\t\t\t\t\t\tadapterType: step.adapterType,\n\t\t\t\t\t\t\toperation: step.operation,\n\t\t\t\t\t\t\texternalReference: reference,\n\t\t\t\t\t\t\t...(accepted.dueAt ? { dueAt: accepted.dueAt.toISOString() } : {}),\n\t\t\t\t\t\t},\n\t\t\t\t\t}, `adapter:${stepIndex}:accepted`);\n\t\t\t\t}\n\t\t\t\tawait writeSuccessCheckpoint(() => writeAdapter(adapterInvocationId, {\n\t\t\t\t\tstatus: \"succeeded\", output, updatedAt: now(),\n\t\t\t\t}));\n\t\t\t\tmarkerDurable = true;\n\t\t\t\thasDurableProviderEffect = true;\n\t\t\t\tif (options.extractExecutionAttestation) {\n\t\t\t\t\tconst attestation = await options.extractExecutionAttestation({\n\t\t\t\t\t\tactionInvocationId, adapterInvocationId, adapterType: step.adapterType,\n\t\t\t\t\t\toperation: step.operation, vendor: adapter.vendor, input: recordedInput,\n\t\t\t\t\t\tstartedAt, completedAt: now(), output,\n\t\t\t\t\t});\n\t\t\t\t\tif (attestation) {\n\t\t\t\t\t\tawait recordExecutionAttestation(actionInvocationId, tenantId, spaceId, attestation, adapterInvocationId);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tawait appendEvent(invocation, {\n\t\t\t\t\teventType: \"AdapterInvocationSucceeded\",\n\t\t\t\t\tsubjectType: adapterEventSubject.subjectType,\n\t\t\t\t\tsubjectId: adapterEventSubject.subjectId,\n\t\t\t\t\tpayload: {\n\t\t\t\t\t\tadapterType: step.adapterType,\n\t\t\t\t\t\toperation: step.operation,\n\t\t\t\t\t\tinput: recordedInput,\n\t\t\t\t\t\toutput,\n\t\t\t\t\t},\n\t\t\t\t}, `adapter:${stepIndex}:succeeded`);\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof RecoverableFinalizationError) throw error;\n\t\t\t\tif (providerReportedSuccess) {\n\t\t\t\t\tconst message = `Provider reported success but Host could not record it; reconciliation required. ${caughtError(executionErrorContext, error)}`;\n\t\t\t\t\tif (handoffDurable || markerDurable) throw new RecoverableFinalizationError(message);\n\t\t\t\t\tconst accepted = pendingHandoff?.adapterInvocationId === adapterInvocationId ? pendingHandoff : undefined;\n\t\t\t\t\tconst patch: ActionInvocationPatch = { status: \"reconciliation_required\" as const, error: message,\n\t\t\t\t\t\t...(accepted ? { pendingCompletion: accepted } : {}) };\n\t\t\t\t\tif (!await finalizeDegradedAdapterAtomically(patch, false, message, accepted, successOutput)) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tawait persistExecutionVerdict(invocation, patch, [\n\t\t\t\t\t\t\t\t() => writeAdapter(adapterInvocationId, {\n\t\t\t\t\t\t\t\t\tstatus: \"succeeded\", ...(successOutput !== undefined ? { output: successOutput } : {}), updatedAt: now(),\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t() => appendDegradedAdapterEvidence(false, message, accepted, successOutput),\n\t\t\t\t\t\t\t]);\n\t\t\t\t\t\t} catch (cause) {\n\t\t\t\t\t\t\tthrow new RecoverableFinalizationError(`${message} ${caughtError(executionErrorContext, cause)}`);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn withConsistency({ actionInvocationId, status: \"reconciliation_required\" as const, error: message,\n\t\t\t\t\t\t...(accepted ? { pendingCompletion: accepted } : {}) }, action.actionId);\n\t\t\t\t}\n\n\t\t\t\tconst message = caughtError(isAdapterCircuitOpenError(error) || (!finalizingProviderResult && providerReturned) ? adapterErrorContext : errorContext, error);\n\t\t\t\tif ((providerReturned && !finalizingProviderResult && (!isAdapterCircuitOpenError(error) || providerOutcome === undefined)) ||\n\t\t\t\t\t(adapterCallThrew && thrownOutcome === \"timeout\")) {\n\t\t\t\t\treturn await settleStepUnknownOutcome({\n\t\t\t\t\t\tkind: \"adapter_outcome_ambiguous\", adapterType: step.adapterType, operation: step.operation,\n\t\t\t\t\t\tvendor: adapter.vendor, adapterInvocationId, message, reason: message,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tawait hostOperation(() => writeAdapter(adapterInvocationId, {\n\t\t\t\t\tstatus: \"failed\",\n\t\t\t\t\terror: message,\n\t\t\t\t\tupdatedAt: now(),\n\t\t\t\t}));\n\t\t\t\tif (isAdapterCircuitOpenError(error)) {\n\t\t\t\t\t// Retain the existing circuit-error classification and event shape.\n\t\t\t\t\t// Adapter-thrown lookalikes use this path too; their text is redacted above.\n\t\t\t\t\tawait hostOperation(() => appendEvent(invocation, {\n\t\t\t\t\t\teventType: \"AdapterInvocationFailed\",\n\t\t\t\t\t\tsubjectType: adapterEventSubject.subjectType,\n\t\t\t\t\t\tsubjectId: adapterEventSubject.subjectId,\n\t\t\t\t\t\tpayload: {\n\t\t\t\t\t\t\tadapterType: step.adapterType,\n\t\t\t\t\t\t\toperation: step.operation,\n\t\t\t\t\t\t\treason: \"circuit_open\",\n\t\t\t\t\t\t\t...(error.retryAfterMs !== undefined ? { retryAfterMs: error.retryAfterMs } : {}),\n\t\t\t\t\t\t},\n\t\t\t\t\t}, `adapter:${stepIndex}:failed`));\n\t\t\t\t}\n\t\t\t\treturn hostOperation(() => failExecution(invocation, \"failed\", message));\n\t\t\t} finally {\n\t\t\t\tif (adapterDeadlineTimer) clearTimeout(adapterDeadlineTimer);\n\t\t\t}\n\t\t}\n\n\t\tconst governanceStore = asGovernanceStore(options.store);\n\t\tif (governanceStore && options.resolvePolicyObligations) {\n\t\t\tconst obligations = await hostOperation(() => governanceStore.listPolicyObligations(actionInvocationId, tenantId, spaceId));\n\t\t\tconst unsatisfied = obligations.filter((obligation) => (obligation.required ?? true) && obligation.status !== \"satisfied\" && obligation.status !== \"waived\");\n\t\t\tif (unsatisfied.length > 0) {\n\t\t\t\tconst message = `Unsatisfied policy obligations: ${unsatisfied.map((item) => item.id).join(\", \")}`;\n\t\t\t\tif (pendingHandoff) {\n\t\t\t\t\t// The external effect is in flight and the evidence that would\n\t\t\t\t\t// have satisfied these may have died with a worker; somebody\n\t\t\t\t\t// has to look rather than the row saying it failed cleanly.\n\t\t\t\t\tawait hostOperation(() => persistExecutionInvocation(invocation, { status: \"reconciliation_required\", error: message }));\n\t\t\t\t\tlet error = message;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait externalCompletion.recordCompletionReconciliation(invocation, { externalReference: pendingHandoff.externalReference, provider: pendingHandoff.provider, kind: \"obligations\" }, message);\n\t\t\t\t\t} catch (logError) {\n\t\t\t\t\t\terror = `${message} Reconciliation log unavailable: ${caughtError({ actionId: invocation.actionId, source: \"execution\" }, logError)}`;\n\t\t\t\t\t\tif (ownVerdict) await hostOperation(() => persistExecutionVerdict(invocation, { error }));\n\t\t\t\t\t}\n\t\t\t\t\treturn withConsistency({ actionInvocationId, status: \"reconciliation_required\" as const, error, pendingCompletion: pendingHandoff }, action.actionId);\n\t\t\t\t}\n\t\t\t\treturn hostOperation(() => failExecution(invocation, \"failed\", message));\n\t\t\t}\n\t\t}\n\n\t\tconst result = withoutPrivateHostFields(data, eventResultFields);\n\t\t// A handoff leaves the invocation running, without a lease, until the\n\t\t// external system completes it by reference. Domain events still go out\n\t\t// now: the handler's writes committed, and what is pending is the\n\t\t// external outcome, not the domain state.\n\t\tconst parked: PendingExternalCompletion | undefined = pendingHandoff ? { ...pendingHandoff, parkedAt: now() } : undefined;\n\t\tconst finalPatch: ActionInvocationPatch = parked\n\t\t\t? { status: \"running\", result, pendingCompletion: parked }\n\t\t\t: { status: \"completed\", result };\n\t\tlet verdictWritten = true;\n\t\ttry {\n\t\t\tconst atomicStore = asAtomicMutationStore(options.store);\n\t\t\tif (action.eventPhase === \"after_adapters\" && atomicStore) {\n\t\t\t\tawait hostOperation(() => atomicStore.transactionWithEvents(async (transaction) => {\n\t\t\t\t\tfor (const [index, event] of domainEvents.entries()) {\n\t\t\t\t\t\tawait appendEvent(\n\t\t\t\t\t\t\tinvocation,\n\t\t\t\t\t\t\tevent,\n\t\t\t\t\t\t\t`domain:${index}`,\n\t\t\t\t\t\t\taction.version,\n\t\t\t\t\t\t\ttransaction,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tif (pendingTransitionEvent) {\n\t\t\t\t\t\tawait appendEvent(invocation, pendingTransitionEvent, \"state:transition\", 1, transaction);\n\t\t\t\t\t}\n\t\t\t\t\tif (executionLease) {\n\t\t\t\t\t\tif (!transaction.updateLeasedActionInvocation) {\n\t\t\t\t\t\t\tthrow new HostError(\"Leased atomic finalization requires transaction-scoped fencing support.\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst updated = await transaction.updateLeasedActionInvocation({\n\t\t\t\t\t\t\tid: actionInvocationId, tenantId, spaceId,\n\t\t\t\t\t\t\tworkerId: executionLease.leaseOwner, leaseToken: executionLease.leaseToken,\n\t\t\t\t\t\t\tpatch: finalPatch,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (!updated) throw new RecoverableFinalizationError(`Invocation lease lost: ${actionInvocationId}`);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tverdictWritten = await writeInlineInvocation(invocation, finalPatch, transaction, onPreservedReconciliation);\n\t\t\t\t\t}\n\t\t\t\t}));\n\t\t\t\tif (!pendingHandoff && verdictWritten) {\n\t\t\t\t\temitInvocationStatusTelemetry(\n\t\t\t\t\t\tinvocation,\n\t\t\t\t\t\t\"completed\",\n\t\t\t\t\t\toptions.telemetry,\n\t\t\t\t\t\tnow(),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (action.eventPhase === \"after_adapters\") {\n\t\t\t\t\tfor (const [index, event] of domainEvents.entries()) {\n\t\t\t\t\t\tawait hostOperation(() => appendEvent(invocation, event, `domain:${index}`, action.version));\n\t\t\t\t\t}\n\t\t\t\t\tif (pendingTransitionEvent) {\n\t\t\t\t\t\tawait hostOperation(() => appendEvent(invocation, pendingTransitionEvent, \"state:transition\", 1));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tawait hostOperation(() => persistExecutionInvocation(invocation, finalPatch));\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (action.eventPhase === \"after_adapters\") {\n\t\t\t\tthrow new RecoverableFinalizationError(errorMessage(error));\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t\treturn {\n\t\t\tactionInvocationId,\n\t\t\tstatus: parked ? \"running\" : \"completed\",\n\t\t\tresult,\n\t\t\t...(parked ? { pendingCompletion: parked } : {}),\n\t\t\t...(invocation.hitlRoute ? { hitlRoute: invocation.hitlRoute } : {}),\n\t\t\t...(invocation.hitlRiskTier ? { hitlRiskTier: invocation.hitlRiskTier } : {}),\n\t\t};\n\t\t} catch (error) {\n\t\t\tif (error instanceof RecoverableFinalizationError) throw error;\n\t\t\tif (retryableGovernance && isRetryableExecutionError(error)) {\n\t\t\t\tconst reason = executionReasonOverride === \"approval_resume\"\n\t\t\t\t\t? \"approval resume\"\n\t\t\t\t\t: !invocation.leaseOwner || invocation.leaseToken === undefined\n\t\t\t\t\t\t? \"not leased\"\n\t\t\t\t\t\t: !action.idempotent\n\t\t\t\t\t\t\t? \"action not idempotent\"\n\t\t\t\t\t\t\t: invocation.attemptCount >= retryableExecutionMaxAttempts\n\t\t\t\t\t\t\t\t? `attempts exhausted (${invocation.attemptCount}/${retryableExecutionMaxAttempts})`\n\t\t\t\t\t\t\t\t: undefined;\n\t\t\t\tif (!reason) throw error;\n\t\t\t\treturn hostOperation(() => failExecution(invocation, \"failed\", caughtError(\n\t\t\t\t\t{ actionId: invocation.actionId, source: \"execution\" },\n\t\t\t\t\tnew Error(`Retryable execution not retried: ${reason}; ${errorMessage(error)}`),\n\t\t\t\t)));\n\t\t\t}\n\t\t\treturn hostOperation(() => failExecution(invocation, \"failed\", caughtError({ actionId: invocation.actionId, source: \"execution\" }, error)));\n\t\t}\n\t}\n\n\tasync function resumeApprovedInvocation(\n\t\tactionInvocationId: string,\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t\tdecision: ActionApprovalDecision,\n\t): Promise<ExecuteActionResult> {\n\t\tif (!decision.approverId.trim()) throw new Error(\"approverId is required\");\n\t\tconst invocation = await options.store.getActionInvocation(\n\t\t\tactionInvocationId,\n\t\t\ttenantId,\n\t\t\tspaceId,\n\t\t);\n\t\tif (!invocation) throw new Error(`ActionInvocation not found: ${actionInvocationId}`);\n\t\tif (isTerminal(invocation.status)) return withConsistency(actionResult(invocation), invocation.actionId);\n\t\tif (invocation.status !== \"waiting_for_approval\") {\n\t\t\treturn {\n\t\t\t\t...actionResult(invocation),\n\t\t\t\terror: `Invocation is not waiting for approval (status: ${invocation.status})`,\n\t\t\t};\n\t\t}\n\t\tconst action = actionResolver(invocation.actionId);\n\t\tif (!action) return fail(invocation, \"failed\", `Unknown action: ${invocation.actionId}`);\n\t\tconst approvalAuthorizationInput = toAuthorizationInput(action, {\n\t\t\ttenantId,\n\t\t\tspaceId,\n\t\t\tactorId: decision.approverId,\n\t\t\tactorType: decision.approverType,\n\t\t});\n\t\tconst entitled = await options.authorization.checkEntitlement(\n\t\t\tapprovalAuthorizationInput,\n\t\t);\n\t\tconst authorized = options.authorization.authorizeApproval\n\t\t\t? await options.authorization.authorizeApproval({\n\t\t\t\t\t...approvalAuthorizationInput,\n\t\t\t\t\tdecision,\n\t\t\t\t})\n\t\t\t: await options.authorization.authorize(approvalAuthorizationInput);\n\t\tif (!entitled || !authorized) {\n\t\t\treturn {\n\t\t\t\t...actionResult(invocation),\n\t\t\t\terror: `Actor ${decision.approverId} is not authorized to decide this approval`,\n\t\t\t};\n\t\t}\n\t\tconst approvalStore = asApprovalStore(options.store);\n\t\tif (!approvalStore) {\n\t\t\treturn {\n\t\t\t\t...actionResult(invocation),\n\t\t\t\terror: \"Approval resume requires a store with approval persistence support.\",\n\t\t\t};\n\t\t}\n\t\tconst transitionStartedAt = now();\n\t\tconst decidedAt = decision.decidedAt ?? transitionStartedAt;\n\t\tconst leaseOwner = `approval-resume-${createFabricId(\"lease\")}`;\n\t\tconst transition = await approvalStore.beginApprovalDecision({\n\t\t\tactionInvocationId,\n\t\t\ttenantId,\n\t\t\tspaceId,\n\t\t\tdecision: { ...decision, decidedAt },\n\t\t\tleaseOwner,\n\t\t\tleaseDurationMs: options.approvalResumeLeaseDurationMs ?? 5 * 60_000,\n\t\t\tnow: transitionStartedAt,\n\t\t});\n\t\tconst transitioned =\n\t\t\ttransition.invocation ??\n\t\t\t(await options.store.getActionInvocation(actionInvocationId, tenantId, spaceId));\n\t\tif (!transition.applied || !transitioned) {\n\t\t\tif (!transitioned) throw new Error(`ActionInvocation not found: ${actionInvocationId}`);\n\t\t\treturn withConsistency(actionResult(transitioned), transitioned.actionId);\n\t\t}\n\t\tif (!decision.approved) {\n\t\t\temitInvocationStatusTelemetry(\n\t\t\t\ttransitioned,\n\t\t\t\t\"failed\",\n\t\t\t\toptions.telemetry,\n\t\t\t\tnow(),\n\t\t\t\t\"waiting_for_approval\",\n\t\t\t);\n\t\t\treturn withConsistency(actionResult(transitioned), transitioned.actionId);\n\t\t}\n\t\treturn executeInvocation(\n\t\t\tactionInvocationId,\n\t\t\ttenantId,\n\t\t\tspaceId,\n\t\t\t{ leaseOwner, leaseToken: transitioned.leaseToken },\n\t\t\t\"approval_resume\",\n\t\t);\n\t}\n\n\tasync function recordExecutionAttestation(\n\t\tactionInvocationId: string,\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t\tattestation: ExecutionAttestation,\n\t\tadapterInvocationId?: string,\n\t): Promise<void> {\n\t\tconst governanceStore = asGovernanceStore(options.store);\n\t\tif (!governanceStore) throw new HostError(\"Execution attestations require a governance-capable store.\");\n\t\tconst invocation = await options.store.getActionInvocation(actionInvocationId, tenantId, spaceId);\n\t\tif (!invocation) throw new HostError(`ActionInvocation not found: ${actionInvocationId}`);\n\t\tconst id = lifecycleId(\"att\", actionInvocationId, adapterInvocationId ?? `${attestation.provider}:${attestation.operation}:${attestation.externalOperationId ?? \"external\"}`);\n\t\tawait governanceStore.appendExecutionAttestation({\n\t\t\t...attestation, id, actionInvocationId, tenantId, spaceId,\n\t\t\t...(adapterInvocationId ? { adapterInvocationId } : {}), recordedAt: now(),\n\t\t});\n\t\tfor (const obligationId of attestation.satisfiesObligations ?? []) {\n\t\t\tawait governanceStore.updatePolicyObligation(actionInvocationId, obligationId, \"satisfied\", attestation.evidenceReferences);\n\t\t}\n\t}\n\n\tasync function recordExternalReconciliation(\n\t\tactionInvocationId: string,\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t\treconciliation: ExternalReconciliation,\n\t): Promise<void> {\n\t\tconst governanceStore = asGovernanceStore(options.store);\n\t\tif (!governanceStore) throw new Error(\"External reconciliation requires a governance-capable store.\");\n\t\tconst invocation = await options.store.getActionInvocation(actionInvocationId, tenantId, spaceId);\n\t\tif (!invocation) throw new Error(`ActionInvocation not found: ${actionInvocationId}`);\n\t\tawait governanceStore.appendExternalReconciliation({\n\t\t\t...reconciliation,\n\t\t\tid: lifecycleId(\"rec\", actionInvocationId, `${reconciliation.provider}:${reconciliation.attempt}`),\n\t\t\tactionInvocationId, tenantId, spaceId,\n\t\t});\n\t}\n\n\t/** Consistency is a property of the action, not of the invocation, so it is read rather than stored. */\n\tfunction declaredConsistency(actionId: ActionId): \"authoritative-now\" | \"provisional-until-reconciled\" | undefined {\n\t\treturn actionResolver(actionId)?.execution?.consistency;\n\t}\n\n\t/**\n\t * Decorates every result leaving the Host, not only a freshly executed one, so an\n\t * idempotent replay reports the same consistency as the original submission.\n\t */\n\tfunction withConsistency<TResult extends { actionInvocationId: string }>(result: TResult, actionId: ActionId): TResult {\n\t\tconst consistency = declaredConsistency(actionId);\n\t\treturn consistency ? { ...result, consistency } : result;\n\t}\n\n\tasync function appendEvent(\n\t\tinvocation: {\n\t\t\tid: string;\n\t\t\tactionId: ActionId;\n\t\t\tactionVersion: number;\n\t\t\ttenantId: string;\n\t\t\tspaceId: string;\n\t\t\tactorId: string;\n\t\t\tactorType: string;\n\t\t\tcorrelationId: string;\n\t\t\tcausationId?: string;\n\t\t\tprovenance?: ActionInvocationRecord[\"provenance\"];\n\t\t},\n\t\tevent: PendingAssetEvent,\n\t\tdeduplicationKey: string,\n\t\tdefaultEventSchemaVersion = 1,\n\t\ttransaction?: PlatformHostMutationTransaction<TDb>,\n\t): Promise<void> {\n\t\tconst timestamp = now();\n\t\tconst envelope: AssetEventEnvelope = {\n\t\t\tid: lifecycleId(\"evt\", invocation.id, deduplicationKey),\n\t\t\ttenantId: invocation.tenantId,\n\t\t\tspaceId: invocation.spaceId,\n\t\t\teventType: event.eventType,\n\t\t\teventSchemaVersion: event.eventSchemaVersion ?? defaultEventSchemaVersion,\n\t\t\tsubjectType: event.subjectType,\n\t\t\tsubjectId: event.subjectId,\n\t\t\tactorId: invocation.actorId,\n\t\t\tactorType: invocation.actorType,\n\t\t\tactionInvocationId: invocation.id,\n\t\t\tpayload: event.payload,\n\t\t\tsequence: await (transaction ?? options.store).nextEventSequence(\n\t\t\t\tinvocation.tenantId,\n\t\t\t\tinvocation.spaceId,\n\t\t\t),\n\t\t\toccurredAt: timestamp,\n\t\t\trecordedAt: timestamp,\n\t\t\tcorrelationId: invocation.correlationId,\n\t\t\t...(invocation.causationId ? { causationId: invocation.causationId } : {}),\n\t\t\t...(invocation.provenance ? { provenance: { source: invocation.provenance.source, ...(invocation.provenance.auditAttributes ? { auditAttributes: invocation.provenance.auditAttributes } : {}) } } : {}),\n\t\t\t...(declaredConsistency(invocation.actionId) === \"provisional-until-reconciled\" ? { consistency: \"provisional-until-reconciled\" as const } : {}),\n\t\t};\n\t\tif (options.outbox) {\n\t\t\tconst hostLifecycleEvent = new Set([\"AdapterInvocationStarted\", \"AdapterInvocationSucceeded\", \"AdapterInvocationFailed\", \"ExternalOperationAccepted\", \"ExternalOperationCompleted\", \"ExternalOperationFailed\", \"ExternalOperationContradicted\", \"ComplianceBlocked\"]).has(envelope.eventType);\n\t\t\tconst shouldPublish = options.outbox.shouldPublish?.(envelope) ?? !hostLifecycleEvent;\n\t\t\tif (!shouldPublish) {\n\t\t\t\tawait (transaction ?? options.store).appendEvent(envelope);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst traceContext = options.outbox.traceContext?.(envelope);\n\t\t\tconst payloadClassification = options.outbox.classifyPayload(envelope);\n\t\t\tconst metadata = {\n\t\t\t\tproducerModuleVersion: options.outbox.producerModuleVersion(invocation.actionId, invocation.actionVersion),\n\t\t\t\tpayloadClassification,\n\t\t\t\tincludeProvenance: options.outbox.includeProvenance?.(envelope, payloadClassification) ?? payloadClassification !== \"restricted\",\n\t\t\t\t// Actor identity is excluded for every classification unless the application opts in.\n\t\t\t\tincludeActor: options.outbox.includeActor?.(envelope, payloadClassification) === true,\n\t\t\t\t...(traceContext ? { traceContext } : {}),\n\t\t\t};\n\t\t\tif (transaction) {\n\t\t\t\tif (!transaction.appendEventWithOutbox) throw new HostError(\"Outbox egress requires an atomic transaction with appendEventWithOutbox.\");\n\t\t\t\tawait transaction.appendEventWithOutbox(envelope, metadata);\n\t\t\t} else {\n\t\t\t\tconst outboxStore = asOutboxStore(options.store);\n\t\t\t\tif (!outboxStore) throw new HostError(\"Outbox egress requires an outbox-capable Platform Host store.\");\n\t\t\t\tawait outboxStore.appendEventWithOutbox(envelope, metadata);\n\t\t\t}\n\t\t} else {\n\t\t\tawait (transaction ?? options.store).appendEvent(envelope);\n\t\t}\n\t}\n\n\tasync function fail(\n\t\tinvocation: {\n\t\t\tid: string;\n\t\t\ttenantId: string;\n\t\t\tspaceId: string;\n\t\t\thitlRoute?: ActionInvocationRecord[\"hitlRoute\"];\n\t\t\thitlRiskTier?: ActionInvocationRecord[\"hitlRiskTier\"];\n\t\t},\n\t\tstatus: Extract<ActionStatus, \"failed\" | \"blocked_by_policy\" | \"validation_failed\">,\n\t\terror: string,\n\t\tonPreservedReconciliation?: (record: ActionInvocationRecord) => void,\n\t): Promise<ExecuteActionResult> {\n\t\tawait persistInvocation(invocation as ActionInvocationRecord, { status, error }, onPreservedReconciliation);\n\t\treturn {\n\t\t\tactionInvocationId: invocation.id,\n\t\t\tstatus,\n\t\t\terror,\n\t\t\t...(invocation.hitlRoute ? { hitlRoute: invocation.hitlRoute } : {}),\n\t\t\t...(invocation.hitlRiskTier ? { hitlRiskTier: invocation.hitlRiskTier } : {}),\n\t\t};\n\t}\n\n\tasync function writeInlineInvocation(\n\t\tinvocation: ActionInvocationRecord,\n\t\tpatch: ActionInvocationPatch,\n\t\ttransaction?: PlatformHostMutationTransaction<TDb>,\n\t\tonPreservedReconciliation?: (record: ActionInvocationRecord) => void,\n\t): Promise<boolean> {\n\t\tif (!invocation.pendingCompletion && !patch.pendingCompletion) {\n\t\t\tawait (transaction ?? options.store).updateActionInvocation(invocation.id, invocation.tenantId, invocation.spaceId, patch);\n\t\t\treturn true;\n\t\t}\n\t\tlet evidenceOnly = false;\n\t\tlet preserved: ActionInvocationRecord | undefined;\n\t\tconst current = transaction?.getActionInvocationForUpdate\n\t\t\t? await transaction.getActionInvocationForUpdate(invocation.id, invocation.tenantId, invocation.spaceId)\n\t\t\t: await options.store.getActionInvocation(invocation.id, invocation.tenantId, invocation.spaceId);\n\t\t// Budget exhaustion first commits a plain verdict, then enriches it.\n\t\t// Admit only that same terminal snapshot; never replace a sweep verdict.\n\t\tconst enrichingOwnVerdict = invocation.status === \"reconciliation_required\"\n\t\t\t&& patch.status === \"reconciliation_required\" && current?.status === \"reconciliation_required\"\n\t\t\t&& current.error === invocation.error && current.pendingCompletion?.overdueAt === undefined;\n\t\tif (current?.status === \"reconciliation_required\" && !enrichingOwnVerdict) {\n\t\t\tconst observed = {\n\t\t\t\t...current,\n\t\t\t\t...(current.result ? { result: { ...current.result } } : {}),\n\t\t\t\t...(current.pendingCompletion ? { pendingCompletion: { ...current.pendingCompletion } } : {}),\n\t\t\t};\n\t\t\t// Keep the existing verdict, including its error and overdue marker.\n\t\t\t// Reconciliation paths can still commit their independent evidence.\n\t\t\tconst parking = patch.status === \"running\" ? patch.pendingCompletion : undefined;\n\t\t\tif (parking?.parkedAt === undefined && patch.status !== \"completed\") {\n\t\t\t\tonPreservedReconciliation?.(observed);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tconst pending = current.pendingCompletion;\n\t\t\tpatch = {\n\t\t\t\tresult: patch.result,\n\t\t\t\t...(parking?.parkedAt !== undefined && pending?.overdueAt !== undefined\n\t\t\t\t\t&& pending.adapterInvocationId === parking.adapterInvocationId\n\t\t\t\t\t&& pending.externalReference === parking.externalReference\n\t\t\t\t\t? { pendingCompletion: { ...pending, parkedAt: parking.parkedAt } } : {}),\n\t\t\t};\n\t\t\tpreserved = { ...observed, ...patch };\n\t\t\tevidenceOnly = true;\n\t\t} else if (!enrichingOwnVerdict && (invocation.pendingCompletion || patch.status === \"completed\") && current?.status !== \"running\") {\n\t\t\tthrow new RecoverableFinalizationError(`Invocation is no longer running: ${invocation.id}`);\n\t\t}\n\t\tawait (transaction ?? options.store).updateActionInvocation(invocation.id, invocation.tenantId, invocation.spaceId, patch);\n\t\tif (preserved) onPreservedReconciliation?.(preserved);\n\t\treturn !evidenceOnly;\n\t}\n\n\tasync function persistInvocation(\n\t\tinvocation: ActionInvocationRecord,\n\t\tpatch: import(\"./types\").ActionInvocationPatch,\n\t\tonPreservedReconciliation?: (record: ActionInvocationRecord) => void,\n\t\tlease?: { leaseOwner: string; leaseToken: number },\n\t): Promise<boolean> {\n\t\tconst previousStatus = invocation.status;\n\t\tconst identity = lease ?? (invocation.leaseOwner && invocation.leaseToken !== undefined ? { leaseOwner: invocation.leaseOwner, leaseToken: invocation.leaseToken } : undefined);\n\t\tif (identity) {\n\t\t\tconst recoverable = options.store as Partial<RecoverablePlatformHostStore<TDb>>;\n\t\t\tif (!recoverable.updateLeasedActionInvocation) {\n\t\t\t\tthrow new HostError(\"Leased execution requires a fencing-capable PlatformHostStore.\");\n\t\t\t}\n\t\t\tconst updated = await recoverable.updateLeasedActionInvocation({\n\t\t\t\tid: invocation.id,\n\t\t\t\ttenantId: invocation.tenantId,\n\t\t\t\tspaceId: invocation.spaceId,\n\t\t\t\tworkerId: identity.leaseOwner,\n\t\t\t\tleaseToken: identity.leaseToken,\n\t\t\t\tpatch,\n\t\t\t});\n\t\t\tif (!updated) throw new RecoverableFinalizationError(`Invocation lease lost: ${invocation.id}`);\n\t\t\temitInvocationStatusTelemetry(invocation, patch.status, options.telemetry, now(), previousStatus);\n\t\t\treturn true;\n\t\t}\n\t\tconst write = (transaction?: PlatformHostMutationTransaction<TDb>) => writeInlineInvocation(invocation, patch, transaction, onPreservedReconciliation);\n\t\tconst atomicStore = invocation.pendingCompletion || patch.pendingCompletion ? asAtomicMutationStore(options.store) : undefined;\n\t\tconst updated = atomicStore ? await atomicStore.transactionWithEvents(write) : await write();\n\t\tif (updated) emitInvocationStatusTelemetry(invocation, patch.status, options.telemetry, now(), previousStatus);\n\t\treturn updated;\n\t}\n\n\tconst externalCompletion = createExternalCompletionLifecycle<TDb>({\n\t\tstore: options.store,\n\t\ttelemetry: options.telemetry,\n\t\tredactErrorText: options.redactErrorText,\n\t\tredactExternalCompletionResult: options.redactExternalCompletionResult,\n\t\teventResultFields,\n\t\tnow,\n\t\tactionResolver,\n\t\tappendEvent,\n\t\tactionResult,\n\t\twithConsistency,\n\t});\n\n\treturn {\n\t\tsubmitAction,\n\t\texecuteInvocation,\n\t\tresumeApprovedInvocation,\n\t\trecordExecutionAttestation,\n\t\trecordExternalReconciliation,\n\t\tcompleteExternalInvocation: externalCompletion.completeExternalInvocation,\n\t\treconcileOverdueCompletions: externalCompletion.reconcileOverdueCompletions,\n\t\trequeueOutboxDeadLetter: createOutboxRequeue<TDb>({\n\t\t\tstore: options.store,\n\t\t\tauthorization: options.authorization,\n\t\t\ttelemetry: options.telemetry,\n\t\t\tnow,\n\t\t}),\n\t};\n}\n\nfunction actionResult(invocation: ActionInvocationRecord): ExecuteActionResult {\n\treturn {\n\t\tactionInvocationId: invocation.id,\n\t\tstatus: invocation.status,\n\t\tresult: invocation.result,\n\t\t...(invocation.error ? { error: invocation.error } : {}),\n\t\t...(invocation.hitlRoute ? { hitlRoute: invocation.hitlRoute } : {}),\n\t\t...(invocation.hitlRiskTier ? { hitlRiskTier: invocation.hitlRiskTier } : {}),\n\t\t...(invocation.authorizationReconciliation ? { reconciliation: invocation.authorizationReconciliation } : {}),\n\t\t...(invocation.adapterReconciliation ? { adapterReconciliation: invocation.adapterReconciliation } : {}),\n\t\t...(invocation.pendingCompletion ? { pendingCompletion: invocation.pendingCompletion } : {}),\n\t};\n}\n\nfunction asApprovalStore<TDb>(\n\tstore: PlatformHostOptions<TDb>[\"store\"],\n): ApprovalPlatformHostStore<TDb> | undefined {\n\tconst candidate = store as Partial<ApprovalPlatformHostStore<TDb>>;\n\treturn typeof candidate.recordHitlDecision === \"function\" &&\n\t\ttypeof candidate.beginApprovalDecision === \"function\"\n\t\t? (store as ApprovalPlatformHostStore<TDb>)\n\t\t: undefined;\n}\n\nfunction asOutboxStore<TDb>(\n\tstore: PlatformHostOptions<TDb>[\"store\"],\n): OutboxPlatformHostStore<TDb> | undefined {\n\tconst candidate = store as Partial<OutboxPlatformHostStore<TDb>>;\n\treturn typeof candidate.appendEventWithOutbox === \"function\" &&\n\t\ttypeof candidate.claimOutbox === \"function\"\n\t\t? (store as OutboxPlatformHostStore<TDb>)\n\t\t: undefined;\n}\n\nfunction numberValue(value: unknown): number | undefined {\n\treturn typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n}\n\nfunction stringValue(value: unknown): string | undefined {\n\treturn typeof value === \"string\" && value.length > 0 ? value : undefined;\n}\n\nfunction isRiskTier(value: unknown): value is \"low\" | \"medium\" | \"high\" {\n\treturn value === \"low\" || value === \"medium\" || value === \"high\";\n}\n\nfunction toAuthorizationInput<TDb>(\n\taction: ActionDefinition<TDb>,\n\tinput: {\n\t\ttenantId: string;\n\t\tspaceId: string;\n\t\tactorId: string;\n\t\tactorType: import(\"@fabricorg/platform\").ActorType;\n\t},\n): ActionAuthorizationInput {\n\treturn {\n\t\tactionId: action.actionId,\n\t\tnamespace: action.namespace,\n\t\trequiredPermissions: action.requiredPermissions ?? [],\n\t\trequiredRoles: action.requiredRoles ?? [],\n\t\ttenantId: input.tenantId,\n\t\tspaceId: input.spaceId,\n\t\tactorId: input.actorId,\n\t\tactorType: input.actorType,\n\t};\n}\n\nfunction declaredPolicies(policyIds: readonly string[]): RuntimePolicyDefinition[] {\n\treturn policyIds.map((policyId) => ({\n\t\tpolicyId: policyId as `${string}.v${number}`,\n\t\tpolicyVersion: Number(policyId.split(\".v\").at(-1) ?? 1),\n\t\tkind: \"code\",\n\t\tcodeEvaluatorPolicyId: policyId as `${string}.v${number}`,\n\t}));\n}\n\nfunction initialState(machine: import(\"@fabricorg/platform\").StateMachineDefinition | undefined): string {\n\treturn Object.values(machine?.states ?? {}).find((state) => state.stateClass === \"initial\")?.id ?? \"none\";\n}\n\nfunction isTerminal(status: ActionStatus): status is Exclude<ActionStatus, \"pending\" | \"running\" | \"waiting_for_approval\"> {\n\treturn [\"completed\", \"failed\", \"blocked_by_policy\", \"reconciliation_required\", \"validation_failed\"].includes(status);\n}\n\nfunction isAdmissionTime(value: unknown): value is Date {\n\treturn value instanceof Date && Number.isFinite(value.getTime());\n}\n\n/** An own data property of `value`, or `undefined`; a getter is not run and a throwing Proxy trap reads as `undefined`. */\nfunction ownDataProperty(value: unknown, key: string): unknown {\n\tif (value === null || typeof value !== \"object\") return undefined;\n\ttry {\n\t\tconst descriptor = Reflect.getOwnPropertyDescriptor(value, key);\n\t\treturn descriptor && \"value\" in descriptor ? descriptor.value : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction validateAuthorizationBinding(\n\tinput: SubmissionSnapshot,\n\tparameterDigest: string,\n\tauthorityMoment?: \"capture\" | \"execution\" | \"both\",\n\tcurrentTime = new Date(),\n): void {\n\tconst binding = input.authorizationBinding!;\n\tif (binding.id !== input.authorizationBindingId && input.authorizationBindingId) throw new Error(\"Authorization binding ID does not match authorizationBindingId.\");\n\tif (binding.tenantId !== input.tenantId || binding.actorId !== input.actorId || binding.actionId !== input.actionId || binding.parameterDigest !== parameterDigest) {\n\t\tthrow new Error(\"Authorization binding does not match the submitted command identity.\");\n\t}\n\tif (authorityMoment && binding.governingMoment !== authorityMoment) throw new Error(\"Authorization binding governingMoment does not match the action execution contract.\");\n\tconst capturedAt = Date.parse(binding.capturedAt);\n\tconst expiresAt = binding.expiresAt === undefined ? undefined : Date.parse(binding.expiresAt);\n\tif (!Number.isFinite(capturedAt) || (expiresAt !== undefined && !Number.isFinite(expiresAt))) {\n\t\tthrow new Error(\"Authorization binding timestamps must be valid ISO-8601 values.\");\n\t}\n\tif (expiresAt !== undefined && (expiresAt <= capturedAt || (authorityMoment === \"capture\" && expiresAt <= currentTime.getTime()))) {\n\t\tthrow new Error(\"Authorization binding must be unexpired at capture and expire after capturedAt.\");\n\t}\n}\n\nfunction idempotencyConflict(\n\texisting: ActionInvocationRecord,\n\tincoming: { actorId: string; authorizationBindingId?: string; actionVersion: number; parameterDigest: string; idempotencyKey: string },\n): IdempotencyConflict | undefined {\n\tconst reasons: IdempotencyConflict[\"reasons\"] = [];\n\tif ((existing.idempotencyActorId ?? existing.actorId) !== incoming.actorId) reasons.push(\"actor\");\n\tif ((existing.idempotencyAuthorizationBindingId ?? existing.authorizationBindingId) !== incoming.authorizationBindingId) reasons.push(\"authority_binding\");\n\tif (existing.actionVersion !== incoming.actionVersion) reasons.push(\"action_version\");\n\tif (existing.parameterDigest !== incoming.parameterDigest) reasons.push(\"parameters\");\n\treturn reasons.length ? { code: \"IDEMPOTENCY_CONFLICT\", idempotencyKey: incoming.idempotencyKey, existingInvocationId: existing.id, reasons } : undefined;\n}\n\nfunction isKnownAdapterOutcome(outcome: unknown): outcome is import(\"@fabricorg/platform\").AdapterOutcomeKind {\n\treturn outcome === \"success\" || outcome === \"transient_failure\" || outcome === \"permanent_failure\" ||\n\t\toutcome === \"timeout\" || outcome === \"ambiguous\";\n}\n","import type { AssetEventEnvelope } from \"@fabricorg/platform\";\nimport type {\n\tEnterpriseEventActorDisclosure,\n\tEnterpriseEventEnvelope,\n\tOutboxActorDisclosure,\n\tOutboxEventMetadata,\n\tOutboxPlatformHostStore,\n\tOutboxRecord,\n} from \"./types\";\nimport {\n\temitPlatformHostTelemetry,\n\tPLATFORM_HOST_METRIC_NAMES,\n\ttype PlatformHostTelemetry,\n\ttype PlatformHostTelemetryEventName,\n} from \"./observability\";\n\nexport function toEnterpriseEventEnvelope(\n\tevent: AssetEventEnvelope,\n\tmetadata: OutboxEventMetadata,\n): EnterpriseEventEnvelope {\n\treturn {\n\t\teventId: event.id,\n\t\teventType: event.eventType,\n\t\teventSchemaVersion: event.eventSchemaVersion,\n\t\ttenantId: event.tenantId,\n\t\tspaceId: event.spaceId,\n\t\tsubjectType: event.subjectType,\n\t\tsubjectId: event.subjectId,\n\t\tsequence: event.sequence,\n\t\t...(event.actionInvocationId ? { actionInvocationId: event.actionInvocationId } : {}),\n\t\tcorrelationId: event.correlationId,\n\t\t...(event.causationId ? { causationId: event.causationId } : {}),\n\t\t// Opt-in only: without it the keys are absent, so existing publishers see an unchanged envelope.\n\t\t...(includesActor(metadata) && event.actorId ? { actorId: event.actorId } : {}),\n\t\t...(includesActor(metadata) && event.actorType ? { actorType: event.actorType } : {}),\n\t\toccurredAt: event.occurredAt,\n\t\trecordedAt: event.recordedAt,\n\t\tproducerModuleVersion: metadata.producerModuleVersion,\n\t\tpayloadClassification: metadata.payloadClassification,\n\t\t...(metadata.traceContext ? { traceContext: { ...metadata.traceContext } } : {}),\n\t\t...(metadata.includeProvenance && event.provenance ? { provenance: event.provenance } : {}),\n\t\t// A provisional fact must stay marked as provisional once it leaves the platform.\n\t\t...(event.consistency ? { consistency: event.consistency } : {}),\n\t\tpayload: event.payload,\n\t};\n}\n\n/** The `includeActor` decision a store records with the outbox record it writes from `metadata`. */\nexport function outboxActorDisclosure(metadata: OutboxEventMetadata): OutboxActorDisclosure {\n\treturn includesActor(metadata) ? \"included\" : \"suppressed\";\n}\n\nfunction includesActor(metadata: OutboxEventMetadata): boolean {\n\treturn metadata.includeActor === true;\n}\n\nexport interface EnterpriseEventPublishContext {\n\tsignal: AbortSignal;\n\t/**\n\t * Why the envelope does or does not carry `actorId`/`actorType`. `runOutboxRelayCycle()` always\n\t * sets it; a caller other than the relay may omit it, which a consumer should treat like `legacy`.\n\t */\n\tactorDisclosure?: EnterpriseEventActorDisclosure;\n}\n\nexport interface EnterpriseEventPublisher {\n\tpublish(event: EnterpriseEventEnvelope, context?: EnterpriseEventPublishContext): Promise<void>;\n}\n\nexport interface OutboxRelayOptions<TDb> {\n\tstore: OutboxPlatformHostStore<TDb>;\n\tpublisher: EnterpriseEventPublisher;\n\tworkerId: string;\n\tleaseDurationMs?: number;\n\tleaseRenewalIntervalMs?: number;\n\tpublishTimeoutMs?: number;\n\tbatchSize?: number;\n\tmaxAttempts?: number;\n\tretryDelayMs?: (attempt: number) => number;\n\tnow?: () => Date;\n\ttelemetry?: PlatformHostTelemetry;\n}\n\nexport interface OutboxRelayResult {\n\tclaimed: number;\n\tpublished: number;\n\tfailed: number;\n\tdeadLettered: number;\n}\n\nexport async function runOutboxRelayCycle<TDb>(\n\toptions: OutboxRelayOptions<TDb>,\n): Promise<OutboxRelayResult> {\n\tconst now = options.now ?? (() => new Date());\n\tconst maxAttempts = options.maxAttempts ?? 10;\n\tconst leaseDurationMs = options.leaseDurationMs ?? 30_000;\n\temitRelayTelemetry(options.telemetry, \"outbox.relay.started\", now(), options.workerId);\n\tlet records: OutboxRecord[];\n\ttry {\n\t\trecords = await options.store.claimOutbox({\n\t\t\tworkerId: options.workerId,\n\t\t\tleaseDurationMs,\n\t\t\tlimit: options.batchSize ?? 100,\n\t\t\tnow: now(),\n\t\t});\n\t} catch (error) {\n\t\temitRelayTelemetry(options.telemetry, \"outbox.relay.failed\", now(), options.workerId);\n\t\tthrow error;\n\t}\n\tfor (const record of records) {\n\t\temitPlatformHostTelemetry(options.telemetry, {\n\t\t\tkind: \"event\",\n\t\t\tname: \"outbox.lease_claimed\",\n\t\t\tmetricName: PLATFORM_HOST_METRIC_NAMES.outboxLeaseClaimed,\n\t\t\toccurredAt: now(),\n\t\t\ttenantId: record.tenantId,\n\t\t\tspaceId: record.spaceId,\n\t\t\tattributes: { attempt: record.attemptCount },\n\t\t});\n\t}\n\tconst result: OutboxRelayResult = { claimed: records.length, published: 0, failed: 0, deadLettered: 0 };\n\tfor (const record of records) {\n\t\tconst stopHeartbeat = startOutboxHeartbeat(options, record, leaseDurationMs);\n\t\ttry {\n\t\t\tawait publishWithTimeout(\n\t\t\t\toptions.publisher,\n\t\t\t\trecord,\n\t\t\t\toptions.publishTimeoutMs ?? 10_000,\n\t\t\t);\n\t\t\tawait stopHeartbeat();\n\t\t\ttry {\n\t\t\t\tawait options.store.markOutboxPublished(record.id, options.workerId, now(), record.leaseToken);\n\t\t\t} catch {\n\t\t\t\t// Publishing may already have succeeded. Leave the row for lease expiry and\n\t\t\t\t// replay with the same immutable event ID; do not claim completion.\n\t\t\t\tresult.failed += 1;\n\t\t\t\temitPlatformHostTelemetry(options.telemetry, {\n\t\t\t\t\tkind: \"event\",\n\t\t\t\t\tname: \"outbox.failed\",\n\t\t\t\t\tmetricName: PLATFORM_HOST_METRIC_NAMES.outboxFailed,\n\t\t\t\t\toccurredAt: now(),\n\t\t\t\t\ttenantId: record.tenantId,\n\t\t\t\t\tspaceId: record.spaceId,\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tresult.published += 1;\n\t\t\temitPlatformHostTelemetry(options.telemetry, {\n\t\t\t\tkind: \"event\",\n\t\t\t\tname: \"outbox.published\",\n\t\t\t\tmetricName: PLATFORM_HOST_METRIC_NAMES.outboxPublished,\n\t\t\t\toccurredAt: now(),\n\t\t\t\ttenantId: record.tenantId,\n\t\t\t\tspaceId: record.spaceId,\n\t\t\t});\n\t\t} catch {\n\t\t\tawait stopHeartbeat();\n\t\t\tconst deadLetter = record.attemptCount >= maxAttempts;\n\t\t\ttry {\n\t\t\t\tawait options.store.markOutboxFailed({\n\t\t\t\t\tid: record.id,\n\t\t\t\t\tworkerId: options.workerId,\n\t\t\t\t\tleaseToken: record.leaseToken,\n\t\t\t\t\terror: \"Event publisher failed\",\n\t\t\t\t\tavailableAt: new Date(now().getTime() + (options.retryDelayMs?.(record.attemptCount) ?? 1_000)),\n\t\t\t\t\tdeadLetter,\n\t\t\t\t});\n\t\t\t} catch {\n\t\t\t\t// Lease loss is recoverable by a later relay; continue the current batch.\n\t\t\t}\n\t\t\tresult.failed += 1;\n\t\t\tif (deadLetter) result.deadLettered += 1;\n\t\t\temitPlatformHostTelemetry(options.telemetry, {\n\t\t\t\tkind: \"event\",\n\t\t\t\tname: deadLetter ? \"outbox.dead_lettered\" : \"outbox.failed\",\n\t\t\t\tmetricName: deadLetter\n\t\t\t\t\t? PLATFORM_HOST_METRIC_NAMES.outboxDeadLettered\n\t\t\t\t\t: PLATFORM_HOST_METRIC_NAMES.outboxFailed,\n\t\t\t\toccurredAt: now(),\n\t\t\t\ttenantId: record.tenantId,\n\t\t\t\tspaceId: record.spaceId,\n\t\t\t\tattributes: { attempt: record.attemptCount },\n\t\t\t});\n\t\t}\n\t}\n\temitRelayTelemetry(options.telemetry, \"outbox.relay.completed\", now(), options.workerId, {\n\t\tclaimed: result.claimed,\n\t\tpublished: result.published,\n\t\tfailed: result.failed,\n\t\tdeadLettered: result.deadLettered,\n\t});\n\treturn result;\n}\n\nasync function publishWithTimeout(\n\tpublisher: EnterpriseEventPublisher,\n\trecord: OutboxRecord,\n\ttimeoutMs: number,\n): Promise<void> {\n\tif (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {\n\t\tthrow new Error(\"publishTimeoutMs must be a positive finite number\");\n\t}\n\tconst controller = new AbortController();\n\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\tconst timeout = new Promise<never>((_, reject) => {\n\t\ttimer = setTimeout(() => {\n\t\t\tconst error = new Error(`Event publisher timed out after ${timeoutMs}ms`);\n\t\t\tcontroller.abort(error);\n\t\t\treject(error);\n\t\t}, timeoutMs);\n\t});\n\ttry {\n\t\tconst context: EnterpriseEventPublishContext = {\n\t\t\tsignal: controller.signal,\n\t\t\tactorDisclosure: record.actorDisclosure ?? \"legacy\",\n\t\t};\n\t\tawait Promise.race([publisher.publish(record.event, context), timeout]);\n\t} finally {\n\t\tif (timer) clearTimeout(timer);\n\t}\n}\n\nfunction startOutboxHeartbeat<TDb>(\n\toptions: OutboxRelayOptions<TDb>,\n\trecord: OutboxRecord,\n\tleaseDurationMs: number,\n): () => Promise<void> {\n\tif (!record.leaseToken) return async () => undefined;\n\tconst intervalMs = options.leaseRenewalIntervalMs ??\n\t\tMath.max(1, Math.floor(leaseDurationMs / 3));\n\tlet stopped = false;\n\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\tlet running: Promise<void> | undefined;\n\tconst schedule = () => {\n\t\tif (!stopped) timer = setTimeout(tick, intervalMs);\n\t};\n\tconst tick = () => {\n\t\trunning = options.store.renewOutboxLease({\n\t\t\tid: record.id,\n\t\t\tworkerId: options.workerId,\n\t\t\tleaseToken: record.leaseToken!,\n\t\t\tleaseDurationMs,\n\t\t}).then(() => undefined).catch(() => undefined).finally(schedule);\n\t};\n\tschedule();\n\treturn async () => {\n\t\tstopped = true;\n\t\tif (timer) clearTimeout(timer);\n\t\tawait running;\n\t};\n}\n\n/**\n * A copy with its own Date fields and trace context. The event payload and\n * provenance are shallow: the copy shares them with the record, as before.\n */\nexport function cloneOutboxRecord(record: OutboxRecord): OutboxRecord {\n\tconst event: EnterpriseEventEnvelope = {\n\t\t...record.event,\n\t\toccurredAt: new Date(record.event.occurredAt),\n\t\trecordedAt: new Date(record.event.recordedAt),\n\t\t...(record.event.traceContext ? { traceContext: { ...record.event.traceContext } } : {}),\n\t};\n\t// Same rule as PostgreSQL hydration: only a record recorded as included yields actor identity,\n\t// whatever its stored envelope holds. The keys are removed, not set to undefined.\n\tif (record.actorDisclosure !== \"included\") {\n\t\tdelete event.actorId;\n\t\tdelete event.actorType;\n\t}\n\treturn {\n\t\t...record,\n\t\tavailableAt: new Date(record.availableAt),\n\t\tcreatedAt: new Date(record.createdAt),\n\t\t...(record.leaseExpiresAt ? { leaseExpiresAt: new Date(record.leaseExpiresAt) } : {}),\n\t\t...(record.publishedAt ? { publishedAt: new Date(record.publishedAt) } : {}),\n\t\tevent,\n\t};\n}\n\nfunction emitRelayTelemetry(\n\ttelemetry: PlatformHostTelemetry | undefined,\n\tname: Extract<PlatformHostTelemetryEventName, `outbox.relay.${string}`>,\n\toccurredAt: Date,\n\tworkerId: string,\n\tattributes?: Record<string, number>,\n): void {\n\tconst metricName = name === \"outbox.relay.started\"\n\t\t? PLATFORM_HOST_METRIC_NAMES.outboxRelayCyclesStarted\n\t\t: name === \"outbox.relay.completed\"\n\t\t\t? PLATFORM_HOST_METRIC_NAMES.outboxRelayCyclesCompleted\n\t\t\t: PLATFORM_HOST_METRIC_NAMES.outboxRelayCyclesFailed;\n\temitPlatformHostTelemetry(telemetry, {\n\t\tkind: \"event\",\n\t\tname,\n\t\tmetricName,\n\t\toccurredAt,\n\t\tattributes: { workerId, ...attributes },\n\t});\n}\n","import { RecoverableFinalizationError, matchesSettledInvocation } from \"./host-internals\";\nimport type { AssetEventEnvelope } from \"@fabricorg/platform\";\nimport type {\n\tApprovalDecisionTransitionResult,\n\tApprovalPlatformHostStore,\n\tActionInvocationRecord,\n\tActionInvocationPatch,\n\tAdapterInvocationRecord,\n\tAdapterInvocationScope,\n\tAdapterInvocationWriteInput,\n\tBeginApprovalDecisionInput,\n\tClaimActionInvocationsInput,\n\tCreateActionInvocationInput,\n\tHitlDecisionEvidence,\n\tGovernancePlatformHostStore,\n\tPolicyObligationRecord,\n\tExecutionAttestationRecord,\n\tExternalReconciliationRecord,\n\tListActionInvocationsInput,\n\tPolicyEvaluationRecord,\n\tRecoverablePlatformHostStore,\n\tOutboxPlatformHostStore,\n\tOutboxRecord,\n\tOutboxRequeuePlatformHostStore,\n\tOutboxRequeueRecord,\n\tRequeueOutboxDeadLetterStoreInput,\n\tRequeueOutboxDeadLetterStoreResult,\n\tOutboxEventMetadata,\n\tClaimOutboxInput,\n\tOutboxStatus,\n\tPlatformHostMutationTransaction,\n} from \"./types\";\nimport { cloneOutboxRecord, outboxActorDisclosure, toEnterpriseEventEnvelope } from \"./outbox\";\nimport type { PlatformHostHealthCounts, PlatformHostHealthQuery } from \"./observability\";\n\nexport interface MemoryPlatformHostTransactionProvider<TDb> {\n\tsnapshot(db: TDb): TDb;\n\trestore(db: TDb, snapshot: TDb): void;\n}\n\nexport class MemoryPlatformHostStore<TDb>\n\timplements RecoverablePlatformHostStore<TDb>, ApprovalPlatformHostStore<TDb>, GovernancePlatformHostStore<TDb>, OutboxPlatformHostStore<TDb>, OutboxRequeuePlatformHostStore<TDb> {\n\treadonly transactionalOutbox: boolean;\n\tdeclare transactionWithEvents?: <TResult>(run: (transaction: PlatformHostMutationTransaction<TDb>) => Promise<TResult>) => Promise<TResult>;\n\tprivate adapterCommit: Promise<void> | undefined;\n\tprivate transactionTail: Promise<void> = Promise.resolve();\n\treadonly invocations: ActionInvocationRecord[] = [];\n\treadonly policyEvaluations: PolicyEvaluationRecord[] = [];\n\treadonly adapterInvocations: AdapterInvocationRecord[] = [];\n\treadonly events: AssetEventEnvelope[] = [];\n\treadonly policyObligations: PolicyObligationRecord[] = [];\n\treadonly executionAttestations: ExecutionAttestationRecord[] = [];\n\treadonly externalReconciliations: ExternalReconciliationRecord[] = [];\n\treadonly outbox: OutboxRecord[] = [];\n\t/**\n\t * Requeue evidence is append-only audit history, so unlike the ledger\n\t * arrays above, which tests have always inspected and seeded directly, it\n\t * is not public: `listOutboxRequeues` returns copies with their own Dates. TypeScript\n\t * `private`, as for the store's other internals, is a compile-time guard.\n\t */\n\tprivate readonly outboxRequeues: OutboxRequeueRecord[] = [];\n\n\tconstructor(\n\t\treadonly db: TDb,\n\t\ttransactionProvider?: MemoryPlatformHostTransactionProvider<TDb>,\n\t) {\n\t\tthis.transactionalOutbox = transactionProvider !== undefined;\n\t\tif (transactionProvider) this.transactionWithEvents = (run) => this.runTransactionWithEvents(run, transactionProvider);\n\t}\n\n\tasync transaction<TResult>(run: (db: TDb) => Promise<TResult>): Promise<TResult> {\n\t\treturn run(this.db);\n\t}\n\n\tprivate async runTransactionWithEvents<TResult>(\n\t\trun: (transaction: PlatformHostMutationTransaction<TDb>) => Promise<TResult>,\n\t\ttransactionProvider: MemoryPlatformHostTransactionProvider<TDb>,\n\t): Promise<TResult> {\n\t\tlet release!: () => void;\n\t\tconst previous = this.transactionTail;\n\t\tthis.transactionTail = new Promise<void>((resolve) => { release = resolve; });\n\t\tawait previous;\n\t\tlet domainSnapshot: TDb | undefined;\n\t\tlet snapshotCreated = false;\n\t\tlet finishCommit: (() => void) | undefined;\n\t\tconst undoLedgerWrites: Array<() => void> = [];\n\t\ttry {\n\t\t\tdomainSnapshot = transactionProvider.snapshot(this.db);\n\t\t\tsnapshotCreated = true;\n\t\t\tconst pendingEvents: Array<{ event: AssetEventEnvelope; metadata?: OutboxEventMetadata }> = [];\n\t\t\tconst pendingUpdates: Array<{ id: string; tenantId: string; spaceId: string; patch: ActionInvocationPatch }> = [];\n\t\t\tconst pendingAdapterUpdates: Array<Parameters<NonNullable<PlatformHostMutationTransaction<TDb>[\"updateAdapterInvocation\"]>>> = [];\n\t\t\tconst conditionalAdapters: AdapterInvocationWriteInput[] = [];\n\t\t\tconst leasedUpdates: import(\"./types\").UpdateLeasedActionInvocationInput[] = [];\n\t\t\tconst pendingReconciliations: ExternalReconciliationRecord[] = [];\n\t\t\tconst appendPending = async (event: AssetEventEnvelope, metadata?: OutboxEventMetadata) => {\n\t\t\t\tif (this.events.some((candidate) => candidate.id === event.id) || pendingEvents.some((candidate) => candidate.event.id === event.id)) return;\n\t\t\t\tpendingEvents.push({ event, ...(metadata ? { metadata } : {}) });\n\t\t\t};\n\t\t\tconst result = await run({\n\t\t\t\tdb: this.db,\n\t\t\t\tgetActionInvocationForUpdate: async (id, tenantId, spaceId) => {\n\t\t\t\t\tconst record = await this.getActionInvocation(id, tenantId, spaceId);\n\t\t\t\t\treturn record ? structuredClone(record) : undefined;\n\t\t\t\t},\n\t\t\t\tgetEvent: async (id, tenantId, spaceId) =>\n\t\t\t\t\tpendingEvents.find((candidate) =>\n\t\t\t\t\t\tcandidate.event.id === id &&\n\t\t\t\t\t\tcandidate.event.tenantId === tenantId &&\n\t\t\t\t\t\tcandidate.event.spaceId === spaceId)?.event ??\n\t\t\t\t\tthis.events.find((event) =>\n\t\t\t\t\t\tevent.id === id &&\n\t\t\t\t\t\tevent.tenantId === tenantId &&\n\t\t\t\t\t\tevent.spaceId === spaceId),\n\t\t\t\tappendEvent: (event) => appendPending(event),\n\t\t\t\tappendEventWithOutbox: (event, metadata) => appendPending(event, metadata),\n\t\t\t\tnextEventSequence: async (tenantId, spaceId) => (await this.listEvents(tenantId, spaceId)).length + pendingEvents.filter((candidate) => candidate.event.tenantId === tenantId && candidate.event.spaceId === spaceId).length + 1,\n\t\t\t\tlistEvents: async (tenantId, spaceId) => [...await this.listEvents(tenantId, spaceId), ...pendingEvents.map((candidate) => candidate.event).filter((event) => event.tenantId === tenantId && event.spaceId === spaceId)],\n\t\t\t\tgetEntityStateSource: async (tenantId, spaceId, entityType, entityId) => {\n\t\t\t\t\tlet source = await this.getEntityStateSource(tenantId, spaceId, entityType, entityId);\n\t\t\t\t\tfor (const { event } of pendingEvents) {\n\t\t\t\t\t\tif (event.tenantId !== tenantId || event.spaceId !== spaceId ||\n\t\t\t\t\t\t\tevent.subjectType !== entityType || event.subjectId !== entityId) continue;\n\t\t\t\t\t\tconst state = (event.payload as { toState?: unknown } | undefined)?.toState;\n\t\t\t\t\t\tif (typeof state === \"string\") source = typeof event.actionInvocationId === \"string\"\n\t\t\t\t\t\t\t? { state, actionInvocationId: event.actionInvocationId } : undefined;\n\t\t\t\t\t}\n\t\t\t\t\treturn source;\n\t\t\t\t},\n\t\t\t\tgetEntityState: async (tenantId, spaceId, entityType, entityId) => {\n\t\t\t\t\tlet state = await this.getEntityState(tenantId, spaceId, entityType, entityId);\n\t\t\t\t\tfor (const pending of pendingEvents) {\n\t\t\t\t\t\tconst event = pending.event;\n\t\t\t\t\t\tif (event.tenantId !== tenantId || event.spaceId !== spaceId || event.subjectType !== entityType || event.subjectId !== entityId) continue;\n\t\t\t\t\t\tconst candidate = (event.payload as { toState?: unknown } | undefined)?.toState;\n\t\t\t\t\t\tif (typeof candidate === \"string\") state = candidate;\n\t\t\t\t\t}\n\t\t\t\t\treturn state;\n\t\t\t\t},\n\t\t\t\tupdateAdapterInvocation: async (id, patch, scope) => {\n\t\t\t\t\tif (!await this.getAdapterInvocation(id, scope)) throw new Error(`AdapterInvocation not found: ${id}`);\n\t\t\t\t\tpendingAdapterUpdates.push([id, patch, scope]);\n\t\t\t\t},\n\t\t\t\twriteAdapterInvocation: async input => {\n\t\t\t\t\tif (!this.adapterWriteMatches(input)) return false;\n\t\t\t\t\tconditionalAdapters.push(structuredClone(input));\n\t\t\t\t\treturn true;\n\t\t\t\t},\n\t\t\t\tappendExternalReconciliation: async (record) => { pendingReconciliations.push(record); },\n\t\t\t\tupdateActionInvocation: async (id, tenantId, spaceId, patch) => { pendingUpdates.push({ id, tenantId, spaceId, patch: copyInvocationPatch(patch) }); },\n\t\t\t\tupdateLeasedActionInvocation: async (input) => {\n\t\t\t\t\tconst record = await this.getActionInvocation(input.id, input.tenantId, input.spaceId);\n\t\t\t\t\tif (!record || record.status !== \"running\" || record.leaseOwner !== input.workerId ||\n\t\t\t\t\t\trecord.leaseToken !== input.leaseToken) return false;\n\t\t\t\t\tleasedUpdates.push(structuredClone(input));\n\t\t\t\t\tpendingUpdates.push({ id: input.id, tenantId: input.tenantId, spaceId: input.spaceId, patch: copyInvocationPatch(input.patch) });\n\t\t\t\t\treturn true;\n\t\t\t\t},\n\t\t\t});\n\t\t\tthis.adapterCommit = new Promise<void>(resolve => { finishCommit = resolve; });\n\t\t\t// The commit lock excludes claims and conditional writes until all buffered\n\t\t\t// writes finish. Recheck before touching any ledger, including events.\n\t\t\tfor (const input of leasedUpdates) {\n\t\t\t\tconst row = this.invocations.find(row => row.id === input.id && row.tenantId === input.tenantId && row.spaceId === input.spaceId);\n\t\t\t\tif (!row || row.status !== \"running\" || row.leaseOwner !== input.workerId || row.leaseToken !== input.leaseToken) throw leaseWriteLost(input.id);\n\t\t\t}\n\t\t\tfor (const input of conditionalAdapters) if (!this.adapterWriteMatches(input)) throw leaseWriteLost(input.scope.actionInvocationId);\n\t\t\tfor (const update of pendingUpdates) {\n\t\t\t\tif (!await this.getActionInvocation(update.id, update.tenantId, update.spaceId)) throw new Error(`ActionInvocation not found: ${update.id}`);\n\t\t\t}\n\t\t\t// Journal only this commit's writes, after run has finished, so rollback\n\t\t\t// preserves lifecycle writes made outside the transaction while it ran.\n\t\t\tconst rememberRecord = (record: object) => {\n\t\t\t\tconst before = { ...record };\n\t\t\t\tundoLedgerWrites.push(() => {\n\t\t\t\t\tfor (const key of Object.keys(record)) Reflect.deleteProperty(record, key);\n\t\t\t\t\tObject.assign(record, before);\n\t\t\t\t});\n\t\t\t};\n\t\t\tconst rememberAppend = <T extends { id: string }>(rows: T[], id: string) => {\n\t\t\t\tif (!rows.some((row) => row.id === id)) undoLedgerWrites.push(() => {\n\t\t\t\t\tconst index = rows.findIndex((row) => row.id === id);\n\t\t\t\t\tif (index !== -1) rows.splice(index, 1);\n\t\t\t\t});\n\t\t\t};\n\t\t\tfor (const pending of pendingEvents) {\n\t\t\t\trememberAppend(this.events, pending.event.id);\n\t\t\t\trememberAppend(this.outbox, pending.event.id);\n\t\t\t\tif (pending.metadata) await this.appendEventWithOutbox(pending.event, pending.metadata);\n\t\t\t\telse await this.appendEvent(pending.event);\n\t\t\t}\n\t\t\tfor (const record of pendingReconciliations) {\n\t\t\t\trememberAppend(this.externalReconciliations, record.id);\n\t\t\t\tawait this.appendExternalReconciliation(record);\n\t\t\t}\n\t\t\tfor (const [id, patch, scope] of pendingAdapterUpdates) {\n\t\t\t\tconst record = await this.getAdapterInvocation(id, scope);\n\t\t\t\tif (!record) throw new Error(`AdapterInvocation not found: ${id}`);\n\t\t\t\trememberRecord(record);\n\t\t\t\tawait this.updateAdapterInvocation(id, patch, scope);\n\t\t\t}\n\t\t\tfor (const input of conditionalAdapters) {\n\t\t\t\tif (!this.adapterWriteMatches(input)) throw leaseWriteLost(input.scope.actionInvocationId);\n\t\t\t\tif (input.mutation.kind === \"create\") {\n\t\t\t\t\trememberAppend(this.adapterInvocations, input.mutation.record.id);\n\t\t\t\t\tawait this.createAdapterInvocation(input.mutation.record);\n\t\t\t\t} else {\n\t\t\t\t\tconst { id } = input.mutation;\n\t\t\t\t\tconst row = this.adapterInvocations.find(row => row.id === id)!;\n\t\t\t\t\trememberRecord(row);\n\t\t\t\t\tawait this.updateAdapterInvocation(input.mutation.id, input.mutation.patch, input.scope);\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (const update of pendingUpdates) {\n\t\t\t\trememberRecord((await this.getActionInvocation(update.id, update.tenantId, update.spaceId))!);\n\t\t\t\tawait this.updateActionInvocation(update.id, update.tenantId, update.spaceId, update.patch);\n\t\t\t}\n\t\t\treturn result;\n\t\t} catch (error) {\n\t\t\tfor (const undo of undoLedgerWrites.reverse()) undo();\n\t\t\tif (snapshotCreated) transactionProvider.restore(this.db, domainSnapshot!);\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tif (finishCommit) { this.adapterCommit = undefined; finishCommit(); }\n\t\t\trelease();\n\t\t}\n\t}\n\n\tasync createActionInvocation(\n\t\tinput: CreateActionInvocationInput,\n\t): Promise<ActionInvocationRecord> {\n\t\tif (input.idempotencyKey) {\n\t\t\tconst existing = this.invocations.find(\n\t\t\t\t(record) =>\n\t\t\t\t\trecord.tenantId === input.tenantId &&\n\t\t\t\t\trecord.spaceId === input.spaceId &&\n\t\t\t\t\trecord.actionId === input.actionId &&\n\t\t\t\t\trecord.idempotencyKey === input.idempotencyKey,\n\t\t\t);\n\t\t\tif (existing) return existing;\n\t\t}\n\t\tconst now = new Date();\n\t\tconst record = { ...input, attemptCount: 0, leaseToken: 0, createdAt: now, updatedAt: now };\n\t\tthis.invocations.push(record);\n\t\treturn record;\n\t}\n\n\tasync getActionInvocation(\n\t\tid: string,\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t): Promise<ActionInvocationRecord | undefined> {\n\t\treturn this.invocations.find(\n\t\t\t(record) => record.id === id && record.tenantId === tenantId && record.spaceId === spaceId,\n\t\t);\n\t}\n\n\tasync updateActionInvocation(\n\t\tid: string,\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t\tpatch: ActionInvocationPatch,\n\t): Promise<void> {\n\t\tconst record = this.invocations.find(row => row.id === id && row.tenantId === tenantId && row.spaceId === spaceId);\n\t\tif (!record) throw new Error(`ActionInvocation not found: ${id}`);\n\t\tObject.assign(record, patch, { updatedAt: new Date() });\n\t\tif (Object.hasOwn(patch, \"pendingStateTransition\")) {\n\t\t\tif (patch.pendingStateTransition) record.pendingStateTransition = { ...patch.pendingStateTransition };\n\t\t\telse delete record.pendingStateTransition;\n\t\t}\n\t\tif (Object.hasOwn(patch, \"pendingCompletion\") && patch.pendingCompletion === undefined) delete record.pendingCompletion;\n\t\tif (Object.hasOwn(patch, \"externalCompletion\") && patch.externalCompletion === undefined) delete record.externalCompletion;\n\t\tif (Object.hasOwn(patch, \"error\") && patch.error === undefined) delete record.error;\n\t\tif (patch.pendingCompletion && patch.status === \"running\") {\n\t\t\t// Parked: waiting on an external system is not holding a lease. A\n\t\t\t// handoff recorded mid-execution (no status) keeps the lease so the\n\t\t\t// executing worker can still finalize.\n\t\t\tdelete record.leaseOwner;\n\t\t\tdelete record.leaseExpiresAt;\n\t\t}\n\t\tif (\n\t\t\tpatch.status === \"waiting_for_approval\" ||\n\t\t\tpatch.status === \"completed\" ||\n\t\t\tpatch.status === \"failed\" ||\n\t\t\tpatch.status === \"blocked_by_policy\" ||\n\t\t\tpatch.status === \"reconciliation_required\" ||\n\t\t\tpatch.status === \"validation_failed\"\n\t\t) {\n\t\t\tdelete record.leaseOwner;\n\t\t\tdelete record.leaseExpiresAt;\n\t\t}\n\t}\n\n\tasync recordHitlDecision(\n\t\tactionInvocationId: string,\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t\tdecision: HitlDecisionEvidence,\n\t): Promise<ActionInvocationRecord> {\n\t\tconst record = await this.getActionInvocation(actionInvocationId, tenantId, spaceId);\n\t\tif (!record) throw new Error(`ActionInvocation not found: ${actionInvocationId}`);\n\t\trecord.hitlRoute = decision.route;\n\t\trecord.hitlRiskTier = decision.riskTier;\n\t\trecord.hitlReason = decision.reason;\n\t\tif (decision.policyVersion) record.hitlPolicyVersion = decision.policyVersion;\n\t\trecord.updatedAt = decision.evaluatedAt;\n\t\treturn record;\n\t}\n\n\tasync beginApprovalDecision(\n\t\tinput: BeginApprovalDecisionInput,\n\t): Promise<ApprovalDecisionTransitionResult> {\n\t\tconst record = await this.getActionInvocation(\n\t\t\tinput.actionInvocationId,\n\t\t\tinput.tenantId,\n\t\t\tinput.spaceId,\n\t\t);\n\t\tif (!record || record.status !== \"waiting_for_approval\") {\n\t\t\treturn { applied: false, ...(record ? { invocation: record } : {}) };\n\t\t}\n\t\trecord.approvalDecision = input.decision;\n\t\trecord.updatedAt = input.now;\n\t\tif (!input.decision.approved) {\n\t\t\trecord.status = \"failed\";\n\t\t\trecord.error = `Approval rejected: ${input.decision.reason ?? \"no reason provided\"}`;\n\t\t\tdelete record.leaseOwner;\n\t\t\tdelete record.leaseExpiresAt;\n\t\t\treturn { applied: true, invocation: record };\n\t\t}\n\t\trecord.status = \"running\";\n\t\trecord.error = undefined;\n\t\trecord.leaseOwner = input.leaseOwner;\n\t\trecord.leaseExpiresAt = new Date(input.now.getTime() + input.leaseDurationMs);\n\t\trecord.leaseToken = (record.leaseToken ?? 0) + 1;\n\t\trecord.attemptCount = Math.max(record.attemptCount, 1);\n\t\treturn { applied: true, invocation: record };\n\t}\n\n\tasync appendPolicyEvaluation(record: PolicyEvaluationRecord): Promise<void> {\n\t\tif (this.policyEvaluations.some((candidate) => candidate.id === record.id)) return;\n\t\tthis.policyEvaluations.push(record);\n\t}\n\n\tasync recordMutationGovernance(\n\t\tactionInvocationId: string,\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t\tcontext: Pick<ActionInvocationRecord, \"mutationFootprint\" | \"executionPrincipal\"> & {\n\t\t\tfootprint: NonNullable<ActionInvocationRecord[\"mutationFootprint\"]>;\n\t\t\texecutionPrincipal: NonNullable<ActionInvocationRecord[\"executionPrincipal\"]>;\n\t\t},\n\t): Promise<ActionInvocationRecord> {\n\t\tconst record = await this.getActionInvocation(actionInvocationId, tenantId, spaceId);\n\t\tif (!record) throw new Error(`ActionInvocation not found: ${actionInvocationId}`);\n\t\trecord.mutationFootprint = context.footprint;\n\t\trecord.executionPrincipal = context.executionPrincipal;\n\t\trecord.updatedAt = new Date();\n\t\treturn record;\n\t}\n\n\tasync appendPolicyObligations(records: PolicyObligationRecord[]): Promise<void> {\n\t\tfor (const record of records) {\n\t\t\tif (!this.policyObligations.some((candidate) => candidate.actionInvocationId === record.actionInvocationId && candidate.id === record.id)) {\n\t\t\t\tthis.policyObligations.push(record);\n\t\t\t}\n\t\t}\n\t}\n\n\tasync listPolicyObligations(actionInvocationId: string, tenantId: string, spaceId: string) {\n\t\treturn this.policyObligations.filter((record) => record.actionInvocationId === actionInvocationId && record.tenantId === tenantId && record.spaceId === spaceId);\n\t}\n\n\tasync updatePolicyObligation(actionInvocationId: string, obligationId: string, status: PolicyObligationRecord[\"status\"], evidenceReferences?: PolicyObligationRecord[\"evidenceReferences\"]): Promise<void> {\n\t\tconst record = this.policyObligations.find((candidate) => candidate.actionInvocationId === actionInvocationId && candidate.id === obligationId);\n\t\tif (!record) throw new Error(`Policy obligation not found: ${obligationId}`);\n\t\trecord.status = status;\n\t\tif (evidenceReferences) record.evidenceReferences = evidenceReferences;\n\t\trecord.updatedAt = new Date();\n\t}\n\n\tasync appendExecutionAttestation(record: ExecutionAttestationRecord): Promise<void> {\n\t\tif (!this.executionAttestations.some((candidate) => candidate.id === record.id)) this.executionAttestations.push(record);\n\t}\n\n\tasync listExecutionAttestations(actionInvocationId: string, tenantId: string, spaceId: string) {\n\t\treturn this.executionAttestations.filter((record) => record.actionInvocationId === actionInvocationId && record.tenantId === tenantId && record.spaceId === spaceId);\n\t}\n\n\tasync appendExternalReconciliation(record: ExternalReconciliationRecord): Promise<void> {\n\t\tif (!this.externalReconciliations.some((candidate) => candidate.id === record.id)) this.externalReconciliations.push(record);\n\t}\n\n\tprivate adapterWriteMatches(input: AdapterInvocationWriteInput): boolean {\n\t\tconst { scope, condition, mutation } = input;\n\t\tif (condition.kind === \"verdict\" && [\"pending\", \"running\", \"waiting_for_approval\"].includes(condition.status)) return false;\n\t\tconst parent = this.invocations.find(row => row.id === scope.actionInvocationId && row.tenantId === scope.tenantId && row.spaceId === scope.spaceId);\n\t\tif (!parent || (condition.kind === \"lease\"\n\t\t\t? parent.status !== \"running\" || parent.leaseOwner !== condition.leaseOwner || parent.leaseToken !== condition.leaseToken\n\t\t\t: !matchesSettledInvocation(parent, condition,\n\t\t\t\tcondition.completionAdapterInvocationId === undefined\n\t\t\t\t|| condition.completionAdapterInvocationId === (mutation.kind === \"create\" ? mutation.record.id : mutation.id)))) return false;\n\t\tif (mutation.kind === \"create\") {\n\t\t\tconst row = mutation.record;\n\t\t\treturn row.tenantId === scope.tenantId && row.spaceId === scope.spaceId && row.actionInvocationId === scope.actionInvocationId\n\t\t\t\t&& !this.adapterInvocations.some(existing => existing.id === row.id);\n\t\t}\n\t\tconst row = this.adapterInvocations.find(row => row.id === mutation.id && row.tenantId === scope.tenantId && row.spaceId === scope.spaceId && row.actionInvocationId === scope.actionInvocationId);\n\t\treturn !!row && (!input.expectedStatuses || input.expectedStatuses.includes(row.status))\n\t\t\t&& !((row.status === \"succeeded\" || row.status === \"ambiguous\") && (mutation.patch.status === \"running\" || mutation.patch.status === \"failed\"));\n\t}\n\n\tasync updateSettledActionInvocation(input: import(\"./types\").UpdateSettledActionInvocationInput): Promise<boolean> {\n\t\twhile (this.adapterCommit) await this.adapterCommit;\n\t\tconst record = this.invocations.find(row => row.id === input.id && row.tenantId === input.tenantId && row.spaceId === input.spaceId);\n\t\tif (!record || !matchesSettledInvocation(record, input.condition)) return false;\n\t\t// No await between the verdict/completion comparison and its annotation.\n\t\tObject.assign(record, {\n\t\t\t...(Object.hasOwn(input.patch, \"error\") ? { error: input.patch.error } : {}),\n\t\t\t...(Object.hasOwn(input.patch, \"adapterReconciliation\") ? { adapterReconciliation: structuredClone(input.patch.adapterReconciliation) } : {}),\n\t\t\tupdatedAt: new Date(),\n\t\t});\n\t\tif (Object.hasOwn(input.patch, \"error\") && input.patch.error === undefined) delete record.error;\n\t\treturn true;\n\t}\n\n\tasync writeAdapterInvocation(input: AdapterInvocationWriteInput): Promise<boolean> {\n\t\twhile (this.adapterCommit) await this.adapterCommit;\n\t\t// No await between checking authority/status and applying the mutation.\n\t\tif (!this.adapterWriteMatches(input)) return false;\n\t\tif (input.mutation.kind === \"create\") this.adapterInvocations.push(structuredClone(input.mutation.record));\n\t\telse {\n\t\t\tconst { id, patch } = input.mutation;\n\t\t\tObject.assign(this.adapterInvocations.find(row => row.id === id)!, structuredClone(patch));\n\t\t}\n\t\treturn true;\n\t}\n\n\tasync createAdapterInvocation(record: AdapterInvocationRecord): Promise<void> {\n\t\tif (this.adapterInvocations.some((candidate) => candidate.id === record.id)) return;\n\t\tthis.adapterInvocations.push(record);\n\t}\n\n\tasync getAdapterInvocation(id: string, scope?: AdapterInvocationScope): Promise<AdapterInvocationRecord | undefined> {\n\t\treturn this.adapterInvocations.find((candidate) => candidate.id === id\n\t\t\t&& (scope === undefined || (candidate.tenantId === scope.tenantId\n\t\t\t\t&& candidate.spaceId === scope.spaceId && candidate.actionInvocationId === scope.actionInvocationId)));\n\t}\n\n\tasync updateAdapterInvocation(\n\t\tid: string,\n\t\tpatch: Partial<\n\t\t\tPick<AdapterInvocationRecord, \"status\" | \"output\" | \"error\" | \"attempt\" | \"updatedAt\" | \"reconciliation\">\n\t\t>,\n\t\tscope?: AdapterInvocationScope,\n\t): Promise<void> {\n\t\tconst record = this.adapterInvocations.find((candidate) => candidate.id === id\n\t\t\t&& (scope === undefined || (candidate.tenantId === scope.tenantId\n\t\t\t\t&& candidate.spaceId === scope.spaceId && candidate.actionInvocationId === scope.actionInvocationId)));\n\t\tif (!record) throw new Error(`AdapterInvocation not found: ${id}`);\n\t\tObject.assign(record, patch);\n\t}\n\n\tasync appendEvent(event: AssetEventEnvelope): Promise<void> {\n\t\tif (this.events.some((candidate) => candidate.id === event.id)) return;\n\t\tthis.events.push(event);\n\t}\n\n\tasync appendEventWithOutbox(event: AssetEventEnvelope, metadata: OutboxEventMetadata): Promise<void> {\n\t\tif (this.events.some((candidate) => candidate.id === event.id)) return;\n\t\tconst createdAt = new Date(event.recordedAt);\n\t\tthis.events.push(event);\n\t\tthis.outbox.push({\n\t\t\tid: event.id,\n\t\t\ttenantId: event.tenantId,\n\t\t\tspaceId: event.spaceId,\n\t\t\tevent: toEnterpriseEventEnvelope(event, metadata),\n\t\t\tactorDisclosure: outboxActorDisclosure(metadata),\n\t\t\tstatus: \"pending\",\n\t\t\tattemptCount: 0,\n\t\t\tavailableAt: createdAt,\n\t\t\tcreatedAt,\n\t\t});\n\t}\n\n\tasync claimOutbox(input: ClaimOutboxInput): Promise<OutboxRecord[]> {\n\t\tconst current = input.now ?? new Date();\n\t\treturn this.outbox\n\t\t\t.filter((record) => record.status === \"pending\" && record.availableAt <= current && (!record.leaseExpiresAt || record.leaseExpiresAt <= current) && (!input.tenantId || record.tenantId === input.tenantId) && (!input.spaceId || record.spaceId === input.spaceId))\n\t\t\t.sort((left, right) => left.createdAt.getTime() - right.createdAt.getTime() || left.id.localeCompare(right.id))\n\t\t\t.slice(0, Math.max(1, Math.min(input.limit ?? 100, 1_000)))\n\t\t\t.map((record) => {\n\t\t\t\trecord.leaseOwner = input.workerId;\n\t\t\t\trecord.leaseExpiresAt = new Date(current.getTime() + input.leaseDurationMs);\n\t\t\t\trecord.leaseToken = (record.leaseToken ?? 0) + 1;\n\t\t\t\trecord.attemptCount += 1;\n\t\t\t\treturn cloneOutboxRecord(record);\n\t\t\t});\n\t}\n\n\tasync markOutboxPublished(id: string, workerId: string, publishedAt: Date, leaseToken?: number): Promise<void> {\n\t\tconst record = this.requireLeasedOutbox(id, workerId, leaseToken);\n\t\trecord.status = \"published\";\n\t\trecord.publishedAt = publishedAt;\n\t\tdelete record.leaseOwner;\n\t\tdelete record.leaseExpiresAt;\n\t}\n\n\tasync markOutboxFailed(input: { id: string; workerId: string; leaseToken?: number; error: string; availableAt: Date; deadLetter: boolean }): Promise<void> {\n\t\tconst record = this.requireLeasedOutbox(input.id, input.workerId, input.leaseToken);\n\t\trecord.status = input.deadLetter ? \"dead_letter\" : \"pending\";\n\t\trecord.lastError = input.error;\n\t\trecord.availableAt = input.availableAt;\n\t\tdelete record.leaseOwner;\n\t\tdelete record.leaseExpiresAt;\n\t}\n\n\tasync renewOutboxLease(input: { id: string; workerId: string; leaseToken: number; leaseDurationMs: number; now?: Date }): Promise<boolean> {\n\t\tconst record = this.outbox.find((candidate) => candidate.id === input.id);\n\t\tconst current = input.now ?? new Date();\n\t\tif (!record || record.status !== \"pending\" || record.leaseOwner !== input.workerId ||\n\t\t\trecord.leaseToken !== input.leaseToken || !record.leaseExpiresAt ||\n\t\t\trecord.leaseExpiresAt <= current) return false;\n\t\trecord.leaseExpiresAt = new Date(current.getTime() + input.leaseDurationMs);\n\t\treturn true;\n\t}\n\n\tasync listOutbox(input: { tenantId?: string; spaceId?: string; statuses?: OutboxStatus[] } = {}): Promise<OutboxRecord[]> {\n\t\treturn this.outbox.filter((record) => (!input.tenantId || record.tenantId === input.tenantId) && (!input.spaceId || record.spaceId === input.spaceId) && (!input.statuses?.length || input.statuses.includes(record.status))).map(cloneOutboxRecord);\n\t}\n\n\tasync getOutboxRecord(id: string, tenantId: string, spaceId: string): Promise<OutboxRecord | undefined> {\n\t\tconst record = this.outbox.find((candidate) => candidate.id === id && candidate.tenantId === tenantId && candidate.spaceId === spaceId);\n\t\treturn record ? cloneOutboxRecord(record) : undefined;\n\t}\n\n\tasync requeueOutboxDeadLetter(input: RequeueOutboxDeadLetterStoreInput): Promise<RequeueOutboxDeadLetterStoreResult> {\n\t\t// No await between the check and the writes, so the compare-and-set and\n\t\t// its evidence are one step for every other caller of this store.\n\t\tconst record = this.outbox.find((candidate) => candidate.id === input.id && candidate.tenantId === input.tenantId && candidate.spaceId === input.spaceId);\n\t\tif (!record) return { applied: false, refusal: \"not_found\" };\n\t\tif (record.status !== \"dead_letter\") return { applied: false, refusal: \"not_dead_letter\", currentStatus: record.status };\n\t\tif ((record.leaseToken ?? 0) !== input.expectedLeaseToken) return { applied: false, refusal: \"stale\", currentStatus: record.status };\n\t\tconst requeue: OutboxRequeueRecord = {\n\t\t\tid: input.requeueId,\n\t\t\toutboxId: record.id,\n\t\t\ttenantId: record.tenantId,\n\t\t\tspaceId: record.spaceId,\n\t\t\teventId: record.event.eventId,\n\t\t\tactorId: input.actorId,\n\t\t\tactorType: input.actorType,\n\t\t\treason: input.reason,\n\t\t\trequeuedAt: new Date(input.requeuedAt),\n\t\t\tavailableAt: new Date(input.availableAt),\n\t\t\tpriorAttemptCount: record.attemptCount,\n\t\t\t...(record.lastError !== undefined ? { priorLastError: record.lastError } : {}),\n\t\t\tpriorAvailableAt: new Date(record.availableAt),\n\t\t\tpriorLeaseToken: record.leaseToken ?? 0,\n\t\t};\n\t\trecord.status = \"pending\";\n\t\trecord.attemptCount = 0;\n\t\trecord.availableAt = new Date(input.availableAt);\n\t\tdelete record.leaseOwner;\n\t\tdelete record.leaseExpiresAt;\n\t\tthis.outboxRequeues.push(requeue);\n\t\treturn { applied: true, record: cloneOutboxRecord(record), requeue: cloneOutboxRequeue(requeue) };\n\t}\n\n\tasync listOutboxRequeues(input: { tenantId: string; spaceId: string; outboxId?: string }): Promise<OutboxRequeueRecord[]> {\n\t\treturn this.outboxRequeues\n\t\t\t.filter((requeue) => requeue.tenantId === input.tenantId && requeue.spaceId === input.spaceId && (input.outboxId === undefined || requeue.outboxId === input.outboxId))\n\t\t\t.sort((left, right) => left.requeuedAt.getTime() - right.requeuedAt.getTime() || left.id.localeCompare(right.id))\n\t\t\t.map(cloneOutboxRequeue);\n\t}\n\n\tprivate requireLeasedOutbox(id: string, workerId: string, leaseToken?: number): OutboxRecord {\n\t\tconst record = this.outbox.find((candidate) => candidate.id === id);\n\t\tif (!record || record.leaseOwner !== workerId ||\n\t\t\t(record.leaseToken ?? 0) !== (leaseToken ?? 0)) {\n\t\t\tthrow new Error(`Outbox record ${id} is not leased by ${workerId}.`);\n\t\t}\n\t\treturn record;\n\t}\n\n\tasync nextEventSequence(tenantId: string, spaceId: string): Promise<number> {\n\t\treturn (\n\t\t\tthis.events.filter((event) => event.tenantId === tenantId && event.spaceId === spaceId)\n\t\t\t\t.length + 1\n\t\t);\n\t}\n\n\tasync getEntityStateSource(\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t\tentityType: string,\n\t\tentityId: string,\n\t): Promise<{ state: string; actionInvocationId: string } | undefined> {\n\t\tlet source: { state: string; actionInvocationId: string } | undefined;\n\t\tfor (const event of this.events) {\n\t\t\tif (event.tenantId !== tenantId || event.spaceId !== spaceId ||\n\t\t\t\tevent.subjectType !== entityType || event.subjectId !== entityId) continue;\n\t\t\tconst state = (event.payload as { toState?: unknown } | undefined)?.toState;\n\t\t\tif (typeof state === \"string\") source = typeof event.actionInvocationId === \"string\"\n\t\t\t\t? { state, actionInvocationId: event.actionInvocationId } : undefined;\n\t\t}\n\t\treturn source;\n\t}\n\n\tasync getEntityState(\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t\tentityType: string,\n\t\tentityId: string,\n\t): Promise<string | undefined> {\n\t\tlet state: string | undefined;\n\t\tfor (const event of this.events) {\n\t\t\tif (\n\t\t\t\tevent.tenantId !== tenantId ||\n\t\t\t\tevent.spaceId !== spaceId ||\n\t\t\t\tevent.subjectType !== entityType ||\n\t\t\t\tevent.subjectId !== entityId\n\t\t\t) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst candidate = (event.payload as { toState?: unknown } | undefined)?.toState;\n\t\t\tif (typeof candidate === \"string\") state = candidate;\n\t\t}\n\t\treturn state;\n\t}\n\n\tasync listActionInvocations(\n\t\tinput: ListActionInvocationsInput = {},\n\t): Promise<ActionInvocationRecord[]> {\n\t\treturn this.invocations\n\t\t\t.filter(\n\t\t\t\t(record) =>\n\t\t\t\t\t(!input.tenantId || record.tenantId === input.tenantId) &&\n\t\t\t\t\t(!input.spaceId || record.spaceId === input.spaceId) &&\n\t\t\t\t\t(!input.statuses?.length || input.statuses.includes(record.status)) &&\n\t\t\t\t\t(!input.updatedBefore || record.updatedAt < input.updatedBefore) &&\n\t\t\t\t\t(!(input.awaitingCompletion || input.completionDueBefore) || record.pendingCompletion !== undefined) &&\n\t\t\t\t\t(!input.completionDueBefore || (record.pendingCompletion?.dueAt !== undefined && record.pendingCompletion.dueAt <= input.completionDueBefore)) &&\n\t\t\t\t\t(!input.unleased || record.leaseOwner === undefined),\n\t\t\t)\n\t\t\t.sort((left, right) => left.createdAt.getTime() - right.createdAt.getTime())\n\t\t\t.slice(0, input.limit ?? 100);\n\t}\n\n\tasync getHealthCounts(input: PlatformHostHealthQuery): Promise<PlatformHostHealthCounts> {\n\t\tconst invocations = this.invocations.filter(\n\t\t\t(record) =>\n\t\t\t\t(!input.tenantId || record.tenantId === input.tenantId) &&\n\t\t\t\t(!input.spaceId || record.spaceId === input.spaceId),\n\t\t);\n\t\tconst outbox = this.outbox.filter(\n\t\t\t(record) =>\n\t\t\t\t(!input.tenantId || record.tenantId === input.tenantId) &&\n\t\t\t\t(!input.spaceId || record.spaceId === input.spaceId),\n\t\t);\n\t\treturn {\n\t\t\tinvocationBacklog: invocations.filter((item) => item.status === \"pending\").length,\n\t\t\tinvocationRunning: invocations.filter((item) => item.status === \"running\").length,\n\t\t\tinvocationExpiredLeases: invocations.filter((item) =>\n\t\t\t\titem.status === \"running\" &&\n\t\t\t\titem.leaseExpiresAt !== undefined &&\n\t\t\t\titem.leaseExpiresAt.getTime() <= input.now.getTime(),\n\t\t\t).length,\n\t\t\tinvocationApprovalWaits: invocations.filter((item) => item.status === \"waiting_for_approval\").length,\n\t\t\tinvocationReconciliationRequired: invocations.filter((item) => item.status === \"reconciliation_required\").length,\n\t\t\toutboxBacklog: outbox.filter((item) => item.status === \"pending\").length,\n\t\t\toutboxExpiredLeases: outbox.filter((item) =>\n\t\t\t\titem.status === \"pending\" &&\n\t\t\t\titem.leaseExpiresAt !== undefined &&\n\t\t\t\titem.leaseExpiresAt.getTime() <= input.now.getTime(),\n\t\t\t).length,\n\t\t\toutboxDeadLetters: outbox.filter((item) => item.status === \"dead_letter\").length,\n\t\t};\n\t}\n\n\tasync claimActionInvocations(\n\t\tinput: ClaimActionInvocationsInput,\n\t): Promise<ActionInvocationRecord[]> {\n\t\twhile (this.adapterCommit) await this.adapterCommit;\n\t\tconst current = input.now ?? new Date();\n\t\tconst eligible = this.invocations\n\t\t\t.filter(\n\t\t\t\t(record) =>\n\t\t\t\t\t(!input.tenantId || record.tenantId === input.tenantId) &&\n\t\t\t\t\t(!input.spaceId || record.spaceId === input.spaceId) &&\n\t\t\t\t\t(record.status === \"pending\" ||\n\t\t\t\t\t\t(record.status === \"running\" &&\n\t\t\t\t\t\t\trecord.leaseExpiresAt !== undefined &&\n\t\t\t\t\t\t\trecord.leaseExpiresAt <= current)),\n\t\t\t)\n\t\t\t.sort((left, right) => left.createdAt.getTime() - right.createdAt.getTime())\n\t\t\t.slice(0, input.limit ?? 10);\n\t\tfor (const record of eligible) {\n\t\t\trecord.status = \"running\";\n\t\t\trecord.leaseOwner = input.workerId;\n\t\t\trecord.leaseExpiresAt = new Date(current.getTime() + input.leaseDurationMs);\n\t\t\trecord.leaseToken = (record.leaseToken ?? 0) + 1;\n\t\t\trecord.attemptCount += 1;\n\t\t\trecord.updatedAt = current;\n\t\t}\n\t\treturn eligible.map((record) => structuredClone(record));\n\t}\n\n\tasync updateLeasedActionInvocation(input: import(\"./types\").UpdateLeasedActionInvocationInput): Promise<boolean> {\n\t\twhile (this.adapterCommit) await this.adapterCommit;\n\t\tconst record = this.invocations.find(row => row.id === input.id && row.tenantId === input.tenantId && row.spaceId === input.spaceId);\n\t\tif (!record || record.status !== \"running\" || record.leaseOwner !== input.workerId ||\n\t\t\trecord.leaseToken !== input.leaseToken) return false;\n\t\tawait this.updateActionInvocation(input.id, input.tenantId, input.spaceId, input.patch);\n\t\treturn true;\n\t}\n\n\tasync renewActionInvocationLease(input: import(\"./types\").RenewActionInvocationLeaseInput): Promise<boolean> {\n\t\tconst record = await this.getActionInvocation(input.id, input.tenantId, input.spaceId);\n\t\tconst current = input.now ?? new Date();\n\t\tif (!record || record.status !== \"running\" || record.leaseOwner !== input.workerId ||\n\t\t\trecord.leaseToken !== input.leaseToken || !record.leaseExpiresAt ||\n\t\t\trecord.leaseExpiresAt <= current) return false;\n\t\trecord.leaseExpiresAt = new Date(current.getTime() + input.leaseDurationMs);\n\t\trecord.updatedAt = current;\n\t\treturn true;\n\t}\n\n\tasync listEvents(tenantId: string, spaceId: string): Promise<AssetEventEnvelope[]> {\n\t\treturn this.events\n\t\t\t.filter((event) => event.tenantId === tenantId && event.spaceId === spaceId)\n\t\t\t.sort((left, right) => left.sequence - right.sequence);\n\t}\n}\n\nfunction cloneOutboxRequeue(requeue: OutboxRequeueRecord): OutboxRequeueRecord {\n\treturn {\n\t\t...requeue,\n\t\trequeuedAt: new Date(requeue.requeuedAt),\n\t\tavailableAt: new Date(requeue.availableAt),\n\t\tpriorAvailableAt: new Date(requeue.priorAvailableAt),\n\t};\n}\n\nfunction copyInvocationPatch(patch: ActionInvocationPatch): ActionInvocationPatch {\n\treturn { ...patch, ...(patch.pendingStateTransition ? { pendingStateTransition: { ...patch.pendingStateTransition } } : {}) };\n}\n\nfunction leaseWriteLost(id: string): Error {\n\treturn new RecoverableFinalizationError(`Invocation lease or adapter condition lost at commit: ${id}`);\n}\n","import { createHash } from \"node:crypto\";\nimport type { PlatformHostSqlClient } from \"./postgres-store\";\n\nexport interface PostgresMigration {\n\tversion: number;\n\tname: string;\n\tsql: string;\n}\n\n/**\n * Applies an immutable, ordered migration set in one PostgreSQL transaction.\n *\n * The transaction-scoped advisory lock serializes migrators. A previously\n * applied version may be presented again only when its checksum is unchanged.\n */\nexport async function applyPostgresMigrations(\n\tclient: PlatformHostSqlClient,\n\tmigrations: readonly PostgresMigration[],\n): Promise<void> {\n\tconst ordered = validateMigrations(migrations);\n\tconst statements = ordered.map((migration) => migrationStatement(migration));\n\n\tawait client.query(`\n\t\tBEGIN;\n\t\tSELECT pg_advisory_xact_lock(hashtext('fabric_platform.schema_migrations'));\n\t\tCREATE SCHEMA IF NOT EXISTS fabric_platform;\n\t\tCREATE TABLE IF NOT EXISTS fabric_platform.schema_migrations (\n\t\t\tversion integer PRIMARY KEY,\n\t\t\tname text NOT NULL,\n\t\t\tchecksum text NOT NULL,\n\t\t\tapplied_at timestamptz NOT NULL DEFAULT now()\n\t\t);\n\t\t${statements.join(\"\\n\")}\n\t\tCOMMIT;\n\t`);\n}\n\nfunction validateMigrations(\n\tmigrations: readonly PostgresMigration[],\n): PostgresMigration[] {\n\tconst ordered = [...migrations].sort((left, right) => left.version - right.version);\n\tconst versions = new Set<number>();\n\n\tfor (const migration of ordered) {\n\t\tif (!Number.isSafeInteger(migration.version) || migration.version < 1) {\n\t\t\tthrow new Error(`Migration version must be a positive safe integer: ${migration.version}`);\n\t\t}\n\t\tif (versions.has(migration.version)) {\n\t\t\tthrow new Error(`Duplicate migration version: ${migration.version}`);\n\t\t}\n\t\tif (!/^[a-z][a-z0-9_]*$/.test(migration.name)) {\n\t\t\tthrow new Error(`Invalid migration name: ${migration.name}`);\n\t\t}\n\t\tif (migration.sql.trim().length === 0) {\n\t\t\tthrow new Error(`Migration ${migration.version} has no SQL`);\n\t\t}\n\t\tversions.add(migration.version);\n\t}\n\n\treturn ordered;\n}\n\nfunction migrationStatement(migration: PostgresMigration): string {\n\tconst checksum = createHash(\"sha256\").update(migration.sql).digest(\"hex\");\n\tconst delimiter = `$fabric_platform_migration_${migration.version}$`;\n\tif (migration.sql.includes(delimiter)) {\n\t\tthrow new Error(`Migration ${migration.version} contains its reserved SQL delimiter`);\n\t}\n\n\treturn `\n\t\tDO ${delimiter}\n\t\tDECLARE\n\t\t\trecorded_checksum text;\n\t\tBEGIN\n\t\t\tSELECT checksum INTO recorded_checksum\n\t\t\tFROM fabric_platform.schema_migrations\n\t\t\tWHERE version = ${migration.version};\n\n\t\t\tIF FOUND THEN\n\t\t\t\tIF recorded_checksum <> ${sqlLiteral(checksum)} THEN\n\t\t\t\t\tRAISE EXCEPTION 'Migration checksum mismatch for version ${migration.version}';\n\t\t\t\tEND IF;\n\t\t\tELSE\n\t\t\t\t${migration.sql}\n\t\t\t\tINSERT INTO fabric_platform.schema_migrations (version, name, checksum)\n\t\t\t\tVALUES (${migration.version}, ${sqlLiteral(migration.name)}, ${sqlLiteral(checksum)});\n\t\t\tEND IF;\n\t\tEND\n\t\t${delimiter};`;\n}\n\nfunction sqlLiteral(value: string): string {\n\treturn `'${value.replaceAll(\"'\", \"''\")}'`;\n}\n","import type { AssetEventEnvelope } from \"@fabricorg/platform\";\nimport type {\n\tActionInvocationPatch,\n\tApprovalDecisionTransitionResult,\n\tApprovalPlatformHostStore,\n\tActionInvocationRecord,\n\tAdapterInvocationRecord,\n\tAdapterInvocationScope,\n\tAdapterInvocationWriteInput,\n\tAtomicMutationPlatformHostStore,\n\tBeginApprovalDecisionInput,\n\tClaimActionInvocationsInput,\n\tCreateActionInvocationInput,\n\tHitlDecisionEvidence,\n\tGovernancePlatformHostStore,\n\tPolicyObligationRecord,\n\tExecutionAttestationRecord,\n\tExternalReconciliationRecord,\n\tListActionInvocationsInput,\n\tPolicyEvaluationRecord,\n\tPlatformHostMutationTransaction,\n\tRecoverablePlatformHostStore,\n\tOutboxPlatformHostStore,\n\tOutboxEventMetadata,\n\tOutboxRecord,\n\tOutboxRequeuePlatformHostStore,\n\tOutboxRequeueRecord,\n\tRequeueOutboxDeadLetterStoreInput,\n\tRequeueOutboxDeadLetterStoreResult,\n\tClaimOutboxInput,\n\tOutboxStatus,\n\tEnterpriseEventEnvelope,\n} from \"./types\";\nimport { outboxActorDisclosure, toEnterpriseEventEnvelope } from \"./outbox\";\nimport { applyPostgresMigrations } from \"./postgres-migrations\";\nimport type { PlatformHostHealthCounts, PlatformHostHealthQuery } from \"./observability\";\n\nexport interface PlatformHostSqlResult<Row = Record<string, unknown>> {\n\trows: Row[];\n}\n\n/** Structural subset implemented by `pg.Pool` and Lakebase-compatible clients. */\nexport interface PlatformHostSqlClient {\n\tquery<Row = Record<string, unknown>>(\n\t\tsql: string,\n\t\tvalues?: unknown[],\n\t): Promise<PlatformHostSqlResult<Row>>;\n}\n\nexport interface PostgresPlatformHostTransactionContext<TDb> {\n\tdb: TDb;\n\tsql: PlatformHostSqlClient;\n}\n\n/**\n * Application-owned transaction binder.\n *\n * Platform Host cannot infer how an application's `TDb` is rebound to a\n * `pg.PoolClient`. Production applications provide this adapter so domain\n * methods and Host ledger writes share one PostgreSQL transaction.\n */\nexport interface PostgresPlatformHostTransactionProvider<TDb> {\n\trun<TResult>(\n\t\trun: (context: PostgresPlatformHostTransactionContext<TDb>) => Promise<TResult>,\n\t): Promise<TResult>;\n}\n\n/** Durable mutation-pipeline ledger for Databricks Lakebase or standard Postgres. */\nexport class PostgresPlatformHostStore<TDb>\n\timplements RecoverablePlatformHostStore<TDb>, ApprovalPlatformHostStore<TDb>, GovernancePlatformHostStore<TDb>, OutboxPlatformHostStore<TDb>, OutboxRequeuePlatformHostStore<TDb> {\n\treadonly transactionWithEvents?: AtomicMutationPlatformHostStore<TDb>[\"transactionWithEvents\"];\n\treadonly transactionalOutbox: boolean;\n\n\tconstructor(\n\t\treadonly db: TDb,\n\t\tprivate readonly sql: PlatformHostSqlClient,\n\t\ttransactionProvider?: PostgresPlatformHostTransactionProvider<TDb>,\n\t) {\n\t\tthis.transactionalOutbox = transactionProvider !== undefined;\n\t\tif (transactionProvider) {\n\t\t\tthis.transactionWithEvents = async <TResult>(\n\t\t\t\trun: (transaction: PlatformHostMutationTransaction<TDb>) => Promise<TResult>,\n\t\t\t): Promise<TResult> =>\n\t\t\t\ttransactionProvider.run(async ({ db, sql }) => {\n\t\t\t\t\tconst scoped = new PostgresPlatformHostStore(db, sql);\n\t\t\t\t\treturn run({\n\t\t\t\t\t\tdb,\n\t\t\t\t\t\tgetActionInvocationForUpdate: async (id, tenantId, spaceId) => {\n\t\t\t\t\t\t\tconst result = await sql.query<Record<string, unknown>>(\n\t\t\t\t\t\t\t\t`SELECT * FROM fabric_platform.action_invocations\n\t\t\t\t\t\t\t\t WHERE id=$1 AND tenant_id=$2 AND space_id=$3\n\t\t\t\t\t\t\t\t FOR UPDATE`,\n\t\t\t\t\t\t\t\t[id, tenantId, spaceId],\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\treturn result.rows[0] ? toActionRecord(result.rows[0]) : undefined;\n\t\t\t\t\t\t},\n\t\t\t\t\t\tgetEvent: (id, tenantId, spaceId) =>\n\t\t\t\t\t\t\tscoped.getEvent(id, tenantId, spaceId),\n\t\t\t\t\t\tappendEvent: (event) => scoped.appendEvent(event),\n\t\t\t\t\t\tappendEventWithOutbox: (event, metadata) => scoped.appendEventWithOutbox(event, metadata),\n\t\t\t\t\t\tnextEventSequence: (tenantId, spaceId) =>\n\t\t\t\t\t\t\tscoped.nextEventSequence(tenantId, spaceId),\n\t\t\t\t\t\tlistEvents: (tenantId, spaceId) =>\n\t\t\t\t\t\t\tscoped.listEvents(tenantId, spaceId),\n\t\t\t\t\t\tgetEntityStateSource: (tenantId, spaceId, entityType, entityId) =>\n\t\t\t\t\t\t\tscoped.getEntityStateSource(tenantId, spaceId, entityType, entityId),\n\t\t\t\t\t\tgetEntityState: (tenantId, spaceId, entityType, entityId) =>\n\t\t\t\t\t\t\tscoped.getEntityState(tenantId, spaceId, entityType, entityId),\n\t\t\t\t\t\tupdateActionInvocation: (id, tenantId, spaceId, patch) =>\n\t\t\t\t\t\t\tscoped.updateActionInvocation(id, tenantId, spaceId, patch),\n\t\t\t\t\t\tupdateLeasedActionInvocation: (input) =>\n\t\t\t\t\t\t\tscoped.updateLeasedActionInvocation(input),\n\t\t\t\t\t\tupdateAdapterInvocation: (id, patch, scope) =>\n\t\t\t\t\t\t\tscoped.updateAdapterInvocation(id, patch, scope),\n\t\t\t\t\t\twriteAdapterInvocation: input => scoped.writeAdapterInvocation(input),\n\t\t\t\t\t\tappendExternalReconciliation: (record) =>\n\t\t\t\t\t\t\tscoped.appendExternalReconciliation(record),\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t}\n\t}\n\n\tasync ensureSchema(): Promise<void> {\n\t\tawait applyPostgresMigrations(this.sql, [{\n\t\t\tversion: 1,\n\t\t\tname: \"host_ledger_baseline\",\n\t\t\tsql: `\n\t\t\tCREATE SCHEMA IF NOT EXISTS fabric_platform;\n\t\t\tCREATE TABLE IF NOT EXISTS fabric_platform.action_invocations (\n\t\t\t\tid text PRIMARY KEY, tenant_id text NOT NULL, space_id text NOT NULL,\n\t\t\t\taction_id text NOT NULL, action_version integer NOT NULL,\n\t\t\t\tactor_id text NOT NULL, actor_type text NOT NULL, status text NOT NULL,\n\t\t\t\tparameters jsonb NOT NULL, result jsonb NOT NULL DEFAULT '{}'::jsonb,\n\t\t\t\tcorrelation_id text NOT NULL, causation_id text, idempotency_key text,\n\t\t\t\tparameter_digest text, parameter_digest_algorithm text, idempotency_actor_id text,\n\t\t\t\tidempotency_authorization_binding_id text, invocation_provenance jsonb,\n\t\t\t\tauthorization_binding jsonb, execution_reason text, authorization_reconciliation jsonb,\n\t\t\t\tadapter_reconciliation jsonb, authorization_binding_id text, error text,\n\t\t\t\tattempt_count integer NOT NULL DEFAULT 0, lease_owner text,\n\t\t\t\tlease_expires_at timestamptz, hitl_route text, hitl_risk_tier text,\n\t\t\t\thitl_reason text, hitl_policy_version text, approval_decision jsonb,\n\t\t\t\tmutation_footprint jsonb, execution_principal jsonb, runtime_evidence jsonb,\n\t\t\t\tcreated_at timestamptz NOT NULL, updated_at timestamptz NOT NULL\n\t\t\t);\n\t\t\tALTER TABLE fabric_platform.action_invocations\n\t\t\t\tADD COLUMN IF NOT EXISTS idempotency_key text,\n\t\t\t\tADD COLUMN IF NOT EXISTS parameter_digest text,\n\t\t\t\tADD COLUMN IF NOT EXISTS parameter_digest_algorithm text,\n\t\t\t\tADD COLUMN IF NOT EXISTS idempotency_actor_id text,\n\t\t\t\tADD COLUMN IF NOT EXISTS idempotency_authorization_binding_id text,\n\t\t\t\tADD COLUMN IF NOT EXISTS invocation_provenance jsonb,\n\t\t\t\tADD COLUMN IF NOT EXISTS authorization_binding jsonb,\n\t\t\t\tADD COLUMN IF NOT EXISTS execution_reason text,\n\t\t\t\tADD COLUMN IF NOT EXISTS authorization_reconciliation jsonb,\n\t\t\t\tADD COLUMN IF NOT EXISTS adapter_reconciliation jsonb,\n\t\t\t\tADD COLUMN IF NOT EXISTS authorization_binding_id text,\n\t\t\t\tADD COLUMN IF NOT EXISTS attempt_count integer NOT NULL DEFAULT 0,\n\t\t\t\tADD COLUMN IF NOT EXISTS lease_owner text,\n\t\t\t\tADD COLUMN IF NOT EXISTS lease_expires_at timestamptz,\n\t\t\t\tADD COLUMN IF NOT EXISTS hitl_route text,\n\t\t\t\tADD COLUMN IF NOT EXISTS hitl_risk_tier text,\n\t\t\t\tADD COLUMN IF NOT EXISTS hitl_reason text,\n\t\t\t\tADD COLUMN IF NOT EXISTS hitl_policy_version text,\n\t\t\t\tADD COLUMN IF NOT EXISTS approval_decision jsonb,\n\t\t\t\tADD COLUMN IF NOT EXISTS mutation_footprint jsonb,\n\t\t\t\tADD COLUMN IF NOT EXISTS execution_principal jsonb,\n\t\t\t\tADD COLUMN IF NOT EXISTS runtime_evidence jsonb;\n\t\t\tCREATE UNIQUE INDEX IF NOT EXISTS action_invocations_idempotency_idx\n\t\t\t\tON fabric_platform.action_invocations\n\t\t\t\t(tenant_id, space_id, action_id, idempotency_key)\n\t\t\t\tWHERE idempotency_key IS NOT NULL;\n\t\t\tCREATE INDEX IF NOT EXISTS action_invocations_parameter_digest_idx\n\t\t\t\tON fabric_platform.action_invocations (tenant_id, parameter_digest)\n\t\t\t\tWHERE parameter_digest IS NOT NULL;\n\t\t\tCREATE INDEX IF NOT EXISTS action_invocations_authority_binding_idx\n\t\t\t\tON fabric_platform.action_invocations (tenant_id, authorization_binding_id)\n\t\t\t\tWHERE authorization_binding_id IS NOT NULL;\n\t\t\tCREATE INDEX IF NOT EXISTS action_invocations_worker_idx\n\t\t\t\tON fabric_platform.action_invocations (status, lease_expires_at, created_at);\n\t\t\tCREATE TABLE IF NOT EXISTS fabric_platform.policy_evaluations (\n\t\t\t\tid text PRIMARY KEY, action_invocation_id text NOT NULL,\n\t\t\t\ttenant_id text NOT NULL, space_id text NOT NULL, outcome jsonb NOT NULL,\n\t\t\t\tcreated_at timestamptz NOT NULL\n\t\t\t);\n\t\t\tCREATE TABLE IF NOT EXISTS fabric_platform.adapter_invocations (\n\t\t\t\tid text PRIMARY KEY, action_invocation_id text NOT NULL,\n\t\t\t\ttenant_id text NOT NULL, space_id text NOT NULL, adapter_type text NOT NULL,\n\t\t\t\toperation text NOT NULL, vendor text NOT NULL, status text NOT NULL,\n\t\t\t\tinput jsonb NOT NULL, output jsonb, error text, attempt integer NOT NULL,\n\t\t\t\tcreated_at timestamptz NOT NULL, updated_at timestamptz NOT NULL\n\t\t\t);\n\t\t\tCREATE TABLE IF NOT EXISTS fabric_platform.policy_obligations (\n\t\t\t\taction_invocation_id text NOT NULL, id text NOT NULL,\n\t\t\t\ttenant_id text NOT NULL, space_id text NOT NULL, type text NOT NULL,\n\t\t\t\tstatus text NOT NULL, required boolean NOT NULL DEFAULT true,\n\t\t\t\tdescription text, evidence_references jsonb, metadata jsonb,\n\t\t\t\tcreated_at timestamptz NOT NULL, updated_at timestamptz NOT NULL,\n\t\t\t\tPRIMARY KEY (action_invocation_id,id)\n\t\t\t);\n\t\t\tCREATE TABLE IF NOT EXISTS fabric_platform.execution_attestations (\n\t\t\t\tid text PRIMARY KEY, action_invocation_id text NOT NULL,\n\t\t\t\ttenant_id text NOT NULL, space_id text NOT NULL, adapter_invocation_id text,\n\t\t\t\tattestation jsonb NOT NULL, recorded_at timestamptz NOT NULL\n\t\t\t);\n\t\t\tCREATE TABLE IF NOT EXISTS fabric_platform.external_reconciliations (\n\t\t\t\tid text PRIMARY KEY, action_invocation_id text NOT NULL,\n\t\t\t\ttenant_id text NOT NULL, space_id text NOT NULL,\n\t\t\t\treconciliation jsonb NOT NULL\n\t\t\t);\n\t\t\tCREATE TABLE IF NOT EXISTS fabric_platform.event_sequences (\n\t\t\t\ttenant_id text NOT NULL, space_id text NOT NULL, next_sequence bigint NOT NULL,\n\t\t\t\tPRIMARY KEY (tenant_id, space_id)\n\t\t\t);\n\t\t\tCREATE TABLE IF NOT EXISTS fabric_platform.asset_events (\n\t\t\t\tid text PRIMARY KEY, tenant_id text NOT NULL, space_id text NOT NULL,\n\t\t\t\tevent_type text NOT NULL, event_schema_version integer NOT NULL,\n\t\t\t\tsubject_type text NOT NULL, subject_id text NOT NULL,\n\t\t\t\tactor_id text NOT NULL, actor_type text NOT NULL, action_invocation_id text,\n\t\t\t\tpayload jsonb NOT NULL, sequence bigint NOT NULL,\n\t\t\t\toccurred_at timestamptz NOT NULL, recorded_at timestamptz NOT NULL,\n\t\t\t\tcorrelation_id text NOT NULL, causation_id text, provenance jsonb, consistency text,\n\t\t\t\tUNIQUE (tenant_id, space_id, sequence)\n\t\t\t);\n\t\t\tALTER TABLE fabric_platform.asset_events ADD COLUMN IF NOT EXISTS provenance jsonb;\n\t\t\tALTER TABLE fabric_platform.asset_events ADD COLUMN IF NOT EXISTS consistency text;\n\t\t\tCREATE INDEX IF NOT EXISTS asset_events_subject_idx\n\t\t\t\tON fabric_platform.asset_events\n\t\t\t\t(tenant_id, space_id, subject_type, subject_id, sequence);\n\t\t\tCREATE TABLE IF NOT EXISTS fabric_platform.event_outbox (\n\t\t\t\tid text PRIMARY KEY, tenant_id text NOT NULL, space_id text NOT NULL,\n\t\t\t\tevent jsonb NOT NULL, status text NOT NULL DEFAULT 'pending',\n\t\t\t\tattempt_count integer NOT NULL DEFAULT 0, available_at timestamptz NOT NULL,\n\t\t\t\tlease_owner text, lease_expires_at timestamptz, last_error text,\n\t\t\t\tcreated_at timestamptz NOT NULL, published_at timestamptz\n\t\t\t);\n\t\t\tCREATE INDEX IF NOT EXISTS event_outbox_claim_idx\n\t\t\t\tON fabric_platform.event_outbox (status, available_at, lease_expires_at, created_at);\n\t\t\t`,\n\t\t}, {\n\t\t\tversion: 2,\n\t\t\tname: \"lease_fencing\",\n\t\t\tsql: `\n\t\t\t\tALTER TABLE fabric_platform.action_invocations\n\t\t\t\t\tADD COLUMN lease_token bigint NOT NULL DEFAULT 0;\n\t\t\t\tALTER TABLE fabric_platform.event_outbox\n\t\t\t\t\tADD COLUMN lease_token bigint NOT NULL DEFAULT 0;\n\t\t\t`,\n\t\t}, {\n\t\t\tversion: 3,\n\t\t\tname: \"external_completion\",\n\t\t\tsql: `\n\t\t\t\tALTER TABLE fabric_platform.action_invocations\n\t\t\t\t\tADD COLUMN pending_completion jsonb,\n\t\t\t\t\tADD COLUMN external_completion jsonb,\n\t\t\t\t\tADD COLUMN completion_due_at timestamptz;\n\t\t\t\tCREATE INDEX action_invocations_completion_due_idx\n\t\t\t\t\tON fabric_platform.action_invocations (completion_due_at)\n\t\t\t\t\tWHERE completion_due_at IS NOT NULL;\n\t\t\t`,\n\t\t}, {\n\t\t\tversion: 4,\n\t\t\tname: \"outbox_actor_disclosure\",\n\t\t\t// Nullable with no default, so rows written before this migration stay NULL and read back\n\t\t\t// as legacy. NOT VALID skips scanning existing rows; the check still applies to every\n\t\t\t// insert and update from here on.\n\t\t\tsql: `\n\t\t\t\tALTER TABLE fabric_platform.event_outbox\n\t\t\t\t\tADD COLUMN actor_disclosure text;\n\t\t\t\tALTER TABLE fabric_platform.event_outbox\n\t\t\t\t\tADD CONSTRAINT event_outbox_actor_disclosure_check\n\t\t\t\t\tCHECK (actor_disclosure IN ('included', 'suppressed')) NOT VALID;\n\t\t\t`,\n\t\t}, {\n\t\t\tversion: 5,\n\t\t\tname: \"outbox_requeue\",\n\t\t\tsql: `\n\t\t\t\tCREATE TABLE fabric_platform.event_outbox_requeues (\n\t\t\t\t\tid text PRIMARY KEY, outbox_id text NOT NULL,\n\t\t\t\t\ttenant_id text NOT NULL, space_id text NOT NULL, event_id text NOT NULL,\n\t\t\t\t\tactor_id text NOT NULL, actor_type text NOT NULL, reason text NOT NULL,\n\t\t\t\t\trequeued_at timestamptz NOT NULL, available_at timestamptz NOT NULL,\n\t\t\t\t\tprior_attempt_count integer NOT NULL, prior_last_error text,\n\t\t\t\t\tprior_available_at timestamptz NOT NULL, prior_lease_token bigint NOT NULL\n\t\t\t\t);\n\t\t\t\tCREATE INDEX event_outbox_requeues_record_idx\n\t\t\t\t\tON fabric_platform.event_outbox_requeues (tenant_id, space_id, outbox_id, requeued_at);\n\t\t\t`,\n\t\t}, {\n\t\t\tversion: 6,\n\t\t\tname: \"invocation_admission\",\n\t\t\t// Nullable with no default: rows written before this migration, and\n\t\t\t// rows of actions that declare no admission check, stay NULL.\n\t\t\tsql: `\n\t\t\t\tALTER TABLE fabric_platform.action_invocations\n\t\t\t\t\tADD COLUMN admitted_at timestamptz;\n\t\t\t`,\n\t\t}, {\n\t\t\tversion: 7,\n\t\t\tname: \"pending_state_transition\",\n\t\t\tsql: `\n\t\t\t\tALTER TABLE fabric_platform.action_invocations\n\t\t\t\t\tADD COLUMN IF NOT EXISTS pending_state_transition jsonb;\n\t\t\t`,\n\t\t}, {\n\t\t\tversion: 8,\n\t\t\tname: \"adapter_reconciliation_checkpoint\",\n\t\t\tsql: `\n\t\t\t\tALTER TABLE fabric_platform.adapter_invocations ADD COLUMN IF NOT EXISTS reconciliation jsonb;\n\t\t\t`,\n\t\t}]);\n\t}\n\n\tasync transaction<TResult>(run: (db: TDb) => Promise<TResult>): Promise<TResult> {\n\t\treturn run(this.db);\n\t}\n\n\tasync createActionInvocation(\n\t\tinput: CreateActionInvocationInput,\n\t): Promise<ActionInvocationRecord> {\n\t\tconst now = new Date();\n\t\t// `admitted_at` (migration 6) is named only for an admitted invocation,\n\t\t// so an invocation of an action without admitSubmission is written with\n\t\t// the same statement as before migration 6 and needs no new column.\n\t\tconst admitted = input.admittedAt !== undefined;\n\t\tconst admittedColumn = admitted ? \"admitted_at,\" : \"\";\n\t\tconst admittedValue = admitted ? \"$25,\" : \"\";\n\t\tlet result;\n\t\ttry {\n\t\t\tresult = await this.sql.query<Record<string, unknown>>(\n\t\t\t\t`INSERT INTO fabric_platform.action_invocations\n\t\t\t\t (id,tenant_id,space_id,action_id,action_version,actor_id,actor_type,status,\n\t\t\t\t\t parameters,result,correlation_id,causation_id,idempotency_key,\n\t\t\t\t\t parameter_digest,parameter_digest_algorithm,idempotency_actor_id,\n\t\t\t\t\t idempotency_authorization_binding_id,invocation_provenance,authorization_binding,execution_reason,\n\t\t\t\t\t authorization_binding_id,error,runtime_evidence,${admittedColumn}created_at,updated_at)\n\t\t\t\t\t VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9::jsonb,$10::jsonb,$11,$12,$13,$14,$15,$16,$17,$18::jsonb,$19::jsonb,$20,$21,$22,$23::jsonb,${admittedValue}$24,$24)\n\t\t\t\t ON CONFLICT (tenant_id,space_id,action_id,idempotency_key)\n\t\t\t\t WHERE idempotency_key IS NOT NULL DO UPDATE SET id=fabric_platform.action_invocations.id\n\t\t\t\t RETURNING *`,\n\t\t\t\t[\n\t\t\t\t\tinput.id, input.tenantId, input.spaceId, input.actionId, input.actionVersion,\n\t\t\t\t\tinput.actorId, input.actorType, input.status, JSON.stringify(input.parameters),\n\t\t\t\t\tJSON.stringify(input.result), input.correlationId, input.causationId ?? null,\n\t\t\t\t\tinput.idempotencyKey ?? null, input.parameterDigest ?? null,\n\t\t\t\t\tinput.parameterDigestAlgorithm ?? null, input.idempotencyActorId ?? null,\n\t\t\t\t\tinput.idempotencyAuthorizationBindingId ?? null,\n\t\t\t\t\tinput.provenance ? JSON.stringify(input.provenance) : null,\n\t\t\t\t\tinput.authorizationBinding ? JSON.stringify(input.authorizationBinding) : null,\n\t\t\t\t\tinput.executionReason ?? null, input.authorizationBindingId ?? null,\n\t\t\t\t\tinput.error ?? null, input.runtimeEvidence ? JSON.stringify(input.runtimeEvidence) : null, now,\n\t\t\t\t\t...(admitted ? [input.admittedAt] : []),\n\t\t\t\t],\n\t\t\t);\n\t\t} catch (error) {\n\t\t\t// 42703 undefined_column: the schema predates migration 6.\n\t\t\tif (admitted && (error as { code?: unknown } | null)?.code === \"42703\") {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"An admitted invocation needs the action_invocations.admitted_at column; run ensureSchema() to apply PostgreSQL migration 6 (invocation_admission) before submitting actions that declare admitSubmission.\",\n\t\t\t\t\t{ cause: error },\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t\treturn toActionRecord(result.rows[0]!);\n\t}\n\n\tasync getActionInvocation(id: string, tenantId: string, spaceId: string) {\n\t\tconst result = await this.sql.query<Record<string, unknown>>(\n\t\t\t`SELECT * FROM fabric_platform.action_invocations\n\t\t\t WHERE id=$1 AND tenant_id=$2 AND space_id=$3`,\n\t\t\t[id, tenantId, spaceId],\n\t\t);\n\t\treturn result.rows[0] ? toActionRecord(result.rows[0]) : undefined;\n\t}\n\n\tasync updateActionInvocation(\n\t\tid: string,\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t\tpatch: ActionInvocationPatch,\n\t): Promise<void> {\n\t\tawait this.sql.query(\n\t\t\t`UPDATE fabric_platform.action_invocations SET\n\t\t\t status=COALESCE($4,status), result=COALESCE($5::jsonb,result),\n\t\t\t error=CASE WHEN $6::boolean THEN $7 ELSE error END,\n\t\t\t authorization_reconciliation=CASE WHEN $8::boolean THEN $9::jsonb ELSE authorization_reconciliation END,\n\t\t\t adapter_reconciliation=CASE WHEN $10::boolean THEN $11::jsonb ELSE adapter_reconciliation END,\n\t\t\t pending_completion=CASE WHEN $12::boolean THEN $13::jsonb ELSE pending_completion END,\n\t\t\t completion_due_at=CASE WHEN $12::boolean THEN ($13::jsonb->>'dueAt')::timestamptz ELSE completion_due_at END,\n\t\t\t external_completion=CASE WHEN $14::boolean THEN $15::jsonb ELSE external_completion END,\n\t\t\t pending_state_transition=CASE WHEN $16::boolean THEN $17::jsonb ELSE pending_state_transition END,\n\t\t\t lease_owner=CASE WHEN ($13::jsonb IS NOT NULL AND $4='running') OR $4 IN ('waiting_for_approval','completed','failed','blocked_by_policy','reconciliation_required','validation_failed')\n\t\t\t THEN NULL ELSE lease_owner END,\n\t\t\t lease_expires_at=CASE WHEN ($13::jsonb IS NOT NULL AND $4='running') OR $4 IN ('waiting_for_approval','completed','failed','blocked_by_policy','reconciliation_required','validation_failed')\n\t\t\t THEN NULL ELSE lease_expires_at END,\n\t\t\t updated_at=now()\n\t\t\t WHERE id=$1 AND tenant_id=$2 AND space_id=$3`,\n\t\t\t[id, tenantId, spaceId, patch.status ?? null,\n\t\t\t patch.result === undefined ? null : JSON.stringify(patch.result),\n\t\t\t Object.hasOwn(patch, \"error\"), patch.error ?? null,\n\t\t\t Object.hasOwn(patch, \"authorizationReconciliation\"),\n\t\t\t patch.authorizationReconciliation ? JSON.stringify(patch.authorizationReconciliation) : null,\n\t\t\t Object.hasOwn(patch, \"adapterReconciliation\"),\n\t\t\t patch.adapterReconciliation ? JSON.stringify(patch.adapterReconciliation) : null,\n\t\t\t Object.hasOwn(patch, \"pendingCompletion\"),\n\t\t\t patch.pendingCompletion ? JSON.stringify(patch.pendingCompletion) : null,\n\t\t\t Object.hasOwn(patch, \"externalCompletion\"),\n\t\t\t patch.externalCompletion ? JSON.stringify(patch.externalCompletion) : null,\n\t\t\t Object.hasOwn(patch, \"pendingStateTransition\"),\n\t\t\t patch.pendingStateTransition ? JSON.stringify(patch.pendingStateTransition) : null],\n\t\t);\n\t}\n\n\tasync recordHitlDecision(\n\t\tactionInvocationId: string,\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t\tdecision: HitlDecisionEvidence,\n\t): Promise<ActionInvocationRecord> {\n\t\tconst result = await this.sql.query<Record<string, unknown>>(\n\t\t\t`UPDATE fabric_platform.action_invocations SET\n\t\t\t hitl_route=$4, hitl_risk_tier=$5, hitl_reason=$6,\n\t\t\t hitl_policy_version=$7, updated_at=$8\n\t\t\t WHERE id=$1 AND tenant_id=$2 AND space_id=$3\n\t\t\t RETURNING *`,\n\t\t\t[\n\t\t\t\tactionInvocationId,\n\t\t\t\ttenantId,\n\t\t\t\tspaceId,\n\t\t\t\tdecision.route,\n\t\t\t\tdecision.riskTier,\n\t\t\t\tdecision.reason,\n\t\t\t\tdecision.policyVersion ?? null,\n\t\t\t\tdecision.evaluatedAt,\n\t\t\t],\n\t\t);\n\t\tconst row = result.rows[0];\n\t\tif (!row) throw new Error(`ActionInvocation not found: ${actionInvocationId}`);\n\t\treturn toActionRecord(row);\n\t}\n\n\tasync beginApprovalDecision(\n\t\tinput: BeginApprovalDecisionInput,\n\t): Promise<ApprovalDecisionTransitionResult> {\n\t\tconst result = await this.sql.query<Record<string, unknown>>(\n\t\t\t`UPDATE fabric_platform.action_invocations SET\n\t\t\t approval_decision=$4::jsonb,\n\t\t\t status=CASE WHEN $5::boolean THEN 'running' ELSE 'failed' END,\n\t\t\t error=CASE WHEN $5::boolean THEN NULL ELSE $6 END,\n\t\t\t lease_owner=CASE WHEN $5::boolean THEN $7 ELSE NULL END,\n\t\t\t lease_expires_at=CASE WHEN $5::boolean THEN $8::timestamptz ELSE NULL END,\n\t\t\t lease_token=CASE WHEN $5::boolean THEN lease_token+1 ELSE lease_token END,\n\t\t\t attempt_count=CASE WHEN $5::boolean THEN GREATEST(attempt_count,1) ELSE attempt_count END,\n\t\t\t updated_at=$9\n\t\t\t WHERE id=$1 AND tenant_id=$2 AND space_id=$3 AND status='waiting_for_approval'\n\t\t\t RETURNING *`,\n\t\t\t[\n\t\t\t\tinput.actionInvocationId,\n\t\t\t\tinput.tenantId,\n\t\t\t\tinput.spaceId,\n\t\t\t\tJSON.stringify({ ...input.decision, decidedAt: input.decision.decidedAt.toISOString() }),\n\t\t\t\tinput.decision.approved,\n\t\t\t\t`Approval rejected: ${input.decision.reason ?? \"no reason provided\"}`,\n\t\t\t\tinput.leaseOwner,\n\t\t\t\tnew Date(input.now.getTime() + input.leaseDurationMs),\n\t\t\t\tinput.now,\n\t\t\t],\n\t\t);\n\t\treturn result.rows[0]\n\t\t\t? { applied: true, invocation: toActionRecord(result.rows[0]) }\n\t\t\t: { applied: false };\n\t}\n\n\tasync appendPolicyEvaluation(record: PolicyEvaluationRecord): Promise<void> {\n\t\tawait this.sql.query(\n\t\t\t`INSERT INTO fabric_platform.policy_evaluations\n\t\t\t (id,action_invocation_id,tenant_id,space_id,outcome,created_at)\n\t\t\t VALUES ($1,$2,$3,$4,$5::jsonb,$6) ON CONFLICT (id) DO NOTHING`,\n\t\t\t[record.id, record.actionInvocationId, record.tenantId, record.spaceId,\n\t\t\t JSON.stringify(record.outcome), record.createdAt],\n\t\t);\n\t}\n\n\tasync recordMutationGovernance(actionInvocationId: string, tenantId: string, spaceId: string, context: { footprint: NonNullable<ActionInvocationRecord[\"mutationFootprint\"]>; executionPrincipal: NonNullable<ActionInvocationRecord[\"executionPrincipal\"]> }): Promise<ActionInvocationRecord> {\n\t\tconst result = await this.sql.query<Record<string, unknown>>(\n\t\t\t`UPDATE fabric_platform.action_invocations SET mutation_footprint=$4::jsonb,\n\t\t\t execution_principal=$5::jsonb, updated_at=now()\n\t\t\t WHERE id=$1 AND tenant_id=$2 AND space_id=$3 RETURNING *`,\n\t\t\t[actionInvocationId, tenantId, spaceId, JSON.stringify(context.footprint), JSON.stringify(context.executionPrincipal)],\n\t\t);\n\t\tif (!result.rows[0]) throw new Error(`ActionInvocation not found: ${actionInvocationId}`);\n\t\treturn toActionRecord(result.rows[0]);\n\t}\n\n\tasync appendPolicyObligations(records: PolicyObligationRecord[]): Promise<void> {\n\t\tfor (const record of records) {\n\t\t\tawait this.sql.query(\n\t\t\t\t`INSERT INTO fabric_platform.policy_obligations\n\t\t\t\t (action_invocation_id,id,tenant_id,space_id,type,status,required,description,evidence_references,metadata,created_at,updated_at)\n\t\t\t\t VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9::jsonb,$10::jsonb,$11,$12)\n\t\t\t\t ON CONFLICT (action_invocation_id,id) DO NOTHING`,\n\t\t\t\t[record.actionInvocationId, record.id, record.tenantId, record.spaceId, record.type, record.status,\n\t\t\t\t record.required ?? true, record.description ?? null,\n\t\t\t\t record.evidenceReferences ? JSON.stringify(record.evidenceReferences) : null,\n\t\t\t\t record.metadata ? JSON.stringify(record.metadata) : null, record.createdAt, record.updatedAt],\n\t\t\t);\n\t\t}\n\t}\n\n\tasync listPolicyObligations(actionInvocationId: string, tenantId: string, spaceId: string): Promise<PolicyObligationRecord[]> {\n\t\tconst result = await this.sql.query<Record<string, unknown>>(\n\t\t\t`SELECT * FROM fabric_platform.policy_obligations WHERE action_invocation_id=$1 AND tenant_id=$2 AND space_id=$3 ORDER BY created_at,id`,\n\t\t\t[actionInvocationId, tenantId, spaceId],\n\t\t);\n\t\treturn result.rows.map(toObligationRecord);\n\t}\n\n\tasync updatePolicyObligation(actionInvocationId: string, obligationId: string, status: PolicyObligationRecord[\"status\"], evidenceReferences?: PolicyObligationRecord[\"evidenceReferences\"]): Promise<void> {\n\t\tawait this.sql.query(\n\t\t\t`UPDATE fabric_platform.policy_obligations SET status=$3,\n\t\t\t evidence_references=COALESCE($4::jsonb,evidence_references), updated_at=now()\n\t\t\t WHERE action_invocation_id=$1 AND id=$2`,\n\t\t\t[actionInvocationId, obligationId, status, evidenceReferences ? JSON.stringify(evidenceReferences) : null],\n\t\t);\n\t}\n\n\tasync appendExecutionAttestation(record: ExecutionAttestationRecord): Promise<void> {\n\t\tconst { id, actionInvocationId, tenantId, spaceId, adapterInvocationId, recordedAt, ...attestation } = record;\n\t\tawait this.sql.query(\n\t\t\t`INSERT INTO fabric_platform.execution_attestations\n\t\t\t (id,action_invocation_id,tenant_id,space_id,adapter_invocation_id,attestation,recorded_at)\n\t\t\t VALUES ($1,$2,$3,$4,$5,$6::jsonb,$7) ON CONFLICT (id) DO NOTHING`,\n\t\t\t[id, actionInvocationId, tenantId, spaceId, adapterInvocationId ?? null, JSON.stringify(attestation), recordedAt],\n\t\t);\n\t}\n\n\tasync listExecutionAttestations(actionInvocationId: string, tenantId: string, spaceId: string): Promise<ExecutionAttestationRecord[]> {\n\t\tconst result = await this.sql.query<Record<string, unknown>>(\n\t\t\t`SELECT * FROM fabric_platform.execution_attestations WHERE action_invocation_id=$1 AND tenant_id=$2 AND space_id=$3 ORDER BY recorded_at,id`,\n\t\t\t[actionInvocationId, tenantId, spaceId],\n\t\t);\n\t\treturn result.rows.map(toAttestationRecord);\n\t}\n\n\tasync appendExternalReconciliation(record: ExternalReconciliationRecord): Promise<void> {\n\t\tconst { id, actionInvocationId, tenantId, spaceId, ...reconciliation } = record;\n\t\tawait this.sql.query(\n\t\t\t`INSERT INTO fabric_platform.external_reconciliations\n\t\t\t (id,action_invocation_id,tenant_id,space_id,reconciliation)\n\t\t\t VALUES ($1,$2,$3,$4,$5::jsonb) ON CONFLICT (id) DO NOTHING`,\n\t\t\t[id, actionInvocationId, tenantId, spaceId, JSON.stringify(reconciliation)],\n\t\t);\n\t}\n\n\tasync updateSettledActionInvocation(input: import(\"./types\").UpdateSettledActionInvocationInput): Promise<boolean> {\n\t\tconst { condition, patch } = input;\n\t\tif ([\"pending\", \"running\", \"waiting_for_approval\"].includes(condition.status)) return false;\n\t\tconst result = await this.sql.query(\n\t\t\t`UPDATE fabric_platform.action_invocations SET\n\t\t\t error=CASE WHEN $7::boolean THEN $8 ELSE error END,\n\t\t\t adapter_reconciliation=CASE WHEN $9::boolean THEN $10::jsonb ELSE adapter_reconciliation END,\n\t\t\t updated_at=now()\n\t\t\t WHERE id=$1 AND tenant_id=$2 AND space_id=$3 AND status=$4\n\t\t\t AND error IS NOT DISTINCT FROM $5::text\n\t\t\t AND ((external_completion IS NULL AND $6::text IS NULL)\n\t\t\t OR ($6::text IS NOT NULL AND external_completion->>'digest'=$6)) RETURNING id`,\n\t\t\t[input.id, input.tenantId, input.spaceId, condition.status, condition.error ?? null,\n\t\t\t condition.externalCompletionDigest ?? null, Object.hasOwn(patch, \"error\"), patch.error ?? null,\n\t\t\t Object.hasOwn(patch, \"adapterReconciliation\"), patch.adapterReconciliation === undefined ? null : JSON.stringify(patch.adapterReconciliation)],\n\t\t);\n\t\treturn result.rows.length === 1;\n\t}\n\n\tasync writeAdapterInvocation(input: AdapterInvocationWriteInput): Promise<boolean> {\n\t\tconst { scope, condition, mutation } = input;\n\t\tif (condition.kind === \"verdict\" && [\"pending\", \"running\", \"waiting_for_approval\"].includes(condition.status)) return false;\n\t\t// FOR UPDATE precedes the child mutation. READ COMMITTED re-evaluates the\n\t\t// predicate on a parent changed by a claimant while this lock waited.\n\t\tconst values: unknown[] = [scope.actionInvocationId, scope.tenantId, scope.spaceId];\n\t\tconst checkCompletion = condition.kind === \"verdict\" && (condition.completionAdapterInvocationId === undefined\n\t\t\t|| condition.completionAdapterInvocationId === (mutation.kind === \"create\" ? mutation.record.id : mutation.id));\n\t\tconst authority = condition.kind === \"lease\"\n\t\t\t? \"status='running' AND lease_owner=$4 AND lease_token=$5\"\n\t\t\t: \"status=$4 AND error IS NOT DISTINCT FROM $5::text\"\n\t\t\t\t+ (checkCompletion ? \" AND ((external_completion IS NULL AND $DIGEST::text IS NULL) OR ($DIGEST::text IS NOT NULL AND external_completion->>'digest'=$DIGEST))\" : \"\");\n\t\tvalues.push(...(condition.kind === \"lease\" ? [condition.leaseOwner, condition.leaseToken] : [condition.status, condition.error ?? null]));\n\t\tconst parent = `WITH parent AS MATERIALIZED (\n\t\t\tSELECT id FROM fabric_platform.action_invocations\n\t\t\tWHERE id=$1 AND tenant_id=$2 AND space_id=$3 AND ${authority} FOR UPDATE\n\t\t)`;\n\t\tlet sql: string;\n\t\tif (mutation.kind === \"create\") {\n\t\t\tconst row = mutation.record;\n\t\t\tif (row.actionInvocationId !== scope.actionInvocationId || row.tenantId !== scope.tenantId || row.spaceId !== scope.spaceId) return false;\n\t\t\tconst hasReconciliation = row.reconciliation !== undefined;\n\t\t\tsql = `${parent} INSERT INTO fabric_platform.adapter_invocations\n\t\t\t\t(id,action_invocation_id,tenant_id,space_id,adapter_type,operation,vendor,status,input,output,error,attempt,created_at,updated_at${hasReconciliation ? \",reconciliation\" : \"\"})\n\t\t\t\tSELECT $6,parent.id,$2,$3,$7,$8,$9,$10,$11::jsonb,$12::jsonb,$13,$14,$15,$16${hasReconciliation ? \",$17::jsonb\" : \"\"} FROM parent\n\t\t\t\tON CONFLICT (id) DO NOTHING RETURNING id`;\n\t\t\tvalues.push(row.id, row.adapterType, row.operation, row.vendor, row.status, JSON.stringify(row.input),\n\t\t\t\trow.output === undefined ? null : JSON.stringify(row.output), row.error ?? null, row.attempt, row.createdAt, row.updatedAt,\n\t\t\t\t...(hasReconciliation ? [JSON.stringify(row.reconciliation)] : []));\n\t\t} else {\n\t\t\tconst { patch } = mutation;\n\t\t\tconst hasReconciliation = patch.reconciliation !== undefined;\n\t\t\tsql = `${parent} UPDATE fabric_platform.adapter_invocations AS adapter SET\n\t\t\t\tstatus=COALESCE($7,status),output=COALESCE($8::jsonb,output),\n\t\t\t\terror=CASE WHEN $9::boolean THEN $10 ELSE error END,\n\t\t\t\tattempt=COALESCE($11,attempt),updated_at=COALESCE($12,now())${hasReconciliation ? \",reconciliation=COALESCE($14::jsonb,reconciliation)\" : \"\"}\n\t\t\t\tFROM parent WHERE adapter.id=$6 AND adapter.action_invocation_id=parent.id AND adapter.tenant_id=$2 AND adapter.space_id=$3\n\t\t\t\tAND ($13::text[] IS NULL OR adapter.status=ANY($13::text[]))\n\t\t\t\tAND NOT (adapter.status IN ('succeeded','ambiguous') AND COALESCE($7,adapter.status) IN ('running','failed'))\n\t\t\t\tRETURNING adapter.id`;\n\t\t\tvalues.push(mutation.id, patch.status ?? null, patch.output === undefined ? null : JSON.stringify(patch.output),\n\t\t\t\tObject.hasOwn(patch, \"error\"), patch.error ?? null, patch.attempt ?? null, patch.updatedAt ?? null,\n\t\t\t\tinput.expectedStatuses ?? null, ...(hasReconciliation ? [JSON.stringify(patch.reconciliation)] : []));\n\t\t}\n\t\tif (condition.kind === \"verdict\" && checkCompletion) {\n\t\t\tvalues.push(condition.externalCompletionDigest ?? null);\n\t\t\tsql = sql.replaceAll(\"$DIGEST\", () => `$${values.length}`);\n\t\t}\n\t\treturn (await this.sql.query(sql, values)).rows.length === 1;\n\t}\n\n\tasync createAdapterInvocation(record: AdapterInvocationRecord): Promise<void> {\n\t\tconst hasReconciliation = record.reconciliation !== undefined;\n\t\tawait this.sql.query(\n\t\t\t`INSERT INTO fabric_platform.adapter_invocations\n\t\t\t (id,action_invocation_id,tenant_id,space_id,adapter_type,operation,vendor,status,\n\t\t\t input,output,error,attempt,created_at,updated_at${hasReconciliation ? \",reconciliation\" : \"\"})\n\t\t\t VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9::jsonb,$10::jsonb,$11,$12,$13,$14${hasReconciliation ? \",$15::jsonb\" : \"\"})\n\t\t\t ON CONFLICT (id) DO NOTHING`,\n\t\t\t[record.id, record.actionInvocationId, record.tenantId, record.spaceId,\n\t\t\t record.adapterType, record.operation, record.vendor, record.status,\n\t\t\t JSON.stringify(record.input), record.output ? JSON.stringify(record.output) : null,\n\t\t\t record.error ?? null, record.attempt, record.createdAt, record.updatedAt,\n\t\t\t ...(hasReconciliation ? [JSON.stringify(record.reconciliation)] : [])],\n\t\t);\n\t}\n\n\tasync getAdapterInvocation(id: string, scope?: AdapterInvocationScope): Promise<AdapterInvocationRecord | undefined> {\n\t\tconst result = await this.sql.query<Record<string, unknown>>(\n\t\t\t`SELECT * FROM fabric_platform.adapter_invocations WHERE id=$1${scope ? \" AND tenant_id=$2 AND space_id=$3 AND action_invocation_id=$4\" : \"\"}`,\n\t\t\t[id, ...(scope ? [scope.tenantId, scope.spaceId, scope.actionInvocationId] : [])],\n\t\t);\n\t\treturn result.rows[0] ? toAdapterRecord(result.rows[0]) : undefined;\n\t}\n\n\tasync updateAdapterInvocation(\n\t\tid: string,\n\t\tpatch: Partial<\n\t\t\tPick<AdapterInvocationRecord, \"status\" | \"output\" | \"error\" | \"attempt\" | \"updatedAt\" | \"reconciliation\">\n\t\t>,\n\t\tscope?: AdapterInvocationScope,\n\t): Promise<void> {\n\t\tconst hasReconciliation = patch.reconciliation !== undefined;\n\t\tawait this.sql.query(\n\t\t\t`UPDATE fabric_platform.adapter_invocations SET\n\t\t\t status=COALESCE($2,status), output=COALESCE($3::jsonb,output),\n\t\t\t error=CASE WHEN $4::boolean THEN $5 ELSE error END,\n\t\t\t attempt=COALESCE($6,attempt), updated_at=COALESCE($7,now())${hasReconciliation ? `,\n\t\t\t reconciliation=COALESCE($${scope ? 11 : 8}::jsonb,reconciliation)` : \"\"} WHERE id=$1${scope ? \" AND tenant_id=$8 AND space_id=$9 AND action_invocation_id=$10\" : \"\"}`,\n\t\t\t[id, patch.status ?? null,\n\t\t\t patch.output === undefined ? null : JSON.stringify(patch.output),\n\t\t\t Object.hasOwn(patch, \"error\"), patch.error ?? null, patch.attempt ?? null,\n\t\t\t patch.updatedAt ?? null, ...(scope ? [scope.tenantId, scope.spaceId, scope.actionInvocationId] : []),\n\t\t\t ...(hasReconciliation ? [JSON.stringify(patch.reconciliation)] : [])],\n\t\t);\n\t}\n\n\tasync appendEvent(event: AssetEventEnvelope): Promise<void> {\n\t\tawait this.sql.query(\n\t\t\t`INSERT INTO fabric_platform.asset_events\n\t\t\t (id,tenant_id,space_id,event_type,event_schema_version,subject_type,subject_id,\n\t\t\t actor_id,actor_type,action_invocation_id,payload,sequence,occurred_at,recorded_at,\n\t\t\t correlation_id,causation_id,provenance,consistency)\n\t\t\t\t VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11::jsonb,$12,$13,$14,$15,$16,$17::jsonb,$18)\n\t\t\t\t ON CONFLICT (id) DO NOTHING`,\n\t\t\t[event.id, event.tenantId, event.spaceId, event.eventType, event.eventSchemaVersion,\n\t\t\t event.subjectType, event.subjectId, event.actorId, event.actorType,\n\t\t\t event.actionInvocationId ?? null, JSON.stringify(event.payload), event.sequence,\n\t\t\t event.occurredAt, event.recordedAt, event.correlationId, event.causationId ?? null,\n\t\t\t event.provenance ? JSON.stringify(event.provenance) : null, event.consistency ?? null],\n\t\t);\n\t}\n\n\tasync appendEventWithOutbox(event: AssetEventEnvelope, metadata: OutboxEventMetadata): Promise<void> {\n\t\tconst envelope = toEnterpriseEventEnvelope(event, metadata);\n\t\tawait this.sql.query(\n\t\t\t`WITH inserted_event AS (\n\t\t\t\tINSERT INTO fabric_platform.asset_events\n\t\t\t\t (id,tenant_id,space_id,event_type,event_schema_version,subject_type,subject_id,\n\t\t\t\t actor_id,actor_type,action_invocation_id,payload,sequence,occurred_at,recorded_at,\n\t\t\t\t correlation_id,causation_id,provenance,consistency)\n\t\t\t\t VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11::jsonb,$12,$13,$14,$15,$16,$17::jsonb,$19)\n\t\t\t\t ON CONFLICT (id) DO NOTHING RETURNING id\n\t\t\t)\n\t\t\tINSERT INTO fabric_platform.event_outbox\n\t\t\t (id,tenant_id,space_id,event,actor_disclosure,status,attempt_count,available_at,created_at)\n\t\t\tSELECT $1,$2,$3,$18::jsonb,$20,'pending',0,$14,$14 FROM inserted_event\n\t\t\tON CONFLICT (id) DO NOTHING`,\n\t\t\t[event.id, event.tenantId, event.spaceId, event.eventType, event.eventSchemaVersion,\n\t\t\t event.subjectType, event.subjectId, event.actorId, event.actorType,\n\t\t\t event.actionInvocationId ?? null, JSON.stringify(event.payload), event.sequence,\n\t\t\t event.occurredAt, event.recordedAt, event.correlationId, event.causationId ?? null,\n\t\t\t event.provenance ? JSON.stringify(event.provenance) : null, JSON.stringify(envelope), event.consistency ?? null,\n\t\t\t outboxActorDisclosure(metadata)],\n\t\t);\n\t}\n\n\tasync claimOutbox(input: ClaimOutboxInput): Promise<OutboxRecord[]> {\n\t\tconst current = input.now ?? new Date();\n\t\tconst leaseExpiresAt = new Date(current.getTime() + input.leaseDurationMs);\n\t\tconst result = await this.sql.query<Record<string, unknown>>(\n\t\t\t`WITH claimable AS (\n\t\t\t\tSELECT id FROM fabric_platform.event_outbox\n\t\t\t\tWHERE status='pending' AND available_at <= $1\n\t\t\t\t AND (lease_expires_at IS NULL OR lease_expires_at <= $1)\n\t\t\t\t AND ($2::text IS NULL OR tenant_id=$2)\n\t\t\t\t AND ($3::text IS NULL OR space_id=$3)\n\t\t\t\tORDER BY created_at,id FOR UPDATE SKIP LOCKED LIMIT $4\n\t\t\t)\n\t\t\tUPDATE fabric_platform.event_outbox AS item\n\t\t\tSET lease_owner=$5, lease_expires_at=$6, lease_token=lease_token+1,\n\t\t\t attempt_count=attempt_count+1\n\t\t\tFROM claimable WHERE item.id=claimable.id RETURNING item.*`,\n\t\t\t[current, input.tenantId ?? null, input.spaceId ?? null, Math.max(1, Math.min(input.limit ?? 100, 1_000)), input.workerId, leaseExpiresAt],\n\t\t);\n\t\treturn result.rows.map(toOutboxRecord);\n\t}\n\n\tasync markOutboxPublished(id: string, workerId: string, publishedAt: Date, leaseToken?: number): Promise<void> {\n\t\tconst result = await this.sql.query(\n\t\t\t`UPDATE fabric_platform.event_outbox SET status='published',published_at=$3,\n\t\t\t lease_owner=NULL,lease_expires_at=NULL\n\t\t\t WHERE id=$1 AND lease_owner=$2 AND lease_token=COALESCE($4,0) RETURNING id`,\n\t\t\t[id, workerId, publishedAt, leaseToken ?? null],\n\t\t);\n\t\tif (result.rows.length === 0) throw new Error(`Outbox record ${id} is not leased by ${workerId}.`);\n\t}\n\n\tasync markOutboxFailed(input: { id: string; workerId: string; leaseToken?: number; error: string; availableAt: Date; deadLetter: boolean }): Promise<void> {\n\t\tconst result = await this.sql.query(\n\t\t\t`UPDATE fabric_platform.event_outbox SET status=$3,last_error=$4,available_at=$5,\n\t\t\t lease_owner=NULL,lease_expires_at=NULL\n\t\t\t WHERE id=$1 AND lease_owner=$2 AND lease_token=COALESCE($6,0) RETURNING id`,\n\t\t\t[input.id, input.workerId, input.deadLetter ? \"dead_letter\" : \"pending\", input.error, input.availableAt, input.leaseToken ?? null],\n\t\t);\n\t\tif (result.rows.length === 0) throw new Error(`Outbox record ${input.id} is not leased by ${input.workerId}.`);\n\t}\n\n\tasync renewOutboxLease(input: { id: string; workerId: string; leaseToken: number; leaseDurationMs: number; now?: Date }): Promise<boolean> {\n\t\tconst current = input.now ?? new Date();\n\t\tconst result = await this.sql.query(\n\t\t\t`UPDATE fabric_platform.event_outbox SET lease_expires_at=$5\n\t\t\t WHERE id=$1 AND status='pending' AND lease_owner=$2 AND lease_token=$3\n\t\t\t AND lease_expires_at > $4\n\t\t\t RETURNING id`,\n\t\t\t[input.id, input.workerId, input.leaseToken,\n\t\t\t\tcurrent, new Date(current.getTime() + input.leaseDurationMs)],\n\t\t);\n\t\treturn result.rows.length === 1;\n\t}\n\n\tasync listOutbox(input: { tenantId?: string; spaceId?: string; statuses?: OutboxStatus[] } = {}): Promise<OutboxRecord[]> {\n\t\tconst result = await this.sql.query<Record<string, unknown>>(\n\t\t\t`SELECT * FROM fabric_platform.event_outbox\n\t\t\t WHERE ($1::text IS NULL OR tenant_id=$1) AND ($2::text IS NULL OR space_id=$2)\n\t\t\t AND ($3::text[] IS NULL OR status=ANY($3::text[])) ORDER BY created_at,id`,\n\t\t\t[input.tenantId ?? null, input.spaceId ?? null, input.statuses?.length ? input.statuses : null],\n\t\t);\n\t\treturn result.rows.map(toOutboxRecord);\n\t}\n\n\tasync getOutboxRecord(id: string, tenantId: string, spaceId: string): Promise<OutboxRecord | undefined> {\n\t\tconst result = await this.sql.query<Record<string, unknown>>(\n\t\t\t`SELECT * FROM fabric_platform.event_outbox\n\t\t\t WHERE id=$1 AND tenant_id=$2 AND space_id=$3`,\n\t\t\t[id, tenantId, spaceId],\n\t\t);\n\t\treturn result.rows[0] ? toOutboxRecord(result.rows[0]) : undefined;\n\t}\n\n\tasync requeueOutboxDeadLetter(input: RequeueOutboxDeadLetterStoreInput): Promise<RequeueOutboxDeadLetterStoreResult> {\n\t\t// One statement, so the transition and its evidence commit together. The\n\t\t// row lock re-reads status and lease token after a concurrent writer\n\t\t// commits, so of two racing requeues exactly one sees the dead letter it\n\t\t// was authorized for; the other writes nothing. Every claim increments\n\t\t// lease_token, so a record dead-lettered again since the caller read it\n\t\t// no longer matches.\n\t\tconst result = await this.sql.query<Record<string, unknown>>(\n\t\t\t`WITH prior AS (\n\t\t\t\tSELECT id, tenant_id, space_id, event->>'eventId' AS event_id,\n\t\t\t\t attempt_count, last_error, available_at, lease_token\n\t\t\t\tFROM fabric_platform.event_outbox\n\t\t\t\tWHERE id=$1 AND tenant_id=$2 AND space_id=$3 AND status='dead_letter'\n\t\t\t\t AND lease_token=$10\n\t\t\t\tFOR UPDATE\n\t\t\t), requeued AS (\n\t\t\t\tUPDATE fabric_platform.event_outbox AS item\n\t\t\t\tSET status='pending', attempt_count=0, available_at=$9,\n\t\t\t\t lease_owner=NULL, lease_expires_at=NULL\n\t\t\t\tFROM prior WHERE item.id=prior.id\n\t\t\t\tRETURNING item.*\n\t\t\t), evidence AS (\n\t\t\t\tINSERT INTO fabric_platform.event_outbox_requeues\n\t\t\t\t (id,outbox_id,tenant_id,space_id,event_id,actor_id,actor_type,reason,\n\t\t\t\t requeued_at,available_at,prior_attempt_count,prior_last_error,\n\t\t\t\t prior_available_at,prior_lease_token)\n\t\t\t\tSELECT $4,prior.id,prior.tenant_id,prior.space_id,prior.event_id,$5,$6,$7,\n\t\t\t\t $8,$9,prior.attempt_count,prior.last_error,prior.available_at,prior.lease_token\n\t\t\t\tFROM prior JOIN requeued ON requeued.id=prior.id\n\t\t\t\tRETURNING *\n\t\t\t)\n\t\t\tSELECT requeued.*,\n\t\t\t evidence.id AS requeue_id, evidence.outbox_id AS requeue_outbox_id,\n\t\t\t evidence.tenant_id AS requeue_tenant_id, evidence.space_id AS requeue_space_id,\n\t\t\t evidence.event_id AS requeue_event_id, evidence.actor_id AS requeue_actor_id,\n\t\t\t evidence.actor_type AS requeue_actor_type, evidence.reason AS requeue_reason,\n\t\t\t evidence.requeued_at AS requeue_requeued_at, evidence.available_at AS requeue_available_at,\n\t\t\t evidence.prior_attempt_count AS requeue_prior_attempt_count,\n\t\t\t evidence.prior_last_error AS requeue_prior_last_error,\n\t\t\t evidence.prior_available_at AS requeue_prior_available_at,\n\t\t\t evidence.prior_lease_token AS requeue_prior_lease_token\n\t\t\tFROM requeued JOIN evidence ON evidence.outbox_id=requeued.id`,\n\t\t\t[input.id, input.tenantId, input.spaceId, input.requeueId, input.actorId,\n\t\t\t input.actorType, input.reason, input.requeuedAt, input.availableAt, input.expectedLeaseToken],\n\t\t);\n\t\tconst row = result.rows[0];\n\t\tif (row) {\n\t\t\treturn {\n\t\t\t\tapplied: true,\n\t\t\t\trecord: toOutboxRecord(row),\n\t\t\t\trequeue: toOutboxRequeueRecord(row, \"requeue_\"),\n\t\t\t};\n\t\t}\n\t\tconst current = await this.sql.query<{ status: string }>(\n\t\t\t`SELECT status FROM fabric_platform.event_outbox\n\t\t\t WHERE id=$1 AND tenant_id=$2 AND space_id=$3`,\n\t\t\t[input.id, input.tenantId, input.spaceId],\n\t\t);\n\t\tconst found = current.rows[0];\n\t\tif (!found) return { applied: false, refusal: \"not_found\" };\n\t\tconst status = found.status as OutboxStatus;\n\t\t// The statement refused, yet the row is a dead letter: it is a later\n\t\t// generation, since a record only returns to dead_letter through a claim\n\t\t// and every claim moves the lease token past the one the caller read.\n\t\treturn status === \"dead_letter\"\n\t\t\t? { applied: false, refusal: \"stale\", currentStatus: status }\n\t\t\t: { applied: false, refusal: \"not_dead_letter\", currentStatus: status };\n\t}\n\n\tasync listOutboxRequeues(input: { tenantId: string; spaceId: string; outboxId?: string }): Promise<OutboxRequeueRecord[]> {\n\t\tconst result = await this.sql.query<Record<string, unknown>>(\n\t\t\t`SELECT * FROM fabric_platform.event_outbox_requeues\n\t\t\t WHERE tenant_id=$1 AND space_id=$2 AND ($3::text IS NULL OR outbox_id=$3)\n\t\t\t ORDER BY requeued_at,id`,\n\t\t\t[input.tenantId, input.spaceId, input.outboxId ?? null],\n\t\t);\n\t\treturn result.rows.map((row) => toOutboxRequeueRecord(row, \"\"));\n\t}\n\n\tasync nextEventSequence(tenantId: string, spaceId: string): Promise<number> {\n\t\tconst result = await this.sql.query<{ next_sequence: string | number }>(\n\t\t\t`INSERT INTO fabric_platform.event_sequences (tenant_id,space_id,next_sequence)\n\t\t\t VALUES ($1,$2,1) ON CONFLICT (tenant_id,space_id) DO UPDATE\n\t\t\t SET next_sequence=fabric_platform.event_sequences.next_sequence+1\n\t\t\t RETURNING next_sequence`,\n\t\t\t[tenantId, spaceId],\n\t\t);\n\t\treturn Number(result.rows[0]!.next_sequence);\n\t}\n\n\tasync getEntityStateSource(\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t\tentityType: string,\n\t\tentityId: string,\n\t): Promise<{ state: string; actionInvocationId: string } | undefined> {\n\t\tconst result = await this.sql.query<{ state?: string; action_invocation_id?: string }>(\n\t\t\t`SELECT payload->>'toState' AS state, action_invocation_id FROM fabric_platform.asset_events\n\t\t\t WHERE tenant_id=$1 AND space_id=$2 AND subject_type=$3 AND subject_id=$4\n\t\t\t AND payload ? 'toState' ORDER BY sequence DESC LIMIT 1`,\n\t\t\t[tenantId, spaceId, entityType, entityId],\n\t\t);\n\t\tconst row = result.rows[0];\n\t\treturn typeof row?.state === \"string\" && typeof row.action_invocation_id === \"string\"\n\t\t\t? { state: row.state, actionInvocationId: row.action_invocation_id } : undefined;\n\t}\n\n\tasync getEntityState(\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t\tentityType: string,\n\t\tentityId: string,\n\t) {\n\t\tconst result = await this.sql.query<{ state?: string }>(\n\t\t\t`SELECT payload->>'toState' AS state FROM fabric_platform.asset_events\n\t\t\t WHERE tenant_id=$1 AND space_id=$2 AND subject_type=$3 AND subject_id=$4\n\t\t\t AND payload ? 'toState' ORDER BY sequence DESC LIMIT 1`,\n\t\t\t[tenantId, spaceId, entityType, entityId],\n\t\t);\n\t\treturn result.rows[0]?.state;\n\t}\n\n\tasync listActionInvocations(\n\t\tinput: ListActionInvocationsInput = {},\n\t): Promise<ActionInvocationRecord[]> {\n\t\tconst conditions: string[] = [];\n\t\tconst values: unknown[] = [];\n\t\tconst add = (condition: string, value: unknown) => {\n\t\t\tvalues.push(value);\n\t\t\tconditions.push(condition.replace(\"?\", `$${values.length}`));\n\t\t};\n\t\tif (input.tenantId) add(\"tenant_id=?\", input.tenantId);\n\t\tif (input.spaceId) add(\"space_id=?\", input.spaceId);\n\t\tif (input.statuses?.length) add(\"status = ANY(?::text[])\", [...input.statuses]);\n\t\tif (input.updatedBefore) add(\"updated_at<?\", input.updatedBefore);\n\t\tif (input.awaitingCompletion || input.completionDueBefore) conditions.push(\"pending_completion IS NOT NULL\");\n\t\tif (input.completionDueBefore) add(\"completion_due_at <= ?\", input.completionDueBefore);\n\t\tif (input.unleased) conditions.push(\"lease_owner IS NULL\");\n\t\tvalues.push(Math.max(1, Math.min(input.limit ?? 100, 1_000)));\n\t\tconst where = conditions.length ? `WHERE ${conditions.join(\" AND \")}` : \"\";\n\t\tconst result = await this.sql.query<Record<string, unknown>>(\n\t\t\t`SELECT * FROM fabric_platform.action_invocations ${where}\n\t\t\t ORDER BY created_at LIMIT $${values.length}`,\n\t\t\tvalues,\n\t\t);\n\t\treturn result.rows.map(toActionRecord);\n\t}\n\n\tasync getHealthCounts(input: PlatformHostHealthQuery): Promise<PlatformHostHealthCounts> {\n\t\tconst result = await this.sql.query<Record<string, string | number>>(\n\t\t\t`SELECT\n\t\t\t\t(SELECT COUNT(*) FROM fabric_platform.action_invocations\n\t\t\t\t WHERE status='pending'\n\t\t\t\t AND ($1::text IS NULL OR tenant_id=$1)\n\t\t\t\t AND ($2::text IS NULL OR space_id=$2)) AS invocation_backlog,\n\t\t\t\t(SELECT COUNT(*) FROM fabric_platform.action_invocations\n\t\t\t\t WHERE status='running'\n\t\t\t\t AND ($1::text IS NULL OR tenant_id=$1)\n\t\t\t\t AND ($2::text IS NULL OR space_id=$2)) AS invocation_running,\n\t\t\t\t(SELECT COUNT(*) FROM fabric_platform.action_invocations\n\t\t\t\t WHERE status='running' AND lease_expires_at IS NOT NULL AND lease_expires_at <= $3\n\t\t\t\t AND ($1::text IS NULL OR tenant_id=$1)\n\t\t\t\t AND ($2::text IS NULL OR space_id=$2)) AS invocation_expired_leases,\n\t\t\t\t(SELECT COUNT(*) FROM fabric_platform.action_invocations\n\t\t\t\t WHERE status='waiting_for_approval'\n\t\t\t\t AND ($1::text IS NULL OR tenant_id=$1)\n\t\t\t\t AND ($2::text IS NULL OR space_id=$2)) AS invocation_approval_waits,\n\t\t\t\t(SELECT COUNT(*) FROM fabric_platform.action_invocations\n\t\t\t\t WHERE status='reconciliation_required'\n\t\t\t\t AND ($1::text IS NULL OR tenant_id=$1)\n\t\t\t\t AND ($2::text IS NULL OR space_id=$2)) AS invocation_reconciliation_required,\n\t\t\t\t(SELECT COUNT(*) FROM fabric_platform.event_outbox\n\t\t\t\t WHERE status='pending'\n\t\t\t\t AND ($1::text IS NULL OR tenant_id=$1)\n\t\t\t\t AND ($2::text IS NULL OR space_id=$2)) AS outbox_backlog,\n\t\t\t\t(SELECT COUNT(*) FROM fabric_platform.event_outbox\n\t\t\t\t WHERE status='pending' AND lease_expires_at IS NOT NULL AND lease_expires_at <= $3\n\t\t\t\t AND ($1::text IS NULL OR tenant_id=$1)\n\t\t\t\t AND ($2::text IS NULL OR space_id=$2)) AS outbox_expired_leases,\n\t\t\t\t(SELECT COUNT(*) FROM fabric_platform.event_outbox\n\t\t\t\t WHERE status='dead_letter'\n\t\t\t\t AND ($1::text IS NULL OR tenant_id=$1)\n\t\t\t\t AND ($2::text IS NULL OR space_id=$2)) AS outbox_dead_letters`,\n\t\t\t[input.tenantId ?? null, input.spaceId ?? null, input.now],\n\t\t);\n\t\tconst row = result.rows[0] ?? {};\n\t\treturn {\n\t\t\tinvocationBacklog: Number(row.invocation_backlog ?? 0),\n\t\t\tinvocationRunning: Number(row.invocation_running ?? 0),\n\t\t\tinvocationExpiredLeases: Number(row.invocation_expired_leases ?? 0),\n\t\t\tinvocationApprovalWaits: Number(row.invocation_approval_waits ?? 0),\n\t\t\tinvocationReconciliationRequired: Number(row.invocation_reconciliation_required ?? 0),\n\t\t\toutboxBacklog: Number(row.outbox_backlog ?? 0),\n\t\t\toutboxExpiredLeases: Number(row.outbox_expired_leases ?? 0),\n\t\t\toutboxDeadLetters: Number(row.outbox_dead_letters ?? 0),\n\t\t};\n\t}\n\n\tasync claimActionInvocations(\n\t\tinput: ClaimActionInvocationsInput,\n\t): Promise<ActionInvocationRecord[]> {\n\t\tconst current = input.now ?? new Date();\n\t\tconst limit = Math.max(1, Math.min(input.limit ?? 10, 100));\n\t\tconst leaseExpiresAt = new Date(current.getTime() + input.leaseDurationMs);\n\t\tconst result = await this.sql.query<Record<string, unknown>>(\n\t\t\t`WITH claimable AS (\n\t\t\t\tSELECT id FROM fabric_platform.action_invocations\n\t\t\t\tWHERE (status='pending' OR\n\t\t\t\t (status='running' AND lease_expires_at IS NOT NULL AND lease_expires_at <= $1))\n\t\t\t\t AND ($2::text IS NULL OR tenant_id=$2)\n\t\t\t\t AND ($3::text IS NULL OR space_id=$3)\n\t\t\t\tORDER BY created_at\n\t\t\t\tFOR UPDATE SKIP LOCKED\n\t\t\t\tLIMIT $4\n\t\t\t)\n\t\t\tUPDATE fabric_platform.action_invocations AS invocation\n\t\t\tSET status='running', lease_owner=$5, lease_expires_at=$6,\n\t\t\t lease_token=lease_token+1, attempt_count=attempt_count+1, updated_at=$1\n\t\t\tFROM claimable WHERE invocation.id=claimable.id\n\t\t\tRETURNING invocation.*`,\n\t\t\t[current, input.tenantId ?? null, input.spaceId ?? null, limit, input.workerId,\n\t\t\t leaseExpiresAt],\n\t\t);\n\t\treturn result.rows.map(toActionRecord);\n\t}\n\n\tasync updateLeasedActionInvocation(input: import(\"./types\").UpdateLeasedActionInvocationInput): Promise<boolean> {\n\t\tconst patch = input.patch;\n\t\tconst result = await this.sql.query(\n\t\t\t`UPDATE fabric_platform.action_invocations SET\n\t\t\t status=COALESCE($6,status), result=COALESCE($7::jsonb,result),\n\t\t\t error=CASE WHEN $8::boolean THEN $9 ELSE error END,\n\t\t\t authorization_reconciliation=CASE WHEN $10::boolean THEN $11::jsonb ELSE authorization_reconciliation END,\n\t\t\t adapter_reconciliation=CASE WHEN $12::boolean THEN $13::jsonb ELSE adapter_reconciliation END,\n\t\t\t pending_completion=CASE WHEN $14::boolean THEN $15::jsonb ELSE pending_completion END,\n\t\t\t completion_due_at=CASE WHEN $14::boolean THEN ($15::jsonb->>'dueAt')::timestamptz ELSE completion_due_at END,\n\t\t\t external_completion=CASE WHEN $16::boolean THEN $17::jsonb ELSE external_completion END,\n\t\t\t pending_state_transition=CASE WHEN $18::boolean THEN $19::jsonb ELSE pending_state_transition END,\n\t\t\t lease_owner=CASE WHEN ($15::jsonb IS NOT NULL AND $6='running') OR $6 IN ('waiting_for_approval','completed','failed','blocked_by_policy','reconciliation_required','validation_failed')\n\t\t\t THEN NULL ELSE lease_owner END,\n\t\t\t lease_expires_at=CASE WHEN ($15::jsonb IS NOT NULL AND $6='running') OR $6 IN ('waiting_for_approval','completed','failed','blocked_by_policy','reconciliation_required','validation_failed')\n\t\t\t THEN NULL ELSE lease_expires_at END,\n\t\t\t updated_at=now()\n\t\t\t WHERE id=$1 AND tenant_id=$2 AND space_id=$3\n\t\t\t AND status='running' AND lease_owner=$4 AND lease_token=$5\n\t\t\t RETURNING id`,\n\t\t\t[input.id, input.tenantId, input.spaceId, input.workerId, input.leaseToken,\n\t\t\t\tpatch.status ?? null,\n\t\t\t\tpatch.result === undefined ? null : JSON.stringify(patch.result),\n\t\t\t\tObject.hasOwn(patch, \"error\"), patch.error ?? null,\n\t\t\t\tObject.hasOwn(patch, \"authorizationReconciliation\"),\n\t\t\t\tpatch.authorizationReconciliation ? JSON.stringify(patch.authorizationReconciliation) : null,\n\t\t\t\tObject.hasOwn(patch, \"adapterReconciliation\"),\n\t\t\t\tpatch.adapterReconciliation ? JSON.stringify(patch.adapterReconciliation) : null,\n\t\t\t\tObject.hasOwn(patch, \"pendingCompletion\"),\n\t\t\t\tpatch.pendingCompletion ? JSON.stringify(patch.pendingCompletion) : null,\n\t\t\t\tObject.hasOwn(patch, \"externalCompletion\"),\n\t\t\t\tpatch.externalCompletion ? JSON.stringify(patch.externalCompletion) : null,\n\t\t\t\tObject.hasOwn(patch, \"pendingStateTransition\"),\n\t\t\t\tpatch.pendingStateTransition ? JSON.stringify(patch.pendingStateTransition) : null],\n\t\t);\n\t\treturn result.rows.length === 1;\n\t}\n\n\tasync renewActionInvocationLease(input: import(\"./types\").RenewActionInvocationLeaseInput): Promise<boolean> {\n\t\tconst current = input.now ?? new Date();\n\t\tconst result = await this.sql.query(\n\t\t\t`UPDATE fabric_platform.action_invocations\n\t\t\t SET lease_expires_at=$6,updated_at=$5\n\t\t\t WHERE id=$1 AND tenant_id=$2 AND space_id=$3\n\t\t\t AND status='running' AND lease_owner=$4 AND lease_token=$7\n\t\t\t AND lease_expires_at > $5\n\t\t\t RETURNING id`,\n\t\t\t[input.id, input.tenantId, input.spaceId, input.workerId, current,\n\t\t\t\tnew Date(current.getTime() + input.leaseDurationMs), input.leaseToken],\n\t\t);\n\t\treturn result.rows.length === 1;\n\t}\n\n\tasync listEvents(tenantId: string, spaceId: string): Promise<AssetEventEnvelope[]> {\n\t\tconst result = await this.sql.query<Record<string, unknown>>(\n\t\t\t`SELECT * FROM fabric_platform.asset_events\n\t\t\t WHERE tenant_id=$1 AND space_id=$2 ORDER BY sequence`,\n\t\t\t[tenantId, spaceId],\n\t\t);\n\t\treturn result.rows.map(toEventRecord);\n\t}\n\n\tasync getEvent(\n\t\tid: string,\n\t\ttenantId: string,\n\t\tspaceId: string,\n\t): Promise<AssetEventEnvelope | undefined> {\n\t\tconst result = await this.sql.query<Record<string, unknown>>(\n\t\t\t`SELECT * FROM fabric_platform.asset_events\n\t\t\t WHERE id=$1 AND tenant_id=$2 AND space_id=$3`,\n\t\t\t[id, tenantId, spaceId],\n\t\t);\n\t\treturn result.rows[0] ? toEventRecord(result.rows[0]) : undefined;\n\t}\n}\n\nfunction toAdapterRecord(row: Record<string, unknown>): AdapterInvocationRecord {\n\treturn {\n\t\tid: String(row.id),\n\t\tactionInvocationId: String(row.action_invocation_id),\n\t\ttenantId: String(row.tenant_id),\n\t\tspaceId: String(row.space_id),\n\t\tadapterType: String(row.adapter_type),\n\t\toperation: String(row.operation),\n\t\tvendor: String(row.vendor),\n\t\tstatus: String(row.status) as AdapterInvocationRecord[\"status\"],\n\t\tinput: row.input as Record<string, unknown>,\n\t\t...(row.output ? { output: row.output as Record<string, unknown> } : {}),\n\t\t...(row.error ? { error: String(row.error) } : {}),\n\t\t...(row.reconciliation ? { reconciliation: row.reconciliation as AdapterInvocationRecord[\"reconciliation\"] } : {}),\n\t\tattempt: Number(row.attempt),\n\t\tcreatedAt: new Date(row.created_at as string | Date),\n\t\tupdatedAt: new Date(row.updated_at as string | Date),\n\t};\n}\n\nfunction toPendingCompletion(value: Record<string, unknown>): NonNullable<ActionInvocationRecord[\"pendingCompletion\"]> {\n\treturn {\n\t\t...(value as unknown as NonNullable<ActionInvocationRecord[\"pendingCompletion\"]>),\n\t\tacceptedAt: new Date(value.acceptedAt as string),\n\t\t...(value.dueAt ? { dueAt: new Date(value.dueAt as string) } : {}),\n\t\t...(value.parkedAt ? { parkedAt: new Date(value.parkedAt as string) } : {}),\n\t\t...(value.overdueAt ? { overdueAt: new Date(value.overdueAt as string) } : {}),\n\t};\n}\n\nfunction toExternalCompletion(value: Record<string, unknown>): NonNullable<ActionInvocationRecord[\"externalCompletion\"]> {\n\treturn {\n\t\t...(value as unknown as NonNullable<ActionInvocationRecord[\"externalCompletion\"]>),\n\t\trecordedAt: new Date(value.recordedAt as string),\n\t};\n}\n\nfunction toActionRecord(row: Record<string, unknown>): ActionInvocationRecord {\n\treturn {\n\t\tid: String(row.id), tenantId: String(row.tenant_id), spaceId: String(row.space_id),\n\t\tactionId: String(row.action_id) as ActionInvocationRecord[\"actionId\"],\n\t\tactionVersion: Number(row.action_version),\n\t\tactorId: String(row.actor_id),\n\t\tactorType: String(row.actor_type) as ActionInvocationRecord[\"actorType\"],\n\t\tstatus: String(row.status) as ActionInvocationRecord[\"status\"],\n\t\tparameters: row.parameters as Record<string, unknown>,\n\t\tresult: row.result as Record<string, unknown>, correlationId: String(row.correlation_id),\n\t\t...(row.causation_id ? { causationId: String(row.causation_id) } : {}),\n\t\t...(row.idempotency_key ? { idempotencyKey: String(row.idempotency_key) } : {}),\n\t\t...(row.parameter_digest ? { parameterDigest: String(row.parameter_digest) } : {}),\n\t\t...(row.parameter_digest_algorithm ? { parameterDigestAlgorithm: String(row.parameter_digest_algorithm) as ActionInvocationRecord[\"parameterDigestAlgorithm\"] } : {}),\n\t\t...(row.idempotency_actor_id ? { idempotencyActorId: String(row.idempotency_actor_id) } : {}),\n\t\t...(row.idempotency_authorization_binding_id ? { idempotencyAuthorizationBindingId: String(row.idempotency_authorization_binding_id) } : {}),\n\t\t...(row.invocation_provenance ? { provenance: row.invocation_provenance as NonNullable<ActionInvocationRecord[\"provenance\"]> } : {}),\n\t\t...(row.authorization_binding ? { authorizationBinding: row.authorization_binding as NonNullable<ActionInvocationRecord[\"authorizationBinding\"]> } : {}),\n\t\t...(row.execution_reason ? { executionReason: String(row.execution_reason) } : {}),\n\t\t...(row.authorization_reconciliation ? { authorizationReconciliation: row.authorization_reconciliation as NonNullable<ActionInvocationRecord[\"authorizationReconciliation\"]> } : {}),\n\t\t...(row.adapter_reconciliation ? { adapterReconciliation: row.adapter_reconciliation as NonNullable<ActionInvocationRecord[\"adapterReconciliation\"]> } : {}),\n\t\t...(row.pending_state_transition ? { pendingStateTransition: row.pending_state_transition as NonNullable<ActionInvocationRecord[\"pendingStateTransition\"]> } : {}),\n\t\t...(row.pending_completion ? { pendingCompletion: toPendingCompletion(row.pending_completion as Record<string, unknown>) } : {}),\n\t\t...(row.external_completion ? { externalCompletion: toExternalCompletion(row.external_completion as Record<string, unknown>) } : {}),\n\t\t...(row.authorization_binding_id\n\t\t\t? { authorizationBindingId: String(row.authorization_binding_id) }\n\t\t\t: {}),\n\t\tattemptCount: Number(row.attempt_count ?? 0),\n\t\tleaseToken: Number(row.lease_token ?? 0),\n\t\t...(row.lease_owner ? { leaseOwner: String(row.lease_owner) } : {}),\n\t\t...(row.lease_expires_at\n\t\t\t? { leaseExpiresAt: new Date(row.lease_expires_at as string | Date) }\n\t\t\t: {}),\n\t\t...(row.hitl_route\n\t\t\t? { hitlRoute: String(row.hitl_route) as ActionInvocationRecord[\"hitlRoute\"] }\n\t\t\t: {}),\n\t\t...(row.hitl_risk_tier\n\t\t\t? { hitlRiskTier: String(row.hitl_risk_tier) as ActionInvocationRecord[\"hitlRiskTier\"] }\n\t\t\t: {}),\n\t\t...(row.hitl_reason ? { hitlReason: String(row.hitl_reason) } : {}),\n\t\t...(row.hitl_policy_version\n\t\t\t? { hitlPolicyVersion: String(row.hitl_policy_version) }\n\t\t\t: {}),\n\t\t...(row.approval_decision\n\t\t\t? { approvalDecision: toApprovalDecision(row.approval_decision) }\n\t\t\t: {}),\n\t\t...(row.mutation_footprint\n\t\t\t? { mutationFootprint: row.mutation_footprint as NonNullable<ActionInvocationRecord[\"mutationFootprint\"]> }\n\t\t\t: {}),\n\t\t...(row.execution_principal\n\t\t\t? { executionPrincipal: row.execution_principal as NonNullable<ActionInvocationRecord[\"executionPrincipal\"]> }\n\t\t\t: {}),\n\t\t...(row.runtime_evidence\n\t\t\t? { runtimeEvidence: row.runtime_evidence as NonNullable<ActionInvocationRecord[\"runtimeEvidence\"]> }\n\t\t\t: {}),\n\t\t...(row.admitted_at ? { admittedAt: new Date(row.admitted_at as string | Date) } : {}),\n\t\t...(row.error ? { error: String(row.error) } : {}),\n\t\tcreatedAt: new Date(row.created_at as string | Date),\n\t\tupdatedAt: new Date(row.updated_at as string | Date),\n\t};\n}\n\nfunction toObligationRecord(row: Record<string, unknown>): PolicyObligationRecord {\n\treturn {\n\t\tid: String(row.id), actionInvocationId: String(row.action_invocation_id),\n\t\ttenantId: String(row.tenant_id), spaceId: String(row.space_id), type: String(row.type),\n\t\tstatus: String(row.status) as PolicyObligationRecord[\"status\"], required: Boolean(row.required),\n\t\t...(row.description ? { description: String(row.description) } : {}),\n\t\t...(row.evidence_references ? { evidenceReferences: row.evidence_references as NonNullable<PolicyObligationRecord[\"evidenceReferences\"]> } : {}),\n\t\t...(row.metadata ? { metadata: row.metadata as Record<string, unknown> } : {}),\n\t\tcreatedAt: new Date(row.created_at as string | Date), updatedAt: new Date(row.updated_at as string | Date),\n\t};\n}\n\nfunction toAttestationRecord(row: Record<string, unknown>): ExecutionAttestationRecord {\n\tconst attestation = row.attestation as Omit<ExecutionAttestationRecord, \"id\" | \"actionInvocationId\" | \"tenantId\" | \"spaceId\" | \"adapterInvocationId\" | \"recordedAt\">;\n\treturn {\n\t\t...attestation, id: String(row.id), actionInvocationId: String(row.action_invocation_id),\n\t\ttenantId: String(row.tenant_id), spaceId: String(row.space_id),\n\t\t...(row.adapter_invocation_id ? { adapterInvocationId: String(row.adapter_invocation_id) } : {}),\n\t\trecordedAt: new Date(row.recorded_at as string | Date),\n\t};\n}\n\nfunction toApprovalDecision(value: unknown): NonNullable<ActionInvocationRecord[\"approvalDecision\"]> {\n\tconst decision = value as Record<string, unknown>;\n\treturn {\n\t\tapproved: Boolean(decision.approved),\n\t\tapproverId: String(decision.approverId),\n\t\tapproverType: String(decision.approverType) as NonNullable<\n\t\t\tActionInvocationRecord[\"approvalDecision\"]\n\t\t>[\"approverType\"],\n\t\t...(decision.reason ? { reason: String(decision.reason) } : {}),\n\t\t...(decision.editsReference\n\t\t\t? { editsReference: String(decision.editsReference) }\n\t\t\t: {}),\n\t\tdecidedAt: new Date(decision.decidedAt as string | Date),\n\t};\n}\n\nfunction toEventRecord(row: Record<string, unknown>): AssetEventEnvelope {\n\treturn {\n\t\tid: String(row.id), tenantId: String(row.tenant_id), spaceId: String(row.space_id),\n\t\teventType: String(row.event_type), eventSchemaVersion: Number(row.event_schema_version),\n\t\tsubjectType: String(row.subject_type), subjectId: String(row.subject_id),\n\t\tactorId: String(row.actor_id), actorType: String(row.actor_type),\n\t\t...(row.action_invocation_id\n\t\t\t? { actionInvocationId: String(row.action_invocation_id) }\n\t\t\t: {}),\n\t\tpayload: row.payload, sequence: Number(row.sequence),\n\t\toccurredAt: new Date(row.occurred_at as string | Date),\n\t\trecordedAt: new Date(row.recorded_at as string | Date),\n\t\tcorrelationId: String(row.correlation_id),\n\t\t...(row.causation_id ? { causationId: String(row.causation_id) } : {}),\n\t\t...(row.provenance ? { provenance: row.provenance as NonNullable<AssetEventEnvelope[\"provenance\"]> } : {}),\n\t\t...(row.consistency ? { consistency: row.consistency as NonNullable<AssetEventEnvelope[\"consistency\"]> } : {}),\n\t};\n}\n\nfunction toOutboxRecord(row: Record<string, unknown>): OutboxRecord {\n\tconst event = row.event as Record<string, unknown>;\n\t// NULL is a row written before migration 4 (legacy). The column, not the JSON, decides whether\n\t// actor identity is hydrated, so a row that was not opted in never yields an actor.\n\tconst actorDisclosure = row.actor_disclosure === \"included\" || row.actor_disclosure === \"suppressed\"\n\t\t? row.actor_disclosure\n\t\t: undefined;\n\tconst actorIncluded = actorDisclosure === \"included\";\n\treturn {\n\t\tid: String(row.id),\n\t\ttenantId: String(row.tenant_id),\n\t\tspaceId: String(row.space_id),\n\t\t...(actorDisclosure ? { actorDisclosure } : {}),\n\t\tevent: {\n\t\t\teventId: String(event.eventId),\n\t\t\teventType: String(event.eventType),\n\t\t\teventSchemaVersion: Number(event.eventSchemaVersion),\n\t\t\ttenantId: String(event.tenantId),\n\t\t\tspaceId: String(event.spaceId),\n\t\t\tsubjectType: String(event.subjectType),\n\t\t\tsubjectId: String(event.subjectId),\n\t\t\tsequence: Number(event.sequence),\n\t\t\t...(event.actionInvocationId ? { actionInvocationId: String(event.actionInvocationId) } : {}),\n\t\t\tcorrelationId: String(event.correlationId),\n\t\t\t...(event.causationId ? { causationId: String(event.causationId) } : {}),\n\t\t\t...(actorIncluded && event.actorId ? { actorId: String(event.actorId) } : {}),\n\t\t\t...(actorIncluded && event.actorType ? { actorType: String(event.actorType) } : {}),\n\t\t\t...(event.provenance ? { provenance: event.provenance as NonNullable<EnterpriseEventEnvelope[\"provenance\"]> } : {}),\n\t\t\t...(event.consistency ? { consistency: event.consistency as NonNullable<EnterpriseEventEnvelope[\"consistency\"]> } : {}),\n\t\t\toccurredAt: new Date(event.occurredAt as string | Date),\n\t\t\trecordedAt: new Date(event.recordedAt as string | Date),\n\t\t\tproducerModuleVersion: String(event.producerModuleVersion),\n\t\t\tpayloadClassification: String(event.payloadClassification) as OutboxRecord[\"event\"][\"payloadClassification\"],\n\t\t\t...(event.traceContext ? { traceContext: event.traceContext as Record<string, string> } : {}),\n\t\t\tpayload: event.payload,\n\t\t},\n\t\tstatus: String(row.status) as OutboxStatus,\n\t\tattemptCount: Number(row.attempt_count),\n\t\tavailableAt: new Date(row.available_at as string | Date),\n\t\t...(row.lease_owner ? { leaseOwner: String(row.lease_owner) } : {}),\n\t\t...(row.lease_expires_at ? { leaseExpiresAt: new Date(row.lease_expires_at as string | Date) } : {}),\n\t\tleaseToken: Number(row.lease_token ?? 0),\n\t\t...(row.last_error ? { lastError: String(row.last_error) } : {}),\n\t\tcreatedAt: new Date(row.created_at as string | Date),\n\t\t...(row.published_at ? { publishedAt: new Date(row.published_at as string | Date) } : {}),\n\t};\n}\n\nfunction toOutboxRequeueRecord(row: Record<string, unknown>, prefix: string): OutboxRequeueRecord {\n\tconst field = (name: string) => row[`${prefix}${name}`];\n\tconst priorLastError = field(\"prior_last_error\");\n\treturn {\n\t\tid: String(field(\"id\")),\n\t\toutboxId: String(field(\"outbox_id\")),\n\t\ttenantId: String(field(\"tenant_id\")),\n\t\tspaceId: String(field(\"space_id\")),\n\t\teventId: String(field(\"event_id\")),\n\t\tactorId: String(field(\"actor_id\")),\n\t\tactorType: String(field(\"actor_type\")) as OutboxRequeueRecord[\"actorType\"],\n\t\treason: String(field(\"reason\")),\n\t\trequeuedAt: new Date(field(\"requeued_at\") as string | Date),\n\t\tavailableAt: new Date(field(\"available_at\") as string | Date),\n\t\tpriorAttemptCount: Number(field(\"prior_attempt_count\")),\n\t\t...(priorLastError !== null && priorLastError !== undefined ? { priorLastError: String(priorLastError) } : {}),\n\t\tpriorAvailableAt: new Date(field(\"prior_available_at\") as string | Date),\n\t\tpriorLeaseToken: Number(field(\"prior_lease_token\")),\n\t};\n}\n","import { isRetryableExecutionError } from \"@fabricorg/platform\";\nimport type {\n\tActionInvocationRecord,\n\tPlatformActionDispatcher,\n\tPlatformActionWorkerCycleResult,\n\tPlatformActionWorkerOptions,\n} from \"./types\";\nimport {\n\temitPlatformHostTelemetry,\n\tPLATFORM_HOST_METRIC_NAMES,\n\ttype PlatformHostTelemetry,\n\ttype PlatformHostTelemetryAttribute,\n} from \"./observability\";\n\nconst DEFAULT_BATCH_SIZE = 10;\nconst DEFAULT_LEASE_DURATION_MS = 5 * 60_000;\nconst DEFAULT_POLL_INTERVAL_MS = 1_000;\n\n/**\n * Durable store-backed dispatch: the pending invocation row is the queue item.\n * Repeated dispatches are safe because the workflow id is stable per invocation.\n */\nexport function createStoreBackedActionDispatcher(): PlatformActionDispatcher {\n\treturn {\n\t\tdispatch: async (input) => ({ workflowId: input.workflowId }),\n\t};\n}\n\n/** Claim and execute one bounded batch. Safe to run concurrently across workers. */\nexport async function runPlatformActionWorkerCycle<TDb>(\n\toptions: PlatformActionWorkerOptions<TDb>,\n): Promise<PlatformActionWorkerCycleResult> {\n\tconst leaseDurationMs = options.leaseDurationMs ?? DEFAULT_LEASE_DURATION_MS;\n\temitWorkerTelemetry(options.telemetry, \"worker.cycle.started\", options.workerId);\n\t// Handoffs past their deadline are findings, not work to claim. The sweep\n\t// runs before the claim so a failure in it strands nothing, and so an\n\t// overdue callback is surfaced even on a cycle that claims nothing.\n\tif (options.sweepOverdueCompletions !== false && typeof options.host.reconcileOverdueCompletions === \"function\") {\n\t\ttry {\n\t\t\tawait options.host.reconcileOverdueCompletions({\n\t\t\t\t...(options.tenantId ? { tenantId: options.tenantId } : {}),\n\t\t\t\t...(options.spaceId ? { spaceId: options.spaceId } : {}),\n\t\t\t});\n\t\t} catch (error) {\n\t\t\toptions.onError?.(error);\n\t\t}\n\t}\n\tlet claimed: ActionInvocationRecord[];\n\ttry {\n\t\tclaimed = await options.store.claimActionInvocations({\n\t\t\tworkerId: options.workerId,\n\t\t\tlimit: options.batchSize ?? DEFAULT_BATCH_SIZE,\n\t\t\tleaseDurationMs,\n\t\t\t...(options.tenantId ? { tenantId: options.tenantId } : {}),\n\t\t\t...(options.spaceId ? { spaceId: options.spaceId } : {}),\n\t\t});\n\t} catch (error) {\n\t\temitWorkerTelemetry(options.telemetry, \"worker.cycle.failed\", options.workerId);\n\t\tthrow error;\n\t}\n\tfor (const invocation of claimed) {\n\t\temitPlatformHostTelemetry(options.telemetry, {\n\t\t\tkind: \"event\",\n\t\t\tname: \"invocation.lease_claimed\",\n\t\t\tmetricName: PLATFORM_HOST_METRIC_NAMES.invocationLeaseClaimed,\n\t\t\toccurredAt: new Date(),\n\t\t\ttenantId: invocation.tenantId,\n\t\t\tspaceId: invocation.spaceId,\n\t\t\tattributes: { attempt: invocation.attemptCount },\n\t\t});\n\t}\n\tlet completed = 0;\n\tlet failed = 0;\n\tlet waitingForApproval = 0;\n\tlet deferred = 0;\n\tfor (const invocation of claimed) {\n\t\tconst stopHeartbeat = startLeaseHeartbeat(options, invocation, leaseDurationMs);\n\t\ttry {\n\t\t\tconst result = await options.host.executeInvocation(\n\t\t\t\tinvocation.id,\n\t\t\t\tinvocation.tenantId,\n\t\t\t\tinvocation.spaceId,\n\t\t\t\t{ leaseOwner: options.workerId, leaseToken: invocation.leaseToken },\n\t\t\t);\n\t\t\tif (result.status === \"completed\") completed += 1;\n\t\t\telse if (result.status === \"waiting_for_approval\") waitingForApproval += 1;\n\t\t\telse failed += 1;\n\t\t} catch (error) {\n\t\t\tif (isRetryableExecutionError(error)) deferred += 1;\n\t\t\telse failed += 1;\n\t\t\toptions.onError?.(error, invocation);\n\t\t} finally {\n\t\t\tawait stopHeartbeat();\n\t\t}\n\t}\n\tconst result = {\n\t\tclaimed: claimed.length,\n\t\tcompleted,\n\t\tfailed,\n\t\t...(waitingForApproval > 0 ? { waitingForApproval } : {}),\n\t\t...(deferred > 0 ? { deferred } : {}),\n\t};\n\temitWorkerTelemetry(options.telemetry, \"worker.cycle.completed\", options.workerId, result);\n\treturn result;\n}\n\nfunction startLeaseHeartbeat<TDb>(\n\toptions: PlatformActionWorkerOptions<TDb>,\n\tinvocation: ActionInvocationRecord,\n\tleaseDurationMs: number,\n): () => Promise<void> {\n\tif (!invocation?.leaseToken) return async () => undefined;\n\tconst intervalMs = options.leaseRenewalIntervalMs ??\n\t\tMath.max(1, Math.floor(leaseDurationMs / 3));\n\tlet stopped = false;\n\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\tlet running: Promise<void> | undefined;\n\tconst schedule = () => {\n\t\tif (!stopped) timer = setTimeout(tick, intervalMs);\n\t};\n\tconst tick = () => {\n\t\trunning = options.store.renewActionInvocationLease({\n\t\t\tid: invocation.id,\n\t\t\ttenantId: invocation.tenantId,\n\t\t\tspaceId: invocation.spaceId,\n\t\t\tworkerId: options.workerId,\n\t\t\tleaseToken: invocation.leaseToken!,\n\t\t\tleaseDurationMs,\n\t\t}).then((renewed) => {\n\t\t\tif (!renewed) options.onError?.(\n\t\t\t\tnew Error(`Invocation lease lost: ${invocation.id}`),\n\t\t\t\tinvocation,\n\t\t\t);\n\t\t}).catch((error: unknown) => options.onError?.(error, invocation))\n\t\t\t.finally(schedule);\n\t};\n\tschedule();\n\treturn async () => {\n\t\tstopped = true;\n\t\tif (timer) clearTimeout(timer);\n\t\tawait running;\n\t};\n}\n\n/** Poll until aborted. Each iteration is bounded and waits without busy-spinning. */\nexport async function runPlatformActionWorker<TDb>(\n\toptions: PlatformActionWorkerOptions<TDb>,\n): Promise<void> {\n\twhile (!options.signal?.aborted) {\n\t\ttry {\n\t\t\tawait runPlatformActionWorkerCycle(options);\n\t\t} catch (error) {\n\t\t\toptions.onError?.(error);\n\t\t}\n\t\tawait abortableDelay(options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS, options.signal);\n\t}\n}\n\nasync function abortableDelay(milliseconds: number, signal?: AbortSignal): Promise<void> {\n\tif (signal?.aborted) return;\n\tawait new Promise<void>((resolve) => {\n\t\tconst timeout = setTimeout(resolve, milliseconds);\n\t\tsignal?.addEventListener(\n\t\t\t\"abort\",\n\t\t\t() => {\n\t\t\t\tclearTimeout(timeout);\n\t\t\t\tresolve();\n\t\t\t},\n\t\t\t{ once: true },\n\t\t);\n\t});\n}\n\nfunction emitWorkerTelemetry(\n\ttelemetry: PlatformHostTelemetry | undefined,\n\tname: \"worker.cycle.started\" | \"worker.cycle.completed\" | \"worker.cycle.failed\",\n\tworkerId: string,\n\tattributes?: Record<string, PlatformHostTelemetryAttribute>,\n): void {\n\tconst metricName = name === \"worker.cycle.started\"\n\t\t? PLATFORM_HOST_METRIC_NAMES.workerCyclesStarted\n\t\t: name === \"worker.cycle.completed\"\n\t\t\t? PLATFORM_HOST_METRIC_NAMES.workerCyclesCompleted\n\t\t\t: PLATFORM_HOST_METRIC_NAMES.workerCyclesFailed;\n\temitPlatformHostTelemetry(telemetry, {\n\t\tkind: \"event\",\n\t\tname,\n\t\tmetricName,\n\t\toccurredAt: new Date(),\n\t\tattributes: { workerId, ...attributes },\n\t});\n}\n","import { digestParameters } from \"./command-identity\";\nimport type {\n\tActionInvocationRecord,\n\tAtomicMutationPlatformHostStore,\n\tPlatformHostStore,\n} from \"./types\";\n\nconst TERMINAL_PARENT_STATUSES = new Set<ActionInvocationRecord[\"status\"]>([\n\t\"completed\",\n\t\"failed\",\n\t\"blocked_by_policy\",\n\t\"reconciliation_required\",\n\t\"validation_failed\",\n]);\n\ninterface HostSagaParentLifecycleIdentity {\n\t/** Stable identity shared by every retry of the same lifecycle transition. */\n\tlifecycleId?: string;\n}\n\n/**\n * Durable record of a single step completing within a saga parent.\n * Structurally compatible with {@link import(\"@fabricorg/platform-temporal\").SagaParentProgressRecord}.\n */\nexport interface HostSagaParentProgressRecord {\n\tstepId: string;\n\tindex: number;\n\ttotal: number;\n\tcompletedAt: string;\n}\n\nexport interface HostSagaParentProgressInput extends HostSagaParentLifecycleIdentity {\n\tparentInvocationId: string;\n\ttenantId: string;\n\tspaceId: string;\n\tprogress: HostSagaParentProgressRecord;\n}\n\nexport interface HostSagaParentApprovalInput extends HostSagaParentLifecycleIdentity {\n\tparentInvocationId: string;\n\ttenantId: string;\n\tspaceId: string;\n\tstepId: string;\n\tapprovalId: string;\n\treason: string;\n}\n\nexport interface HostSagaParentCancellationInput extends HostSagaParentLifecycleIdentity {\n\tparentInvocationId: string;\n\ttenantId: string;\n\tspaceId: string;\n\treason: string;\n\tactorId: string;\n}\n\nexport interface HostSagaParentCompletionInput extends HostSagaParentLifecycleIdentity {\n\tparentInvocationId: string;\n\ttenantId: string;\n\tspaceId: string;\n\tresult: Record<string, unknown>;\n}\n\nexport interface HostSagaParentFailureInput extends HostSagaParentLifecycleIdentity {\n\tparentInvocationId: string;\n\ttenantId: string;\n\tspaceId: string;\n\terror: string;\n\tcompensation: HostCompensationRecord[];\n}\n\nexport interface HostCompensationRecord {\n\tstepId: string;\n\tactionId: string;\n\terror?: string;\n}\n\n/**\n * Durable saga parent lifecycle contract backed by a Platform Host store.\n *\n * Structurally compatible with {@link import(\"@fabricorg/platform-temporal\").SagaParentLifecycle}\n * so an instance can be passed directly to\n * {@link import(\"@fabricorg/platform-temporal\").createSagaParentActivities}.\n *\n * Every transition is durable: the parent invocation row is the authoritative\n * state, and lifecycle events are the audit trail. A worker that rolls over\n * mid-saga can create a fresh adapter pointing at the same store and observe\n * the persisted progress, approval park, cancellation, completion, or failure\n * without in-memory state.\n */\nexport interface HostSagaParentLifecycle {\n\trecordProgress(input: HostSagaParentProgressInput): Promise<void>;\n\tparkApproval(input: HostSagaParentApprovalInput): Promise<void>;\n\tcancel(input: HostSagaParentCancellationInput): Promise<void>;\n\tcomplete(input: HostSagaParentCompletionInput): Promise<void>;\n\tfail(input: HostSagaParentFailureInput): Promise<void>;\n}\n\nexport interface CreateDurableSagaParentLifecycleOptions<TDb> {\n\tstore: PlatformHostStore<TDb>;\n\t/** Optional clock for deterministic tests. */\n\tnow?: () => Date;\n}\n\n/**\n * Create a {@link HostSagaParentLifecycle} backed by a Platform Host store.\n *\n * The parent invocation must already exist in the store (created by\n * `submitAction` or `createActionInvocation`). Each method appends a typed\n * lifecycle event and transitions the parent invocation to the appropriate\n * status so a fresh worker can observe the persisted state after a rollover.\n */\nexport function createDurableSagaParentLifecycle<TDb>(\n\toptions: CreateDurableSagaParentLifecycleOptions<TDb>,\n): HostSagaParentLifecycle {\n\tconst store = options.store;\n\tconst now = options.now ?? (() => new Date());\n\tconst transactionWithEvents = (\n\t\tstore as PlatformHostStore<TDb> & Partial<AtomicMutationPlatformHostStore<TDb>>\n\t).transactionWithEvents?.bind(store);\n\tif (!transactionWithEvents) {\n\t\tthrow new Error(\n\t\t\t\"Durable saga parent lifecycle requires store.transactionWithEvents for atomic event and parent updates.\",\n\t\t);\n\t}\n\tconst runInTransaction = transactionWithEvents;\n\n\tasync function applyLifecycleTransition(\n\t\tinput: {\n\t\t\ttenantId: string;\n\t\t\tspaceId: string;\n\t\t\tparentInvocationId: string;\n\t\t\tlifecycleId?: string;\n\t\t},\n\t\tlifecycleId: string,\n\t\teventType: string,\n\t\tpayload: Record<string, unknown>,\n\t\tpatch?: Partial<Pick<ActionInvocationRecord, \"status\" | \"result\" | \"error\">>,\n\t): Promise<void> {\n\t\tconst eventId = `sagapar_${digestParameters({\n\t\t\tparentInvocationId: input.parentInvocationId,\n\t\t\tlifecycleId,\n\t\t}).slice(0, 40)}`;\n\t\tawait runInTransaction(async (transaction) => {\n\t\t\tif (!transaction.getActionInvocationForUpdate) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Durable saga parent lifecycle requires transaction.getActionInvocationForUpdate for serialization.\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (!transaction.getEvent) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Durable saga parent lifecycle requires transaction.getEvent for identity-scoped evidence lookup.\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst parent = await transaction.getActionInvocationForUpdate(\n\t\t\t\tinput.parentInvocationId,\n\t\t\t\tinput.tenantId,\n\t\t\t\tinput.spaceId,\n\t\t\t);\n\t\t\tif (!parent) {\n\t\t\t\tthrow new Error(`Saga parent invocation not found: ${input.parentInvocationId}`);\n\t\t\t}\n\t\t\tconst prior = await transaction.getEvent(eventId, input.tenantId, input.spaceId);\n\t\t\tif (prior) {\n\t\t\t\tif (prior.eventType !== eventType ||\n\t\t\t\t\tdigestParameters(prior.payload) !== digestParameters(payload)) {\n\t\t\t\t\tthrow new Error(`Saga lifecycle identity ${lifecycleId} has contradictory evidence.`);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (TERMINAL_PARENT_STATUSES.has(parent.status)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Saga parent invocation ${input.parentInvocationId} is already terminal (${parent.status}).`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst sequence = await transaction.nextEventSequence(input.tenantId, input.spaceId);\n\t\t\tconst timestamp = now();\n\t\t\tawait transaction.appendEvent({\n\t\t\t\tid: eventId,\n\t\t\t\ttenantId: input.tenantId,\n\t\t\t\tspaceId: input.spaceId,\n\t\t\t\teventType,\n\t\t\t\teventSchemaVersion: 1,\n\t\t\t\tsubjectType: \"ActionInvocation\",\n\t\t\t\tsubjectId: input.parentInvocationId,\n\t\t\t\tactorId: \"system\",\n\t\t\t\tactorType: \"system\",\n\t\t\t\tactionInvocationId: input.parentInvocationId,\n\t\t\t\tpayload,\n\t\t\t\tsequence,\n\t\t\t\toccurredAt: timestamp,\n\t\t\t\trecordedAt: timestamp,\n\t\t\t\tcorrelationId: input.parentInvocationId,\n\t\t\t\tcausationId: lifecycleId,\n\t\t\t});\n\t\t\tif (patch) {\n\t\t\t\tawait transaction.updateActionInvocation(\n\t\t\t\t\tinput.parentInvocationId,\n\t\t\t\t\tinput.tenantId,\n\t\t\t\t\tinput.spaceId,\n\t\t\t\t\tpatch,\n\t\t\t\t);\n\t\t\t}\n\t\t});\n\t}\n\n\treturn {\n\t\tasync recordProgress(input) {\n\t\t\tawait applyLifecycleTransition(\n\t\t\t\tinput,\n\t\t\t\tinput.lifecycleId ?? `host:${input.parentInvocationId}:progress:${input.progress.stepId}:${input.progress.index}`,\n\t\t\t\t\"SagaParentProgress\",\n\t\t\t\t{\n\t\t\t\t\tstepId: input.progress.stepId,\n\t\t\t\t\tindex: input.progress.index,\n\t\t\t\t\ttotal: input.progress.total,\n\t\t\t\t\tcompletedAt: input.progress.completedAt,\n\t\t\t\t},\n\t\t\t);\n\t\t},\n\n\t\tasync parkApproval(input) {\n\t\t\tawait applyLifecycleTransition(\n\t\t\t\tinput,\n\t\t\t\tinput.lifecycleId ?? `host:${input.parentInvocationId}:approval:${input.approvalId}`,\n\t\t\t\t\"SagaParentApprovalParked\",\n\t\t\t\t{\n\t\t\t\t\tstepId: input.stepId,\n\t\t\t\t\tapprovalId: input.approvalId,\n\t\t\t\t\treason: input.reason,\n\t\t\t\t},\n\t\t\t\t{ status: \"waiting_for_approval\" },\n\t\t\t);\n\t\t},\n\n\t\tasync cancel(input) {\n\t\t\tawait applyLifecycleTransition(\n\t\t\t\tinput,\n\t\t\t\tinput.lifecycleId ?? `host:${input.parentInvocationId}:cancel`,\n\t\t\t\t\"SagaParentCancelled\",\n\t\t\t\t{ reason: input.reason, actorId: input.actorId },\n\t\t\t\t{ status: \"failed\", error: `Saga cancelled: ${input.reason}` },\n\t\t\t);\n\t\t},\n\n\t\tasync complete(input) {\n\t\t\tawait applyLifecycleTransition(\n\t\t\t\tinput,\n\t\t\t\tinput.lifecycleId ?? `host:${input.parentInvocationId}:complete`,\n\t\t\t\t\"SagaParentCompleted\",\n\t\t\t\t{ result: input.result },\n\t\t\t\t{ status: \"completed\", result: input.result },\n\t\t\t);\n\t\t},\n\n\t\tasync fail(input) {\n\t\t\tawait applyLifecycleTransition(\n\t\t\t\tinput,\n\t\t\t\tinput.lifecycleId ?? `host:${input.parentInvocationId}:fail`,\n\t\t\t\t\"SagaParentFailed\",\n\t\t\t\t{ error: input.error, compensation: input.compensation },\n\t\t\t\t{ status: \"failed\", error: input.error },\n\t\t\t);\n\t\t},\n\t};\n}\n","import type { ActionId, ActorType } from \"@fabricorg/platform\";\nimport type { AdapterInvocationScope, GovernedActionHost, RecoverablePlatformHostStore } from \"./types\";\n\n// ── Tenant isolation conformance ────────────────────────────────────────────\n//\n// Every other seam ships an executable definition of correct. Isolation was\n// the guarantee every document asked for and every vertical tested itself.\n// These checks prove the kernel's part of it: a tenant's scope is a key on\n// the reads and writes these checks probe — invocations, claims, completions,\n// events, adapter checkpoints — not a filter somebody remembered to add. What the\n// vertical's identity adapter derives into that scope is the identity port's\n// business, and its suite; what a projection authorizes is the projection\n// host's authorize hook, and the subject may lend one for the projection check.\n\nexport interface TenantIsolationScope {\n\ttenantId: string;\n\tspaceId: string;\n\tactorId: string;\n\tactorType: ActorType;\n}\n\nexport interface TenantIsolationSubject<TDb = unknown> {\n\thost: GovernedActionHost;\n\tstore: RecoverablePlatformHostStore<TDb>;\n\t/** A governed action registered on the host, and parameters it accepts. */\n\tactionId: ActionId;\n\tparameters?: Record<string, unknown>;\n\t/** Two scopes in different tenants. */\n\tours: TenantIsolationScope;\n\ttheirs: TenantIsolationScope;\n\t/**\n\t * Optional: a governed read the subject exposes, scoped as the projection\n\t * host scopes it. Returns what a viewer in `scope` sees for the view. Every\n\t * row must carry the `tenantId` it belongs to, so the check can tell a row\n\t * of ours from a row of theirs that merely looks the same; two tenants may\n\t * legitimately hold equal-looking rows.\n\t */\n\tread?(scope: TenantIsolationScope): Promise<{ allowed: boolean; rows: readonly { tenantId: string }[] }>;\n\t/**\n\t * Optional: put the host and store back to a known state before a check.\n\t * The checks tolerate accumulated state, and each retires any row it\n\t * creates directly, so this exists for subjects whose store is shared.\n\t */\n\treset?(): Promise<void> | void;\n}\n\nexport interface TenantIsolationCheck {\n\tid:\n\t\t| \"fabric.tenancy.invocation-scoped-read.v1\"\n\t\t| \"fabric.tenancy.idempotency-key-scoped.v1\"\n\t\t| \"fabric.tenancy.events-scoped.v1\"\n\t\t| \"fabric.tenancy.worker-claim-scoped.v1\"\n\t\t| \"fabric.tenancy.completion-scoped.v1\"\n\t\t| \"fabric.tenancy.projection-scoped.v1\"\n\t\t| \"fabric.tenancy.adapter-invocation-read-scoped.v1\"\n\t\t| \"fabric.tenancy.adapter-invocation-write-scoped.v1\";\n\trun(subject: TenantIsolationSubject): Promise<string[]>;\n}\n\nexport interface TenantIsolationResult {\n\tpassed: boolean;\n\tchecks: Array<{ id: TenantIsolationCheck[\"id\"]; status: \"passed\" | \"failed\" | \"skipped\"; evidence: string[]; error?: string }>;\n}\n\nfunction fail(message: string): never {\n\tthrow new Error(message);\n}\n\nfunction submitInput(subject: TenantIsolationSubject, scope: TenantIsolationScope, idempotencyKey: string) {\n\treturn {\n\t\tactionId: subject.actionId,\n\t\tparameters: subject.parameters ?? {},\n\t\ttenantId: scope.tenantId,\n\t\tspaceId: scope.spaceId,\n\t\tactorId: scope.actorId,\n\t\tactorType: scope.actorType,\n\t\tidempotencyKey,\n\t};\n}\n\nasync function adapterProbe(subject: TenantIsolationSubject) {\n\tawait subject.reset?.();\n\tif (subject.ours.tenantId === subject.theirs.tenantId) fail(\"the two scopes must be in different tenants\");\n\tconst suffix = globalThis.crypto.randomUUID();\n\tconst scope: AdapterInvocationScope = {\n\t\ttenantId: subject.ours.tenantId, spaceId: `iso-probe-${suffix}`, actionInvocationId: `iso_act_${suffix}`,\n\t};\n\tconst id = `iso_adp_${suffix}`;\n\tconst condition = { kind: \"verdict\" as const, status: \"reconciliation_required\" as const, error: \"isolation probe\" };\n\tconst parentCreated = !!subject.store.writeAdapterInvocation;\n\tif (parentCreated) await subject.store.createActionInvocation({\n\t\tid: scope.actionInvocationId, tenantId: scope.tenantId, spaceId: scope.spaceId,\n\t\tactionId: subject.actionId, actionVersion: 1, actorId: subject.ours.actorId, actorType: subject.ours.actorType,\n\t\tstatus: condition.status, error: condition.error, parameters: {}, result: {}, correlationId: suffix,\n\t});\n\tconst now = new Date();\n\ttry {\n\t\tawait subject.store.createAdapterInvocation({\n\t\t\tid, ...scope, adapterType: \"iso\", operation: \"probe\", vendor: \"iso\",\n\t\t\tstatus: \"running\", input: {}, output: { probe: true }, attempt: 1, createdAt: now, updatedAt: now,\n\t\t});\n\t} catch (error) {\n\t\tif (parentCreated) await subject.store.updateActionInvocation(scope.actionInvocationId, scope.tenantId, scope.spaceId, { status: \"failed\", error: \"tenant isolation probe; setup failed\" });\n\t\tthrow error;\n\t}\n\tconst retire = async () => {\n\t\ttry { await subject.store.updateAdapterInvocation(id, { status: \"failed\", error: \"tenant isolation probe; retired\", updatedAt: new Date() }, scope); }\n\t\tfinally {\n\t\t\tif (parentCreated) await subject.store.updateActionInvocation(scope.actionInvocationId, scope.tenantId, scope.spaceId, { status: \"failed\", error: \"tenant isolation probe; never executed\" });\n\t\t}\n\t};\n\treturn { id, scope, condition, retire };\n}\n\n/**\n * The suite any deployment of the host must pass before it claims isolation.\n *\n * Eight checks: an invocation cannot be read, executed, or completed under\n * another tenant's scope; an idempotency key is a tenant's own, so the same\n * key in two tenants is two invocations; a tenant's event stream carries no\n * other tenant's events; a worker scoped to one tenant does not claim another's\n * work; an adapter checkpoint cannot be read or written under another tenant,\n * space, or owning invocation; and, when the subject lends a read, a viewer in\n * the other tenant sees nothing of ours.\n */\nexport function tenantIsolationChecks(): readonly TenantIsolationCheck[] {\n\treturn [\n\t\t{\n\t\t\tid: \"fabric.tenancy.invocation-scoped-read.v1\",\n\t\t\tasync run(subject) {\n\t\t\t\tawait subject.reset?.();\n\t\t\t\tif (subject.ours.tenantId === subject.theirs.tenantId) fail(\"the two scopes must be in different tenants\");\n\t\t\t\tconst ours = await subject.host.submitAction(submitInput(subject, subject.ours, \"iso:read\"));\n\t\t\t\tconst crossRead = await subject.store.getActionInvocation(ours.actionInvocationId, subject.theirs.tenantId, subject.theirs.spaceId);\n\t\t\t\tif (crossRead !== undefined) fail(\"an invocation was readable under another tenant's scope\");\n\t\t\t\tconst shape = (record: { status?: unknown; result?: unknown; error?: unknown; attemptCount?: unknown; updatedAt?: unknown } | undefined) =>\n\t\t\t\t\tJSON.stringify({ status: record?.status, result: record?.result, error: record?.error, attemptCount: record?.attemptCount, updatedAt: record?.updatedAt });\n\t\t\t\tconst before = await subject.store.getActionInvocation(ours.actionInvocationId, subject.ours.tenantId, subject.ours.spaceId);\n\t\t\t\tif (!before) fail(\"our own invocation was not readable under our scope, so the check proves nothing\");\n\t\t\t\t// Snapshotted now: a store may hand back its live record.\n\t\t\t\tconst untouched = shape(before);\n\t\t\t\tlet crossExecute: unknown;\n\t\t\t\ttry {\n\t\t\t\t\tcrossExecute = await subject.host.executeInvocation(ours.actionInvocationId, subject.theirs.tenantId, subject.theirs.spaceId);\n\t\t\t\t} catch {\n\t\t\t\t\tcrossExecute = undefined;\n\t\t\t\t}\n\t\t\t\tif (crossExecute !== undefined) fail(\"an invocation was executable under another tenant's scope\");\n\t\t\t\t// Inert means untouched, not merely that nothing came back: a host\n\t\t\t\t// that read and wrote cross-tenant and then threw would otherwise pass.\n\t\t\t\tconst after = await subject.store.getActionInvocation(ours.actionInvocationId, subject.ours.tenantId, subject.ours.spaceId);\n\t\t\t\tif (untouched !== shape(after)) fail(\"an execution attempted under another tenant's scope changed our invocation\");\n\t\t\t\treturn [\"invocation readable under our scope, invisible and untouched under the other tenant's\"];\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tid: \"fabric.tenancy.idempotency-key-scoped.v1\",\n\t\t\tasync run(subject) {\n\t\t\t\tawait subject.reset?.();\n\t\t\t\tconst ours = await subject.host.submitAction(submitInput(subject, subject.ours, \"iso:shared-key\"));\n\t\t\t\tconst again = await subject.host.submitAction(submitInput(subject, subject.ours, \"iso:shared-key\"));\n\t\t\t\tif (ours.actionInvocationId !== again.actionInvocationId) fail(\"the same idempotency key in one tenant produced two invocations, so the key is not doing anything and the check proves nothing\");\n\t\t\t\tconst theirs = await subject.host.submitAction(submitInput(subject, subject.theirs, \"iso:shared-key\"));\n\t\t\t\tif (ours.actionInvocationId === theirs.actionInvocationId) fail(\"the same idempotency key in two tenants resolved to one invocation\");\n\t\t\t\treturn [\"one idempotency key: one invocation within a tenant, two across tenants\"];\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tid: \"fabric.tenancy.events-scoped.v1\",\n\t\t\tasync run(subject) {\n\t\t\t\tawait subject.reset?.();\n\t\t\t\tconst ours = await subject.host.submitAction(submitInput(subject, subject.ours, \"iso:events\"));\n\t\t\t\tconst theirEvents = await subject.store.listEvents(subject.theirs.tenantId, subject.theirs.spaceId);\n\t\t\t\tconst leaked = theirEvents.filter((event) => event.tenantId === subject.ours.tenantId || event.actionInvocationId === ours.actionInvocationId);\n\t\t\t\tif (leaked.length > 0) fail(`${leaked.length} of our events appeared in the other tenant's stream`);\n\t\t\t\tconst ourEvents = await subject.store.listEvents(subject.ours.tenantId, subject.ours.spaceId);\n\t\t\t\tif (!ourEvents.some((event) => event.actionInvocationId === ours.actionInvocationId)) fail(\"our own stream does not carry the event we just caused, so the check proves nothing\");\n\t\t\t\tif (ourEvents.some((event) => event.tenantId !== subject.ours.tenantId)) fail(\"another tenant's event appeared in our stream\");\n\t\t\t\treturn [\"event streams carry their own tenant's events and only those\"];\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tid: \"fabric.tenancy.worker-claim-scoped.v1\",\n\t\t\tasync run(subject) {\n\t\t\t\tawait subject.reset?.();\n\t\t\t\t// A pending row in a space of our own that nothing else uses, so a\n\t\t\t\t// backlog cannot push it past the claim limit, and a claim scoped to\n\t\t\t\t// it cannot sweep up real work. The row is retired afterwards so a\n\t\t\t\t// live worker never runs it.\n\t\t\t\tconst probeSpace = `iso-probe-${Date.now()}`;\n\t\t\t\tconst created = await subject.store.createActionInvocation({\n\t\t\t\t\tid: `iso_pending_${Date.now()}`,\n\t\t\t\t\ttenantId: subject.ours.tenantId,\n\t\t\t\t\tspaceId: probeSpace,\n\t\t\t\t\tactionId: subject.actionId,\n\t\t\t\t\tactionVersion: 1,\n\t\t\t\t\tactorId: subject.ours.actorId,\n\t\t\t\t\tactorType: subject.ours.actorType,\n\t\t\t\t\tstatus: \"pending\",\n\t\t\t\t\tparameters: subject.parameters ?? {},\n\t\t\t\t\tresult: {},\n\t\t\t\t\tcorrelationId: `iso-corr-${Date.now()}`,\n\t\t\t\t});\n\t\t\t\ttry {\n\t\t\t\t\tconst theirs = await subject.store.claimActionInvocations({\n\t\t\t\t\t\tworkerId: \"iso-worker\", leaseDurationMs: 1_000, limit: 1_000,\n\t\t\t\t\t\ttenantId: subject.theirs.tenantId, spaceId: probeSpace,\n\t\t\t\t\t});\n\t\t\t\t\tif (theirs.some((row) => row.id === created.id)) fail(\"a worker scoped to another tenant claimed our pending invocation\");\n\t\t\t\t\tconst ours = await subject.store.claimActionInvocations({\n\t\t\t\t\t\tworkerId: \"iso-worker\", leaseDurationMs: 1_000, limit: 1_000,\n\t\t\t\t\t\ttenantId: subject.ours.tenantId, spaceId: probeSpace,\n\t\t\t\t\t});\n\t\t\t\t\tif (!ours.some((row) => row.id === created.id)) fail(\"a worker scoped to our own tenant did not claim our pending invocation, so the check proves nothing\");\n\t\t\t\t} finally {\n\t\t\t\t\tawait subject.store.updateActionInvocation(created.id, subject.ours.tenantId, probeSpace, {\n\t\t\t\t\t\tstatus: \"failed\", error: \"tenant isolation probe; never executed\",\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\treturn [\"tenant-scoped claim takes our work and leaves other tenants' alone\"];\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tid: \"fabric.tenancy.completion-scoped.v1\",\n\t\t\tasync run(subject) {\n\t\t\t\tawait subject.reset?.();\n\t\t\t\tconst ours = await subject.host.submitAction(submitInput(subject, subject.ours, \"iso:complete\"));\n\t\t\t\tlet outcome: string;\n\t\t\t\ttry {\n\t\t\t\t\tawait subject.host.completeExternalInvocation(ours.actionInvocationId, subject.theirs.tenantId, subject.theirs.spaceId, {\n\t\t\t\t\t\texternalReference: \"iso-ref\", outcome: \"completed\", observedAt: new Date().toISOString(),\n\t\t\t\t\t});\n\t\t\t\t\toutcome = \"accepted\";\n\t\t\t\t} catch (error) {\n\t\t\t\t\tconst refusal = (error as { refusal?: string }).refusal;\n\t\t\t\t\toutcome = refusal ?? \"threw\";\n\t\t\t\t}\n\t\t\t\tif (outcome !== \"not_found\") fail(`a completion under another tenant's scope was ${outcome}; it must be refused as not_found`);\n\t\t\t\t// And under our own scope the invocation is found, whatever else it says.\n\t\t\t\tlet mine: string;\n\t\t\t\ttry {\n\t\t\t\t\tawait subject.host.completeExternalInvocation(ours.actionInvocationId, subject.ours.tenantId, subject.ours.spaceId, {\n\t\t\t\t\t\texternalReference: \"iso-ref\", outcome: \"completed\", observedAt: new Date().toISOString(),\n\t\t\t\t\t});\n\t\t\t\t\tmine = \"accepted\";\n\t\t\t\t} catch (error) {\n\t\t\t\t\tmine = (error as { refusal?: string }).refusal ?? \"threw\";\n\t\t\t\t}\n\t\t\t\tif (mine === \"not_found\") fail(\"a completion under our own scope was refused as not_found, so the check proves nothing\");\n\t\t\t\treturn [\"completion under the other tenant's scope refused as not_found; found under ours\"];\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tid: \"fabric.tenancy.projection-scoped.v1\",\n\t\t\tasync run(subject) {\n\t\t\t\tif (!subject.read) return [\"skipped: subject lends no read\"];\n\t\t\t\tawait subject.reset?.();\n\t\t\t\tawait subject.host.submitAction(submitInput(subject, subject.ours, \"iso:projection\"));\n\t\t\t\tconst ours = await subject.read(subject.ours);\n\t\t\t\tconst theirs = await subject.read(subject.theirs);\n\t\t\t\tif (!ours.allowed) fail(\"our own viewer was denied the read\");\n\t\t\t\tif (ours.rows.length === 0) fail(\"our own viewer saw nothing, so the check proves nothing\");\n\t\t\t\tif (ours.rows.some((row) => row?.tenantId !== subject.ours.tenantId)) fail(\"our own viewer saw rows that are not ours, or rows carrying no tenant\");\n\t\t\t\t// The other tenant may have rows of its own; what it must not have\n\t\t\t\t// is any of ours. Rows say whose they are, so two tenants holding\n\t\t\t\t// equal-looking rows is not a leak.\n\t\t\t\tconst leaked = theirs.allowed ? theirs.rows.filter((row) => row?.tenantId === subject.ours.tenantId) : [];\n\t\t\t\tif (leaked.length > 0) fail(`a viewer in the other tenant saw ${leaked.length} of our rows`);\n\t\t\t\treturn [theirs.allowed ? \"other tenant's viewer sees none of our rows\" : \"other tenant's viewer is denied\"];\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tid: \"fabric.tenancy.adapter-invocation-read-scoped.v1\",\n\t\t\tasync run(subject) {\n\t\t\t\tconst { id, scope, retire } = await adapterProbe(subject);\n\t\t\t\ttry {\n\t\t\t\t\tconst theirs = { ...scope, tenantId: subject.theirs.tenantId, spaceId: subject.theirs.spaceId };\n\t\t\t\t\tif (await subject.store.getAdapterInvocation(id, { ...scope, tenantId: subject.theirs.tenantId })) fail(\"an adapter invocation was readable under another tenant's scope\");\n\t\t\t\t\tif (await subject.store.getAdapterInvocation(id, theirs)) fail(\"an adapter invocation was readable under another tenant's scope\");\n\t\t\t\t\tif (await subject.store.getAdapterInvocation(id, { ...scope, spaceId: `${scope.spaceId}-other` })) fail(\"an adapter invocation was readable under another space's scope\");\n\t\t\t\t\tif (await subject.store.getAdapterInvocation(id, { ...scope, actionInvocationId: `${scope.actionInvocationId}-other` })) fail(\"an adapter invocation was readable under another action invocation's scope\");\n\t\t\t\t\tconst ours = await subject.store.getAdapterInvocation(id, scope);\n\t\t\t\t\tif (!ours || ours.id !== id || ours.tenantId !== scope.tenantId || ours.spaceId !== scope.spaceId || ours.actionInvocationId !== scope.actionInvocationId) fail(\"our own adapter invocation was not readable under our scope, so the check proves nothing\");\n\t\t\t\t} finally {\n\t\t\t\t\tawait retire();\n\t\t\t\t}\n\t\t\t\treturn [\"adapter invocation readable under our scope and invisible outside it\"];\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tid: \"fabric.tenancy.adapter-invocation-write-scoped.v1\",\n\t\t\tasync run(subject) {\n\t\t\t\tconst { id, scope, condition, retire } = await adapterProbe(subject);\n\t\t\t\tconst shape = (record: { status: unknown; error?: unknown; output?: unknown; attempt: unknown }) =>\n\t\t\t\t\tJSON.stringify({ status: record.status, error: record.error, output: record.output, attempt: record.attempt });\n\t\t\t\ttry {\n\t\t\t\t\tconst before = await subject.store.getAdapterInvocation(id, scope);\n\t\t\t\t\tif (!before) fail(\"our own adapter invocation was not readable under our scope, so the check proves nothing\");\n\t\t\t\t\t// Snapshot before writing: the memory store returns its live row.\n\t\t\t\t\tconst untouched = shape(before);\n\t\t\t\t\tfor (const other of [\n\t\t\t\t\t\t{ ...scope, tenantId: subject.theirs.tenantId, spaceId: subject.theirs.spaceId },\n\t\t\t\t\t\t{ ...scope, tenantId: subject.theirs.tenantId },\n\t\t\t\t\t\t{ ...scope, spaceId: `${scope.spaceId}-other` },\n\t\t\t\t\t\t{ ...scope, actionInvocationId: `${scope.actionInvocationId}-other` },\n\t\t\t\t\t]) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tawait subject.store.updateAdapterInvocation(id, { status: \"failed\", error: \"iso probe\", updatedAt: new Date() }, other);\n\t\t\t\t\t\t} catch { /* A not-found error is an acceptable refusal. */ }\n\t\t\t\t\t\tif (subject.store.writeAdapterInvocation) {\n\t\t\t\t\t\t\tif (subject.store.updateSettledActionInvocation && await subject.store.updateSettledActionInvocation({ id: other.actionInvocationId, tenantId: other.tenantId, spaceId: other.spaceId, condition, patch: { error: \"out-of-scope parent\" } })) fail(\"a settled parent update admitted another scope\");\n\t\t\t\t\t\t\tif (await subject.store.writeAdapterInvocation({ scope: other, condition, mutation: { kind: \"update\", id, patch: { status: \"failed\", error: \"iso probe\" } } })) fail(\"a conditional adapter update admitted another scope\");\n\t\t\t\t\t\t\tconst row = await subject.store.getAdapterInvocation(id, scope);\n\t\t\t\t\t\t\tif (!row) fail(\"our adapter row disappeared\");\n\t\t\t\t\t\t\tif (await subject.store.writeAdapterInvocation({ scope: other, condition, mutation: { kind: \"create\", record: { ...row!, id: `${id}-other` } } })) fail(\"a conditional adapter create admitted another scope\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst after = await subject.store.getAdapterInvocation(id, scope);\n\t\t\t\t\t\tif (!after || shape(after) !== untouched) fail(\"an adapter invocation changed under another scope\");\n\t\t\t\t\t}\n\t\t\t\t\tif (subject.store.writeAdapterInvocation && !await subject.store.writeAdapterInvocation({ scope, condition, expectedStatuses: [\"running\"], mutation: { kind: \"update\", id, patch: { attempt: 2 } } })) fail(\"our conditional adapter update was refused, so the check proves nothing\");\n\t\t\t\t\tawait subject.store.updateAdapterInvocation(id, { status: \"succeeded\", updatedAt: new Date() }, scope);\n\t\t\t\t\tif ((await subject.store.getAdapterInvocation(id, scope))?.status !== \"succeeded\") fail(\"our own adapter invocation was not updated under our scope, so the check proves nothing\");\n\t\t\t\t} finally {\n\t\t\t\t\tawait retire();\n\t\t\t\t}\n\t\t\t\treturn [\"adapter invocation untouched outside our scope and writable under ours\"];\n\t\t\t},\n\t\t},\n\t];\n}\n\n/** Run every check, returning each result rather than throwing on the first. */\nexport async function runTenantIsolationChecks(subject: TenantIsolationSubject): Promise<TenantIsolationResult> {\n\tconst checks: TenantIsolationResult[\"checks\"] = [];\n\tfor (const check of tenantIsolationChecks()) {\n\t\ttry {\n\t\t\tconst evidence = await check.run(subject);\n\t\t\tchecks.push({ id: check.id, status: evidence[0]?.startsWith(\"skipped\") ? \"skipped\" : \"passed\", evidence });\n\t\t} catch (error) {\n\t\t\tchecks.push({ id: check.id, status: \"failed\", evidence: [], error: error instanceof Error ? error.message : String(error) });\n\t\t}\n\t}\n\treturn { passed: checks.every((check) => check.status !== \"failed\"), checks };\n}\n","import type { AssetEventEnvelope } from \"@fabricorg/platform\";\nimport type { AtomicMutationPlatformHostStore, OutboxEventMetadata, OutboxPlatformHostStore, OutboxRecord, PlatformHostStore, RecoverablePlatformHostStore } from \"./types\";\n\n// Stable event IDs let recovery re-append evidence without replacing history.\n// Duplicates are probed within one tenant and space; cross-space uniqueness is not checked.\nexport interface EventAppendSubject<TDb = unknown> {\n\tstore: Pick<PlatformHostStore<TDb>, \"appendEvent\">\n\t\t& Pick<RecoverablePlatformHostStore<TDb>, \"listEvents\">\n\t\t& Partial<Pick<OutboxPlatformHostStore<TDb>, \"appendEventWithOutbox\" | \"listOutbox\" | \"claimOutbox\" | \"markOutboxPublished\" | \"markOutboxFailed\">>\n\t\t& Partial<Pick<AtomicMutationPlatformHostStore<TDb>, \"transactionWithEvents\">>;\n\ttenantId: string;\n\t/** Optional: restore a known state before a check; probes tolerate accumulated state. */\n\treset?(): Promise<void> | void;\n}\n\nexport interface EventAppendCheck {\n\tid:\n\t\t| \"fabric.store.event-append-first-write-wins.v1\"\n\t\t| \"fabric.store.event-append-outbox-first-write-wins.v1\"\n\t\t| \"fabric.store.event-append-outbox-after-plain.v1\"\n\t\t| \"fabric.store.event-append-transaction-first-write-wins.v1\"\n\t\t| \"fabric.store.event-append-transaction-outbox-first-write-wins.v1\"\n\t\t| \"fabric.store.event-append-transaction-outbox-after-plain.v1\";\n\trun<TDb>(subject: EventAppendSubject<TDb>): Promise<string[]>;\n}\n\nexport interface EventAppendResult {\n\tpassed: boolean;\n\tchecks: Array<{ id: EventAppendCheck[\"id\"]; status: \"passed\" | \"failed\" | \"skipped\"; evidence: string[]; error?: string }>;\n}\n\nfunction fail(message: string): never { throw new Error(message); }\nfunction message(error: unknown): string { return error instanceof Error ? error.message : String(error); }\n\n// Compare whole records, allowing JSON transport and database hydration differences.\nfunction normalize(value: unknown, key?: string): unknown {\n\tif (value == null) return undefined;\n\tif (value instanceof Date) return value.getTime();\n\tif (typeof value === \"string\") {\n\t\tif (key === \"sequence\" || key === \"attemptCount\" || key === \"leaseToken\") return Number(value);\n\t\tconst timestamp = key && [\"occurredAt\", \"recordedAt\", \"availableAt\", \"leaseExpiresAt\", \"createdAt\", \"publishedAt\"].includes(key);\n\t\tif ((timestamp || /^\\d{4}-\\d{2}-\\d{2}(?:T|$)/.test(value)) && Number.isFinite(Date.parse(value))) return Date.parse(value);\n\t}\n\tif (Array.isArray(value)) return value.map(item => normalize(item));\n\tif (typeof value === \"object\") return Object.fromEntries(Object.entries(value)\n\t\t.sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0)\n\t\t.map(([name, item]) => [name, normalize(item, name)]));\n\treturn value;\n}\nfunction shape(event: unknown): string { return JSON.stringify(normalize(event)); }\nfunction rowShape(row: OutboxRecord): string { return shape(row); }\n\n// Initial buffered duplicates have no pre-duplicate snapshot. Check the varied fields\n// a store exposes, allowing its own extra fields and fields it omits or returns as null.\nfunction keepsFirstValues(actual: object, first: object, duplicates: readonly object[]): boolean {\n\tconst record = actual as Record<string, unknown>;\n\tconst original = first as Record<string, unknown>;\n\tconst alternatives = duplicates as readonly Record<string, unknown>[];\n\tconst keys = new Set([...Object.keys(first), ...duplicates.flatMap(value => Object.keys(value))]);\n\tfor (const key of keys) {\n\t\tconst expected = shape(normalize(original[key], key));\n\t\tconst changed = alternatives.map(value => shape(normalize(value[key], key))).filter(value => value !== expected);\n\t\tif (record[key] != null && changed.length) {\n\t\t\tconst value = shape(normalize(record[key], key));\n\t\t\tif (value !== expected) return false;\n\t\t}\n\t}\n\treturn true;\n}\n\nasync function append(label: string, run: () => Promise<void>) {\n\ttry { await run(); }\n\tcatch (error) { fail(`${label} append threw: ${message(error)}`); }\n}\n\nasync function probeRows<TDb>(subject: EventAppendSubject<TDb>, spaceId: string): Promise<OutboxRecord[]> {\n\t// Defensive: outbox checks already require listOutbox before writing.\n\tif (!subject.store.listOutbox) fail(\"store has outbox append but lacks listOutbox; cannot verify rows\");\n\t// Filter locally too: a broken list implementation must not expand cleanup's scope.\n\treturn (await subject.store.listOutbox({ tenantId: subject.tenantId, spaceId }))\n\t\t.filter(row => row.tenantId === subject.tenantId && row.spaceId === spaceId);\n}\n\nconst leaseDurationMs = 30_000;\n// Whole seconds and a small clock-skew margin for stores with coarse availability.\nfunction dueTime(): Date { return new Date(Math.floor(Date.now() / 1_000) * 1_000 - 5_000); }\nconst relayInterference = \"another worker claimed the probe outbox row; pause outbox relays for the probe tenant\";\ntype OutboxState = \"pending\" | \"leased\" | \"retry-pending\" | \"published\";\ninterface RunState { filterViolation: boolean }\ninterface ProbeScope {\n\tspaceId: string;\n\tworkerId: string;\n\trun: RunState;\n\tleaseTokens: Map<string, number | undefined>;\n\tviolatingClaimRows: OutboxRecord[];\n}\n\nfunction checkWorker(row: OutboxRecord, workerId: string) {\n\tif (row.leaseOwner && row.leaseOwner !== workerId) fail(relayInterference);\n}\n// A store may end a lease by setting its expiry to its own clock, which can run\n// slightly ahead of ours; only an expiry beyond this margin counts as live.\nconst clockSkewMs = 5_000;\nfunction leaseExpiry(row: OutboxRecord): number | undefined {\n\treturn row.leaseExpiresAt == null ? undefined : Number(normalize(row.leaseExpiresAt, \"leaseExpiresAt\"));\n}\n// Wait out a released lease whose expiry is still inside the skew margin, so the\n// next claim can take the row.\nasync function waitForLeaseExpiry(row: OutboxRecord) {\n\tconst expiry = leaseExpiry(row);\n\tif (expiry !== undefined && expiry > Date.now()) await new Promise(resolve => setTimeout(resolve, expiry - Date.now() + 100));\n}\nfunction checkState(row: OutboxRecord, state: OutboxState, workerId: string) {\n\t// Another worker's lease is relay interference, whatever its expiry.\n\tcheckWorker(row, workerId);\n\tconst expiry = leaseExpiry(row);\n\tif (state === \"retry-pending\" && expiry !== undefined && expiry > Date.now() + clockSkewMs) {\n\t\tfail(\"markOutboxFailed did not release the lease\");\n\t}\n\tif (row.status !== (state === \"published\" ? \"published\" : \"pending\")) fail(relayInterference);\n\tif (state === \"leased\" && row.leaseOwner !== workerId) fail(relayInterference);\n}\nfunction leaseToken(row: OutboxRecord): number | undefined {\n\treturn row.leaseToken == null ? undefined : Number(row.leaseToken);\n}\n\nasync function claimProbeRows<TDb>(subject: EventAppendSubject<TDb>, scope: ProbeScope, pendingCount: number) {\n\tif (scope.run.filterViolation) fail(\"outbox check skipped because of the earlier claimOutbox filter violation\");\n\tconst rows = await subject.store.claimOutbox!({ tenantId: subject.tenantId, spaceId: scope.spaceId,\n\t\tnow: new Date(), workerId: scope.workerId, leaseDurationMs, limit: pendingCount });\n\tconst foreign = rows.filter(row => row.tenantId !== subject.tenantId || row.spaceId !== scope.spaceId);\n\tconst own = rows.filter(row => row.tenantId === subject.tenantId && row.spaceId === scope.spaceId);\n\tfor (const row of own) scope.leaseTokens.set(row.id, leaseToken(row));\n\tif (foreign.length) {\n\t\tscope.run.filterViolation = true;\n\t\tscope.violatingClaimRows = own;\n\t\tfail(`claimOutbox ignored the tenant/space filter; foreign row IDs: ${foreign.map(row => row.id).join(\", \")}; `\n\t\t\t+ `their leases lapse within ${leaseDurationMs}ms of the claim if the store honours leaseDurationMs; `\n\t\t\t+ \"the checks write nothing to foreign rows; further claims skipped for this run after filter violation\");\n\t}\n\treturn rows;\n}\n\nasync function retireAfterFilterViolation<TDb>(subject: EventAppendSubject<TDb>, scope: ProbeScope) {\n\tconst errors: string[] = [];\n\t// Only the violating claim's returned probe rows carry authority for cleanup.\n\t// Do not claim again, including for rows that claim failed to return.\n\tfor (const row of scope.violatingClaimRows) {\n\t\ttry {\n\t\t\tcheckState(row, \"leased\", scope.workerId);\n\t\t\tawait subject.store.markOutboxFailed!({ id: row.id, workerId: scope.workerId, leaseToken: scope.leaseTokens.get(row.id),\n\t\t\t\tdeadLetter: true, error: \"event append probe; never published\", availableAt: dueTime() });\n\t\t} catch (error) { errors.push(`probe row retirement failed (${row.id}): ${message(error)}`); }\n\t}\n\tconst pending = (await probeRows(subject, scope.spaceId)).filter(row => row.status === \"pending\");\n\tif (pending.length) errors.push(`probe rows still pending after filter violation: ${pending.map(row => row.id).join(\", \")}; dead-letter them by hand`);\n\tif (errors.length) fail(errors.join(\"; \"));\n}\n\nasync function retire<TDb>(subject: EventAppendSubject<TDb>, scope: ProbeScope) {\n\tconst { store } = subject;\n\tif (!store.listOutbox) return; // Outbox checks require this before writing.\n\tif (scope.run.filterViolation) {\n\t\ttry { await retireAfterFilterViolation(subject, scope); }\n\t\tcatch (error) { fail(`probe rows could not be retired: ${message(error)}`); }\n\t\treturn;\n\t}\n\tlet failure: string | undefined;\n\ttry {\n\t\tlet pending = (await probeRows(subject, scope.spaceId)).filter(row => row.status === \"pending\");\n\t\twhile (pending.length) {\n\t\t\t// Defensive: outbox checks require these methods before writing.\n\t\t\tif (!store.claimOutbox || !store.markOutboxFailed) fail(\"missing claimOutbox/markOutboxFailed\");\n\t\t\tfor (const row of pending) checkWorker(row, scope.workerId);\n\t\t\t// A failure during the leased snapshot can leave rows already claimed by this probe.\n\t\t\tconst owned = pending.filter(row => row.leaseOwner === scope.workerId);\n\t\t\tconst claimed = owned.length ? owned : await claimProbeRows(subject, scope, pending.length);\n\t\t\tif (!claimed.length) {\n\t\t\t\tfor (const row of await probeRows(subject, scope.spaceId)) checkState(row, \"pending\", scope.workerId);\n\t\t\t\tfail(\"claimOutbox returned no rows for pending probe outbox rows\");\n\t\t\t}\n\t\t\tconst errors: string[] = [];\n\t\t\tfor (const row of claimed) {\n\t\t\t\tcheckState(row, \"leased\", scope.workerId);\n\t\t\t\ttry {\n\t\t\t\t\tawait store.markOutboxFailed({ id: row.id, workerId: scope.workerId, leaseToken: scope.leaseTokens.get(row.id),\n\t\t\t\t\t\tdeadLetter: true, error: \"event append probe; never published\", availableAt: dueTime() });\n\t\t\t\t} catch (error) { errors.push(`probe row retirement failed: ${message(error)}`); }\n\t\t\t}\n\t\t\tif (errors.length) fail(errors.join(\"; \"));\n\t\t\tconst retired = await probeRows(subject, scope.spaceId);\n\t\t\tconst remaining = retired.filter(row => row.status === \"pending\");\n\t\t\tif (remaining.length >= pending.length) fail(\"retirement made no progress\");\n\t\t\tfor (const row of claimed) {\n\t\t\t\tif (retired.find(candidate => candidate.id === row.id)?.status !== \"dead_letter\") {\n\t\t\t\t\tfail(`retirement did not leave the probe outbox row in dead_letter: ${row.id}`);\n\t\t\t\t}\n\t\t\t}\n\t\t\tpending = remaining;\n\t\t}\n\t} catch (error) { failure = message(error); }\n\t// The violation may have happened during a retirement claim rather than the probe.\n\tif (scope.run.filterViolation) {\n\t\ttry { await retireAfterFilterViolation(subject, scope); }\n\t\tcatch (error) { failure = [failure, message(error)].filter(Boolean).join(\"; \"); }\n\t}\n\tif (failure) fail(`probe rows could not be retired: ${failure}`);\n}\n\nfunction requireOutboxVerification<TDb>(store: EventAppendSubject<TDb>[\"store\"]) {\n\tfor (const key of [\"listOutbox\", \"claimOutbox\", \"markOutboxPublished\", \"markOutboxFailed\"] as const) {\n\t\tif (!store[key]) fail(`store has outbox append but lacks ${key}; cannot verify or clean up probe rows`);\n\t}\n}\n\ntype Mode = \"plain\" | \"outbox\" | \"after-plain\" | \"transaction\" | \"transaction-outbox\" | \"transaction-after-plain\";\nasync function probe<TDb>(subject: EventAppendSubject<TDb>, mode: Mode, run: RunState = { filterViolation: false }): Promise<string[]> {\n\tconst { store, tenantId } = subject;\n\tconst transactional = mode.startsWith(\"transaction\");\n\tconst afterPlain = mode === \"after-plain\" || mode === \"transaction-after-plain\";\n\tconst outbox = mode === \"outbox\" || mode === \"transaction-outbox\" || afterPlain;\n\tif (transactional && !store.transactionWithEvents) return [\"skipped: store has no transactionWithEvents\"];\n\tif (!transactional && outbox && !store.appendEventWithOutbox) return [\"skipped: store has no appendEventWithOutbox\"];\n\tif (outbox && run.filterViolation) fail(\"outbox check skipped because of the earlier claimOutbox filter violation\");\n\tawait subject.reset?.();\n\tconst spaceId = `event-append-probe-${globalThis.crypto.randomUUID()}`;\n\tconst scope: ProbeScope = { spaceId, workerId: `event-append-probe-${globalThis.crypto.randomUUID()}`, run,\n\t\tleaseTokens: new Map(), violatingClaimRows: [] };\n\t// Whole seconds, slightly in the past: due when availability uses recordedAt.\n\tconst recordedAt = dueTime();\n\tconst first: AssetEventEnvelope = {\n\t\tid: globalThis.crypto.randomUUID(), tenantId, spaceId, eventType: \"EventAppendProbe\", eventSchemaVersion: 1,\n\t\tsubjectType: \"EventAppendProbe\", subjectId: \"first\", actorId: \"event-append-probe\", actorType: \"system\",\n\t\tactionInvocationId: globalThis.crypto.randomUUID(), correlationId: globalThis.crypto.randomUUID(), causationId: globalThis.crypto.randomUUID(),\n\t\tpayload: { probe: \"first\", nested: { b: 2, a: 1 } }, sequence: 50,\n\t\toccurredAt: new Date(recordedAt.getTime() - 1_000), recordedAt,\n\t\tprovenance: { source: \"system\", auditAttributes: { \"probe.origin\": \"first\" } },\n\t};\n\tconst metadata: OutboxEventMetadata = { producerModuleVersion: \"event-append-probe@1\", payloadClassification: \"internal\",\n\t\ttraceContext: { traceparent: \"first\" }, includeProvenance: false, includeActor: false };\n\tconst duplicates = ([\"later\", \"earlier\"] as const).map((direction, index) => ({\n\t\tdirection,\n\t\tevent: { ...first, eventType: `${direction}EventAppendProbe`, eventSchemaVersion: index + 2,\n\t\t\tsubjectType: `${direction}Probe`, subjectId: direction, actorId: `${direction}-actor`, actorType: \"service_account\",\n\t\t\tactionInvocationId: globalThis.crypto.randomUUID(), correlationId: globalThis.crypto.randomUUID(), causationId: globalThis.crypto.randomUUID(),\n\t\t\tpayload: { probe: direction, [direction]: true }, sequence: index === 0 ? 99 : 1,\n\t\t\toccurredAt: new Date(first.occurredAt.getTime() + (index === 0 ? 2_000 : -2_000)),\n\t\t\trecordedAt: new Date(recordedAt.getTime() + (index === 0 ? 2_000 : -2_000)),\n\t\t\tprovenance: { source: \"api\", auditAttributes: { \"probe.origin\": direction, [`probe.${direction}`]: \"added\" } }, consistency: \"provisional-until-reconciled\",\n\t\t} satisfies AssetEventEnvelope,\n\t\tmetadata: { producerModuleVersion: `event-append-probe@${index + 2}`, payloadClassification: \"confidential\",\n\t\t\ttraceContext: { traceparent: direction, [direction]: \"added\" }, includeProvenance: true, includeActor: true } satisfies OutboxEventMetadata,\n\t}));\n\t// Keep expected input values independent of stores that retain the supplied objects.\n\tconst firstInput = structuredClone(first);\n\tconst outboxInput = structuredClone({ ...first, ...metadata });\n\tconst duplicateInputs = structuredClone(duplicates);\n\tlet original: string | undefined;\n\tconst verifyEvents = (events: AssetEventEnvelope[], context = \"\") => {\n\t\t// Fresh control events share this space; only duplicates of the probe ID count.\n\t\tevents = events.filter(event => event.id === firstInput.id);\n\t\tif (events.length === 0) fail(\"store kept no event, so the check proves nothing\" + context);\n\t\tif (events.length !== 1) fail(`store kept ${events.length === 2 ? \"two\" : events.length} events instead of one` + context);\n\t\tconst event = events[0]!;\n\t\tif (!keepsFirstValues(event, firstInput, duplicateInputs.map(value => value.event)) || (original !== undefined && shape(event) !== original)) {\n\t\t\tfail(\"store kept the later event or changed the first event\" + context);\n\t\t}\n\t\toriginal ??= shape(event);\n\t};\n\tconst verify = async (state?: OutboxState) => {\n\t\tconst context = state ? ` on duplicate append against the ${state} outbox row` : \"\";\n\t\tverifyEvents(await store.listEvents(tenantId, spaceId), context);\n\t\tif (!outbox) return undefined;\n\t\tconst rows = await probeRows(subject, spaceId);\n\t\tif (afterPlain) {\n\t\t\tif (rows.length) fail(\"store added an outbox row for an already-stored event\");\n\t\t\treturn undefined;\n\t\t}\n\t\tif (rows.length === 0) fail(state ? `store removed the existing outbox row on duplicate append (${state})`\n\t\t\t: \"store added no outbox row, so the check proves nothing\");\n\t\tif (rows.length !== 1) fail(`store added a second outbox row (${rows.length} rows)` + context);\n\t\treturn rows[0]!;\n\t};\n\tlet controlSequence = 100;\n\tconst duplicate = async (afterEach: () => Promise<void>) => {\n\t\tfor (const { event, metadata, direction } of duplicates) {\n\t\t\tif (transactional) {\n\t\t\t\tconst controlId = globalThis.crypto.randomUUID();\n\t\t\t\tconst control = { ...firstInput, id: controlId, sequence: controlSequence++, payload: { probe: \"transaction-control\" } };\n\t\t\t\tawait store.transactionWithEvents!(async tx => {\n\t\t\t\t\tawait append(\"committed duplicate transaction\", () => outbox ? tx.appendEventWithOutbox!(event, metadata) : tx.appendEvent(event));\n\t\t\t\t\tawait append(\"committed duplicate transaction control\", () => tx.appendEvent(control));\n\t\t\t\t});\n\t\t\t\tif (!(await store.listEvents(tenantId, spaceId)).some(event => event.id === controlId)) {\n\t\t\t\t\tfail(`committed duplicate transaction lost its control event: ${controlId}`);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tawait append(direction, () => outbox ? store.appendEventWithOutbox!(event, metadata) : store.appendEvent(event));\n\t\t\t}\n\t\t\tawait afterEach();\n\t\t}\n\t};\n\tlet failure: string | undefined;\n\ttry {\n\t\tif (transactional) {\n\t\t\tconst supported = await store.transactionWithEvents!(async tx => {\n\t\t\t\tif (outbox && !tx.appendEventWithOutbox) return false;\n\t\t\t\tif (outbox) requireOutboxVerification(store);\n\t\t\t\tawait append(\"first transaction\", () => outbox && !afterPlain ? tx.appendEventWithOutbox!(first, metadata) : tx.appendEvent(first));\n\t\t\t\tfor (const { event, metadata, direction } of duplicates) {\n\t\t\t\t\tawait append(`${direction} transaction`, () => outbox ? tx.appendEventWithOutbox!(event, metadata) : tx.appendEvent(event));\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t});\n\t\t\tif (!supported) return [\"skipped: transaction has no appendEventWithOutbox\"];\n\t\t} else {\n\t\t\tif (outbox) requireOutboxVerification(store);\n\t\t\tawait append(\"first\", () => mode === \"outbox\" ? store.appendEventWithOutbox!(first, metadata) : store.appendEvent(first));\n\t\t}\n\t\tif (outbox && !afterPlain) {\n\t\t\tlet row = (await verify())!;\n\t\t\tcheckState(row, \"pending\", scope.workerId);\n\t\t\t// Establish the first row before comparing snapshots, including buffered transaction duplicates.\n\t\t\tif (row.event.producerModuleVersion !== metadata.producerModuleVersion) fail(\"store changed the first pending outbox producerModuleVersion metadata\");\n\t\t\tif (row.event.payloadClassification !== metadata.payloadClassification) fail(\"store changed the first pending outbox payloadClassification metadata\");\n\t\t\tif (row.actorDisclosure === \"included\") fail(\"store included actor disclosure although first metadata did not opt in with includeActor\");\n\t\t\tif (row.event.actorId != null || row.event.actorType != null) fail(\"store put actorId or actorType on the outbox envelope although first metadata did not opt in with includeActor\");\n\t\t\tif (!keepsFirstValues(row.event, outboxInput, duplicateInputs.map(value => ({ ...value.event, ...value.metadata })))) {\n\t\t\t\tfail(\"store changed the first pending outbox envelope\");\n\t\t\t}\n\t\t\tfor (const state of [\"pending\", \"leased\", \"retry-pending\", \"published\"] as const) {\n\t\t\t\t// Check again immediately before acting, so visible relay interference is explicit.\n\t\t\t\trow = (await verify())!;\n\t\t\t\tcheckState(row, state, scope.workerId);\n\t\t\t\tconst snapshot = rowShape(row);\n\t\t\t\tawait duplicate(async () => {\n\t\t\t\t\trow = (await verify(state))!;\n\t\t\t\t\tif (rowShape(row) !== snapshot) fail(`store changed the existing ${state} outbox row on duplicate append (including delivery state, envelope and metadata)`\n\t\t\t\t\t\t+ ((row.leaseOwner && row.leaseOwner !== scope.workerId) || row.status !== (state === \"published\" ? \"published\" : \"pending\")\n\t\t\t\t\t\t\t? `; ${relayInterference}` : \"\"));\n\t\t\t\t});\n\t\t\t\tif (state === \"pending\" || state === \"retry-pending\") {\n\t\t\t\t\tcheckState(row, state, scope.workerId);\n\t\t\t\t\tif (state === \"retry-pending\") await waitForLeaseExpiry(row);\n\t\t\t\t\tconst claimed = await claimProbeRows(subject, scope, 1);\n\t\t\t\t\trow = (await verify())!;\n\t\t\t\t\tcheckWorker(row, scope.workerId);\n\t\t\t\t\tif (row.status !== \"pending\") fail(relayInterference);\n\t\t\t\t\tif (claimed.length !== 1 || claimed[0]!.id !== row.id || row.leaseOwner !== scope.workerId) fail(\"claimOutbox did not lease the pending probe outbox row\");\n\t\t\t\t\tif (state === \"retry-pending\") {\n\t\t\t\t\t\trow = (await verify())!;\n\t\t\t\t\t\tcheckState(row, \"leased\", scope.workerId);\n\t\t\t\t\t\tawait store.markOutboxPublished!(row.id, scope.workerId, new Date(), scope.leaseTokens.get(row.id));\n\t\t\t\t\t\trow = (await verify())!;\n\t\t\t\t\t\tcheckWorker(row, scope.workerId);\n\t\t\t\t\t\tif (row.status !== \"published\") fail(\"markOutboxPublished did not settle the probe outbox row as published\");\n\t\t\t\t\t}\n\t\t\t\t} else if (state === \"leased\") {\n\t\t\t\t\trow = (await verify())!;\n\t\t\t\t\tcheckState(row, \"leased\", scope.workerId);\n\t\t\t\t\tawait store.markOutboxFailed!({ id: row.id, workerId: scope.workerId, leaseToken: scope.leaseTokens.get(row.id),\n\t\t\t\t\t\tdeadLetter: false, availableAt: dueTime(), error: \"event append probe; retry\" });\n\t\t\t\t\trow = (await verify())!;\n\t\t\t\t\tcheckState(row, \"retry-pending\", scope.workerId);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tawait verify();\n\t\t\tawait duplicate(async () => { await verify(); });\n\t\t\tif (afterPlain) {\n\t\t\t\t// A positive control prevents a blind listOutbox from proving absence vacuously.\n\t\t\t\tconst control = { ...first, id: globalThis.crypto.randomUUID(), sequence: 51, payload: { probe: \"control\" } };\n\t\t\t\tif (transactional) await store.transactionWithEvents!(tx => append(\"control transaction\", () => tx.appendEventWithOutbox!(control, metadata)));\n\t\t\t\telse await append(\"control\", () => store.appendEventWithOutbox!(control, metadata));\n\t\t\t\tconst rows = await probeRows(subject, spaceId);\n\t\t\t\tif (rows.length !== 1 || rows[0]!.event.eventId !== control.id) fail(\"store did not expose exactly the control event's outbox row; absence verification proves nothing\");\n\t\t\t\tcheckState(rows[0]!, \"pending\", scope.workerId);\n\t\t\t}\n\t\t}\n\t} catch (error) { failure = message(error); }\n\tfinally {\n\t\tif (outbox) {\n\t\t\ttry { await retire(subject, scope); }\n\t\t\tcatch (error) { failure = [failure, message(error)].filter(Boolean).join(\"; \"); }\n\t\t}\n\t\tif (failure) fail(failure);\n\t}\n\treturn [\"earlier and later duplicate appends kept one first event\" + (outbox ? afterPlain\n\t\t? \" and added no outbox row, verified by a fresh control row\"\n\t\t: \" and preserved pending, leased, retry-pending and published outbox rows and first metadata\" : \"\")];\n}\n\n/**\n * Six checks detecting common first-write-wins violations through plain,\n * outbox and transaction appends, including outbox-after-plain and committed\n * duplicates: throwing, replacing, merging, keeping both events, selecting the\n * earlier-ordered or later-ordered duplicate, adding outbox rows, and resetting\n * or rewriting existing outbox rows in the probed states. They are not exhaustive.\n * Duplicates have both earlier and later ordering fields and vary the remaining\n * envelope and outbox metadata fields. Whole-record snapshots compare duplicates\n * while pending, leased by the probe, retry-pending, and settled as published.\n * Retry-pending accepts a cleared or expired lease, the probe owner retained\n * without an expiry, or an expiry within five seconds of the probe's clock,\n * which is waited out before the row is claimed again; attempt counts and\n * error formatting are not prescribed.\n * Initial comparisons accept store-specific fields and fields the store omits\n * or returns as null; transaction verification runs after commit without requiring\n * read-your-writes. Each committed duplicate transaction also appends a fresh plain\n * control event whose presence is verified after commit.\n * Successful outbox-creating checks leave the probe row\n * published although nothing was sent; its event-append-probe space identifies\n * it. Absence checks write a control row that cleanup dead-letters. These rows can\n * be requeued by operator tooling; exclude probe spaces from real publication.\n *\n * Intended for test or staging stores with outbox relays paused for the probe\n * tenant. Event and availability inputs use whole seconds a few seconds in the\n * past; claims and publication markers use real current time. Checks leave\n * append-only events in fresh event-append-probe spaces. Final cleanup\n * attempts to dead-letter visible probe rows still pending with\n * \"event append probe; never published\".\n * Claims use real current time, a pending-probe-row limit, and a 30-second lease.\n * A filter-ignoring claim can lease foreign rows and make whatever writes the\n * claim itself makes (such as incrementing attempts). Checks write nothing to\n * foreign rows and stop claiming for that run (or that standalone check).\n * After a filter violation, cleanup can dead-letter only probe rows returned by\n * that claim, using the probe worker and claim tokens without further claims.\n * Failures list visible probe rows still pending and instruct manual dead-lettering.\n * Later outbox checks in the run fail as skipped because of the earlier filter\n * violation. Leases lapse within 30 seconds\n * of the claim if the store honours the lease duration.\n *\n * Missing append capabilities skip; missing listOutbox, claimOutbox,\n * markOutboxPublished or markOutboxFailed fails verification/cleanup.\n * Known limits: rules comparing ordering fields in mixed directions, store-wide\n * uniqueness across spaces or tenants, the dead-letter state, claims that\n * lease foreign rows without returning them, buffered merges into fields the\n * store never returns, and duplicate handling that only holds within one\n * process. Stores requiring gapless sequences, or unique keys over fields the\n * control events share with the probe event, can fail falsely.\n */\nexport function eventAppendChecks(): readonly EventAppendCheck[] {\n\treturn checksForRun();\n}\n\nfunction checksForRun(run?: RunState): readonly EventAppendCheck[] {\n\treturn [\n\t\t{ id: \"fabric.store.event-append-first-write-wins.v1\", run: subject => probe(subject, \"plain\", run) },\n\t\t{ id: \"fabric.store.event-append-outbox-first-write-wins.v1\", run: subject => probe(subject, \"outbox\", run) },\n\t\t{ id: \"fabric.store.event-append-outbox-after-plain.v1\", run: subject => probe(subject, \"after-plain\", run) },\n\t\t{ id: \"fabric.store.event-append-transaction-first-write-wins.v1\", run: subject => probe(subject, \"transaction\", run) },\n\t\t{ id: \"fabric.store.event-append-transaction-outbox-first-write-wins.v1\", run: subject => probe(subject, \"transaction-outbox\", run) },\n\t\t{ id: \"fabric.store.event-append-transaction-outbox-after-plain.v1\", run: subject => probe(subject, \"transaction-after-plain\", run) },\n\t];\n}\n\n/**\n * Run eventAppendChecks and collect results instead of stopping at the first\n * failure. Use test or staging stores with relays paused for the probe tenant;\n * see eventAppendChecks for probe publication markers and cleanup side effects.\n */\nexport async function runEventAppendChecks<TDb>(subject: EventAppendSubject<TDb>): Promise<EventAppendResult> {\n\tconst checks: EventAppendResult[\"checks\"] = [];\n\tfor (const check of checksForRun({ filterViolation: false })) {\n\t\ttry {\n\t\t\tconst evidence = await check.run(subject);\n\t\t\tchecks.push({ id: check.id, status: evidence[0]?.startsWith(\"skipped: \") ? \"skipped\" : \"passed\", evidence });\n\t\t} catch (error) {\n\t\t\tchecks.push({ id: check.id, status: \"failed\", evidence: [], error: message(error) });\n\t\t}\n\t}\n\treturn { passed: checks.every(check => check.status !== \"failed\"), checks };\n}\n"],"mappings":";;;;;;;;AA6BA,MAAa,iCAAiC;AAgC9C,IAAa,2BAAb,cAA8C,MAAM;CAE9B;CADrB,OAAgB;CAChB,YAAY,UAAwC;EACnD,MAAM,oBAAoB,SAAS,eAAe,8BAA8B,SAAS,qBAAqB,IAAI,SAAS,QAAQ,KAAK,IAAI,GAAG;EAD3H,KAAA,WAAA;EAEpB,KAAK,OAAO;CACb;AACD;;;;;;;;AAqBA,IAAa,uBAAb,cAA0C,MAAM;CAGrC;CACA;CAEA;CALV,OAAgB;CAChB,YACC,UACA,SAEA,aACC;EACD,MAAM,UAAU,SAAS,gCAAgC,UAAU,cAAc,KAAK,gBAAgB,GAAG,yBAAyB;EALzH,KAAA,WAAA;EACA,KAAA,UAAA;EAEA,KAAA,cAAA;EAGT,KAAK,OAAO;CACb;AACD;;;;;;;;;;AAsBA,IAAa,0BAAb,cAA6C,MAAM;CAE7B;CADrB,OAAgB;CAChB,YAAY,SAA6C,SAAiB;EACzE,MAAM,OAAO;EADO,KAAA,UAAA;EAEpB,KAAK,OAAO;CACb;CACA,IAAI,YAAqB;EACxB,OAAO,KAAK,YAAY;CACzB;AACD;;;AC9HA,MAAa,6BAA6B;AAM1C,SAAgB,iBAAiB,YAA6B;CAC7D,QAAA,GAAOA,OAAAA,WAAAA,CAAW,QAAQ,CAAC,CAAC,QAAA,GAAOC,oBAAAA,cAAAA,CAAc,UAAU,CAAC,CAAC,CAAC,OAAO,KAAK;AAC3E;AAEA,MAAM,iBAAiB;AACvB,MAAM,oBAAoB;AAE1B,SAAgB,oBACf,OACA,SAC4D;CAC5D,IAAI,CAAC,OAAO,OAAO,KAAA;CACnB,IAAI,CAAC,kBAAkB,KAAK,MAAM,MAAM,GAAG,MAAM,IAAI,MAAM,yCAAyC,MAAM,QAAQ;CAClH,M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