Skip to content

Commit 007fdb1

Browse files
docs(skills): teach the hook body first in data-hooks.md, drop hook ctx.api methods that do not exist, guard nullable hook and formula predicates (#31201)
<!-- claude-projects-attribution: {"github_login":"huangyiirene"} --> _Requested by **Irene** · [project thread](https://claude.ai/code/project/chan_01TJXtQ1tVD26ecLDZxFS67x?thread=cmsg_01TJXtQ1tVD26ecLDZxFS67x4pLvSdLeUWyhWnmj1XoZjT)_ Fixes #31131 Clause-②: no Metadata-protocol: none `dispatch-gates --tier` reads a MANDATORY model tier for `skills/**` (clause ① of the model-tiering ruling); it is waived by the standing order of the maintainer in this project (2026-11-03), and this card ran on the project's default model. The dispatching seat runs the contract review. ## 维护者速读 - 改了什么:`objectstack-data` 的 `references/data-hooks.md` 改为先教沙箱 `body`:Schema 示例、实现小节、Pattern 3 都写成 `body`;`handler` 只作为已弃用形式保留(读脱敏 Pattern 4,因为 `body` 只回写 `ctx.input`;以及按名字注册的字符串 `handler`)。仓库方法表与 `api.write` 行去掉钩子 `ctx.api` 并不存在的 `upsert` / `updateMany` / `deleteMany`,批量写法改教 `update` / `delete` 加 `{ where, multi: true }`。Pattern 1–3 的 `body` 改用 `ctx.previous.id` 定位行(`body` 的 `ctx.input` 只在载荷带 `id` 时才有 `id`,批量/按 where/删除时为空,`where` 会匹配全部行)。两处钩子 `condition` 与 `objectstack-formula` 一处谓词加 `!= null` 守卫;§ Capabilities 链到 Connector recipes。 - 为什么改:这些地方把已弃用的入口、发布门会拒绝的裸可空比较、以及运行时会抛 "not implemented" 的方法教给 AI(#31131,承接 #31113 / PR #31127)。 - 风险与回滚:只改技能文字与 eval;两个文件都在 token 上限内,无上限上调(data-hooks 9987 → 9905,formula SKILL 5950 → 5956,后者由席位认可为余量支取);发 `@objectstack/skills` patch;回滚即 revert。 - 先看:`skills/objectstack-data/references/data-hooks.md` 的 § `ctx.api.object(name)` 方法表与 Pattern 3 / Pattern 4(席位裁定:Pattern 4 保留为标注弃用的 `handler`;批量写法以引擎为准)。 - 两分钟验证:`node scripts/check-skills-token-ratchet.mjs`,预期退出 0,`57 authored bundle file(s) within their ceilings`。 - 需要你做的:`skills/**` 属 Tier H(人合),需要 `os-zhuang` 或 `hotlong` 的一次 approval,之后席位落地。 ## What changes ### 1. `data-hooks.md` teaches `body` first Code sites: `HookSchema.handler` (`packages/spec/src/data/hook.zod.ts` L485: "DEPRECATED, prefer `body`") and `HookSchema.body` (L487–L498: preferred; with both present the runtime uses `body`). The capability set is `HookBodyCapability` (`packages/spec/src/data/hook-body.zod.ts` L48–L54; no `http.fetch`, L38). Per example, against the body runner (`packages/runtime/src/sandbox/body-runner.ts`): - **What a `body` receives:** `buildSandboxContext` (L1232 onward) hands a JSON snapshot: `input`, `previous` (`undefined` on insert), `result`, `user`, `session`, `event`, `object`, `api`, `log`, `title`, `notice`. - **What it can change:** only `ctx.input`, via `applyMutationsToInput` (L496; header L24–L36). A write to `ctx.result` stays in the VM. - **The row id:** `ctx.input` is a snapshot of the flat-input Proxy (`unwrapProxyToPlain`, L1481), whose `ownKeys` lists only the payload's keys (`installFlatInput`, `packages/objectql/src/hook-wrappers.ts` L689). So `ctx.input.id` exists only when the payload carries one: it is undefined on a bulk (`multi: true`) update, a `where`-addressed update and every delete. `ctx.previous.id` is bound on all of them; `packages/runtime/src/sandbox/perrow-dispatch-signal.integration.test.ts` L49 and L187–L188 pin `inputIdType === 'undefined'` and "the row id a per-row body needs is `ctx.previous.id`". - **Capabilities:** each `ctx.api.object(n).<method>` is gated by `api.read` / `api.write` in `quickjs-runner.ts` L705–L708. The method then runs on the engine's repository (`ObjectRepository`, `packages/objectql/src/engine.ts` L10079), and a method that repository lacks throws `not implemented` (`quickjs-runner.ts` L1368). - **A throw aborts the write:** the hook wrapper rethrows (`body-runner.ts` L497–L505). - **No outbound HTTP:** no `http.fetch` token, and `fetch` is absent from the VM (same file, § Sandbox restrictions). Every `handler` site the card listed, re-read on `main` `620b6e6d`: | `main` line | Site | Now | |:--|:--|:--| | L97 | Schema example `handler: async (ctx: HookContext) => {…}` | A `body: { language: 'js', source, capabilities: [] }`, commented "the inline `handler` is deprecated"; the unused `HookContext` import goes. | | L155–L171 | `#### handler — Implementation`: inline function "(recommended for simple hooks)" and the string ref `'my_plugin.validateAccount'` | `#### body — Implementation`: a `body` that normalises `ctx.input.email`, with "a throw aborts the write". One sentence names the deprecated `handler`'s two shapes (inline function, registered function's name) and links § Registration Methods, which holds the string-ref example. | | L319 | `body` vs `handler` comparison table | Stays: it documents the deprecated form. Its `handler` column header now says "(deprecated)"; the Status row already did. | | L739 | Cross-Object API `handler:` snippet | Deleted (seat ruling). Homes: § `ctx.api.object(name)` (the repo, the `where` key, the `filter` alias) and Pattern 2 (the related-record `insert`). The prose above it stays. | | L817 | Pattern 3, Multi-Object Logic, inline `handler` | A `body` with `capabilities: ['api.write']`; bulk write `update(fields, { where: { account_id: ctx.previous.id }, multi: true })` (review M1: `ctx.input.id` made the `where` empty, matching every contact). The comment "Only the sandbox `ctx.api` adds `updateMany`/`deleteMany`" goes (false, see § 2). | | L845 | Pattern 4, Data Masking on Read (`afterFind`) | Stays a `handler` (seat ruling A). Retitled "(deprecated inline `handler`)" with the reason: a `body` writes back only `ctx.input`, and its `ctx.result` is a snapshot. The field-level-metadata callout is unchanged. | | L890 | Registration, string-named `handler: 'normalize'` + `functions` | Stays (string-registered form), labelled "(deprecated)". | Same defect in the pre-existing bodies (review S3, claim widened 6710683947): Pattern 1 (`beforeDelete`) counted open opportunities on `account_id: ctx.input.id`, which is `{}` on a delete, so it counted across every account; it now keys on `ctx.previous.id`, and its comment says a delete's `ctx.input` is empty. Pattern 2 recorded `String(ctx.input.id || '')`; it now records `(ctx.previous || ctx.result || {}).id` (`previous` on update/delete, `result` on insert). The three "`input.id` names the row" sentences (the "Why so few?" callout, § `condition`'s `before*` and `after*` bullets) now read "`input.id` (`handler`; a `body`: `ctx.previous.id`)", and the sandbox `ctx.input` row says `id` is there only if the payload has it. Also, so the page does not contradict itself: the intro and § Sandboxed Hook Bodies no longer say "everything above this point showed the inline `handler`"; "Skip handler execution" and "inside the handler" in § `condition` become hook / body; § Sandbox restrictions labels "a bundled `handler`" as deprecated; § Hook Context API says the documented `ctx` is the deprecated in-process `handler` context. ### 2. The repository method table teaches only methods the hook's `ctx.api` has (seat ruling, same file) A hook body's `ctx.api` is the engine's `ScopedContext` (`buildSandboxApiSource`, `body-runner.ts` L1208–L1210), whose `object(name)` returns `ObjectRepository`: `find`, `findOne`, `insert`, `create`, `update`, `updateById`, `delete`, `deleteById`, `count`, `aggregate` and `execute` (which the sandbox does not install, `quickjs-runner.ts` L705–L708). `upsert`, `updateMany` and `deleteMany` therefore throw `ctx.api.object('…').updateMany not implemented`. The bulk form is the option: `ObjectRepository.update(data, options)` passes `options` to `engine.update` (`engine-object-repository.ts` L83–L88), which routes a predicate with `multi: true` to the driver's `updateMany` (`engine.ts` L6147–L6153, L7616); `delete` the same way (`packages/metadata-core/src/engine-delete-dispatch.ts` L72, L133 "Delete requires an ID or options.multi=true"). ```diff -| `update(data, opts?)` | `api.write` | **`update({ id, ...fields })`** — put the id **inside** `data` | -| `upsert(data, opts?)` | `api.write` | `upsert({ … })` | -| `delete(opts)` | `api.write` | `delete({ where: { id } })` | -| `aggregate` · `updateMany` · `deleteMany` | read · write · write | also installed; same `where` shape | +| `update(data, opts?)` | `api.write` | **`update({ id, ...fields })`** — put the id **inside** `data`; bulk: `update(fields, { where, multi: true })` | +| `delete(opts)` | `api.write` | `delete({ where: { id } })`; bulk: `delete({ where, multi: true })` | +| `aggregate(opts)` | `api.read` | same `where` shape | ``` ```diff -| `api.write` | `ctx.api.object(n).insert` / `update` / `delete` / `upsert` / `updateMany` / `deleteMany` | +| `api.write` | `ctx.api.object(n).insert` / `update` / `delete` | ``` ### 3. Nullable comparisons are guarded Code site: `packages/lint/src/validate-null-guards.ts`; its wiring table (L89) lists the lifecycle hook `condition` as covered (`hook-wrappers.ts` `materializeDeclaredFields`), and L747 makes a hook condition's fault refuse the write. `skills/objectstack-formula/SKILL.md` L112–L122 teaches the same rule. | Site | Before | After | |:--|:--|:--| | data-hooks.md L105 (schema example; not on the card, same site group by seat ruling) | `record.status == 'active' && record.amount > 1000` | `record.status == 'active' && record.amount != null && record.amount > 1000` | | data-hooks.md L219 | `record.annual_revenue > 1000000` | `record.annual_revenue != null && record.annual_revenue > 1000000` | | formula SKILL.md L268 (`os:check` block) | `record.amount > 10000 && record.region in ['us', 'eu']` | `record.amount != null && record.amount > 10000 && record.region in ['us', 'eu']` | Measured, not assumed: `findUnguardedNullableOperands` (the gate's decision procedure, run through `tsx` with every named field nullable) returns 1 finding for each "before" predicate and 0 for each "after" predicate. ### 4. § Capabilities links Connector recipes "outbound calls go through Connector recipes" now links [`objectstack-automation/references/integration-recipes.md`](../../objectstack-automation/references/integration-recipes.md) (relative from `skills/objectstack-data/references/`, resolves to `skills/objectstack-automation/references/integration-recipes.md`), with "(`connector_action` in a flow)". The target's recipes are connector declarations dispatched by a flow (recipe 1 is a scheduled flow); a `record-before-*` flow gates a write, a `record-after-*` or scheduled flow carries a side effect, so the note names no phase (review S1). `rules/validation.md` already sends external-API checks to this section. ## Token readings (`node scripts/check-skills-token-ratchet.mjs`, exit 0) | File | `main` `620b6e6d` | This branch | Ceiling | |:--|--:|--:|--:| | `skills/objectstack-data/references/data-hooks.md` | 9987 | 9905 | 10011 | | `skills/objectstack-formula/SKILL.md` | 5950 | 5956 | 5997 (+6 drawn from existing headroom, accepted by the seat as review S2) | No ceiling is raised, so the ruling path was not used. No line was re-wrapped. Every deletion, with the facts it held and where each survives: - **Cross-Object API `handler` snippet (main L738–L755).** Facts: `ctx.api.object(name)` returns a repository → § `ctx.api.object(name)` first paragraph; `findOne({ where: { id } })` with `where` canonical and `filter` a tolerated alias → same section, "Query shape" and the `filter:` note; inserting a related record with the session user → Pattern 2 (`audit_log` insert, `ctx.session && ctx.session.userId`); "within the same transaction" and "`body` needs `api.read` / `api.write`" → the prose kept above it. - **`#### handler — Implementation` (main L155–L171).** Facts: the inline-function shape → the comparison table's Shape row; the string reference → § Registration Methods (`handler: 'normalize'` + `functions`), linked from the new sentence; "throw to abort" → the new section's first line and § Error Handling. "(recommended for simple hooks)" is dropped: it recommended the deprecated door. - **§ Sandboxed Hook Bodies lead (main L311–L313).** "Everything above this point showed the inline `handler`" is no longer true; "the form a metadata-only runtime executes" stays in the new lead. - **Pattern 3's four-line comment.** The bulk form `update(data, { where, multi: true })` stays in the code and in the method table; "the handler-side repo has no `updateMany`" is moot for a `body`; "only the sandbox `ctx.api` adds `updateMany` / `deleteMany`" was false (§ 2). - **Method table rows `upsert` and `aggregate · updateMany · deleteMany`, and three `api.write` tokens.** False (§ 2); `aggregate` keeps its own row. - **§ `async` bullets "Calling slow external APIs" and "Logging to external systems" (seat ruling).** A `body` has no outbound HTTP; home: § Capabilities → Connector recipes. - **Schema example `HookContext` import.** Unused once the example is a `body`. - **Review round (paid the M1/S3 additions, net −54 bytes):** Gotcha 1's closing sentence "Guard optional values with `record.x != null`, not with `has(record.x)`" (home: § `condition`, "Guard optional values with `!= null`, never with `has(...)`", same file); Pattern 1's trailing comment "count() is a read; an undeclared token throws in the VM" (homes: the method table's `count` → `api.read` row and § Capabilities "Calling an undeclared one throws inside the VM"); Pattern 2's `async: false, // must run inside the transaction` line (home: § `async`, "Blocking (default) — runs within transaction" and "When to use async: false: Creating related records"); Pattern 1's old comment "(it is undefined on insert)" (home: the sandbox `ctx.previous` row). ## Eval cases - `objectstack-data/evals/hooks-security-seeds-datasources.json` case 12 (new, body-first, bulk form, row key): copy a changed `account.industry` onto its contacts. The expected answer keys the bulk `where` on `ctx.previous.id` and says why. Must contain `afterUpdate`, `language`, `js`, `api.write`, `multi: true`, `ctx.previous.id`; must not contain `handler:`, `HookContext`, `account_id: ctx.input.id`. (`updateMany(` left the list per N1: an answer explaining the trap may name it.) - `objectstack-data/evals/hooks-security-seeds-datasources.json` case 13 (new, the guard): run a hook only when an optional `annual_revenue` is above 1,000,000. Must contain `condition:`, `record.annual_revenue != null`, `record.annual_revenue > 1000000`; `must_not_contain` is empty (per N1, `has(record.annual_revenue) &&` would fail an answer that explains why `has()` is no guard). The runtime sentence now says it refuses each write on an account with no `annual_revenue` (review S4). - `objectstack-formula/evals/cel-predicates-formulas.json` case 2 (corrected): its `expected_output` predicate was unguarded while its prose asked for the guard; the predicate now carries `record.amount != null &&`, and `must_contain` asserts `record.amount != null` (in place of the bare `record.`). - Sweep: no other case in either skill's evals rewards `handler`, `updateMany` / `deleteMany` / hook `upsert`, or an unguarded nullable comparison (cases 7 and 10 already forbid `handler:`). Every `must_contain` string appears in its `expected_output`, and no `must_not_contain` string does. - The Connector recipes link has no case of its own: case 10 already asserts that the external-API check leaves the hook. ## Other sites found (not changed: outside this card's file surface) - `skills/objectstack-automation/references/state-machines-and-approvals.md` L90, L128, L133, L135: ``condition: cel`record.amount > 100000` `` (and `> 500000`, `<= 500000`) on a `record-after-update` flow's start and edges, unguarded and refused (confirmed by the review). Going to a follow-up card. - `packages/spec/src/data/hook.zod.ts` L524–L526: the `condition` jsdoc `@example` and `.describe()` show `record.amount > 1000` unguarded, published to `content/docs/references/data/hook.mdx`. Going to a follow-up card. - `skills/objectstack-formula/SKILL.md` L57: the `cel` row's example `` cel`record.amount * 1.1` `` multiplies a possibly-null field. It is a computed value in a reference table, not a predicate the gate judges. ## Deviations (all accepted by the seat before writing) - The card's L739 example is deleted, not rewritten (seat ruling 2). - The card's L845 example stays a `handler`, labelled deprecated (seat ruling 1, option A): a `body` cannot rewrite `ctx.result`. - Widened in the same file (claim comment 6710259290): the `upsert` / `updateMany` / `deleteMany` correction (§ 2), the L105 guard, the two `async` bullets. - Widened again after the contract review (claim comment 6710683947): Patterns 1 and 2 keyed on `ctx.previous.id`, and the "`input.id` names the row" prose scoped to the `handler`. The sandbox `ctx.input` row ("plus `id`") states the same claim for a body, so it was scoped in the same commit. ## Review round 1 (contract review 6710673767, FAIL at 9931ab6) - M1 fixed (Pattern 3 and case 12 on `ctx.previous.id`; case 12 forbids `account_id: ctx.input.id`). S1 fixed (no flow phase in the Connector recipes note). S2 accepted by the seat as a headroom draw. S3 fixed under the widening. S4 fixed. N1 applied (quote-free `must_contain`, trap-explaining strings off `must_not_contain`). N4 and N5 corrected in this body. N2 and N3 skipped by the seat's word. - Delta review 6710804344 (FAIL at a15a1f3): Gotcha 1 said both `ctx.result` and `ctx.input` carry `id`; it now reads "(`ctx.result` adds `id`)" (9b1e926, +4 tokens from headroom: 9901 → 9905). N2 left as is. - `origin/main` had moved 5 commits past the base `620b6e6d` at review time (`3c1eb635`, `8acbfab9`, `bd5a443c`, `150f7401`, `658d84f5`), none touching these files; merged into the branch with the fix (merge commit, no rebase). ## Verification <details><summary>Local gates on 9931ab6: 46 derived, 46 exit 0, 0 NOT MEASURED</summary> - `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` derived 46 commands for the 5 changed paths; each ran after a full `pnpm build` (exit 0) under `NODE_OPTIONS=--max-old-space-size=8192`, with its exit code captured before any pipe. `dispatch-gates --ran` reconciles: 46 derived, 46 run, 0 NOT-MEASURED, 0 UNRUN. All 46 exited 0, including `check:skill-identifier-liveness`, `check:skill-compatibility`, `check:skill-frame-sync`, `check:skill-docs`, `check:skill-refs`, `check:doc-authoring`, `check:corpus-claim-drift`, `check:role-word` and the token ratchet. </details> - `pnpm check:skill-top-level-keys` (an artifact-roster family, not derived): exit 0. - `pnpm --filter @objectstack/spec run check:skill-examples` (the `os:check` gate; not derived): exit 0, `285 prose examples type-check across 3 surface(s)`. - `node scripts/check-skills-token-ratchet.mjs`: exit 0, `57 authored bundle file(s) within their ceilings`. - `node scripts/check-commit-card-trailers.mjs --range origin/main..HEAD`: exit 0 before the push. - Delta run on a15a1f3 (after the review fix and the `origin/main` merge): the token ratchet, `check:skill-refs`, both eval JSON files parse, `check-commit-card-trailers`, `check:skill-identifier-liveness`, `check:skill-top-level-keys`, `check:doc-authoring`, `check:corpus-claim-drift`, `check:role-word`, and `@objectstack/spec` build + `check:skill-examples` (285 prose examples type-check): all exit 0. ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. (No schema touched.) - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran. - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset (`'@objectstack/skills': patch`), and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` not touched; nothing to regenerate. - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. (The 维护者速读 section is Chinese, per the lane template.) - [x] The *Before Submitting* list in CONTRIBUTING.md is done. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01J8VVAnzH4vvvJVUf6zdYe9 <!-- signed: domain:skills#3 · huangyiirene · session_01J8VVAj7CvjkGXvgXzd6RZ7 --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 7fe019f commit 007fdb1

5 files changed

Lines changed: 94 additions & 87 deletions

File tree

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@objectstack/skills': patch
3+
---
4+
5+
docs(skills): teach the hook `body` first in `objectstack-data`'s data-hooks reference, guard nullable hook-condition and formula predicates, link Connector recipes
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
`references/data-hooks.md` now teaches the sandboxed `body` in its schema example, its implementation section and the cross-object pattern; the inline `handler` appears only as the deprecated form (the read-masking pattern stays one, since a `body` writes back only `ctx.input`). Its `body` examples key the row on `ctx.previous.id`: a body's `ctx.input` carries `id` only when the payload does, so a bulk, by-`where` or delete dispatch would otherwise scope a write or a count to every row. Its repository table and `api.write` row drop `upsert` / `updateMany` / `deleteMany`, which a hook's `ctx.api` does not implement, and teach `update` / `delete` with `{ where, multi: true }` as the bulk form. Two hook `condition` examples and one `objectstack-formula` predicate gain the `!= null` guard the publish gate requires, and § Capabilities links the Connector recipes reference. The platform behaviour already shipped; this release only teaches it.

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

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,26 @@
110110
"must_contain": ["ObjectSchema.create", "remoteName", "sharingModel: 'public_read'"],
111111
"must_not_contain": ["columnName:"]
112112
}
113+
},
114+
{
115+
"id": 12,
116+
"prompt": "When an `account`'s `industry` changes, copy the new value into `account_industry` on every contact of that account.",
117+
"expected_output": "An `afterUpdate` hook on `account` with a sandboxed `body: { language: 'js', source, capabilities: ['api.write'] }`: the source compares `ctx.input.industry` with `ctx.previous.industry` and, when it changed, makes one bulk write, `ctx.api.object('contact').update({ account_industry: ctx.input.industry }, { where: { account_id: ctx.previous.id }, multi: true })`. The row is keyed on `ctx.previous.id`: a body's `ctx.input` carries `id` only when the payload does, so on a bulk or by-`where` update the key would be empty and the `where` would match every contact. Not the deprecated inline `handler`, and not a bulk method the hook's `ctx.api` does not have (`updateMany` throws \"not implemented\").",
118+
"files": [],
119+
"assertions": {
120+
"must_contain": ["afterUpdate", "language", "js", "api.write", "multi: true", "ctx.previous.id"],
121+
"must_not_contain": ["handler:", "HookContext", "account_id: ctx.input.id"]
122+
}
123+
},
124+
{
125+
"id": 13,
126+
"prompt": "Run our `account` enrichment hook only for accounts whose `annual_revenue` (an optional currency field) is above 1,000,000.",
127+
"expected_output": "The hook's declarative `condition: P`record.annual_revenue != null && record.annual_revenue > 1000000``. `record` is total over the declared fields, so an empty `annual_revenue` reads `null` and CEL has no `>` overload for it: the publish gate refuses the unguarded comparison, and at runtime it would refuse each write on an account with no `annual_revenue`. `has(record.annual_revenue)` is not a guard (a declared field holding null is present).",
128+
"files": [],
129+
"assertions": {
130+
"must_contain": ["condition:", "record.annual_revenue != null", "record.annual_revenue > 1000000"],
131+
"must_not_contain": []
132+
}
113133
}
114134
]
115135
}

0 commit comments

Comments
 (0)