@cogover/sdk 0.11.0 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +65 -21
  2. package/dist/crypto.js +89 -46
  3. package/dist/data.js +4 -1
  4. package/dist/email.d.ts +77 -0
  5. package/dist/email.js +192 -0
  6. package/dist/index.d.ts +2 -0
  7. package/dist/internal/base64.js +76 -27
  8. package/dist/internal/bridge.js +41 -3
  9. package/dist/internal/job-config.js +7 -1
  10. package/dist/internal/job-runtime.js +4 -0
  11. package/dist/internal/messaging.js +75 -0
  12. package/dist/internal/trigger-runtime.js +5 -0
  13. package/dist/internal/utf8.js +18 -17
  14. package/dist/jobs.d.ts +4 -0
  15. package/dist/locks.js +13 -3
  16. package/dist/logger.js +47 -1
  17. package/dist/notifications.d.ts +56 -0
  18. package/dist/notifications.js +92 -0
  19. package/dist/org.js +14 -14
  20. package/dist/records.d.ts +13 -0
  21. package/dist/response.js +21 -1
  22. package/dist/router.js +2 -0
  23. package/dist/schema.d.ts +1 -0
  24. package/dist/script.d.ts +4 -0
  25. package/dist/script.js +11 -3
  26. package/dist/trigger.d.ts +6 -0
  27. package/docs/en/api-reference/background-jobs.md +288 -0
  28. package/docs/en/api-reference/cryptography.md +317 -0
  29. package/docs/en/api-reference/fetch-and-secrets.md +184 -0
  30. package/docs/en/api-reference/inbound-webhooks.md +65 -0
  31. package/docs/en/api-reference/notifications-and-email.md +317 -0
  32. package/docs/en/api-reference/organization-structure.md +304 -0
  33. package/docs/en/api-reference/overview.md +198 -0
  34. package/docs/en/api-reference/push-messages.md +115 -0
  35. package/docs/en/api-reference/record-triggers.md +469 -0
  36. package/docs/en/api-reference/records.md +447 -0
  37. package/docs/en/api-reference/scripts-and-routes.md +354 -0
  38. package/docs/en/api-reference/state-and-locks.md +162 -0
  39. package/docs/en/usage-guide.md +218 -19
  40. package/package.json +1 -1
  41. package/docs/en/api-reference.md +0 -2619
