npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@fabricorg/platform

v1.22.0

Published

Generic, vertical-agnostic runtime for ontology-based business applications. Provides actions, modules, events, policies, state machines, adapters, displays, projections, privacy, and evidence contracts. Zero runtime dependencies; portable across any data

Readme

@fabricorg/platform

A portable runtime for ontology-based, agent-native business applications. Zero dependencies. Bring your own database client.

npm install @fabricorg/platform

Hello, action

import { z } from "zod";
import type { ActionDefinition, ActionContext } from "@fabricorg/platform/actions";

const greet: ActionDefinition<unknown> = {
  id: "demo.greet",
  schema: z.object({ name: z.string() }),
  handler: async (ctx: ActionContext<unknown>, params: { name: string }) => {
    return { greeting: `Hello, ${params.name}!` };
  },
};

That's the smallest unit. From here, you compose actions into a FabricModule<TDb>, register the module at startup, and call invokeAction("demo.greet", ...) from any of three call paths (authenticated user, signed token, or system/agent). Every call passes through the same pipeline: policy → state machine → handler → adapters → events → projections.

For a complete walkthrough see https://platform.techfabric.com/docs/getting-started/quickstart.

Why use this

You're building a governed business application — not a CRUD app. You need:

  • A single, auditable entry point for every mutation
  • Policies that gate every change before it happens
  • Events as evidence (not retrofitted logs)
  • Agents and humans treated identically by policy
  • A vertical-specific ontology layered on a portable runtime

That's what this package gives you. Nothing more.

What's in the box

| Subpath | What you get | |---|---| | @fabricorg/platform | Re-exports everything below | | @fabricorg/platform/discovery | Portable discovery-surface declarations and validation | | @fabricorg/platform/actions | ActionDefinition, ActionContext, SagaImplementation | | @fabricorg/platform/policies | PolicyEvaluator, PolicyContext, code/data/hybrid evaluation | | @fabricorg/platform/state-machines | StateMachineDefinition, structural and guard-aware transition evaluation | | @fabricorg/platform/events | AssetEventEnvelope, EventTypeRegistry | | @fabricorg/platform/projections | Replay/snapshot framework | | @fabricorg/platform/adapters | AdapterRegistry, executeWithAdapterRetry, in-process circuit breaker (InMemoryAdapterCircuitBreaker, AdapterCircuitBreakerRegistry, AdapterCircuitOpenError) | | @fabricorg/platform/modules | FabricModule<TDb>, createModuleRegistry | | @fabricorg/platform/manifest | exportModuleManifest, exportModuleManifestBundle, ModuleManifest | | @fabricorg/platform/ids | createFabricId, FABRIC_ID_PREFIXES | | @fabricorg/platform/privacy | Redaction + data classification | | @fabricorg/platform/evidence | Compliance evidence packets: generateEvidencePacket, verifyEvidencePacketChecksum, canonicalJson (see Evidence packets) | | @fabricorg/platform/governance | External footprints, delegated principals, obligations, attestations, and reconciliation | | @fabricorg/platform/objects | Shared object-type contracts | | @fabricorg/platform/testing | In-memory adapter registry, fake ActionContext, deterministic IDs |

Modules may publish versioned ViewContracts. A view may also declare a portable parameterSchema; ProjectionHost validates those inputs and keeps each canonical parameter identity in a separate snapshot. replayView filters declared event schema versions and requires an explicit upgradeSnapshot function before resuming an older compatible snapshot; manifests serialize the logical shape, parameter schema, and metadata but never executable functions or initial state. Physical stores remain adapter concerns.

Composing a vertical

Verticals declare a FabricModule<TDb> that registers their actions, policies, state machines, events, and adapters with the platform:

import type { FabricModule } from "@fabricorg/platform/modules";
import { createModuleRegistry } from "@fabricorg/platform/modules";

const myModule: FabricModule<MyDbClient> = {
  namespace: "demo",
  version: "1.0.0",
  objectTypes: ["Widget"],
  actions: [greet, /* ... */],
  policies: [/* ... */],
  stateMachines: [/* ... */],
};

// At app startup:
const registry = createModuleRegistry([myModule]);

The platform never auto-loads a module. The host app composes an instance-scoped registry and injects it into its hosts. Experience roles, slots, action intents, and display rendering live in @fabricorg/experience-contracts, carried through the namespaced fabric.experience/v1 extension.

Staged descendant invocations

An action may declare stagesInvocations as the child action IDs it is allowed to stage. Its handler returns requests through ActionResult.stagedInvocations; an after_adapters finalizer may add requests through ActionFinalizationResult.stagedInvocations. Each request contains only a stable key, an action ID, and parameters. Actor, tenant, space, correlation, causation, authorization, provenance, and child identity remain Host-owned.

