Skip to content

Commit 10321fa

Browse files
fix(spec): the hook form offers refusals and texts only where HookSchema accepts them (#38078)
<!-- claude-projects-attribution: {"github_login":"os-tesla"} --> _Requested by **Tesla** · [project thread](https://claude.ai/code/project/chan_01AXsQkLFKRdQCqQ3RTr6Jao?thread=cmsg_01AXsQkLFKRdQCqQ3RTr6Jao25upKJEGo6EpwNBNHeRSB5)_ Fixes #36799 repo:objectstack#3 · os-tesla · session_01L9qibwvndECT67oMnono1P Clause-②: no Metadata-protocol: none ## 维护者速读 - 搭建者在工作室里编辑一个表达式写成的钩子时,不会再看到拒绝码和文案这两栏;JavaScript 钩子和旧式处理函数钩子照常显示。 - 属于「作者界面只提供保存时会被接受的东西」这条线,替用工作室写钩子的搭建者解决填了就保存失败的问题。 - 只改表单什么时候显示这两栏,钩子能写什么完全不变;万一条件写错,最多是该显示的栏没显示,可以直接撤回。 - 无 ## What changes - `packages/spec/src/data/hook.metadata-form.ts`: the `refusals` and `texts` rows both carry one `visibleWhen`, `SANDBOXED_CODE_VISIBLE`, which is the test `HookSchema` refuses both keys by (`hook.zod.ts`, the refusals and texts refinements): shown for a `js` body, or for no body and a non-empty `handler`; hidden on an `expression` body. The form serves it as `{ dialect: 'cel', source: "data.body.language == 'js' || data.body == null && data.handler != null && data.handler != ''" }` (`defineMetadataForm` lifts the string, as for every other row). - Written without parentheses on purpose: the Studio form evaluator (`ui/packages/app-shell/src/views/metadata-admin/predicate.ts`) splits `||` before `&&` and has no grouping, so a parenthesised group fails open. The const's docblock says so. - No schema, no other form, no evaluator, no locale pack changes (label and help text are unchanged). - `patch` changeset for `@objectstack/spec`. ## Tests - `packages/spec/src/system/metadata-form-declared-rows.pin.test.ts`, new top-level `describe` "hook.refusals and hook.texts are shown exactly where HookSchema accepts them" (the shared harness that already pins the action form's gated `refusals` / `texts` rows): - each row is offered once and its served `visibleWhen` equals `{ dialect: 'cel', source: <the predicate> }`; - for each row × five drafts (expression body, js body, handler and no body, neither, empty handler and no body), the predicate read against `{ data: draft }` equals "`HookSchema.safeParse` raises no issue at that key"; - the predicate is read by a test-local reader of exactly the subset it is written in (`||` over `&&` over `data.path ==|!= 'literal'|null`, loose `null == undefined`, no grouping); any other shape throws, so a rewrite fails the pin. CONTROLS: the reader refuses a grouped and an `in` rewrite, and the schema refuses the key on some drafts and accepts it on others. <details><summary>Readings at 8c37099 (base origin/main 815e882)</summary> - Premise at 815e882: `git show origin/main:packages/spec/src/data/hook.metadata-form.ts | grep -c visibleWhen` = 0 (the card's `hook.form.ts` has since been renamed). - The predicate through the real Studio evaluator (`evaluatePredicate` + `buildPredicateCtx` from `predicate.ts` at 815e882, run under `node --experimental-transform-types`): expression body `false`, js body `true`, handler `'fn'` and no body `true`, neither `false`, handler `''` `false`; all five equal `HookSchema`'s verdict. - Ablation on the committed fix, file restored with `git checkout HEAD --` after each (`git status --porcelain` empty): `visibleWhen` removed from `refusals` → `Tests 6 failed | 23 passed (29)` (that row's six pins); removed from `texts` → `6 failed | 23 passed (29)` (that row's six). - Build: `env -u OS_SKIP_DTS bash scripts/pm/os-verify-lock.sh -c "pnpm exec turbo run build --filter='./packages/**' --filter='@objectstack/dogfood^...' --concurrency=2"` exit 0 (83 tasks). - `pnpm --filter @objectstack/spec check:generated` exit 0 ("All 14 generated artifacts are up to date"); spec `typecheck` exit 0; `eslint` on the two changed `.ts` exit 0. - `vitest run src/data src/system src/ui` in `packages/spec`: `Test Files 470 passed (470)`, `Tests 16505 passed | 1 todo (16506)`. - `dispatch-gates --ran`: 86 derived, 86 run, every one exit 0, 0 NOT-MEASURED (a derived zero), 0 unrun. </details> ## Acceptance notes - A hidden row keeps a value already written: an author who fills `refusals` on a `js` body and then switches the body to `expression` no longer sees the row, and the save is refused at a key the form does not show. This holds for every `visibleWhen` row (the metadata form does not clear hidden values); not widened here. - Out of scope, for the seat to file (seat said it will): the Studio form evaluator fails open on a parenthesised group, so `field.metadata-form.ts`'s `percentDisplay` row and the currency row after it read TRUE on every field type (measured at 815e882: `{ type: 'text' }` → `true`; the same predicate without parentheses → `false`). ## Verification Read first (by risk): 1. `packages/spec/src/data/hook.metadata-form.ts`: `SANDBOXED_CODE_VISIBLE` and its two uses. 2. `packages/spec/src/system/metadata-form-declared-rows.pin.test.ts`: the new describe, `evalFormPredicate` and `refusedAt`. Two-minute check: `pnpm --filter @objectstack/spec exec vitest run src/system/metadata-form-declared-rows.pin.test.ts` shows 29 passing; delete `visibleWhen: SANDBOXED_CODE_VISIBLE,` from the `texts` row and the same command shows 6 failing. --- _Generated by [Claude Code](https://claude.ai/code/session_01L9qibwvndECT67oMnono1P)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 32dc5d8 commit 10321fa

4 files changed

Lines changed: 136 additions & 3 deletions

File tree

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@objectstack/spec': patch
3+
---
4+
5+
fix(spec): the Studio hook form offers `refusals` and `texts` only where a hook may declare them
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
`hookForm` offered the `refusals` and `texts` rows on every hook. `HookSchema` refuses both keys on an `expression` body, so an author writing an expression hook was offered two sections that could only make the save fail. Both rows now carry a `visibleWhen` that is the schema's own test: they are shown for a `js` body, and for a hook with no body and a non-empty `handler`, and hidden on an `expression` body. What a hook may declare does not change. Nothing to migrate.

‎packages/lint/src/validate-predicate-path-refs.test.ts‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -709,7 +709,11 @@ describe('#7010 corpus — shipped METADATA_FORM_REGISTRY', () => {
709709
// It is 96 today, an ADDITION of ONE: #35926 offered the field form's
710710
// `inlineEdit` select, gated on `data.type in ['lookup','master_detail']`. It
711711
// is an in-list, so it does not reach the literal-comparison census below.
712-
expect(predicates, 'the shipped metadata forms carry no predicates at all').toBe(96);
712+
// It is 98 today, an ADDITION of TWO: the hook form's `refusals` and `texts`
713+
// rows are each gated on the test `HookSchema` refuses both keys by,
714+
// `data.body.language == 'js' || data.body == null && data.handler != null
715+
// && data.handler != ''`. They reach the literal-comparison census below.
716+
expect(predicates, 'the shipped metadata forms carry no predicates at all').toBe(98);
713717

714718
const findings = validatePredicatePathRefs(corrupted);
715719
expect(findings).toHaveLength(predicates);
@@ -840,7 +844,10 @@ describe('#7010 corpus — shipped METADATA_FORM_REGISTRY', () => {
840844
// It is 67 today: #35096's `action :: texts` and #34823's
841845
// `action :: refusals` rows are each gated on `data.type == 'script'`, two
842846
// single-quoted literal comparisons.
843-
expect(comparisons, 'no shipped predicate carries an `==`/`!=` literal comparison').toBe(67);
847+
// It is 71 today: the hook form's `hook :: refusals` and `hook :: texts`
848+
// gates each carry two single-quoted literal comparisons, `== 'js'` and
849+
// `!= ''` (the two `null` comparisons are not single-quoted literals).
850+
expect(comparisons, 'no shipped predicate carries an `==`/`!=` literal comparison').toBe(71);
844851

845852
const rhsFindings = validatePredicatePathRefs(corrupted)
846853
.filter((f) => f.rule === PREDICATE_RHS_PATH_SHAPED);

‎packages/spec/src/data/hook.metadata-form.ts‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,20 @@
22

33
import { defineMetadataForm } from '../ui/view.zod';
44

5+
/**
6+
* The rows `refusals` and `texts` are shown where the hook has code that can
7+
* throw a code or ask for a text: a `js` body, or no body and a handler. That
8+
* is the test `HookSchema` refuses both keys by (`hook.zod.ts`, the refusals
9+
* and texts refinements); an `expression` body is refused, so its form does
10+
* not offer them. The handler half reads non-empty, as the schema's does.
11+
*
12+
* Written without parentheses on purpose: the Studio form evaluator splits
13+
* `||` before `&&` but has no grouping, and a parenthesised group fails open
14+
* (the row is shown on every draft).
15+
*/
16+
const SANDBOXED_CODE_VISIBLE =
17+
"data.body.language == 'js' || data.body == null && data.handler != null && data.handler != ''";
18+
519
/**
620
* Form Layout for Hook Metadata Type
721
*
@@ -10,7 +24,8 @@ import { defineMetadataForm } from '../ui/view.zod';
1024
* `source` renders in a Monaco code editor with language-appropriate
1125
* syntax highlighting. The hook's refusal catalogue (`refusals`) and its
1226
* declared texts (`texts`) sit beside it: a js body or a handler may declare
13-
* them, an expression body may not.
27+
* them, an expression body may not, so both rows are shown only where
28+
* `HookSchema` accepts them (`SANDBOXED_CODE_VISIBLE` above).
1429
*/
1530
export const hookForm = defineMetadataForm({
1631
schemaId: 'hook',
@@ -58,6 +73,7 @@ export const hookForm = defineMetadataForm({
5873
field: 'refusals',
5974
type: 'record',
6075
widget: 'key-only-record',
76+
visibleWhen: SANDBOXED_CODE_VISIBLE,
6177
helpText: 'Refusal catalogue, keyed by the SCREAMING_SNAKE code the hook throws (e.g. CLEAN_VERSION_REQUIRED). The caller reads the declared message, translated into their language, with the declared status. For a JavaScript (L2) body or a handler; refused on an expression body',
6278
fields: [
6379
{ field: 'message', type: 'textarea', required: true, helpText: 'The sentence the user reads when the body throws this code. Plain text, unless the entry declares params: then a {{ name }} hole fills a declared param' },
@@ -82,6 +98,7 @@ export const hookForm = defineMetadataForm({
8298
field: 'texts',
8399
type: 'record',
84100
widget: 'key-only-record',
101+
visibleWhen: SANDBOXED_CODE_VISIBLE,
85102
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",
86103
fields: [
87104
{ 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' },

‎packages/spec/src/system/metadata-form-declared-rows.pin.test.ts‎

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ import { describe, it, expect } from 'vitest';
4444

4545
import { METADATA_FORM_REGISTRY } from './metadata-form-registry';
4646
import { ActionRefusalSchema, ActionTextSchema } from '../ui/action.zod';
47+
import { HookSchema } from '../data/hook.zod';
4748

4849
type FormEntry = {
4950
field?: string;
@@ -339,3 +340,101 @@ describe('action.refusals and action.texts are key-only records beside the scrip
339340
expect(indexOf('texts'), 'beside the body, before the param dialog rows').toBeLessThan(indexOf('params'));
340341
});
341342
});
343+
344+
/**
345+
* **hook.refusals and hook.texts are shown where `HookSchema` accepts them.**
346+
*
347+
* `HookSchema` refuses both keys unless the hook has code that can throw a code
348+
* or ask for a text: a `js` body, or no body and a non-empty handler. The form
349+
* used to offer both rows on every hook, so an author writing an `expression`
350+
* hook was handed two sections that could only make the save fail. Each row
351+
* now carries the schema's own test as its `visibleWhen`; this pin reads the
352+
* two served predicates and holds them equal to the schema's verdict on each
353+
* draft shape the form can produce.
354+
*
355+
* The predicate is read by {@link evalFormPredicate}, a reader of exactly the
356+
* subset the predicate is written in (`||` over `&&` over `path ==|!= literal`,
357+
* no grouping, the Studio form evaluator's precedence and its loose
358+
* `null == undefined`). Any other shape throws, so a rewrite this reader does
359+
* not know fails the pin instead of being read as some verdict.
360+
*/
361+
describe('hook.refusals and hook.texts are shown exactly where HookSchema accepts them', () => {
362+
const SOURCE = "data.body.language == 'js' || data.body == null && data.handler != null && data.handler != ''";
363+
const base = { name: 'credit_guard', object: 'order', events: ['beforeInsert'] };
364+
const DRAFTS: Array<[string, Record<string, unknown>]> = [
365+
['an expression body', { body: { language: 'expression', source: 'record.amount > 0' } }],
366+
['a js body', { body: { language: 'js', source: 'return;' } }],
367+
['a handler and no body', { handler: 'creditGuard' }],
368+
['neither a body nor a handler', {}],
369+
['an empty handler and no body', { handler: '' }],
370+
];
371+
const DECLARED = {
372+
refusals: { CREDIT_LIMIT: { message: 'This order exceeds the customer credit limit.' } },
373+
texts: { follow_up_subject: { message: 'Follow up' } },
374+
} as const;
375+
376+
const sourceOf = (p: FormEntry['visibleWhen']) => (typeof p === 'string' ? p : p?.source);
377+
378+
function readPath(path: string, data: Record<string, unknown>): unknown {
379+
const [root, ...segs] = path.split('.');
380+
if (root !== 'data' || segs.length === 0) throw new Error(`unknown path shape: ${path}`);
381+
let cur: unknown = data;
382+
for (const seg of segs) {
383+
if (cur == null) return undefined;
384+
cur = (cur as Record<string, unknown>)[seg];
385+
}
386+
return cur;
387+
}
388+
389+
function readLiteral(raw: string): unknown {
390+
if (raw === 'null') return null;
391+
const quoted = /^'([^']*)'$/.exec(raw);
392+
if (quoted) return quoted[1];
393+
throw new Error(`unknown literal shape: ${raw}`);
394+
}
395+
396+
/** Read `source` against `{ data }`; throws on any shape outside the subset above. */
397+
function evalFormPredicate(source: string, data: Record<string, unknown>): boolean {
398+
if (/[()]/.test(source)) throw new Error(`grouping is outside the subset: ${source}`);
399+
return source.split(' || ').some((conj) =>
400+
conj.split(' && ').every((atom) => {
401+
const m = /^(data(?:\.[A-Za-z_]+)+) (==|!=) (null|'[^']*')$/.exec(atom.trim());
402+
if (!m) throw new Error(`unknown atom shape: ${atom}`);
403+
const left = readPath(m[1]!, data);
404+
const right = readLiteral(m[3]!);
405+
const equal = left == null && right == null ? true : left === right;
406+
return m[2] === '==' ? equal : !equal;
407+
}),
408+
);
409+
}
410+
411+
const refusedAt = (key: 'refusals' | 'texts', draft: Record<string, unknown>) => {
412+
const parsed = HookSchema.safeParse({ ...base, ...draft, [key]: DECLARED[key] });
413+
return !parsed.success && parsed.error.issues.some((i) => i.path.length === 1 && i.path[0] === key);
414+
};
415+
416+
it('CONTROLS: the reader refuses a shape it does not know, and the schema cut is real', () => {
417+
expect(() => evalFormPredicate(`(${SOURCE})`, {}), 'dark control: a grouped rewrite is not read').toThrow(
418+
/grouping/,
419+
);
420+
expect(() => evalFormPredicate("data.body.language in ['js']", {})).toThrow(/atom/);
421+
const verdicts = DRAFTS.map(([, draft]) => refusedAt('refusals', draft));
422+
expect(verdicts, 'the schema refuses the key on some drafts and accepts it on others').toContain(true);
423+
expect(verdicts).toContain(false);
424+
});
425+
426+
it.each(['refusals', 'texts'] as const)('%s carries the schema\'s own test as its visibleWhen', (key) => {
427+
const [row, ...extra] = rowFor('hook', key);
428+
expect(row, `\`${key}\` is declared by HookSchema; the hook form must offer it`).toBeDefined();
429+
expect(extra, 'one row only').toEqual([]);
430+
expect(row!.visibleWhen).toEqual({ dialect: 'cel', source: SOURCE });
431+
});
432+
433+
it.each(
434+
(['refusals', 'texts'] as const).flatMap((key) => DRAFTS.map(([what, draft]) => [key, what, draft] as const)),
435+
)('%s is shown on %s exactly when HookSchema accepts it there', (key, _what, draft) => {
436+
const [row] = rowFor('hook', key);
437+
const shown = evalFormPredicate(sourceOf(row!.visibleWhen) ?? '', draft);
438+
expect(shown).toBe(!refusedAt(key, draft));
439+
});
440+
});

0 commit comments

Comments
 (0)