TechFabricTechFabricPlatform
Platform referenceReference

Platform Host 6.x

Install and operate the durable governed-action host for applications called by Hermes, Harness, MCP, and other agent runtimes.

@fabricorg/platform-host is the application-side runtime for governed mutations. It creates the durable invocation before dispatch, validates the registered action schema, enforces authorization and policy, coordinates adapters, appends canonical events, and supports approval and interruption recovery.

An external agent such as Hermes does not install this package merely to call a Fabric application. The application installs Platform Host and exposes a narrow authenticated REST or MCP gateway, and the agent on the other side of it receives only that gateway, a registration-bound credential and the exact set of actions its current grant allows, which is what makes the blast radius of a compromised agent a question with a written answer.

IntegratorInstall @fabricorg/platform-host?Correct boundary
Application or vertical ownerYesRegister actions and run the governed Host
Hermes, TechFabric Harness, or another external agentNoDiscover and invoke the application's REST/MCP gateway
Durable worker owned by the applicationYesCall executeInvocation() for a persisted invocation

Install

Platform Host 6.x requires Node.js 20 or newer, Platform 1.1 or newer, and the Assembly peer. Run Node 22.23.4, 24.22.1, or 26.12.1 or newer in the same release line in production for the Brotli decoder fix in CVE-2026-111497; Node 20 is end-of-life and has no fixed release.

pnpm add @fabricorg/platform@^1.2.0 @fabricorg/platform-host@^6.0.0 @fabricorg/assembly@^0.3.0
npm install @fabricorg/platform@^1.2.0 @fabricorg/platform-host@^6.0.0 @fabricorg/assembly@^0.3.0

The package supports ESM and CommonJS. Version 6.0.0 publishes Host contract generation 2. Applications should record both values in runtime evidence because the npm version and durable contract generation evolve independently.

Wire the host

The ingress layer authenticates the caller and creates any immutable admission record. It then submits a trusted command to the Host. Do not pass credentials, bearer tokens, signatures, nonces, or private provider configuration as action parameters.

import {
  createGovernedActionHost,
  PostgresPlatformHostStore,
} from "@fabricorg/platform-host";

const store = new PostgresPlatformHostStore(
  domainStore,
  pool,
  {
    run: async (run) => {
      const client = await pool.connect();
      try {
        await client.query("BEGIN");
        const result = await run({
          db: domainStore.withClient(client),
          sql: client,
        });
        await client.query("COMMIT");
        return result;
      } catch (error) {
        await client.query("ROLLBACK");
        throw error;
      } finally {
        client.release();
      }
    },
  },
);

await store.ensureSchema();

const host = createGovernedActionHost({
  store,
  resolveAction: (actionId) => actionCatalog.get(actionId),
  authorization: {
    checkEntitlement,
    authorize: authorizeSubmission,
    authorizeExecution: async ({
      invocation,
      parameters,
      executionReason,
    }) =>
      admissionStore.revalidate({
        admissionId: invocation.authorizationBindingId,
        tenantId: invocation.tenantId,
        actorId: invocation.actorId,
        actionId: invocation.actionId,
        parameters,
        executionReason,
      }),
  },
  runtimeEvidence: {
    hostPackageVersion: deployedHostPackageVersion,
    policyRulesetVersion: "application-policy.v1",
  },
});

domainStore.withClient(client) is application-owned: it must return the same domain-store interface bound to the supplied PostgreSQL/Lakebase transaction. The transaction provider is what allows domain writes, event sequence allocation, canonical event append, and invocation finalization to commit or roll back as one unit.

Production applications use PostgresPlatformHostStore with Lakebase or PostgreSQL and run ensureSchema() during controlled startup or migration. MemoryPlatformHostStore is for tests and explicit local development.

Bind execution to the approved composition

For an assembled application, pass the exact lockfile and the full explicit module registry:

const host = createGovernedActionHost({
  store,
  registry,
  authorization,
  composition: {
    assembly: approvedAssembly,
    resolveInitiatingReleaseDigest: (submission) =>
      releaseRegistry.resolveTrustedDigest(submission.provenance),
  },
});

Every registered FabricModule must carry its published package version and compiler-derived manifestDigest. Host derives loaded capability identities from registry.orderedModules; it doesn't accept a parallel caller-supplied artifact list. Startup fails on a missing, extra, duplicate, version-mismatched, or digest-mismatched capability.

For each new invocation, Host stores the trusted assembly digest and, when resolved, the initiating promoted release digest in runtimeEvidence. Release lookup failure or a malformed digest fails before invocation creation. PostgreSQL stores these fields in the existing JSONB runtime-evidence document, so no schema column is added.

