From d40ddc856dea83f7691f1e55cfa06b213a6eae08 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 10:03:42 +0000 Subject: [PATCH 1/6] feat(spec): IAutomationService.dryRun contract, a dry run of an unpublished flow definition The method, its options, result and step types, and its documented semantics: simulated writes, the named user's identity, by-name start admission, a stop at approval and wait nodes, outbound nodes reported and never sent, and no registration, arming or persisted run. Pinned at the type level and on the doc block. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5nK9bbdtG9bJTBujTZ --- .changeset/33757-flow-dry-run-contract.md | 18 ++ .../contracts/automation-dry-run.pin.test.ts | 190 ++++++++++++ .../spec/src/contracts/automation-service.ts | 290 ++++++++++++++++++ 3 files changed, 498 insertions(+) create mode 100644 .changeset/33757-flow-dry-run-contract.md create mode 100644 packages/spec/src/contracts/automation-dry-run.pin.test.ts diff --git a/.changeset/33757-flow-dry-run-contract.md b/.changeset/33757-flow-dry-run-contract.md new file mode 100644 index 00000000000..1b13e08d154 --- /dev/null +++ b/.changeset/33757-flow-dry-run-contract.md @@ -0,0 +1,18 @@ +--- +'@objectstack/spec': patch +--- + +feat(spec): `IAutomationService.dryRun`, a dry run of a flow definition that need not be published: once, unarmed, as a named user, against a supplied start, without changing live data (#33757) + +Clause-②: yes (widening) — a new optional member on `IAutomationService` and new exported types. No existing member, type or code changes, and an implementation without the member still satisfies the contract. +Metadata-protocol: none + +The contract half of #33661 (objectstack-ai/cloud#3309 item 5, option A, ruled by the account owner); #33661 implements it in `@objectstack/service-automation` and `@objectstack/runtime`. The method's doc block states the semantics the implementation owes: + +- **Writes are simulated, never made.** `create_record`, `update_record` and `delete_record` report the write they would make (object, operation, target rows, values as computed); a create binds an opaque placeholder id that later reads by id see. No hook, trigger, other flow or audit row runs, since nothing is written. +- **Identity is the named user**, whose own grants the engine resolves, and the run is never elevated, a `runAs: 'system'` definition included. Admission is the by-name start rule (`flowStartRefusal`), judged on the supplied definition against the named user; a refusal answers `status: 'refused'` with `PERMISSION_DENIED`, before any node runs. +- **Approval nodes and waits stop the run** (every node type whose descriptor declares `supportsPause: true`), reported with who would be asked, what would resume it, the screen, or the flow it would start. Nothing is created or scheduled. +- **Side effects outside the data** (`notify`, `http`, `connector_action`, `script`, `save_notice`) are never sent, only reported with their computed payload. +- **Unarmed and unregistered**: never registered or listed, the trigger never armed, no run persisted, one pass with no retry. An invalid definition throws what `registerFlow` throws. + +**In-process APIs.** `@objectstack/spec/contracts` exports `FlowDryRunOptions`, `FlowDryRunResult`, `FlowDryRunStatus`, `FlowDryRunRefusalCode`, `FlowDryRunStep` and the step types it unions over (`FlowDryRunStepBase`, `FlowDryRunRouteStep`, `FlowDryRunAssignmentStep`, `FlowDryRunDecisionStep`, `FlowDryRunReadStep`, `FlowDryRunWriteStep`, `FlowDryRunOutboundStep`, `FlowDryRunStopStep`). All additive. diff --git a/packages/spec/src/contracts/automation-dry-run.pin.test.ts b/packages/spec/src/contracts/automation-dry-run.pin.test.ts new file mode 100644 index 00000000000..2db3dd4982c --- /dev/null +++ b/packages/spec/src/contracts/automation-dry-run.pin.test.ts @@ -0,0 +1,190 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#33757] `IAutomationService.dryRun`: run a flow definition that need not be + * published, once, unarmed, as a named user, against a supplied start, without + * changing live data. The contract half of #33661, which implements it. + * + * Pinned at the type level, because a TypeScript interface member has no Zod + * schema to assert against (the `automation-toggle-flow-caller` pin's form, + * compiled by `check:test-typecheck` under `tsconfig.test.json`): + * + * 1. **The signature.** Optional, `(definition: unknown, options: + * FlowDryRunOptions) => Promise`, so an implementation + * without it still satisfies the contract. + * 2. **The options name a user and carry no grants.** `userId` is a required + * string; positions, permission sets, posture and email do not compile, so + * a caller cannot dry-run with grants the user does not hold. + * 3. **The closed unions.** The four statuses, the three refusal codes (each + * an existing `AutomationResult.code` member, none minted) and the seven + * step kinds. + * 4. **The documented semantics.** The method's doc block states each ruled + * point (writes, identity, admission, approvals and waits, outbound + * nodes, unarmed and unregistered). Prose is unassertable except by + * reading it, so the contract source is read. + * + * ⛔ Not pinned here: the behaviour. That is #33661, in + * `@objectstack/service-automation` and `@objectstack/runtime`. + */ + +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; + +import { describe, it, expect } from 'vitest'; + +import type { + AutomationResult, + FlowDryRunOptions, + FlowDryRunRefusalCode, + FlowDryRunResult, + FlowDryRunStatus, + FlowDryRunStep, + IAutomationService, +} from './automation-service'; + +/** Type-level identity: true iff A and B are the same type. */ +type Eq< A, B > = (< T >() => T extends A ? 1 : 2) extends (< T >() => T extends B ? 1 : 2) ? true : false; +/** Compile error when the argument is not `true`. */ +type Assert< T extends true > = T; + +type DryRun = NonNullable< IAutomationService['dryRun'] >; + +// Exported deliberately — an unread alias is TS6196, and a pin no program compiles is no pin at all. + +/** 1. The signature. */ +export type DryRunSignature = Assert< Eq< DryRun, (definition: unknown, options: FlowDryRunOptions) => Promise< FlowDryRunResult > > >; +/** Optional: the member may be absent. */ +export type DryRunIsOptional = Assert< Eq< undefined extends IAutomationService['dryRun'] ? true : false, true > >; +export class ServiceWithoutDryRun implements Pick< IAutomationService, 'execute' | 'listFlows' | 'dryRun' > { + async execute() { return { success: true }; } + async listFlows() { return []; } +} + +/** 2. The options: a required acting user, and the start keys `execute` reads. */ +export type UserIdIsRequired = Assert< Eq< FlowDryRunOptions['userId'], string > >; +export type UserIdNotOptional = Assert< Eq< {} extends Pick< FlowDryRunOptions, 'userId' > ? true : false, false > >; +export const minimalOptions: FlowDryRunOptions = { userId: 'usr_maker' }; +export const startOptions: FlowDryRunOptions = { + userId: 'usr_maker', + object: 'opportunity', + event: 'on_update', + record: { id: 'opp_1', stage: 'won' }, + previous: { id: 'opp_1', stage: 'open' }, + params: { note: 'x' }, + locale: 'zh-CN', + tenantId: 'org_1', +}; +// @ts-expect-error — the acting user is required. +export const noUser: FlowDryRunOptions = { record: { id: 'opp_1' } }; +// @ts-expect-error — no grants: the engine resolves the named user's own positions. +export const withPositions: FlowDryRunOptions = { userId: 'usr_maker', positions: ['admin'] }; +// @ts-expect-error — no grants: the engine resolves the named user's own permission sets. +export const withPermissions: FlowDryRunOptions = { userId: 'usr_maker', permissions: ['modify_all'] }; +// @ts-expect-error — no grants: the engine resolves the named user's own posture. +export const withPosture: FlowDryRunOptions = { userId: 'usr_maker', posture: 'PLATFORM_ADMIN' }; +// @ts-expect-error — no grants: the engine resolves the named user's own email. +export const withEmail: FlowDryRunOptions = { userId: 'usr_maker', email: 'boss@example.com' }; +// @ts-expect-error — the run is never elevated: there is no run-as channel. +export const withRunAs: FlowDryRunOptions = { userId: 'usr_maker', runAs: 'system' }; + +/** 3. The closed unions, spelled once. `satisfies` proves membership; `Eq` proves there is nothing else. */ +export const DRY_RUN_STATUSES = ['completed', 'stopped', 'failed', 'refused'] as const satisfies readonly FlowDryRunStatus[]; +export type StatusIsExactlyTheFour = Assert< Eq< FlowDryRunStatus, (typeof DRY_RUN_STATUSES)[number] > >; +export type ResultStatusIsTheUnion = Assert< Eq< FlowDryRunResult['status'], FlowDryRunStatus > >; + +export const DRY_RUN_REFUSAL_CODES = ['PERMISSION_DENIED', 'FLOW_NO_START_NODE', 'FLOW_INPUT_SCHEMA_INVALID'] as const satisfies readonly FlowDryRunRefusalCode[]; +export type RefusalCodeIsExactlyTheThree = Assert< Eq< FlowDryRunRefusalCode, (typeof DRY_RUN_REFUSAL_CODES)[number] > >; +/** No code is minted: every refusal code is an existing `AutomationResult.code` member. */ +export type RefusalCodesAreExisting = Assert< Eq< FlowDryRunRefusalCode extends NonNullable< AutomationResult['code'] > ? true : false, true > >; +export type ResultRefusalShape = Assert< Eq< NonNullable< FlowDryRunResult['refusal'] >, { code: FlowDryRunRefusalCode; message: string } > >; + +export const DRY_RUN_STEP_KINDS = ['route', 'assignment', 'decision', 'read', 'write', 'outbound', 'stop'] as const satisfies readonly FlowDryRunStep['kind'][]; +export type StepKindIsExactlyTheSeven = Assert< Eq< FlowDryRunStep['kind'], (typeof DRY_RUN_STEP_KINDS)[number] > >; +export type WriteOperations = Assert< Eq< Extract< FlowDryRunStep, { kind: 'write' } >['operation'], 'create' | 'update' | 'delete' > >; +export type StopReasons = Assert< Eq< Extract< FlowDryRunStep, { kind: 'stop' } >['reason'], 'pause' | 'not_simulated' > >; + +/** A result an implementation can build without a cast: one ordered step list. */ +export const stoppedAtApproval: FlowDryRunResult = { + status: 'stopped', + steps: [ + { kind: 'route', nodeId: 'start', nodeType: 'start' }, + { kind: 'decision', nodeId: 'big_deal', nodeType: 'decision', branch: 'big', expression: 'record.amount > 100000', next: ['create_task'] }, + { kind: 'write', nodeId: 'create_task', nodeType: 'create_record', operation: 'create', object: 'task', recordIds: ['dryrun:create_task:1'], values: { subject: 'Review' } }, + { kind: 'assignment', nodeId: 'remember', nodeType: 'assignment', values: { taskId: 'dryrun:create_task:1' } }, + { kind: 'outbound', nodeId: 'tell_owner', nodeType: 'notify', payload: { to: ['usr_owner'], body: 'Review' } }, + { kind: 'stop', nodeId: 'approve', nodeType: 'approval', reason: 'pause', approvers: ['usr_manager'] }, + ], +}; +export const refusedAtAdmission: FlowDryRunResult = { + status: 'refused', + steps: [], + refusal: { code: 'PERMISSION_DENIED', message: 'This caller may not start this flow.' }, +}; +export const failedOnPermission: FlowDryRunResult = { + status: 'failed', + steps: [ + { kind: 'route', nodeId: 'start', nodeType: 'start' }, + { + kind: 'write', + nodeId: 'close_deal', + nodeType: 'update_record', + operation: 'update', + object: 'opportunity', + recordIds: ['opp_1'], + values: { stage: 'closed' }, + refusal: { code: 'PERMISSION_DENIED', message: 'no edit access' }, + }, + ], + error: 'update_record close_deal: no edit access', +}; +// @ts-expect-error — a dry run has no run to resume or read back: no `runId`. +export const withRunId: FlowDryRunResult = { status: 'completed', steps: [], runId: 'run_1' }; + +describe('IAutomationService.dryRun — the contract (#33757)', () => { + it('an implementation reads the options and answers the result without a cast', async () => { + const seen: string[] = []; + const service: Pick< IAutomationService, 'dryRun' > = { + dryRun: async (_definition, options) => { + seen.push(options.userId); + return stoppedAtApproval; + }, + }; + const result = await service.dryRun?.({ name: 'draft' }, startOptions); + expect(seen).toEqual(['usr_maker']); + expect(result?.steps.map((s) => s.kind)).toEqual(['route', 'decision', 'write', 'assignment', 'outbound', 'stop']); + }); + + it('a service without dryRun still satisfies the contract, and a caller finds the member absent', () => { + const service: Pick< IAutomationService, 'execute' | 'listFlows' | 'dryRun' > = new ServiceWithoutDryRun(); + expect(service.dryRun).toBeUndefined(); + }); + + it("the method's doc block states each ruled point", () => { + const source = readFileSync(fileURLToPath(new URL('./automation-service.ts', import.meta.url)), 'utf8'); + const end = source.indexOf('dryRun?(definition: unknown, options: FlowDryRunOptions)'); + expect(end).toBeGreaterThan(0); + const start = source.lastIndexOf('/**', end); + const doc = source.slice(start, end); + for (const heading of [ + '**Unarmed and unregistered.**', + '**Identity: the named user.**', + '**Admission: the by-name start rule.**', + '**Writes: simulated, never made.**', + '**Side effects outside the data.**', + '**Approval nodes and waits: the run stops.**', + ]) { + expect(doc, heading).toContain(heading); + } + for (const sentence of [ + 'It is never elevated.', + 'never registered', + 'No run is persisted', + 'no other flow, no audit row.', + 'never send or call anything', + 'no child run starts.', + 'every named user.', + ]) { + expect(doc, sentence).toContain(sentence); + } + }); +}); diff --git a/packages/spec/src/contracts/automation-service.ts b/packages/spec/src/contracts/automation-service.ts index 6747277f5d4..acbf0d108b4 100644 --- a/packages/spec/src/contracts/automation-service.ts +++ b/packages/spec/src/contracts/automation-service.ts @@ -1437,6 +1437,188 @@ export interface ConnectorConnectionCallbackRequest { context?: ExecutionContext; } +/** + * What {@link IAutomationService.dryRun} is asked to run the definition + * against (#33757): the acting user, and the start a trigger would hand the + * run. The start keys are {@link AutomationContext}'s own, read as + * {@link IAutomationService.execute} reads them. + * + * ⛔ No grants: no positions, permission sets, posture or email. The engine + * resolves the named user's own, so a caller cannot run a dry run with grants + * the user does not hold. + */ +export interface FlowDryRunOptions extends Pick { + /** + * The acting user, a `sys_user` id. Required: a dry run always acts as a + * named user, so it never meets `AUTOMATION_UNSCOPED_RUN_DATA_ACCESS`. + */ + userId: string; +} + +/** + * The overall answer of {@link IAutomationService.dryRun}. + * + * - `'completed'`: the run reached an `end` node. An `end` node declaring + * `outcome: 'refused'` completes too; its step carries the rendered + * `refusalMessage`. + * - `'stopped'`: the run reached a node it does not go past (see + * {@link FlowDryRunStopStep}); that node is the last step. + * - `'failed'`: a node failed or met a refusal that no `fault` edge or + * `try_catch` region contains, so the live run would fail there too; that + * node is the last step. + * - `'refused'`: the run never started (see {@link FlowDryRunResult.refusal}). + * ⛔ Not {@link AutomationResult.status}'s `'refused'`, which is an `end` + * node's outcome; here that case is `'completed'`. + */ +export type FlowDryRunStatus = 'completed' | 'stopped' | 'failed' | 'refused'; + +/** + * Why a dry run never started: existing {@link AutomationResult.code} members + * only, each with the meaning it has there. ⛔ No new code is minted for a dry + * run. + */ +export type FlowDryRunRefusalCode = Extract, 'PERMISSION_DENIED' | 'FLOW_NO_START_NODE' | 'FLOW_INPUT_SCHEMA_INVALID'>; + +/** What every step of a dry run reports. */ +export interface FlowDryRunStepBase { + /** The node's id in the definition. */ + nodeId: string; + /** The node's `type` as the definition declares it. */ + nodeType: string; + /** + * The refusal this node met, as a failed live run reports it + * ({@link AutomationResult.innerRefusal}): the permission refusal the named + * user would meet, for example. Absent when the node met none. + */ + refusal?: FlowInnerRefusal; + /** The node's failure text when it failed for a reason other than a refusal. */ + error?: string; +} + +/** + * A node that only routes the run: `start`, `end`, `loop`, + * `parallel_gateway`, `join_gateway` and `try_catch`. + */ +export interface FlowDryRunRouteStep extends FlowDryRunStepBase { + kind: 'route'; + /** An `end` node declaring `outcome: 'refused'`: its message, rendered. */ + refusalMessage?: string; +} + +/** An `assignment` node: the variables it set, with the values it computed. */ +export interface FlowDryRunAssignmentStep extends FlowDryRunStepBase { + kind: 'assignment'; + values: Record; +} + +/** A `decision` node: which way the run went, and why. */ +export interface FlowDryRunDecisionStep extends FlowDryRunStepBase { + kind: 'decision'; + /** + * The branch label: the `label` of the first `config.conditions` entry that + * held, or `'default'` when none held. Absent on a decision that declares + * no conditions, whose out-edges carry the branching. + */ + branch?: string; + /** + * Why: the authored expression that held (the condition entry's, or the + * out-edge's). Absent when the run took the default branch because none + * held. + */ + expression?: string; + /** The ids of the nodes the run went on to; more than one only for `mode: 'inclusive'`. */ + next: string[]; +} + +/** A `get_record` node: the live rows it read, in the named user's scope. */ +export interface FlowDryRunReadStep extends FlowDryRunStepBase { + kind: 'read'; + object: string; + /** The ids of the rows the read answered, placeholder ids included. */ + recordIds: string[]; +} + +/** + * A `create_record`, `update_record` or `delete_record` node: the write it + * would make. ⛔ Nothing was written. + */ +export interface FlowDryRunWriteStep extends FlowDryRunStepBase { + kind: 'write'; + operation: 'create' | 'update' | 'delete'; + object: string; + /** + * The rows the write targets. For an update or a delete, the live rows (or + * placeholder ids) it would change, as the named user's scope reads them. + * For a create, the one placeholder id the run binds to the new row. + */ + recordIds: string[]; + /** + * The field values as the node computed them; absent for a delete. + */ + values?: Record; +} + +/** + * A node with an effect outside the data: `notify`, `http`, + * `connector_action`, `script` and `save_notice`. ⛔ Nothing was sent or + * called. + */ +export interface FlowDryRunOutboundStep extends FlowDryRunStepBase { + kind: 'outbound'; + /** + * What the node would send, as it computed it: the message, the request, + * the connector input, or (`script`) the function name and its inputs. + */ + payload: unknown; +} + +/** + * The node the run stopped at. Always the last step, and only on a + * `'stopped'` result. + */ +export interface FlowDryRunStopStep extends FlowDryRunStepBase { + kind: 'stop'; + /** + * `'pause'`: the node type's descriptor declares `supportsPause: true` + * (`approval`, `wait`, `screen`, `subflow` and `map` among the shipped + * ones). `'not_simulated'`: a node type outside every class this contract + * names, whose effect a dry run cannot know. + */ + reason: 'pause' | 'not_simulated'; + /** An approval node: the ids of the users it would ask, when the run can resolve them. */ + approvers?: string[]; + /** A `wait` node: what would resume it, from its `waitEventConfig`. */ + wait?: { eventType: string; timerDuration?: string; signalName?: string }; + /** A `screen` node: the screen it would show. */ + screen?: ScreenSpec; + /** A `subflow` or `map` node: the flow it would start. */ + flowName?: string; +} + +/** One executed node of a dry run. */ +export type FlowDryRunStep = + | FlowDryRunRouteStep + | FlowDryRunAssignmentStep + | FlowDryRunDecisionStep + | FlowDryRunReadStep + | FlowDryRunWriteStep + | FlowDryRunOutboundStep + | FlowDryRunStopStep; + +/** What {@link IAutomationService.dryRun} answers. */ +export interface FlowDryRunResult { + status: FlowDryRunStatus; + /** + * One entry per node execution, in the order the run executed them: a node + * inside a loop appears once per pass. Empty when `status` is `'refused'`. + */ + steps: FlowDryRunStep[]; + /** Set exactly when `status` is `'refused'`: why the run never started. */ + refusal?: { code: FlowDryRunRefusalCode; message: string }; + /** Set exactly when `status` is `'failed'`: the run's failure text. */ + error?: string; +} + export interface IAutomationService { /** * Execute a named flow or script @@ -1513,6 +1695,114 @@ export interface IAutomationService { todos?: ConversionTodoNotice[]; }; + /** + * Dry-run a flow definition that need not be published: once, unarmed, as + * a named user, against a supplied start, without changing live data + * (#33757, the contract half of #33661; objectstack-ai/cloud#3309 item 5, + * option A). A maker sees what a drafted flow would do before publishing it. + * + * Optional, like every member past {@link execute} and {@link listFlows}: + * only the engine that runs flows can offer it, and a caller that finds it + * absent says a dry run is not available rather than guessing. + * + * **In what order it answers.** + * - `options.userId` that is not a non-empty string: throws a `TypeError` + * before the definition is read. + * - A definition {@link registerFlow} would refuse: throws what + * {@link registerFlow} throws for the same definition. Nothing is + * registered. + * - Admission, then the trigger-time refusals {@link execute} classifies + * before dispatch (`FLOW_NO_START_NODE`, `FLOW_INPUT_SCHEMA_INVALID`): + * `status: 'refused'` with that code in `refusal` and no steps. No node + * has run. + * - Otherwise the nodes run, as described below. + * + * **Unarmed and unregistered.** + * - The definition is never registered: {@link listFlows} and + * {@link getFlow} do not answer it during or after the call. + * - Its trigger (a record change, a schedule, an API route) is never armed. + * - The definition runs once per call, with no retry. + * - No run is persisted: there is no `runId`, and {@link getRun}, + * {@link listRuns} and the run history never show it. + * + * **Identity: the named user.** + * - The run acts as `options.userId`. The engine resolves that user's own + * grants (positions, permission sets, posture, email), as it does for a + * run whose context carries none; the options have no slot for grants. + * - It is never elevated. A definition declaring `runAs: 'system'` also + * runs as the named user: every read and every permission judgement is + * that user's, so its report can show a refusal the published flow, + * running elevated, would not meet. + * - The method does not judge whether its caller may act as `userId`, as + * {@link execute} does not judge `AutomationContext.userId`. A door that + * serves a person passes that person's id. + * + * **Admission: the by-name start rule.** The rules that admit a start by + * name (`flowStartRefusal`, `@objectstack/runtime`'s + * `flow-start-admission.ts`), judged on the supplied definition's `type`, + * `runAs` and `requiredPermissions` against the named user. There is no + * system-principal bypass, since the run always names a user. + * - A definition declaring `runAs: 'system'` whose `type` starts on its own + * trigger (`autolaunched`, `record_change`, `schedule`) is refused for + * every named user. + * - A definition declaring `runAs: 'system'` is refused when the named user + * is an AI service account (ADR-0151 D3), as at the trigger routes: a dry + * run starts with no action in hand, so no AI opt-in stands. + * - A named user missing any capability the definition's + * `requiredPermissions` names is refused. + * - Each refusal is `code: 'PERMISSION_DENIED'` with the message the + * by-name start answers for the same rule. + * + * **Writes: simulated, never made.** + * - `create_record`, `update_record` and `delete_record` write nothing, and + * nothing is rolled back, since nothing was written. Each reports the + * write it would make ({@link FlowDryRunWriteStep}). + * - A create binds a placeholder id to the new row: opaque, unique within + * the call, and never the id of a live row. + * - A later read by id of a row the run created or updated answers the + * simulated values, and of a row the run deleted answers nothing. + * - A read that filters rather than names an id answers the live rows the + * named user can read, and does not see the run's simulated writes. + * - Since nothing is written, nothing a write sets off runs: no record + * hook, no record-change trigger, no other flow, no audit row. + * - The data engine does not judge a simulated write, so a write it would + * refuse for a validation rule, a uniqueness constraint or a required + * field reports as it would be made. A permission refusal is the + * exception: the step carries, in `refusal`, the refusal the named user + * would meet for that operation on that object or row. + * + * **Reads.** `get_record` reads live data, in the named user's scope. + * + * **A node that meets a refusal or fails.** It is reported, never skipped + * silently: its step carries the refusal or the failure, and the run goes + * on as the live run would, along a `fault` edge or out of a `try_catch` + * region that contains it, or else it ends `'failed'`. + * + * **Side effects outside the data.** `notify`, `http`, `connector_action`, + * `script` and `save_notice` never send or call anything. Each reports the + * payload it computed ({@link FlowDryRunOutboundStep}) and binds no output, + * so a later node that reads its output finds it unset. + * + * **Approval nodes and waits: the run stops.** At the first node whose type's + * descriptor declares `supportsPause: true` (an approval, a `wait`, a + * `screen`, a `subflow`, a `map`), the run stops with `status: 'stopped'` + * and reports the node: who it would ask, how long or for what it would + * wait, the screen it would show, or the flow it would start + * ({@link FlowDryRunStopStep}). No approval request is created, no resume + * is scheduled, and no child run starts. A node type outside every class + * named here also stops the run (`reason: 'not_simulated'`). + * + * **Nodes that route or compute** (`start`, `end`, `decision`, + * `assignment`, `loop`, `parallel_gateway`, `join_gateway`, `try_catch`) + * run as the live run runs them, and report what they did. + * + * @param definition - The flow definition (raw, pre-parse), as + * {@link registerFlow} takes it + * @param options - The acting user and the start + * @returns The run's status and its ordered steps + */ + dryRun?(definition: unknown, options: FlowDryRunOptions): Promise; + /** * Unregister a flow by name * @param name - Flow name (snake_case) From 0695d5ce8169a39f13dbda89a6f9b9ffdf68609e Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 10:08:11 +0000 Subject: [PATCH 2/6] chore(spec): regenerate api-surface and export-origins for the dryRun contract types Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5nK9bbdtG9bJTBujTZ --- packages/spec/api-surface/contracts.json | 13 +++++++++++++ packages/spec/export-origins/contracts.json | 13 +++++++++++++ 2 files changed, 26 insertions(+) diff --git a/packages/spec/api-surface/contracts.json b/packages/spec/api-surface/contracts.json index d337bbb0eb7..b03433dabfc 100644 --- a/packages/spec/api-surface/contracts.json +++ b/packages/spec/api-surface/contracts.json @@ -124,6 +124,19 @@ "FieldFileDescription (interface)", "FieldFileSlot (interface)", "FinishReason (type)", + "FlowDryRunAssignmentStep (interface)", + "FlowDryRunDecisionStep (interface)", + "FlowDryRunOptions (interface)", + "FlowDryRunOutboundStep (interface)", + "FlowDryRunReadStep (interface)", + "FlowDryRunRefusalCode (type)", + "FlowDryRunResult (interface)", + "FlowDryRunRouteStep (interface)", + "FlowDryRunStatus (type)", + "FlowDryRunStep (type)", + "FlowDryRunStepBase (interface)", + "FlowDryRunStopStep (interface)", + "FlowDryRunWriteStep (interface)", "FlowRuntimeState (interface)", "FlowUnboundCause (type)", "GenerateDraftOpts (interface)", diff --git a/packages/spec/export-origins/contracts.json b/packages/spec/export-origins/contracts.json index 41d842b1fb3..ecfad48997d 100644 --- a/packages/spec/export-origins/contracts.json +++ b/packages/spec/export-origins/contracts.json @@ -124,6 +124,19 @@ "FieldFileDescription": "src/contracts/storage-service.ts#FieldFileDescription (interface)", "FieldFileSlot": "src/contracts/storage-service.ts#FieldFileSlot (interface)", "FinishReason": "node_modules/ai/dist/index.d.ts#FinishReason (type)", + "FlowDryRunAssignmentStep": "src/contracts/automation-service.ts#FlowDryRunAssignmentStep (interface)", + "FlowDryRunDecisionStep": "src/contracts/automation-service.ts#FlowDryRunDecisionStep (interface)", + "FlowDryRunOptions": "src/contracts/automation-service.ts#FlowDryRunOptions (interface)", + "FlowDryRunOutboundStep": "src/contracts/automation-service.ts#FlowDryRunOutboundStep (interface)", + "FlowDryRunReadStep": "src/contracts/automation-service.ts#FlowDryRunReadStep (interface)", + "FlowDryRunRefusalCode": "src/contracts/automation-service.ts#FlowDryRunRefusalCode (type)", + "FlowDryRunResult": "src/contracts/automation-service.ts#FlowDryRunResult (interface)", + "FlowDryRunRouteStep": "src/contracts/automation-service.ts#FlowDryRunRouteStep (interface)", + "FlowDryRunStatus": "src/contracts/automation-service.ts#FlowDryRunStatus (type)", + "FlowDryRunStep": "src/contracts/automation-service.ts#FlowDryRunStep (type)", + "FlowDryRunStepBase": "src/contracts/automation-service.ts#FlowDryRunStepBase (interface)", + "FlowDryRunStopStep": "src/contracts/automation-service.ts#FlowDryRunStopStep (interface)", + "FlowDryRunWriteStep": "src/contracts/automation-service.ts#FlowDryRunWriteStep (interface)", "FlowRuntimeState": "src/contracts/automation-service.ts#FlowRuntimeState (interface)", "FlowUnboundCause": "src/contracts/automation-service.ts#FlowUnboundCause (type)", "GenerateDraftOpts": "src/contracts/external-datasource-service.ts#GenerateDraftOpts (interface)", From f635d5af49fa982a9b4f1c2aed1feab34d2cf646 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 11:17:07 +0000 Subject: [PATCH 3/6] feat(spec): dryRun contract round 2, start condition, three-way write permission, step order Adds the condition_not_met status, a three-way write permission bounded to the object-level check, the shipped parallel node and the step order of side-by-side branches, drops FLOW_NO_START_NODE from the refusal codes, rewords failed as the dry run's own answer, states what simulated rows hold, the definition's own name, the tenant membership refusal, and names each stop reason by what the node does. Regenerates api-surface and export-origins on the merged tree. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5nK9bbdtG9bJTBujTZ --- .changeset/33757-flow-dry-run-contract.md | 7 +- packages/spec/api-surface/contracts.json | 8 + packages/spec/export-origins/contracts.json | 8 + .../contracts/automation-dry-run.pin.test.ts | 51 +++-- .../spec/src/contracts/automation-service.ts | 179 +++++++++++++----- 5 files changed, 193 insertions(+), 60 deletions(-) diff --git a/.changeset/33757-flow-dry-run-contract.md b/.changeset/33757-flow-dry-run-contract.md index 1b13e08d154..710d39f187c 100644 --- a/.changeset/33757-flow-dry-run-contract.md +++ b/.changeset/33757-flow-dry-run-contract.md @@ -9,10 +9,11 @@ Metadata-protocol: none The contract half of #33661 (objectstack-ai/cloud#3309 item 5, option A, ruled by the account owner); #33661 implements it in `@objectstack/service-automation` and `@objectstack/runtime`. The method's doc block states the semantics the implementation owes: -- **Writes are simulated, never made.** `create_record`, `update_record` and `delete_record` report the write they would make (object, operation, target rows, values as computed); a create binds an opaque placeholder id that later reads by id see. No hook, trigger, other flow or audit row runs, since nothing is written. -- **Identity is the named user**, whose own grants the engine resolves, and the run is never elevated, a `runAs: 'system'` definition included. Admission is the by-name start rule (`flowStartRefusal`), judged on the supplied definition against the named user; a refusal answers `status: 'refused'` with `PERMISSION_DENIED`, before any node runs. +- **Writes are simulated, never made.** `create_record`, `update_record` and `delete_record` report the write they would make (object, operation, target rows, values as computed) and a three-way `permission` (`allowed` / `refused` from the object-level write check, `not_judged` for deletes and every row-level refusal; `not_judged` never means allowed). A create binds an opaque placeholder id that later reads by id see, holding only the fields the flow set; an updated row reads as the live row with the simulated fields laid over it. No hook, trigger, other flow or audit row runs, since nothing is written. +- **Identity is the named user**, whose own grants the engine resolves, and the run is never elevated, a `runAs: 'system'` definition included. A `tenantId` must be an organization the user is a member of. Admission is the by-name start rule (`flowStartRefusal`), judged on the supplied definition against the named user; a refusal answers `status: 'refused'` with `PERMISSION_DENIED`, before any node runs. +- **A start condition that does not hold** answers `status: 'condition_not_met'` with the condition, mirroring the live run's skip exit. - **Approval nodes and waits stop the run** (every node type whose descriptor declares `supportsPause: true`), reported with who would be asked, what would resume it, the screen, or the flow it would start. Nothing is created or scheduled. - **Side effects outside the data** (`notify`, `http`, `connector_action`, `script`, `save_notice`) are never sent, only reported with their computed payload. - **Unarmed and unregistered**: never registered or listed, the trigger never armed, no run persisted, one pass with no retry. An invalid definition throws what `registerFlow` throws. -**In-process APIs.** `@objectstack/spec/contracts` exports `FlowDryRunOptions`, `FlowDryRunResult`, `FlowDryRunStatus`, `FlowDryRunRefusalCode`, `FlowDryRunStep` and the step types it unions over (`FlowDryRunStepBase`, `FlowDryRunRouteStep`, `FlowDryRunAssignmentStep`, `FlowDryRunDecisionStep`, `FlowDryRunReadStep`, `FlowDryRunWriteStep`, `FlowDryRunOutboundStep`, `FlowDryRunStopStep`). All additive. +**In-process APIs.** `@objectstack/spec/contracts` exports `FlowDryRunOptions`, `FlowDryRunResult`, `FlowDryRunStatus`, `FlowDryRunRefusalCode`, `FlowDryRunWritePermission`, `FlowDryRunStep` and the step types it unions over (`FlowDryRunStepBase`, `FlowDryRunRouteStep`, `FlowDryRunAssignmentStep`, `FlowDryRunDecisionStep`, `FlowDryRunReadStep`, `FlowDryRunWriteStep`, `FlowDryRunOutboundStep`, `FlowDryRunStopStep`). All additive. diff --git a/packages/spec/api-surface/contracts.json b/packages/spec/api-surface/contracts.json index b03433dabfc..5f02b9e20ee 100644 --- a/packages/spec/api-surface/contracts.json +++ b/packages/spec/api-surface/contracts.json @@ -2,6 +2,8 @@ "description": "Every exported `name (kind)` of one published entry point of @objectstack/spec — the breadth half of the ADR-0059 backward-compatibility gate. Sharded by entry point (#5837) so two PRs touching different entry points never share a file. Reads the BUILT dist/*.d.ts: regenerate with `pnpm --filter @objectstack/spec gen:api-surface` after a real build.", "entry": "./contracts", "exports": [ + "ACTION_CONFIRMATION_REFUSAL_REASONS (const)", + "ACTION_CONFIRMATION_SERVICE (const)", "AIActionConfirmation (interface)", "AIConversation (interface)", "AIMessage (type)", @@ -14,6 +16,7 @@ "AIToolCall (type)", "AIToolDefinition (interface)", "AIToolResult (type)", + "AI_ACTION_CONFIRMATION_CAPABILITY (const)", "AI_ACTION_CONFIRMATION_MEMBER (const)", "APPROVAL_ACTION_KINDS (const)", "APPROVAL_ACTION_KIND_LABELS (const)", @@ -23,6 +26,9 @@ "APPROVAL_STATUS_LABELS (const)", "AUDIT_CHECKPOINT_SIGNER_SERVICE (const)", "AUDIT_CHECKPOINT_SINK_SERVICE (const)", + "ActionConfirmationHandOff (interface)", + "ActionConfirmationPending (interface)", + "ActionConfirmationRefusalReason (type)", "ActionConfirmationRequiredDetails (interface)", "AdapterContext (interface)", "AdapterSearchOptions (interface)", @@ -136,6 +142,7 @@ "FlowDryRunStep (type)", "FlowDryRunStepBase (interface)", "FlowDryRunStopStep (interface)", + "FlowDryRunWritePermission (type)", "FlowDryRunWriteStep (interface)", "FlowRuntimeState (interface)", "FlowUnboundCause (type)", @@ -148,6 +155,7 @@ "HttpResponseObserver (type)", "IAIConversationService (interface)", "IAIService (interface)", + "IActionConfirmationService (interface)", "IAdvancedServiceRegistry (interface)", "IAnalyticsService (interface)", "IAppLifecycleService (interface)", diff --git a/packages/spec/export-origins/contracts.json b/packages/spec/export-origins/contracts.json index ecfad48997d..9fd8dab1644 100644 --- a/packages/spec/export-origins/contracts.json +++ b/packages/spec/export-origins/contracts.json @@ -2,6 +2,8 @@ "description": "Which SOURCE DECLARATION each name exported by one public entry point of @objectstack/spec resolves to, after its alias chain is unwound: `# ()`. Two exports share an origin string iff they are the same declaration — so equal origins across two entries are a harmless re-export, and different origins under one name are the #4411 dual-source trap. Generated from src/ (no build needed) and read by the export-surface pin tests, which compare against it instead of each building their own ts.createProgram — that was ~55s of compilation per CI lap and a non-deterministic timeout that ejected unrelated PRs from the merge queue (#4796). Sharded by entry point (#5837) so two retirement PRs never share a file. Carries NO line numbers: the pins asserted the line as `\\d+`, and recording it would rewrite this artifact on every edit that shifts a line in any .zod.ts. Regenerate with `pnpm --filter @objectstack/spec gen:export-origins` and read the diff.", "entry": "./contracts", "exports": { + "ACTION_CONFIRMATION_REFUSAL_REASONS": "src/contracts/ai-service.ts#ACTION_CONFIRMATION_REFUSAL_REASONS (const)", + "ACTION_CONFIRMATION_SERVICE": "src/contracts/ai-service.ts#ACTION_CONFIRMATION_SERVICE (const)", "AIActionConfirmation": "src/contracts/ai-service.ts#AIActionConfirmation (interface)", "AIConversation": "src/contracts/ai-service.ts#AIConversation (interface)", "AIMessage": "src/contracts/ai-service.ts#AIMessage (type)", @@ -14,6 +16,7 @@ "AIToolCall": "src/contracts/ai-service.ts#AIToolCall (type)", "AIToolDefinition": "src/contracts/ai-service.ts#AIToolDefinition (interface)", "AIToolResult": "src/contracts/ai-service.ts#AIToolResult (type)", + "AI_ACTION_CONFIRMATION_CAPABILITY": "src/contracts/ai-service.ts#AI_ACTION_CONFIRMATION_CAPABILITY (const)", "AI_ACTION_CONFIRMATION_MEMBER": "src/contracts/ai-service.ts#AI_ACTION_CONFIRMATION_MEMBER (const)", "APPROVAL_ACTION_KINDS": "src/contracts/approval-service.ts#APPROVAL_ACTION_KINDS (const)", "APPROVAL_ACTION_KIND_LABELS": "src/contracts/approval-service.ts#APPROVAL_ACTION_KIND_LABELS (const)", @@ -23,6 +26,9 @@ "APPROVAL_STATUS_LABELS": "src/contracts/approval-service.ts#APPROVAL_STATUS_LABELS (const)", "AUDIT_CHECKPOINT_SIGNER_SERVICE": "src/contracts/audit-checkpoint.ts#AUDIT_CHECKPOINT_SIGNER_SERVICE (const)", "AUDIT_CHECKPOINT_SINK_SERVICE": "src/contracts/audit-checkpoint.ts#AUDIT_CHECKPOINT_SINK_SERVICE (const)", + "ActionConfirmationHandOff": "src/contracts/ai-service.ts#ActionConfirmationHandOff (interface)", + "ActionConfirmationPending": "src/contracts/ai-service.ts#ActionConfirmationPending (interface)", + "ActionConfirmationRefusalReason": "src/contracts/ai-service.ts#ActionConfirmationRefusalReason (type)", "ActionConfirmationRequiredDetails": "src/contracts/ai-service.ts#ActionConfirmationRequiredDetails (interface)", "AdapterContext": "src/contracts/knowledge-adapter.ts#AdapterContext (interface)", "AdapterSearchOptions": "src/contracts/knowledge-adapter.ts#AdapterSearchOptions (interface)", @@ -136,6 +142,7 @@ "FlowDryRunStep": "src/contracts/automation-service.ts#FlowDryRunStep (type)", "FlowDryRunStepBase": "src/contracts/automation-service.ts#FlowDryRunStepBase (interface)", "FlowDryRunStopStep": "src/contracts/automation-service.ts#FlowDryRunStopStep (interface)", + "FlowDryRunWritePermission": "src/contracts/automation-service.ts#FlowDryRunWritePermission (type)", "FlowDryRunWriteStep": "src/contracts/automation-service.ts#FlowDryRunWriteStep (interface)", "FlowRuntimeState": "src/contracts/automation-service.ts#FlowRuntimeState (interface)", "FlowUnboundCause": "src/contracts/automation-service.ts#FlowUnboundCause (type)", @@ -148,6 +155,7 @@ "HttpResponseObserver": "src/contracts/http-server.ts#HttpResponseObserver (type)", "IAIConversationService": "src/contracts/ai-service.ts#IAIConversationService (interface)", "IAIService": "src/contracts/ai-service.ts#IAIService (interface)", + "IActionConfirmationService": "src/contracts/ai-service.ts#IActionConfirmationService (interface)", "IAdvancedServiceRegistry": "src/contracts/service-registry.ts#IAdvancedServiceRegistry (interface)", "IAnalyticsService": "src/contracts/analytics-service.ts#IAnalyticsService (interface)", "IAppLifecycleService": "src/contracts/app-lifecycle-service.ts#IAppLifecycleService (interface)", diff --git a/packages/spec/src/contracts/automation-dry-run.pin.test.ts b/packages/spec/src/contracts/automation-dry-run.pin.test.ts index 2db3dd4982c..b3b00649777 100644 --- a/packages/spec/src/contracts/automation-dry-run.pin.test.ts +++ b/packages/spec/src/contracts/automation-dry-run.pin.test.ts @@ -15,12 +15,12 @@ * 2. **The options name a user and carry no grants.** `userId` is a required * string; positions, permission sets, posture and email do not compile, so * a caller cannot dry-run with grants the user does not hold. - * 3. **The closed unions.** The four statuses, the three refusal codes (each - * an existing `AutomationResult.code` member, none minted) and the seven - * step kinds. + * 3. **The closed unions.** The five statuses, the two refusal codes (each + * an existing `AutomationResult.code` member, none minted), the seven + * step kinds, the three-way write permission and the six stop reasons. * 4. **The documented semantics.** The method's doc block states each ruled * point (writes, identity, admission, approvals and waits, outbound - * nodes, unarmed and unregistered). Prose is unassertable except by + * nodes, unarmed and unregistered, the start condition, step order). Prose is unassertable except by * reading it, so the contract source is read. * * ⛔ Not pinned here: the behaviour. That is #33661, in @@ -39,6 +39,7 @@ import type { FlowDryRunResult, FlowDryRunStatus, FlowDryRunStep, + FlowDryRunWritePermission, IAutomationService, } from './automation-service'; @@ -88,12 +89,15 @@ export const withEmail: FlowDryRunOptions = { userId: 'usr_maker', email: 'boss@ export const withRunAs: FlowDryRunOptions = { userId: 'usr_maker', runAs: 'system' }; /** 3. The closed unions, spelled once. `satisfies` proves membership; `Eq` proves there is nothing else. */ -export const DRY_RUN_STATUSES = ['completed', 'stopped', 'failed', 'refused'] as const satisfies readonly FlowDryRunStatus[]; -export type StatusIsExactlyTheFour = Assert< Eq< FlowDryRunStatus, (typeof DRY_RUN_STATUSES)[number] > >; +export const DRY_RUN_STATUSES = ['completed', 'condition_not_met', 'stopped', 'failed', 'refused'] as const satisfies readonly FlowDryRunStatus[]; +export type StatusIsExactlyTheFive = Assert< Eq< FlowDryRunStatus, (typeof DRY_RUN_STATUSES)[number] > >; export type ResultStatusIsTheUnion = Assert< Eq< FlowDryRunResult['status'], FlowDryRunStatus > >; -export const DRY_RUN_REFUSAL_CODES = ['PERMISSION_DENIED', 'FLOW_NO_START_NODE', 'FLOW_INPUT_SCHEMA_INVALID'] as const satisfies readonly FlowDryRunRefusalCode[]; -export type RefusalCodeIsExactlyTheThree = Assert< Eq< FlowDryRunRefusalCode, (typeof DRY_RUN_REFUSAL_CODES)[number] > >; +export const DRY_RUN_REFUSAL_CODES = ['PERMISSION_DENIED', 'FLOW_INPUT_SCHEMA_INVALID'] as const satisfies readonly FlowDryRunRefusalCode[]; +export type RefusalCodeIsExactlyTheTwo = Assert< Eq< FlowDryRunRefusalCode, (typeof DRY_RUN_REFUSAL_CODES)[number] > >; +// @ts-expect-error — registration refuses a definition with no start node, so a dry run throws before it could answer this code. +export const noStartNodeCode: FlowDryRunRefusalCode = 'FLOW_NO_START_NODE'; +export type StartConditionShape = Assert< Eq< NonNullable< FlowDryRunResult['startCondition'] >, { expression: string; result: false } > >; /** No code is minted: every refusal code is an existing `AutomationResult.code` member. */ export type RefusalCodesAreExisting = Assert< Eq< FlowDryRunRefusalCode extends NonNullable< AutomationResult['code'] > ? true : false, true > >; export type ResultRefusalShape = Assert< Eq< NonNullable< FlowDryRunResult['refusal'] >, { code: FlowDryRunRefusalCode; message: string } > >; @@ -101,18 +105,24 @@ export type ResultRefusalShape = Assert< Eq< NonNullable< FlowDryRunResult['refu export const DRY_RUN_STEP_KINDS = ['route', 'assignment', 'decision', 'read', 'write', 'outbound', 'stop'] as const satisfies readonly FlowDryRunStep['kind'][]; export type StepKindIsExactlyTheSeven = Assert< Eq< FlowDryRunStep['kind'], (typeof DRY_RUN_STEP_KINDS)[number] > >; export type WriteOperations = Assert< Eq< Extract< FlowDryRunStep, { kind: 'write' } >['operation'], 'create' | 'update' | 'delete' > >; -export type StopReasons = Assert< Eq< Extract< FlowDryRunStep, { kind: 'stop' } >['reason'], 'pause' | 'not_simulated' > >; +export type StopReasons = Assert< Eq< Extract< FlowDryRunStep, { kind: 'stop' } >['reason'], 'approval' | 'wait' | 'screen' | 'starts_flow' | 'suspends' | 'not_simulated' > >; +export const WRITE_PERMISSIONS = ['allowed', 'refused', 'not_judged'] as const satisfies readonly FlowDryRunWritePermission[]; +export type WritePermissionIsExactlyTheThree = Assert< Eq< FlowDryRunWritePermission, (typeof WRITE_PERMISSIONS)[number] > >; +/** Every write step answers the permission; it is never left out. */ +export type WriteStepPermissionRequired = Assert< Eq< Extract< FlowDryRunStep, { kind: 'write' } >['permission'], FlowDryRunWritePermission > >; +/** A decision reports every expression that held, not one. */ +export type DecisionExpressions = Assert< Eq< Extract< FlowDryRunStep, { kind: 'decision' } >['expressions'], string[] > >; /** A result an implementation can build without a cast: one ordered step list. */ export const stoppedAtApproval: FlowDryRunResult = { status: 'stopped', steps: [ { kind: 'route', nodeId: 'start', nodeType: 'start' }, - { kind: 'decision', nodeId: 'big_deal', nodeType: 'decision', branch: 'big', expression: 'record.amount > 100000', next: ['create_task'] }, - { kind: 'write', nodeId: 'create_task', nodeType: 'create_record', operation: 'create', object: 'task', recordIds: ['dryrun:create_task:1'], values: { subject: 'Review' } }, + { kind: 'decision', nodeId: 'big_deal', nodeType: 'decision', branch: 'big', expressions: ['record.amount > 100000'], next: ['create_task'] }, + { kind: 'write', nodeId: 'create_task', nodeType: 'create_record', operation: 'create', object: 'task', recordIds: ['dryrun:create_task:1'], values: { subject: 'Review' }, permission: 'allowed' }, { kind: 'assignment', nodeId: 'remember', nodeType: 'assignment', values: { taskId: 'dryrun:create_task:1' } }, { kind: 'outbound', nodeId: 'tell_owner', nodeType: 'notify', payload: { to: ['usr_owner'], body: 'Review' } }, - { kind: 'stop', nodeId: 'approve', nodeType: 'approval', reason: 'pause', approvers: ['usr_manager'] }, + { kind: 'stop', nodeId: 'approve', nodeType: 'approval', reason: 'approval', approvers: ['usr_manager'] }, ], }; export const refusedAtAdmission: FlowDryRunResult = { @@ -132,10 +142,15 @@ export const failedOnPermission: FlowDryRunResult = { object: 'opportunity', recordIds: ['opp_1'], values: { stage: 'closed' }, - refusal: { code: 'PERMISSION_DENIED', message: 'no edit access' }, + permission: 'refused', }, ], - error: 'update_record close_deal: no edit access', + error: 'update_record close_deal: the named user may not update opportunity', +}; +export const conditionNotMet: FlowDryRunResult = { + status: 'condition_not_met', + steps: [], + startCondition: { expression: 'record.stage == "won" && previous.stage != "won"', result: false }, }; // @ts-expect-error — a dry run has no run to resume or read back: no `runId`. export const withRunId: FlowDryRunResult = { status: 'completed', steps: [], runId: 'run_1' }; @@ -172,6 +187,8 @@ describe('IAutomationService.dryRun — the contract (#33757)', () => { '**Writes: simulated, never made.**', '**Side effects outside the data.**', '**Approval nodes and waits: the run stops.**', + '**The name.**', + '**Step order.**', ]) { expect(doc, heading).toContain(heading); } @@ -183,6 +200,12 @@ describe('IAutomationService.dryRun — the contract (#33757)', () => { 'never send or call anything', 'no child run starts.', 'every named user.', + "`status: 'condition_not_met'`", + "`'not_judged'` never means allowed.", + 'the simulated fields laid over it', + 'holds only the fields the flow set', + 'each branch\'s steps together', + 'could not continue past this', ]) { expect(doc, sentence).toContain(sentence); } diff --git a/packages/spec/src/contracts/automation-service.ts b/packages/spec/src/contracts/automation-service.ts index acbf0d108b4..d6385572f81 100644 --- a/packages/spec/src/contracts/automation-service.ts +++ b/packages/spec/src/contracts/automation-service.ts @@ -1447,12 +1447,22 @@ export interface ConnectorConnectionCallbackRequest { * resolves the named user's own, so a caller cannot run a dry run with grants * the user does not hold. */ -export interface FlowDryRunOptions extends Pick { +export interface FlowDryRunOptions extends Pick { /** * The acting user, a `sys_user` id. Required: a dry run always acts as a * named user, so it never meets `AUTOMATION_UNSCOPED_RUN_DATA_ACCESS`. */ userId: string; + /** + * The organization the run is in, read as {@link AutomationContext.tenantId}. + * It must be an organization the named user is a member of; any other is + * refused before any node runs (`status: 'refused'`, + * `PERMISSION_DENIED`). That refusal is the dry run's own: a live run's + * setup refuses no organization, it only resolves none of the user's + * grants there. Absent, the run is in no organization, as a by-name start + * that carries none. + */ + tenantId?: string; } /** @@ -1461,23 +1471,36 @@ export interface FlowDryRunOptions extends Pick, 'PERMISSION_DENIED' | 'FLOW_NO_START_NODE' | 'FLOW_INPUT_SCHEMA_INVALID'>; +export type FlowDryRunRefusalCode = Extract, 'PERMISSION_DENIED' | 'FLOW_INPUT_SCHEMA_INVALID'>; /** What every step of a dry run reports. */ export interface FlowDryRunStepBase { @@ -1486,9 +1509,9 @@ export interface FlowDryRunStepBase { /** The node's `type` as the definition declares it. */ nodeType: string; /** - * The refusal this node met, as a failed live run reports it - * ({@link AutomationResult.innerRefusal}): the permission refusal the named - * user would meet, for example. Absent when the node met none. + * A refusal this node met, as a failed live run reports it + * ({@link AutomationResult.innerRefusal}): a read refused in the named + * user's scope, for example. Absent when the node met none. */ refusal?: FlowInnerRefusal; /** The node's failure text when it failed for a reason other than a refusal. */ @@ -1496,8 +1519,8 @@ export interface FlowDryRunStepBase { } /** - * A node that only routes the run: `start`, `end`, `loop`, - * `parallel_gateway`, `join_gateway` and `try_catch`. + * A node that only routes the run: `start`, `end`, `loop`, `parallel` and + * `try_catch`. */ export interface FlowDryRunRouteStep extends FlowDryRunStepBase { kind: 'route'; @@ -1521,16 +1544,17 @@ export interface FlowDryRunDecisionStep extends FlowDryRunStepBase { */ branch?: string; /** - * Why: the authored expression that held (the condition entry's, or the - * out-edge's). Absent when the run took the default branch because none - * held. + * Why: every authored expression that held, in declaration order. One for + * a `config.conditions` entry or an exclusive decision's out-edge; one per + * branch taken for `mode: 'inclusive'`. Empty when the run took the + * default branch because none held. */ - expression?: string; + expressions: string[]; /** The ids of the nodes the run went on to; more than one only for `mode: 'inclusive'`. */ next: string[]; } -/** A `get_record` node: the live rows it read, in the named user's scope. */ +/** A `get_record` node: the rows it read, in the named user's scope. */ export interface FlowDryRunReadStep extends FlowDryRunStepBase { kind: 'read'; object: string; @@ -1538,6 +1562,22 @@ export interface FlowDryRunReadStep extends FlowDryRunStepBase { recordIds: string[]; } +/** + * Whether the named user may make a simulated write, as far as a dry run can + * judge it without writing. + * + * - `'allowed'` / `'refused'`: the answer of the object-level write check + * (`canWriteObject`, insert or update) for the named user. `'allowed'` says + * that check admits the write, never that the write would succeed. + * - `'not_judged'`: what that check does not judge. Every delete (the check + * has no delete arm). For an insert or update, nothing else is judged + * either: row-level and post-image rules (the RLS `using` pre-image and + * `check` post-image), controlled-by-parent, the tenant post-image, + * provenance gates and the `owner_id` forge are never reported. ⛔ + * `'not_judged'` never means allowed. + */ +export type FlowDryRunWritePermission = 'allowed' | 'refused' | 'not_judged'; + /** * A `create_record`, `update_record` or `delete_record` node: the write it * would make. ⛔ Nothing was written. @@ -1556,6 +1596,8 @@ export interface FlowDryRunWriteStep extends FlowDryRunStepBase { * The field values as the node computed them; absent for a delete. */ values?: Record; + /** The named user's permission for this write, as far as a dry run judges it. */ + permission: FlowDryRunWritePermission; } /** @@ -1579,12 +1621,18 @@ export interface FlowDryRunOutboundStep extends FlowDryRunStepBase { export interface FlowDryRunStopStep extends FlowDryRunStepBase { kind: 'stop'; /** - * `'pause'`: the node type's descriptor declares `supportsPause: true` - * (`approval`, `wait`, `screen`, `subflow` and `map` among the shipped - * ones). `'not_simulated'`: a node type outside every class this contract - * names, whose effect a dry run cannot know. - */ - reason: 'pause' | 'not_simulated'; + * What the node would do that a dry run does not: + * - `'approval'`: ask people to decide (the approvals plugin's `approval` + * and `approval_revise` nodes); + * - `'wait'`: wait for a timer or a signal (`wait`); + * - `'screen'`: ask the person for input (`screen`); + * - `'starts_flow'`: start another flow (`subflow`, `map`); + * - `'suspends'`: suspend the run for another reason (any other node type + * whose descriptor declares `supportsPause: true`); + * - `'not_simulated'`: something a dry run cannot know (a node type + * outside every class this contract names). + */ + reason: 'approval' | 'wait' | 'screen' | 'starts_flow' | 'suspends' | 'not_simulated'; /** An approval node: the ids of the users it would ask, when the run can resolve them. */ approvers?: string[]; /** A `wait` node: what would resume it, from its `waitEventConfig`. */ @@ -1609,12 +1657,24 @@ export type FlowDryRunStep = export interface FlowDryRunResult { status: FlowDryRunStatus; /** - * One entry per node execution, in the order the run executed them: a node - * inside a loop appears once per pass. Empty when `status` is `'refused'`. + * One entry per node execution: a node inside a loop appears once per + * pass. Empty when `status` is `'refused'` or `'condition_not_met'`. + * Branches that run side by side (a `parallel` node's branches, a node's + * several unconditional out-edges) are listed one branch after another, in + * declaration order (`config.branches`, then out-edges), each branch's + * steps together; an inclusive decision's branches likewise, as the live + * run takes them one at a time. Otherwise steps are in the order the run + * executed them. */ steps: FlowDryRunStep[]; /** Set exactly when `status` is `'refused'`: why the run never started. */ refusal?: { code: FlowDryRunRefusalCode; message: string }; + /** + * Set exactly when `status` is `'condition_not_met'`: the start node's + * `condition` as authored (its `source`, for an expression envelope) and + * what it evaluated to against the supplied `record` / `previous`. + */ + startCondition?: { expression: string; result: false }; /** Set exactly when `status` is `'failed'`: the run's failure text. */ error?: string; } @@ -1708,15 +1768,28 @@ export interface IAutomationService { * **In what order it answers.** * - `options.userId` that is not a non-empty string: throws a `TypeError` * before the definition is read. - * - A definition {@link registerFlow} would refuse: throws what - * {@link registerFlow} throws for the same definition. Nothing is + * - A definition {@link registerFlow} would refuse under the definition's + * own `name`: throws what {@link registerFlow} throws for it. Nothing is * registered. - * - Admission, then the trigger-time refusals {@link execute} classifies - * before dispatch (`FLOW_NO_START_NODE`, `FLOW_INPUT_SCHEMA_INVALID`): + * - A `tenantId` naming an organization the named user is not a member + * of, then admission, then the trigger-time refusal {@link execute} + * classifies before dispatch (`FLOW_INPUT_SCHEMA_INVALID`): * `status: 'refused'` with that code in `refusal` and no steps. No node * has run. + * - A start node whose `condition` does not hold for the supplied `record` + * / `previous`: `status: 'condition_not_met'`, the condition and its + * value in `startCondition`, and no steps. This mirrors the live run's + * skip exit, which evaluates the same condition at the same point + * (`execute`, `output: { skipped: true, reason: 'condition_not_met' }`, + * `engine.ts` in `@objectstack/service-automation`). * - Otherwise the nodes run, as described below. * + * **The name.** The definition's own `name` is the flow's name for the + * call: the name registration judges, and the one nodes read their per-flow + * keys under (the `flows..…` translation keys). It is never looked + * up among registered flows, and a registered flow of that name is neither + * read nor touched. + * * **Unarmed and unregistered.** * - The definition is never registered: {@link listFlows} and * {@link getFlow} do not answer it during or after the call. @@ -1759,24 +1832,37 @@ export interface IAutomationService { * write it would make ({@link FlowDryRunWriteStep}). * - A create binds a placeholder id to the new row: opaque, unique within * the call, and never the id of a live row. - * - A later read by id of a row the run created or updated answers the - * simulated values, and of a row the run deleted answers nothing. + * - A later read by id of a row the run updated answers the live row with + * the simulated fields laid over it; of a row the run deleted, nothing. + * - A row the run created holds only the fields the flow set. The fields + * the engine sets on a real insert (defaults, autonumbers, formulas, the + * owner, timestamps) are absent from it, so a later node that reads one + * finds it unset. * - A read that filters rather than names an id answers the live rows the * named user can read, and does not see the run's simulated writes. * - Since nothing is written, nothing a write sets off runs: no record * hook, no record-change trigger, no other flow, no audit row. * - The data engine does not judge a simulated write, so a write it would * refuse for a validation rule, a uniqueness constraint or a required - * field reports as it would be made. A permission refusal is the - * exception: the step carries, in `refusal`, the refusal the named user - * would meet for that operation on that object or row. + * field reports as it would be made. + * - Each write step carries a three-way `permission` + * ({@link FlowDryRunWritePermission}): `'allowed'` or `'refused'` from + * the object-level write check (`canWriteObject`, insert or update) for + * the named user, and `'not_judged'` for every delete and for every + * refusal that check does not judge (row-level and post-image rules, + * controlled-by-parent, the tenant post-image, provenance gates, the + * `owner_id` forge). `'not_judged'` never means allowed. A `'refused'` + * write is a refusal the step met (below). * * **Reads.** `get_record` reads live data, in the named user's scope. * * **A node that meets a refusal or fails.** It is reported, never skipped * silently: its step carries the refusal or the failure, and the run goes - * on as the live run would, along a `fault` edge or out of a `try_catch` - * region that contains it, or else it ends `'failed'`. + * on along a `fault` edge or out of a `try_catch` region that contains it, + * or else it ends `'failed'`: the dry run could not continue past this + * step. That is the dry run's own answer, in both directions: it can fail + * where the live run would not, and pass where the live run would fail + * ({@link FlowDryRunStatus}). * * **Side effects outside the data.** `notify`, `http`, `connector_action`, * `script` and `save_notice` never send or call anything. Each reports the @@ -1786,15 +1872,22 @@ export interface IAutomationService { * **Approval nodes and waits: the run stops.** At the first node whose type's * descriptor declares `supportsPause: true` (an approval, a `wait`, a * `screen`, a `subflow`, a `map`), the run stops with `status: 'stopped'` - * and reports the node: who it would ask, how long or for what it would - * wait, the screen it would show, or the flow it would start - * ({@link FlowDryRunStopStep}). No approval request is created, no resume - * is scheduled, and no child run starts. A node type outside every class - * named here also stops the run (`reason: 'not_simulated'`). + * and reports the node and what it would do: who it would ask, how long or + * for what it would wait, the screen it would show, or the flow it would + * start ({@link FlowDryRunStopStep}). No approval request is created, no + * resume is scheduled, and no child run starts. A node type outside every + * class named here also stops the run (`reason: 'not_simulated'`). * * **Nodes that route or compute** (`start`, `end`, `decision`, - * `assignment`, `loop`, `parallel_gateway`, `join_gateway`, `try_catch`) - * run as the live run runs them, and report what they did. + * `assignment`, `loop`, `parallel`, `try_catch`) run as the live run runs + * them, and report what they did. + * + * **Step order.** One list ({@link FlowDryRunResult.steps}). Branches that + * run side by side (a `parallel` node's branches, a node's several + * unconditional out-edges) are listed one branch after another in + * declaration order, each branch's steps together, as the `parallel` node's + * own run record lists them; an inclusive decision's branches likewise, as + * the live run takes them one at a time. * * @param definition - The flow definition (raw, pre-parse), as * {@link registerFlow} takes it From 5753362e87b135179c2a4067fd5cb27e1a459b57 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 12:24:19 +0000 Subject: [PATCH 4/6] feat(spec): dryRun contract round 3, answer order follows execute The start condition answers before the node input-schema refusal, as execute evaluates them, and the pin asserts that order. A refused write step carries its refusal, the method and type docs agree on the three-way permission and say every write is not_judged with no object-level check installed, and unconditional fan-out order is named as the dry run's own. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5nK9bbdtG9bJTBujTZ --- .../contracts/automation-dry-run.pin.test.ts | 18 ++++- .../spec/src/contracts/automation-service.ts | 74 ++++++++++++------- 2 files changed, 63 insertions(+), 29 deletions(-) diff --git a/packages/spec/src/contracts/automation-dry-run.pin.test.ts b/packages/spec/src/contracts/automation-dry-run.pin.test.ts index b3b00649777..b9632565784 100644 --- a/packages/spec/src/contracts/automation-dry-run.pin.test.ts +++ b/packages/spec/src/contracts/automation-dry-run.pin.test.ts @@ -18,7 +18,7 @@ * 3. **The closed unions.** The five statuses, the two refusal codes (each * an existing `AutomationResult.code` member, none minted), the seven * step kinds, the three-way write permission and the six stop reasons. - * 4. **The documented semantics.** The method's doc block states each ruled + * 4. **The documented semantics, and the answer order.** The method's doc block states each ruled * point (writes, identity, admission, approvals and waits, outbound * nodes, unarmed and unregistered, the start condition, step order). Prose is unassertable except by * reading it, so the contract source is read. @@ -143,6 +143,7 @@ export const failedOnPermission: FlowDryRunResult = { recordIds: ['opp_1'], values: { stage: 'closed' }, permission: 'refused', + refusal: { code: 'PERMISSION_DENIED', message: 'the named user may not update opportunity' }, }, ], error: 'update_record close_deal: the named user may not update opportunity', @@ -206,8 +207,23 @@ describe('IAutomationService.dryRun — the contract (#33757)', () => { 'holds only the fields the flow set', 'each branch\'s steps together', 'could not continue past this', + 'With no object-level check\n * installed, every write step answers `\'not_judged\'`.', + "its step carries\n * `refusal` (`code: 'PERMISSION_DENIED'`)", + "For a node's unconditional\n * out-edges this is the dry run's own order", ]) { expect(doc, sentence).toContain(sentence); } }); + + it('answers in the live run\'s order: admission, then the start condition, then the input-schema check', () => { + const source = readFileSync(fileURLToPath(new URL('./automation-service.ts', import.meta.url)), 'utf8'); + const end = source.indexOf('dryRun?(definition: unknown, options: FlowDryRunOptions)'); + const doc = source.slice(source.lastIndexOf('/**', end), end); + const order = [ + doc.indexOf("then admission: `status: 'refused'`, `PERMISSION_DENIED` in"), + doc.indexOf('Then the start condition.'), + doc.indexOf('Then the node input-schema check'), + ]; + expect(order.every((i) => i >= 0) && order[0] < order[1] && order[1] < order[2], `answer order at ${order.join(', ')}`).toBe(true); + }); }); diff --git a/packages/spec/src/contracts/automation-service.ts b/packages/spec/src/contracts/automation-service.ts index d6385572f81..347e545f59f 100644 --- a/packages/spec/src/contracts/automation-service.ts +++ b/packages/spec/src/contracts/automation-service.ts @@ -1566,15 +1566,20 @@ export interface FlowDryRunReadStep extends FlowDryRunStepBase { * Whether the named user may make a simulated write, as far as a dry run can * judge it without writing. * - * - `'allowed'` / `'refused'`: the answer of the object-level write check - * (`canWriteObject`, insert or update) for the named user. `'allowed'` says - * that check admits the write, never that the write would succeed. - * - `'not_judged'`: what that check does not judge. Every delete (the check - * has no delete arm). For an insert or update, nothing else is judged - * either: row-level and post-image rules (the RLS `using` pre-image and - * `check` post-image), controlled-by-parent, the tenant post-image, - * provenance gates and the `owner_id` forge are never reported. ⛔ + * - `'allowed'` / `'refused'`: an insert or an update, answered by the + * object-level write check (`canWriteObject`, insert or update) for the + * named user. `'allowed'` says that check admits the write, never that the + * write would succeed. + * - `'not_judged'`: every delete (the check has no delete arm), and every + * write when no object-level check is installed. `canWriteObject` is a + * method of `@objectstack/plugin-security`'s service, not of + * `ISecurityService`, so a kernel without that plugin has none. ⛔ * `'not_judged'` never means allowed. + * + * Never reported, for any operation, whatever the answer: the refusals that + * check does not judge, which are row-level and post-image rules (the RLS + * `using` pre-image and `check` post-image), controlled-by-parent, the tenant + * post-image, provenance gates and the `owner_id` forge. */ export type FlowDryRunWritePermission = 'allowed' | 'refused' | 'not_judged'; @@ -1663,8 +1668,9 @@ export interface FlowDryRunResult { * several unconditional out-edges) are listed one branch after another, in * declaration order (`config.branches`, then out-edges), each branch's * steps together; an inclusive decision's branches likewise, as the live - * run takes them one at a time. Otherwise steps are in the order the run - * executed them. + * run takes them one at a time. For unconditional out-edges that is the + * dry run's own order, and it can differ from the live step log, which can + * interleave them. Otherwise steps are in the order the run executed them. */ steps: FlowDryRunStep[]; /** Set exactly when `status` is `'refused'`: why the run never started. */ @@ -1772,17 +1778,21 @@ export interface IAutomationService { * own `name`: throws what {@link registerFlow} throws for it. Nothing is * registered. * - A `tenantId` naming an organization the named user is not a member - * of, then admission, then the trigger-time refusal {@link execute} - * classifies before dispatch (`FLOW_INPUT_SCHEMA_INVALID`): - * `status: 'refused'` with that code in `refusal` and no steps. No node - * has run. - * - A start node whose `condition` does not hold for the supplied `record` - * / `previous`: `status: 'condition_not_met'`, the condition and its - * value in `startCondition`, and no steps. This mirrors the live run's - * skip exit, which evaluates the same condition at the same point + * of, then admission: `status: 'refused'`, `PERMISSION_DENIED` in + * `refusal`, and no steps. + * - Then the start condition. A start node whose `condition` does not hold + * for the supplied `record` / `previous` answers + * `status: 'condition_not_met'`, the condition and its value in + * `startCondition`, and no steps. This mirrors the live run's skip exit * (`execute`, `output: { skipped: true, reason: 'condition_not_met' }`, - * `engine.ts` in `@objectstack/service-automation`). - * - Otherwise the nodes run, as described below. + * `engine.ts` in `@objectstack/service-automation`), in the live run's + * order: `execute` evaluates the start condition before its node + * input-schema check, so a condition that does not hold answers first. + * - Then the node input-schema check {@link execute} runs before dispatch: + * `status: 'refused'`, `FLOW_INPUT_SCHEMA_INVALID` in `refusal`, and no + * steps. + * - No node has run before any of these answers. Otherwise the nodes run, + * as described below. * * **The name.** The definition's own `name` is the flow's name for the * call: the name registration judges, and the one nodes read their per-flow @@ -1846,13 +1856,19 @@ export interface IAutomationService { * refuse for a validation rule, a uniqueness constraint or a required * field reports as it would be made. * - Each write step carries a three-way `permission` - * ({@link FlowDryRunWritePermission}): `'allowed'` or `'refused'` from - * the object-level write check (`canWriteObject`, insert or update) for - * the named user, and `'not_judged'` for every delete and for every - * refusal that check does not judge (row-level and post-image rules, - * controlled-by-parent, the tenant post-image, provenance gates, the - * `owner_id` forge). `'not_judged'` never means allowed. A `'refused'` - * write is a refusal the step met (below). + * ({@link FlowDryRunWritePermission}). An insert or an update answers + * `'allowed'` or `'refused'`, from the object-level write check + * (`canWriteObject`, insert or update) for the named user; `'allowed'` + * never means the write would succeed. A delete answers `'not_judged'`, + * since that check has no delete arm. With no object-level check + * installed, every write step answers `'not_judged'`. + * `'not_judged'` never means allowed. + * - The refusals that check does not judge are never reported, for any + * operation: row-level and post-image rules, controlled-by-parent, the + * tenant post-image, provenance gates, the `owner_id` forge. + * - A `'refused'` write is a refusal the step met: its step carries + * `refusal` (`code: 'PERMISSION_DENIED'`), and the run goes on as after + * any refusal (below). * * **Reads.** `get_record` reads live data, in the named user's scope. * @@ -1887,7 +1903,9 @@ export interface IAutomationService { * unconditional out-edges) are listed one branch after another in * declaration order, each branch's steps together, as the `parallel` node's * own run record lists them; an inclusive decision's branches likewise, as - * the live run takes them one at a time. + * the live run takes them one at a time. For a node's unconditional + * out-edges this is the dry run's own order: the live run runs those + * branches under `Promise.all`, and its step log can interleave them. * * @param definition - The flow definition (raw, pre-parse), as * {@link registerFlow} takes it From 58c56c9515b06dbd226a29a743916152868012de Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 13:33:07 +0000 Subject: [PATCH 5/6] feat(spec): dryRun contract round 4, a start condition that throws answers failed A start node condition whose evaluation throws answers status 'failed' with no steps, before the node input-schema check, as execute's catch does; startCondition carries the expression and the fault. The answer order says the re-entrancy guard cannot fire for a dry run, and the changeset's not_judged sentence now matches the contract. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5nK9bbdtG9bJTBujTZ --- .changeset/33757-flow-dry-run-contract.md | 4 +- .../contracts/automation-dry-run.pin.test.ts | 25 +++++++++-- .../spec/src/contracts/automation-service.ts | 42 +++++++++++++++---- 3 files changed, 57 insertions(+), 14 deletions(-) diff --git a/.changeset/33757-flow-dry-run-contract.md b/.changeset/33757-flow-dry-run-contract.md index 710d39f187c..7d110466fe1 100644 --- a/.changeset/33757-flow-dry-run-contract.md +++ b/.changeset/33757-flow-dry-run-contract.md @@ -9,9 +9,9 @@ Metadata-protocol: none The contract half of #33661 (objectstack-ai/cloud#3309 item 5, option A, ruled by the account owner); #33661 implements it in `@objectstack/service-automation` and `@objectstack/runtime`. The method's doc block states the semantics the implementation owes: -- **Writes are simulated, never made.** `create_record`, `update_record` and `delete_record` report the write they would make (object, operation, target rows, values as computed) and a three-way `permission` (`allowed` / `refused` from the object-level write check, `not_judged` for deletes and every row-level refusal; `not_judged` never means allowed). A create binds an opaque placeholder id that later reads by id see, holding only the fields the flow set; an updated row reads as the live row with the simulated fields laid over it. No hook, trigger, other flow or audit row runs, since nothing is written. +- **Writes are simulated, never made.** `create_record`, `update_record` and `delete_record` report the write they would make (object, operation, target rows, values as computed) and a three-way `permission`: an insert or update answers `allowed` or `refused` from the object-level write check, a delete answers `not_judged`, and every write answers `not_judged` when no object-level check is installed; `not_judged` never means allowed, and row-level refusals are never reported. A create binds an opaque placeholder id that later reads by id see, holding only the fields the flow set; an updated row reads as the live row with the simulated fields laid over it. No hook, trigger, other flow or audit row runs, since nothing is written. - **Identity is the named user**, whose own grants the engine resolves, and the run is never elevated, a `runAs: 'system'` definition included. A `tenantId` must be an organization the user is a member of. Admission is the by-name start rule (`flowStartRefusal`), judged on the supplied definition against the named user; a refusal answers `status: 'refused'` with `PERMISSION_DENIED`, before any node runs. -- **A start condition that does not hold** answers `status: 'condition_not_met'` with the condition, mirroring the live run's skip exit. +- **A start condition that does not hold** answers `status: 'condition_not_met'` with the condition, mirroring the live run's skip exit. One whose evaluation throws answers `status: 'failed'` with no steps, the condition and the thrown message in `startCondition`, as the live run's catch does; both answer before the node input-schema check. - **Approval nodes and waits stop the run** (every node type whose descriptor declares `supportsPause: true`), reported with who would be asked, what would resume it, the screen, or the flow it would start. Nothing is created or scheduled. - **Side effects outside the data** (`notify`, `http`, `connector_action`, `script`, `save_notice`) are never sent, only reported with their computed payload. - **Unarmed and unregistered**: never registered or listed, the trigger never armed, no run persisted, one pass with no retry. An invalid definition throws what `registerFlow` throws. diff --git a/packages/spec/src/contracts/automation-dry-run.pin.test.ts b/packages/spec/src/contracts/automation-dry-run.pin.test.ts index b9632565784..01dfb5aabe6 100644 --- a/packages/spec/src/contracts/automation-dry-run.pin.test.ts +++ b/packages/spec/src/contracts/automation-dry-run.pin.test.ts @@ -97,7 +97,12 @@ export const DRY_RUN_REFUSAL_CODES = ['PERMISSION_DENIED', 'FLOW_INPUT_SCHEMA_IN export type RefusalCodeIsExactlyTheTwo = Assert< Eq< FlowDryRunRefusalCode, (typeof DRY_RUN_REFUSAL_CODES)[number] > >; // @ts-expect-error — registration refuses a definition with no start node, so a dry run throws before it could answer this code. export const noStartNodeCode: FlowDryRunRefusalCode = 'FLOW_NO_START_NODE'; -export type StartConditionShape = Assert< Eq< NonNullable< FlowDryRunResult['startCondition'] >, { expression: string; result: false } > >; +export type StartConditionShape = Assert< Eq< + NonNullable< FlowDryRunResult['startCondition'] >, + { expression: string; result: false; fault?: never } | { expression: string; fault: string; result?: never } +> >; +// @ts-expect-error — a start condition either did not hold or could not be evaluated, never both. +export const bothResultAndFault: NonNullable< FlowDryRunResult['startCondition'] > = { expression: 'record.x', result: false, fault: 'boom' }; /** No code is minted: every refusal code is an existing `AutomationResult.code` member. */ export type RefusalCodesAreExisting = Assert< Eq< FlowDryRunRefusalCode extends NonNullable< AutomationResult['code'] > ? true : false, true > >; export type ResultRefusalShape = Assert< Eq< NonNullable< FlowDryRunResult['refusal'] >, { code: FlowDryRunRefusalCode; message: string } > >; @@ -153,6 +158,16 @@ export const conditionNotMet: FlowDryRunResult = { steps: [], startCondition: { expression: 'record.stage == "won" && previous.stage != "won"', result: false }, }; +/** A start condition that throws when evaluated: `'failed'`, no steps, the fault beside the condition. */ +export const conditionFaulted: FlowDryRunResult = { + status: 'failed', + steps: [], + startCondition: { + expression: 'record.amount > "high"', + fault: 'condition failed to evaluate as CEL: no such overload — source: `record.amount > "high"`.', + }, + error: 'condition failed to evaluate as CEL: no such overload — source: `record.amount > "high"`.', +}; // @ts-expect-error — a dry run has no run to resume or read back: no `runId`. export const withRunId: FlowDryRunResult = { status: 'completed', steps: [], runId: 'run_1' }; @@ -210,20 +225,24 @@ describe('IAutomationService.dryRun — the contract (#33757)', () => { 'With no object-level check\n * installed, every write step answers `\'not_judged\'`.', "its step carries\n * `refusal` (`code: 'PERMISSION_DENIED'`)", "For a node's unconditional\n * out-edges this is the dry run's own order", + "A `condition` whose evaluation throws", + "`status: 'failed'` and no steps, the condition and the thrown message\n * in `startCondition` (`fault`)", + 'cannot fire for a dry run: a dry run holds no\n * active-run key and writes nothing.', ]) { expect(doc, sentence).toContain(sentence); } }); - it('answers in the live run\'s order: admission, then the start condition, then the input-schema check', () => { + it('answers in the live run\'s order: admission, then the start condition (unmet, then faulted), then the input-schema check', () => { const source = readFileSync(fileURLToPath(new URL('./automation-service.ts', import.meta.url)), 'utf8'); const end = source.indexOf('dryRun?(definition: unknown, options: FlowDryRunOptions)'); const doc = source.slice(source.lastIndexOf('/**', end), end); const order = [ doc.indexOf("then admission: `status: 'refused'`, `PERMISSION_DENIED` in"), doc.indexOf('Then the start condition.'), + doc.indexOf('A `condition` whose evaluation throws'), doc.indexOf('Then the node input-schema check'), ]; - expect(order.every((i) => i >= 0) && order[0] < order[1] && order[1] < order[2], `answer order at ${order.join(', ')}`).toBe(true); + expect(order.every((i, k) => i >= 0 && (k === 0 || order[k - 1] < i)), `answer order at ${order.join(', ')}`).toBe(true); }); }); diff --git a/packages/spec/src/contracts/automation-service.ts b/packages/spec/src/contracts/automation-service.ts index 347e545f59f..223d130181b 100644 --- a/packages/spec/src/contracts/automation-service.ts +++ b/packages/spec/src/contracts/automation-service.ts @@ -1478,15 +1478,20 @@ export interface FlowDryRunOptions extends Pick Date: Sun, 15 Nov 2026 14:38:17 +0000 Subject: [PATCH 6/6] feat(spec): dryRun contract round 5, qualify the faulting condition by error strategy The faulting start condition's answer follows the live run on the default error strategy only. Under errorHandling.strategy 'retry' the live run's retry attempts do not evaluate the start condition, so the dry run's answer is its own there; the order list, the 'failed' doc, the startCondition doc and the changeset say so and name the engine card. Rewrap the long line in the 'failed' doc. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5nK9bbdtG9bJTBujTZ --- .changeset/33757-flow-dry-run-contract.md | 2 +- .../contracts/automation-dry-run.pin.test.ts | 21 ++++++++++ .../spec/src/contracts/automation-service.ts | 38 +++++++++++++------ 3 files changed, 48 insertions(+), 13 deletions(-) diff --git a/.changeset/33757-flow-dry-run-contract.md b/.changeset/33757-flow-dry-run-contract.md index 7d110466fe1..69df3e0e043 100644 --- a/.changeset/33757-flow-dry-run-contract.md +++ b/.changeset/33757-flow-dry-run-contract.md @@ -11,7 +11,7 @@ The contract half of #33661 (objectstack-ai/cloud#3309 item 5, option A, ruled b - **Writes are simulated, never made.** `create_record`, `update_record` and `delete_record` report the write they would make (object, operation, target rows, values as computed) and a three-way `permission`: an insert or update answers `allowed` or `refused` from the object-level write check, a delete answers `not_judged`, and every write answers `not_judged` when no object-level check is installed; `not_judged` never means allowed, and row-level refusals are never reported. A create binds an opaque placeholder id that later reads by id see, holding only the fields the flow set; an updated row reads as the live row with the simulated fields laid over it. No hook, trigger, other flow or audit row runs, since nothing is written. - **Identity is the named user**, whose own grants the engine resolves, and the run is never elevated, a `runAs: 'system'` definition included. A `tenantId` must be an organization the user is a member of. Admission is the by-name start rule (`flowStartRefusal`), judged on the supplied definition against the named user; a refusal answers `status: 'refused'` with `PERMISSION_DENIED`, before any node runs. -- **A start condition that does not hold** answers `status: 'condition_not_met'` with the condition, mirroring the live run's skip exit. One whose evaluation throws answers `status: 'failed'` with no steps, the condition and the thrown message in `startCondition`, as the live run's catch does; both answer before the node input-schema check. +- **A start condition that does not hold** answers `status: 'condition_not_met'` with the condition, mirroring the live run's skip exit. One whose evaluation throws answers `status: 'failed'` with no steps, the condition and the thrown message in `startCondition`, as the live run's catch does on the default error strategy; under `errorHandling.strategy: 'retry'` the live run's retry attempts do not evaluate the start condition (#33935), so there the dry run's answer is its own. Both answer before the node input-schema check. - **Approval nodes and waits stop the run** (every node type whose descriptor declares `supportsPause: true`), reported with who would be asked, what would resume it, the screen, or the flow it would start. Nothing is created or scheduled. - **Side effects outside the data** (`notify`, `http`, `connector_action`, `script`, `save_notice`) are never sent, only reported with their computed payload. - **Unarmed and unregistered**: never registered or listed, the trigger never armed, no run persisted, one pass with no retry. An invalid definition throws what `registerFlow` throws. diff --git a/packages/spec/src/contracts/automation-dry-run.pin.test.ts b/packages/spec/src/contracts/automation-dry-run.pin.test.ts index 01dfb5aabe6..c89998fded5 100644 --- a/packages/spec/src/contracts/automation-dry-run.pin.test.ts +++ b/packages/spec/src/contracts/automation-dry-run.pin.test.ts @@ -228,11 +228,32 @@ describe('IAutomationService.dryRun — the contract (#33757)', () => { "A `condition` whose evaluation throws", "`status: 'failed'` and no steps, the condition and the thrown message\n * in `startCondition` (`fault`)", 'cannot fire for a dry run: a dry run holds no\n * active-run key and writes nothing.', + "On the default error strategy that is\n * the live run's answer", + "Under `errorHandling.strategy: 'retry'` the answer is the dry run's\n * own", ]) { expect(doc, sentence).toContain(sentence); } }); + it('a faulting start condition follows the live run only on the default error strategy (#33935)', () => { + const source = readFileSync(fileURLToPath(new URL('./automation-service.ts', import.meta.url)), 'utf8'); + const statusEnd = source.indexOf('export type FlowDryRunStatus ='); + const resultStart = source.indexOf('export interface FlowDryRunResult {'); + const methodEnd = source.indexOf('dryRun?(definition: unknown, options: FlowDryRunOptions)'); + const docs = { + "the 'failed' status doc": source.slice(source.lastIndexOf('/**', statusEnd), statusEnd), + 'the startCondition doc': source.slice(resultStart, source.indexOf('startCondition?:', resultStart)), + 'the dryRun doc block': source.slice(source.lastIndexOf('/**', methodEnd), methodEnd), + }; + for (const [where, doc] of Object.entries(docs)) { + expect(doc, where).toContain('On the default error strategy'); + expect(doc, where).toContain("`errorHandling.strategy: 'retry'`"); + expect(doc, where).toContain('#33935'); + } + expect(docs["the 'failed' status doc"]).toContain("Under\n * `errorHandling.strategy: 'retry'` it is the dry run's own answer, not a\n * prediction"); + expect(source).not.toContain('This one follows the live run, whose'); + }); + it('answers in the live run\'s order: admission, then the start condition (unmet, then faulted), then the input-schema check', () => { const source = readFileSync(fileURLToPath(new URL('./automation-service.ts', import.meta.url)), 'utf8'); const end = source.indexOf('dryRun?(definition: unknown, options: FlowDryRunOptions)'); diff --git a/packages/spec/src/contracts/automation-service.ts b/packages/spec/src/contracts/automation-service.ts index 223d130181b..da99c730352 100644 --- a/packages/spec/src/contracts/automation-service.ts +++ b/packages/spec/src/contracts/automation-service.ts @@ -1480,18 +1480,23 @@ export interface FlowDryRunOptions extends Pick