You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Commit e4bfa33
Browse filesBrowse the repository at this point in the historyBrowse 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#34967Fixes#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>
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`.
Copy file name to clipboardExpand all lines: skills/objectstack-data/evals/hooks-security-seeds-datasources.json
+20Lines changed: 20 additions & 0 deletions
Original file line number
Diff line number
Diff line change
@@ -211,6 +211,26 @@
211
211
"must_not_contain": ["using: 'owner_id"]
212
212
}
213
213
},
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).",
"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.",
"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.",
memoryMb:32, // optional, ≤ 256 (best-effort under QuickJS)
@@ -261,9 +254,10 @@ The sandbox is handed a **JSON snapshot** of these (built by
261
254
|`ctx.api`| object | Cross-object CRUD. Gated by `api.read` / `api.write` — see below. |
262
255
|`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). |
263
256
|`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`. |
265
258
|`ctx.activity`|`{ append }`| Gated by `activity.append`. |
266
259
|`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). |
267
261
|`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. |
268
262
269
263
(Action bodies additionally receive `ctx.recordId` and `ctx.record`, and their
@@ -329,9 +323,9 @@ set of legal tokens (`HookBodyCapability`) is exactly seven:
329
323
330
324
| Token | Unlocks |
331
325
|:--|:--|
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. |
|`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`. |
|`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. |
0 commit comments