See Production adoption for the lockfile and deployment-check sequence.

Submit an admitted agent command

Create the admission before starting background orchestration. Persist only an opaque, non-secret binding on the invocation.

const admission = await admissionStore.admit({
  tenantId,
  registrationId,
  actorId,
  actionId,
  parameters,
  idempotencyKey,
});

const submitted = await host.submitAction({
  actionId,
  parameters,
  tenantId,
  spaceId,
  actorId,
  actorType: "agent",
  idempotencyKey,
  authorizationBindingId: admission.id,
  correlationId,
});

The same logical request must reuse the same idempotency key and canonical parameters. Platform Host binds new idempotent invocation rows to the action version, actor/authority binding, and a fabric-canonical-json-sha256-v1 parameter digest. In audit-only mode a changed command recovers the old invocation and calls onConflict; in enforce mode it throws IdempotencyConflictError with code IDEMPOTENCY_CONFLICT. Legacy rows without a digest skip only the unavailable parameter comparison and call onLegacyRecord; actor, authority-binding, and action-version mismatches still reject in enforce mode. Host defaults to enforcement; set conflictMode: "audit-only" for the documented preflight soak and rollback window.

Submission authorization answers whether the caller may create the durable invocation. authorizeExecution revalidates the original actor, schema-parsed durable parameters, current registration and resource scope immediately before policies and mutation code. It runs with an executionReason of:

  • initial for first execution;
  • approval_resume after an approval decision;
  • recovery for interrupted work.
  • offline_replay for a command captured while disconnected and submitted for reconciliation.

Actions may declare execution.authorityMoment as capture, execution, or both. An offline replay whose execution-time authority is denied returns reconciliation_required with a structured outcome; it's neither silently executed nor discarded. AuthorizationBinding contains audit-safe evidence and an opaque binding ID. Credentials and signed principal proofs stay out. For execution and both, the Host detects an expired binding before mutation. resourceScope is an opaque identifier interpreted by the application-owned authorizeExecution policy.

Invocation provenance

SubmitActionInput.provenance accepts an InvocationProvenance envelope that separates bounded trace attributes from allowlisted durable audit attributes. Attribute names are namespaced (domain.key), values and counts are limited, and audit attributes fail closed without an allowlist and pass through the configured redactor. Restricted outbox payloads omit provenance unless a classification-aware host policy opts in. SDUI integrations use experience.documentId, experience.compositionId, and experience.releaseId as audit attributes; channel and interaction detail remain trace-only. Core does not interpret experience vocabulary.

provenance: {
  source: "sdui",
  correlationId,
  auditAttributes: {
    "experience.documentId": documentId,
    "experience.compositionId": compositionId,
    "experience.releaseId": releaseId,
  },
  traceAttributes: { "experience.channel": "pos" },
}

For execution and both, revocation can therefore stop work that was admitted earlier but has not executed. capture requires durable capture evidence and intentionally governs by that recorded moment. An already completed idempotent replay remains observable and does not execute again.

Events, adapters, and recovery

Use eventPhase: "before_adapters" for durable intent/outbox events. With the PostgreSQL transaction provider, the handler's domain writes and those declared events commit atomically.

Use eventPhase: "after_adapters" only for completion or attestation events whose truth requires every configured adapter to have succeeded. In Host 6.x, the completion event and invocation completion commit together on a capable store. If this final domain-event/invocation write fails while a succeeded adapter checkpoint is retained, idempotent recovery repairs its evidence without a provider call and retries finalization within recoveryMaxAttempts.

Returned ambiguous or timeout outcomes, timeouts thrown from adapter.execute (including an aborted adapter deadline), contradictory successful results, and reverse contradictions (success: false with outcome: "success") route to reconciliation_required. Host detects a thrown timeout from the adapter deadline's aborted signal or an error message matching /timeout|deadline|timed?\s*out/i. A definite rejection whose message matches therefore also routes to reconciliation; the message matcher does not prove that the provider timed out.

An uninterpretable provider reply (a non-object, null, or an array), a getter that throws before Host can interpret the reply, and an unrecognised outcome string such as "timed_out" also take this path. Host copies the reply's contract fields and other own enumerable fields into a plain object before interpretation, reading each top-level field once. A getter that throws during the copy takes the unreadable-reply path. These outcomes are not retried by the retry helper. Object replies retain the previous truthiness reading of success, including truthy non-boolean values from JavaScript adapters. The reconciliation kind remains adapter_outcome_ambiguous.

