Skip to content

Commit e4bfa33

Browse files
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 (#35309)
<!-- claude-projects-attribution: {"github_login":"os-bill"} --> _Requested by **Bill** · [project thread](https://claude.ai/code/project/chan_016iMXWSZDzqWRWvWzdNo8wg?thread=cmsg_016iMXWSZDzqWRWvWzdNo8wg1XdbbGasMNVx41tq3hZKV4)_ Fixes #34967 Fixes #35117 Part of #34546 Clause-②: no Metadata-protocol: none The declaration half of #34546 only: hook `texts` + `ctx.text` taught once in objectstack-data. The translation-bundle half is in PR #35302, which owns the bundle shape; #34546 stays open until both PRs merge, and the area then closes that card by hand. ## 维护者速读 - 改了什么:数据技能 `data-hooks.md` 的 `api.transaction` 一行写明:回调是一个数据源上的一个事务,写到其他数据源的对象会在执行前被拒(`400 ERR_CROSS_DATASOURCE_TRANSACTION_WRITE`);在已打开的单元里(钩子所在写入的单元,或调用方的)它并入该单元,返回不提交、抛错不回滚。另在 `refusals` 旁新增 `texts` + `ctx.text` 的教学块,附两条 eval。 - 为什么改:原文无条件写「返回即提交、抛错即回滚」,AI 照写会以为内层已回滚或已提交;跨数据源的拒绝和钩子组织语言文本也没教。 - 风险与回滚:仅技能文本与 eval,无代码改动;token 棚 10011 → 10122(先删同文件十处重复,余额按实测提高)。回滚即 revert 本 PR。 - 先看:`skills/objectstack-data/references/data-hooks.md` 的 `api.transaction` 行与新的 `Declared texts` 块;`scripts/check-skills-token-ratchet.mjs` 的 data-hooks 行注。 - 两分钟验证:`node scripts/check-skills-token-ratchet.mjs | grep data-hooks`,预期见 `10122 tokens (ceiling 10122; headroom 0)`。 - 需要你做的:席位合同审核通过后批准落地(受管面 `skills/**`)。 ## What changes `skills/objectstack-data/references/data-hooks.md`: - **`api.transaction` row** (Capabilities table). Was: "runs the callback's `ctx.api` ops in **one driver transaction** (commit on return, rollback on throw)", with no condition. Now: 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. Worded from `content/docs/automation/hooks.mdx` ("A nested `transaction()` joins the outer unit, so its return is no commit") and from PR #35102's `CrossDatasourceTransactionWriteError` and its ADR-0119 note (2026-11-18), which says the trio the sandbox uses gets the same refusal as `transaction(cb)`. Runtime read: `packages/runtime/src/sandbox/quickjs-runner.ts` `__txCommit` / `__txRollback` abstain on a joined handle and the rollback leaf re-throws; `ScopedContext.beginTransaction` joins the ambient transaction (`owned: false`). - **New "Declared texts (`texts`)" block** right after "Declared refusals", in its compact form: declare on the hook, ask with `ctx.text(key, params?)` (no capability; a `js` body or a `handler`, never an `expression` body); the organization's language (Setup → Localization, else `i18n.defaultLocale`), never the saver's; translated first, then filled from `params`; a missing translation never fails the hook; an unreadable Localization setting rejects; only declared keys. Worded from `hooks.mdx` § "Writing a sentence people read — `texts`" and the `texts` TSDoc in `packages/spec/src/data/hook.zod.ts`. The block names the translation key inline, `hooks.HOOK.texts.KEY.message`, and points to objectstack-i18n for the bundle; the bundle shape is not restated (PR #35302 owns it). - **`ctx.text` row** in the sandbox `ctx` table: one cell, a pointer to the block. `skills/objectstack-data/evals/hooks-security-seeds-datasources.json`: two cases, ids 28 and 29 (25 and 26 are taken by open draft PR #34964), inserted after id 17 so they do not touch that PR's hunk at the end of the array: - 28: a blocking `afterUpdate` body whose `ctx.api.transaction` throws after an insert and catches it, plus an insert to a business object on a non-default datasource (`join`, `ERR_CROSS_DATASOURCE_TRANSACTION_WRITE`). - 29: an `afterInsert` hook writing a task subject in the organization's language (`texts`, `ctx.text`, `params`); it links the task by `ctx.result.id` and pins `related_to_lead: ctx.input.id` as must_not_contain. `scripts/check-skills-token-ratchet.mjs`: the data-hooks row 10011 → 10122 with its note. `.changeset/34967-data-hooks-transaction-texts.md`: `@objectstack/skills` patch. ### Paid down first, remainder by measurement Raise path: the standing ruling 「A:先削重复,余额按实测提高」 (ruling record 6513306068, letter B). Ten restatements cut in the same file, each keeping its other home: 2. Hook Context API, "Sandbox vs in-process" blockquote (now a two-line pointer). Other home: the `body` vs `handler` table under Sandboxed Hook Bodies. 3. "Reading the current organization": the column / RLS / seed-row sentence. Other home: the `HookContext` listing comment on `organizationId` and the code line's own comment. 4. `body` — Implementation: the example block. Other home: "The `body` shape" block and the `before*` bullet under it (`ctx.input.x = …`). 5. Pattern 4: the five-line `session.roles` comment (now one line). Other home: the `ctx.session` row ("`session.roles` was retired in 17.0.0") and the field-level callout above the pattern. 6. Copy-paste example: the "`ctx.result` is the PARTIAL patch" comment. Other home: Gotcha 1 right above it, and the example's intro sentence. 7. Copy-paste example: the "needs the acting user to be able to edit" comment. Other home: Gotcha 2 right above it. 8. Body shape block: the `// the FUNCTION BODY only — not a module` comment. Other home: the bullet under the block (`source` is the function body the runtime wraps) and Sandbox restrictions (import/require rejected). 9. Sandbox `ctx` table, `ctx.email` row: "; not in a hook body". Other home: the `email.send` capability row ("Not in a hook body (refused at parse and at bind)"). 10. `api.read` capability row: the `ctx.title` clauses. Other home: the `ctx.title` row. 11. HookContext listing: the `notice?` comment. Other home: the `ctx.notice` row, which links rules/lifecycle.md § Save Notice. Restored in the fix round (review 6999973886): the "Why so few?" per-row sentence, byte-identical to `main` (PR #34964 cites it as a home). Items are numbered 2-11; ten cuts remain. Arithmetic (bytes, `ceil(bytes / 4)` tokens): `main` 40004 (10001 of 10011, headroom 10). The text adds 1805, the ten cuts remove 1323, landed 40486 → 10122. The ceiling moves +111, the measured remainder only, pinned at the measurement. ### `skills/**` readings | Reading | Before (`c809deb67`) | After | |:--|--:|--:| | `data-hooks.md` lines | 890 | 893 | | `data-hooks.md` tokens | 10001 | 10122 | | All `skills/**/SKILL.md` lines | 4835 | 4835 | | Whole `skills/**` tree lines | 22082 | 22105 | | Bundle tokens (ratchet's "bundle total") | 270968 | 271730 | The bundle token delta is +121 in authored text and +641 in eval fixtures (unpriced, population 1b). ## Tests No package code changes, so there are no package tests to run. The one edited script is `scripts/check-skills-token-ratchet.mjs` (a row note and the measured ceiling): its own `--self-test` passes (104 cases). No `*.test.*` file names it. No ablation: text, config and a ratchet row only. ## Acceptance notes - Observation, not filed (no repro run): the sandbox refuses a `ctx.api.transaction` nested inside another one in the same body (`nested ctx.api.transaction is not supported`, `quickjs-runner.ts` `__txBegin`). The row does not say so. That is a different case from joining a unit the host opened. - Observation, not filed: the Hook Context API `input` section shows a delete's `ctx.input` as `{ id: '123' }`, while pattern 1 says a delete's `ctx.input` is empty (`ctx.previous` is the row). Read only, not measured, and the two may describe different doors (`handler` vs `body`). - Footer: the dispatch order asks for the body to end with the "Generated with" line and the session URL. AGENTS.md asks for the rule-plus-session-URL footer block on a PR body. This body carries both, the block last. ## Verification <details><summary>Premise readings on origin/main c809deb</summary> - A1 holds: `skills/objectstack-data/references/data-hooks.md:334`, the `api.transaction` row: "runs the callback's `ctx.api` ops in **one driver transaction** (commit on return, rollback on throw)", no condition, nothing on datasources. - A2 holds: `grep -n "texts\|ctx.text"` gives 0 hits in the file; the `refusals` block is at :830-879 (`### Declared refusals` :830), plus uses at :609 and :742. - A3 holds: `hooks-security-seeds-datasources.json` has 25 cases (ids 1-24 and 27). </details> <details><summary>Ratchet</summary> ``` ✓ check-skills-token-ratchet: skills/objectstack-data/references/data-hooks.md is 10122 tokens (ceiling 10122; headroom 0). ✓ check-skills-token-ratchet: 59 authored bundle file(s) within their ceilings; 10 generator-owned file(s) and 38 eval fixture(s) measured, not ratcheted. ✓ check-skills-token-ratchet self-test: 104 cases pass. ``` </details> <details><summary>Local gate subset (head f7fa386; fix round 84b73e2 re-ran the ratchet, skills, changeset gates and overlap-check, all exit 0)</summary> `node scripts/pm/dispatch-gates.mjs --commands` derived 65 commands. 60 exited 0 on the first run, `check:pm-dispatch-gates` among them (fast tier, 2249 cases). `check:doc-formula-expressions` exited 3 (`PREREQUISITE NOT MET`, `@objectstack/lint` not built); it exited 0 after `turbo run build --filter=@objectstack/lint` under the verify lock. Four Build Core families exited 3 for unbuilt dist and were not measured locally: `check:dts-closure`, `check:dual-build-cjs-loads`, `check:lean-entry-closure`, `check:sourcemap-no-sources-content`. CI's Build Core runs them. Exit codes were captured before any pipe and reconciled with `--ran`. ``` ✓ check-skill-links: 269 relative link(s) in 73 published skill file(s) resolve; 139 fragment(s) name a real heading under GitHub's slug rule. ✓ check-skill-id-lint: 120 file(s) clean (pattern /#[0-9]{3,}/g). ✓ check:doc-formula-expressions: 26 record-scoped formula example(s) across 580 files / 1854 TS blocks judged clean by @objectstack/formula. ✓ dispatch-gates --ran: 65 derived famil(ies) accounted for — 61 run, 4 NOT-MEASURED (4 DERIVED from a recorded exit 3). overlap-check: ✓ #34964 (shares the eval json and data-hooks.md): merges cleanly · VERDICT clean exit 0 overlap-check at 84b73e2: ✓ #34964, #35312: merges cleanly · VERDICT clean exit 0 ``` </details> 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01Utp6CazXu8zyYD5PC6J2u7 --- _Generated by [Claude Code](https://claude.ai/code/session_01Utp6CazXu8zyYD5PC6J2u7)_ <!-- signed: repo:objectstack#5 · os-bill · session_01Utp6CazXu8zyYD5PC6J2u7 --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 475ae46 commit e4bfa33

4 files changed

Lines changed: 85 additions & 32 deletions

File tree

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
---
2+
'@objectstack/skills': patch
3+
---
4+
5+
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`
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
objectstack-data's `references/data-hooks.md`:
11+
12+
- 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.
13+
- 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.
14+
- Ten restatements in the same file were removed to pay for the new text.
15+
16+
`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`.

‎scripts/check-skills-token-ratchet.mjs‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1032,7 +1032,21 @@ export const CEILINGS = new Map([
10321032
// (its two halves live in the listing comment and the two-axes note, which
10331033
// now names the two `tenantId` symbols), the `ctx.user` paragraph under the
10341034
// `??` line that shows it, and the `session.roles` history clause.
1035-
['skills/objectstack-data/references/data-hooks.md', 10011],
1035+
// 10011 -> 10122 (the data-hooks follow-ups of PRs #34503, #35102 and
1036+
// #34545): the `api.transaction` row teaches that a body transaction is on
1037+
// the default datasource only (`400 ERR_CROSS_DATASOURCE_TRANSACTION_WRITE`
1038+
// for a write to any other) and that inside an open unit it joins that unit
1039+
// (its return no commit, its throw no rollback); a `Declared texts` block
1040+
// beside `refusals`, naming its translation key, and a `ctx.text` pointer row
1041+
// teach hook `texts` + `ctx.text`. Raise path the standing ruling
1042+
// 「A:先削重复,余额按实测提高」 (ruling record 6513306068, letter B). PAID DOWN
1043+
// FIRST — ten restatements cut, each keeping its other home (listed in the
1044+
// PR body). Arithmetic against `main`'s 40004 bytes (headroom 10): the text
1045+
// adds 1805, the cuts remove 1323, so the LANDED file is 40486 bytes ->
1046+
// ceil(40486 / 4) = 10122; the ceiling moves +111, the measured remainder
1047+
// only. Pinned AT the measurement.
1048+
// ceil($(wc -c < skills/objectstack-data/references/data-hooks.md) / 4) == ceil(40486 / 4)
1049+
['skills/objectstack-data/references/data-hooks.md', 10122],
10361050
['skills/objectstack-data/rules/datasources.md', 911],
10371051
// -552 (was 3584): re-locked at the landed count (#16374) after PR #16187
10381052
// (the two `tree` rows) and PR #16369 (the ASCII decision tree deleted)

‎skills/objectstack-data/evals/hooks-security-seeds-datasources.json‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -211,6 +211,26 @@
211211
"must_not_contain": ["using: 'owner_id"]
212212
}
213213
},
214+
{
215+
"id": 28,
216+
"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.",
217+
"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).",
218+
"files": [],
219+
"assertions": {
220+
"must_contain": ["join", "ERR_CROSS_DATASOURCE_TRANSACTION_WRITE"],
221+
"must_not_contain": []
222+
}
223+
},
224+
{
225+
"id": 29,
226+
"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`.",
227+
"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.",
228+
"files": [],
229+
"assertions": {
230+
"must_contain": ["texts", "ctx.text", "params"],
231+
"must_not_contain": ["related_to_lead: ctx.input.id"]
232+
}
233+
},
214234
{
215235
"id": 20,
216236
"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.",

‎skills/objectstack-data/references/data-hooks.md‎

Lines changed: 34 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -128,14 +128,7 @@ const myHook = defineHook({
128128
#### `body` — Implementation
129129

130130
A `source` of statements against `ctx`; a throw aborts the write
131-
([Sandboxed Hook Bodies](#sandboxed-hook-bodies-body--what-the-sandbox-ctx-can-call)):
132-
133-
```typescript
134-
body: {
135-
language: 'js',
136-
source: `if (ctx.input.email) ctx.input.email = ctx.input.email.trim().toLowerCase();`,
137-
}
138-
```
131+
([Sandboxed Hook Bodies](#sandboxed-hook-bodies-body--what-the-sandbox-ctx-can-call)).
139132

140133
#### `condition` — Declarative Filtering
141134

@@ -228,7 +221,7 @@ CEL has no overload for does **not** degrade to "the hook did not fire" — it
228221
```jsonc
229222
body: {
230223
language: 'js', // 'js' = L2 sandboxed script | 'expression' = L1 pure formula
231-
source: "/* function body */", // the FUNCTION BODY only — not a module
224+
source: "/* function body */",
232225
capabilities: ['api.read', 'api.write', 'log'], // default: []
233226
timeoutMs: 250, // optional, ≤ 30000 (hook default 250ms, action 5000ms)
234227
memoryMb: 32, // optional, ≤ 256 (best-effort under QuickJS)
@@ -261,9 +254,10 @@ The sandbox is handed a **JSON snapshot** of these (built by
261254
| `ctx.api` | object | Cross-object CRUD. Gated by `api.read` / `api.write` — see below. |
262255
| `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). |
263256
| `ctx.crypto` | `{ randomUUID }` | Gated by `crypto.uuid`. |
264-
| `ctx.email` | `{ send }` | Gated by `email.send`; not in a hook body. |
257+
| `ctx.email` | `{ send }` | Gated by `email.send`. |
265258
| `ctx.activity` | `{ append }` | Gated by `activity.append`. |
266259
| `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). |
260+
| `ctx.text` | `(key, params?) => Promise<string>` | A declared sentence in the organization's language — [`texts`](#declared-texts-texts). |
267261
| `ctx.title` | `(field?) => Promise<string \| null>` | **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. |
268262

269263
(Action bodies additionally receive `ctx.recordId` and `ctx.record`, and their
@@ -329,9 +323,9 @@ set of legal tokens (`HookBodyCapability`) is exactly seven:
329323

330324
| Token | Unlocks |
331325
|:--|:--|
332-
| `api.read` | `ctx.api.object(n).find` / `findOne` / `count` / `aggregate`; also `ctx.title('<lookup field>')`, which reads that related record. Plain `ctx.title()` reads nothing and needs no token. |
326+
| `api.read` | `ctx.api.object(n).find` / `findOne` / `count` / `aggregate`; also `ctx.title('<lookup field>')`. |
333327
| `api.write` | `ctx.api.object(n).insert` / `update` / `delete` |
334-
| `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`. |
328+
| `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`. |
335329
| `crypto.uuid` | `ctx.crypto.randomUUID()` |
336330
| `log` | `ctx.log.debug` / `info` / `warn` / `error(msg, data?)` |
337331
| `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 +401,9 @@ const fillPositionOnHire = defineHook({
407401
body: {
408402
language: 'js',
409403
source: `
410-
// afterUpdate → ctx.result is the PARTIAL patch. Gate on the field this
411-
// write actually set, then re-query for the lookup FK it does NOT carry.
412404
if (!ctx.result || ctx.result.stage !== 'hired') return;
413405
const rec = await ctx.api.object('candidate').findOne({ where: { id: ctx.result.id } });
414406
if (!rec || !rec.position_id) return;
415-
// Cross-object write — needs the acting user to be able to edit 'position'.
416407
await ctx.api.object('position').update({ id: rec.position_id, status: 'filled' });
417408
ctx.log.info('position filled', { position: rec.position_id });
418409
`,
@@ -444,11 +435,8 @@ export default fillPositionOnHire;
444435

445436
## Hook Context API
446437

447-
> **Sandbox vs in-process.** The `ctx` documented below is the **in-process
448-
> `handler`** context (full Node; `handler` is deprecated). A metadata-native **`body`** sees a
449-
> capability-gated *subset* of it inside an isolated VM — see
450-
> [Sandboxed Hook Bodies](#sandboxed-hook-bodies-body--what-the-sandbox-ctx-can-call)
451-
> for exactly what is and isn't available there.
438+
> The `ctx` below is the deprecated in-process `handler`'s; a `body` sees the
439+
> [sandbox subset](#what-lives-on-the-sandbox-ctx).
452440
453441
The engine's `HookContext` provides:
454442

@@ -483,7 +471,7 @@ interface HookContext {
483471
// Engine access
484472
ql: IDataEngine; // ObjectQL engine instance
485473
api?: ScopedContext; // Cross-object CRUD API
486-
notice?: (message: string) => void; // Save notice: rules/lifecycle.md § Save Notice
474+
notice?: (message: string) => void;
487475

488476
// User info shortcut (undefined for system / unauthenticated writes)
489477
user?: {
@@ -497,10 +485,7 @@ interface HookContext {
497485

498486
### Reading the current organization
499487

500-
The value a hook usually wants when it needs "the current org to filter/scope
501-
by" is the caller's **active organization** — the same value that lives in the
502-
`organization_id` column, in `current_user.organizationId` inside RLS/sharing
503-
predicates, and in seed rows. Read it as **`organizationId`**:
488+
To scope by the caller's **active organization**, read **`organizationId`**:
504489

505490
```typescript
506491
// ✅ Blessed — matches columns, RLS `current_user`, and seed data
@@ -696,12 +681,7 @@ const maskSensitiveData = defineHook({
696681
handler: async (ctx) => {
697682
// Exempt the engine's own elevated reads (`isSystem`) — internal writes
698683
// and self-reads must see the real values.
699-
//
700-
// ⚠️ Never gate this on a session claim: `ctx.session?.roles?.includes(…)`
701-
// is always `undefined` (see the ctx table above), so a mask written that
702-
// way never exempts anyone. A per-permission-set or per-position exemption
703-
// belongs in field-level permissions (the callout above), which the read
704-
// path applies for you.
684+
// ⚠️ Never a session claim (`ctx.session.roles` is gone, ctx table above).
705685
const isElevated = ctx.session?.isSystem === true;
706686

707687
if (!isElevated) {
@@ -878,6 +858,29 @@ export default defineHook({
878858
refused: at save if thrown literally, else as a `500`. Unchanged `ctx.api`
879859
errors and crashes pass through.
880860

861+
### Declared texts (`texts`)
862+
863+
A sentence the hook writes into a record (a task's subject, a logged summary) is
864+
read by the whole organization: declare it in `texts` and ask for it with
865+
`ctx.text(key, params?)` — no capability; a `js` body or a `handler`, never an
866+
`expression` body.
867+
868+
```typescript
869+
texts: { follow_up_subject: { message: 'Follow up with lead: {{ lead }}', params: ['lead'] } },
870+
// afterInsert body (capabilities: ['api.write']):
871+
const subject = await ctx.text('follow_up_subject', { lead: ctx.input.name });
872+
await ctx.api.object('crm_task').insert({ subject, related_to_lead: ctx.result.id });
873+
```
874+
875+
- In the **organization's** language (Setup → Localization, else the app's
876+
`i18n.defaultLocale`), never the saver's.
877+
- Translated first, then the `{{ }}` holes are filled from `params` (holes as in `refusals`).
878+
- A missing translation never fails the hook: the declared `message` is written.
879+
- An unreadable Localization setting rejects `ctx.text`; catch it to write anyway.
880+
- Only declared keys: another is refused at save if asked for literally, else as
881+
a `500`. A string the hook builds itself is written as it is.
882+
- Translation key `hooks.<hook>.texts.<key>.message`; the bundle: [objectstack-i18n](../../objectstack-i18n/SKILL.md).
883+
881884
---
882885

883886
## References

0 commit comments

Comments
 (0)