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.
Declaring hooks
Section titled “Declaring hooks”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.
// "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 |
Hook targets
Section titled “Hook targets”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[].notificationHookSlugnames an after hook that targets that signal; it is never a script slug.
Kernel collection events
Section titled “Kernel collection events”An after hook may also observe the kernel’s collection events with an explicit target:
{ stage: "after", executionScope: "user", targets: [{ owner: { kind: "kernel" }, resource: "event", entitySchemaSlug: "collection", eventSchemaSlug: "add-entity-to-collection", operation: "create", }],}- Only
review,add-entity-to-collectionandremove-entity-from-collectionare 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
collectionremains a separate local target. Names alone never select kernel ownership.
Input projections
Section titled “Input projections”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.
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[] };}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:
jsonuses canonical JSON equality, including array order and multiplicity.unordered-arraycompares 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
Section titled “Before hooks”Before hooks use defineAutomationPolicy and automationType: "policy".
- They apply to submitted mutations, never to provider population, whose data the provider’s
detailsscript shapes. - They run sequentially by
(position, pluginId, hookSlug); omittedpositionmeans 1000. - The compiler and runtime allow only the policy-safe host surface:
executeRyotql, integration/config/preference/user-settings reads, cache reads, and diagnosticlog/span.
Policy input
Section titled “Policy input”Each run receives shared automation metadata and optional immutable references with per-item projected request snapshots:
{ 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.
Decisions
Section titled “Decisions”Return a decision for each item, matched by its identity:
{ 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.
Transform patches
Section titled “Transform patches”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,setandremovecannot 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
AppSchemabefore writing.
Batching and failures
Section titled “Batching and failures”- Only before-event hooks may set
batchFrequency: "item" | "once-per-subject"; omission meansitem. For event-create batches,once-per-subjectruns on the first eligible item for each deterministic subject key. - Before hooks have no
retryfield. - 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
Section titled “After hooks”After hooks use defineAutomation and automationType: "automation".
Automation input
Section titled “Automation input”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.
Results
Section titled “Results”- 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.signalsandchanges.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.
Execution scope
Section titled “Execution scope”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.
Batch frequency
Section titled “Batch frequency”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.itemswithoperation: "batch"and must filter the items itself. - Large writes produce deterministic chunks, so processing must remain idempotent per item.
batchMaxItemsmay 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.
Retries
Section titled “Retries”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
initialDelayMsup tomaxDelayMs. - 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.runIdas its idempotency key. All attempts share that logical run ID; external exactly-once delivery is not guaranteed.
Causation
Section titled “Causation”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.
Installation lifecycle
Section titled “Installation lifecycle”- 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
Section titled “System plugins”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.