Unknown-outcome settlement uses transactionWithEvents when its transaction supplies updateAdapterInvocation, appendExternalReconciliation on a governance-capable store, and updateLeasedActionInvocation for a leased invocation. A store advertising conditional adapter writes also needs transaction-scoped writeAdapterInvocation for leased finalization. In that transaction Host writes the ambiguous checkpoint, AdapterInvocationAmbiguous with its stable event ID, governance ExternalReconciliation evidence where supported, and the fenced reconciliation_required verdict, in that order. These writes commit together. Host retries once on a non-lease error; a second non-lease failure selects the verdict-first fallback. Lease loss raises RecoverableFinalizationError without retry or fallback.

Without those transaction members, or after two non-lease transaction failures, the verdict-first fallback writes the terminal verdict (retrying once except on lease loss), then the checkpoint, event, and reconciliation record. If both checkpoint shapes fail, Host still attempts the ambiguity event and reconciliation record. After the verdict commits, Host attempts each remaining evidence write even if the event append fails, then surfaces the first error as RecoverableFinalizationError. An evidence failure can leave a terminal verdict with missing evidence; a later direct execution returns that verdict and workers exclude it from recovery, without repairing the evidence gap. If both verdict attempts fail, Host surfaces RecoverableFinalizationError without attempting an unfenced checkpoint.

With the original action definition and adapter-step order available, recovery checks ambiguous rows before the parked-handoff shortcut, stale-action gates, authorization, and handler execution. This applies to actions declared idempotent and actions not declared idempotent. Settlement uses the stored reconciliation metadata or the legacy row's error as its message and reason, without running the handler or an adapter. For a running invocation whose action resolves, executeInvocation reads each adapter step's row before the pending-handoff shortcut, stopping on recorded ambiguity or a failed read. A failed read surfaces RecoverableFinalizationError, where base 939bcad returned the parked result. The shortcut's condition is unchanged from base: a running invocation with pendingCompletion and no lease owner returns early without requiring pendingCompletion.parkedAt. If the action no longer resolves, the shortcut still returns the handoff before the unknown-action failure. Completion callbacks that settle the invocation require parking, including after a deadline sweep.

AdapterInvocationRecord.reconciliation is an optional, redacted checkpoint preserving reason, external reference, and the original adapterEventSubject. The subject stays out of the returned AdapterReconciliationOutcome. Recovery uses this checkpoint without scanning listEvents(). Without stored subject metadata it uses { subjectType: "AdapterInvocation", subjectId: adapterInvocationId }; the stable event ID deduplicates an event already written. Custom stores should persist the checkpoint through adapter create, update, and read methods.

Ordinary adapter writes do not name the migration 8 column and remain compatible with schemas lacking it. If a checkpoint write carrying reconciliation fails, fallback retries the row once without that field, using legacy status: "ambiguous" plus error. Unknown outcomes therefore still settle without migration 8, but without stored checkpoint metadata. Apply PostgreSQL migration 8 through ensureSchema() in controlled startup or migrations to retain that metadata. An error inside an atomic PostgreSQL transaction first rolls it back; the legacy write runs outside that transaction on the fallback path.

On a store without atomic support, if the verdict cannot be written at all, no durable write after the call succeeds: neither verdict nor checkpoint is saved, as after a crash mid-call. A leftover running step can then re-run on recovery for an idempotent action under the same adapterInvocationId idempotency key, within the worker recovery budget. A reclaimed non-idempotent action with a running row without a matching durable handoff settles that step as unknown. A succeeded row or durable handoff instead ends reconciliation_required as an applied effect. Adapters should be idempotent or carry that stable key. The same exposure applies if two atomic attempts roll back and the fallback verdict cannot be written.

Once an invocation has a durable succeeded adapter row or accepted handoff, errors in Host store reads or writes raise RecoverableFinalizationError instead of ending it failed. This includes later adapter checkpoints, obligation reads, and the completion write in both before_adapters and after_adapters. Recovery also protects Host store operations before and around the handler when an earlier provider effect is recorded. Authorization, policy and handler callbacks retain their own failure semantics. Idempotent recovery repairs recorded success/handoff evidence without calling that step's provider. Non-idempotent interruption ends reconciliation_required instead of repairing the invocation. Lease loss retains its fencing error.

If neither record is durable, Host retries the failed handoff or marker write once. After a second failure it reuses degraded atomic finalization where available, otherwise writes the reconciliation_required verdict first, then attempts the succeeded marker with safe output, ExternalOperationAccepted when applicable, and AdapterInvocationSucceeded. Each fallback evidence write is attempted independently; the first error raises RecoverableFinalizationError after the remaining writes are attempted. A terminal verdict can retain missing evidence. If even the verdict cannot be saved, Host throws RecoverableFinalizationError; the row can remain running. Recovery may replay that unrecorded outcome for an idempotent action under its stable adapterInvocationId, within the worker budget. A reclaimed non-idempotent action instead ends reconciliation_required. A durable handoff takes precedence over its running row and is recorded as an applied effect with its external reference. A running row without such a handoff is settled as unknown. A succeeded row also ends reconciliation_required. With no rows or only failed rows, the existing non-idempotent interruption gates still fail the invocation.

