From f8a88d3462ab88094a6223cf5f02a889cc26c3b3 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 11:43:42 +0000 Subject: [PATCH 1/8] feat(spec): offer the hook texts row in the Studio hook form The hook form gains a key-only record row for HookSchema.texts beside refusals, with message and params, and the reconciliation ledger drops its hook/texts omit row. Claude-Session: https://claude.ai/code/session_01L6bhgX6mQpVU8yUysiRAFC Co-authored-by: Claude --- packages/spec/src/data/hook.form.ts | 19 +++++++++++++++++-- .../metadata-form-zod-reconciliation.test.ts | 11 ----------- 2 files changed, 17 insertions(+), 13 deletions(-) diff --git a/packages/spec/src/data/hook.form.ts b/packages/spec/src/data/hook.form.ts index 6d2932ce0cf..3b839a76f5c 100644 --- a/packages/spec/src/data/hook.form.ts +++ b/packages/spec/src/data/hook.form.ts @@ -8,8 +8,9 @@ import { defineForm } from '../ui/view.zod'; * Hooks intercept the data lifecycle. The body field is a composite * (`{ language, source, capabilities?, timeoutMs?, memoryMb? }`) whose * `source` renders in a Monaco code editor with language-appropriate - * syntax highlighting. The hook's refusal catalogue (`refusals`) sits beside it: - * a js body or a handler may declare one, an expression body may not. + * syntax highlighting. The hook's refusal catalogue (`refusals`) and its + * declared texts (`texts`) sit beside it: a js body or a handler may declare + * them, an expression body may not. */ export const hookForm = defineForm({ schemaId: 'hook', @@ -73,6 +74,20 @@ export const hookForm = defineForm({ { field: 'params', type: 'tags', helpText: 'Names the sentences may fill (e.g. state): the body throws { code, params: { state } }, and a {{ state }} hole renders it. Absent: the sentences are plain text' }, ], }, + // The declared texts are the same record shape as the refusal + // catalogue — keyed by the snake_case key the code asks for, an entry + // `{ message, params? }` with no member that echoes its key — so the + // row takes the same key-only record control. + { + field: 'texts', + type: 'record', + widget: 'key-only-record', + helpText: "Sentences the hook writes into records, keyed by the snake_case key its code asks for with ctx.text (e.g. follow_up_subject). The hook gets the declared message in the organization's language, translated, with the declared message as the fallback. For a JavaScript (L2) body or a handler; refused on an expression body", + fields: [ + { field: 'message', type: 'textarea', required: true, helpText: 'The sentence the hook writes when its code asks for this key. Plain text, unless the entry declares params: then a {{ name }} hole fills a declared param' }, + { field: 'params', type: 'tags', helpText: 'Names the sentence may fill (e.g. lead): the code asks for ctx.text(key, { lead }), and a {{ lead }} hole renders it. Absent: the sentence is plain text' }, + ], + }, ], }, { diff --git a/packages/spec/src/system/metadata-form-zod-reconciliation.test.ts b/packages/spec/src/system/metadata-form-zod-reconciliation.test.ts index 02bd67dffc3..88456f34fd4 100644 --- a/packages/spec/src/system/metadata-form-zod-reconciliation.test.ts +++ b/packages/spec/src/system/metadata-form-zod-reconciliation.test.ts @@ -464,17 +464,6 @@ const LEDGER: ReadonlyArray = [ key: 'homeAmount', why: "planned, not yet written — the `{ field, rateDate, rateField }` pointers are validated at parse (all three required, each judged against the object's field map), but no engine converts the amount or stores the home amount and the rate until the write-time home-currency projection lands, which ADR-0144 D9 releases with this key. A form control offered today would let an author declare a home amount nothing writes", }, - // #34374 — a hook's declared texts land in the hook's source first. The - // Studio row (a key-only record beside `refusals`, with its help text in - // the eleven metadata-forms bundles) is a follow-up, so this row records - // why the key is not offered yet. - { - kind: 'omit', - type: 'hook', - path: ROOT_PATH, - key: 'texts', - why: "live, not yet offered in the Studio — the sentences a hook writes into records (`ctx.text`, answered in the organization's language) are validated at parse (snake_case keys, closed-scope holes over declared `params`, a literal `ctx.text` key the hook does not declare refused at save) and read at run time, and they are declared in the hook's package source beside the code that asks for them. The Studio row, a key-only record beside `refusals`, needs its labels and help text translated in the eleven metadata-forms bundles and is owed to a follow-up card; until then a hook authored in the Studio declares `texts` through the metadata API or its package source", - }, // #34273 — an action's refusal catalogue lands in the action's source // first, as a hook's declared texts did (#34374). The Studio row (a // key-only record, with its help text in the eleven metadata-forms From 0cfc18e8d216fd244f769c1175f82f325c28b593 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 11:47:47 +0000 Subject: [PATCH 2/8] feat(spec): HookContext declares ctx.text A typed hook handler can call ctx.text(key, params) against HookContext: the member is declared the way api and notice are (z.unknown at parse, a static cast for the type), with the signature the runtime binds, and the named HookTextReader type beside HookNoticeSetter. Claude-Session: https://claude.ai/code/session_01L6bhgX6mQpVU8yUysiRAFC Co-authored-by: Claude --- .../spec/src/data/hook-context-text.test.ts | 78 +++++++++++++++++++ packages/spec/src/data/hook.zod.ts | 34 ++++++++ 2 files changed, 112 insertions(+) create mode 100644 packages/spec/src/data/hook-context-text.test.ts diff --git a/packages/spec/src/data/hook-context-text.test.ts b/packages/spec/src/data/hook-context-text.test.ts new file mode 100644 index 00000000000..2fe4f41bc96 --- /dev/null +++ b/packages/spec/src/data/hook-context-text.test.ts @@ -0,0 +1,78 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#35197] `HookContext.text` — the published type of the `ctx.text(key, + * params?)` call a hook asks for one of its declared `texts` with. + * + * The runtime binds it on every path a hook runs on + * (`packages/runtime/src/sandbox/hook-text.ts`, `HookTextSurface`), so a typed + * handler must be able to call it against `HookContext` without a local type. + * Pinned from both sides: + * + * 1. the type: `HookContext['text']` is exactly an optional + * `(key: string, params?: Record) => Promise`, + * the signature the runtime injects, and a wrong call shape is a type + * error. The `@ts-expect-error` lines are real checks: `tsconfig.test.json` + * compiles this layer (`pnpm --filter @objectstack/spec check:test-typecheck`). + * 2. the parse: `HookContextSchema` (deliberately non-strict, which strips a + * key it does not declare) keeps the bound function. + */ + +import { describe, expect, it } from 'vitest'; + +import { HookContextSchema, type HookContext, type HookTextReader } from './hook.zod'; + +/** `true` only when every `A` is a usable `B`. */ +type Assignable = [A] extends [B] ? true : false; + +type RuntimeTextSurface = (key: string, params?: Record) => Promise; + +describe('HookContext.text — the declared-text call a typed handler makes', () => { + it('declares the signature the runtime injects, optional like api and notice', () => { + const declaredIsRuntime: Assignable, RuntimeTextSurface> = true; + const runtimeIsDeclared: Assignable> = true; + const namedIsMember: Assignable> = true; + const optional: Assignable = true; + expect([declaredIsRuntime, runtimeIsDeclared, namedIsMember, optional]).toEqual([true, true, true, true]); + }); + + it('a typed handler calls it with a key and params and gets a string', async () => { + const asked: Array<[string, Record | undefined]> = []; + const handler = async (ctx: HookContext): Promise => { + const lead = 'Ada'; + return (await ctx.text?.('follow_up_subject', { lead })) ?? ''; + }; + const ctx: HookContext = { + object: 'crm_lead', + event: 'afterInsert', + input: {}, + text: async (key, params) => { + asked.push([key, params]); + return `Follow up with qualified lead: ${String(params?.lead)}`; + }, + }; + await expect(handler(ctx)).resolves.toBe('Follow up with qualified lead: Ada'); + expect(asked).toEqual([['follow_up_subject', { lead: 'Ada' }]]); + }); + + it('a wrong call shape is a type error', () => { + const text: HookTextReader = async (key) => key; + // @ts-expect-error the key is the snake_case string a hook declares, never a number + void text(42); + // @ts-expect-error params is a name → value record, never a positional list + void text('follow_up_subject', ['Ada']); + const answer = async (): Promise => { + // @ts-expect-error the call resolves to the sentence, a string + const n: number = await text('follow_up_subject'); + void n; + }; + expect(typeof answer).toBe('function'); + }); + + it('the parse keeps the bound function instead of stripping it', () => { + const text: HookTextReader = async () => 'sentence'; + const parsed = HookContextSchema.parse({ object: 'crm_lead', event: 'afterInsert', input: {}, text }); + expect(parsed.text).toBe(text); + expect('text' in HookContextSchema.parse({ object: 'crm_lead', event: 'afterInsert', input: {} })).toBe(false); + }); +}); diff --git a/packages/spec/src/data/hook.zod.ts b/packages/spec/src/data/hook.zod.ts index f8275109575..49b2f0174c7 100644 --- a/packages/spec/src/data/hook.zod.ts +++ b/packages/spec/src/data/hook.zod.ts @@ -1927,6 +1927,34 @@ export const HookContextSchema = lazySchema(() => z.object({ + 'by the engine on every insert/update dispatch (a no-op when nothing listens); absent on find/delete', ), + /** + * Declared Text (#34374, ruling 6913660232 parameter 7) + * + * `await ctx.text('follow_up_subject', { lead })` answers one of the hook's + * declared `texts` (see `HookSchema.texts`) in the ORGANIZATION's language, + * translated through `hooks..texts..message`, the declared + * `message` as the fallback, its `{{ }}` holes filled from `params`. A key + * the hook does not declare rejects the call, and so does a Localization + * setting that cannot be read. + * + * The runtime binds it on every path a hook runs on — a sandboxed `js` body + * and an in-process `handler` (`buildHookTextSurface`). The save-time check + * reads the literal spelling `ctx.text('key'`, so a key asked for through + * an alias or a computed name is only judged when the hook runs. + * + * Runtime-only, like {@link api} and {@link notice}: a live function, so the + * RUNTIME schema is `z.unknown()` (JSON Schema `{}`) and the type is a static + * cast. Optional for the same reason they are: a context parsed without the + * runtime carries none. + */ + text: (z.unknown().optional() as unknown as z.ZodOptional>) + .describe( + 'Answer one of the hook\'s declared texts: `await ctx.text(KEY, params?)` returns the sentence in the ' + + 'organization\'s language (translated through hooks..texts..message, the declared message as the ' + + 'fallback, holes filled from params). Bound by the runtime on every path a hook runs on; a key the hook does ' + + 'not declare rejects the call', + ), + /** * Current User Info * Convenience shortcut for session.userId + additional user metadata. @@ -1963,6 +1991,12 @@ export type HookEventType = z.input; * a non-empty string. */ export type HookNoticeSetter = (message: string) => void; +/** + * The function a hook calls as `ctx.text(key, params?)` (#34374) — see + * `HookContext.text` and `HookSchema.texts`. Resolves to the declared sentence + * in the organization's language; rejects a key the hook does not declare. + */ +export type HookTextReader = (key: string, params?: Record) => Promise; export type HookContext = z.input; /** * The engine's dispatch marker (#6966) — see `HookContext.dispatch`. Named so From 0d0744ce1e8b49633d76d2f70b9ddf6d7353d686 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 11:55:12 +0000 Subject: [PATCH 3/8] feat(platform-objects): the hook texts row in the eleven metadata-forms packs en regenerated from the form source; the ten translated packs carry hand-written translations following each pack's refusals wording. Claude-Session: https://claude.ai/code/session_01L6bhgX6mQpVU8yUysiRAFC Co-authored-by: Claude --- .../apps/translations/ar.metadata-forms.generated.ts | 12 ++++++++++++ .../apps/translations/de.metadata-forms.generated.ts | 12 ++++++++++++ .../apps/translations/en.metadata-forms.generated.ts | 12 ++++++++++++ .../translations/es-ES.metadata-forms.generated.ts | 12 ++++++++++++ .../apps/translations/fr.metadata-forms.generated.ts | 12 ++++++++++++ .../apps/translations/fr.source-hashes.generated.ts | 1 + .../translations/ja-JP.metadata-forms.generated.ts | 12 ++++++++++++ .../apps/translations/ko.metadata-forms.generated.ts | 12 ++++++++++++ .../translations/pt-BR.metadata-forms.generated.ts | 12 ++++++++++++ .../apps/translations/ru.metadata-forms.generated.ts | 12 ++++++++++++ .../translations/zh-CN.metadata-forms.generated.ts | 12 ++++++++++++ .../translations/zh-Hant.metadata-forms.generated.ts | 12 ++++++++++++ 12 files changed, 133 insertions(+) diff --git a/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts index 63f7f7fb176..16f18cf9f14 100644 --- a/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts @@ -989,6 +989,18 @@ export const arMetadataForms: NonNullable = { label: "المعاملات", helpText: "الأسماء التي يمكن للجمل ملؤها (مثل state): يرمي المتن { code, params: { state } } ويعرض العنصر النائب {{ state }} قيمتها. عند الغياب: الجمل نص عادي" }, + texts: { + label: "النصوص", + helpText: "الجمل التي يكتبها الخطاف في السجلات، مفهرسة بالمفتاح بصيغة snake_case الذي تطلبه شيفرته عبر ctx.text (مثل follow_up_subject). يتلقى الخطاف الرسالة المُعلنة بلغة المؤسسة، مترجمة، مع الرسالة المُعلنة بديلًا عند غياب الترجمة. لمتن JavaScript ‏(L2) أو معالج؛ ويُرفض في متن التعبير" + }, + "texts.message": { + label: "الرسالة", + helpText: "الجملة التي يكتبها الخطاف عندما تطلب شيفرته هذا المفتاح. نص عادي، ما لم يُعلن الإدخال params: عندها يملأ العنصر النائب {{ name }} معاملًا مُعلنًا" + }, + "texts.params": { + label: "المعاملات", + helpText: "الأسماء التي يمكن للجملة ملؤها (مثل lead): تطلب الشيفرة ctx.text(key, { lead }) ويعرض العنصر النائب {{ lead }} قيمتها. عند الغياب: الجملة نص عادي" + }, handler: { label: "المعالج", helpText: "اسم دالة المعالج (مُهمَل — يُفضَّل `body`)" diff --git a/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts index 8fc7676271b..720eb0354bf 100644 --- a/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts @@ -989,6 +989,18 @@ export const deMetadataForms: NonNullable = { label: "Parameter", helpText: "Namen, die die Sätze füllen dürfen (z. B. state): Der Rumpf wirft { code, params: { state } }, und ein Platzhalter {{ state }} zeigt den Wert. Fehlt er: Die Sätze sind einfacher Text" }, + texts: { + label: "Texte", + helpText: "Sätze, die der Hook in Datensätze schreibt, nach dem snake_case-Schlüssel, den sein Code mit ctx.text anfragt (z. B. follow_up_subject). Der Hook erhält die deklarierte Meldung in der Sprache der Organisation, übersetzt, mit der deklarierten Meldung als Rückfall. Für einen JavaScript-Rumpf (L2) oder einen Handler; bei einem Ausdrucksrumpf abgelehnt" + }, + "texts.message": { + label: "Meldung", + helpText: "Der Satz, den der Hook schreibt, wenn sein Code diesen Schlüssel anfragt. Einfacher Text, außer der Eintrag deklariert params: dann füllt ein Platzhalter {{ name }} einen deklarierten Parameter" + }, + "texts.params": { + label: "Parameter", + helpText: "Namen, die der Satz füllen darf (z. B. lead): Der Code fragt ctx.text(key, { lead }) an, und ein Platzhalter {{ lead }} zeigt den Wert. Fehlt er: Der Satz ist einfacher Text" + }, handler: { label: "Handler", helpText: "Name der Handler-Funktion (veraltet – besser `body`)" diff --git a/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts index 328473cddb0..c4e81aac640 100644 --- a/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts @@ -989,6 +989,18 @@ export const enMetadataForms: NonNullable = { label: "Params", helpText: "Names the sentences may fill (e.g. state): the body throws { code, params: { state } }, and a {{ state }} hole renders it. Absent: the sentences are plain text" }, + texts: { + label: "Texts", + helpText: "Sentences the hook writes into records, keyed by the snake_case key its code asks for with ctx.text (e.g. follow_up_subject). The hook gets the declared message in the organization's language, translated, with the declared message as the fallback. For a JavaScript (L2) body or a handler; refused on an expression body" + }, + "texts.message": { + label: "Message", + helpText: "The sentence the hook writes when its code asks for this key. Plain text, unless the entry declares params: then a {{ name }} hole fills a declared param" + }, + "texts.params": { + label: "Params", + helpText: "Names the sentence may fill (e.g. lead): the code asks for ctx.text(key, { lead }), and a {{ lead }} hole renders it. Absent: the sentence is plain text" + }, handler: { label: "Handler", helpText: "Handler function name (deprecated — prefer `body`)" diff --git a/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts index 8109d542dc4..0666f3ea388 100644 --- a/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts @@ -989,6 +989,18 @@ export const esESMetadataForms: NonNullable = label: "Parámetros", helpText: "Nombres que las frases pueden rellenar (p. ej. state): el cuerpo lanza { code, params: { state } } y un marcador {{ state }} muestra su valor. Si se omite: las frases son texto plano" }, + texts: { + label: "Textos", + helpText: "Frases que el gancho escribe en los registros, indexadas por la clave snake_case que su código pide con ctx.text (p. ej. follow_up_subject). El gancho recibe el mensaje declarado en el idioma de la organización, traducido, con el mensaje declarado como respaldo. Para un cuerpo JavaScript (L2) o un manejador; se rechaza en un cuerpo de expresión" + }, + "texts.message": { + label: "Mensaje", + helpText: "La frase que escribe el gancho cuando su código pide esta clave. Texto plano, salvo que la entrada declare params: entonces un marcador {{ name }} se rellena con un parámetro declarado" + }, + "texts.params": { + label: "Parámetros", + helpText: "Nombres que la frase puede rellenar (p. ej. lead): el código pide ctx.text(key, { lead }) y un marcador {{ lead }} muestra su valor. Si se omite: la frase es texto plano" + }, handler: { label: "Manejador", helpText: "Nombre de función manejadora (obsoleto — preferir `body`)" diff --git a/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts index 338d452a1af..2e47bd7c82d 100644 --- a/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts @@ -989,6 +989,18 @@ export const frMetadataForms: NonNullable = { label: "Paramètres", helpText: "Les noms que les phrases peuvent remplir (par ex. state) : le corps lève { code, params: { state } }, et un espace réservé {{ state }} en affiche la valeur. Absent : les phrases sont du texte brut" }, + texts: { + label: "Textes", + helpText: "Les phrases que le hook écrit dans les enregistrements, indexées par la clé snake_case que son code demande avec ctx.text (par ex. follow_up_subject). Le hook reçoit le message déclaré dans la langue de l’organisation, traduit, avec le message déclaré comme repli. Pour un corps JavaScript (L2) ou un gestionnaire ; refusé sur un corps expression" + }, + "texts.message": { + label: "Message", + helpText: "La phrase que le hook écrit lorsque son code demande cette clé. Texte brut, sauf si l’entrée déclare des params : un espace réservé {{ name }} reçoit alors un paramètre déclaré" + }, + "texts.params": { + label: "Paramètres", + helpText: "Les noms que la phrase peut remplir (par ex. lead) : le code demande ctx.text(key, { lead }), et un espace réservé {{ lead }} en affiche la valeur. Absent : la phrase est du texte brut" + }, handler: { label: "Gestionnaire", helpText: "Nom de la fonction de gestion (obsolète — préférez `body`)" diff --git a/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts index 052e7f2ba4d..88c0f192be0 100644 --- a/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts @@ -66,6 +66,7 @@ export const frGeneratedSourceHashes: Readonly> = { "metadataForms.hook.fields.description.label": "779a4342c8eb6707", "metadataForms.hook.fields.refusals.message.label": "2af15199795c25b9", "metadataForms.hook.fields.refusals.reasons.message.label": "2af15199795c25b9", + "metadataForms.hook.fields.texts.message.label": "2af15199795c25b9", "metadataForms.hook.label": "248bb1cdc692252d", "metadataForms.object.fields.description.label": "779a4342c8eb6707", "metadataForms.object.fields.fields.description.label": "779a4342c8eb6707", diff --git a/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts index 3f6cd992f09..63371ee0c03 100644 --- a/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts @@ -989,6 +989,18 @@ export const jaJPMetadataForms: NonNullable = label: "パラメーター", helpText: "文に埋め込める名前(例: state)。本体が { code, params: { state } } をスローすると、{{ state }} プレースホルダーにその値が表示されます。未指定: 文はプレーンテキストです" }, + texts: { + label: "テキスト", + helpText: "フックがレコードに書き込む文。コードが ctx.text で要求する snake_case のキー(例: follow_up_subject)をキーとします。フックには宣言したメッセージが組織の言語に翻訳されて返り、翻訳がない場合は宣言したメッセージが返ります。JavaScript(L2)本体またはハンドラーで使用可能。expression 本体では拒否されます" + }, + "texts.message": { + label: "メッセージ", + helpText: "コードがこのキーを要求したときにフックが書き込む文。プレーンテキスト。ただしエントリが params を宣言している場合、{{ name }} プレースホルダーに宣言済みのパラメーターが入ります" + }, + "texts.params": { + label: "パラメーター", + helpText: "文に埋め込める名前(例: lead)。コードが ctx.text(key, { lead }) を要求すると、{{ lead }} プレースホルダーにその値が表示されます。未指定: 文はプレーンテキストです" + }, handler: { label: "ハンドラー", helpText: "ハンドラー関数名(非推奨 — `body` を推奨)" diff --git a/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts index 83b6a3e1992..119caa20a0b 100644 --- a/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts @@ -989,6 +989,18 @@ export const koMetadataForms: NonNullable = { label: "매개변수", helpText: "문장에 채울 수 있는 이름(예: state)입니다. 본문이 { code, params: { state } }를 던지면 {{ state }} 자리 표시자에 그 값이 표시됩니다. 없으면 문장은 일반 텍스트입니다" }, + texts: { + label: "텍스트", + helpText: "훅이 레코드에 쓰는 문장으로, 코드가 ctx.text로 요청하는 snake_case 키(예: follow_up_subject)를 키로 합니다. 훅은 선언된 메시지를 조직의 언어로 번역해 받으며, 번역이 없으면 선언된 메시지를 받습니다. JavaScript(L2) 본문 또는 핸들러용이며, expression 본문에서는 거부됩니다" + }, + "texts.message": { + label: "메시지", + helpText: "코드가 이 키를 요청할 때 훅이 쓰는 문장입니다. 일반 텍스트이며, 항목이 params를 선언하면 {{ name }} 자리 표시자에 선언된 매개변수가 채워집니다" + }, + "texts.params": { + label: "매개변수", + helpText: "문장에 채울 수 있는 이름(예: lead)입니다. 코드가 ctx.text(key, { lead })를 요청하면 {{ lead }} 자리 표시자에 그 값이 표시됩니다. 없으면 문장은 일반 텍스트입니다" + }, handler: { label: "핸들러", helpText: "핸들러 함수 이름(사용 중단, `body` 권장)" diff --git a/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts index 364cb7ba667..dea2e09a05d 100644 --- a/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts @@ -989,6 +989,18 @@ export const ptBRMetadataForms: NonNullable = label: "Parâmetros", helpText: "Nomes que as frases podem preencher (por exemplo state): o corpo lança { code, params: { state } } e um marcador {{ state }} mostra o valor. Ausente: as frases são texto simples" }, + texts: { + label: "Textos", + helpText: "Frases que o hook escreve nos registros, indexadas pela chave snake_case que o código dele pede com ctx.text (por exemplo follow_up_subject). O hook recebe a mensagem declarada no idioma da organização, traduzida, com a mensagem declarada como alternativa. Para um corpo JavaScript (L2) ou um handler; recusado em um corpo de expressão" + }, + "texts.message": { + label: "Mensagem", + helpText: "A frase que o hook escreve quando o código dele pede esta chave. Texto simples, a menos que a entrada declare params: então um marcador {{ name }} é preenchido com um parâmetro declarado" + }, + "texts.params": { + label: "Parâmetros", + helpText: "Nomes que a frase pode preencher (por exemplo lead): o código pede ctx.text(key, { lead }) e um marcador {{ lead }} mostra o valor. Ausente: a frase é texto simples" + }, handler: { label: "Handler", helpText: "Nome da função handler (obsoleto — prefira `body`)" diff --git a/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts index ef3ff534857..0397923e065 100644 --- a/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts @@ -989,6 +989,18 @@ export const ruMetadataForms: NonNullable = { label: "Параметры", helpText: "Имена, которые могут заполнять фразы (например, state): тело выбрасывает { code, params: { state } }, и заполнитель {{ state }} показывает значение. Если отсутствует: фразы — простой текст" }, + texts: { + label: "Тексты", + helpText: "Фразы, которые хук записывает в записи, с ключами в snake_case, которые его код запрашивает через ctx.text (например, follow_up_subject). Хук получает объявленное сообщение в переводе на язык организации, а без перевода — само объявленное сообщение. Для тела JavaScript (L2) или обработчика; для тела-выражения отклоняется" + }, + "texts.message": { + label: "Сообщение", + helpText: "Фраза, которую хук записывает, когда его код запрашивает этот ключ. Простой текст, если запись не объявляет params: тогда заполнитель {{ name }} подставляет объявленный параметр" + }, + "texts.params": { + label: "Параметры", + helpText: "Имена, которые может заполнять фраза (например, lead): код запрашивает ctx.text(key, { lead }), и заполнитель {{ lead }} показывает значение. Если отсутствует: фраза — простой текст" + }, handler: { label: "Обработчик", helpText: "Имя функции-обработчика (устарело — используйте `body`)" diff --git a/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts index 6305508ab42..6e820738da2 100644 --- a/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts @@ -989,6 +989,18 @@ export const zhCNMetadataForms: NonNullable = label: "参数", helpText: "句子可填入的名称(例如 state):正文抛出 { code, params: { state } },{{ state }} 占位符即显示该值。不填:句子为纯文本" }, + texts: { + label: "文本", + helpText: "钩子写入记录的句子,以其代码通过 ctx.text 请求的 snake_case 键为键(例如 follow_up_subject)。钩子得到按组织语言翻译的声明句子,无翻译时回退为声明的句子。适用于 JavaScript(L2)正文或处理器;表达式正文声明会被拒绝" + }, + "texts.message": { + label: "句子", + helpText: "代码请求此键时钩子写入的句子。纯文本;若该条目声明了参数,则 {{ name }} 占位符填入一个已声明的参数" + }, + "texts.params": { + label: "参数", + helpText: "句子可填入的名称(例如 lead):代码请求 ctx.text(key, { lead }),{{ lead }} 占位符即显示该值。不填:句子为纯文本" + }, handler: { label: "处理器", helpText: "处理器函数名(已废弃——建议使用 body)" diff --git a/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts index 8672e220bf2..ad8ce45755d 100644 --- a/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts @@ -989,6 +989,18 @@ export const zhHantMetadataForms: NonNullable label: "參數", helpText: "句子可填入的名稱(例如 state):內文丟擲 { code, params: { state } },{{ state }} 預留位置即顯示該值。不填:句子為純文字" }, + texts: { + label: "文字", + helpText: "掛鉤寫入記錄的句子,以其程式碼透過 ctx.text 請求的 snake_case 鍵為鍵(例如 follow_up_subject)。掛鉤取得依組織語言翻譯的宣告句子,無翻譯時退回宣告的句子。適用於 JavaScript(L2)內文或處理器;運算式內文宣告會被拒絕" + }, + "texts.message": { + label: "句子", + helpText: "程式碼請求此鍵時掛鉤寫入的句子。純文字;若該條目宣告了參數,則 {{ name }} 預留位置填入一個已宣告的參數" + }, + "texts.params": { + label: "參數", + helpText: "句子可填入的名稱(例如 lead):程式碼請求 ctx.text(key, { lead }),{{ lead }} 預留位置即顯示該值。不填:句子為純文字" + }, handler: { label: "處理器", helpText: "處理器函式名(已廢棄——建議使用 body)" From 5fb220661625850ac4a45b2ad0c781a5fa4b6bcf Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 11:57:25 +0000 Subject: [PATCH 4/8] test(spec): a parsed hook context needs its engine reference Claude-Session: https://claude.ai/code/session_01L6bhgX6mQpVU8yUysiRAFC Co-authored-by: Claude --- packages/spec/src/data/hook-context-text.test.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/spec/src/data/hook-context-text.test.ts b/packages/spec/src/data/hook-context-text.test.ts index 2fe4f41bc96..8a55448892d 100644 --- a/packages/spec/src/data/hook-context-text.test.ts +++ b/packages/spec/src/data/hook-context-text.test.ts @@ -71,8 +71,8 @@ describe('HookContext.text — the declared-text call a typed handler makes', () it('the parse keeps the bound function instead of stripping it', () => { const text: HookTextReader = async () => 'sentence'; - const parsed = HookContextSchema.parse({ object: 'crm_lead', event: 'afterInsert', input: {}, text }); - expect(parsed.text).toBe(text); - expect('text' in HookContextSchema.parse({ object: 'crm_lead', event: 'afterInsert', input: {} })).toBe(false); + const bare = { object: 'crm_lead', event: 'afterInsert', input: {}, ql: {} }; + expect(HookContextSchema.parse({ ...bare, text }).text).toBe(text); + expect('text' in HookContextSchema.parse(bare)).toBe(false); }); }); From 13feefb0de0d4524e75cf117155ba325ae685291 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 12:06:04 +0000 Subject: [PATCH 5/8] test(spec): the typed hook context literal carries its engine reference Claude-Session: https://claude.ai/code/session_01L6bhgX6mQpVU8yUysiRAFC Co-authored-by: Claude --- packages/spec/src/data/hook-context-text.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/spec/src/data/hook-context-text.test.ts b/packages/spec/src/data/hook-context-text.test.ts index 8a55448892d..07f5f0b41d1 100644 --- a/packages/spec/src/data/hook-context-text.test.ts +++ b/packages/spec/src/data/hook-context-text.test.ts @@ -46,6 +46,7 @@ describe('HookContext.text — the declared-text call a typed handler makes', () object: 'crm_lead', event: 'afterInsert', input: {}, + ql: {}, text: async (key, params) => { asked.push([key, params]); return `Follow up with qualified lead: ${String(params?.lead)}`; From 772b1c3a07651c131137a4d66d80c304e7c50e11 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 12:06:50 +0000 Subject: [PATCH 6/8] chore(spec): regenerate the artifacts HookContext.text moves, add the changeset Claude-Session: https://claude.ai/code/session_01L6bhgX6mQpVU8yUysiRAFC Co-authored-by: Claude --- .changeset/34575-hook-texts-studio-row.md | 12 ++++++++++++ content/docs/references/data/hook.mdx | 1 + packages/spec/api-surface/data.json | 1 + packages/spec/authorable-surface/data.json | 1 + packages/spec/export-origins/data.json | 1 + 5 files changed, 16 insertions(+) create mode 100644 .changeset/34575-hook-texts-studio-row.md diff --git a/.changeset/34575-hook-texts-studio-row.md b/.changeset/34575-hook-texts-studio-row.md new file mode 100644 index 00000000000..eb656062b83 --- /dev/null +++ b/.changeset/34575-hook-texts-studio-row.md @@ -0,0 +1,12 @@ +--- +'@objectstack/spec': patch +'@objectstack/platform-objects': patch +--- + +feat(spec): the Studio hook form offers a hook's declared `texts`, and `HookContext` declares `ctx.text` + +Clause-②: yes +Metadata-protocol: none + +- **Studio hook form.** `hookForm` gains a `texts` row beside `refusals`: a key-only record keyed by the snake_case key the hook's code asks for with `ctx.text`, each entry editing its `message` and `params`. An author editing a hook in the Studio can now write the `texts` the schema has accepted since 18.6.0, instead of going through the metadata API or the package source. The row's label and help text ship in all eleven metadata-forms locale packs of `@objectstack/platform-objects`. Nothing about what a hook may declare changes. +- **`HookContext.text`.** `HookContext` now declares `text?: (key: string, params?: Record) => Promise` (named `HookTextReader`), the call the runtime already binds on every path a hook runs on, declared the way `api` and `notice` are: `z.unknown()` at parse, a static cast for the type, optional because a context parsed without the runtime carries none. A typed handler no longer needs a local type to call `ctx.text`. `HookContextSchema.parse` now keeps a bound `text` instead of stripping it. \ No newline at end of file diff --git a/content/docs/references/data/hook.mdx b/content/docs/references/data/hook.mdx index 5dacd667e99..4cb224fc03a 100644 --- a/content/docs/references/data/hook.mdx +++ b/content/docs/references/data/hook.mdx @@ -122,6 +122,7 @@ L2 sandboxed JS body — runs inside an isolated VM with declared capabilities | **ql** | `any` | ✅ | ObjectQL Engine Reference | | **api** | `any` | optional | Cross-object data access (IScopedContext — `object(name)` + `transaction(cb)`) | | **notice** | `any` | optional | Tell the person who made THIS insert/update what the save set in motion: `ctx.notice(message)` hands one non-empty string to the write's own `onNotice` listener, answered as the create/update `notice`. Bound by the engine on every insert/update dispatch (a no-op when nothing listens); absent on find/delete | +| **text** | `any` | optional | Answer one of the hook's declared texts: `await ctx.text(KEY, params?)` returns the sentence in the organization's language (translated through hooks.``.texts.``.message, the declared message as the fallback, holes filled from params). Bound by the runtime on every path a hook runs on; a key the hook does not declare rejects the call | | **user** | `{ id?: string; name?: string; email?: string; organizationId?: string }` | optional | Current user info shortcut | ### Nested Shape: `HookContext.dispatch` diff --git a/packages/spec/api-surface/data.json b/packages/spec/api-surface/data.json index d69183d4b25..ba883cf2404 100644 --- a/packages/spec/api-surface/data.json +++ b/packages/spec/api-surface/data.json @@ -419,6 +419,7 @@ "HookRefusalSchema (const)", "HookSchema (const)", "HookText (type)", + "HookTextReader (type)", "HookTextSchema (const)", "HookUpdateDoc (type)", "HookUpdateOptions (type)", diff --git a/packages/spec/authorable-surface/data.json b/packages/spec/authorable-surface/data.json index 73e8740e18e..b26e8b55698 100644 --- a/packages/spec/authorable-surface/data.json +++ b/packages/spec/authorable-surface/data.json @@ -491,6 +491,7 @@ "data/HookContext:result", "data/HookContext:session", "data/HookContext:submitted", + "data/HookContext:text", "data/HookContext:transaction", "data/HookContext:user", "data/HookRefusal:message", diff --git a/packages/spec/export-origins/data.json b/packages/spec/export-origins/data.json index aabb17a6b31..6ce59e36a38 100644 --- a/packages/spec/export-origins/data.json +++ b/packages/spec/export-origins/data.json @@ -409,6 +409,7 @@ "HookRefusalSchema": "src/data/hook.zod.ts#HookRefusalSchema (const)", "HookSchema": "src/data/hook.zod.ts#HookSchema (const)", "HookText": "src/data/hook.zod.ts#HookText (type)", + "HookTextReader": "src/data/hook.zod.ts#HookTextReader (type)", "HookTextSchema": "src/data/hook.zod.ts#HookTextSchema (const)", "HookUpdateDoc": "src/data/hook-api.ts#HookUpdateDoc (type)", "HookUpdateOptions": "src/data/hook-api.ts#HookUpdateOptions (type)", From 3d0f92b1960d94707a78ac1f2d6d94281077f1d1 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 12:13:05 +0000 Subject: [PATCH 7/8] test(platform-objects): the hook form's texts record joins the enumerated children Claude-Session: https://claude.ai/code/session_01L6bhgX6mQpVU8yUysiRAFC Co-authored-by: Claude --- .../translations/action-body-panel-echo-decisions.test.ts | 8 ++++++-- .../hook-execution-panel-echo-decisions.test.ts | 5 +++-- .../object-lifecycle-panel-echo-decisions.test.ts | 5 ++++- 3 files changed, 13 insertions(+), 5 deletions(-) diff --git a/packages/platform-objects/src/apps/translations/action-body-panel-echo-decisions.test.ts b/packages/platform-objects/src/apps/translations/action-body-panel-echo-decisions.test.ts index 28836024b59..aeabac85761 100644 --- a/packages/platform-objects/src/apps/translations/action-body-panel-echo-decisions.test.ts +++ b/packages/platform-objects/src/apps/translations/action-body-panel-echo-decisions.test.ts @@ -705,9 +705,11 @@ describe('#19403 round 5 — the blind spot, FIFTH shape: one schema, two forms, // 9 since #26835: the hook form offers the `refusals` record, whose two // entry fields (`message`, `status`) are enumerated the same way. 12 since // #33657: the entry also offers `reasons` (a record of `{ message }`) and - // `params`, three more enumerated children. + // `params`, three more enumerated children. 14 since #34575: the form + // offers the `texts` record, whose entry fields (`message`, `params`) are + // enumerated the same way. expect(HOOK_ENUMERATED.covered.length, 'hookForm enumerates no repeater row properties').toBe(0); - expect(HOOK_ENUMERATED.skipped.length).toBe(12); + expect(HOOK_ENUMERATED.skipped.length).toBe(14); for (const child of SHARED_BODY_CHILDREN) expect(HOOK_ENUMERATED.skipped).toContain(`body.${child}`); expect(HOOK_ENUMERATED.skipped).toContain('retryPolicy.maxRetries'); expect(HOOK_ENUMERATED.skipped).toContain('retryPolicy.backoffMs'); @@ -716,6 +718,8 @@ describe('#19403 round 5 — the blind spot, FIFTH shape: one schema, two forms, expect(HOOK_ENUMERATED.skipped).toContain('refusals.reasons'); expect(HOOK_ENUMERATED.skipped).toContain('refusals.reasons.message'); expect(HOOK_ENUMERATED.skipped).toContain('refusals.params'); + expect(HOOK_ENUMERATED.skipped).toContain('texts.message'); + expect(HOOK_ENUMERATED.skipped).toContain('texts.params'); // // ⇒ one composite, two forms, two different greens: a lit control that // passes on a sibling repeater, and a dark control that is right about diff --git a/packages/platform-objects/src/apps/translations/hook-execution-panel-echo-decisions.test.ts b/packages/platform-objects/src/apps/translations/hook-execution-panel-echo-decisions.test.ts index a16a1620b59..7367c3de712 100644 --- a/packages/platform-objects/src/apps/translations/hook-execution-panel-echo-decisions.test.ts +++ b/packages/platform-objects/src/apps/translations/hook-execution-panel-echo-decisions.test.ts @@ -785,9 +785,10 @@ describe('#19403 round 6 — the composite blind spot, hook side, CLOSED', () => // round 5 wrote down. Seven children sit enumerated and outside it — 9 // since #26835, when the `refusals` record's `message` / `status` joined, // and 12 since #33657, when its `reasons` (with `reasons.message`) and - // `params` joined. + // `params` joined, and 14 since #34575, when the `texts` record's + // `message` / `params` joined. expect(HOOK_ENUMERATED.covered.length, 'hookForm enumerates no repeater row properties').toBe(0); - expect(HOOK_ENUMERATED.skipped.length).toBe(12); + expect(HOOK_ENUMERATED.skipped.length).toBe(14); for (const child of SHARED_BODY_CHILDREN) expect(HOOK_ENUMERATED.skipped).toContain(`body.${child}`); expect(HOOK_ENUMERATED.skipped).toContain('retryPolicy.maxRetries'); expect(HOOK_ENUMERATED.skipped).toContain('retryPolicy.backoffMs'); diff --git a/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts b/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts index b6691bf30e5..f5cb0f238c8 100644 --- a/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts +++ b/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts @@ -1286,7 +1286,10 @@ describe('#19403 round 10 — the verdicts, on the live bundles', () => { // 741 since #33657: the hook form's refusal entry offers `reasons` (with // its `message`) and `params` — three row labels, authored in all three // locales. - expect(translated.length, `${locale} positive control`).toBe(741); + // 744 since #34575: the hook form offers the `texts` record and its + // `message` / `params` entry fields — three row labels, authored in all + // three locales. + expect(translated.length, `${locale} positive control`).toBe(744); } // ⭐ DARK — the blindness, executable. On a synthetic two-locale catalog the // all-three predicate returns 0 while the per-locale one returns 1, so the From b702af98f78e55e7ef47fd2b7ecef10bf97ca69e Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 12:52:41 +0000 Subject: [PATCH 8/8] chore(changeset): HookContext.text is an added protocol member, spec at minor Claude-Session: https://claude.ai/code/session_01L6bhgX6mQpVU8yUysiRAFC Co-authored-by: Claude --- .changeset/34575-hook-texts-studio-row.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/.changeset/34575-hook-texts-studio-row.md b/.changeset/34575-hook-texts-studio-row.md index eb656062b83..fb5cd505b22 100644 --- a/.changeset/34575-hook-texts-studio-row.md +++ b/.changeset/34575-hook-texts-studio-row.md @@ -1,12 +1,14 @@ --- -'@objectstack/spec': patch +'@objectstack/spec': minor '@objectstack/platform-objects': patch --- feat(spec): the Studio hook form offers a hook's declared `texts`, and `HookContext` declares `ctx.text` -Clause-②: yes -Metadata-protocol: none +Clause-②: yes (widening) +Metadata-protocol: added + +The added key is the type member `HookContext.text` (the authorable-surface record lists `HookContext` members); nothing a stack writes changes. - **Studio hook form.** `hookForm` gains a `texts` row beside `refusals`: a key-only record keyed by the snake_case key the hook's code asks for with `ctx.text`, each entry editing its `message` and `params`. An author editing a hook in the Studio can now write the `texts` the schema has accepted since 18.6.0, instead of going through the metadata API or the package source. The row's label and help text ship in all eleven metadata-forms locale packs of `@objectstack/platform-objects`. Nothing about what a hook may declare changes. - **`HookContext.text`.** `HookContext` now declares `text?: (key: string, params?: Record) => Promise` (named `HookTextReader`), the call the runtime already binds on every path a hook runs on, declared the way `api` and `notice` are: `z.unknown()` at parse, a static cast for the type, optional because a context parsed without the runtime carries none. A typed handler no longer needs a local type to call `ctx.text`. `HookContextSchema.parse` now keeps a bound `text` instead of stripping it. \ No newline at end of file