From 693d937587319330ad14a3775b32e56c9d5de431 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 19:29:09 +0000 Subject: [PATCH 1/9] feat(lint, runtime): an action body that cannot compile in its wrapper is refused, and answers naming itself WIP: rule, registry entry, explanation, runner wiring. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufziunkXbDT7wUWqfmWz --- packages/lint/src/action-body-wrapper.ts | 39 ++++ packages/lint/src/authoring-rules.ts | 23 +++ packages/lint/src/index.ts | 11 ++ packages/lint/src/rule-explanations.ts | 22 +++ packages/lint/src/runtime.ts | 5 + .../src/validate-action-body-compiles.test.ts | 151 ++++++++++++++++ .../lint/src/validate-action-body-compiles.ts | 168 ++++++++++++++++++ .../runtime/src/sandbox/quickjs-runner.ts | 52 +++++- 8 files changed, 470 insertions(+), 1 deletion(-) create mode 100644 packages/lint/src/action-body-wrapper.ts create mode 100644 packages/lint/src/validate-action-body-compiles.test.ts create mode 100644 packages/lint/src/validate-action-body-compiles.ts diff --git a/packages/lint/src/action-body-wrapper.ts b/packages/lint/src/action-body-wrapper.ts new file mode 100644 index 00000000000..bdf6ae21ced --- /dev/null +++ b/packages/lint/src/action-body-wrapper.ts @@ -0,0 +1,39 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The one spelling of the wrapper an L2 action 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 + * (`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. + * + * 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. + * + * Hook and job bodies run in a different wrapper, `(async (ctx) => { … })`, and + * are not described here. + * + * No imports: the runtime reaches this module through `@objectstack/lint/runtime`. + */ + +/** The parameters an action body's wrapper binds, in call order: the params bag, then the context. */ +export const ACTION_BODY_PARAMETERS = ['input', 'ctx'] as const; + +/** + * The function expression an action body runs as: `(async (input, ctx) => { SOURCE })`. + * + * The source is placed after the opening brace on the expression's FIRST line, + * so line N of the source is line N of the expression; a compile error's line + * number therefore reads directly as a line of `body.source`. + */ +export function actionBodyFunctionExpression(source: string): string { + return `(async (${ACTION_BODY_PARAMETERS.join(', ')}) => { ${source} })`; +} diff --git a/packages/lint/src/authoring-rules.ts b/packages/lint/src/authoring-rules.ts index d8b5e886c9a..58b505b7a34 100644 --- a/packages/lint/src/authoring-rules.ts +++ b/packages/lint/src/authoring-rules.ts @@ -149,6 +149,7 @@ import { type MembershipKeyOwners, } from './validate-membership-key-declarations.js'; import { validateRuleCompilability } from './validate-rule-compilability.js'; +import { validateActionBodyCompiles } from './validate-action-body-compiles.js'; import { validateRuleSchemaFormats } from './validate-rule-schema-formats.js'; import { validateActionLocations } from './validate-action-locations.js'; import { lintFlowPatterns } from './lint-flow-patterns.js'; @@ -2888,6 +2889,28 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [ runtimeTypes: ['object', 'object_extension'], run: (stack) => validateRuleCompilability(stack), }, + // An L2 action body that does not compile in the wrapper the runtime runs it + // in (`(async (input, ctx) => { SOURCE })`, built from the same function the + // rule compiles inside). Such a body passed every author-time door and then + // failed every run, on every door; `const input = ctx.input || {}` is the + // shape an AI author writes, a redeclared parameter. Gating: no reading of + // the metadata behaves as written, because the body never starts. A + // regular-expression literal the host refuses is the one `warning` arm (the + // two engines' regular-expression dialects measurably differ; see the + // module). Across the runtime publish gate for `action` writes and for + // `object` writes, whose inline `actions[]` the same walk reads; the + // differential charges a write only with the bodies it adds. The rule loads + // no dependency: compiling goes through the host's `node:vm`. + { + name: 'validateActionBodyCompiles', + tier: 'gating', + input: 'parsed', + commands: ALL, + source: 'packages/lint/src/validate-action-body-compiles.ts', + surfaces: CLI_AND_RUNTIME, + runtimeTypes: ['action', 'object'], + run: (stack) => validateActionBodyCompiles(stack), + }, // #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 321b63564a7..48bed036b98 100644 --- a/packages/lint/src/index.ts +++ b/packages/lint/src/index.ts @@ -1020,6 +1020,17 @@ export type { ActionBodyWriteExclusion, } from './validate-action-body-writes.js'; +// An action body must compile in the wrapper the runtime runs it in, which the +// runtime builds from `actionBodyFunctionExpression` — the same function the +// rule compiles inside, so the two cannot disagree about the wrapper. +export { + validateActionBodyCompiles, + hostCompileFailure, + 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'; + // 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 // implicit-field set so all three agree on what is writable without being diff --git a/packages/lint/src/rule-explanations.ts b/packages/lint/src/rule-explanations.ts index 4f0a88033d8..9d3123c48cd 100644 --- a/packages/lint/src/rule-explanations.ts +++ b/packages/lint/src/rule-explanations.ts @@ -1458,6 +1458,27 @@ const ACTION_BODY_SOURCE_UNPARSEABLE_EXPLANATION: RuleExplanation = { ], }; +const ACTION_BODY_DOES_NOT_COMPILE_EXPLANATION: RuleExplanation = { + rule: 'action-body-does-not-compile', + covers: 'the wrapper an action body is compiled in', + paragraphs: [ + 'An action body is not a script of its own. The runtime pastes `body.source` into the body of ' + + '`(async (input, ctx) => { … })` and calls it with the action\'s params and its context, so the ' + + 'statements share a scope with two parameters the author never wrote. A source that is valid on its ' + + 'own can fail to compile there, and then every run of the action fails, on every door, before any ' + + 'statement runs.', + 'The common case is declaring a parameter again: `const input = ctx.input || {}` or `let ctx = …` is a ' + + 'redeclaration, a SyntaxError. Read the params as `input` (they are also `ctx.input`), or give the ' + + 'local another name. `var input = …` is not a redeclaration and compiles.', + '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. The runtime\'s engine is QuickJS. ' + + 'The two agree on redeclarations, grammar and strict-mode errors; they measurably differ on regular ' + + 'expressions, so a regular-expression literal the host refuses is reported as a warning rather than ' + + 'refused. Syntax the host accepts and QuickJS does not is not caught here; at run time such an ' + + 'action answers a 500 that names the action and the compile error.', + ], +}; + const ACTION_BODY_WRITE_UNPROVISIONED_ANCHOR_EXPLANATION: RuleExplanation = { rule: 'action-body-write-unprovisioned-anchor', covers: 'why a write to an unprovisioned anchor never lands', @@ -6300,6 +6321,7 @@ export const RULE_EXPLANATIONS: Readonly> = Obje [ACTION_BODY_WRITE_UNKNOWN_FIELD_EXPLANATION.rule]: ACTION_BODY_WRITE_UNKNOWN_FIELD_EXPLANATION, [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, [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 ca7dea462b9..f434443ddd1 100644 --- a/packages/lint/src/runtime.ts +++ b/packages/lint/src/runtime.ts @@ -97,3 +97,8 @@ 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'; diff --git a/packages/lint/src/validate-action-body-compiles.test.ts b/packages/lint/src/validate-action-body-compiles.test.ts new file mode 100644 index 00000000000..65198be4449 --- /dev/null +++ b/packages/lint/src/validate-action-body-compiles.test.ts @@ -0,0 +1,151 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { describe, expect, it } from 'vitest'; +import { + ACTION_BODY_DOES_NOT_COMPILE, + hostCompileFailure, + validateActionBodyCompiles, +} from './validate-action-body-compiles.js'; +import { actionBodyFunctionExpression } from './action-body-wrapper.js'; +import { runAuthoringRules } from './authoring-rules.js'; +import { runRuntimeAuthoringRules } from './runtime-gate.js'; + +/** The body the card's scenario run authored, byte for byte. */ +const CARD_BODY = 'const input = ctx.input || {}; return 1;'; + +const scriptAction = (name: string, source: string, extra: Record = {}) => ({ + name, + label: 'Probe', + objectName: 'ab_ticket', + type: 'script', + locations: [], + body: { language: 'js', source }, + ...extra, +}); + +const ticket = (actions: unknown[] = []) => ({ + name: 'ab_ticket', + label: 'Ticket', + sharingModel: 'private', + fields: { name: { type: 'text', label: 'Name' } }, + actions, +}); + +const compileFindings = (fs: readonly T[]): T[] => + fs.filter((f) => f.rule === ACTION_BODY_DOES_NOT_COMPILE); + +describe('action-body-does-not-compile · the wrapper is the runtime\'s', () => { + it('compiles the body inside `(async (input, ctx) => { SOURCE })`, source on the first line', () => { + expect(actionBodyFunctionExpression('return 1;')).toBe('(async (input, ctx) => { return 1; })'); + }); + + it('refuses the card\'s body: `input` declared again is a SyntaxError in that wrapper', () => { + const [f, ...rest] = validateActionBodyCompiles({ actions: [scriptAction('decide_approval_step', CARD_BODY)] }); + expect(rest).toEqual([]); + expect(f.severity).toBe('error'); + expect(f.rule).toBe(ACTION_BODY_DOES_NOT_COMPILE); + expect(f.where).toBe('action "decide_approval_step" › body'); + expect(f.path).toBe('actions[0].body.source'); + expect(f.message).toContain('SyntaxError'); + expect(f.message).toContain("'input'"); + expect(f.message).toContain('line 1'); + expect(f.hint).toContain('`input` is already a parameter of the wrapper'); + }); + + it('…while the same source compiles on its own, which is why no parse check saw it', () => { + expect(hostCompileFailure(CARD_BODY)).toBeUndefined(); + }); + + it('refuses `let ctx` the same way, and names the line of body.source', () => { + const [f] = validateActionBodyCompiles({ actions: [scriptAction('p', 'const a = 1;\n\nlet ctx = a;\nreturn ctx;')] }); + expect(f.severity).toBe('error'); + expect(f.message).toContain('line 3'); + expect(f.hint).toContain('`ctx` is already a parameter'); + }); + + it('refuses a body that does not parse at all', () => { + const [f] = validateActionBodyCompiles({ actions: [scriptAction('p', 'return {')] }); + expect(f.severity).toBe('error'); + expect(f.hint).toContain('async function whose parameters are `input` and `ctx`'); + }); + + it('refuses `new.target`, which the wrapper, compiled as a script, does not allow', () => { + expect(validateActionBodyCompiles({ actions: [scriptAction('p', 'new.target; return 1;')] })).toHaveLength(1); + }); + + it('accepts bodies that compile: `var input`, reading the params, a function named like a parameter', () => { + const actions = [ + scriptAction('a1', 'var input = ctx.input || {}; return input;'), + scriptAction('a2', 'const params = input || {}; return params.amount;'), + scriptAction('a3', 'function input2() {} return await Promise.resolve(input2);'), + scriptAction('a4', 'return { ok: true };'), + ]; + expect(validateActionBodyCompiles({ actions })).toEqual([]); + }); + + it('reports a regular-expression literal the host refuses as a warning, never a refusal', () => { + const [f] = validateActionBodyCompiles({ actions: [scriptAction('p', 'return /(/.test(input.s);')] }); + expect(f.severity).toBe('warning'); + expect(f.message).toContain('regular expression'); + }); + + it('never runs the body: a source that closes the wrapper early compiles and nothing in it executes', () => { + const g = globalThis as { __actionBodyCompileProbe?: number }; + delete g.__actionBodyCompileProbe; + const findings = validateActionBodyCompiles({ + actions: [scriptAction('p', '}); globalThis.__actionBodyCompileProbe = 1; ((x) => {')], + }); + expect(findings).toEqual([]); + expect(g.__actionBodyCompileProbe).toBeUndefined(); + }); + + it('walks object-inline actions, a merged action once, and skips non-script and non-js bodies', () => { + const bad = scriptAction('dup', CARD_BODY); + const findings = validateActionBodyCompiles({ + actions: [bad, { ...scriptAction('modal', CARD_BODY), type: 'modal' }], + objects: [ticket([bad, { ...scriptAction('other', 'x'), body: { language: 'formula', source: CARD_BODY } }])], + }); + expect(findings.map((f) => f.path)).toEqual(['actions[0].body.source']); + }); +}); + +describe('action-body-does-not-compile · the doors that run it', () => { + it('os validate, os build and os lint all refuse the card\'s body', () => { + const stack = { objects: [ticket()], actions: [scriptAction('decide_approval_step', CARD_BODY)] }; + for (const command of ['validate', 'build', 'lint'] as const) { + const fs = compileFindings(runAuthoringRules(command, { normalized: stack, parsed: stack })); + expect(fs.map((f) => [f.severity, f.path]), command).toEqual([['error', 'actions[0].body.source']]); + } + }); + + it('the runtime publish door refuses an action write carrying it, and admits one that compiles', () => { + const refused = runRuntimeAuthoringRules({ + type: 'action', + item: scriptAction('decide_approval_step', CARD_BODY), + context: { objects: [ticket()] }, + }); + expect(compileFindings(refused.errors)).toHaveLength(1); + expect(refused.rulesRun).toContain('validateActionBodyCompiles'); + + const admitted = runRuntimeAuthoringRules({ + type: 'action', + item: scriptAction('decide_approval_step', 'const params = input || {}; return 1;'), + context: { objects: [ticket()] }, + }); + expect(compileFindings([...admitted.errors, ...admitted.advisories])).toEqual([]); + }); + + it('the object door refuses an object write whose inline action does not compile', () => { + const r = runRuntimeAuthoringRules({ type: 'object', item: ticket([scriptAction('p', CARD_BODY)]), context: { objects: [] } }); + expect(compileFindings(r.errors)).toHaveLength(1); + }); + + it('an unrelated write is not charged with a stored action body that does not compile', () => { + const r = runRuntimeAuthoringRules({ + type: 'object', + item: { ...ticket(), name: 'ab_other', label: 'Other' }, + context: { objects: [ticket([scriptAction('p', CARD_BODY)])] }, + }); + expect(compileFindings(r.errors)).toEqual([]); + }); +}); diff --git a/packages/lint/src/validate-action-body-compiles.ts b/packages/lint/src/validate-action-body-compiles.ts new file mode 100644 index 00000000000..9e2fd44dd44 --- /dev/null +++ b/packages/lint/src/validate-action-body-compiles.ts @@ -0,0 +1,168 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * An L2 action body must COMPILE in the wrapper the runtime runs it in. + * + * ## The failure this refuses + * + * The runtime runs `body.source` as the body of + * {@link actionBodyFunctionExpression} — `(async (input, ctx) => { SOURCE })` — + * never as a script of its own. A source that is valid on its own can fail to + * compile there. The common case is the one an AI author writes because `input` + * reads like a free variable: `const input = ctx.input || {}` declares a + * parameter a second time, which is a SyntaxError raised before any statement + * of the body runs. Before this rule such a body passed `os validate`, + * `os build`, `os verify` and the publish door, and then EVERY run of the + * action failed, on every door, for as long as the metadata was deployed. + * + * The existing parse check (`action-body-source-unparseable`) cannot see it: it + * parses the source with the TypeScript parser inside a synthesised + * `async function __body(ctx)`, a different binding list, and a parser reports + * no redeclaration at all (that is an early error, not a grammar error). + * + * ## How it judges + * + * It compiles `actionBodyFunctionExpression(source)` — the function the runtime + * builds, from the same function — with the host JavaScript engine, as a + * SCRIPT, the way the runtime evaluates it. Compiling never runs anything: a + * source that closes the wrapper early and writes statements after it compiles + * here and nothing in it executes. `node:vm`'s `Script` is used where the host + * has it (every Node the package supports from 22.3); otherwise the `Function` + * constructor compiles the same text as a function body. A host that refuses + * both (a page under a content security policy) gets no finding: the rule + * cannot judge there, and says nothing rather than guess. + * + * ## The engines are not the same engine — what that costs, measured + * + * The runtime's engine is QuickJS; this rule's is the host's (V8 on Node). Both + * implement the same early errors, and over a probe of 36 bodies the two agreed + * on every redeclaration, every grammar error, every strict-mode error and every + * misplaced `new.target` / `super`. They disagreed in one place: a regular + * expression literal. Node 22's V8 refuses duplicate named capture groups + * (`/(?x)|(?y)/`), which QuickJS accepts and runs. A regular-expression + * failure is therefore reported as a `warning`: the two dialects are where a + * host refusal measurably does not predict a runtime refusal, and an `error` + * there would refuse a body that runs. Every other compile failure is an + * `error`. The disagreement in the other direction (syntax the host accepts and + * QuickJS does not, such as newer grammar) is a missed finding, never a false + * 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. + */ + +import { ACTION_BODY_PARAMETERS, actionBodyFunctionExpression } from './action-body-wrapper.js'; +import { collectActionBodies } from './validate-action-body-writes.js'; + +/** Rule id. */ +export const ACTION_BODY_DOES_NOT_COMPILE = 'action-body-does-not-compile'; + +export interface ActionBodyCompileFinding { + /** `error`, except a regular-expression literal the host refuses (`warning`; see the module note). */ + severity: 'error' | 'warning'; + rule: string; + /** e.g. `action "decide_approval_step" › body`. */ + where: string; + /** e.g. `actions[0].body.source`. */ + path: string; + message: string; + hint: string; +} + +/** What the host engine said about a text it would not compile. */ +export interface HostCompileFailure { + /** `SyntaxError: `. */ + error: string; + /** 1-based line of the compiled text the engine named, when it named one. */ + line?: number; +} + +type VmModule = { Script: new (code: string, options?: { filename?: string }) => unknown }; + +const COMPILE_FILENAME = 'action-body'; + +function hostVm(): VmModule | undefined { + const proc = (globalThis as { process?: { getBuiltinModule?: (id: string) => unknown } }).process; + if (typeof proc?.getBuiltinModule !== 'function') return undefined; + try { + const vm = proc.getBuiltinModule('node:vm') as Partial | undefined; + return typeof vm?.Script === 'function' ? (vm as VmModule) : undefined; + } catch { + return undefined; + } +} + +/** + * Compile `text` with the host engine WITHOUT running it, and answer why it did + * not compile, or `undefined` when it compiled (or when the host refuses to + * compile anything at all, which is no verdict about `text`). + */ +export function hostCompileFailure(text: string): HostCompileFailure | undefined { + try { + const vm = hostVm(); + if (vm) new vm.Script(text, { filename: COMPILE_FILENAME }); + // Compiled, never called: the constructed function is discarded. + else new Function(text); + return undefined; + } catch (e) { + const err = e as { name?: unknown; message?: unknown; stack?: unknown }; + if (err?.name !== 'SyntaxError') return undefined; + const lineMatch = new RegExp(`^${COMPILE_FILENAME}:(\\d+)`).exec(String(err.stack ?? '')); + return { + error: `SyntaxError: ${String(err.message ?? '')}`, + ...(lineMatch ? { line: Number(lineMatch[1]) } : {}), + }; + } +} + +/** The host's sentence for a regular-expression literal it refuses (V8 and SpiderMonkey both open so). */ +const REGEXP_FAILURE = /^SyntaxError: Invalid regular expression/; + +/** A redeclaration the host names (`Identifier 'input' has already been declared`), and the name. */ +const REDECLARED = /^SyntaxError: Identifier '([^']+)' has already been declared/; + +/** + * 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. + * Walks the bodies {@link collectActionBodies} walks — both registration + * sites, `type: 'script'` only, a merged action once. + */ +export function validateActionBodyCompiles(stack: Record): ActionBodyCompileFinding[] { + const findings: ActionBodyCompileFinding[] = []; + 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_FAILURE.test(failure.error); + const redeclared = REDECLARED.exec(failure.error)?.[1]; + const parameter = redeclared !== undefined && (ACTION_BODY_PARAMETERS as readonly string[]).includes(redeclared) + ? redeclared + : undefined; + + findings.push({ + severity: regexp ? 'warning' : 'error', + 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 ` + + `\`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' + : `Fix body.source so it compiles as the statements of an async function whose parameters are ` + + `${ACTION_BODY_PARAMETERS.map((p) => `\`${p}\``).join(' and ')}`, + }); + } + + return findings; +} diff --git a/packages/runtime/src/sandbox/quickjs-runner.ts b/packages/runtime/src/sandbox/quickjs-runner.ts index 26887c7af60..571aa67e747 100644 --- a/packages/runtime/src/sandbox/quickjs-runner.ts +++ b/packages/runtime/src/sandbox/quickjs-runner.ts @@ -41,6 +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 type { ScriptContext, ScriptOrigin, @@ -392,6 +393,11 @@ 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. + // // [#23702] `SETTLE` attaches the same two handlers the bare `.then(…)` // did and hands back the BODY's own promise as the script's completion // value, so the host holds that promise ({@link relayedEngineRefusal} @@ -406,7 +412,7 @@ export class QuickJSScriptRunner implements ScriptRunner { ${REJECT_HANDLER} );` : `globalThis.__result = undefined; globalThis.__error = undefined; globalThis.__errorInfo = undefined; globalThis.__errorRefusal = undefined; globalThis.__errorFromHost = undefined; - ${SETTLE}((async (input, ctx) => { ${args.source} })(globalThis.__input, globalThis.__ctx), + ${SETTLE}(${actionBodyFunctionExpression(args.source)}(globalThis.__input, globalThis.__ctx), function(v){ globalThis.__result = JSON.stringify(v === undefined ? null : v); }, ${REJECT_HANDLER} );`; @@ -422,6 +428,9 @@ export class QuickJSScriptRunner implements ScriptRunner { } const err = vm.dump(evalRes.error); evalRes.error.dispose(); + if (args.origin.kind === 'action' && isCompileFailure(err)) { + throw actionBodyCompileFailure(args.origin.name, formatErr(err)); + } throw new SandboxError( `${args.origin.kind} '${args.origin.name}' threw: ${formatErr(err)}`, userFacingMessage(formatErr(err)), @@ -2362,6 +2371,47 @@ function cryptoRandomUUID(): string { return `${r()}-${r().slice(0, 4)}-4${r().slice(0, 3)}-${r().slice(0, 4)}-${r()}${r().slice(0, 4)}`; } +/** + * Did evaluating the wrapper fail because the body does not COMPILE? + * + * Evaluating the wrapper compiles it and runs one statement, which calls the + * async arrow. An async function never throws synchronously: everything the + * body does, a `throw new SyntaxError(…)` or a `JSON.parse` of bad text + * included, rejects its promise and crosses `__error`, never `evalCode`'s + * error. So a `SyntaxError` here is the compiler's: the body did not start. + */ +function isCompileFailure(err: unknown): boolean { + return !!err && typeof err === 'object' && (err as { name?: unknown }).name === 'SyntaxError'; +} + +/** + * The error an action whose body does not compile answers with, on every run. + * + * Not a crash, and not a refusal. A crash (`TypeError` in `innerMessage`) is + * answered with the sanitised `500 Internal server error`, because its text may + * carry the data the body was reading; a compile error carries none, and the + * opaque answer was all an MCP caller of `run_action` ever saw for a body that + * can never run. So the sentence names the action and the compiler's reason, + * and the declared status is `500`: the caller sent nothing wrong, the + * deployed metadata is broken, and no retry of the same call can succeed. No + * code is declared, so the doors answer the status's own `INTERNAL_ERROR` and + * relay the sentence (a declared 5xx code would withhold it). The operator line + * keeps the runner's `KIND 'NAME' …` shape. + * + * The author-time rule `action-body-does-not-compile` refuses such a body at + * `os validate` / `os build` / publish; this is the answer for one that got + * past it (deployed before the rule, or syntax the author's host accepted). + */ +function actionBodyCompileFailure(actionName: string, compilerError: string): SandboxError { + const reason = compilerError.split('\n')[0].slice(0, 240); + return new SandboxError( + `action '${actionName}' does not compile: ${compilerError}`, + `Action '${actionName}' cannot run: its body does not compile (${reason}). ` + + 'The action\'s author must fix its body.source and publish it again.', + { status: 500 }, + ); +} + function formatErr(err: unknown): string { if (err && typeof err === 'object') { const o = err as { message?: string; name?: string; stack?: string }; From 1a5536e44bf6438942f157aa8e4c47b90a460f6c Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 19:30:05 +0000 Subject: [PATCH 2/9] test(lint, runtime): pin the author-time refusal and the run-time answer Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufziunkXbDT7wUWqfmWz --- .../src/validate-action-body-compiles.test.ts | 5 ++- .../sandboxed-action-crash-is-a-fault.test.ts | 40 +++++++++++++++++++ 2 files changed, 43 insertions(+), 2 deletions(-) diff --git a/packages/lint/src/validate-action-body-compiles.test.ts b/packages/lint/src/validate-action-body-compiles.test.ts index 65198be4449..0d0fa211025 100644 --- a/packages/lint/src/validate-action-body-compiles.test.ts +++ b/packages/lint/src/validate-action-body-compiles.test.ts @@ -52,8 +52,9 @@ describe('action-body-does-not-compile · the wrapper is the runtime\'s', () => expect(f.hint).toContain('`input` is already a parameter of the wrapper'); }); - it('…while the same source compiles on its own, which is why no parse check saw it', () => { - expect(hostCompileFailure(CARD_BODY)).toBeUndefined(); + it('…while the same source compiles in the parse check\'s own wrapper, which is why that check never saw it', () => { + // `action-body-source-unparseable` parses inside `async function __body(ctx)`, which binds no `input`. + expect(hostCompileFailure(`async function __body(ctx) {\n${CARD_BODY}\n}`)).toBeUndefined(); }); it('refuses `let ctx` the same way, and names the line of body.source', () => { diff --git a/packages/runtime/src/sandbox/sandboxed-action-crash-is-a-fault.test.ts b/packages/runtime/src/sandbox/sandboxed-action-crash-is-a-fault.test.ts index a1c9b6e669d..79f9e3edd61 100644 --- a/packages/runtime/src/sandbox/sandboxed-action-crash-is-a-fault.test.ts +++ b/packages/runtime/src/sandbox/sandboxed-action-crash-is-a-fault.test.ts @@ -134,3 +134,43 @@ describe('[#17273] and the door answers it as one', () => { expect(response.body.error.message).toBe('Contact has no phone'); }); }); + +describe('an action body that does not compile answers naming the action and the compile error', () => { + /** The body from the scenario run the fix answers, byte for byte. */ + const CARD_BODY = 'const input = ctx.input || {}; return 1;'; + + async function compileFailure(source: string): Promise { + const e = await runner + .runScript({ language: 'js', source, capabilities: [] }, { input: {} }, actionOpts) + .then(() => null, (err) => err as SandboxError); + expect(e, 'expected the body to fail, but the script resolved').toBeInstanceOf(SandboxError); + return e!; + } + + it('the runner names the action and the compiler, declares 500, and is no crash', async () => { + const err = await compileFailure(CARD_BODY); + expect(err.message).toBe("action 'submit_signoff' does not compile: SyntaxError: invalid redefinition of parameter name"); + expect(err.status).toBe(500); + expect(err.code).toBeUndefined(); + expect(err.innerMessage).toContain("Action 'submit_signoff' cannot run: its body does not compile"); + expect(err.innerMessage).toContain('SyntaxError: invalid redefinition of parameter name'); + }); + + it('the /actions door answers 500 INTERNAL_ERROR with that sentence, never the bare "Internal server error"', async () => { + const err = await compileFailure(CARD_BODY); + const response = await throughActionsDoor(err); + expect(response.status).toBe(500); + expect(response.body.error.code).toBe('INTERNAL_ERROR'); + expect(response.body.error.message).not.toBe('Internal server error'); + expect(response.body.error.message).toContain("Action 'submit_signoff' cannot run"); + expect(response.body.error.message).toContain('invalid redefinition of parameter name'); + }); + + it('control: a body that throws a SyntaxError while RUNNING is still a crash, answered with the sanitised 500', async () => { + const err = await compileFailure("JSON.parse('{'); return 1;"); + expect(err.message).toContain("action 'submit_signoff' threw:"); + const response = await throughActionsDoor(err); + expect(response.status).toBe(500); + expect(response.body.error.message).toBe('Internal server error'); + }); +}); From 647d43ad5924c75be43c872a29c15bf3b6edd931 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 19:37:54 +0000 Subject: [PATCH 3/9] docs: action-body-does-not-compile in the action body pages, the error catalog and the rule count Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufziunkXbDT7wUWqfmWz --- content/docs/api/error-catalog.mdx | 1 + content/docs/automation/hook-bodies.mdx | 1 + content/docs/deployment/cli.mdx | 2 +- content/docs/deployment/validating-metadata.mdx | 2 +- content/docs/getting-started/build-with-claude-code.mdx | 2 +- content/docs/ui/actions.mdx | 5 ++++- content/docs/ui/react-pages.mdx | 2 +- 7 files changed, 10 insertions(+), 5 deletions(-) diff --git a/content/docs/api/error-catalog.mdx b/content/docs/api/error-catalog.mdx index fe2eb256600..89ba645ac1b 100644 --- a/content/docs/api/error-catalog.mdx +++ b/content/docs/api/error-catalog.mdx @@ -709,6 +709,7 @@ value directly (single wrap). | Type has no server dispatch (`url`/`modal`/`form`/`api`), or a param-contract violation | **400** | `{ success: false, error: { message, code } }` | | Data engine or automation service unavailable | **503** | `{ success: false, error: { message, code } }` | | Handler **crashed** (`TypeError`, driver error, sandbox timeout) | **500** | `{ success: false, error: { message, code } }` | +| Sandboxed body **does not compile** in its `(async (input, ctx) => { … })` wrapper | **500** | `{ success: false, error: { message, code: 'INTERNAL_ERROR' } }` — `message` names the action and the compile error | A rejection and a crash are told apart by the thrown error: a plain `throw new Error(msg)`, a sandboxed body's deliberate throw, or a diff --git a/content/docs/automation/hook-bodies.mdx b/content/docs/automation/hook-bodies.mdx index e4da1c5a928..13a22c957d2 100644 --- a/content/docs/automation/hook-bodies.mdx +++ b/content/docs/automation/hook-bodies.mdx @@ -227,6 +227,7 @@ Static validation around a hook is asymmetric, and it is worth knowing exactly w - **Checked — write side, literal-only.** Since [#4271](https://github.com/objectstack-ai/objectstack/issues/4271), `body.source` is **parsed** (never executed, never type-checked) and the field names it writes are resolved against the target object's declarations, which include every field an `objectExtensions` entry of the same artifact adds to it. An unknown field raises `hook-body-write-unknown-field` — a **warning** carrying a did-you-mean suggestion, which never blocks a build. Action bodies get the same check on their `ctx.api` writes (`action-body-write-unknown-field`). Both run under `os validate`, `os lint` and `os compile`. The *existence* question is advisory like this because the answer can depend on a package the build cannot see; the separate *writability* question — [writing a `readonly` field through `ctx.api`](#writing-a-readonly-field) — **does** gate, because both halves of that judgement are declared in the stack being checked. - **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 literal that engine refuses is a warning, because its dialect measurably differs from the runtime's QuickJS. 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`. Four literal write shapes are recognized, and only these: diff --git a/content/docs/deployment/cli.mdx b/content/docs/deployment/cli.mdx index 2b7dbac084b..2a72098eaa9 100644 --- a/content/docs/deployment/cli.mdx +++ b/content/docs/deployment/cli.mdx @@ -887,7 +887,7 @@ os compile --json # JSON output for CI pipelines → Normalizing stack definition... → Lowering inline handlers... → Validating protocol compliance... - → Running author-time rules (70)... + → Running author-time rules (71)... → 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 8d45ee2ec62..2a01e2e2b04 100644 --- a/content/docs/deployment/validating-metadata.mdx +++ b/content/docs/deployment/validating-metadata.mdx @@ -865,7 +865,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 (70)... + → Running author-time rules (71)... → 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 b3cdd1858d9..df9b3e58a3c 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 (70)... + → Running author-time rules (71)... ✗ Author-time rules failed (1 issue) • stack · action 'resolve_ticket' visible: bare reference `status` — a diff --git a/content/docs/ui/actions.mdx b/content/docs/ui/actions.mdx index 7f7255e72e0..ff1f0158bb7 100644 --- a/content/docs/ui/actions.mdx +++ b/content/docs/ui/actions.mdx @@ -72,7 +72,10 @@ export default defineStack({ Self-contained logic ships inside the metadata and runs in the server sandbox — signature `(input, ctx)`, with `ctx.api.object(name)` for data access, a -5-second default timeout, and declared `capabilities`: +5-second default timeout, and declared `capabilities`. `input` and `ctx` are the +wrapper's parameters, so a body must not declare them again: `const input = …` +does not compile, and `os validate` / `os build` / the publish door refuse it +(`action-body-does-not-compile`): ```typescript export const MarkDoneAction = defineAction({ diff --git a/content/docs/ui/react-pages.mdx b/content/docs/ui/react-pages.mdx index b52c38b01c8..321b2d90c8c 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 (70)... + → Running author-time rules (71)... → Checking that every required capability has a provider installable in this edition... → Checking package docs (ADR-0046)... From e4dd5a5d1d956f9cab00cc4a0cba5515682bab6b Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 19:38:30 +0000 Subject: [PATCH 4/9] chore: changeset for the action body compile refusal Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufziunkXbDT7wUWqfmWz --- .../34884-action-body-does-not-compile.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 .changeset/34884-action-body-does-not-compile.md diff --git a/.changeset/34884-action-body-does-not-compile.md b/.changeset/34884-action-body-does-not-compile.md new file mode 100644 index 00000000000..e9eba8f50e9 --- /dev/null +++ b/.changeset/34884-action-body-does-not-compile.md @@ -0,0 +1,17 @@ +--- +'@objectstack/lint': patch +'@objectstack/runtime': patch +--- + +fix(lint, runtime)!: an action body that cannot compile in its `(async (input, ctx) => { … })` wrapper is refused at validate, build and publish, and at run time answers naming the action and the compile error + +Clause-②: no (narrowing) — an L2 action body (`type: 'script'`, `body.language: 'js'`) that does not compile as the body of `(async (input, ctx) => { … })` passed `os validate`, `os build`, `os lint`, `os verify` and the runtime publish door (`action` and `object` writes); it is now refused there as `action-body-does-not-compile` at `error`, except a regular-expression literal the host engine refuses, which is a `warning`. Such a body never ran: every run failed with a SyntaxError before its first statement. `@objectstack/lint` also gains the exports `validateActionBodyCompiles`, `hostCompileFailure`, `ACTION_BODY_DOES_NOT_COMPILE`, `ACTION_BODY_PARAMETERS`, `actionBodyFunctionExpression` and two finding types on `.`, and `actionBodyFunctionExpression` on `./runtime`. +Metadata-protocol: none + + + +**BREAKING** for a stack carrying an action body that does not compile in the runtime's wrapper, most often one that declares a wrapper parameter again (`const input = ctx.input || {}`, `let ctx = …`): `os validate`, `os build` and the publish door now refuse it, naming the action, the compile error and its line. The fix: read the params as `input` (they are also `ctx.input`), or give the local another name (`const params = ctx.input || {}`); `var input = …` compiles. + +The rule compiles the body inside the expression the runtime builds, from the same function (`actionBodyFunctionExpression`, which the QuickJS runner now builds its wrapper from), with the host's JavaScript engine and without running it. Run `os explain action-body-does-not-compile` for what it judges and where the host's engine and the runtime's QuickJS differ. + +At run time, an action whose body still does not compile (one deployed before this release, or syntax the host engine accepts and QuickJS does not) answers `500 INTERNAL_ERROR` on the `/actions` door and MCP `run_action` with the sentence `Action 'NAME' cannot run: its body does not compile (SyntaxError: …). The action's author must fix its body.source and publish it again.`, where it answered `500 INTERNAL_ERROR "Internal server error"`. The server log line reads `action 'NAME' does not compile: SyntaxError: …`. A body that crashes while running (a `TypeError`, a `SyntaxError` thrown by `JSON.parse`) still answers the sanitised `500`. Hook and job bodies are unchanged. From 1190befe28d550415307059a56202a3f1f778bd5 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 19:42:50 +0000 Subject: [PATCH 5/9] test(lint): the object door roster names validateActionBodyCompiles Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufziunkXbDT7wUWqfmWz --- packages/lint/src/runtime-gate.object-writes.test.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/packages/lint/src/runtime-gate.object-writes.test.ts b/packages/lint/src/runtime-gate.object-writes.test.ts index 0b3e515dd5e..3ae2b38889e 100644 --- a/packages/lint/src/runtime-gate.object-writes.test.ts +++ b/packages/lint/src/runtime-gate.object-writes.test.ts @@ -191,6 +191,12 @@ describe('the object write door dispatches at the adjudicated scope (#4716)', () 'validateRlsPredicateEnforceability', 'validateMembershipKeyDeclarations', 'validateRuleCompilability', + // Joins with its card's acceptance ("refused at validate, build or + // publish"): an object write carries its inline `actions[]`, the second + // place an action body is published, so a body that does not compile + // in the runtime's wrapper is refused here as at the `action` door. Its + // door cases are in `validate-action-body-compiles.test.ts`. + 'validateActionBodyCompiles', 'validateRuleSchemaFormats', ]); }); @@ -566,6 +572,7 @@ describe('the object write door dispatches at the adjudicated scope (#4716)', () 'validateRlsPredicateEnforceability', // [#25234] — see the roster pin above 'validateMembershipKeyDeclarations', // [#25234] 'validateRuleCompilability', + 'validateActionBodyCompiles', // see the roster pin above 'validateRuleSchemaFormats', ]); }); From f34867b93d61caf5b11ae77e7733369e7b6a8f16 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 20:10:32 +0000 Subject: [PATCH 6/9] test(runtime): pay the metadata load during collection in the action door pins Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufziunkXbDT7wUWqfmWz --- .../src/sandbox/sandboxed-action-crash-is-a-fault.test.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/packages/runtime/src/sandbox/sandboxed-action-crash-is-a-fault.test.ts b/packages/runtime/src/sandbox/sandboxed-action-crash-is-a-fault.test.ts index 79f9e3edd61..7e44fa1279f 100644 --- a/packages/runtime/src/sandbox/sandboxed-action-crash-is-a-fault.test.ts +++ b/packages/runtime/src/sandbox/sandboxed-action-crash-is-a-fault.test.ts @@ -29,6 +29,9 @@ import { describe, it, expect, vi } from 'vitest'; import { QuickJSScriptRunner, SandboxError } from './quickjs-runner.js'; import type { ScriptRunOptions } from './script-runner.js'; import { HttpDispatcher } from '../http-dispatcher.js'; +// Paid during collection, never inside a case's clocked window: the door's +// reach loads this package lazily (`check:test-source-alias`). +import '@objectstack/metadata'; const runner = new QuickJSScriptRunner({ hookTimeoutMs: 10_000, actionTimeoutMs: 10_000 }); const actionOpts: ScriptRunOptions = { origin: { kind: 'action', name: 'submit_signoff' } }; From 3d9dc01f718f8119f3a9a338652a9daee12e0214 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 21:11:56 +0000 Subject: [PATCH 7/9] feat(spec): register the ADR-0087 semantic entry for the action body compile refusal The refusal narrows what the authoring doors accept, so the changeset now declares Metadata-protocol: narrowed, carries the registered marker and the precedent's BREAKING scope, FROM -> TO, Fix and measured exposure, and grades @objectstack/lint and @objectstack/spec minor. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufziunkXbDT7wUWqfmWz --- .../34884-action-body-does-not-compile.md | 18 +++++--- ...18.action-body-does-not-compile-refused.ts | 46 +++++++++++++++++++ 2 files changed, 58 insertions(+), 6 deletions(-) create mode 100644 packages/spec/src/migrations/entries/semantic/18.action-body-does-not-compile-refused.ts diff --git a/.changeset/34884-action-body-does-not-compile.md b/.changeset/34884-action-body-does-not-compile.md index e9eba8f50e9..d918d885f65 100644 --- a/.changeset/34884-action-body-does-not-compile.md +++ b/.changeset/34884-action-body-does-not-compile.md @@ -1,17 +1,23 @@ --- -'@objectstack/lint': patch +'@objectstack/lint': minor +'@objectstack/spec': minor '@objectstack/runtime': patch --- fix(lint, runtime)!: an action body that cannot compile in its `(async (input, ctx) => { … })` wrapper is refused at validate, build and publish, and at run time answers naming the action and the compile error Clause-②: no (narrowing) — an L2 action body (`type: 'script'`, `body.language: 'js'`) that does not compile as the body of `(async (input, ctx) => { … })` passed `os validate`, `os build`, `os lint`, `os verify` and the runtime publish door (`action` and `object` writes); it is now refused there as `action-body-does-not-compile` at `error`, except a regular-expression literal the host engine refuses, which is a `warning`. Such a body never ran: every run failed with a SyntaxError before its first statement. `@objectstack/lint` also gains the exports `validateActionBodyCompiles`, `hostCompileFailure`, `ACTION_BODY_DOES_NOT_COMPILE`, `ACTION_BODY_PARAMETERS`, `actionBodyFunctionExpression` and two finding types on `.`, and `actionBodyFunctionExpression` on `./runtime`. -Metadata-protocol: none +Metadata-protocol: narrowed +Skills-docs: follow-up owed — `skills/objectstack-data/references/data-hooks.md` teaches the action wrap `(async (input, ctx) => { … })` without saying a body must not declare `input` / `ctx` again; this change teaches it in `content/docs/ui/actions.mdx` and `content/docs/automation/hook-bodies.mdx`. - + -**BREAKING** for a stack carrying an action body that does not compile in the runtime's wrapper, most often one that declares a wrapper parameter again (`const input = ctx.input || {}`, `let ctx = …`): `os validate`, `os build` and the publish door now refuse it, naming the action, the compile error and its line. The fix: read the params as `input` (they are also `ctx.input`), or give the local another name (`const params = ctx.input || {}`); `var input = …` compiles. +**BREAKING** only for an action body that never ran. The runtime compiles an L2 action's `body.source` as the statements of `(async (input, ctx) => { SOURCE })`, so a body that declares a wrapper parameter again (`const input = ctx.input || {}`, `let ctx = …`), or fails to compile there for any other reason, raises a SyntaxError before its first statement. Every authoring door accepted it: the parse check (`action-body-source-unparseable`) reads the source inside a different wrapper, and a parser reports no redeclaration. It deployed clean, and then every run of the action answered `500 INTERNAL_ERROR "Internal server error"` on the `/actions` door and MCP `run_action`. `action-body-does-not-compile` now refuses it at `os validate`, `os build`, `os lint` and the runtime publish door (`422 INVALID_METADATA`), naming the action, the compile error and its line of `body.source`. The publish door runs the rule on `object` writes too, so an object write cannot republish a refused body inline in `actions[]`. Hook and job bodies (`(async (ctx) => { … })`) are not judged. Measured first-party exposure: zero — `os validate` over the example apps reports no finding, and no skill or docs sample carries an action body that redeclares `input` or `ctx`. -The rule compiles the body inside the expression the runtime builds, from the same function (`actionBodyFunctionExpression`, which the QuickJS runner now builds its wrapper from), with the host's JavaScript engine and without running it. Run `os explain action-body-does-not-compile` for what it judges and where the host's engine and the runtime's QuickJS differ. +**FROM → TO.** FROM `body: { language: 'js', source: 'const input = ctx.input || {}; return input.amount;' }` (accepted at every door, failing every run) TO `source: 'const params = ctx.input || {}; return params.amount;'` (or `return input.amount;`). -At run time, an action whose body still does not compile (one deployed before this release, or syntax the host engine accepts and QuickJS does not) answers `500 INTERNAL_ERROR` on the `/actions` door and MCP `run_action` with the sentence `Action 'NAME' cannot run: its body does not compile (SyntaxError: …). The action's author must fix its body.source and publish it again.`, where it answered `500 INTERNAL_ERROR "Internal server error"`. The server log line reads `action 'NAME' does not compile: SyntaxError: …`. A body that crashes while running (a `TypeError`, a `SyntaxError` thrown by `JSON.parse`) still answers the sanitised `500`. Hook and job bodies are unchanged. +**Fix:** read the params as `input` (they are also `ctx.input`), or give the local another name (`const params = ctx.input || {}`); `var input = …` compiles. Fix any other compile error the finding names at the line it names. The semantic entry `action-body-does-not-compile-refused` carries the same notice into the upgrade guide and `os migrate meta`. `os explain action-body-does-not-compile` says what the rule judges and where the host's engine and the runtime's QuickJS differ. + +The rule compiles the body inside the expression the runtime builds, from the same function (`actionBodyFunctionExpression`, which the QuickJS runner now builds its wrapper from, byte for byte as before), with the host's JavaScript engine and without running it. + +At run time, an action whose body still does not compile (one deployed before this release, or syntax the host engine accepts and QuickJS does not) answers `500 INTERNAL_ERROR` on the `/actions` door and MCP `run_action` with the sentence `Action 'NAME' cannot run: its body does not compile (SyntaxError: …). The action's author must fix its body.source and publish it again.`, where it answered `500 INTERNAL_ERROR "Internal server error"`. The server log line reads `action 'NAME' does not compile: SyntaxError: …`. A body that crashes while running (a `TypeError`, a `SyntaxError` thrown by `JSON.parse`) still answers the sanitised `500`. 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 new file mode 100644 index 00000000000..c362a231d94 --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/18.action-body-does-not-compile-refused.ts @@ -0,0 +1,46 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// #34884 — an L2 action body (`type: 'script'`, `body.language: 'js'`) must +// compile as the body of the wrapper the runtime runs it in, an async arrow +// function whose parameters are `input` and `ctx`: one that does not is refused +// at error as `action-body-does-not-compile` (@objectstack/lint). 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 an action body that fails to compile there. Not +// converted: which name the author meant for the local is a judgement. +export const entry: SemanticMigration = { + id: 'action-body-does-not-compile-refused', + surface: + 'actions[].body.source, and objects[].actions[].body.source, of an action of type script whose body.language is ' + + 'js, on an action or object saved or published through the metadata doors (PUT /api/v1/meta/action/NAME, ' + + 'PUT /api/v1/meta/object/NAME with inline actions, POST /api/v1/packages/PKG/publish-drafts and the per-item ' + + 'publish) or loaded by os validate / os build / os lint: a source that does not compile as the statements of ' + + 'the async arrow function the runtime wraps it in, whose parameters are input and ctx. The common case declares ' + + 'a parameter a second time, as in const input = ctx.input || {} or let ctx = …', + replacement: + 'Write the body as the statements of an async function whose parameters are input (the action\'s params) and ctx ' + + '(the context): read the params as input, or give the local another name (const params = ctx.input || {}); ' + + 'var input = … also compiles. Fix any other compile error the finding names at the line of body.source it ' + + 'names. Refused at error as `action-body-does-not-compile` (422 INVALID_METADATA at the doors). A regular ' + + 'expression literal the host engine refuses is reported at warning, never refused.', + reason: + 'The runtime never runs body.source as a script of its own: it compiles it inside an async arrow function with ' + + 'the parameters input and ctx, and a source that redeclares one of them, or otherwise fails to compile there, ' + + 'raises a SyntaxError before its first statement. Every authoring door accepted such a body (the parse check ' + + 'reads the source inside a different wrapper, and a parser reports no redeclaration), so it deployed clean ' + + 'and then EVERY run of the action failed, answering an opaque 500 INTERNAL_ERROR on the /actions door and on ' + + 'MCP run_action 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. The host ' + + 'engine and the runtime\'s QuickJS agreed on every early error probed except regular-expression literals, ' + + '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 ' + + '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 action (`os validate` or `os build`): no `action-body-does-not-compile` finding at error at ' + + 'actions[N].body.source or objects[N].actions[N].body.source. PUT /api/v1/meta/action/NAME with each such body ' + + 'corrected answers 200, and running the action on POST /api/v1/actions/OBJECT/ACTION/ID answers the body\'s ' + + 'result instead of 500 INTERNAL_ERROR.', +}; From bc80b37795b91a1401c5c574d014b6a6b377e82a Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 21:16:58 +0000 Subject: [PATCH 8/9] docs(validating-metadata): list the action body compile rule in the four-doors table The rule runs on validate, build and lint, and at the publish door for action and object writes; the table had no row for it. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufziunkXbDT7wUWqfmWz --- content/docs/deployment/validating-metadata.mdx | 1 + 1 file changed, 1 insertion(+) diff --git a/content/docs/deployment/validating-metadata.mdx b/content/docs/deployment/validating-metadata.mdx index 2a01e2e2b04..d28c626164a 100644 --- a/content/docs/deployment/validating-metadata.mdx +++ b/content/docs/deployment/validating-metadata.mdx @@ -519,6 +519,7 @@ orthogonal to both, and no cell here can carry it; it is written out in | Print page blocks — a page that declares `print` holds only printable component types (`print-page-block-unprintable`, #22158) | ✓ | ✓ | ✓ | ✓ᵖ | | 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) | ✓ | ✓ | ✓ | ✓ᵃᶜᵒ | | 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`) | ✓ | ✓ | ✓ | ✓ᵒᵖᵉᵇᵖᵒᵃᵒˣ | From 578e68604499122a325b96b55deb8e4718e4979e Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 22:08:03 +0000 Subject: [PATCH 9/9] test(core): sample the action compile-failure interpolations in the sandbox fault census The census renders every SandboxError construction in quickjs-runner.ts; the new action compile-failure site interpolates actionName and compilerError, so the crash samples carry one value for each. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufziunkXbDT7wUWqfmWz --- .../core/src/utils/import-runner-sandbox-fault-row.test.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/packages/core/src/utils/import-runner-sandbox-fault-row.test.ts b/packages/core/src/utils/import-runner-sandbox-fault-row.test.ts index 5085210bae4..b39b6abbc18 100644 --- a/packages/core/src/utils/import-runner-sandbox-fault-row.test.ts +++ b/packages/core/src/utils/import-runner-sandbox-fault-row.test.ts @@ -122,6 +122,10 @@ const CRASH_SAMPLES: Readonly> = { ...SAMPLES, 'formatErr(err)': 'TypeError: boom', errStr: 'TypeError: boom', + // An action body that does not compile in its wrapper: the action's name and + // the compiler's sentence (`actionBodyCompileFailure`). + actionName: 'mz_lock_decide', + compilerError: 'SyntaxError: invalid redefinition of parameter name', }; /**