For idempotent recovery, the handler still runs before the adapter loop. The loop reads each checkpoint before getInput() or adapter lookup. Succeeded rows and durable handoffs use stored adapter type, operation, vendor, input and output; a falsy new input or removed adapter does not skip evidence repair. Stable event IDs deduplicate replayed accepted and success events; newly repaired success events include recovered: true and stored input/output when available.

Recovery looks up the stable attestation ID. If present, Host reuses it and reapplies its satisfiesObligations updates without calling the extractor. If absent and stored output exists, Host calls extractExecutionAttestation with stored input/output and checkpoint createdAt and updatedAt as start/completion times. The extractor may run again after an interrupted append; it must return deterministic evidence for the same input. A handoff checkpoint with no output, or withheld output, skips extraction. Repair errors remain recoverable within the budget.

Known limits: a later step's definite provider failure or pre-call refusal can still end the invocation failed after an earlier step succeeded. Authorization denials, ordinary handler failures, validation/state-guard rejection, and unsatisfied policy obligations on recovery retain their existing terminal outcomes. These are decisions or application failures, not Host store errors. Idempotent recovery can call a provider again for an unrecorded running outcome, or for a definite failed row whose invocation failure verdict was lost. The handler still re-runs before the adapter loop. Saga compensation is unchanged. Withheld-output and refused-handoff reconciliation retain the degraded pattern. Adapter-row fencing and overdue-sweep/late-callback rules are described below.

Event appends are first-write-wins by event ID. Host re-appends lifecycle events under stable IDs on retry and recovery, and each later attempt carries a fresh sequence and timestamps and can carry a different payload. A custom store's appendEvent and appendEventWithOutbox must treat an ID it already holds as a no-op that keeps the first event: do not throw, replace, or merge it. A store that refuses these appends can leave recovery unable to converge, so the invocation stays running until the recovery budget settles it, even when the adapter effect succeeded. Custom stores that currently throw on a conflicting append need to change. The shipped stores enforce ID uniqueness across the whole store, not per tenant or space. The rule covers the outbox too: appendEventWithOutbox for an ID already stored adds no outbox row, including when the first append went through plain appendEvent, so that event is never published later. Keep outbox.shouldPublish deterministic for a given event ID. Custom store authors can run eventAppendChecks() or runEventAppendChecks({ store, tenantId }) to detect common first-write-wins violations through six within-space checks for plain, outbox and transactional appends. They cover pending, leased, retry-pending and published outbox rows, plus transactional outbox-after-plain. The checks are not exhaustive; the README lists known limits. Pause relays for the probe tenant: probes use real timestamps and mark their settled outbox rows published without sending anything. See the package README for probe and capability requirements.

