From f7fa38653f2b5e451d4870369afd8dab5884ef18 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 03:25:33 +0000 Subject: [PATCH 1/2] docs(skills): data-hooks api.transaction row says when it joins an outer unit and that it is one datasource; teach hook texts + ctx.text The api.transaction capability row now states one transaction on one datasource (a write to another datasource is refused with 400 ERR_CROSS_DATASOURCE_TRANSACTION_WRITE) and that inside an open unit it joins that unit: its return is no commit, its throw no rollback. A Declared texts block beside Declared refusals teaches a hook's texts and ctx.text. Paid by seven same-file restatement cuts; the remainder raises the data-hooks.md ratchet row by measurement (10011 -> 10123). Two eval cases added. Claude-Session: https://claude.ai/code/session_01Utp6CazXu8zyYD5PC6J2u7 Co-authored-by: Claude --- .../34967-data-hooks-transaction-texts.md | 16 +++++ scripts/check-skills-token-ratchet.mjs | 15 ++++- .../hooks-security-seeds-datasources.json | 20 ++++++ .../objectstack-data/references/data-hooks.md | 62 ++++++++++--------- 4 files changed, 82 insertions(+), 31 deletions(-) create mode 100644 .changeset/34967-data-hooks-transaction-texts.md diff --git a/.changeset/34967-data-hooks-transaction-texts.md b/.changeset/34967-data-hooks-transaction-texts.md new file mode 100644 index 00000000000..6653b2d97f3 --- /dev/null +++ b/.changeset/34967-data-hooks-transaction-texts.md @@ -0,0 +1,16 @@ +--- +'@objectstack/skills': patch +--- + +docs(skills): the hooks skill says when `ctx.api.transaction` joins an outer unit, that its transaction is one datasource, and teaches hook `texts` with `ctx.text` + +Clause-②: no +Metadata-protocol: none + +objectstack-data's `references/data-hooks.md`: + +- The `api.transaction` capability row no longer says only "commit on return, rollback on throw". It now says the callback runs in one transaction on one datasource, and that a write in it to an object on another datasource is refused before it runs (`400 ERR_CROSS_DATASOURCE_TRANSACTION_WRITE`). Inside a unit that is already open (the one the hook's write runs in, or a caller's) it joins that unit: its return is no commit and its throw no rollback, so a throw the body catches keeps the callback's writes, and the outer unit commits or rolls back all of it. +- A new "Declared texts (`texts`)" block beside "Declared refusals" teaches a hook's `texts` and `ctx.text(key, params?)`: the sentence is written in the organization's language, translated first and then filled, a missing translation never fails the hook, an unreadable Localization setting rejects, and only declared keys are answered. The sandbox `ctx` table gains a `ctx.text` row that points to it. The translation key is left to objectstack-i18n. +- Seven restatements in the same file were removed to pay for the new text. + +`evals/hooks-security-seeds-datasources.json` gains two cases, one on the joined transaction and the one-datasource rule, one on `texts` with `ctx.text`. diff --git a/scripts/check-skills-token-ratchet.mjs b/scripts/check-skills-token-ratchet.mjs index b8d6ab2ecd2..4a188ff475f 100644 --- a/scripts/check-skills-token-ratchet.mjs +++ b/scripts/check-skills-token-ratchet.mjs @@ -1004,7 +1004,20 @@ export const CEILINGS = new Map([ // (its two halves live in the listing comment and the two-axes note, which // now names the two `tenantId` symbols), the `ctx.user` paragraph under the // `??` line that shows it, and the `session.roles` history clause. - ['skills/objectstack-data/references/data-hooks.md', 10011], + // 10011 -> 10123 (the data-hooks follow-ups of PRs #34503, #35102 and + // #34545): the `api.transaction` row teaches one datasource per body + // transaction (`400 ERR_CROSS_DATASOURCE_TRANSACTION_WRITE`) and that inside + // an open unit it joins that unit (its return no commit, its throw no + // rollback); a `Declared texts` block beside `refusals` and a + // `ctx.text` pointer row teach hook `texts` + `ctx.text`. Raise path the + // standing ruling 「A:先削重复,余额按实测提高」 (ruling record 6513306068, + // letter B). PAID DOWN FIRST — seven restatements cut, each keeping its other + // home (listed in the PR body). Arithmetic against `main`'s 40004 bytes + // (headroom 10): the text adds 1747, the cuts remove 1259, so the LANDED file + // is 40492 bytes -> ceil(40492 / 4) = 10123; the ceiling moves +112, the + // measured remainder only. Pinned AT the measurement. + // ceil($(wc -c < skills/objectstack-data/references/data-hooks.md) / 4) == ceil(40492 / 4) + ['skills/objectstack-data/references/data-hooks.md', 10123], ['skills/objectstack-data/rules/datasources.md', 911], // -552 (was 3584): re-locked at the landed count (#16374) after PR #16187 // (the two `tree` rows) and PR #16369 (the ASCII decision tree deleted) diff --git a/skills/objectstack-data/evals/hooks-security-seeds-datasources.json b/skills/objectstack-data/evals/hooks-security-seeds-datasources.json index ec19e54ad1c..e2e748aa638 100644 --- a/skills/objectstack-data/evals/hooks-security-seeds-datasources.json +++ b/skills/objectstack-data/evals/hooks-security-seeds-datasources.json @@ -191,6 +191,26 @@ "must_not_contain": ["using: 'owner_id"] } }, + { + "id": 28, + "prompt": "A blocking `afterUpdate` hook body on `invoice` (default `onError: 'abort'`) runs `ctx.api.transaction`: it inserts a `payment`, then throws when the balance would go negative. The body catches that throw so the save still succeeds. Is the `payment` row rolled back? Is it committed when the callback returns? We also want it to insert a `ledger_entry`, an object on our `finance` datasource, in the same callback.", + "expected_output": "Inside the save's unit (a blocking `afterUpdate` that can abort runs in it) `ctx.api.transaction` joins that unit: its throw is no rollback and its return is no commit. The caught throw keeps the `payment` row, and the outer unit commits it with the save, or rolls back all of it. To undo the payment, check the balance before inserting, or let the throw out of the body so the save is refused and everything rolls back. A body transaction is one datasource: the `ledger_entry` insert is refused before it runs, `400 ERR_CROSS_DATASOURCE_TRANSACTION_WRITE`; keep the objects one transaction writes on one datasource, or write the ledger outside it.", + "files": [], + "assertions": { + "must_contain": ["join", "ERR_CROSS_DATASOURCE_TRANSACTION_WRITE"], + "must_not_contain": [] + } + }, + { + "id": 29, + "prompt": "Our organization works in German (Setup → Localization); reps save leads in English or French. Write an `afterInsert` hook on `crm_lead` that opens a `crm_task` whose subject reads `Follow up with lead: NAME`.", + "expected_output": "The hook declares the sentence in `texts` (`follow_up_subject: { message: 'Follow up with lead: {{ lead }}', params: ['lead'] }`) and its `js` body (capabilities `['api.write']`; `ctx.text` needs none) writes `subject: await ctx.text('follow_up_subject', { lead: ctx.input.name })` into the `crm_task` insert. The subject is written in the organization's language (German), never the saving rep's: translated first, then filled from `params`. A missing German translation writes the declared `message` and does not fail the hook; the translation key is objectstack-i18n's. No sentence is hard-coded in the body.", + "files": [], + "assertions": { + "must_contain": ["texts", "ctx.text", "params"], + "must_not_contain": [] + } + }, { "id": 20, "prompt": "Each `project` shows a `task_count` — the number of its `task` records (each task has a `project` lookup). Add a `client_viewer` permission set: clients read projects, but must never be able to read tasks.", diff --git a/skills/objectstack-data/references/data-hooks.md b/skills/objectstack-data/references/data-hooks.md index ecc4eb055fc..6afe07f233d 100644 --- a/skills/objectstack-data/references/data-hooks.md +++ b/skills/objectstack-data/references/data-hooks.md @@ -46,9 +46,8 @@ ObjectStack provides lifecycle events organized by operation type: > bulk write hands hooks **no** row-scoping predicate: it lives on the engine-internal > `OperationContext.ast`, so the RLS / sharing filters composed onto it bind > the driver call itself, where no handler can widen them — scope a batch through -> `options.where` at the caller. Both phases dispatch **once per matched row**, -> each on a single-record-shaped context whose `input.id` (`handler`; a `body`: `ctx.previous.id`) names that row and -> whose `previous` is that row's pre-image (ADR-0058 Addendum II). And there is +> `options.where` at the caller. Both phases dispatch **once per matched row** +> (ADR-0058 Addendum II; see `condition` below). And there is > no `beforeCount`/`beforeAggregate`: read authorization and > row filtering belong to **RLS / permission rules**, and field masking to > **field-level metadata** — declarative mechanisms that apply everywhere, rather than @@ -128,14 +127,7 @@ const myHook = defineHook({ #### `body` — Implementation A `source` of statements against `ctx`; a throw aborts the write -([Sandboxed Hook Bodies](#sandboxed-hook-bodies-body--what-the-sandbox-ctx-can-call)): - -```typescript -body: { - language: 'js', - source: `if (ctx.input.email) ctx.input.email = ctx.input.email.trim().toLowerCase();`, -} -``` +([Sandboxed Hook Bodies](#sandboxed-hook-bodies-body--what-the-sandbox-ctx-can-call)). #### `condition` — Declarative Filtering @@ -264,6 +256,7 @@ The sandbox is handed a **JSON snapshot** of these (built by | `ctx.email` | `{ send }` | Gated by `email.send`; not in a hook body. | | `ctx.activity` | `{ append }` | Gated by `activity.append`. | | `ctx.notice` | `(message) => void` | **Tell the saver what this save set in motion** — answered as the create/update `notice`, shown on the save toast. No capability; insert/update only; last call wins. [`rules/lifecycle.md` § Save Notice](../rules/lifecycle.md#save-notice). | +| `ctx.text` | `(key, params?) => Promise` | A declared sentence in the organization's language — [`texts`](#declared-texts-texts). | | `ctx.title` | `(field?) => Promise` | **Name the record, not its id.** `ctx.title()` resolves this object's `nameField`, a **formula** included (no extra read); `ctx.title('account_id')` resolves a lookup's title (needs `api.read`). `null` when there is no title, never the id. **Per door:** `body` has it; a deprecated `handler` gets it at runtime, undeclared on `HookContext` (TS2339 when annotated) — use `body`; `ql.registerHook` and a bare `ObjectQL` `bindHooks` lack it. | (Action bodies additionally receive `ctx.recordId` and `ctx.record`, and their @@ -331,7 +324,7 @@ set of legal tokens (`HookBodyCapability`) is exactly seven: |:--|:--| | `api.read` | `ctx.api.object(n).find` / `findOne` / `count` / `aggregate`; also `ctx.title('')`, which reads that related record. Plain `ctx.title()` reads nothing and needs no token. | | `api.write` | `ctx.api.object(n).insert` / `update` / `delete` | -| `api.transaction` | `ctx.api.transaction(async () => { … })` — runs the callback's `ctx.api` ops in **one driver transaction** (commit on return, rollback on throw). Pair it with `api.write`. | +| `api.transaction` | `ctx.api.transaction(async () => { … })` — runs the callback's `ctx.api` ops in **one transaction on one datasource**: commit on return, rollback on throw. A write in it to an object on another datasource is refused before it runs (`400 ERR_CROSS_DATASOURCE_TRANSACTION_WRITE`). Inside a unit already open (the one the hook's write runs in, or a caller's) it **joins** that unit: its return is no commit and its throw no rollback; the outer unit commits or rolls back all of it, so a throw the body catches keeps the callback's writes. Pair it with `api.write`. | | `crypto.uuid` | `ctx.crypto.randomUUID()` | | `log` | `ctx.log.debug` / `info` / `warn` / `error(msg, data?)` | | `email.send` | `ctx.email.send({ to, subject, text })` — mail via the mail service; sender, user and organization are stamped (`BodyMailSendInputSchema`). **Not in a hook body** (refused at parse and at bind): a message cannot be taken back if the hook's write rolls back. Mail on a record change goes through an action, a job or a flow. | @@ -407,12 +400,9 @@ const fillPositionOnHire = defineHook({ body: { language: 'js', source: ` - // afterUpdate → ctx.result is the PARTIAL patch. Gate on the field this - // write actually set, then re-query for the lookup FK it does NOT carry. if (!ctx.result || ctx.result.stage !== 'hired') return; const rec = await ctx.api.object('candidate').findOne({ where: { id: ctx.result.id } }); if (!rec || !rec.position_id) return; - // Cross-object write — needs the acting user to be able to edit 'position'. await ctx.api.object('position').update({ id: rec.position_id, status: 'filled' }); ctx.log.info('position filled', { position: rec.position_id }); `, @@ -444,11 +434,8 @@ export default fillPositionOnHire; ## Hook Context API -> **Sandbox vs in-process.** The `ctx` documented below is the **in-process -> `handler`** context (full Node; `handler` is deprecated). A metadata-native **`body`** sees a -> capability-gated *subset* of it inside an isolated VM — see -> [Sandboxed Hook Bodies](#sandboxed-hook-bodies-body--what-the-sandbox-ctx-can-call) -> for exactly what is and isn't available there. +> The `ctx` below is the deprecated in-process `handler`'s; a `body` sees the +> [sandbox subset](#what-lives-on-the-sandbox-ctx). The engine's `HookContext` provides: @@ -497,10 +484,7 @@ interface HookContext { ### Reading the current organization -The value a hook usually wants when it needs "the current org to filter/scope -by" is the caller's **active organization** — the same value that lives in the -`organization_id` column, in `current_user.organizationId` inside RLS/sharing -predicates, and in seed rows. Read it as **`organizationId`**: +To scope by the caller's **active organization**, read **`organizationId`**: ```typescript // ✅ Blessed — matches columns, RLS `current_user`, and seed data @@ -696,12 +680,7 @@ const maskSensitiveData = defineHook({ handler: async (ctx) => { // Exempt the engine's own elevated reads (`isSystem`) — internal writes // and self-reads must see the real values. - // - // ⚠️ Never gate this on a session claim: `ctx.session?.roles?.includes(…)` - // is always `undefined` (see the ctx table above), so a mask written that - // way never exempts anyone. A per-permission-set or per-position exemption - // belongs in field-level permissions (the callout above), which the read - // path applies for you. + // ⚠️ Never a session claim (`ctx.session.roles` is gone, ctx table above). const isElevated = ctx.session?.isSystem === true; if (!isElevated) { @@ -878,6 +857,29 @@ export default defineHook({ refused: at save if thrown literally, else as a `500`. Unchanged `ctx.api` errors and crashes pass through. +### Declared texts (`texts`) + +A sentence the hook writes into a record (a task's subject, a logged summary) is +read by the whole organization: declare it in `texts` and ask for it with +`ctx.text(key, params?)` — no capability; a `js` body or a `handler`, never an +`expression` body. + +```typescript +texts: { follow_up_subject: { message: 'Follow up with lead: {{ lead }}', params: ['lead'] } }, +// afterInsert body (capabilities: ['api.write']): +const subject = await ctx.text('follow_up_subject', { lead: ctx.input.name }); +await ctx.api.object('crm_task').insert({ subject, related_to_lead: ctx.input.id }); +``` + +- In the **organization's** language (Setup → Localization, else the app's + `i18n.defaultLocale`), never the saver's. +- Translated first, then the `{{ }}` holes are filled from `params` (holes as in `refusals`). +- A missing translation never fails the hook: the declared `message` is written. +- An unreadable Localization setting rejects `ctx.text`; catch it to write anyway. +- Only declared keys: another is refused at save if asked for literally, else as + a `500`. A string the hook builds itself is written as it is. +- Translation key: [objectstack-i18n](../../objectstack-i18n/SKILL.md). + --- ## References From 84b73e214610ea6179b01f0411b3488806aef1dd Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 04:48:11 +0000 Subject: [PATCH 2/2] docs(skills): data-hooks texts example links by ctx.result.id; body transaction is on the default datasource; texts block names its key Review fix round. The Declared texts example is an afterInsert body, so it links the task by ctx.result.id (ctx.input.id is undefined on insert). The api.transaction row says the transaction is on the default datasource and a write to any other is refused. The texts block names its translation key inline and keeps the objectstack-i18n pointer. The "Why so few?" per-row sentence is restored, since another open PR cites it as a home. Paid by four more same-file restatement cuts; the ratchet row re-pinned at the measurement (10122). Eval 28 says default datasource and uses a neutral object name; eval 29 pins the link. Claude-Session: https://claude.ai/code/session_01Utp6CazXu8zyYD5PC6J2u7 Co-authored-by: Claude --- .../34967-data-hooks-transaction-texts.md | 8 ++--- scripts/check-skills-token-ratchet.mjs | 29 ++++++++++--------- .../hooks-security-seeds-datasources.json | 8 ++--- .../objectstack-data/references/data-hooks.md | 19 ++++++------ 4 files changed, 33 insertions(+), 31 deletions(-) diff --git a/.changeset/34967-data-hooks-transaction-texts.md b/.changeset/34967-data-hooks-transaction-texts.md index 6653b2d97f3..acd48f59deb 100644 --- a/.changeset/34967-data-hooks-transaction-texts.md +++ b/.changeset/34967-data-hooks-transaction-texts.md @@ -9,8 +9,8 @@ Metadata-protocol: none objectstack-data's `references/data-hooks.md`: -- The `api.transaction` capability row no longer says only "commit on return, rollback on throw". It now says the callback runs in one transaction on one datasource, and that a write in it to an object on another datasource is refused before it runs (`400 ERR_CROSS_DATASOURCE_TRANSACTION_WRITE`). Inside a unit that is already open (the one the hook's write runs in, or a caller's) it joins that unit: its return is no commit and its throw no rollback, so a throw the body catches keeps the callback's writes, and the outer unit commits or rolls back all of it. -- A new "Declared texts (`texts`)" block beside "Declared refusals" teaches a hook's `texts` and `ctx.text(key, params?)`: the sentence is written in the organization's language, translated first and then filled, a missing translation never fails the hook, an unreadable Localization setting rejects, and only declared keys are answered. The sandbox `ctx` table gains a `ctx.text` row that points to it. The translation key is left to objectstack-i18n. -- Seven restatements in the same file were removed to pay for the new text. +- The `api.transaction` capability row no longer says only "commit on return, rollback on throw". It now says the callback runs in one transaction on the default datasource, and that a write in it to an object on any other datasource is refused before it runs (`400 ERR_CROSS_DATASOURCE_TRANSACTION_WRITE`). Inside a unit that is already open (the one the hook's write runs in, or a caller's) it joins that unit: its return is no commit and its throw no rollback, so a throw the body catches keeps the callback's writes, and the outer unit commits or rolls back all of it. +- A new "Declared texts (`texts`)" block beside "Declared refusals" teaches a hook's `texts` and `ctx.text(key, params?)`: the sentence is written in the organization's language, translated first and then filled, a missing translation never fails the hook, an unreadable Localization setting rejects, and only declared keys are answered. The sandbox `ctx` table gains a `ctx.text` row that points to it. It names the translation key, `hooks.HOOK.texts.KEY.message`, and leaves the bundle to objectstack-i18n. +- Ten restatements in the same file were removed to pay for the new text. -`evals/hooks-security-seeds-datasources.json` gains two cases, one on the joined transaction and the one-datasource rule, one on `texts` with `ctx.text`. +`evals/hooks-security-seeds-datasources.json` gains two cases, one on the joined transaction and the default-datasource rule, one on `texts` with `ctx.text`. diff --git a/scripts/check-skills-token-ratchet.mjs b/scripts/check-skills-token-ratchet.mjs index 4a188ff475f..9f189dd69bb 100644 --- a/scripts/check-skills-token-ratchet.mjs +++ b/scripts/check-skills-token-ratchet.mjs @@ -1004,20 +1004,21 @@ export const CEILINGS = new Map([ // (its two halves live in the listing comment and the two-axes note, which // now names the two `tenantId` symbols), the `ctx.user` paragraph under the // `??` line that shows it, and the `session.roles` history clause. - // 10011 -> 10123 (the data-hooks follow-ups of PRs #34503, #35102 and - // #34545): the `api.transaction` row teaches one datasource per body - // transaction (`400 ERR_CROSS_DATASOURCE_TRANSACTION_WRITE`) and that inside - // an open unit it joins that unit (its return no commit, its throw no - // rollback); a `Declared texts` block beside `refusals` and a - // `ctx.text` pointer row teach hook `texts` + `ctx.text`. Raise path the - // standing ruling 「A:先削重复,余额按实测提高」 (ruling record 6513306068, - // letter B). PAID DOWN FIRST — seven restatements cut, each keeping its other - // home (listed in the PR body). Arithmetic against `main`'s 40004 bytes - // (headroom 10): the text adds 1747, the cuts remove 1259, so the LANDED file - // is 40492 bytes -> ceil(40492 / 4) = 10123; the ceiling moves +112, the - // measured remainder only. Pinned AT the measurement. - // ceil($(wc -c < skills/objectstack-data/references/data-hooks.md) / 4) == ceil(40492 / 4) - ['skills/objectstack-data/references/data-hooks.md', 10123], + // 10011 -> 10122 (the data-hooks follow-ups of PRs #34503, #35102 and + // #34545): the `api.transaction` row teaches that a body transaction is on + // the default datasource only (`400 ERR_CROSS_DATASOURCE_TRANSACTION_WRITE` + // for a write to any other) and that inside an open unit it joins that unit + // (its return no commit, its throw no rollback); a `Declared texts` block + // beside `refusals`, naming its translation key, and a `ctx.text` pointer row + // teach hook `texts` + `ctx.text`. Raise path the standing ruling + // 「A:先削重复,余额按实测提高」 (ruling record 6513306068, letter B). PAID DOWN + // FIRST — ten restatements cut, each keeping its other home (listed in the + // PR body). Arithmetic against `main`'s 40004 bytes (headroom 10): the text + // adds 1805, the cuts remove 1323, so the LANDED file is 40486 bytes -> + // ceil(40486 / 4) = 10122; the ceiling moves +111, the measured remainder + // only. Pinned AT the measurement. + // ceil($(wc -c < skills/objectstack-data/references/data-hooks.md) / 4) == ceil(40486 / 4) + ['skills/objectstack-data/references/data-hooks.md', 10122], ['skills/objectstack-data/rules/datasources.md', 911], // -552 (was 3584): re-locked at the landed count (#16374) after PR #16187 // (the two `tree` rows) and PR #16369 (the ASCII decision tree deleted) diff --git a/skills/objectstack-data/evals/hooks-security-seeds-datasources.json b/skills/objectstack-data/evals/hooks-security-seeds-datasources.json index e2e748aa638..301087711bd 100644 --- a/skills/objectstack-data/evals/hooks-security-seeds-datasources.json +++ b/skills/objectstack-data/evals/hooks-security-seeds-datasources.json @@ -193,8 +193,8 @@ }, { "id": 28, - "prompt": "A blocking `afterUpdate` hook body on `invoice` (default `onError: 'abort'`) runs `ctx.api.transaction`: it inserts a `payment`, then throws when the balance would go negative. The body catches that throw so the save still succeeds. Is the `payment` row rolled back? Is it committed when the callback returns? We also want it to insert a `ledger_entry`, an object on our `finance` datasource, in the same callback.", - "expected_output": "Inside the save's unit (a blocking `afterUpdate` that can abort runs in it) `ctx.api.transaction` joins that unit: its throw is no rollback and its return is no commit. The caught throw keeps the `payment` row, and the outer unit commits it with the save, or rolls back all of it. To undo the payment, check the balance before inserting, or let the throw out of the body so the save is refused and everything rolls back. A body transaction is one datasource: the `ledger_entry` insert is refused before it runs, `400 ERR_CROSS_DATASOURCE_TRANSACTION_WRITE`; keep the objects one transaction writes on one datasource, or write the ledger outside it.", + "prompt": "A blocking `afterUpdate` hook body on `invoice` (default `onError: 'abort'`) runs `ctx.api.transaction`: it inserts a `payment`, then throws when the balance would go negative. The body catches that throw so the save still succeeds. Is the `payment` row rolled back? Is it committed when the callback returns? We also want it to insert a `bank_transfer`, a business object on our `finance` datasource, in the same callback.", + "expected_output": "Inside the save's unit (a blocking `afterUpdate` that can abort runs in it) `ctx.api.transaction` joins that unit: its throw is no rollback and its return is no commit. The caught throw keeps the `payment` row, and the outer unit commits it with the save, or rolls back all of it. To undo the payment, check the balance before inserting, or let the throw out of the body so the save is refused and everything rolls back. A body transaction is on the default datasource only: the `bank_transfer` insert is refused before it runs, `400 ERR_CROSS_DATASOURCE_TRANSACTION_WRITE`, and a plain `ctx.api` write to it inside the save's unit is refused the same way. Keep the objects it writes on the default datasource, or make that write outside the unit (an `async: true` hook).", "files": [], "assertions": { "must_contain": ["join", "ERR_CROSS_DATASOURCE_TRANSACTION_WRITE"], @@ -204,11 +204,11 @@ { "id": 29, "prompt": "Our organization works in German (Setup → Localization); reps save leads in English or French. Write an `afterInsert` hook on `crm_lead` that opens a `crm_task` whose subject reads `Follow up with lead: NAME`.", - "expected_output": "The hook declares the sentence in `texts` (`follow_up_subject: { message: 'Follow up with lead: {{ lead }}', params: ['lead'] }`) and its `js` body (capabilities `['api.write']`; `ctx.text` needs none) writes `subject: await ctx.text('follow_up_subject', { lead: ctx.input.name })` into the `crm_task` insert. The subject is written in the organization's language (German), never the saving rep's: translated first, then filled from `params`. A missing German translation writes the declared `message` and does not fail the hook; the translation key is objectstack-i18n's. No sentence is hard-coded in the body.", + "expected_output": "The hook declares the sentence in `texts` (`follow_up_subject: { message: 'Follow up with lead: {{ lead }}', params: ['lead'] }`) and its `js` body (capabilities `['api.write']`; `ctx.text` needs none) writes `subject: await ctx.text('follow_up_subject', { lead: ctx.input.name })` into the `crm_task` insert, linked by `ctx.result.id` (`ctx.input.id` is undefined on insert). The subject is written in the organization's language (German), never the saving rep's: translated first, then filled from `params`. A missing German translation writes the declared `message` and does not fail the hook; the translation key is objectstack-i18n's. No sentence is hard-coded in the body.", "files": [], "assertions": { "must_contain": ["texts", "ctx.text", "params"], - "must_not_contain": [] + "must_not_contain": ["related_to_lead: ctx.input.id"] } }, { diff --git a/skills/objectstack-data/references/data-hooks.md b/skills/objectstack-data/references/data-hooks.md index 6afe07f233d..9c293b5737e 100644 --- a/skills/objectstack-data/references/data-hooks.md +++ b/skills/objectstack-data/references/data-hooks.md @@ -46,8 +46,9 @@ ObjectStack provides lifecycle events organized by operation type: > bulk write hands hooks **no** row-scoping predicate: it lives on the engine-internal > `OperationContext.ast`, so the RLS / sharing filters composed onto it bind > the driver call itself, where no handler can widen them — scope a batch through -> `options.where` at the caller. Both phases dispatch **once per matched row** -> (ADR-0058 Addendum II; see `condition` below). And there is +> `options.where` at the caller. Both phases dispatch **once per matched row**, +> each on a single-record-shaped context whose `input.id` (`handler`; a `body`: `ctx.previous.id`) names that row and +> whose `previous` is that row's pre-image (ADR-0058 Addendum II). And there is > no `beforeCount`/`beforeAggregate`: read authorization and > row filtering belong to **RLS / permission rules**, and field masking to > **field-level metadata** — declarative mechanisms that apply everywhere, rather than @@ -220,7 +221,7 @@ CEL has no overload for does **not** degrade to "the hook did not fire" — it ```jsonc body: { language: 'js', // 'js' = L2 sandboxed script | 'expression' = L1 pure formula - source: "/* function body */", // the FUNCTION BODY only — not a module + source: "/* function body */", capabilities: ['api.read', 'api.write', 'log'], // default: [] timeoutMs: 250, // optional, ≤ 30000 (hook default 250ms, action 5000ms) memoryMb: 32, // optional, ≤ 256 (best-effort under QuickJS) @@ -253,7 +254,7 @@ The sandbox is handed a **JSON snapshot** of these (built by | `ctx.api` | object | Cross-object CRUD. Gated by `api.read` / `api.write` — see below. | | `ctx.log` | `{ debug, info, warn, error }` | Gated by `log`. Call **`ctx.log.info(msg, data?)`** — `ctx.log` is an **object, not** callable as `ctx.log(msg)`. Emission is **best-effort** (see Troubleshooting). | | `ctx.crypto` | `{ randomUUID }` | Gated by `crypto.uuid`. | -| `ctx.email` | `{ send }` | Gated by `email.send`; not in a hook body. | +| `ctx.email` | `{ send }` | Gated by `email.send`. | | `ctx.activity` | `{ append }` | Gated by `activity.append`. | | `ctx.notice` | `(message) => void` | **Tell the saver what this save set in motion** — answered as the create/update `notice`, shown on the save toast. No capability; insert/update only; last call wins. [`rules/lifecycle.md` § Save Notice](../rules/lifecycle.md#save-notice). | | `ctx.text` | `(key, params?) => Promise` | A declared sentence in the organization's language — [`texts`](#declared-texts-texts). | @@ -322,9 +323,9 @@ set of legal tokens (`HookBodyCapability`) is exactly seven: | Token | Unlocks | |:--|:--| -| `api.read` | `ctx.api.object(n).find` / `findOne` / `count` / `aggregate`; also `ctx.title('')`, which reads that related record. Plain `ctx.title()` reads nothing and needs no token. | +| `api.read` | `ctx.api.object(n).find` / `findOne` / `count` / `aggregate`; also `ctx.title('')`. | | `api.write` | `ctx.api.object(n).insert` / `update` / `delete` | -| `api.transaction` | `ctx.api.transaction(async () => { … })` — runs the callback's `ctx.api` ops in **one transaction on one datasource**: commit on return, rollback on throw. A write in it to an object on another datasource is refused before it runs (`400 ERR_CROSS_DATASOURCE_TRANSACTION_WRITE`). Inside a unit already open (the one the hook's write runs in, or a caller's) it **joins** that unit: its return is no commit and its throw no rollback; the outer unit commits or rolls back all of it, so a throw the body catches keeps the callback's writes. Pair it with `api.write`. | +| `api.transaction` | `ctx.api.transaction(async () => { … })` — runs the callback's `ctx.api` ops in **one transaction on the default datasource**: commit on return, rollback on throw. A write in it to an object on any other datasource is refused before it runs (`400 ERR_CROSS_DATASOURCE_TRANSACTION_WRITE`). Inside a unit already open (the one the hook's write runs in, or a caller's) it **joins** that unit: its return is no commit and its throw no rollback; the outer unit commits or rolls back all of it, so a throw the body catches keeps the callback's writes. Pair it with `api.write`. | | `crypto.uuid` | `ctx.crypto.randomUUID()` | | `log` | `ctx.log.debug` / `info` / `warn` / `error(msg, data?)` | | `email.send` | `ctx.email.send({ to, subject, text })` — mail via the mail service; sender, user and organization are stamped (`BodyMailSendInputSchema`). **Not in a hook body** (refused at parse and at bind): a message cannot be taken back if the hook's write rolls back. Mail on a record change goes through an action, a job or a flow. | @@ -470,7 +471,7 @@ interface HookContext { // Engine access ql: IDataEngine; // ObjectQL engine instance api?: ScopedContext; // Cross-object CRUD API - notice?: (message: string) => void; // Save notice: rules/lifecycle.md § Save Notice + notice?: (message: string) => void; // User info shortcut (undefined for system / unauthenticated writes) user?: { @@ -868,7 +869,7 @@ read by the whole organization: declare it in `texts` and ask for it with texts: { follow_up_subject: { message: 'Follow up with lead: {{ lead }}', params: ['lead'] } }, // afterInsert body (capabilities: ['api.write']): const subject = await ctx.text('follow_up_subject', { lead: ctx.input.name }); -await ctx.api.object('crm_task').insert({ subject, related_to_lead: ctx.input.id }); +await ctx.api.object('crm_task').insert({ subject, related_to_lead: ctx.result.id }); ``` - In the **organization's** language (Setup → Localization, else the app's @@ -878,7 +879,7 @@ await ctx.api.object('crm_task').insert({ subject, related_to_lead: ctx.input.id - An unreadable Localization setting rejects `ctx.text`; catch it to write anyway. - Only declared keys: another is refused at save if asked for literally, else as a `500`. A string the hook builds itself is written as it is. -- Translation key: [objectstack-i18n](../../objectstack-i18n/SKILL.md). +- Translation key `hooks..texts..message`; the bundle: [objectstack-i18n](../../objectstack-i18n/SKILL.md). ---