Skip to content

Lifecycle hooks

Lifecycle hooks let a plugin react to writes. A before hook (a policy) can allow, reject or transform a submitted mutation before it is written. An after hook (an automation) runs as a job after a write commits and may return its own changes. This page covers how hooks are declared and targeted, what input each receives, how they are batched and retried, and how installation pins what they run.

Every manifest declares hooks, including [] when empty.

  • A hook’s identity is (pluginId, slug). Keep its slug stable when changing its script, targets, order or metadata.
  • Ordinary hook targets name schemas declared by the manifest. Event targets name both their entity schema and event schema.
  • There are no wildcards or expression rules.
  • The archive includes only active discovered scripts, and every hook must reference an automation-kind script with the correct automationType.
manifest/plugin.ts
// "item" must be a declared entity schema.
hooks: [
{
slug: "item.ensure-membership",
name: "Ensure library membership",
scriptSlug: "ensure-membership",
stage: "after",
targets: [
{ resource: "entity", operation: "create", entitySchemaSlug: "item" },
{ resource: "provider-entity-import", operation: "complete", entitySchemaSlug: "item" },
],
causationSources: ["api", "import", "integration"],
retry: { maxAttempts: 3, initialDelayMs: 1000, maxDelayMs: 60000, externalIdempotency: "none" },
},
],
Field Stage Meaning
slug Both Stable hook identity
name Both English name
scriptSlug Both An automation-kind script with the matching automationType
stage Both before or after
targets Both At least one target
metadata Both Optional JSON handed to the script as hookMetadata
causationSources Both Optional causation filter
position Before Order among policies; omitted means 1000
batchFrequency Before Event targets only: item (default) or once-per-subject
executionScope After user or global; omitted matches both
frequency After item (default) or batch
batchMaxItems After 1–1000; requires frequency: "batch"
retry After Retry policy
resource Operations Stages Names
entity create, update, delete Both entitySchemaSlug
event create, update, delete Both entitySchemaSlug and eventSchemaSlug
relationship create, update, delete Both relationshipSchemaSlug
provider-entity-import complete After entitySchemaSlug
signal emit After signalSchemaSlug
  • Import completion remains a fact even when the global entity already exists.
  • signalSchemas[].notificationHookSlug names an after hook that targets that signal; it is never a script slug.

An after hook may also observe the kernel’s collection events with an explicit target:

An after hook observing kernel collections
{
stage: "after",
executionScope: "user",
targets: [{
owner: { kind: "kernel" },
resource: "event",
entitySchemaSlug: "collection",
eventSchemaSlug: "add-entity-to-collection",
operation: "create",
}],
}
  • Only review, add-entity-to-collection and remove-entity-from-collection are available through this exception.
  • It requires user execution and cannot be a before hook or a global observer.
  • An observer keeps its own plugin’s write authority. It must not extend kernel schemas or write another plugin’s domain data.
  • A plugin’s own schema named collection remains a separate local target. Names alone never select kernel ownership.

Hooks receive a deterministic projection of the complete immutable trigger retained by the kernel. Projection changes only the sandbox input; it never removes evidence from the retained trigger.

Each automation script must declare inputProjection in its defineManifest. At least one resource is required, names are trimmed and unique, and undeclared resources fail closed rather than receiving a complete payload. Every resource a hook targets must be declared in its script’s projection.

After-automation projection shape
inputProjection: {
entity?: { properties: string[]; compareProperties: Comparison[]; parentEntityProperties: string[] };
event?: { properties: string[]; compareProperties: Comparison[] };
relationship?: { properties: string[]; compareProperties: Comparison[]; parentEntityProperties: string[] };
providerEntityImport?: true;
signal?: { properties: string[] };
}
Policy projection shape (deliberately smaller)
inputProjection: {
entity?: { properties: string[] };
event?: { properties: string[] };
relationship?: { properties: string[] };
}
Option Effect
properties Selects keys from each projected draft, before, after or signal property map. All non-property identity and operation fields remain present.
parentEntityProperties Independently selects population.parentEntity.properties; other population fields remain present.
compareProperties Produces a sorted changedProperties list on update requests and changes, including items in projected batches.

Comparison kinds:

  • json uses canonical JSON equality, including array order and multiplicity.
  • unordered-array compares arrays as sets of canonical JSON elements, ignoring order and duplicate multiplicity. Non-arrays use JSON equality.
  • Missing and present values, including null, remain distinct.
  • Compared properties need not also be selected into snapshots.

Before hooks use defineAutomationPolicy and automationType: "policy".

  • They apply to submitted mutations, never to provider population, whose data the provider’s details script shapes.
  • They run sequentially by (position, pluginId, hookSlug); omitted position means 1000.
  • The compiler and runtime allow only the policy-safe host surface: executeRyotql, integration/config/preference/user-settings reads, cache reads, and diagnostic log/span.

Each run receives shared automation metadata and optional immutable references with per-item projected request snapshots:

Policy input
{
automation: { /* hookSlug, causation, occurredAt, executionUserId, hookMetadata?, references */ },
items: [{ itemIdentity, payload }],
}

A policy call has no run or trigger, so its metadata carries no runId or triggerId.

