From 8329621bb4cc9f3f0cc43e2cdcada4e39a6568b8 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 00:09:39 +0000 Subject: [PATCH 1/3] fix(lint)!: compile hook and job bodies in the (ctx) wrapper the runtime runs them in Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01L6bhgTggz8AL2bCABoDGis --- packages/lint/src/action-body-wrapper.ts | 45 +++-- packages/lint/src/authoring-rules.ts | 21 +++ packages/lint/src/index.ts | 24 ++- packages/lint/src/rule-explanations.ts | 43 +++++ packages/lint/src/runtime.ts | 11 +- .../lint/src/validate-action-body-compiles.ts | 144 ++++++++++++---- .../src/validate-hook-body-compiles.test.ts | 161 ++++++++++++++++++ .../lint/src/validate-hook-body-compiles.ts | 139 +++++++++++++++ .../runtime/src/sandbox/quickjs-runner.ts | 15 +- 9 files changed, 543 insertions(+), 60 deletions(-) create mode 100644 packages/lint/src/validate-hook-body-compiles.test.ts create mode 100644 packages/lint/src/validate-hook-body-compiles.ts diff --git a/packages/lint/src/action-body-wrapper.ts b/packages/lint/src/action-body-wrapper.ts index bdf6ae21ced..ee202e899ae 100644 --- a/packages/lint/src/action-body-wrapper.ts +++ b/packages/lint/src/action-body-wrapper.ts @@ -1,25 +1,27 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. /** - * The one spelling of the wrapper an L2 action body runs in. + * The one spelling of each wrapper an L2 body runs in. * - * The runtime does not run an action's `body.source` as a script of its own: it - * pastes the source into the body of an async arrow and calls that arrow with - * the action's params and its context + * The runtime does not run a body's `source` as a script of its own: it pastes + * the source into the body of an async arrow and calls that arrow * (`packages/runtime/src/sandbox/quickjs-runner.ts`). So the source's - * statements share a scope with two bindings the author never wrote, and a - * source that is valid on its own can fail to compile there: declaring `input` - * or `ctx` again with `const` / `let` / `class` is a redeclaration of a - * parameter, a SyntaxError raised before any statement runs. + * statements share a scope with bindings the author never wrote, and a source + * that is valid on its own can fail to compile there: declaring a parameter + * again with `const` / `let` / `class` is a redeclaration, a SyntaxError raised + * before any statement runs. * - * The runtime builds its wrapper from {@link actionBodyFunctionExpression}, and - * the author-time rule (`validate-action-body-compiles.ts`) compiles the source - * inside that same expression, so the check and the run cannot disagree about - * the wrapper. ⛔ Never spell the wrapper a second time anywhere: a copy is a - * second shape the next edit can move one side of. + * There are two wrappers. An action body takes the action's params and its + * context, `(async (input, ctx) => { … })`; a hook body and a job body take the + * context alone, `(async (ctx) => { … })` (a job has no input to hand in, and + * `JobSchema.body` documents `ctx` as its whole surface). * - * Hook and job bodies run in a different wrapper, `(async (ctx) => { … })`, and - * are not described here. + * The runtime builds each wrapper from {@link actionBodyFunctionExpression} and + * {@link hookBodyFunctionExpression}, and the author-time rules + * (`validate-action-body-compiles.ts`, `validate-hook-body-compiles.ts`) + * compile the source inside those same expressions, so the check and the run + * cannot disagree about a wrapper. ⛔ Never spell a wrapper a second time + * anywhere: a copy is a second shape the next edit can move one side of. * * No imports: the runtime reaches this module through `@objectstack/lint/runtime`. */ @@ -37,3 +39,16 @@ export const ACTION_BODY_PARAMETERS = ['input', 'ctx'] as const; export function actionBodyFunctionExpression(source: string): string { return `(async (${ACTION_BODY_PARAMETERS.join(', ')}) => { ${source} })`; } + +/** The parameter a hook or job body's wrapper binds: the context. */ +export const HOOK_BODY_PARAMETERS = ['ctx'] as const; + +/** + * The function expression a hook body and a job body run as: `(async (ctx) => { SOURCE })`. + * + * The same one-line placement as {@link actionBodyFunctionExpression}: line N of + * the source is line N of the expression. + */ +export function hookBodyFunctionExpression(source: string): string { + return `(async (${HOOK_BODY_PARAMETERS.join(', ')}) => { ${source} })`; +} diff --git a/packages/lint/src/authoring-rules.ts b/packages/lint/src/authoring-rules.ts index 435a441b0cf..324c34f2313 100644 --- a/packages/lint/src/authoring-rules.ts +++ b/packages/lint/src/authoring-rules.ts @@ -149,6 +149,7 @@ import { } from './validate-membership-key-declarations.js'; import { validateRuleCompilability } from './validate-rule-compilability.js'; import { validateActionBodyCompiles } from './validate-action-body-compiles.js'; +import { validateHookAndJobBodyCompiles } from './validate-hook-body-compiles.js'; import { validateRuleSchemaFormats } from './validate-rule-schema-formats.js'; import { validateActionLocations } from './validate-action-locations.js'; import { validateActionObjectBinding } from './validate-action-object-binding.js'; @@ -2965,6 +2966,26 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [ runtimeTypes: ['action', 'object'], run: (stack) => validateActionBodyCompiles(stack), }, + // The same compile check over an L2 hook body and an L2 job body, in the + // wrapper the runtime runs both in (`(async (ctx) => { SOURCE })`, built from + // the same function the rule compiles inside). Gating for the action rule's + // reason: the body never starts. Same severity split, read through the one + // `judgeBodyCompile`; two ids (`hook-body-does-not-compile`, + // `job-body-does-not-compile`). Across the runtime publish gate for `hook` + // writes only: a hook is runtime-creatable, a job is not + // (`allowRuntimeCreate: false`), so no door publishes a job body, and no + // object write carries a hook (`hooks` is not an ObjectSchema key). The rule + // loads no dependency: compiling goes through the host's `node:vm`. + { + name: 'validateHookAndJobBodyCompiles', + tier: 'gating', + input: 'parsed', + commands: ALL, + source: 'packages/lint/src/validate-hook-body-compiles.ts', + surfaces: CLI_AND_RUNTIME, + runtimeTypes: ['hook'], + run: (stack, ctx) => validateHookAndJobBodyCompiles(stack, ctx), + }, // #5178 — the residual half of #5029, which registering `ajv-formats` does // NOT close: under `strict: false` a MISSPELLED format name (`emial`) is // logged once and DROPPED, so the rule compiles, ships, runs on every write diff --git a/packages/lint/src/index.ts b/packages/lint/src/index.ts index d7fd53933ee..3a11942b6b9 100644 --- a/packages/lint/src/index.ts +++ b/packages/lint/src/index.ts @@ -1029,10 +1029,30 @@ export type { export { validateActionBodyCompiles, hostCompileFailure, + judgeBodyCompile, ACTION_BODY_DOES_NOT_COMPILE, } from './validate-action-body-compiles.js'; -export type { ActionBodyCompileFinding, HostCompileFailure } from './validate-action-body-compiles.js'; -export { ACTION_BODY_PARAMETERS, actionBodyFunctionExpression } from './action-body-wrapper.js'; +export type { + ActionBodyCompileFinding, + HostCompileFailure, + BodyCompileShape, + BodyCompileVerdict, +} from './validate-action-body-compiles.js'; +export { + ACTION_BODY_PARAMETERS, + actionBodyFunctionExpression, + HOOK_BODY_PARAMETERS, + hookBodyFunctionExpression, +} from './action-body-wrapper.js'; + +// The same compile check over hook and job bodies, in their own `(ctx)` +// wrapper, which the runtime builds from `hookBodyFunctionExpression`. +export { + validateHookAndJobBodyCompiles, + HOOK_BODY_DOES_NOT_COMPILE, + JOB_BODY_DOES_NOT_COMPILE, +} from './validate-hook-body-compiles.js'; +export type { HookBodyCompileFinding } from './validate-hook-body-compiles.js'; // The same write-set question on the third surface — a flow `update_record` // node's structural `config.fields`. Shares the hook rule's field index and diff --git a/packages/lint/src/rule-explanations.ts b/packages/lint/src/rule-explanations.ts index 6d69bea6619..04851ba3e9d 100644 --- a/packages/lint/src/rule-explanations.ts +++ b/packages/lint/src/rule-explanations.ts @@ -1487,6 +1487,47 @@ const ACTION_BODY_DOES_NOT_COMPILE_EXPLANATION: RuleExplanation = { ], }; +/** Shared by the hook and job compile rules: the two bodies run in one wrapper. */ +const CTX_BODY_COMPILE: readonly string[] = [ + 'The rule compiles the body inside the same expression the runtime builds, from the same function, ' + + 'with this host\'s JavaScript engine and without running it, and reads the failure the way ' + + '`action-body-does-not-compile` does: a regular-expression pattern the host refuses is a warning, ' + + 'because the runtime\'s QuickJS accepts some patterns the host does not; every other compile failure, ' + + 'a literal that never closes or whose flags are not a flag set included, is refused. Syntax the host ' + + 'accepts and QuickJS does not is not caught here.', +]; + +const HOOK_BODY_DOES_NOT_COMPILE_EXPLANATION: RuleExplanation = { + rule: 'hook-body-does-not-compile', + covers: 'the wrapper a hook body is compiled in', + paragraphs: [ + 'A hook body is not a script of its own. The runtime pastes `body.source` into the body of ' + + '`(async (ctx) => { … })` and calls it with the hook\'s context, so the statements share a scope with ' + + 'a parameter the author never wrote. A source that is valid on its own can fail to compile there, and ' + + 'then every run of the hook fails before any statement runs.', + 'The common cases are declaring the parameter again (`const ctx = …`, `let ctx`), declaring any name ' + + 'twice with `let` / `const`, and grammar errors. Use `ctx` as it is, or give the local another name ' + + '(`const input = ctx.input || {}`).', + ...CTX_BODY_COMPILE, + 'The parse check on the same body (`hook-body-source-unparseable`) uses a parser, which reports no ' + + 'redeclaration and no other early error, so it passes most bodies this rule refuses.', + ], +}; + +const JOB_BODY_DOES_NOT_COMPILE_EXPLANATION: RuleExplanation = { + rule: 'job-body-does-not-compile', + covers: 'the wrapper a job body is compiled in', + paragraphs: [ + 'A job body runs in the hook\'s wrapper, `(async (ctx) => { … })`: a job has no input to hand in, so ' + + '`ctx` is its whole surface. A source that is valid on its own can fail to compile there, and then ' + + 'every scheduled run of the job fails before any statement runs.', + 'The common cases are declaring the parameter again (`const ctx = …`, `let ctx`), declaring any name ' + + 'twice with `let` / `const`, and grammar errors. Use `ctx` as it is, or give the local another name ' + + '(`const api = ctx.api`).', + ...CTX_BODY_COMPILE, + ], +}; + const ACTION_BODY_WRITE_UNPROVISIONED_ANCHOR_EXPLANATION: RuleExplanation = { rule: 'action-body-write-unprovisioned-anchor', covers: 'why a write to an unprovisioned anchor never lands', @@ -6421,6 +6462,8 @@ export const RULE_EXPLANATIONS: Readonly> = Obje [ACTION_RECORD_WRITE_DISCARDED_EXPLANATION.rule]: ACTION_RECORD_WRITE_DISCARDED_EXPLANATION, [ACTION_BODY_SOURCE_UNPARSEABLE_EXPLANATION.rule]: ACTION_BODY_SOURCE_UNPARSEABLE_EXPLANATION, [ACTION_BODY_DOES_NOT_COMPILE_EXPLANATION.rule]: ACTION_BODY_DOES_NOT_COMPILE_EXPLANATION, + [HOOK_BODY_DOES_NOT_COMPILE_EXPLANATION.rule]: HOOK_BODY_DOES_NOT_COMPILE_EXPLANATION, + [JOB_BODY_DOES_NOT_COMPILE_EXPLANATION.rule]: JOB_BODY_DOES_NOT_COMPILE_EXPLANATION, [ACTION_BODY_WRITE_UNPROVISIONED_ANCHOR_EXPLANATION.rule]: ACTION_BODY_WRITE_UNPROVISIONED_ANCHOR_EXPLANATION, [FLOW_NODE_WRITE_UNKNOWN_FIELD_EXPLANATION.rule]: FLOW_NODE_WRITE_UNKNOWN_FIELD_EXPLANATION, [FLOW_NODE_WRITE_UNPROVISIONED_ANCHOR_EXPLANATION.rule]: FLOW_NODE_WRITE_UNPROVISIONED_ANCHOR_EXPLANATION, diff --git a/packages/lint/src/runtime.ts b/packages/lint/src/runtime.ts index f434443ddd1..e87994e856d 100644 --- a/packages/lint/src/runtime.ts +++ b/packages/lint/src/runtime.ts @@ -97,8 +97,9 @@ export type { UserTextParams } from './finding-user-text.js'; // through it. One ladder for every producer of platform-composed user text. export { renderUserText, userTextLocaleOf } from './finding-user-text.js'; export type { UserTextEntry } from './finding-user-text.js'; -// The wrapper an action body runs in, for the runtime that builds it -// (`@objectstack/runtime`'s QuickJS runner). The author-time rule -// `action-body-does-not-compile` compiles the body inside the same expression, -// so the check and the run cannot disagree about the wrapper. -export { actionBodyFunctionExpression } from './action-body-wrapper.js'; +// The wrappers an action body and a hook or job body run in, for the runtime +// that builds them (`@objectstack/runtime`'s QuickJS runner). The author-time +// rules `action-body-does-not-compile`, `hook-body-does-not-compile` and +// `job-body-does-not-compile` compile the body inside the same expression, so +// the check and the run cannot disagree about a wrapper. +export { actionBodyFunctionExpression, hookBodyFunctionExpression } from './action-body-wrapper.js'; diff --git a/packages/lint/src/validate-action-body-compiles.ts b/packages/lint/src/validate-action-body-compiles.ts index bae57fbce50..4cede3d1b2e 100644 --- a/packages/lint/src/validate-action-body-compiles.ts +++ b/packages/lint/src/validate-action-body-compiles.ts @@ -59,8 +59,11 @@ * one; at run time the action then answers a coded `500` naming itself and the * compile error (`quickjs-runner.ts`). * - * Only action bodies are judged. Hook and job bodies run in `(async (ctx) => { - * … })`, a different wrapper, and are outside this rule. + * Hook and job bodies run in a different wrapper, `(async (ctx) => { … })`, + * and are judged by `hook-body-does-not-compile` / `job-body-does-not-compile` + * (`validate-hook-body-compiles.ts`), which read their compile failures through + * the same {@link judgeBodyCompile}, so every body kind takes the same severity + * split. */ import { ACTION_BODY_PARAMETERS, actionBodyFunctionExpression } from './action-body-wrapper.js'; @@ -148,6 +151,101 @@ const REGEXP_FLAGS = /^SyntaxError: Invalid regular expression flags/; /** A redeclaration the host names (`Identifier 'input' has already been declared`), and the name. */ const REDECLARED = /^SyntaxError: Identifier '([^']+)' has already been declared/; +/** How a compile failure is classified; every body kind's rule reads the same classes. */ +export type BodyCompileShape = + /** A regular-expression PATTERN the host refuses — the one `warning` arm. */ + | 'regexp-pattern' + /** A regular-expression literal that never closes on its line. */ + | 'regexp-unterminated' + /** A regular-expression literal whose flags are not a flag set. */ + | 'regexp-flags' + /** A parameter of the wrapper declared again. */ + | 'redeclared-parameter' + /** Any other compile failure. */ + | 'other'; + +/** What compiling one body inside its wrapper said, when it did not compile. */ +export interface BodyCompileVerdict { + /** `warning` for a regular-expression pattern only; every other failure is an `error`. */ + severity: 'error' | 'warning'; + shape: BodyCompileShape; + /** The host's sentence, `SyntaxError: …`. */ + error: string; + /** `, line N` when the host named a line (line N of the source), else empty. */ + at: string; + /** The wrapper parameter declared again, on `redeclared-parameter`. */ + parameter?: string; +} + +/** + * Compile `expression` — a body's wrapper with the body inside it, from the one + * function the runtime builds it with — and classify why it did not compile, or + * answer `undefined` when it compiled (or when the host cannot judge). + * `parameters` are the wrapper's own bindings, so a redeclared one is named. + */ +export function judgeBodyCompile(expression: string, parameters: readonly string[]): BodyCompileVerdict | undefined { + const failure = hostCompileFailure(expression); + if (!failure) return undefined; + + const at = failure.line !== undefined ? `, line ${failure.line}` : ''; + const redeclared = REDECLARED.exec(failure.error)?.[1]; + const parameter = redeclared !== undefined && parameters.includes(redeclared) ? redeclared : undefined; + const shape: BodyCompileShape = parameter !== undefined + ? 'redeclared-parameter' + : REGEXP_PATTERN_FAILURE.test(failure.error) + ? 'regexp-pattern' + : REGEXP_UNTERMINATED.test(failure.error) + ? 'regexp-unterminated' + : REGEXP_FLAGS.test(failure.error) + ? 'regexp-flags' + : 'other'; + + return { + severity: shape === 'regexp-pattern' ? 'warning' : 'error', + shape, + error: failure.error, + at, + ...(parameter !== undefined ? { parameter } : {}), + }; +} + +/** + * The finding's message for a verdict: `wrapper` is the wrapper shown with an + * ellipsis for the body, `subject` the body's owner as a noun (`this action`). + */ +export function bodyCompileMessage(verdict: BodyCompileVerdict, wrapper: string, subject: string): string { + return verdict.shape === 'regexp-pattern' + ? `body's regular expression is refused by this host's engine (${verdict.error}${verdict.at}); the runtime's ` + + `engine may accept it, but if it does not, every run of ${subject} fails` + : `body does not compile in the wrapper the runtime runs it in, ` + + `${wrapper} (${verdict.error}${verdict.at}), so every run of ${subject} fails`; +} + +/** + * The finding's hint for a verdict. The two body-kind-specific answers are the + * caller's — what to do about a redeclared parameter, and the generic fix — and + * the regular-expression answers are the same for every kind. + */ +export function bodyCompileHint( + verdict: BodyCompileVerdict, + own: { redeclared: (parameter: string) => string; other: string }, +): string { + switch (verdict.shape) { + case 'redeclared-parameter': + return own.redeclared(verdict.parameter!); + case 'regexp-pattern': + return 'Rewrite the regular expression in a form both engines accept, or build it with new RegExp(…) at run time'; + case 'regexp-unterminated': + return 'A `/` opens a regular-expression literal that never closes on its line: close it with `/`, write a ' + + '`/` inside it as `\\/`, or, if the `/` is a division, give it a left-hand operand'; + case 'regexp-flags': + return 'A regular-expression literal\'s flags are letters from `dgimsuvy`, each at most once, and never ' + + '`u` with `v`'; + default: + return own.other; + } +} + /** * Every L2 action body that does not compile in the runtime's action wrapper. * Pure `(stack) => Finding[]` (ADR-0019); safe on pre- or post-parse stacks. @@ -159,42 +257,24 @@ export function validateActionBodyCompiles(stack: Record): Acti if (!stack || typeof stack !== 'object') return findings; for (const site of collectActionBodies(stack)) { - const failure = hostCompileFailure(actionBodyFunctionExpression(site.source)); - if (!failure) continue; - - const at = failure.line !== undefined ? `, line ${failure.line}` : ''; - const regexp = REGEXP_PATTERN_FAILURE.test(failure.error); - const unterminated = REGEXP_UNTERMINATED.test(failure.error); - const flags = REGEXP_FLAGS.test(failure.error); - const redeclared = REDECLARED.exec(failure.error)?.[1]; - const parameter = redeclared !== undefined && (ACTION_BODY_PARAMETERS as readonly string[]).includes(redeclared) - ? redeclared - : undefined; + const verdict = judgeBodyCompile(actionBodyFunctionExpression(site.source), ACTION_BODY_PARAMETERS); + if (!verdict) continue; findings.push({ - severity: regexp ? 'warning' : 'error', + severity: verdict.severity, rule: ACTION_BODY_DOES_NOT_COMPILE, where: `action "${site.name}" › body`, path: site.path, - message: regexp - ? `body's regular expression is refused by this host's engine (${failure.error}${at}); the runtime's ` + - `engine may accept it, but if it does not, every run of this action fails` - : `body does not compile in the wrapper the runtime runs it in, ` + - `${actionBodyFunctionExpression('…')} (${failure.error}${at}), so every run of this action fails`, - hint: parameter !== undefined - ? `\`${parameter}\` is already a parameter of the wrapper: use it as it is (the action's params are ` + + message: bodyCompileMessage(verdict, actionBodyFunctionExpression('…'), 'this action'), + hint: bodyCompileHint(verdict, { + redeclared: (parameter) => + `\`${parameter}\` is already a parameter of the wrapper: use it as it is (the action's params are ` + `\`input\`, the context is \`ctx\`), or give the local another name, e.g. ` + - `\`const params = ctx.input || {}\`` - : regexp - ? 'Rewrite the regular expression in a form both engines accept, or build it with new RegExp(…) at run time' - : unterminated - ? 'A `/` opens a regular-expression literal that never closes on its line: close it with `/`, write a ' + - '`/` inside it as `\\/`, or, if the `/` is a division, give it a left-hand operand' - : flags - ? 'A regular-expression literal\'s flags are letters from `dgimsuvy`, each at most once, and never ' + - '`u` with `v`' - : `Fix body.source so it compiles as the statements of an async function whose parameters are ` + - `${ACTION_BODY_PARAMETERS.map((p) => `\`${p}\``).join(' and ')}`, + `\`const params = ctx.input || {}\``, + other: + `Fix body.source so it compiles as the statements of an async function whose parameters are ` + + `${ACTION_BODY_PARAMETERS.map((p) => `\`${p}\``).join(' and ')}`, + }), }); } diff --git a/packages/lint/src/validate-hook-body-compiles.test.ts b/packages/lint/src/validate-hook-body-compiles.test.ts new file mode 100644 index 00000000000..1448f269444 --- /dev/null +++ b/packages/lint/src/validate-hook-body-compiles.test.ts @@ -0,0 +1,161 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { describe, expect, it } from 'vitest'; +import { + HOOK_BODY_DOES_NOT_COMPILE, + JOB_BODY_DOES_NOT_COMPILE, + validateHookAndJobBodyCompiles, +} from './validate-hook-body-compiles.js'; +import { hostCompileFailure } from './validate-action-body-compiles.js'; +import { hookBodyFunctionExpression } from './action-body-wrapper.js'; +import { HOOK_BODY_SOURCE_UNPARSEABLE, validateHookBodyWrites } from './validate-hook-body-writes.js'; +import { runAuthoringRules } from './authoring-rules.js'; +import { runRuntimeAuthoringRules } from './runtime-gate.js'; +import { explainRule } from './rule-explanations.js'; + +/** The two bodies the claim measured: 0 TypeScript parse diagnostics, refused by the host in the `(ctx)` wrapper. */ +const REDECLARED_CTX = 'const ctx = ctx.input || {}; return 1;'; +const REDECLARED_LOCAL = 'let x = 1; let x = 2;'; + +const hook = (name: string, source: string, extra: Record = {}) => ({ + name, + object: 'hb_ticket', + events: ['beforeInsert'], + body: { language: 'js', source }, + ...extra, +}); + +const job = (name: string, source: string, extra: Record = {}) => ({ + name, + schedule: { type: 'interval', intervalMs: 60_000 }, + body: { language: 'js', source, capabilities: ['api.read'] }, + ...extra, +}); + +const ticket = { + name: 'hb_ticket', + label: 'Ticket', + sharingModel: 'private', + fields: { name: { type: 'text', label: 'Name' } }, +}; + +const compileFindings = (fs: readonly T[]): T[] => + fs.filter((f) => f.rule === HOOK_BODY_DOES_NOT_COMPILE || f.rule === JOB_BODY_DOES_NOT_COMPILE); + +describe('hook-body-does-not-compile / job-body-does-not-compile · the wrapper is the runtime\'s', () => { + it('compiles the body inside `(async (ctx) => { SOURCE })`, source on the first line', () => { + expect(hookBodyFunctionExpression('return 1;')).toBe('(async (ctx) => { return 1; })'); + }); + + it('refuses an uncompilable hook: `ctx` declared again is a SyntaxError in that wrapper', () => { + const [f, ...rest] = validateHookAndJobBodyCompiles({ hooks: [hook('stamp_owner', REDECLARED_CTX)] }); + expect(rest).toEqual([]); + expect([f.rule, f.severity, f.where, f.path]).toEqual([ + HOOK_BODY_DOES_NOT_COMPILE, + 'error', + 'hook "stamp_owner" › body', + 'hooks[0].body.source', + ]); + expect(f.message).toContain("SyntaxError: Identifier 'ctx' has already been declared"); + expect(f.message).toContain('line 1'); + expect(f.hint).toContain('`ctx` is already the parameter of the wrapper'); + }); + + it('refuses an uncompilable job the same way, under its own id and path', () => { + const [f, ...rest] = validateHookAndJobBodyCompiles({ jobs: [job('nightly_close', 'const a = 1;\n\n' + REDECLARED_LOCAL)] }); + expect(rest).toEqual([]); + expect([f.rule, f.severity, f.where, f.path]).toEqual([ + JOB_BODY_DOES_NOT_COMPILE, + 'error', + 'job "nightly_close" › body', + 'jobs[0].body.source', + ]); + expect(f.message).toContain("Identifier 'x' has already been declared"); + expect(f.message).toContain('line 3'); + expect(f.hint).toContain('async function whose parameter is `ctx`'); + }); + + it('…while the parse check on the same bodies reports nothing, which is why it never saw them', () => { + // `hook-body-source-unparseable` parses with the TypeScript parser, which reports no early error. + const parsed = validateHookBodyWrites({ + objects: [ticket], + hooks: [hook('a', REDECLARED_CTX), hook('b', REDECLARED_LOCAL)], + }); + expect(parsed.filter((f) => f.rule === HOOK_BODY_SOURCE_UNPARSEABLE)).toEqual([]); + expect(hostCompileFailure(hookBodyFunctionExpression(REDECLARED_LOCAL))?.error).toContain('already been declared'); + }); + + it('takes the action rule\'s severity split: a regular-expression pattern warns, its token is refused', () => { + const fs = validateHookAndJobBodyCompiles({ + hooks: [hook('h1', 'return /(?x)|(?y)/.test(ctx.input.s);'), hook('h2', 'return /abc;')], + jobs: [job('j1', 'return /a/gg;')], + }); + expect(fs.map((f) => [f.rule, f.severity, f.path])).toEqual([ + [HOOK_BODY_DOES_NOT_COMPILE, 'warning', 'hooks[0].body.source'], + [HOOK_BODY_DOES_NOT_COMPILE, 'error', 'hooks[1].body.source'], + [JOB_BODY_DOES_NOT_COMPILE, 'error', 'jobs[0].body.source'], + ]); + }); + + it('accepts bodies that compile, and skips L1 expression bodies and bodiless entries', () => { + const fs = validateHookAndJobBodyCompiles({ + hooks: [ + hook('ok1', 'var ctx2 = ctx; if (ctx.input.email) ctx.input.email = ctx.input.email.toLowerCase();'), + hook('ok2', 'const input = ctx.input || {}; return input;'), + hook('l1', REDECLARED_CTX, { body: { language: 'expression', source: REDECLARED_CTX } }), + { name: 'handler_only', object: 'hb_ticket', events: ['beforeInsert'], handler: 'stampOwner' }, + ], + jobs: [job('ok3', 'const rows = await ctx.api.object("hb_ticket").find({}); return { outcome: "ok", rows };')], + }); + expect(fs).toEqual([]); + }); + + it('locates a hook lowered from an inline handler at the key the author wrote', () => { + const lowered = hook('lowered', REDECLARED_LOCAL, { handler: 'hooks.lowered' }); + const [f] = validateHookAndJobBodyCompiles({ hooks: [lowered] }, { loweredHookRefs: new Set(['hooks.lowered']) }); + expect(f.path).toBe('hooks[0].handler'); + expect(f.message).toContain('lowered from the inline handler'); + }); + + it('never runs the body: a source that closes the wrapper early compiles and nothing in it executes', () => { + const g = globalThis as { __hookBodyCompileProbe?: number }; + delete g.__hookBodyCompileProbe; + const fs = validateHookAndJobBodyCompiles({ + hooks: [hook('p', '}); globalThis.__hookBodyCompileProbe = 1; ((ctx) => {')], + }); + expect(fs).toEqual([]); + expect(g.__hookBodyCompileProbe).toBeUndefined(); + }); + + it('os explain has a page for each id', () => { + expect(explainRule(HOOK_BODY_DOES_NOT_COMPILE)).toBeDefined(); + expect(explainRule(JOB_BODY_DOES_NOT_COMPILE)).toBeDefined(); + }); +}); + +describe('hook-body-does-not-compile / job-body-does-not-compile · the doors that run it', () => { + it('os validate, os build and os lint all refuse the uncompilable hook and the uncompilable job', () => { + const stack = { objects: [ticket], hooks: [hook('stamp_owner', REDECLARED_CTX)], jobs: [job('nightly_close', REDECLARED_LOCAL)] }; + for (const command of ['validate', 'build', 'lint'] as const) { + const fs = compileFindings(runAuthoringRules(command, { normalized: stack, parsed: stack })); + expect(fs.map((f) => [f.rule, f.severity, f.path]), command).toEqual([ + [HOOK_BODY_DOES_NOT_COMPILE, 'error', 'hooks[0].body.source'], + [JOB_BODY_DOES_NOT_COMPILE, 'error', 'jobs[0].body.source'], + ]); + } + }); + + it('the runtime publish door refuses a hook write carrying it, and admits one that compiles', () => { + const refused = runRuntimeAuthoringRules({ type: 'hook', item: hook('stamp_owner', REDECLARED_CTX), context: { objects: [ticket] } }); + expect(compileFindings(refused.errors).map((f) => [f.rule, f.severity])).toEqual([[HOOK_BODY_DOES_NOT_COMPILE, 'error']]); + expect(refused.rulesRun).toContain('validateHookAndJobBodyCompiles'); + + const admitted = runRuntimeAuthoringRules({ + type: 'hook', + item: hook('stamp_owner', 'const input = ctx.input || {}; return input;'), + context: { objects: [ticket] }, + }); + expect(compileFindings([...admitted.errors, ...admitted.advisories])).toEqual([]); + expect(admitted.rulesRun).toContain('validateHookAndJobBodyCompiles'); + }); +}); diff --git a/packages/lint/src/validate-hook-body-compiles.ts b/packages/lint/src/validate-hook-body-compiles.ts new file mode 100644 index 00000000000..7abe508df96 --- /dev/null +++ b/packages/lint/src/validate-hook-body-compiles.ts @@ -0,0 +1,139 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * An L2 hook body and an L2 job body must COMPILE in the wrapper the runtime + * runs them in. + * + * ## The failure this refuses + * + * The runtime runs a hook's or a job's `body.source` as the body of + * {@link hookBodyFunctionExpression} — `(async (ctx) => { SOURCE })` — never as + * a script of its own (`packages/runtime/src/sandbox/quickjs-runner.ts`; a job + * takes the hook's wrapper because it has no input to hand in). A source that + * is valid on its own can fail to compile there: `const ctx = …` or `let ctx` + * declares the wrapper's parameter a second time, a SyntaxError raised before + * any statement runs, and so is `let x = 1; let x = 2;` or any grammar error. + * Before this rule such a body passed `os validate`, `os build`, `os verify` + * and the publish door, and then every run of the hook or job failed, for as + * long as the metadata was deployed. + * + * The parse check on the same body (`hook-body-source-unparseable`) cannot see + * most of it: it parses the source with the TypeScript parser inside a + * synthesised `async function __body(ctx)`, and a parser reports no early + * error (a redeclaration is one) at all. + * + * ## How it judges + * + * Exactly the way `action-body-does-not-compile` judges an action body + * (`validate-action-body-compiles.ts`, whose module note measures the two + * engines against each other): the expression the runtime builds, from the same + * function, is compiled with the host engine as a script and never run, and the + * failure is read through the one {@link judgeBodyCompile}. So the severity + * split is the action rule's: a regular-expression PATTERN the host refuses is a + * `warning` (QuickJS's pattern dialect measurably differs from V8's there), and + * every other compile failure is an `error`. + * + * ## Two rule ids, one wrapper + * + * A hook finding is `hook-body-does-not-compile` and a job finding is + * `job-body-does-not-compile`: the id names the body kind, as the action rule's + * does, so `os explain` and a `suppressWarnings` entry address one kind. The + * walk is one: `hooks[*].body` and `jobs[*].body`, `language: 'js'` only (an L1 + * expression body is not run in this wrapper). + */ + +import { HOOK_BODY_PARAMETERS, hookBodyFunctionExpression } from './action-body-wrapper.js'; +import { bodyCompileHint, bodyCompileMessage, judgeBodyCompile } from './validate-action-body-compiles.js'; +import { hookBodyFindingLocation } from './validate-hook-body-writes.js'; +import { recordsOf } from './object-graph.js'; + +/** Rule id for a hook body. */ +export const HOOK_BODY_DOES_NOT_COMPILE = 'hook-body-does-not-compile'; + +/** Rule id for a job body. */ +export const JOB_BODY_DOES_NOT_COMPILE = 'job-body-does-not-compile'; + +export interface HookBodyCompileFinding { + /** `error`, except a regular-expression PATTERN the host refuses (`warning`). */ + severity: 'error' | 'warning'; + rule: string; + /** e.g. `hook "stamp_owner" › body`, `job "nightly_close" › body`. */ + where: string; + /** e.g. `hooks[0].body.source`, `hooks[0].handler` (lowered), `jobs[0].body.source`. */ + path: string; + message: string; + hint: string; +} + +type AnyRec = Record; + +const isRec = (v: unknown): v is AnyRec => !!v && typeof v === 'object' && !Array.isArray(v); + +/** The L2 source of a hook or job body, or `undefined` when there is nothing to compile. */ +function scriptSource(body: unknown): string | undefined { + if (!isRec(body) || body.language !== 'js') return undefined; + return typeof body.source === 'string' && body.source.trim() !== '' ? body.source : undefined; +} + +const OTHER_FIX = + 'Fix body.source so it compiles as the statements of an async function whose parameter is `ctx`'; + +/** + * Every L2 hook body and job body that does not compile in the runtime's + * `(ctx)` wrapper. Pure `(stack) => Finding[]` (ADR-0019); safe on pre- or + * post-parse stacks. `ctx.loweredHookRefs` locates a hook whose body the build + * lowered from an inline `handler` at `hooks[i].handler`, the key the author + * wrote ({@link hookBodyFindingLocation}). + */ +export function validateHookAndJobBodyCompiles( + stack: AnyRec, + ctx?: { loweredHookRefs?: ReadonlySet }, +): HookBodyCompileFinding[] { + const findings: HookBodyCompileFinding[] = []; + if (!isRec(stack)) return findings; + + recordsOf(stack.hooks).forEach((hook, index) => { + const source = scriptSource(hook.body); + if (source === undefined) return; + const verdict = judgeBodyCompile(hookBodyFunctionExpression(source), HOOK_BODY_PARAMETERS); + if (!verdict) return; + const name = typeof hook.name === 'string' && hook.name ? hook.name : `#${index}`; + const loc = hookBodyFindingLocation(hook, index, ctx); + findings.push({ + severity: verdict.severity, + rule: HOOK_BODY_DOES_NOT_COMPILE, + where: `hook "${name}" › body`, + path: loc.path, + message: bodyCompileMessage(verdict, hookBodyFunctionExpression('…'), 'this hook') + loc.messageSuffix, + hint: bodyCompileHint(verdict, { + redeclared: (parameter) => + `\`${parameter}\` is already the parameter of the wrapper: use it as it is (the hook's record is ` + + `\`ctx.input\`), or give the local another name, e.g. \`const input = ctx.input || {}\``, + other: OTHER_FIX, + }), + }); + }); + + recordsOf(stack.jobs).forEach((job, index) => { + const source = scriptSource(job.body); + if (source === undefined) return; + const verdict = judgeBodyCompile(hookBodyFunctionExpression(source), HOOK_BODY_PARAMETERS); + if (!verdict) return; + const name = typeof job.name === 'string' && job.name ? job.name : `#${index}`; + findings.push({ + severity: verdict.severity, + rule: JOB_BODY_DOES_NOT_COMPILE, + where: `job "${name}" › body`, + path: `jobs[${index}].body.source`, + message: bodyCompileMessage(verdict, hookBodyFunctionExpression('…'), 'this job'), + hint: bodyCompileHint(verdict, { + redeclared: (parameter) => + `\`${parameter}\` is already the parameter of the wrapper: use it as it is (a job reaches data ` + + `through \`ctx.api\`), or give the local another name, e.g. \`const api = ctx.api\``, + other: OTHER_FIX, + }), + }); + }); + + return findings; +} diff --git a/packages/runtime/src/sandbox/quickjs-runner.ts b/packages/runtime/src/sandbox/quickjs-runner.ts index 82740de8143..f7ff1870dda 100644 --- a/packages/runtime/src/sandbox/quickjs-runner.ts +++ b/packages/runtime/src/sandbox/quickjs-runner.ts @@ -41,7 +41,7 @@ import { import { resolveSandboxTimeoutMs, sandboxBusinessMessage, isEngineDuplicateRecordEnvelope, INTERNAL_ERROR_MESSAGE } from '@objectstack/types'; import type { HookBody, ScriptBody, ExpressionBody, HookBodyCapability } from '@objectstack/spec/data'; import { isUnlandedWriteRefusal } from '@objectstack/objectql'; -import { actionBodyFunctionExpression } from '@objectstack/lint/runtime'; +import { actionBodyFunctionExpression, hookBodyFunctionExpression } from '@objectstack/lint/runtime'; import type { ScriptContext, ScriptOrigin, @@ -415,10 +415,13 @@ export class QuickJSScriptRunner implements ScriptRunner { // hand in as a first parameter, and `JobSchema.body` documents `ctx` as // the whole surface. Only an action body is `(input, ctx)`. // - // The action wrapper is `actionBodyFunctionExpression` from - // `@objectstack/lint/runtime`, the expression the author-time rule - // `action-body-does-not-compile` compiles a body inside, so the two - // cannot disagree about it. ⛔ Never spell it inline here again. + // Both wrappers come from `@objectstack/lint/runtime`: + // `hookBodyFunctionExpression` (hooks, jobs) and + // `actionBodyFunctionExpression`, the expressions the author-time rules + // `hook-body-does-not-compile` / `job-body-does-not-compile` and + // `action-body-does-not-compile` compile a body inside, so the check and + // the run cannot disagree about a wrapper. ⛔ Never spell either inline + // here again. // // [#23702] `SETTLE` attaches the same two handlers the bare `.then(…)` // did and hands back the BODY's own promise as the script's completion @@ -429,7 +432,7 @@ export class QuickJSScriptRunner implements ScriptRunner { const SETTLE = '((p, onOk, onErr) => (p.then(onOk, onErr), p))'; const wrapped = args.origin.kind !== 'action' ? `globalThis.__result = undefined; globalThis.__error = undefined; globalThis.__errorInfo = undefined; globalThis.__errorRefusal = undefined; globalThis.__errorFromHost = undefined; - ${SETTLE}((async (ctx) => { ${args.source} })(globalThis.__ctx), + ${SETTLE}(${hookBodyFunctionExpression(args.source)}(globalThis.__ctx), function(v){ globalThis.__result = JSON.stringify(v === undefined ? null : v); }, ${REJECT_HANDLER} );` From f58a65afe9f2f8de51313cbc4be6c5e59a4ce30d Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 00:13:39 +0000 Subject: [PATCH 2/3] fix(lint)!: register the hook/job compile refusal, document it, add its changeset Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01L6bhgTggz8AL2bCABoDGis --- .../34987-hook-job-body-does-not-compile.md | 26 ++++++++++ content/docs/automation/hook-bodies.mdx | 1 + ...18.action-body-does-not-compile-refused.ts | 3 +- ....hook-job-body-does-not-compile-refused.ts | 49 +++++++++++++++++++ 4 files changed, 78 insertions(+), 1 deletion(-) create mode 100644 .changeset/34987-hook-job-body-does-not-compile.md create mode 100644 packages/spec/src/migrations/entries/semantic/18.hook-job-body-does-not-compile-refused.ts diff --git a/.changeset/34987-hook-job-body-does-not-compile.md b/.changeset/34987-hook-job-body-does-not-compile.md new file mode 100644 index 00000000000..57aeed09cbe --- /dev/null +++ b/.changeset/34987-hook-job-body-does-not-compile.md @@ -0,0 +1,26 @@ +--- +'@objectstack/lint': minor +'@objectstack/runtime': minor +'@objectstack/spec': minor +--- + +fix(lint)!: a hook body or job body that does not compile in the wrapper the runtime runs it in is refused + +Clause-②: no (narrowing) +Metadata-protocol: narrowed +Skills-docs: follow-up owed — skills/objectstack-data/references/data-hooks.md (its "Sandbox restrictions" section teaches what a body may contain and names no compile check) + + + +**BREAKING** only for a hook or job body that never ran. The runtime runs an L2 hook body and an L2 job body (`body.language: 'js'`) as the body of `(async (ctx) => { … })`. A source that does not compile there, such as `const ctx = ctx.input || {}` (the parameter declared again) or `let x = 1; let x = 2;`, raised a SyntaxError before its first statement on every run, yet passed `os validate`, `os build`, `os lint` and the runtime publish door: the hook parse check reads the source with a parser, which reports no redeclaration, and a job body had no check at all. + +What moves (FROM → TO): + +- New gating rule `validateHookAndJobBodyCompiles` (`@objectstack/lint`), rule ids `hook-body-does-not-compile` and `job-body-does-not-compile`: FROM no finding TO `error` at `os validate`, `os build`, `os lint`, and at the runtime publish door for `hook` writes (`422 INVALID_METADATA`). No door publishes a job, so a job body is refused by the three commands. A hook lowered from an inline `handler` is located at `hooks[N].handler`. The severity split is `action-body-does-not-compile`'s, read through the same `judgeBodyCompile`: a regular-expression pattern the host engine refuses is a `warning`, and every other compile failure is an `error`. +- `hookBodyFunctionExpression` and `HOOK_BODY_PARAMETERS` (`@objectstack/lint`, the first also on `@objectstack/lint/runtime`): the one spelling of the `(ctx)` wrapper. The runtime's QuickJS runner now builds the hook and job wrapper from it, byte for byte the wrapper it built before, so the check and the run cannot disagree about it. +- `judgeBodyCompile`, `BodyCompileVerdict` and `BodyCompileShape` (`@objectstack/lint`): the compile-and-classify core both rules share. `action-body-does-not-compile` reads it with unchanged findings. +- `os explain hook-body-does-not-compile` and `os explain job-body-does-not-compile` explain both rules. + +The fix: use `ctx` as it is, or give the local another name (`const input = ctx.input || {}` in a hook, `const api = ctx.api` in a job); declare each name once; fix any other compile error at the line of `body.source` the finding names. + +No conversion is made (ADR-0087 D3, entry `hook-job-body-does-not-compile-refused`): which name the author meant for the local is a judgement. Measured first-party exposure: zero. diff --git a/content/docs/automation/hook-bodies.mdx b/content/docs/automation/hook-bodies.mdx index 035f8675ef2..32535bfe7df 100644 --- a/content/docs/automation/hook-bodies.mdx +++ b/content/docs/automation/hook-bodies.mdx @@ -228,6 +228,7 @@ Static validation around a hook is asymmetric, and it is worth knowing exactly w - **Checked — writes to a system column the object has no storage for.** Since [#8663](https://github.com/objectstack-ai/objectstack/issues/8663), a write to an injected system column is no longer exempted on the strength of its NAME alone. The registry injects `owner_id` / `organization_id` / the audit family onto an ADR-0015 [`external` object](/docs/data-modeling/external-datasources) exactly as onto a local one, but the remote database owns that schema and no column exists behind them. Writing one raises `hook-body-write-unprovisioned-anchor` (or `action-body-write-unprovisioned-anchor` / `flow-node-write-unprovisioned-anchor` on the other two surfaces) — a **warning** on all three, including the flow-node rule that otherwise gates, because the claim is about a remote schema the build cannot see. A column you **declare** yourself is untouched: on a federated object a declared `owner_id` maps a remote column you vouch for. Why it matters more than an ordinary typo: an undeclared name is refused upstream by the engine's own write-path validator (`INVALID_FIELD`), whereas the injected anchor is in the registered schema and passes it — so it is the one payload key that reaches the remote database raw, where a SQL remote aborts the **whole statement** with an untyped `no such column` and takes the correctly named fields of the same payload with it. - **Checked — writes that reach nothing at all.** Since [#4345](https://github.com/objectstack-ai/objectstack/issues/4345), an action body assigning to `ctx.record` raises `action-record-write-discarded`, also a warning. This one is **not** a field-resolution question: an action's `ctx.record` is a snapshot the runtime never writes back, so the assignment is discarded whether or not the field is declared — see [Signature conventions](#signature-conventions) below. - **Checked — an action body compiles in its wrapper.** An action body runs as the body of `(async (input, ctx) => { … })`, so `input` and `ctx` are parameters the body shares a scope with. A body that does not compile there — `const input = ctx.input || {}` redeclares a parameter, a syntax error — raises `action-body-does-not-compile`, an **error** under `os validate`, `os build`, `os lint` and the runtime publish door (`action` and `object` writes), naming the action and the compile error. Read the params as `input`, or name the local differently (`const params = ctx.input || {}`); `var input = …` compiles. The check compiles the body inside the same expression the runtime builds, without running it, with the host's JavaScript engine; a regular-expression pattern that engine refuses is a warning, because the two pattern dialects measurably differ (the runtime's QuickJS accepts duplicate named groups and modifier groups), while a literal that never closes on its line, or whose flags are not a flag set, is an error like any other compile failure. An action whose body still fails to compile at run time answers `500 INTERNAL_ERROR` with a sentence naming the action and the compile error, never a bare `Internal server error`. +- **Checked — a hook or job body compiles in its wrapper.** A hook body and a job body both run as the body of `(async (ctx) => { … })`: a job has no input to hand in, so `ctx` is its one parameter. A body that does not compile there — `const ctx = …` or `let ctx` redeclares the parameter, `let x = 1; let x = 2;` declares a name twice, or any grammar error — raises `hook-body-does-not-compile` or `job-body-does-not-compile`, an **error** under `os validate`, `os build` and `os lint`, naming the hook or job and the compile error; the runtime publish door refuses a `hook` write carrying one (no door publishes a job). Use `ctx` as it is, or give the local another name (`const input = ctx.input || {}`). The check is the action check's, over the hook's own wrapper: the same expression the runtime builds, compiled without running it, with the same warning for a regular-expression pattern the host's engine refuses. The parse check on a hook body (`hook-body-source-unparseable`) uses a parser, which reports no redeclaration, so it passes most bodies this check refuses. Four literal write shapes are recognized, and only these: diff --git a/packages/spec/src/migrations/entries/semantic/18.action-body-does-not-compile-refused.ts b/packages/spec/src/migrations/entries/semantic/18.action-body-does-not-compile-refused.ts index 45932c0265c..2b60c3a3c5a 100644 --- a/packages/spec/src/migrations/entries/semantic/18.action-body-does-not-compile-refused.ts +++ b/packages/spec/src/migrations/entries/semantic/18.action-body-does-not-compile-refused.ts @@ -36,7 +36,8 @@ export const entry: SemanticMigration = { + 'runtime builds, from the same function, with the host JavaScript engine and without running it. The host ' + 'engine and the runtime\'s QuickJS agreed on every early error probed except regular-expression patterns, ' + 'hence the warning there. Such a body never ran, so no run of it ever succeeded and no stored row changes ' - + 'shape. Hook and job bodies, which run in a different wrapper, are not judged. No first-party stack (example ' + + 'shape. Hook and job bodies run in a different wrapper and are judged by their own rules ' + + '(hook-job-body-does-not-compile-refused). No first-party stack (example ' + 'apps, skills, docs samples) carries such a body today. There is no mechanical rewrite: renaming a local is ' + 'a choice about which name the rest of the body reads.', acceptanceCriteria: diff --git a/packages/spec/src/migrations/entries/semantic/18.hook-job-body-does-not-compile-refused.ts b/packages/spec/src/migrations/entries/semantic/18.hook-job-body-does-not-compile-refused.ts new file mode 100644 index 00000000000..ef768456d95 --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/18.hook-job-body-does-not-compile-refused.ts @@ -0,0 +1,49 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// #34987 — an L2 hook body and an L2 job body (`body.language: 'js'`) must +// compile as the body of the wrapper the runtime runs both in, an async arrow +// function whose one parameter is `ctx`: one that does not is refused at error +// as `hook-body-does-not-compile` / `job-body-does-not-compile` +// (@objectstack/lint), the check `action-body-does-not-compile` already makes +// for an action body, with the same severity split. It narrows what the +// authoring doors accept; no key is removed, so there is no tombstone. +// Measured first-party exposure at this change: zero — no example app, skill or +// docs sample carries a hook or job body that fails to compile there (one docs +// sample elides its body with an ellipsis; it is prose, not metadata). Not +// converted: which name the author meant for the local is a judgement. +export const entry: SemanticMigration = { + id: 'hook-job-body-does-not-compile-refused', + surface: + 'hooks[].body.source and jobs[].body.source whose body.language is js, on a hook saved or published through ' + + 'the metadata doors (PUT /api/v1/meta/hook/NAME, POST /api/v1/packages/PKG/publish-drafts and the per-item ' + + 'publish) or a hook or job loaded by os validate / os build / os lint, a hook body lowered from an inline ' + + 'handler included: a source that does not compile as the statements of the async arrow function the runtime ' + + 'wraps it in, whose one parameter is ctx. The common cases declare ctx a second time (const ctx = …, let ctx), ' + + 'declare one name twice with let or const, or carry a grammar error', + replacement: + 'Write the body as the statements of an async function whose parameter is ctx (the context): use ctx as it is, ' + + 'or give the local another name (const input = ctx.input || {} in a hook, const api = ctx.api in a job), and ' + + 'declare each name once. Fix any other compile error the finding names at the line of body.source it names. ' + + 'Refused at error as `hook-body-does-not-compile` or `job-body-does-not-compile` (422 INVALID_METADATA at the ' + + 'hook door). A regular expression whose pattern the host engine refuses is reported at warning, never ' + + 'refused; a literal that never closes or whose flags are not a flag set is refused.', + reason: + 'The runtime never runs a hook or job body.source as a script of its own: it compiles it inside an async arrow ' + + 'function with the one parameter ctx, and a source that redeclares it, or otherwise fails to compile there, ' + + 'raises a SyntaxError before its first statement. Every authoring door accepted such a body (the hook parse ' + + 'check reads the source with a parser, which reports no redeclaration or other early error, and a job body ' + + 'had no check at all), so it deployed clean and then every run of the hook or job failed for as long as it ' + + 'stayed deployed. The rule compiles the source inside the expression the runtime builds, from the same ' + + 'function, with the host JavaScript engine and without running it, and reads the failure exactly as the ' + + 'action rule does. No door publishes a job at run time, so a job body is refused by the three CLI commands. ' + + 'Such a body never ran, so no run of it ever succeeded and no stored row changes shape. No first-party stack ' + + '(example apps, skills, docs samples) carries such a body today. There is no mechanical rewrite: renaming a ' + + 'local is a choice about which name the rest of the body reads.', + acceptanceCriteria: + 'Load every hook and job (`os validate` or `os build`): no `hook-body-does-not-compile` finding at error at ' + + 'hooks[N].body.source or hooks[N].handler, and no `job-body-does-not-compile` finding at error at ' + + 'jobs[N].body.source. PUT /api/v1/meta/hook/NAME with each such hook body corrected answers 200, and the ' + + 'hook runs on its next event instead of failing it.', +}; From e1209577f0c435f6cd645404c63c6604a6cd3d90 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 00:34:09 +0000 Subject: [PATCH 3/3] docs: the author-time rule count reads 74, and the door table lists the hook/job compile check Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01L6bhgTggz8AL2bCABoDGis --- content/docs/deployment/cli.mdx | 2 +- content/docs/deployment/validating-metadata.mdx | 3 ++- content/docs/getting-started/build-with-claude-code.mdx | 2 +- content/docs/ui/react-pages.mdx | 2 +- 4 files changed, 5 insertions(+), 4 deletions(-) diff --git a/content/docs/deployment/cli.mdx b/content/docs/deployment/cli.mdx index 66304b6fef6..859be8420f0 100644 --- a/content/docs/deployment/cli.mdx +++ b/content/docs/deployment/cli.mdx @@ -928,7 +928,7 @@ os compile --json # JSON output for CI pipelines → Normalizing stack definition... → Lowering inline handlers... → Validating protocol compliance... - → Running author-time rules (73)... + → Running author-time rules (74)... → Checking that every required capability has a provider installable in this edition... → Collecting package docs (ADR-0046)... 0 collected → Writing artifact... diff --git a/content/docs/deployment/validating-metadata.mdx b/content/docs/deployment/validating-metadata.mdx index 1a9178bc5b7..1d35c002e64 100644 --- a/content/docs/deployment/validating-metadata.mdx +++ b/content/docs/deployment/validating-metadata.mdx @@ -520,6 +520,7 @@ orthogonal to both, and no cell here can carry it; it is written out in | Page variable declarations — each name once and never blank, a `defaultValue` of its declared type, a `source` naming a component the page holds (#28663, #28725) | ✓ | ✓ | ✓ | ✓ᵖ | | JSX / React page source parses (ADR-0080/0081) | ✓ | ✓ | ✓ | — | | Script action bodies compile in the runtime's wrapper — an L2 action's `body.source` that does not compile as the body of `(async (input, ctx) => { … })`, most often `const input = …` redeclaring a parameter; an object write runs it over its inline `actions[]`, so an object write cannot republish a refused body (`action-body-does-not-compile`, #34884) | ✓ | ✓ | ✓ | ✓ᵃᶜᵒ | +| Hook and job bodies compile in the runtime's wrapper — an L2 hook or job `body.source` that does not compile as the body of `(async (ctx) => { … })`, most often `const ctx = …` redeclaring the parameter or one name declared twice; no door publishes a job, so the publish column is the `hook` write alone (`hook-body-does-not-compile`, `job-body-does-not-compile`, #34987) | ✓ | ✓ | ✓ | ✓ʰ | | Approval-node approvers (ADR-0090 D3) | ✓ | ✓ | ✓ | ✓ᶠ | | Security posture (ADR-0090 — e.g. every custom object declares `sharingModel`) | ✓ | ✓ | ✓ | ✓ˢᵖᵉᵇᵒ | | Security vocabulary freeze (ADR-0090 D3 — the reserved word, replaced by `permission_set` / `position` / `business_unit`) | ✓ | ✓ | ✓ | ✓ᵒᵖᵉᵇᵖᵒᵃᵒˣ | @@ -866,7 +867,7 @@ A clean run walks the registry and reports timing: Config: /path/to/support-desk/objectstack.config.ts Load time: 21ms → Validating against ObjectStack Protocol... - → Running author-time rules (73)... + → Running author-time rules (74)... → Checking that every required capability has a provider installable in this edition... → Checking package docs (ADR-0046)... diff --git a/content/docs/getting-started/build-with-claude-code.mdx b/content/docs/getting-started/build-with-claude-code.mdx index 26b9cca3739..6f5431ddc86 100644 --- a/content/docs/getting-started/build-with-claude-code.mdx +++ b/content/docs/getting-started/build-with-claude-code.mdx @@ -311,7 +311,7 @@ visible: 'status != "resolved"' ◆ Validate ──────────────────────────────────────── → Validating against ObjectStack Protocol... - → Running author-time rules (73)... + → Running author-time rules (74)... ✗ Author-time rules failed (1 issue) • stack · action 'resolve_ticket' visible: bare reference `status` — a diff --git a/content/docs/ui/react-pages.mdx b/content/docs/ui/react-pages.mdx index 4da1da497c2..2be905415ba 100644 --- a/content/docs/ui/react-pages.mdx +++ b/content/docs/ui/react-pages.mdx @@ -404,7 +404,7 @@ objectstack validate ──────────────────────────────────────── → Loading configuration... → Validating against ObjectStack Protocol... - → Running author-time rules (73)... + → Running author-time rules (74)... → Checking that every required capability has a provider installable in this edition... → Checking package docs (ADR-0046)...