The parent action may map an allowlisted child action ID to a Host-owned principal name through stagedInvocationPrincipals. StagedInvocationRequest has no principal, actor, or authorization field, and the Host request-field allowlist rejects those extra fields from a handler or finalizer. Module registration validates that every mapping key is in stagesInvocations and that each principal name matches [a-z][a-z0-9._:-]{0,127}. The Host composition registers each name with its actor ID and actor type, records the selected name when it stages the child, and resolves that durable name at dispatch. @fabricorg/platform-host 8.7.0 and later enforces these rules and refuses an unregistered name during staging or dispatch. Earlier Host versions ignore stagedInvocationPrincipals and dispatch the child as the parent's actor. Upgrade the Host rollout described in its staged-invocation documentation before shipping a module that declares a principal mapping.

Module registration rejects unknown targets, self-targets, capture-authority targets, and targets in another module unless that module is a declared dependency. A staged child is not delegated under the parent's authorization decision: dispatch submits it through the current registered action, entitlement, authorization, admission, runtime-evidence, and dispatcher pipeline. See the @fabricorg/platform-host staging contract for transaction, recovery, release, and limit semantics.

Exporting a module manifest

Downstream tooling — semantics exporters, docs generators, tool generators — often needs a module's ontology as data rather than live code. @fabricorg/platform/manifest exports a stable, JSON-serializable, versioned description of any FabricModule:

import { exportModuleManifest } from "@fabricorg/platform/manifest";

const manifest = exportModuleManifest(myModule);
const json = JSON.stringify(manifest, null, 2);

exportModuleManifest is a pure function of the module object: it does not touch the registries and the module does not need to be registered first. Declaration order is preserved everywhere, so the same module always produces byte-identical JSON. Function fields (handler, policy evaluate, transition guard, dynamic targetState, adapter getInput) are never serialized — the manifest contains definitions only, never raw parameter values, secrets, or runtime data. Manifest v2 object registrations may include PortableJsonSchema, qualified relations, namespaced semantic annotations, and enforcement-owned invariants. Actions whose validators expose toJSONSchema() include parameterSchema and optional resultSchema definitions. normalizeModuleManifest and normalizeModuleManifestBundle let v2 readers accept v1 input without promising down-conversion.

An entity schema does not validate arbitrary writes through TDb. Persisted-record validation requires an explicit Host/database adapter. For actions without finalize, when an action declares resultSchema, Platform Host validates the public result after the handler and before events or adapters; failure rolls back domain writes only when the Host store has a transaction provider that includes them.

An action may declare failureSchema, a SchemaValidator<ActionFailure> for the data its handler returns with { success: false }. ActionFailure is { code, data? }: a fixed code chosen by the action, using the same syntax as an admission refusal code, and optional plain JSON detail. ActionResult is unchanged. A supporting host records only the schema's parsed output beside the failed status, so the schema should allowlist what may be stored. @fabricorg/platform-host 8.21.0 and later records it (see its declared handler refusals), refuses an action that declares it on a store without support, and does not read returned data for an action without it. Registration rejects a failureSchema without a safeParse function.

An action may also declare admitSubmission, an async check that decides whether submission parameters may be recorded. It receives the trusted tenantId, spaceId, actorId and actorType, the submitted parameters and a signal (ActionAdmissionSignal, a structural subset of AbortSignal; Host passes a real one), and answers { admitted: true } or { admitted: false, code } with a fixed code. @fabricorg/platform-host 7.3.0 and later runs it after authorizing the submitter and before persisting parameters, refuses on a throw, timeout or any other answer, and passes the admission time to the handler as ActionContext.admittedAt. An older host ignores the field, so a handler that relies on it should refuse without ctx.admittedAt. Registration rejects an admitSubmission that is not a function. Host defaults to writing nothing for a refused submission. Opt-in idempotency.recordRefusals reserves keyed definitive refusals with fixed evidence and empty parameters; see the Host refusal contract for identity, digest and rollout rules.

The action lifecycle