Return a decision for each item, matched by its identity:

Policy output
{
items: [{ itemIdentity, decision }];
}
Decision Effect
{ action: "allow" } Accept the item as submitted
{ action: "reject", reason } Reject the write; reason is a catalogMessage(...) (see Messages)
{ action: "transform", patch } Change the draft before it is written

The request snapshots and references are read-only. Calculating values does not write them to source; changes require an explicit transform decision. No domain writes, HTTP, signals, notifications, cache writes, persistent claims, child workflows or filesystem grants are allowed.

A patch must name the current resource and contain a non-empty draft patch.

Resource May patch
Entity create/update name and properties
Relationship create/update Properties
Event create/update Properties, sessionEntityId and occurredAt
  • Event identity and schema fields are immutable, and delete transforms are rejected.
  • A properties patch is { remove: string[], set: Record<string, JsonValue> }. Names are unique, set and remove cannot overlap, removal runs before set, and an empty patch is invalid.
  • The kernel applies accepted patches in hook order, projects that updated request for the next policy, keeps operation, scope and target identity fixed, and validates the final draft with its AppSchema before writing.
  • Only before-event hooks may set batchFrequency: "item" | "once-per-subject"; omission means item. For event-create batches, once-per-subject runs on the first eligible item for each deterministic subject key.
  • Before hooks have no retry field.
  • A policy is called once per command with every item it targets and leaves no automation history.
  • A policy that cannot run for want of capacity makes the write fail as unavailable (HTTP 503). Any other policy failure fails it with policy-execution-failed (HTTP 400). Neither creates a mutation.
  • Resubmission is a new command; delayed automatic and manual policy retry are not allowed.

After hooks use defineAutomation and automationType: "automation".

The automation input contains triggerId, runId, hookSlug, causation, occurredAt, executionUserId, optional hookMetadata, and the projected payload. Narrow on payload.category, payload.resource and payload.operation before reading its data.

  • An after hook returns { changes? }. The kernel commits the change set in the same transaction that records the attempt’s success, under the hook’s causation and root budget, so a retried attempt never commits twice.
  • Signals and notifications are changes.signals and changes.notifications.
  • After hooks run concurrently and independently. Dependent steps belong in one script or plugin workflow.
  • The write that triggers an after hook queues it as a job when it commits. The response never waits for it, and a failure does not roll back committed source data.

An after hook may declare executionScope: "user" | "global"; omission matches both. The kernel compares it against the run’s executionUserId, so a user hook is never planned for a global write and a global hook is never planned for a user-scoped one. Per-recipient signal hooks keep working because each recipient’s run carries that user.

After-hook frequency defaults to "item"; "batch" requires entity, event or relationship targets.

  • Item and batch hooks match separate triggers.
  • A batch matches when any item matches, but receives projected payload.items with operation: "batch" and must filter the items itself.
  • Large writes produce deterministic chunks, so processing must remain idempotent per item.
  • batchMaxItems may be 1–1000. The lowest matching pinned hook or global limit applies, not limits from unmatched hooks.
  • Projected invocations must also fit 64 KiB and may be chunked smaller. Complete evidence is still retained independently of the projection.

Omitted retry means { maxAttempts: 1, initialDelayMs: 1000, maxDelayMs: 60000, externalIdempotency: "none" }.

Field Rule
maxAttempts 1–10, including the first attempt
initialDelayMs 1–3,600,000
maxDelayMs 1–86,400,000, and at least initialDelayMs
externalIdempotency none or run-id
  • Exponential delays double from initialDelayMs up to maxDelayMs.
  • Only kernel-classified infrastructure failures are retryable. Schema failures, missing retained artifacts and business failures are terminal.
  • HTTP uncertain outcomes are terminal unless the hook declares externalIdempotency: "run-id".
  • Automatic retries require that declaration when the hook’s reachable executable dependencies use httpCall, including delegated effects.
  • Declare it only if the external operation supports deduplication and receives automation.runId as its idempotency key. All attempts share that logical run ID; external exactly-once delivery is not guaranteed.

causationSources optionally limits a hook to writes from api, import, integration, bootstrap, provider-refresh, automation or scheduler.

  • Kernel-owned causation carries execution, root and parent attribution, depth, lane and source context.
  • Child writes keep the root, derive parents from the trusted run and increment depth. Plugin input cannot choose parentage.
  • Budget-blocked policies reject writes. Blocked after-hook planning preserves committed mutations.

See automations.

  • Ingestion validates a complete prospective registry, persists immutable precompiled content-addressed scripts, and atomically swaps the active snapshot. It does not start compiler workers.
  • Readers see a complete old or new snapshot.
  • Existing durable workflows keep their pinned versions; new resolution uses the active snapshot.
  • Batch candidates pin code and configuration before writing; sealed committed chunks determine their runs. Later plugin changes cannot add hooks to an already committed command.

System plugins are deployment-controlled.

  • Accepted hook runs keep pinned package, configuration and script revisions through their retry window.
  • Disablement and uninstall exclude new planning but do not cancel accepted runs.
  • The kernel keeps compact revision attribution for history after executable artifacts expire.