Skip to content

Commit 6592546

Browse files
docs(skills): data hooks and actions teach the multi-reason refusal throw (#37619)
<!-- claude-projects-attribution: {"github_login":"os-sales"} --> _Requested by **Sales** · [project thread](https://claude.ai/code/project/chan_01D5bWFY3rFzgJcytD5gD4Uu?thread=cmsg_01D5bWFY3rFzgJcytD5gD4UuPE7uyDAJyqjwwMzomWv5ff)_ Fixes #37407 Clause-②: no (published prose only; teaches the list throw already on main) Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:AI 助手照技能文档写钩子或动作时,现在会写「一次拒绝、列出多条原因」的写法,每条原因按用户的语言显示一行,最后一行是总结句。以前文档只教一次一条原因,这个能力在 #37395 已经上线,文档没跟上。 - 为什么做:#36877 的裁决要求配套技能文档;5 号座位审核时还留了两条要写进来:一条原因怎么声明,以及总结句里有占位符时要传顶层参数,否则占位处是空的。 - 出错会怎样:只改技能文字,不动产品。两个文件原本都没有余量,为了不变长,同文件里压缩了一些说法,删了一个重复的条件示例和示例里的一个字段,没有删掉事实。写错的话撤回即可。 - 要你做什么:这是受管的技能文件,需要审批人批准后才能合并。 ## What changes `skills/objectstack-data/references/data-hooks.md` and `skills/objectstack-ui/rules/actions.md`, plus a `patch` changeset for `@objectstack/skills`. - **data-hooks.md, Declared refusals:** - The `reasons` bullet says how an entry declares them: a snake_case reason mapped to `{ message }` only, under the code's wire `code` and status; another status needs another code (zone o5-U note N1, comment 7181230894). - The `params` bullet says a reason's holes follow the same rule. - A new bullet teaches the list throw, `reasons: [{ reason, params? }, …]` instead of `reason`: one translated line each, filled from its own `params`; `userMessage` joins them by newlines and ends with the entry's `message`, filled from the throw's top-level `params`, else its holes are empty (note N3); the HTTP doors answer `details.refusals: [{ reason, message }]`, absent for a single `reason` (the MCP tool gives the lines as text beside its envelope, so the page does not say every door). - The last bullet adds that a listed reason is judged even under a code that declares no `reasons`, and that a `reasons` that is not a non-empty list of `{ reason, params? }`, or one beside `reason`, is a `500`. - **actions.md, Refusing by code:** one sentence with the shape: "For several reasons throw `reasons: [{ reason, params? }, …]`, not `reason`: `userMessage` is one line per reason, closed by the code's `message` (rules there)." The rules stay a pointer to the hook section. - **Paid in the same files.** Both sat at zero token headroom, so every added byte is paid for nearby; net −13 lines. Removed: the third ("Complex conditions") `condition` example, two comments that restated the condition below them, `annual_revenue` from the insert `input` sample, the "lifecycle events organized by operation type" lead-in. The rest is tightened wording (data-hooks: What Are Hooks, `defineHook`, `has()`, `filter:`, `findOne`, unpredicated `find`, capabilities lead-in, `ctx.log`, `HookContext` note, `ctx.input`; actions: shorter example strings and one `params` array on one line). No other file pins any shortened string. Checked against `packages/runtime/src/sandbox/hook-refusal-catalogue.ts`, `quickjs-runner.ts` and `packages/spec/src/data/declared-entry.zod.ts` on `main`: the join order and closing line, top-level `params` filling the closing `message`, `details.refusals` only on a list throw, a listed reason judged under every code, `{ message }` as the reason value. Small calls made here (no card): - The list form is shown inline in a bullet, not as a second throw in the example, to fit the byte budget. The assignment form (`e.reasons = [...]; throw e`) is not taught; the object-literal throw is the one the page already uses. - The three list faults are written as run-time `500`s: the source detects them in the runner, not at save. - actions.md describes `userMessage`, not how the console toast renders its newlines, which was not traced. The console's param-dialog listing of reasons (#37538) is not taught here. ## Why PR #37395 (#36877) let one throw carry several declared reasons. Its `Skills-docs:` line points here: both pages taught the single `reason` form only, so an agent writing a hook or action that refuses a selection for several reasons had no pointer to the list. ## Verification Run at `19b5b425d` (contract-review fixes; `f0fd20d1e` before), each exit 0: - `node scripts/check-skills-token-ratchet.mjs`: both files within their ceilings (data-hooks.md 10122/10122, actions.md 3880/3880). - `node scripts/check-skill-links.mjs`, `node scripts/check-skill-identifier-liveness.mjs`, `node scripts/check-skill-top-level-keys.mjs`. - `pnpm --filter @objectstack/spec check:skill-refs`, `check:skill-docs`. - `pnpm --filter @objectstack/spec check:skill-examples` (after building spec, client and client-react): 352 prose examples type-check, the edited `os:check` blocks included. - `node scripts/pm/overlap-check.mjs`: clean. The edits were drafted by a contract-tier subagent, as `dispatch-gates --tier` requires for `skills/**`, and reviewed here (one claim narrowed). The contract-review fixes (S1, N1, N3 of 7197638051) were drafted the same way; the extra bytes in actions.md are paid by wording-only tightenings in the same file. Contract review (L2) is owed before landing: `skills/**` is a governed surface (Tier H). ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes. - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: its generated artifacts are regenerated and committed (not touched). - [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. - [x] The *Before Submitting* list in CONTRIBUTING.md is done. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01L6bhgUpnvPnJ1hR74pUrVj --- _Generated by [Claude Code](https://claude.ai/code/session_01L6bhgUpnvPnJ1hR74pUrVj)_ <!-- signed: repo:objectstack#2 · os-sales · session_01L6bhgUpnvPnJ1hR74pUrVj --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 68aa1be commit 6592546

3 files changed

Lines changed: 68 additions & 71 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): data hooks and actions teach the multi-reason refusal throw
6+
7+
Clause-②: no (published prose only; teaches the list throw already on main)
8+
Metadata-protocol: none
9+
10+
`skills/objectstack-data/references/data-hooks.md` (Declared refusals) now teaches the list form beside the single `reason`: throw `reasons: [{ reason, params? }, …]`; each line is translated and filled from its own `params`; `userMessage` joins the lines and closes with the entry's `message`, filled from the throw's top-level `params` (else its holes render empty); the HTTP doors answer `details.refusals`. It says how an entry declares `reasons` (a snake_case reason to `{ message }` only; another status needs another code), that every listed reason must be declared (refused at save when literal, a `500` at run), and that a `reasons` that is not a non-empty list of `{ reason, params? }`, or one beside `reason`, is a `500`. `skills/objectstack-ui/rules/actions.md` (Refusing by code) shows an action's body the same list shape, `reasons: [{ reason, params? }, …]` instead of `reason`, closed by the code's `message`, and points at the hook section for the rules. Both files sat at zero token headroom, so the words are paid for by tightening prose in the same file; no fact is removed (one redundant `condition` example and a sample field go).

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

Lines changed: 38 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -17,13 +17,11 @@ data hooks.
1717

1818
### What Are Hooks?
1919

20-
Hooks are **event handlers** that execute during the ObjectQL data access lifecycle.
21-
They intercept operations at specific points (before/after) — see [Before vs After](#before-vs-after-hooks).
20+
Hooks are **event handlers** in the ObjectQL data access lifecycle, run before or
21+
after an operation — see [Before vs After](#before-vs-after-hooks).
2222

2323
### Hook Lifecycle Events
2424

25-
ObjectStack provides lifecycle events organized by operation type:
26-
2725
| Event | When It Fires | Use Cases |
2826
|:------|:--------------|:----------|
2927
| **Read Operations** | | |
@@ -66,12 +64,11 @@ ObjectStack provides lifecycle events organized by operation type:
6664

6765
## Hook Definition Schema
6866

69-
Every hook must conform to the `HookSchema`. Author it with `defineHook()` —
70-
preferred over a bare `: Hook` literal (the same rule as `defineDatasource`):
71-
it validates when the module is imported, so constraint-level mistakes a bare
72-
annotation can't catch — a non-`snake_case` `name`, a misspelled key routed
73-
through a spread — fail while you author instead of at deploy, and the export
74-
carries defaults already materialized.
67+
Every hook must conform to `HookSchema`. Author it with `defineHook()`, not a
68+
bare `: Hook` literal (the same rule as `defineDatasource`): it validates when the
69+
module is imported, so constraint-level mistakes an annotation can't catch — a
70+
non-`snake_case` `name`, a misspelled key routed through a spread — fail while you
71+
author, not at deploy, and the export carries defaults already materialized.
7572

7673
<!-- os:check -->
7774
```typescript
@@ -125,20 +122,15 @@ const myHook = defineHook({
125122

126123
#### `condition` — Declarative Filtering
127124

128-
Skip the hook if the condition is false. Author it as a **CEL
125+
Skips the hook when false. Author it as a **CEL
129126
predicate** over `record` and `previous` (use `P\`...\`` from
130127
`@objectstack/spec`; SQL-style `=` / `AND` / `IN (...)` is not CEL):
131128

132129
```typescript
133-
// Only run for high-value accounts
134130
condition: P`record.annual_revenue != null && record.annual_revenue > 1000000`
135131

136-
// Only run for specific statuses
137132
condition: P`record.status in ['pending', 'in_review']`
138133

139-
// Complex conditions
140-
condition: P`record.type == 'enterprise' && record.region == 'APAC' && record.is_active == true`
141-
142134
// A TRANSITION — fires only on the update that completes the task,
143135
// not on later updates of an already-done record
144136
condition: P`previous.done != true && record.done == true`
@@ -180,8 +172,8 @@ in neither). So:
180172
- **Guard optional values with `!= null`, never with `has(...)`.** A declared
181173
field holding `null` is *present*, so `has(record.spent)` is uniformly true and
182174
`has(record.spent) && record.spent > record.budget` still faults on
183-
`null > null`. `has()` answers "is this key declared at all", which is a
184-
question about your spelling, not about your data.
175+
`null > null`. `has()` asks whether the key is declared at all: your
176+
spelling, not your data.
185177

186178
⚠️ **An unevaluable condition ABORTS the operation.** A typo'd key
187179
(`record.stauts`), a column read off `previous` on an insert, or a comparison
@@ -280,15 +272,12 @@ await ctx.api.object('task').find({ where: { $and: [{ done: false }, { owner_id:
280272
281273
> `filter:` is tolerated as an **object-valued** alias (normalised to `where`),
282274
> but prefer `where`. Do **not** pass an array-of-triples such as
283-
> `[['id', '=', x]]` — that is not a supported value shape and silently matches
284-
> nothing.
275+
> `[['id', '=', x]]` — an unsupported shape that silently matches nothing.
285276
286-
**`findOne` must say which record it wants.** It reads a single row, so an
287-
absent or empty predicate does not come back as `null` — it comes back as the
288-
object's **first row**: a real, plausible-looking record with nothing to do with
289-
what you asked for, which your `if (!row)` cannot catch. So `findOne()`,
290-
`findOne({})` and `findOne({ where: {} })` **throw**. Be specific in one
291-
of three ways:
277+
**`findOne` must say which record it wants.** An absent or empty
278+
predicate would return not `null` but the object's **first row**, an unrelated
279+
record your `if (!row)` cannot catch. So `findOne()`, `findOne({})`
280+
and `findOne({ where: {} })` **throw**. Be specific in one of three ways:
292281
293282
```js
294283
await ctx.api.object('candidate').findOne({ where: { id } }); // by predicate
@@ -298,15 +287,14 @@ await ctx.api.object('audit')
298287
await ctx.api.object('candidate').find({ limit: 1 }); // any row will do
299288
```
300289

301-
An unpredicated `find` / `count` is fine — returning or counting every row is an
302-
honest answer.
290+
An unpredicated `find` / `count` is fine: every row is an honest answer.
303291

304292
### Capabilities — the complete list
305293

306294
A body may only touch a `ctx` API it declared in `capabilities`. Calling an
307295
undeclared one **throws inside the VM** — `capability '<token>' not granted to
308-
hook '<name>' …` — which surfaces as a hook error (see Troubleshooting). The full
309-
set of legal tokens (`HookBodyCapability`) is exactly seven:
296+
hook '<name>' …` — which surfaces as a hook error (see Troubleshooting). The legal
297+
tokens (`HookBodyCapability`) are exactly seven:
310298

311299
| Token | Unlocks |
312300
|:--|:--|
@@ -424,17 +412,14 @@ export default fillPositionOnHire;
424412
`log` capability the call **throws** (surfaces as a hook error); (2) **with** the
425413
capability it emits only when the runtime wired a logger into the hook context —
426414
otherwise it is a **silent no-op**. Treat `ctx.log` as best-effort diagnostics,
427-
not a reliable side-channel or proof a hook ran; to observe an effect, assert on
428-
the data it writes.
415+
never proof a hook ran; to observe an effect, assert on the data it writes.
429416

430417
---
431418

432419
## Hook Context API
433420

434-
> The `ctx` below is the deprecated in-process `handler`'s; a `body` sees the
435-
> [sandbox subset](#what-lives-on-the-sandbox-ctx).
436-
437-
The engine's `HookContext` provides:
421+
> The `ctx` below, the engine's `HookContext`, is the deprecated in-process
422+
> `handler`'s; a `body` sees the [sandbox subset](#what-lives-on-the-sandbox-ctx).
438423
439424
### Context Properties
440425

@@ -504,7 +489,7 @@ const org = ctx.user?.organizationId ?? ctx.session?.organizationId;
504489
505490
### `input` — Operation Parameters
506491

507-
The structure of `ctx.input` varies by event:
492+
`ctx.input` varies by event:
508493

509494
**Insert operations:**
510495
```typescript
@@ -513,7 +498,6 @@ The structure of `ctx.input` varies by event:
513498
// All field values being inserted
514499
name: 'Acme Corp',
515500
industry: 'Technology',
516-
annual_revenue: 5000000,
517501
...
518502
}
519503
```
@@ -770,7 +754,6 @@ ctx.ql.registerHook('beforeInsert', async (hookCtx) => { /* ... */ },
770754
file, default-exported, then listed in the stack's `hooks` array (method 1). This is
771755
the layout both real hook modules in the repo use.
772756

773-
774757
---
775758

776759
## Best Practices
@@ -791,7 +774,6 @@ hook (its `ctx.api` writes roll back with the write) or record it in the caller,
791774
where the write is made; assume `ctx.session` exists — system operations carry
792775
no user.
793776

794-
795777
---
796778

797779
## Error Handling
@@ -802,10 +784,9 @@ A throw aborts the operation and rolls back its transaction; `onError: 'log'`
802784
### Declared refusals (`refusals`)
803785

804786
A hook that enforces a business rule declares a `refusals` catalogue, one
805-
SCREAMING_SNAKE code per rule, and the hook throws the code. Without one, a `body`'s
806-
throw is answered `HOOK_ABORTED`, the platform's code: fine for a failure you did not
807-
plan, not for a rule the user can act on. A cross-object guard a validation rule
808-
cannot read:
787+
SCREAMING_SNAKE code per rule, and throws the code. Without one, a `body`'s
788+
throw is answered `HOOK_ABORTED`, the platform's code: fine for an unplanned failure, not
789+
for a rule the user can act on. A cross-object guard a validation rule cannot read:
809790

810791
<!-- os:check -->
811792
```typescript
@@ -840,15 +821,21 @@ export default defineHook({
840821
- A `js` `body` or a `handler` (inline or named) can declare one; an
841822
`expression` body, or neither, is refused at save.
842823
- The wire `code` is the status's (default 400), with the hook's as `declaredCode`.
843-
- `reasons` (snake_case, thrown as `reason`) add sentences that keep the code's wire
844-
`code` and status.
845-
- `params` names what a `{{ name }}` hole may fill (thrown as `params`); a hole
846-
over any other name, or any hole with no `params`, is refused.
824+
- `reasons` maps a snake_case reason (thrown as `reason`) to `{ message }` only: a
825+
sentence under the code's wire `code` and status; another status needs another code.
826+
- `params` names what a `{{ name }}` hole, a reason's too, may fill (thrown as
827+
`params`); a hole over any other name, or any hole with no `params`, is refused.
828+
- For several reasons throw `reasons: [{ reason: 'on_loan', params: { due } }, …]`, not
829+
`reason`: one translated line each, filled from its own `params`. `userMessage` joins
830+
them by newlines and ends with the entry's `message`, filled from the throw's
831+
top-level `params` (else its holes are empty); the HTTP doors answer
832+
`details.refusals: [{ reason, message }]`, absent for a single `reason`.
847833
- Translated via `hooks.<hook>.refusals.<CODE>.message` (or
848834
`….<CODE>.reasons.<REASON>.message`); the thrown text and `status` are unused.
849-
- An undeclared code (or none), or a reason missing from a code's `reasons`, is
850-
refused: at save if thrown literally, else as a `500`. Unchanged `ctx.api`
851-
errors and crashes pass through.
835+
- An undeclared code (or none), or a reason missing from a code's `reasons` (a listed
836+
one even when the code declares none), is refused: at save if thrown literally, else
837+
as a `500`. A `reasons` not a non-empty list of `{ reason, params? }`, or beside
838+
`reason`, is a `500`. Unchanged `ctx.api` errors and crashes pass through.
852839

853840
### Declared texts (`texts`)
854841

0 commit comments

Comments
 (0)