@@ -0,0 +1,469 @@
1
+ # `@cogover/sdk` API reference: Record triggers
2
+
3
+ This page is part of the [`@cogover/sdk` API reference](overview.md).
4
+
5
+ ## Record triggers
6
+
7
+ A record trigger runs project code when records of one Object are created, updated,
8
+ or deleted. Declare each trigger with `defineTrigger` and list the results in the
9
+ project's named `triggers` export. The default export is still the HTTP handler and
10
+ is optional in a project that only declares triggers.
11
+
12
+ This example assumes that `workspace.d.ts` declares the `order` Object and the
13
+ fields used below.
14
+
15
+ ```typescript
16
+ import { defineTrigger } from "@cogover/sdk";
17
+
18
+ export const triggers = [
19
+ defineTrigger({
20
+ key: "order_credit_check",
21
+ object: "order",
22
+ timing: "beforeChange",
23
+ operations: ["create", "update"],
24
+ fields: ["status", "amount", "customer"],
25
+ changedFields: ["status", "amount"],
26
+ when: { op: "=", field: "status", params: "confirmed" },
27
+ writableFields: ["approval_level"],
28
+ }, async ({ records }) => {
29
+ for (const record of records) {
30
+ if ((record.new.amount ?? 0) > 1_000_000_000) {
31
+ record.addError("amount", "AMOUNT_TOO_LARGE", "Amount exceeds the approval limit.");
32
+ continue;
33
+ }
34
+ record.new.approval_level = "high";
35
+ }
36
+ }),
37
+ ];
38
+ ```
39
+
40
+ A trigger has one of two timings. A **before-change** trigger runs before the change
41
+ is saved: it can reject records and adjust the values that will be saved. An
42
+ **after-change** trigger runs asynchronously after the change has been saved: it
43
+ cannot reject or modify that change, but it may write records and call `fetch`. See
44
+ [Before-change execution rules](#before-change-execution-rules) and
45
+ [After-change execution rules](#after-change-execution-rules).
46
+
47
+ Cogover reads the trigger configuration when a project version is published and
48
+ applies it while that version is active. Deactivating the project removes its
49
+ triggers. A project can declare at most 50 triggers, and an Object can have at most
50
+ 20 active before-change triggers; a version that declares more on one Object fails to
51
+ publish.
52
+
53
+ ### `defineTrigger(config, handler): TriggerDefinition`
54
+
55
+ ```typescript
56
+ function defineTrigger<
57
+ ObjectSlug extends keyof Schema & string,
58
+ Operation extends TriggerOperation,
59
+ Schema extends object = EffectiveWorkspaceObjects,
60
+ >(
61
+ config: TriggerConfig<ObjectSlug, Operation, Schema>,
62
+ handler: TriggerHandler<ObjectSlug, Operation, Schema>,
63
+ ): TriggerDefinition;
64
+ ```
65
+
66
+ The type arguments are inferred from `config.object` and `config.operations`.
67
+ With a generated `workspace.d.ts`, the object slug, every field slug in the
68
+ configuration, and the values of `record.new` and `record.old` are checked against
69
+ the declared Object. Without Workspace declarations, slugs are strings and field
70
+ values are `unknown`.
71
+
72
+ `defineTrigger` validates the configuration immediately and throws `ValidationError`
73
+ for any violation, for an unknown configuration key, or for a handler that is not a
74
+ function. It returns a frozen `TriggerDefinition`.
75
+
76
+ ```typescript
77
+ type TriggerTiming = "beforeChange" | "afterChange";
78
+ type TriggerOperation = "create" | "update" | "delete";
79
+ type TriggerRunWhen = "always" | "onEnter";
80
+
81
+ interface TriggerConfig<
82
+ ObjectSlug extends string = string,
83
+ Operation extends TriggerOperation = TriggerOperation,
84
+ Schema extends object = EffectiveWorkspaceObjects,
85
+ > {
86
+ readonly key: string;
87
+ readonly name?: string;
88
+ readonly object: ObjectSlug;
89
+ readonly timing: TriggerTiming;
90
+ readonly operations: readonly Operation[];
91
+ readonly fields: readonly FieldSlug[]; // field slugs of the Object
92
+ readonly changedFields?: readonly FieldSlug[];
93
+ readonly when?: TriggerFilter;
94
+ readonly runWhen?: TriggerRunWhen;
95
+ readonly writableFields?: readonly FieldSlug[];
96
+ readonly order?: number;
97
+ readonly timeoutMs?: number;
98
+ }
99
+ ```
100
+
101
+ | Option | Required | Rules and meaning |
102
+ |---|---|---|
103
+ | `key` | Yes | Identifies the trigger inside the project. Starts with an ASCII letter and contains letters, digits, or `_`; at most 100 characters. Keep it stable between versions: a new key is a different trigger. |
104
+ | `name` | No | Display name of at most 250 characters. Defaults to `key`. |
105
+ | `object` | Yes | Slug of the Object whose records run the trigger. |
106
+ | `timing` | Yes | `"beforeChange"` runs before the change is saved and can reject or adjust it. `"afterChange"` runs asynchronously after the change has been saved. |
107
+ | `operations` | Yes | Non-empty list of `"create"`, `"update"`, and `"delete"` without duplicates. |
108
+ | `fields` | Yes | 1–200 unique field slugs. `record.new` and `record.old` contain only these fields and `id`. |
109
+ | `changedFields` | No | 1–200 unique field slugs; requires the `"update"` operation. An update runs the trigger only when at least one of these fields changed. Creates and deletes are not affected. |
110
+ | `when` | No | A `TriggerFilter`. Only matching records run the trigger. |
111
+ | `runWhen` | No | `"always"` (default) or `"onEnter"`. `"onEnter"` requires `when`. |
112
+ | `writableFields` | No | At most 100 unique field slugs that the handler may change. Only for `"beforeChange"`; must be empty when `"delete"` is the only operation. A formula, auto number, rollup summary, or other read-only field makes the version fail to publish. Defaults to `[]`. |
113
+ | `order` | No | Integer from 1000 through 8999; defaults to `5000`. Triggers of an Object run in ascending order. Other values are reserved for Cogover. Do not rely on the relative order of triggers that share a value. |
114
+ | `timeoutMs` | No | Integer from 100 through 3000; defaults to `2000`. Time budget of one handler call. |
115
+
116
+ Object and field slugs start with an ASCII letter or `_`, contain letters, digits,
117
+ or `_`, and are at most 355 characters. `changedFields` and `writableFields` do not
118
+ have to be listed in `fields`.
119
+
120
+ ### Trigger filters
121
+
122
+ ```typescript
123
+ interface TriggerFilterCondition {
124
+ readonly op: FilterOperator;
125
+ readonly field: string;
126
+ readonly params?: unknown;
127
+ }
128
+
129
+ interface TriggerFilterGroup {
130
+ readonly op: "and" | "or";
131
+ readonly conditions: readonly TriggerFilter[];
132
+ }
133
+
134
+ type TriggerFilter = TriggerFilterCondition | TriggerFilterGroup;
135
+ ```
136
+
137
+ ```typescript
138
+ when: {
139
+ op: "and",
140
+ conditions: [
141
+ { op: "=", field: "status", params: "confirmed" },
142
+ { op: "or", conditions: [
143
+ { op: ">=", field: "amount", params: 1_000_000 },
144
+ { op: "in", field: "priority", params: ["high", "urgent"] },
145
+ ] },
146
+ ],
147
+ }
148
+ ```
149
+
150
+ A condition compares one field using a `FilterOperator`. `params` is the JSON
151
+ comparison value: it is required for every operator except `"is null"` and
152
+ `"not null"`, which take none. `"in"` and `"not in"` take a non-empty array and
153
+ `"between"` takes exactly two values. A group combines a non-empty list of
154
+ filters. A filter is nested at most 8 levels deep and contains at most 50
155
+ conditions. Trigger filters are plain objects: expressions built with `and()`,
156
+ `or()`, or field references are for `records.list` and are rejected here.
157
+
158
+ `when` is evaluated on the new values, or on the old values when a record is
159
+ deleted. With `runWhen: "onEnter"` the trigger runs only when the record did not
160
+ match `when` before the change and matches after it; a record that is being created
161
+ counts as not matching before, and `runWhen` is ignored for deletes.
162
+
163
+ Cogover decides which triggers run once, before the first trigger of a change, from
164
+ the values submitted by the writer together with field defaults. A value changed by
165
+ an earlier trigger does not change which triggers run, but later triggers see it in
166
+ `record.new`.
167
+
168
+ ### `TriggerDefinition` and `TriggerManifest`
169
+
170
+ ```typescript
171
+ interface TriggerManifest {
172
+ readonly key: string;
173
+ readonly name?: string;
174
+ readonly object: string;
175
+ readonly timing: TriggerTiming;
176
+ readonly operations: readonly TriggerOperation[];
177
+ readonly fields: readonly string[];
178
+ readonly changedFields?: readonly string[];
179
+ readonly when?: TriggerFilter;
180
+ readonly runWhen: TriggerRunWhen;
181
+ readonly writableFields: readonly string[];
182
+ readonly order: number;
183
+ readonly timeoutMs: number;
184
+ }
185
+
186
+ type TriggerSandboxHandler = (inputJson: string) => Promise<string>;
187
+
188
+ interface TriggerDefinition {
189
+ readonly key: string;
190
+ readonly config: TriggerManifest;
191
+ readonly __cogoverTriggerHandler: TriggerSandboxHandler;
192
+ }
193
+ ```
194
+
195
+ `config` is the normalized configuration as deeply frozen plain JSON, with every
196
+ default applied: `runWhen: "always"`, `writableFields: []`, `order: 5000`, and
197
+ `timeoutMs: 2000`. Optional settings that were not provided are absent. It is
198
+ detached from the object passed to `defineTrigger`, so later edits of that object
199
+ have no effect. `__cogoverTriggerHandler` is reserved for Cogover; project code
200
+ does not call it.
201
+
202
+ ### Trigger handler context
203
+
204
+ ```typescript
205
+ type TriggerHandler<
206
+ ObjectSlug extends string = string,
207
+ Operation extends TriggerOperation = TriggerOperation,
208
+ Schema extends object = EffectiveWorkspaceObjects,
209
+ > = (context: TriggerContext<ObjectSlug, Operation, Schema>) => void | Promise<void>;
210
+
211
+ interface TriggerContext<
212
+ ObjectSlug extends string = string,
213
+ Operation extends TriggerOperation = TriggerOperation,
214
+ Schema extends object = EffectiveWorkspaceObjects,
215
+ > {
216
+ readonly records: readonly TriggerRecord<Fields, Operation>[]; // Fields of ObjectSlug
217
+ readonly trigger: TriggerInfo<Operation>;
218
+ readonly invocation: InvocationContext;
219
+ readonly data: DataApi<Schema>;
220
+ readonly schema: SchemaApi<Schema>;
221
+ readonly log: ScriptLogger;
222
+ readonly push: PushApi<Schema>;
223
+ readonly notifications: NotificationsApi;
224
+ readonly email: EmailApi<Schema>;
225
+ readonly jobs: JobsApi;
226
+ readonly secrets: SecretsApi;
227
+ readonly crypto: CryptoApi;
228
+ readonly org: OrgApi;
229
+ }
230
+
231
+ interface TriggerInfo<Operation extends TriggerOperation = TriggerOperation> {
232
+ readonly id: string;
233
+ readonly key: string;
234
+ readonly timing: TriggerTiming;
235
+ readonly operation: Operation;
236
+ readonly objectSlug: string;
237
+ readonly changeId: string;
238
+ }
239
+
240
+ interface TriggerRecord<Fields = Record<string, unknown>, Operation extends TriggerOperation = TriggerOperation> {
241
+ readonly key: string;
242
+ readonly id: CogoverRecordId | null;
243
+ readonly new: TriggerNewValues<Fields> | null;
244
+ readonly old: TriggerOldValues<Fields> | null;
245
+ readonly changedFields: readonly (keyof Fields & string)[];
246
+ addError(field: (keyof Fields & string) | null, code: string, message?: string): void;
247
+ }
248
+
249
+ type TriggerNewValues<Fields> = {
250
+ -readonly [K in keyof Fields]?: Fields[K] | UpdateFields<Fields>[K];
251
+ };
252
+
253
+ type TriggerOldValues<Fields> = {
254
+ readonly [K in keyof Fields]?: Fields[K];
255
+ };
256
+ ```
257
+
258
+ A handler may be synchronous or asynchronous; its return value is ignored. One call
259
+ receives all records of the same change that run the trigger, up to 200 records and
260
+ 200 KiB, so a batch write or an import calls the handler once per chunk instead of
261
+ once per record. Keep `fields` short, and read related data for the whole list with
262
+ one `records.getMany` call rather than one read per record.
263
+
264
+ `data`, `schema`, `log`, `invocation`, `push`, `notifications`, `email`, `jobs`, `secrets`,
265
+ `crypto`, and `org` are the same APIs that scripts receive. A trigger context has no `input`,
266
+ `request`, `response`, `state`, or `locks`; `push`, `notifications`, and `email` are refused in a
267
+ before-change trigger. `trigger.operation` is
268
+ the operation of the current call, `trigger.id` identifies the trigger registration, and
269
+ `trigger.changeId` identifies the record change that caused the call.
270
+
271
+ Each `TriggerRecord` describes one record:
272
+
273
+ - `key` correlates the record with its result. It is not a record ID.
274
+ - `id` is the record ID, or `null` while a record that is being created has no ID yet.
275
+ In an after-change trigger it is always set.
276
+ - `new` holds the values after the change as a plain, mutable object. It is `null`
277
+ when the record is deleted.
278
+ - `old` holds the values before the change and is deeply frozen. It is `null` when the
279
+ record is created.
280
+ - `changedFields` is a frozen list of the field slugs that changed. For a created
281
+ record it lists every field that has a value. For an update it can also list system
282
+ fields that Cogover sets on every write, such as `updated`.
283
+
284
+ The declared `operations` narrow these types: `new` is never `null` unless
285
+ `"delete"` is declared, `old` is never `null` unless `"create"` is declared, and a
286
+ trigger that only declares `"delete"` has `new: null`. `TriggerNewValues` and
287
+ `TriggerOldValues` make every field optional because a field that is not listed in
288
+ `fields`, or that has no value, is `undefined`.
289
+
290
+ ### Validating and changing records
291
+
292
+ This section applies to before-change triggers. In an after-change trigger the
293
+ change is already saved: `addError` only reports to the project log and
294
+ `record.new` must not be changed (see
295
+ [After-change execution rules](#after-change-execution-rules)).
296
+
297
+ `record.addError(field, code, message?)` rejects the record. `field` is a field slug,
298
+ or `null` for an error about the whole record. `code` starts with an upper-case ASCII
299
+ letter and contains upper-case letters, digits, or `_`; at most 64 characters, for
300
+ example `AMOUNT_TOO_LARGE`. `message` is an optional English text of at most 500
301
+ characters that Cogover shows to the end user when it has no translation for the
302
+ code; an empty message is ignored. Invalid arguments throw `ValidationError`. A
303
+ record may collect several errors.
304
+
305
+ A rejected record is not saved, and any change the handler made to it is discarded.
306
+ The writer receives HTTP 400 with `msg: "BEFORE_CHANGE_TRIGGER_REJECTED"`, the error
307
+ codes in `meta` keyed by field slug (`$record` for an error about the whole record),
308
+ and the optional texts in `messages` keyed by code. A rejected single-record write
309
+ stops at the first trigger that reports an error. In a batch write only the rejected
310
+ rows fail, and a rejected row is not passed to later triggers.
311
+
312
+ When the writer is a script of a Custom Backend Module, nothing is saved and its
313
+ `records.create`, `records.update`, or other write throws:
314
+
315
+ - `ValidationError` with `details.reason` `"TRIGGER_REJECTED"` and `details.r` `70`
316
+ when a trigger rejected the record. `details` also holds `operation` and
317
+ `objectSlug`, and `triggerKey` when Cogover knows which trigger it was. When Cogover
318
+ receives the trigger's error codes and texts, `details.fieldErrors` maps each field
319
+ slug (`$record` for the whole record) to its code and `details.messages` lists the
320
+ texts; do not rely on them being present.
321
+ - `RetryableError` with `details.reason` `"TRIGGER_FAILED"` and `details.r` `71` when a
322
+ trigger could not decide, for example because it threw or exceeded its `timeoutMs`.
323
+ The write may succeed when it is made again later; in an after-change trigger or a
324
+ job, letting the error escape makes Cogover run the handler again.
325
+
326
+ A rejection in `batchInsert` or `batchUpdate` does not throw: only the rejected rows
327
+ fail, and each has `r` `70` with the same `fieldErrors` and `messages` in its row
328
+ result. `deleteMany` deletes the records no trigger rejected and lists each rejected ID
329
+ in `notDeleted` and `recordErrors`; it throws only when every record was rejected (see
330
+ [Record API](records.md#record-api)).
331
+
332
+ To change the values that will be saved, assign fields of `record.new`:
333
+
334
+ ```typescript
335
+ record.new.approval_level = "high";
336
+ record.new.customer = "ACC-1"; // same format as records.update() input
337
+ record.new.note = null; // clears the field
338
+ ```
339
+
340
+ - Only fields listed in `writableFields` may change. When the handler returns, the
341
+ SDK compares every top-level field of `record.new` with a snapshot taken before the
342
+ handler ran, using a deep JSON comparison. Changing any other field, including
343
+ `id`, throws `ValidationError` naming the field, and the write fails.
344
+ - Assigned values use the same format as `records.update` input and must be JSON
345
+ data. `NaN`, functions, `Map`, `Set`, and class instances are rejected; a `Date` is
346
+ sent as its ISO 8601 string. A `date_time` field takes epoch milliseconds and a
347
+ `date` field a `"yyyy-MM-dd"` string; an ISO string, such as a `Date`, written to a
348
+ `date_time` field is stored as that instant, and written to a `date` field as its
349
+ UTC day. Assigning `null` clears a field; assigning `undefined` or
350
+ deleting the field has the same effect.
351
+ - A change inside an array or object value is detected and sends the whole field value.
352
+ - `record.new` itself cannot be replaced, and a record that is being deleted has
353
+ nothing to change.
354
+ - Cogover validates the final values again before saving, including field types and
355
+ required, unique, and duplicate rules. For the fields a trigger changed, the
356
+ field's manual create/modify setting and the writer's field edit permission are
357
+ not applied. Read-only fields such as formulas, auto numbers, and rollups, and
358
+ system fields, are always refused.
359
+
360
+ ### Before-change execution rules
361
+
362
+ A before-change trigger runs for every source of a write: the Cogover web
363
+ application, API keys, imports, automation processes, other Custom Backend Modules,
364
+ and writes made through `data.asUser()` or `data.asSystem()`. Maintenance writes
365
+ made by Cogover itself — recalculating formula and rollup fields, background record
366
+ merges, and cascading deletes — do not run before-change triggers, and neither does
367
+ a request that only validates input without saving.
368
+
369
+ - **Read-only.** A before-change trigger may read records and schema, but every
370
+ record write, `fetch`, lock, state write, push message, notification, email (including
371
+ `email.senders()`), `jobs.enqueue`, `secrets.get`, and every `crypto` operation with a
372
+ `{ secret }` key is refused with
373
+ `PermissionDeniedError` whose `details.reason` is `"TRIGGER_READ_ONLY"`. This
374
+ applies to every identity, including `data.asSystem()`. Every `crypto` operation
375
+ with a key given in the call remains available, as do `crypto.sha256`,
376
+ `crypto.randomBytes`, `crypto.randomUUID`, `crypto.timingSafeEqual`, and every
377
+ [`org`](organization-structure.md#organization-structure) read.
378
+ - **Identity.** `data.object()` acts as the user who made the change, with that
379
+ user's permissions, and `invocation` describes the same user. When a change has
380
+ no user, `invocation.identity` is `"system"` and `data.object()` works only if the
381
+ project's approved identity policy sets `allowInternalSystem: true`; otherwise its
382
+ calls throw `PermissionDeniedError` with `details.reason` `"IDENTITY_NOT_GRANTED"`
383
+ while the handler still receives `records`. `data.asUser()` and `data.asSystem()`
384
+ follow the project's identity policy as usual.
385
+ - **Fail closed.** When a handler throws, exceeds `timeoutMs`, exceeds a runtime
386
+ limit, or cannot be run, the write is rejected and nothing is saved. The writer
387
+ receives `msg: "BEFORE_CHANGE_TRIGGER_FAILED"` without internal details.
388
+ - **Time.** Each call must finish within `timeoutMs`. All before-change triggers of
389
+ one write share a total budget of 8 seconds.
390
+
391
+ ### After-change execution rules
392
+
393
+ An after-change trigger (`timing: "afterChange"`) runs asynchronously, shortly after
394
+ the change has been saved. Use it for follow-up work such as creating or updating
395
+ related records or notifying another system. It runs for the same sources of a
396
+ write as a before-change trigger, with the same exceptions.
397
+
398
+ ```typescript
399
+ import { defineTrigger, fetch, RetryableError } from "@cogover/sdk";
400
+
401
+ export const triggers = [
402
+ defineTrigger({
403
+ key: "order_confirmed_notify",
404
+ object: "order",
405
+ timing: "afterChange",
406
+ operations: ["create", "update"],
407
+ fields: ["status", "amount"],
408
+ changedFields: ["status"],
409
+ when: { op: "=", field: "status", params: "confirmed" },
410
+ runWhen: "onEnter",
411
+ }, async ({ records, trigger }) => {
412
+ for (const record of records) {
413
+ const response = await fetch("https://erp.example.com/orders", {
414
+ method: "POST",
415
+ headers: {
416
+ "content-type": "application/json",
417
+ // The same change of the same record always produces the same key.
418
+ "idempotency-key": `${trigger.changeId}:${record.id}`,
419
+ },
420
+ body: JSON.stringify({ id: record.id, amount: record.new.amount }),
421
+ });
422
+ if (response.status >= 500) {
423
+ throw new RetryableError("The ERP is temporarily unavailable");
424
+ }
425
+ }
426
+ }),
427
+ ];
428
+ ```
429
+
430
+ - **Cannot block or change the saved record.** The writer has already received its
431
+ response. `writableFields` is not allowed, and changing `record.new` makes the call
432
+ fail with `ValidationError`. `record.addError()` rejects nothing: the reported
433
+ errors are only written to the project log. To change the record, call
434
+ `records.update`; that is a new write and runs triggers again.
435
+ - **Saved values.** `record.id` is always set. `record.new` holds the values as they
436
+ were saved, including the record ID and values assigned while saving, such as an
437
+ auto number. For a deleted record `record.new` is `null` and `record.old` holds the
438
+ last values.
439
+ - **May write and call out.** Record writes, `fetch`, `push`, `notifications`, `email`,
440
+ `jobs.enqueue`, `secrets.get`, and `crypto` work as they do in a script, within the
441
+ same runtime limits. `data.object()` acts as the user who made the change, and the other identity
442
+ rules of before-change triggers apply. The trigger context has no `state` or `locks`;
443
+ `push` is the usual way to refresh the records the handler changed for everyone who
444
+ has them open, and longer work, or work that needs `state` or `locks`, belongs in a
445
+ [background job](background-jobs.md#background-jobs).
446
+ - **Best-effort delivery.** Cogover does not guarantee that an after-change handler
447
+ runs exactly once. It may occasionally run more than once for the same change, or
448
+ not at all. Make every handler idempotent: `trigger.changeId` together with
449
+ `record.id` identifies one change of one record. Never make an after-change
450
+ trigger the only guarantee of a critical rule; enforce such rules in a
451
+ before-change trigger.
452
+ - **Retries.** Throw `RetryableError` when a handler fails for a temporary reason,
453
+ such as an external service that is unavailable. Cogover runs the handler again
454
+ later: by default up to 5 more times, waiting longer before each attempt, from
455
+ about one second to about ten minutes. A call that exceeds `timeoutMs`, or that
456
+ Cogover could not run for a temporary reason, is retried the same way. Any other
457
+ error is not retried: the failure is logged and the handler does not run again for
458
+ that change. When the retries are used up, the handler does not run again for that
459
+ change either.
460
+ - **Loops end.** A write made by a trigger runs triggers again, possibly including
461
+ the same trigger. Cogover limits such chains: every automated write uses one step
462
+ of a fixed budget (10 steps for a change made directly by a user or an API
463
+ client), and after-change triggers no longer run once the budget is used up. Use
464
+ `changedFields`, `when`, and `runWhen: "onEnter"` so that a handler's own writes
465
+ do not start it again.
466
+ - **Order and time.** Each call must finish within `timeoutMs`. After-change triggers
467
+ of one change run independently of each other: do not rely on their relative
468
+ order. A retried call may run after a later change of the same record has already
469
+ been processed, so read the current record when the latest values matter.