Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions .changeset/34967-data-hooks-transaction-texts.md
Original file line number Diff line number Diff line change
@@ -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 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 default-datasource rule, one on `texts` with `ctx.text`.
16 changes: 15 additions & 1 deletion scripts/check-skills-token-ratchet.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -1004,7 +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.
['skills/objectstack-data/references/data-hooks.md', 10011],
// 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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 `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"],
"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, 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": ["related_to_lead: ctx.input.id"]
}
},
{
"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.",
Expand Down
65 changes: 34 additions & 31 deletions skills/objectstack-data/references/data-hooks.md
Original file line number Diff line number Diff line change
Expand Up @@ -128,14 +128,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

Expand Down Expand Up @@ -228,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)
Expand Down Expand Up @@ -261,9 +254,10 @@ 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<string>` | A declared sentence in the organization's language — [`texts`](#declared-texts-texts). |
| `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. |

(Action bodies additionally receive `ctx.recordId` and `ctx.record`, and their
Expand Down Expand Up @@ -329,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('<lookup field>')`, 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('<lookup field>')`. |
| `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 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. |
Expand Down Expand Up @@ -407,12 +401,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 });
`,
Expand Down Expand Up @@ -444,11 +435,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:

Expand Down Expand Up @@ -483,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?: {
Expand All @@ -497,10 +485,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
Expand Down Expand Up @@ -696,12 +681,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) {
Expand Down Expand Up @@ -878,6 +858,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.result.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 `hooks.<hook>.texts.<key>.message`; the bundle: [objectstack-i18n](../../objectstack-i18n/SKILL.md).

---

## References
Expand Down
Loading