Conditional adapter-row writes (8.0.0, issue #79)

PlatformHostStore.writeAdapterInvocation(input) is optional. Memory and PostgreSQL implement it; custom stores can keep their existing methods. Without it, Host retains unchecked adapter creates and updates, so a reclaimed worker can overwrite a newer worker's adapter checkpoint.

The input carries scope (tenant, space, invocation), a create or update mutation, a condition, and optional expectedStatuses. A lease condition requires a running parent with the supplied leaseOwner and leaseToken. A verdict condition requires the exact parent status and error written by this execution. Host also captures the handoff row ID as completionAdapterInvocationId, so externalCompletionDigest guards that row's callback output: an absent digest requires no recorded completion; a supplied digest requires that same completion. Other adapter rows retain the status/error and expected-row-status checks without the digest check. Omitting the captured row ID retains the conservative digest check on adapter writes. Absent error matches no error. Both parent and adapter must match scope. A create must also match the record's scope and refuses a duplicate ID. The method returns false when its conditions fail. Conditional updates reject succeeded or ambiguous to running or failed, including when callers omit expectedStatuses.

Host captures the supplied execution credentials before loading the invocation. It uses them for fenced invocation writes and leased adapter creation, retry preparation, success, failure, and ambiguity checkpoints. A refused lease or row-status check raises RecoverableFinalizationError. This prevents stale checkpoint writes; adapters still need stable idempotency keys because a lease cannot cancel a provider call already in flight. Inline writes use the verdict condition after this execution writes its own verdict; earlier unleased adapter writes retain their existing path.

Verdict-first fallbacks use the settled verdict condition after the terminal write releases the lease. Their expected row status is the last state observed or written by that execution. A changed parent status/error or row refuses the adapter update; a changed completion also refuses a write to the captured handoff row. These refusals emit invocation.adapter_evidence_refused (fabric.platform.invocation.adapter_evidence_refused) through the telemetry hook. The adapter row stays untouched, with no unchecked retry. Host still attempts AdapterInvocationAmbiguous and reconciliation evidence; withheld-output and refused-handoff success evidence may already have been appended before the refused marker write. A refusal is not an evidence-collector error. Thrown store errors are retained while each independent fallback write is attempted, then the first error is raised as RecoverableFinalizationError.

An inline writer preserving a sweep verdict does not adopt it as this execution's own verdict. Its adapter evidence keeps the unchecked inline path; conditional settled-parent enrichment is used only for a verdict this execution actually wrote. The inline guard reads the current row only when the execution snapshot or its patch carries pendingCompletion.

Budget exhaustion saves its plain verdict before reading evidence. It then enriches the parent through optional updateSettledActionInvocation, comparing that execution's exact status, error, and completion snapshot. Parent enrichment joins the independent evidence collector, alongside adapter checkpoints, events and reconciliation records. Refusal emits invocation.adapter_evidence_refused with evidence: "parent_enrichment" and is not an error; a missing updateSettledActionInvocation skips only parent enrichment. Evidence writes still run. A thrown store error is collected and raised as RecoverableFinalizationError after the remaining writes are attempted. The two optional store methods are expected together. Successful enrichment stores the error and adapterReconciliation before returning them; skipped or refused enrichment can leave replay with only the plain verdict. Stores omitting writeAdapterInvocation retain unchecked adapter writes. A retained handoff's reference is included in the initial budget verdict.

Subclasses of the built-in stores that override createAdapterInvocation or updateAdapterInvocation for encryption or auditing must also override writeAdapterInvocation. Checked writes can bypass the unchecked methods. Alternatively, explicitly disable the capability and accept the weaker stale-worker guarantee. Parent annotations similarly have their own updateSettledActionInvocation seam.

Atomic finalizers require transaction-scoped writeAdapterInvocation when the store advertises the capability and execution holds a lease. A missing member selects verdict-first fallback before transaction evidence writes. PostgreSQL locks the matching parent with FOR UPDATE before the adapter mutation in one SQL statement. Memory rechecks buffered lease and adapter predicates at commit and excludes claims and other conditional writes while applying the commit. A commit-time conflict rolls back and raises RecoverableFinalizationError. No schema migration is added by this capability; it uses the existing parent lease and verdict columns.

External-completion adapter writes use the callback's transaction-scoped updateAdapterInvocation when available, sharing its invocation lock. These are callback writes rather than worker-lease writes; legacy transactions without that member retain the outer-store write. The sweep retains its transaction-scoped reconciliation append and parked/overdue settlement rules.

Bounded worker recovery (8.0.0)

recoveryMaxAttempts is an optional positive integer. Its effective default is max(5, retryableExecutionMaxAttempts); Infinity is rejected. Both caps count the same worker claims. Construction rejects an explicit recoveryMaxAttempts below retryableExecutionMaxAttempts. The governance cap stops transient pre-policy deferrals at its cap; the recovery budget stops resumed execution above its cap. With the defaults, governance retry exhaustion therefore happens on claim 5 before recovery exhaustion could happen on claim 6.

Host checks a resumed leased running invocation immediately after lease ownership, before normal action resolution, ambiguity scans, authorization, the handler, or adapter work. When attemptCount > recoveryMaxAttempts, it settles reconciliation_required with recovery attempts exhausted (n/max). It writes that verdict before resolving the action or reading adapter evidence, releasing the lease. A running row without a matching durable handoff receives unknown-outcome settlement. A recorded ambiguous row enriches the parent error and adapterReconciliation, as well as adapter/event evidence, using its stored reconciliation evidence and a conditional parent update. A durable handoff takes precedence over that step's running row. It is recorded as an applied effect with its external reference in the message and, on governance stores, the reconciliation record. It is not marked ambiguous solely because its marker was lost. If resolution or row reads throw, or no relevant row exists, the plain verdict already written stands. Enrichment failure can retain an evidence gap. Transition telemetry is emitted once when the status changes. If the verdict is unwritable, Host throws RecoverableFinalizationError; later claims continue but do not execute mutation code.

The counter counts worker claims, including the first run, rather than provider calls or completed recoveries. With the default of 5: the first run plus four recoveries; the sixth claim settles. A raised governance cap raises the implicit recovery budget with it. Inline/direct execution does not increment the counter. Approval acceptance sets it to at least 1 without incrementing it on resume. Approval resume holds a temporary lease and uses the existing count: a count equal to the budget is admitted, while a count above the budget settles reconciliation before the handler. Approval does not reset an exhausted budget. A worker dying before reaching the check consumes a claim without calling a provider at that point. Parked handoffs have no lease, are not claimed by workers, and are outside this budget. The existing parked shortcut and ambiguity scan remain in place. retryableExecutionMaxAttempts still limits pre-policy deferrals. No new store method is required.

  • Callers. Inline submitAction() without a dispatcher and direct executeInvocation() can now reject with an error whose name is "RecoverableFinalizationError" where 7.x returned failed. The class is not exported. Without a lease, the invocation stays running and workers do not claim it. Before a handoff is durable, call executeInvocation() again yourself and cap your own retries. Once a handoff is durable, re-running executeInvocation() on the unleased running row returns without resuming execution (it first settles any step already recorded ambiguous). If execution stopped before parking, callbacks are refused with still_executing until a sweep. Declare completionDeadlineMs for actions that hand off so the sweep surfaces the row, then reconcile it per the external-completion runbook. The leased worker budget does not bound unleased calls. A previously leased direct call retains its lease until expiry and can also be recovered by a worker. Terminal degraded verdicts can retain evidence gaps and are not automatically repaired.

A deadline sweep retains the handoff and sets pendingCompletion.overdueAt with its reconciliation_required verdict. A late callback settles that verdict only when the handoff also has parkedAt, proving Host reached parking after its remaining steps and finalization. An unparked handoff stays in reconciliation even if later-step ambiguity evidence is missing; the callback's redacted result and outcome are recorded as evidence for an operator without applying the action's result schema. This evidence-only behavior applies to invocations already reconciliation_required; callbacks for unparked running invocations are refused with still_executing. Any parked row without overdueAt, including a 7.x row, still uses the old "did not complete by" error substring. That compatibility path is weaker: an unrelated error containing the substring on a parked row lacking the marker can also authorize settlement.

reconcileOverdueCompletions() re-reads each listed candidate and checks it is still running, unleased, due, not already marked overdue, and waiting on the same adapter invocation and external reference. With transactionWithEvents and transaction-scoped getActionInvocationForUpdate, the check and verdict/marker write share a row lock. Reconciliation evidence shares the transaction when appendExternalReconciliation is available; otherwise it is written on the outer store and may survive rollback. A custom transaction exposing getActionInvocationForUpdate without appendExternalReconciliation makes the sweep append on the outer store while holding the row lock. If the reconciliation table has a foreign key to the invocation, that append can block on the held lock. Implement both members in the same transaction. Without the transaction lock, Host re-reads immediately but a read/write race allows a concurrent change between that read and write to be overwritten.

Inline execution preserves the stored reconciliation verdict while committing independent adapter checkpoints, events, and reconciliation records, including references from refused handoffs. If it reaches parking after the sweep, it commits the handler result and parkedAt on the same handoff, retaining status reconciliation_required, the sweep error, and overdueAt. Successful after_adapters finalization commits the deferred domain events because the handler and remaining adapters have succeeded. Inline callers receive the latest record observed by the preserving writer, merged with its evidence update, after these writes succeed. No post-attempt read is needed. Leased paths retain RecoverableFinalizationError on fencing failure. The transaction lock serializes the check with the sweep where available; stores without it retain a read/write race. In-flight adapters and earlier domain writes are not undone. Verdict-first fallbacks attempt independent evidence writes before raising the first failure as RecoverableFinalizationError. Reconciliation-log failures leave the sweep error unchanged. Custom stores must preserve and reload optional overdueAt as a Date. PostgreSQL hydrates existing JSONB without a new migration. The worker cycle sweeps before claiming; sweepOverdueCompletions: false disables this step.

Circuit-open refusals and deadline expiry before execution stay failed. Host-store errors in prepareAttempt become recoverable when an earlier success or handoff is durable. Returned permanent_failure, exhausted transient_failure, and exhausted non-timeout adapter throws stay failed, unless reading any field of the reply throws: Host copies the reply before interpreting it, so such a reply takes the unreadable-reply path to reconciliation. Adapters use permanent_failure or transient_failure for definite non-effects; no additional definite-failure flag is needed.

Adapters still need a stable provider idempotency identity and an explicit reconciliation path for ambiguous remote outcomes. A non-idempotent action with unknown side effects must fail closed for operator reconciliation; it must not blindly rerun after a stale lease.

State-machine guards run with trusted entity state, actor, schema-parsed parameters, invocation ID, and transaction-bound database context. A guard that returns false or throws fails closed before the handler runs. Transaction providers should expose transaction-scoped getEntityState() so the read, domain write, event append, and invocation finalization use the same database snapshot.

An idempotent action can resume in its target state without a self-loop only if the event that set the current recorded state was written by the same actionInvocationId. A new invocation validates normally and fails unless the machine defines that edge. Use a self-loop for a new mutation, or the same idempotency key to deduplicate to the original invocation at submission.

Stores and mutation transactions may implement getEntityStateSource(tenantId, spaceId, entityType, entityId), returning { state, actionInvocationId } from the event selected by getEntityState(), or undefined when provenance is unavailable. Host prefers the transaction method, then the store method. Without either method, it uses transaction listEvents(), else store listEvents() when available, selecting the subject's highest-sequence event with a string payload.toState. The returned state and invocation writer must match the current state and invocation. Missing provenance leaves normal validation in force. Memory and PostgreSQL stores implement the method; memory transactions include pending events.

Dispatcher submission failures leave the invocation pending. Re-submit the same idempotency key to retry the stable workflow ID. A kind: "saga" action must be mapped to a durable worker-side SagaImplementation; direct execution through the atomic Host path is refused.

Runtime observability and health

Pass a vendor-neutral telemetry callback or { record } sink to the Host, action worker cycle, or outbox relay. Lifecycle records use the stable names exported by PLATFORM_HOST_METRIC_NAMES. Telemetry is best effort, so a metrics backend outage cannot alter governed execution.

import { getPlatformHostHealthSnapshot } from "@fabricorg/platform-host";

const health = await getPlatformHostHealthSnapshot({
  store,
  tenantId,
  spaceId,
  workers: [{ lastHeartbeatAt, staleAfterMs: 30_000 }],
});

Health responses contain only tenant/space-scoped aggregate counts. Invocation backlog, running and expired leases, approval waits, reconciliation-required work, outbox backlog, expired leases, and dead letters. Parameters, results, actors, event payloads, and errors are never returned. An unavailable source is unhealthy and not ready; stale workers and operational lease, dead-letter, or reconciliation findings are reported as readiness reason codes. Approval waits remain visible without making a healthy worker pool unready.

Agent-facing gateway contract

The application gateway carries these responsibilities, and the model carries none of them, which is the division that keeps a model swap from being a security review.

  1. authenticate a tenant- and registration-bound credential;
  2. derive actorId and actorType server-side;
  3. filter discovery to explicitly reviewed actions in the current grant;
  4. require a stable idempotency key for every mutation;
  5. stage private or large content and submit only an opaque reference where necessary;
  6. pass the opaque admission ID as authorizationBindingId;
  7. surface actionInvocationId, status, approval state, and privacy-safe errors;
  8. provide status and reconciliation operations scoped to the same registration.

The agent must never call action handlers, adapters, Temporal workflows, or the database directly. Temporal may dispatch and recover a Host invocation, but it is not a second mutation authority.

Production checklist

  • Register each mutation as a FabricModule action with a stable schema and declared events.
  • Configure both submission and execution-time authorization for delegated agents.
  • Use a transaction provider for atomic domain writes and canonical events.
  • Configure a durable dispatcher/worker; inline execution is only for tests and local development.
  • Keep secrets out of parameters and use redactActionParameters as defense in depth.
  • Configure redactAdapterOutput(actionId, adapterType, operation, output) before recording provider output. Adapter rows, AdapterInvocationSucceeded, and extractExecutionAttestation receive its redacted output. If the hook throws or returns null, an array, or a non-object, Host withholds output and records reconciliation_required with safe success/accepted evidence and supported reconciliation evidence. A first accepted reference remains pending. The finalization transaction contract below governs ordering and rollback.
  • Configure redactErrorText(context, message) for caught handler/execution errors, adapter errors and ambiguous reasons, and completion errors. Exported ErrorTextRedactionContext supplies the action and source plus adapter/provider details where applicable. Host fixed text bypasses it; circuit-open and consistency messages use adapter context. Empty error input bypasses the hook unchanged. For non-empty input, throwing or returning a non-string or empty string uses a fixed placeholder on execution paths; completion error redaction instead refuses with non-retryable redaction_failed before writes.
  • Configure redactExternalCompletionResult(actionId, provider, result) before merging, schema validation, and persistence. It covers recorded results, including results attached to failed callbacks, plus completed invocation results, adapter output and completion events. Class instances and Dates are accepted as non-null, non-array objects. A throw or null, array, or non-object return refuses as non-retryable redaction_failed before writes; exhaustive refusal switches need that case. Completion digests use redacted values. A matching legacy raw incoming digest is acknowledged before invoking hooks; historical records remain intact. Contradiction detection compares retained values otherwise. Redactors should be deterministic and stable across deploys; a changed redactor can make a repeat look like different evidence.
  • Keep domain events/results, policy/HITL evidence, explicit attestations/reconciliations, saga/approval inputs and outbox publisher errors audit-safe. Parameter-schema issue messages used for validation_failed, the HITL rejected reason, policy block reasons and action-result validation paths are not passed through redactErrorText. Worker onError exceptions are also outside these hooks. Independently of hook configuration, refused fenced writes inside an adapter step rethrow; protecting the new owner's adapter row also requires the optional writeAdapterInvocation capability; refused-handoff ordering and audit events also change without the hooks.
  • Declare admitSubmission on actions whose parameters must be verified against trusted context (such as a secret reference the tenant's store must hold) before they are persisted; Host 7.3.0 and later runs it before writing anything for the submission, on a copy of the parameters it took when submitAction was called, and refuses parameters that are not JSON data.
  • Use stable command and provider idempotency identities.
  • Revalidate resource scope before prospect-visible or otherwise external adapter effects.
  • Resume approvals through resumeApprovedInvocation() instead of calling mutation code directly.
  • Rebuild projections from listEvents() with sequence-monotonic checkpoints.
  • Test policy denial, tenant isolation, revocation, adapter failure, crash recovery, and idempotent replay.
  • Certify PostgreSQL or Lakebase migrations, concurrency, failover, backup, and restore in the target environment; this repository's SQL adapter suite is deterministic rather than a live database test.

See Agent HITL for approval routing and Mutation pipeline for stage ordering.

Degraded adapter finalization

For withheld output and refused handoffs (immediate completion or a second handoff), Host uses transactionWithEvents when the transaction supplies updateAdapterInvocation, updateLeasedActionInvocation for a leased invocation, and appendExternalReconciliation for withheld output or refused handoffs on a governance-capable store. Leased finalization also needs transaction-scoped writeAdapterInvocation when the store advertises it. These optional members must share the event/verdict transaction; the adapter update must enforce the store method's supplied tenant, space, and invocation scope. Both built-in stores provide them when configured with a transaction provider. Custom stores must implement them to get this atomic behavior.

When atomic finalization succeeds, evidence events, any withheld-output or refused-handoff reconciliation entry, the adapter's succeeded marker, and the terminal reconciliation_required verdict commit together. Host writes evidence and the marker before the fenced verdict, which releases the lease, then emits status telemetry after commit. It retries the whole transaction once on a non-lease error. If the retry also fails with a non-lease error, Host selects the verdict-first fallback described below. Lease loss is not retried or converted to fallback; it raises RecoverableFinalizationError. Atomic rollback leaves the invocation and adapter row running until a retry or fallback commits. If lease loss or an unavailable fallback verdict prevents finalization, the invocation remains reclaimable and the adapter can run again under the same adapterInvocationId idempotency key for idempotent actions within the worker recovery budget. Non-idempotent reclaim inspects its checkpoints instead of replaying a call.

Without the required transaction members, or after two non-lease transaction failures, Host keeps the verdict-first order: the reconciliation_required verdict precedes evidence and the adapter marker. It retries the verdict write once, except on lease loss. After the verdict is durable, Host attempts each evidence write independently: a failed event, reconciliation append, or adapter checkpoint does not skip the remaining writes. Host raises the first evidence failure as RecoverableFinalizationError only after those attempts finish. This includes unknown-outcome settlement and post-success degraded finalization. Failed writes can still leave a terminal verdict with missing evidence; terminal replay does not repair that evidence gap. If both verdict-write attempts fail, the adapter can run again on recovery for an idempotent action within the worker recovery budget, the same exposure as a crash mid-step. A reclaimed non-idempotent action settles a running checkpoint as unknown.

A refused handoff's provider reference is included in the step's AdapterInvocationSucceeded event even when explicit adapter output omits it. Capable atomic transactions append its reconciliation record with the step's evidence. The fallback independently attempts the reference-bearing event, the governance reconciliation append, the outer recordCompletionReconciliation append, and the adapter marker. Both reconciliation appends use the same stable id to deduplicate repeated attempts. A failure of either append is reported after the remaining fallback evidence writes are attempted. A non-sweep verdict may receive a log-unavailable error note; a preserved sweep verdict keeps its error. After successful atomic finalization, the outer append retains its existing tolerated-failure behavior. If its annotation write fails, Host raises RecoverableFinalizationError while keeping the committed verdict and adapter marker intact; terminal replay retains the verdict.

On this page