Every invokeAction(id, params) call goes through:

  1. evaluatePolicies — every policy registered for the action runs (code/data/hybrid). A single block halts the invocation. Policies may return guidance (factsUsed + typed correctiveActions) so hosts can show exactly why a block happened and what the operator can do next. Corrective actions declare kind: "invoke_action" | "navigate" | "manual" so UIs do not guess whether a remediation is executable.

    Code-policy evaluators may throw RetryableExecutionError(message, { cause }) for transient dependency failures. Import it and isRetryableExecutionError from @fabricorg/platform or @fabricorg/platform/policies. The predicate recognises matching name and code across package copies. Platform propagates this error; Platform Host retries pre-handler governance only for a leased, idempotent invocation below its retryableExecutionMaxAttempts cap (default 5), after lease expiry, before policy evidence is written. Inline execution, non-idempotent actions, approval resume, and exhausted attempts fail terminally. Obligation resolution and persistence are outside this governance retry region. RetryableExecutionError does not opt a handler into rollback retry. Host also applies recoveryMaxAttempts before resumed leased execution. It uses the same claim counter and defaults to max(5, retryableExecutionMaxAttempts). An explicit lower recovery cap is rejected.

  2. State-machine validation — if the action's target entity is bound to a state machine, the Host reads authoritative state at the mutation boundary, validates the requested transition, and executes its guard with trusted entity, actor, parameter, invocation, and database context. A false or throwing guard fails closed.

  3. Handler — actionDef.handler(ctx, params) runs inside a single TDb transaction. Handler parses its own input via its schema (single source of truth).

    A handler or its transaction wrapper may throw ReconciliationRequiredError(message, { cause }) when a domain effect may already have committed and an operator must decide what to do. Import it and isReconciliationRequiredError from @fabricorg/platform or @fabricorg/platform/policies. The stable name and EXECUTION_RECONCILIATION_REQUIRED code let the predicate recognise a second package copy. Platform Host honours this signal at its handler-transaction catch, recording terminal reconciliation_required instead of failed. For example, a recovery-receipt store can check its own stored result against the current action schema and declared events before handing it back, and signal a mismatch. Wrappers cannot tell which Host transaction they wrap and should not translate internal Host errors by matching messages. Put non-sensitive operator detail in the message because cause is not stored. Atomic transactionWithEvents stores roll back the attempt's domain events and StateTransitioned together; built-in transaction-only stores leave domain writes and already appended events persisted beside the reconciliation record. This does not change pre-handler governance, state-guard, adapter, or finalization failure semantics; see the Host boundary and rollback contract.

    Provider-dependent records can use the optional action-level finalize hook through defineFinalizingAction. It requires an atomic, immediate after_adapters action; idempotency is not required. Before adapters, Host normalizes the hook's parameters and public handler data with JSON.parse(JSON.stringify(value)), then validates the normalized JSON: Dates become ISO strings, undefined object properties drop, class instances use their JSON representation, and non-finite numbers become null. Serialization failures such as cycles or BigInt fail before adapter execution. Host strips private eventResultFields from hook handler data; handler events are normalized separately. The hook receives copies of those saved inputs and ordered succeeded/skipped stored redacted adapter outputs, plus transaction-bound db without services. Hook event schema versions default to action.version when omitted. A handler may return a strict-JSON plain-object adapterPreparation alongside data. Finalizing getInput(params, handlerResult, adapterPreparation?) receives a copy as its third argument, or undefined for absent preparation and older checkpoints. The channel is excluded from public results, hook input and event extraction. Host saves it separately within the 256 KiB checkpoint limit, retains it while running or reconciliation is required, and removes only that key with terminal completion/failure or cancellation. Derived adapter inputs still use redactAdapterInput and its existing durable evidence contract. Non-finalizing handlers returning preparation fail before adapter delivery. defineFinalizingAction checks ctx.adapterPreparationProtocol === "v1" after the handler returns preparation and refuses unsupported hosts; no preparation needs no new capability. Checkpoints use atomic-after-adapters-v2 with preparation and atomic-after-adapters-v1 without it. Replay refuses mismatched shapes before adapter delivery; settlement clears preparation and restores v1. Upgrade all workers before handlers return preparation. Older Hosts refuse in-flight v2 checkpoints, requiring reconciliation after recorded effects or settling failed without recorded effects. An older Host does not clear preparation, so a row it settles keeps the v2 checkpoint and its preparation. Handler capability and manifest protocols stay v1. It returns declared events and/or a shallow result patch. The manifest exports only finalization: { protocol: "atomic-after-adapters-v1" }, not the callback. The helper refuses older hosts before handler code runs. See the Host finalization contract for transaction requirements, validation, rollback and reconciliation semantics. With a compatible durable preparation checkpoint, Host recovery reuses recorded outputs and replays finalization without rerunning the handler. Missing or incompatible evidence retains effect-aware refusal; see the Host finalization contract for rollout and limits.

  4. Adapters — for each actionDef.adapterSteps, the registered implementation runs via executeWithAdapterRetry (idempotent retry, exponential backoff, and an optional per-adapter circuit breaker; see Adapter circuit breakers). Adapters may classify outcomes as success, transient_failure, permanent_failure, timeout, or ambiguous; only transient idempotent outcomes are retried. Platform Host routes returned ambiguous and timeout outcomes, timeouts thrown from adapter.execute (detected from the adapter deadline's abort signal or an error message matching /timeout|deadline|timed?\s*out/i), contradictory results in either direction (success: true with a non-success outcome, or success: false with outcome: "success"), uninterpretable replies (including getters that throw before Host interprets the reply), and unrecognised outcome strings to reconciliation_required. Settlement is atomic on capable stores and verdict-first otherwise; unwritable fallback verdicts can leave the step eligible for recovery under its idempotency key, while evidence failures after a committed verdict can leave evidence gaps. Post-success Host write failures recover from durable success/handoff checkpoints without calling that provider again, or settle reconciliation_required when Host cannot save the outcome after one write retry. Recovery repairs stable-ID events and attestations. The optional Host recoveryMaxAttempts (positive integer, default max(5, retryableExecutionMaxAttempts)) bounds worker claims before execution; exhaustion settles reconciliation. With no durable checkpoint or verdict, only idempotent actions replay a running step under the stable key within that budget. Non-idempotent reclaim settles running or succeeded steps to reconciliation; no rows or only failed rows retain failure. A deadline sweep followed by a late callback can settle completed if a later step's ambiguous evidence was never written. See the Host recovery limits. Host store errors after a durable success or handoff, including prepareAttempt on a later step, are recoverable. Pre-call deadline expiry and circuit-open refusals retain failed semantics, as do returned permanent failures, exhausted transient failures, and exhausted non-timeout adapter throws. Adapters use permanent_failure or transient_failure for definite non-effects; no additional definite-failure flag is needed.

  5. Events — domain events are appended; projections derive read models on next replay.

  6. Completion — invocation status is marked, telemetry emitted.

validateActionParameters is also exposed for preview/dry-run paths but is not part of the execute pipeline.

Adapter circuit breakers

AdapterImplementation.circuitBreaker configures a breaker for one adapter operation:

const sendAdapter: AdapterImplementation = {
  adapterType: "email",
  operation: "send",
  vendor: "mailco",
  idempotent: true,
  circuitBreaker: { mode: "enforce", failureThreshold: 5, windowMs: 60_000, cooldownMs: 30_000 },
  execute: async (input, context) => ({ success: true }),
};

AdapterCircuitBreakerRegistry creates one InMemoryAdapterCircuitBreaker per key (default adapterType:operation) from an adapter's config on first use, and none for an adapter without a config. The first config seen for a key wins: later conflicting configs reuse the existing breaker without throwing. Adapters sharing a key should use the same configuration.

The default key is shared across tenants, spaces, and vendors within one registry. Failures for one tenant can therefore open the breaker for another. Opt into isolation when failure domains differ:

import { AdapterCircuitBreakerRegistry, scopedAdapterCircuitBreakerKey } from "@fabricorg/platform/adapters";

const breakers = new AdapterCircuitBreakerRegistry({ key: scopedAdapterCircuitBreakerKey });
const scope = { tenantId: "tenant-1", spaceId: "space-1" };
const breaker = breakers.forAdapter(sendAdapter, scope);
// Exact custom-key lookup without creating a breaker:
breakers.getByKey(scopedAdapterCircuitBreakerKey(sendAdapter, scope));

The helper URI-encodes tenant, space, vendor, and adapter identifiers to avoid delimiter collisions, ending with the readable adapterType:operation for ordinary identifiers. Missing space or vendor is distinct from an empty string (vendor is required by the TypeScript adapter contract). Undefined scope uses a separate vendor-specific unscoped namespace rather than rejecting the call. Calls without scope share that namespace; pass scope for tenant isolation. Keys appear in telemetry and errors, so use non-secret identifiers. Breakers are never evicted: a scoped key creates one breaker per tenant, space, vendor and operation for the life of the registry, and those keys are high-cardinality, so do not use them as metric labels. get(type, operation) retains its default-key lookup; use getByKey(key) for custom keys. A custom key(adapter, scope) can select other failure domains.

executeWithAdapterRetry({ ..., circuitBreaker }) asks it for admission immediately before every attempt, with no await between admission and the execute call, and records the outcome of every attempt that reached execute. Put any awaited work an attempt needs first (for example, writing the attempt number) in the optional prepareAttempt(attempt, maxAttempts) hook, which runs before admission. If prepareAttempt throws, no admission is taken and no outcome is recorded; the error is classified and retried or rethrown like an error thrown by execute. Without circuitBreaker and prepareAttempt the retry loop is unchanged. @fabricorg/platform-host 7.4.0 and later wires this up for every adapter step.

Scope. The breaker is in-process memory. It is not distributed: each process, replica or Host instance with its own registry trips on the failures it observes itself, and state is lost on restart. To share a breaker across processes, implement the AdapterCircuitBreaker interface over shared storage and supply it through an AdapterCircuitBreakerProvider.

States. closed → open → (after cooldownMs) half_open → closed or back to open. Half-open admits one probe call. A probe success closes the breaker and clears its window, and a probe failure reopens it and restarts the cooldown. In enforce mode, other calls are refused while the probe is in flight. The probe holds its slot until it records an outcome or its lease of probeLeaseMs expires (default max(cooldownMs, windowMs), independent of the cooldown, so cooldownMs: 0 still admits one probe at a time). After the lease expires the next call becomes the probe. check() is a side-effect-free preview: it does not commit an elapsed cooldown, take the probe, change the epoch or emit telemetry.

Stale outcomes. An outcome may change the breaker's state only if the call was admitted in the breaker's current epoch. The epoch advances on every state change (including the one an elapsed cooldown commits), every manual-override change, and every probe grant. Each admission returned by acquire() carries its epoch as generation, and executeWithAdapterRetry passes it back to record(). An outcome from an earlier epoch is dropped: it does not close or reopen the breaker, does not resolve or free the probe slot, and is not added to the rolling window, so it cannot help trip the breaker later. This covers a replaced probe that reports after its replacement closed the breaker, and a call admitted while closed whose failure arrives after the breaker opened. Outcomes from the current epoch count exactly as described under Thresholds. A direct caller that records without an admission, or with one that has no generation, is treated as current: the outcome is sampled, can trip a closed breaker and resolves an outstanding probe.

Thresholds. failureThreshold is a failure count, with the same rule as the .NET port. Let M = minimumSamples ?? failureThreshold. Once at least M outcomes fall within the last windowMs, a recorded failure opens the breaker when either:

  • the most recent failureThreshold outcomes are all failures, or
  • the failure ratio in the window is at least failureThreshold / M.

Without minimumSamples this means "failureThreshold consecutive failures". With failureThreshold: 10, minimumSamples: 20 the breaker also opens at a 50% failure rate over at least 20 calls. assertAdapterCircuitBreakerConfig rejects a non-positive or fractional failureThreshold or minimumSamples, a non-positive windowMs, and a negative cooldownMs.

Modes. monitor runs the same state machine and telemetry but never blocks a call. Calls that enforce mode would have refused are reported as would_reject. enforce refuses calls while the breaker is open: execute is not called, and executeWithAdapterRetry throws AdapterCircuitOpenError (code: "ADAPTER_CIRCUIT_OPEN", adapterKey, state, attempt, retryAfterMs when known). If the breaker opens between attempts, retrying stops and the same error is thrown. Use isAdapterCircuitOpenError(error) to recognise it, which also works across duplicate copies of this package.

Outcome mapping (classifyCircuitBreakerOutcome):

| Adapter outcome | Counts as | |---|---| | success | success | | transient_failure | failure | | timeout | failure | | ambiguous | failure (no definite answer is a health signal, even though Host routes it to reconciliation) | | permanent_failure | ignored (the dependency answered and rejected the request; not a dependency failure) | | thrown error | the kind classifyThrownError returns, transient_failure by default, mapped as above |

Manual override. manualOverride: "force_open" | "force_closed" in the config, or breaker.setManualOverride(...) at runtime (undefined clears it). An override pins the reported state and suspends automatic transitions. Outcomes of calls admitted under the override keep being recorded; setting or clearing the override starts a new epoch, so outcomes of calls admitted before the change are dropped as stale. Like an automatic open, force_open blocks only in enforce mode. Clearing returns the breaker to closed with its window intact.

Telemetry. Pass onEvent to the breaker or registry to receive state_change (with a reason), rejected and would_reject events. Errors the callback throws, and promises it rejects, are swallowed so telemetry cannot change a call's outcome. Events are delivered after the operation that produced them commits, never part-way through a decision or a record. Committing an elapsed cooldown is its own step, delivered before acquire() decides, so a callback that forces the breaker open on cooldown_elapsed refuses that call. A callback may call back into the breaker: it sees committed state, its changes apply from the next decision on, and the events they produce are delivered after it returns, in order. A callback never revokes an admission that is already committed, so there are two exceptions to the cooldown rule above: a breaker call made from inside a callback decides before its own cooldown_elapsed is delivered, and with cooldownMs: 0 a cooldown that falls due again during a decision (because a callback reopened the breaker) is admitted before its event is delivered. Use a non-zero cooldownMs and avoid calling acquire() from a callback if an override set from telemetry must always stop the next call.

Evidence packets

generateEvidencePacket builds a sealed, redacted, checksummed evidence packet for one subject. Your application supplies a read port over its own store; the generator persists nothing, so storing the returned envelope is up to you.

import {
  generateEvidencePacket,
  verifyEvidencePacketChecksum,
  type EvidencePacketReadPort,
} from "@fabricorg/platform/evidence";

const port: EvidencePacketReadPort = {
  listEvents: ({ tenantId, spaceId, subjects }) => store.eventsFor(tenantId, spaceId, subjects),
  // Optional readers below; access events are omitted when their reader is absent.
  resolveRelatedSubjects: (subject, scope) => store.relatedSubjects(subject, scope),
  listActionInvocations: (scope, ids) => store.actionInvocations(scope, ids),
  listPolicyEvaluations: (scope, invocationIds) => store.policyEvaluations(scope, invocationIds),
  listAdapterInvocations: (scope, invocationIds) => store.adapterInvocations(scope, invocationIds),
  listAccessEvents: (scope, subjects) => store.accessEvents(scope, subjects),
};

const packet = await generateEvidencePacket(
  { subject: { subjectType: "Case", subjectId: caseId }, policyVersion: "2026-06" },
  { tenantId, spaceId, actorId, correlationId, db, now: new Date() },
  {
    port,
    anonymizationPolicy: { fields: [{ match: "key", value: "email", method: "tokenize" }] },
  },
);
await store.savePacket(packet);
verifyEvidencePacketChecksum(packet); // true until the payload is altered

The optional listAccessEvents(scope, subjects) reader receives the resolved subjects (primary first, then related), even when there are no events or invocation ids. The generator omits payload.accessEvents when the reader is absent, preserving existing payloads and checksums; a reader returning [] includes accessEvents: []. The port selects the relevant access records; the generator does not filter them by subject. Records require id, tenantId and spaceId and pass through the same scope checks, JSON normalization, de-duplication, id sorting and redaction as other sections. References use access_event with only string resourceType and resourceId metadata from the redacted record. Schema version remains 1.

What the tests in evidence/generator.test.ts cover:

  • Access events. Tests cover absent versus empty sections, the pinned legacy checksum, copied scope and subjects, scope rejection, sorting, duplicate conflicts, redaction and identifier/section preservation.
  • Scope fails closed. A record from the port whose tenantId or spaceId differs from the context throws EvidencePacketGenerationError with code EVIDENCE_SCOPE_MISMATCH, in every section. The check runs on the record as returned and again after normalization. A dependent record for an action invocation the generator did not request throws EVIDENCE_UNREQUESTED_RECORD. An error thrown by the port propagates, and no packet is returned.
  • What the port decides. The generator does not check an event's subject against the requested subjects: a port may return events recorded against the primary subject's own action invocations under another subject. Selecting the right events is the port's job.
  • Record shape. Records must have a non-empty id, and events their documented fields. occurredAt and recordedAt must be a Date or an ISO 8601 / PostgreSQL ISO date-time string with an explicit zone: YYYY-MM-DD (or a signed 4–6 digit year), T or a space, HH:MM[:SS[.fraction]], an optional single space, then Z, +HH, +HH:MM or +HHMM with offset hours up to 14 (for example 2026-05-01 10:20:30.123456+00). The string is parsed field by field without Date's lenient parser, and an out-of-range field (February 30, hour 24, offset +15) or any other format throws EVIDENCE_INVALID_RECORD instead of being rolled over or guessed. A zone-less string such as "2026-05-01 00:00:00" throws too, because reading it would depend on the host's time zone. Timestamps are kept to millisecond precision, truncated (.123999+00 becomes .123Z). Values JSON cannot represent faithfully (NaN, Infinity, invalid Date objects, bigint, Maps, class instances without toJSON, an own __proto__ key) throw EVIDENCE_INVALID_RECORD instead of being changed or dropped. A cyclic value (including a toJSON that returns itself) is not detected: it fails with a RangeError rather than an EvidencePacketGenerationError, and no packet is produced. Fields inherited from a prototype are not read.
  • Subjects. The primary subject comes first, then the related subjects, de-duplicated and sorted. Related subjects are used only when the port has resolveRelatedSubjects and includeRelated is not false; payload.includeRelated records whether that lookup ran.
  • Deterministic payload. Events are sorted by the occurredAt instant, then the recordedAt instant, sequence and id; the other sections by id. Every Date becomes an ISO string, and event timestamps given as zoned strings are rewritten as the ISO string of the same instant; other strings are kept as given. So with the same now, packet id and options, the same records give the same payload and checksum when they come back in a different order, with keys in a different order, or with an event timestamp as a Date or as a zoned string (the tests use Z, +00, +00:00 and +0200) for the same millisecond.
  • Redaction before hashing. The payload runs through the privacy AnonymizationEngine with data class "evidence_packet", and its AnonymizationMetadata is stored as payload.redaction (jobId defaults to the packet id, reason to "evidence_packet_generation", redactedAt to the generation time). In the tests, a redacted value does not appear anywhere in the serialized envelope, because the envelope's subjects and reference metadata are read from the redacted payload.
    • The engine passes any _privacy key through without applying the policy, because that is where it keeps its own metadata. The generator therefore accepts a _privacy value from the port, at any depth, only when it has exactly the AnonymizationMetadata shape the engine writes (for example on an event already anonymized with anonymizeAssetEventPayload); any other _privacy value throws EVIDENCE_INVALID_RECORD. Fixed-format fields are pinned: redactedAt (top level and per field) must be an exact toISOString() value and beforeChecksum 64 lowercase hex characters. The free-text fields (reason, jobId, policyVersion, each fieldPath, and the preservedSemantics entries) are only type-checked as strings, not inspected, so a port that writes sensitive text into them would carry it into the packet.
    • Record ids must come through redaction unchanged; a policy that removes or changes one (for example mask on id) throws EVIDENCE_IDENTIFIER_REDACTED. Subject ids may be transformed, for example tokenized, but must remain non-empty strings.
    • The engine scopes each token to its field path, including array positions. The same raw value therefore gets a different token in each place it appears, within one packet and across packets (a related subject's token changes when its position in subjects does). Tokenized values cannot be used to match records or to look packets up; index the raw subject outside the packet if you need that. For the same reason, tokenizing actionInvocationId breaks the link between records and their action invocations, and the generator does not detect it.
    • The policy matches field names and paths, not values used as object keys, so a sensitive value stored as a key ({ byEmail: { "[email protected]": 1 } }) is not redacted.
    • Envelope fields copied from the context (generatedBy, correlationId, causationId) and from the input (policyVersion) are not redacted.
    • Supply anonymization.beforeChecksumKey (a non-empty string or Uint8Array) to use HMAC-SHA256 for field beforeChecksum values. Without a key, the default remains unkeyed SHA-256 of JSON.stringify(value): low-entropy values can be recovered by enumeration, including with nullify or drop. Supply a secret key from the application's secret store and keep it stable while any party needs to verify checksums; keyed verification requires the key. The generator passes it only to the engine, outside the packet context. Existing hash output remains unsalted SHA-256, and the tenant, space, field path and policy version used by tokenize are in the packet. Those outputs still permit candidate guessing; use opaque references where appropriate.
  • Checksum. checksum is the hex SHA-256 of canonicalJson(payload), recorded with checksumAlgorithm: EVIDENCE_PACKET_CHECKSUM_ALGORITHM. verifyEvidencePacketChecksum returns false for a changed payload, a missing checksum or an unknown algorithm. The checksum covers the payload, not the other envelope fields.

createEvidencePacketRenderer(options) wraps the generator as an EvidenceRenderer for one packet type.

Saga actions

Multi-step orchestrations declare kind: "saga" on the ActionDefinition and ship a SagaImplementation:

import type { SagaImplementation } from "@fabricorg/platform/actions";

export const ingestSaga: SagaImplementation = async (ctx, runChild) => {
  const step1 = await runChild({
    suffix: "step-1",
    actionId: "demo.receive_payload",
    parameters: { /* ... */ },
  });
  // orchestrate further child actions...
  return {
    resultData: { /* ... */ },
    event: { eventType: "...", subjectType: "...", subjectId: "...", payload: {} },
  };
};

Your worker maps action IDs to implementations. The platform dispatches generically — no platform code references vertical action IDs.

PlatformHost does not execute a kind: "saga" definition as an atomic handler. Configure a durable dispatcher and map the action to its saga implementation in the workflow worker. Direct execution fails closed so a handlerless saga cannot be recorded as completed.

Projection sequence semantics

ReplayableAssetEvent.sequence is the ordering cursor of the complete tenant/space ledger. A view usually filters that ledger by event type and subject, so gaps in this global cursor do not prove that subject events are missing. Event sources that can guarantee contiguous per-subject ordering may also provide subjectSequence; only that explicit sequence is used for missing-event warnings.

Use EventAppendProjector<TDb> when a ledger writer maintains an event-ID-keyed read index in the append transaction. The projector receives the stored event and the writer's transaction-bound db. Writes through that binding must be idempotent per event ID and limited to derived rows. The Host store capability defines registration, failure handling, and rebuild for Host-backed writers.

Portability boundary

The repository Boundary Guard scans source and packed artifacts and fails CI if any of these leak in:

  • Concrete database/ORM imports — the literal Prisma, the field name prisma:, or the type default TDb = any
  • Vertical vocabulary from the governed denylist
  • "Register default" hooks (registerDefaultPolicies, etc.) — the platform never auto-loads anything
  • Module-scope mutable registries, import-time environment reads, or unapproved infrastructure imports

This is what keeps the platform portable across verticals and consumers. If you fork or add new patterns specific to your domain, extend the list in boundary.test.ts.

Compatibility

  • Runtime: Node 22+. 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.
  • Module formats: ESM and CommonJS (dual format from v0.2.0+)
  • TypeScript: 5.0+, moduleResolution: node or node16/nodenext

Versioning

0.x while contracts evolve. 1.0 only after at least two materially different verticals validate the API.

See CHANGELOG.md for release history.

Documentation

Full reference docs at https://platform.techfabric.com

Discovery surface declarations

Actions and views can declare surface: "internal" with a non-blank surfaceReason. Omission means public discovery. Registration, manifest export and manifest normalization reject unknown surfaces and missing reasons. Public manifests retain both fields, so contract digests cover the declaration. Existing declarations without these fields preserve their exported shape.

External catalog consumers must omit internal entries, including their reason and schemas, and apply their existing audience disclosure rules to public entries. This is discovery metadata: it does not grant invocation/read access, bypass policy, or stop authorized workers from running internal actions through the governed Host. A public entry is not a promise of an authored route.

surface controls definition discovery, while action execution.sensitivity and view usage.classification describe execution/data disclosure. These are independent declarations. assertSurfaceDeclaration is available from the root and @fabricorg/platform/discovery. Reasons are authored public-package metadata; authors must keep them free of secrets.

No first-party compiler or generator artifact applies discovery filtering. All deliberately retain internal contracts for trusted assembly and worker integration; none implements external catalog disclosure. A usage contract or generated schema must not be served as an audience catalog without the internal-surface and audience filters above.

Privacy engine

The engine requires an application-owned field policy. Configure field before-checksums with the optional second constructor argument, exported as AnonymizationEngineOptions:

const engine = new AnonymizationEngine(policy, { beforeChecksumKey: secretFromStore });

beforeChecksumKey accepts a non-empty string or Uint8Array; invalid or empty keys throw TypeError. The engine stores the key privately and copies byte keys at construction. With a key, beforeChecksum is lowercase hex HMAC-SHA256 of JSON.stringify(value). Without a key it retains the existing unkeyed SHA-256, which reveals low-entropy values by enumeration even when the field is nullified or dropped. Use a secret from the application's secret store, keep it stable while verification is needed, and provide it to authorized verifiers. Verification of a keyed checksum requires the key.

The four standalone privacy wrappers accept the same options as a trailing argument. Lifecycle evidence copies the supplied metadata's checksums; its options do not re-key previously generated metadata. This option does not change FieldRedactor, hash, tokenize, stableChecksum, or packet-level checksum algorithms.

Adapter step deadlines

Adapter steps may declare deadlineMs, a positive finite integer duration in milliseconds. Platform Host uses it instead of its adapterDeadlineMs duration for that step. The budget begins just before retry execution and spans attempts and retry delays. Action and module registration, manifest normalization and export, and Host execution validate step durations. Host rejects invalid resolved steps before handler or adapter execution. Manifest export preserves valid durations. See the Platform Host README for cooperative cancellation and failure semantics.

Agentic product acceptance

The certification subpath exports PRODUCT_REQUIREMENTS, AGENT_SURFACES and evaluateProductConformance(input, options). Supply the exact operation inventory, source revision and build digest plus trusted contract/integration/live test-run observations. It reports missing, stale, failed or unavailable evidence per action and surface; mutations additionally require atomic-history proof. Module-wide requirements cover current authorization, tenant isolation, governed context, UC/ semantic qualification, Harness agents, diagnostics and repair handoffs.

This portable evaluator performs no I/O, executes no actions, grants no permissions and does not authenticate arbitrary artifact references. The caller must verify evidence provenance and assertion coverage before using its completeness result. See the shared checklist and the existing strict execution-contract profile; neither replaces runtime policy.

Handler rollback retry signal

RetryableHandlerError and isRetryableHandlerError are exported from the root and /policies. The error has stable name RetryableHandlerError and code HANDLER_RETRYABLE, recognized across ESM/CommonJS copies. Throw it to assert that effects stayed in the supplied Host transaction. Platform Host can retry after confirmed rollback, within the same attempt, subject to ownership, adapter-evidence and input-copy guards. handlerRetry defaults to three total tries (1–10). A classifier can opt raw errors in; it asserts safety for the whole retried unit. Transaction callbacks and handlers must keep effects inside that transaction when opting into retry. See packages/platform-host/README.md (Retry a rolled-back handler transaction) for provider confirmation, exclusions, delay options, recovery and terminal settlement.

Event cause attribution

AssetEventEnvelope.causedBy?: EventCause records a cause separately from the envelope actor. The public root and events exports include EventPrincipalAttribution (id, type, and basis: "invocation_context" | "recorded_decision") and EventCause: principal with that principal, automatic with a mechanism, or unattributed with reason not_recorded or unverified. Basis identifies the attribution source, not proof of authentication. Absence means not recorded by the producer or not preserved by the store. Do not infer a cause from absence; treat an unrecognized kind as unavailable attribution.

Host approval lifecycle events retain the waiting invocation's envelope actor and stamp the cause: requests use the invocation actor, decisions the persisted approver, expiry the automatic platform.approval_deadline mechanism, and cancellation an unattributed reason. See Host attribution and ADR 0025. Actor disclosure gates apply to this field on egress. Outbox disclosure additionally requires outbox.includeCause to return literal true. Stored-record erasure retains the cause like the actor; it is excluded from the redactor view.

License

MIT