diff --git a/.changeset/33661-automation-dry-run.md b/.changeset/33661-automation-dry-run.md new file mode 100644 index 00000000000..0878b0dfe21 --- /dev/null +++ b/.changeset/33661-automation-dry-run.md @@ -0,0 +1,23 @@ +--- +'@objectstack/spec': patch +'@objectstack/core': patch +'@objectstack/runtime': patch +'@objectstack/plugin-security': patch +'@objectstack/service-automation': patch +--- + +feat(automation): `IAutomationService.dryRun` runs an unpublished flow definition once, unarmed, as a named user + +Clause-②: yes (widening) — `AutomationEngine.dryRun` admits a `runAs: 'system'` self-triggered draft for the named user (ruling B); `@objectstack/core` exports the shared flow-start rules (`aiAccountElevatedStartRefusal`, `requiredPermissionsStartRefusal`, `requiredPermissionsRefusal`, `missingCapabilities`, `isAiServiceAccount`, `AI_ACCOUNT_ELEVATED_START_REFUSAL`, `FlowStartPermissionRefusal`); plugin-security's registered `security` service serves `canWriteObject` +Metadata-protocol: none + +The automation service now implements `dryRun(definition, { userId, record, … })`, the method the `IAutomationService` contract declares. A dry run admits the definition by the checks `registerFlow` asks, then by the rules that admit a start by name, and then runs it once against the supplied record as the named user. It registers nothing and arms no trigger, and it writes, sends and pauses nothing: + +- Record writes (`create_record`, `update_record`, `delete_record`) are simulated. The step shows the values the run would write and a placeholder id for a new record. The named user's object-level write permission is judged as allowed, refused or not judged. A later read by id in the same run sees the simulated row. +- Routing and computing nodes (`assignment`, `decision`, gateways, loops, parallel branches, try/catch) run on the engine's own executors. A decision step shows the branch taken and the expressions it evaluated. +- Outbound nodes (`http`, email and the like) are never executed. The step shows the payload they would send. +- The run stops at a node that pauses (`approval`, `wait`, `screen`, a subflow) and names why. A node type the dry run cannot simulate stops it as `not_simulated`. + +Under maintainer ruling B (record 6917953931), a draft declaring `runAs: 'system'` whose type starts on its own trigger is admitted to a dry run for the named user, and the run is never elevated. The contract's admission text says so. A by-name start of a published flow keeps refusing such a flow. + +The AI service account rule and the flow's own `requiredPermissions` rule now live in `@objectstack/core`. The by-name start doors and the dry run both ask that one copy. `@objectstack/runtime` re-exports every symbol under the name it had. The registered `security` service now also exposes `canWriteObject`, so a dry run can judge a write without performing it. diff --git a/packages/core/src/security/flow-start-rules.ts b/packages/core/src/security/flow-start-rules.ts new file mode 100644 index 00000000000..70858439530 --- /dev/null +++ b/packages/core/src/security/flow-start-rules.ts @@ -0,0 +1,153 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The flow start rules two different askers share — ONE spelling, asked by + * both: + * + * - every door that starts a published flow by name + * (`flowStartRefusal`, `@objectstack/runtime`'s `flow-start-admission.ts`, + * whose header is the authority on the rules and their order there); + * - a dry run of an unpublished definition + * (`IAutomationService.dryRun`, `@objectstack/service-automation`), which + * the contract admits by "the rules that admit a start by name". + * + * They live here, below both, because `@objectstack/service-automation` does + * not depend on `@objectstack/runtime`, and a rule each asker spelled for + * itself is a rule that drifts: the account reading, the capability + * arithmetic, the refusals' code and status, and their words are written here + * once. `flow-start-admission.ts` re-exports every one of them under the name + * it always had. + * + * Two rules are here, and only two: + * + * - **The AI service account rule** ({@link aiAccountElevatedStartRefusal}; + * ADR-0151 D3 and Non-goals, ruling record 6812617393, letter C): an AI + * service account starts a flow declared `runAs: 'system'` only through + * an action its author opted into AI. + * - **The flow's own `requiredPermissions`** + * ({@link requiredPermissionsStartRefusal}; ruling record 6377848497, + * letter A): a caller must hold every capability the flow names. + * + * The elevated self-triggered rule stays in `flow-start-admission.ts`: only + * the by-name doors ask it. A dry run admits such a draft for the named user, + * never elevated (ruling record 6917953931, letter B), so it is not shared. + * + * The system principal is NOT decided here: each asker reads + * `isSystem` itself, before it asks (a dry run never runs as it). + */ + +/** The ADR-0112 `403` a start the rules here do not admit answers. */ +export interface FlowStartPermissionRefusal { + code: 'PERMISSION_DENIED'; + status: 403; + message: string; +} + +/** + * [ADR-0066 D4] The capabilities in `required` the caller does not hold, in + * declaration order — the arithmetic behind every declared + * `requiredPermissions` gate that admits a caller to an execution surface, + * asked by the action gate (`actionPermissionError`, `action-execution.ts`), + * the flow start gate and a dry run's admission. A declaration is a list of + * capability names; the caller holds the capabilities its permission sets + * grant (`ExecutionContext.systemPermissions`). Empty when nothing is declared + * (an ungated surface) or when the caller holds all of them. A value that is + * not an array declares nothing. + */ +export function missingCapabilities( + required: unknown, + executionContext: { systemPermissions?: readonly string[] } | null | undefined, +): string[] { + if (!Array.isArray(required) || required.length === 0) return []; + const held = new Set(executionContext?.systemPermissions ?? []); + return (required as string[]).filter((perm) => !held.has(perm)); +} + +/** + * The refusal answered when the caller lacks a capability the flow's + * `requiredPermissions` names — the same code and status as the action + * gate's 403 (ADR-0112). ⛔ No new code is minted here. + * + * The message names the declared and the missing capabilities, as the action + * gate's does — the remedy is a grant, and a caller cannot ask for one it + * cannot name — and nothing else about the flow: not its name, its type or its + * run-as declaration. + */ +export function requiredPermissionsRefusal(required: readonly string[], missing: readonly string[]): FlowStartPermissionRefusal { + return { + code: 'PERMISSION_DENIED', + status: 403, + message: + `Starting this flow requires capability [${required.join(', ')}] — ` + + `caller is missing [${missing.join(', ')}]`, + }; +} + +/** + * The refusal answered when an AI service account starts a flow declared + * `runAs: 'system'` and what starts the flow carries no AI opt-in — the same + * code and status as the refusal beside it (ADR-0112). ⛔ No new code is + * minted here. + * + * The message names the rule and the opt-in the author adds, and nothing else + * about THIS flow: not its name, its type or its definition, and not the + * door, so it reads the same wherever it is answered. It names the action + * route and the MCP tool because those are the doors where the opt-in can + * stand. + */ +export const AI_ACCOUNT_ELEVATED_START_REFUSAL = Object.freeze({ + code: 'PERMISSION_DENIED', + status: 403, + message: + 'An AI service account starts a flow that runs as the system only through an action its author opted ' + + "into AI. Declare `ai: { exposed: true, description: … }` on an action of type 'flow' that targets the " + + 'flow, and have the account run that action (the REST actions route or the MCP `run_action` tool).', +} as const); + +/** + * Whether `executionContext` is an AI service account's (ADR-0151 D3): the + * agent principal that is its own subject, `principalKind: 'agent'` with no + * `onBehalfOf`. An OAuth-delegated agent names the person it acts for and is + * not one; neither is a person, the guest or the system principal. + * + * ONE reading, asked by the AI service account rule and by the builders that + * forward the account's kind onto the run it starts, so the caller judged as + * an account is the caller whose run carries the kind. + */ +export function isAiServiceAccount( + executionContext: { principalKind?: unknown; onBehalfOf?: unknown } | null | undefined, +): boolean { + return executionContext?.principalKind === 'agent' && !executionContext?.onBehalfOf; +} + +/** + * The AI service account rule: {@link AI_ACCOUNT_ELEVATED_START_REFUSAL} when + * `executionContext` is an AI service account, the flow declares + * `runAs: 'system'`, and what starts it carries no `ai.exposed: true` opt-in + * (`aiExposed`); else `null`. A dry run starts with no action in hand, so it + * asks with `aiExposed: false`. + */ +export function aiAccountElevatedStartRefusal( + flow: { runAs?: unknown }, + executionContext: { principalKind?: unknown; onBehalfOf?: unknown } | null | undefined, + aiExposed: boolean, +): FlowStartPermissionRefusal | null { + if (flow.runAs === 'system' && isAiServiceAccount(executionContext) && aiExposed !== true) { + return AI_ACCOUNT_ELEVATED_START_REFUSAL; + } + return null; +} + +/** + * The flow's own `requiredPermissions` rule: {@link requiredPermissionsRefusal} + * naming what the caller is missing, or `null` when it holds every capability + * the flow names (or the flow names none). + */ +export function requiredPermissionsStartRefusal( + flow: { requiredPermissions?: unknown }, + executionContext: { systemPermissions?: readonly string[] } | null | undefined, +): FlowStartPermissionRefusal | null { + const missing = missingCapabilities(flow.requiredPermissions, executionContext); + if (missing.length === 0) return null; + return requiredPermissionsRefusal(flow.requiredPermissions as string[], missing); +} diff --git a/packages/core/src/security/index.ts b/packages/core/src/security/index.ts index 279595f84c9..e3c78d3e81f 100644 --- a/packages/core/src/security/index.ts +++ b/packages/core/src/security/index.ts @@ -717,3 +717,16 @@ export { type CallerMailSenderSource, type CallerMailBoundsResult, } from './caller-mail-bounds.js'; + +// The flow start rules a by-name start of a published flow +// (`flowStartRefusal`, runtime) and a dry run of an unpublished definition +// (`IAutomationService.dryRun`, service-automation) both ask — one spelling. +export { + missingCapabilities, + requiredPermissionsRefusal, + AI_ACCOUNT_ELEVATED_START_REFUSAL, + isAiServiceAccount, + aiAccountElevatedStartRefusal, + requiredPermissionsStartRefusal, + type FlowStartPermissionRefusal, +} from './flow-start-rules.js'; diff --git a/packages/plugins/plugin-security/src/registered-security-service-members.pin.test.ts b/packages/plugins/plugin-security/src/registered-security-service-members.pin.test.ts index 79da8dca56e..9893995172b 100644 --- a/packages/plugins/plugin-security/src/registered-security-service-members.pin.test.ts +++ b/packages/plugins/plugin-security/src/registered-security-service-members.pin.test.ts @@ -90,11 +90,21 @@ const DECLARED_MEMBERS = { /** * Members the registered service serves that are deliberately NOT part of the * contract — plugin-internal, no caller outside this package — each with the - * reason. Empty: every served member is declared. An entry here is a decision - * that a member stays off the contract; a member another package calls is a - * contract, and belongs on `ISecurityService` instead. + * reason. An entry here is a decision that a member stays off the contract; a + * member another package calls is a contract, and belongs on + * `ISecurityService` instead — except where a published contract places it + * off `ISecurityService`, and the entry cites that contract. One such entry: + * `canWriteObject`, which the `IAutomationService.dryRun` contract's + * `FlowDryRunWritePermission` text names a method of this plugin's service + * and not of `ISecurityService`. */ -const SERVED_NOT_DECLARED: Readonly> = {}; +const SERVED_NOT_DECLARED: Readonly> = { + canWriteObject: + 'the object-level write check a flow dry run asks (`@objectstack/service-automation`). The ' + + '`IAutomationService.dryRun` contract (`FlowDryRunWritePermission`, packages/spec/src/contracts/' + + 'automation-service.ts) names it a method of this plugin\'s service and NOT of ISecurityService, so a ' + + 'kernel without this plugin has none and every write step answers `not_judged`', +}; /** * OPTIONAL members this plugin must SERVE, each with the reason its absence is diff --git a/packages/plugins/plugin-security/src/security-plugin-security-service.ts b/packages/plugins/plugin-security/src/security-plugin-security-service.ts index 6a1efe8d394..b2b1c5e4726 100644 --- a/packages/plugins/plugin-security/src/security-plugin-security-service.ts +++ b/packages/plugins/plugin-security/src/security-plugin-security-service.ts @@ -108,6 +108,7 @@ export interface SecurityServiceHost { readonly tenancyPosture: SecurityPlugin['tenancyPosture']; canExport: SecurityPlugin['canExport']; canReadObject: SecurityPlugin['canReadObject']; + canWriteObject: SecurityPlugin['canWriteObject']; checkAuthoredRowWrite: SecurityPlugin['checkAuthoredRowWrite']; checkControlledByParentWrite: SecurityPlugin['checkControlledByParentWrite']; declareEveryone: SecurityPlugin['declareEveryone']; @@ -127,7 +128,7 @@ export interface SecurityServiceHost { /** The `security` service registration `SecurityPlugin#start` runs; the comment above its call there is its contract. */ export function registerSecurityService( - this: Pick, + this: Pick, ctx: PluginContext, ql: IObjectQLEngine, metadata: IMetadataService, @@ -407,6 +408,12 @@ export function registerSecurityService( const registeredSecurityService = Object.assign(securityService, { getMetadataReadableFields: (object: string, context?: any) => this.getMetadataReadableFields(object, context), + // [#33661] The object-level write check (insert or update) a flow dry + // run asks for each simulated write (`IAutomationService.dryRun`, + // "canWriteObject is a method of plugin-security's service"). The same + // method the engine's write-gate probe calls; ⛔ not a second decision. + canWriteObject: (object: string, operation: 'insert' | 'update', context?: any, data?: unknown) => + this.canWriteObject(object, operation, context, data), // [#21729] The ownership-floor alternate seam — how a plugin that // installs a tighter row gate stops the platform's `created_by` floor // pre-empting it, registered beside that gate and nowhere else. Same diff --git a/packages/plugins/plugin-security/src/security-plugin.ts b/packages/plugins/plugin-security/src/security-plugin.ts index 2b279efd9d4..936fc6b83f3 100644 --- a/packages/plugins/plugin-security/src/security-plugin.ts +++ b/packages/plugins/plugin-security/src/security-plugin.ts @@ -2328,12 +2328,13 @@ export class SecurityPlugin implements Plugin { const readQl = () => this.ql; const readTenancyPosture = () => this.tenancyPosture; const readEpoch = () => this.epoch; - const host: Pick = { + const host: Pick = { acceptedDefaultPermissionSets: this.acceptedDefaultPermissionSets, baselinePermissionSets: this.baselinePermissionSets, bootstrapPermissionSets: this.bootstrapPermissionSets, canExport: (...a) => this.canExport(...a), canReadObject: (...a) => this.canReadObject(...a), + canWriteObject: (...a) => this.canWriteObject(...a), checkAuthoredRowWrite: (...a) => this.checkAuthoredRowWrite(...a), checkControlledByParentWrite: (...a) => this.checkControlledByParentWrite(...a), declareEveryone: (...a) => this.declareEveryone(...a), diff --git a/packages/runtime/src/flow-start-admission.ts b/packages/runtime/src/flow-start-admission.ts index 6e062859d09..1df9eb84a0e 100644 --- a/packages/runtime/src/flow-start-admission.ts +++ b/packages/runtime/src/flow-start-admission.ts @@ -115,9 +115,15 @@ * The same reason `flow-dispatch-status.ts` is one: a rule each door spells * for itself is a rule that drifts, and a door left out is the defect, not a * gap. The type set, the account rule, the capability check, the refusals' - * code and status, and their words live here once, so a caller refused at one + * code and status, and their words live once, so a caller refused at one * door is refused alike at the other two — * an MCP agent and a person are judged at the same door by the same rule. + * Rules 2 and 3 (their refusals, the account reading and the capability + * arithmetic) are written in `@objectstack/core`'s `flow-start-rules.ts` and + * re-exported here, because a dry run of an unpublished definition + * (`IAutomationService.dryRun`) asks them too, from a package that does not + * depend on this one; rule 1 and rule 2b are asked by the by-name doors alone + * and stay here. * ⛔ A second copy of the type set or the refusal, at any door, is the defect * by construction. * @@ -147,7 +153,23 @@ import { isObjectLessActionKey } from '@objectstack/objectql'; // and status rule 2b answers are the action door's own literals, checked at // compile time, with no value edge back into `action-execution.ts`. import type { ActionConfirmationRefusal } from './action-execution.js'; -import { missingCapabilities } from './required-capabilities.js'; +// Rules 2 and 3, their refusals and the account reading are spelled ONCE, in +// `@objectstack/core` (`flow-start-rules.ts`): a dry run of an unpublished +// definition (`IAutomationService.dryRun`, `@objectstack/service-automation`, +// which does not depend on this package) asks the same two rules. Re-exported +// here under the names every door imports. +import { + aiAccountElevatedStartRefusal, + isAiServiceAccount, + requiredPermissionsStartRefusal, + type FlowStartPermissionRefusal, +} from '@objectstack/core'; +export { + AI_ACCOUNT_ELEVATED_START_REFUSAL, + isAiServiceAccount, + requiredPermissionsRefusal, + type FlowStartPermissionRefusal, +} from '@objectstack/core'; /** * The three flow types that start on their OWN trigger — or as a sub-flow @@ -183,55 +205,6 @@ export const ELEVATED_START_REFUSAL = Object.freeze({ + "or as a sub-flow from a parent flow's `subflow` node.", } as const); -/** - * The refusal a door answers when the caller lacks a capability the flow's - * `requiredPermissions` names — the same code and status as - * {@link ELEVATED_START_REFUSAL} and as the action gate's 403 (ADR-0112). ⛔ No - * new code is minted here. - * - * The message names the declared and the missing capabilities, as the action - * gate's does — the remedy is a grant, and a caller cannot ask for one it - * cannot name — and nothing else about the flow: not its name, its type or its - * run-as declaration. - */ -export function requiredPermissionsRefusal(required: readonly string[], missing: readonly string[]): FlowStartPermissionRefusal { - return { - code: 'PERMISSION_DENIED', - status: 403, - message: - `Starting this flow requires capability [${required.join(', ')}] — ` - + `caller is missing [${missing.join(', ')}]`, - }; -} - -/** - * The refusal a door answers when an AI service account starts a flow declared - * `runAs: 'system'` and what starts the flow at that door carries no AI - * opt-in (rule 2; ADR-0151 Non-goals, ruling record 6812617393, letter C) — - * the same code and status as the two refusals beside it (ADR-0112). ⛔ No new - * code is minted here. - * - * The message names the rule and the opt-in the author adds, and nothing else - * about THIS flow: not its name, its type or its definition, and not the - * door, so it reads the same at every door. It names the action route and the - * MCP tool because those are the doors where the opt-in can stand. - */ -export const AI_ACCOUNT_ELEVATED_START_REFUSAL = Object.freeze({ - code: 'PERMISSION_DENIED', - status: 403, - message: - 'An AI service account starts a flow that runs as the system only through an action its author opted ' - + "into AI. Declare `ai: { exposed: true, description: … }` on an action of type 'flow' that targets the " - + 'flow, and have the account run that action (the REST actions route or the MCP `run_action` tool).', -} as const); - -/** The ADR-0112 `403` a door answers for a start rules 1, 2 and 3 do not admit. */ -export interface FlowStartPermissionRefusal { - code: 'PERMISSION_DENIED'; - status: 403; - message: string; -} - /** * The refusal rule 2b answers: the action door's own (`428 * ACTION_CONFIRMATION_REQUIRED`, ADR-0112), its code, status and `details` @@ -322,23 +295,6 @@ export function confirmationGatedStartRefusal(declaration: FlowStartActionDeclar }; } -/** - * Whether `executionContext` is an AI service account's (ADR-0151 D3): the - * agent principal that is its own subject, `principalKind: 'agent'` with no - * `onBehalfOf`. An OAuth-delegated agent names the person it acts for and is - * not one; neither is a person, the guest or the system principal. - * - * ONE reading, asked by rule 2 ({@link flowStartRefusal}) and by the two - * builders that forward the account's kind onto the run it starts - * (`buildAutomationContext`, `dispatchFlowAction`), so the caller a door - * judges as an account is the caller whose run carries the kind. - */ -export function isAiServiceAccount( - executionContext: { principalKind?: unknown; onBehalfOf?: unknown } | null | undefined, -): boolean { - return executionContext?.principalKind === 'agent' && !executionContext?.onBehalfOf; -} - /** * What a door that starts a flow by name states about ITSELF for rule 2. A * required argument of {@link flowStartRefusal}, so a door that never @@ -710,9 +666,8 @@ export async function flowStartRefusal( if (flow && isElevatedSelfTriggered(flow)) return ELEVATED_START_REFUSAL; // [ADR-0151 Non-goals; ruling record 6812617393, letter C] Rule 2: the // account starts an elevated flow only where the author's AI opt-in stands. - if (flow && flow.runAs === 'system' && isAiServiceAccount(executionContext) && door.aiExposed !== true) { - return AI_ACCOUNT_ELEVATED_START_REFUSAL; - } + const accountRefusal = flow ? aiAccountElevatedStartRefusal(flow, executionContext, door.aiExposed) : null; + if (accountRefusal) return accountRefusal; // [ADR-0151 D3 rule 3] Rule 2b: the confirmation an action declares // travels with what it starts. It reads the flow's NAME and the door's // declarations only, so it is asked whether or not the definition could @@ -731,7 +686,5 @@ export async function flowStartRefusal( if (gated) return confirmationGatedStartRefusal(gated); } if (!flow) return null; - const missing = missingCapabilities(flow.requiredPermissions, executionContext); - if (missing.length > 0) return requiredPermissionsRefusal(flow.requiredPermissions as string[], missing); - return null; + return requiredPermissionsStartRefusal(flow, executionContext); } diff --git a/packages/runtime/src/required-capabilities.ts b/packages/runtime/src/required-capabilities.ts index 7b67f39a4aa..75c44161cc6 100644 --- a/packages/runtime/src/required-capabilities.ts +++ b/packages/runtime/src/required-capabilities.ts @@ -20,16 +20,8 @@ * (`content/docs/permissions/system-context.mdx`) anchors it there. */ -/** - * The capabilities in `required` the caller does not hold, in declaration - * order. Empty when nothing is declared (an ungated surface) or when the - * caller holds all of them. A value that is not an array declares nothing. - */ -export function missingCapabilities( - required: unknown, - executionContext: { systemPermissions?: readonly string[] } | null | undefined, -): string[] { - if (!Array.isArray(required) || required.length === 0) return []; - const held = new Set(executionContext?.systemPermissions ?? []); - return (required as string[]).filter((perm) => !held.has(perm)); -} +// The arithmetic itself lives in `@objectstack/core` (`flow-start-rules.ts`), +// below this package, because a dry run in `@objectstack/service-automation` +// asks it too and that package does not depend on this one. Re-exported under +// the name every gate here imports. +export { missingCapabilities } from '@objectstack/core'; diff --git a/packages/services/service-automation/src/builtin/crud-nodes.ts b/packages/services/service-automation/src/builtin/crud-nodes.ts index e8198559c64..37f792ef190 100644 --- a/packages/services/service-automation/src/builtin/crud-nodes.ts +++ b/packages/services/service-automation/src/builtin/crud-nodes.ts @@ -36,6 +36,7 @@ import { resolveValueSlotMap } from './value-slot-map.js'; import { refuseNode } from '../guard-refusal.js'; import { parseNodeConfig } from './parse-config.js'; import { resolveRunDataContext, stampSystemInsertOwner } from '../runtime-identity.js'; +import { dryRunDataEngine } from '../dry-run.js'; import { refusalCarriedBy } from '../inner-refusal.js'; import { staleSummaryAnswerLines, staleSummaryRefusalOrThrow } from '@objectstack/types'; @@ -547,11 +548,17 @@ function storedMetadataWriteRefusal( */ export function registerCrudNodes(engine: AutomationEngine, ctx: PluginContext): void { const getData = (): IDataEngine | undefined => { + let real: IDataEngine | undefined; try { - return ctx.getService('data') ?? ctx.getService('objectql'); + real = ctx.getService('data') ?? ctx.getService('objectql'); } catch { - return undefined; + real = undefined; } + // [#33661] Inside a dry run (`AutomationEngine.dryRun`) the node + // reaches the dry run's stand-in: live reads, simulated writes. + // Outside one this is `undefined` and the node reaches `real`. + const dry = dryRunDataEngine(real, () => ctx.getService('security')) as IDataEngine | undefined; + return dry ?? real; }; // ── get_record ──────────────────────────────────────── diff --git a/packages/services/service-automation/src/builtin/save-notice-node.ts b/packages/services/service-automation/src/builtin/save-notice-node.ts index 6d742c8040b..7fab5387ebb 100644 --- a/packages/services/service-automation/src/builtin/save-notice-node.ts +++ b/packages/services/service-automation/src/builtin/save-notice-node.ts @@ -32,7 +32,38 @@ import { flowNoticeMessageKey } from '@objectstack/spec/system'; import type { AutomationEngine } from '../engine.js'; import { refuseNode } from '../guard-refusal.js'; import { parseNodeConfig } from './parse-config.js'; -import { renderTextSlot } from './template.js'; +import type { AutomationContext } from '@objectstack/spec/contracts'; +import { renderTextSlot, type VariableMap } from './template.js'; + +/** + * The save notice's message as a run renders it: translated at + * `flowNoticeMessageKey(flowName, nodeId)` in `context.locale`, its holes + * filled through the engine's one text renderer, and the authored template + * when the run names no flow. ONE spelling, asked by this executor and by a + * dry run's outbound payload (`dry-run.ts`), so the sentence a dry run reports + * is the sentence the saver would read in the same locale. + */ +export function renderSaveNoticeMessage( + engine: Pick, + flowName: string | undefined, + nodeId: string, + authored: unknown, + variables: VariableMap, + context: AutomationContext, +): string | undefined { + return flowName === undefined + ? renderTextSlot(authored, variables, context.currency) + : engine.renderFlowTextSlot( + { + key: flowNoticeMessageKey(flowName, nodeId), + authored, + subject: `flow '${flowName}' save_notice '${nodeId}'`, + shownAs: 'the save notice', + }, + variables, + context, + ); +} export function registerSaveNoticeNode(engine: AutomationEngine, _ctx: PluginContext): void { engine.registerNodeExecutor({ @@ -77,18 +108,7 @@ export function registerSaveNoticeNode(engine: AutomationEngine, _ctx: PluginCon // The writer's locale, not the run's: a record-change run carries // none of its own, and the reader of this sentence is the writer. const renderContext = channel.locale ? { ...context, locale: channel.locale } : context; - const message = flowName === undefined - ? renderTextSlot(parsed.config.message, variables, context.currency) - : engine.renderFlowTextSlot( - { - key: flowNoticeMessageKey(flowName, node.id), - authored: parsed.config.message, - subject: `flow '${flowName}' save_notice '${node.id}'`, - shownAs: 'the save notice', - }, - variables, - renderContext, - ); + const message = renderSaveNoticeMessage(engine, flowName, node.id, parsed.config.message, variables, renderContext); if (typeof message !== 'string' || message.trim() === '') { return { success: false, diff --git a/packages/services/service-automation/src/dry-run.test.ts b/packages/services/service-automation/src/dry-run.test.ts new file mode 100644 index 00000000000..2b519f5addd --- /dev/null +++ b/packages/services/service-automation/src/dry-run.test.ts @@ -0,0 +1,596 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * `AutomationEngine.dryRun` (#33661) against `IAutomationService.dryRun`'s + * docblock: each node class the in-app v2-narrow tier offers (create_record, + * update_record, assignment, decision, approval), the admission refusals, and + * the "unarmed, unregistered, nothing written, nothing sent" promises. + * + * The data engine below records every call it receives, so "writes nothing" + * is read off the calls it never got, not off the result. + */ +import { describe, it, expect } from 'vitest'; +import { AI_ACCOUNT_ELEVATED_START_REFUSAL, createMemoryI18n, requiredPermissionsRefusal } from '@objectstack/core'; +import { + assertEngineDeleteDispatch, assertEngineFindOnePredicate, assertEngineUpdateDispatch, + ENGINE_DELETE_REJECT_MESSAGE, ENGINE_UPDATE_REJECT_MESSAGE, +} from '@objectstack/metadata-core'; +import { defineActionDescriptor } from '@objectstack/spec/automation'; +import { flowNoticeMessageKey, flowRefusalMessageKey } from '@objectstack/spec/system'; +import type { FlowDryRunResult } from '@objectstack/spec/contracts'; +import { AutomationEngine, type FlowUserGrants } from './engine.js'; +import { registerCrudNodes } from './builtin/crud-nodes.js'; +import { registerLogicNodes } from './builtin/logic-nodes.js'; +import { registerLoopNode } from './builtin/loop-node.js'; +import { registerSaveNoticeNode } from './builtin/save-notice-node.js'; +import { i18nServiceReader } from './plugin.js'; + +function makeLogger(): any { + const l: any = { info() {}, warn() {}, error() {}, debug() {} }; + l.child = () => l; + return l; +} + +/** A live data engine holding `deal` rows, recording every call. */ +function liveData(rows: Record> = { d1: { id: 'd1', stage: 'open', amount: 10 } }) { + const calls: Array<{ op: string; obj: string; q?: any }> = []; + // Equality on plain fields only: a combinator or an operator object is + // refused, never read as a field name. + const match = (where: any) => Object.values(rows).filter((r) => !where || Object.entries(where).every(([k, v]) => { + if (k.startsWith('$') || (v !== null && typeof v === 'object')) throw new Error(`liveData: unsupported filter '${k}'`); + return r[k] === v; + })); + const data: any = { + async find(obj: string, q: any) { + calls.push({ op: 'find', obj, q }); + const hits = match(q?.where); + const page = typeof q?.limit === 'number' ? hits.slice(0, q.limit) : hits; + return page.map((r) => ({ ...r })); + }, + async findOne(obj: string, q: any) { + assertEngineFindOnePredicate(obj, q); + calls.push({ op: 'findOne', obj, q }); + const r = match(q?.where)[0]; + return r ? { ...r } : null; + }, + async insert(obj: string) { calls.push({ op: 'insert', obj }); throw new Error('a dry run must not insert'); }, + async update(obj: string, payload: any, options?: any) { + assertEngineUpdateDispatch(payload, options); + calls.push({ op: 'update', obj }); + throw new Error('a dry run must not update'); + }, + async delete(obj: string, options?: any) { + assertEngineDeleteDispatch(options); + calls.push({ op: 'delete', obj }); + throw new Error('a dry run must not delete'); + }, + }; + return { data, calls }; +} + +interface Harness { + engine: AutomationEngine; + calls: Array<{ op: string; obj: string; q?: any }>; + approvalCalls: number; + writeChecks: Array<{ object: string; operation: string; context: any }>; +} + +function harness(opts: { + grants?: Partial; + canWrite?: (object: string, operation: string) => boolean; + /** Translation bundles by locale, served through the engine's one i18n source. */ + bundles?: Record>; + /** The grants read fails (the resolver throws). */ + grantsFail?: boolean; + /** The grants resolver answers nothing (`null`). */ + grantsNone?: boolean; + /** No grants resolver is wired at all. */ + noGrantsResolver?: boolean; + /** The live `deal` rows, when not the one default row. */ + rows?: Record>; +} = {}): Harness { + const { data, calls } = liveData(opts.rows); + const writeChecks: Harness['writeChecks'] = []; + const security = opts.canWrite + ? { + async canWriteObject(object: string, operation: string, context: any) { + writeChecks.push({ object, operation, context }); + return opts.canWrite!(object, operation); + }, + } + : undefined; + const ctx: any = { + logger: makeLogger(), + getService: (n: string) => (n === 'data' ? data : n === 'security' ? security : undefined), + }; + const engine = new AutomationEngine(makeLogger()); + registerLogicNodes(engine, ctx); + registerCrudNodes(engine, ctx); + registerLoopNode(engine, ctx); + registerSaveNoticeNode(engine, ctx); + if (opts.bundles) { + const i18n = createMemoryI18n(); + for (const [locale, data] of Object.entries(opts.bundles)) i18n.loadTranslations(locale, data); + engine.setI18nServiceSource(i18nServiceReader({ + getService: ((name: string) => { + if (name === 'i18n') return i18n as T; + throw new Error(`service '${name}' not registered`); + }) as never, + })); + } + const h: Harness = { engine, calls, approvalCalls: 0, writeChecks }; + // An approval node as the approvals plugin declares it: it pauses, so a + // dry run must stop at it and never call it (that would create a request). + engine.registerNodeExecutor({ + type: 'approval', + descriptor: defineActionDescriptor({ + type: 'approval', version: '1.0.0', name: 'Approval', category: 'logic', source: 'plugin', + supportsPause: true, resumeAuthority: 'service', + } as any), + async execute() { h.approvalCalls++; return { success: true, suspend: true }; }, + }); + if (!opts.noGrantsResolver) engine.setUserGrantsResolver(async () => opts.grantsFail ? Promise.reject(new Error('grants store unreachable')) : opts.grantsNone ? null as never : ({ + positions: [], + permissions: [], + accessible_org_ids: ['org_1'], + systemPermissions: [], + ...opts.grants, + })); + return h; +} + +/** A bundle holding `text` at the dotted translation `key`. */ +function bundleAt(key: string, text: string): Record { + const parts = key.split('.'); + const root: Record = {}; + let at = root; + for (const part of parts.slice(0, -1)) at = (at[part] = {}) as Record; + at[parts[parts.length - 1]] = text; + return root; +} + +const writes = (h: Harness) => h.calls.filter((c) => c.op === 'insert' || c.op === 'update' || c.op === 'delete'); + +function flow(nodes: any[], edges: any[], extra: Record = {}) { + return { name: 'draft_flow', label: 'Draft flow', type: 'autolaunched', nodes, edges, ...extra }; +} +const chain = (...ids: string[]) => ids.slice(1).map((id, i) => ({ id: `e${i}`, source: ids[i], target: id })); + +describe('dryRun — create_record and update_record (writes simulated, never made)', () => { + it('a create reports the values it computed and a placeholder id, writes nothing, and a later read by id sees only the fields the flow set', async () => { + const h = harness(); + const result = await h.engine.dryRun(flow([ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'mk', type: 'create_record', label: 'Create', config: { objectName: 'deal', fields: { amount: { dialect: 'cel', source: 'record.amount * 2' }, stage: 'new' }, outputVariable: 'created' } }, + { id: 'rd', type: 'get_record', label: 'Read', config: { objectName: 'deal', filter: { id: { dialect: 'cel', source: 'created.id' } }, outputVariable: 'back' } }, + { id: 'end', type: 'end', label: 'End' }, + ], chain('start', 'mk', 'rd', 'end')), { userId: 'usr_maker', record: { id: 'd1', amount: 21 } }); + + expect(result.status).toBe('completed'); + expect(writes(h)).toEqual([]); + const create = result.steps.find((s) => s.nodeId === 'mk'); + expect(create).toMatchObject({ kind: 'write', operation: 'create', object: 'deal', values: { amount: 42, stage: 'new' }, permission: 'not_judged' }); + const placeholder = (create as any).recordIds[0]; + expect(typeof placeholder).toBe('string'); + expect(placeholder).not.toBe('d1'); + // The read by id answers the simulated row, never the live engine. + expect(result.steps.find((s) => s.nodeId === 'rd')).toMatchObject({ kind: 'read', object: 'deal', recordIds: [placeholder] }); + expect(h.calls.filter((c) => c.op === 'findOne' && c.q?.where?.id === placeholder)).toEqual([]); + expect(result.steps.map((s) => s.kind)).toEqual(['route', 'write', 'read', 'route']); + }); + + it('an update targets the live row in the named user\'s scope, writes nothing, and a later read by id sees the simulated fields laid over it', async () => { + const h = harness({ canWrite: () => true }); + const result = await h.engine.dryRun(flow([ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'up', type: 'update_record', label: 'Update', config: { objectName: 'deal', filter: { id: 'd1' }, fields: { stage: 'won' } } }, + { id: 'rd', type: 'get_record', label: 'Read', config: { objectName: 'deal', filter: { id: 'd1' }, outputVariable: 'back' } }, + { id: 'as', type: 'assignment', label: 'Keep', config: { assignments: { seen: { dialect: 'cel', source: 'back.stage + "/" + string(back.amount)' } } } }, + { id: 'end', type: 'end', label: 'End' }, + ], chain('start', 'up', 'rd', 'as', 'end')), { userId: 'usr_maker' }); + + expect(result.status).toBe('completed'); + expect(writes(h)).toEqual([]); + expect(result.steps.find((s) => s.nodeId === 'up')).toMatchObject({ + kind: 'write', operation: 'update', object: 'deal', recordIds: ['d1'], values: { stage: 'won' }, permission: 'allowed', + }); + expect(h.writeChecks.map((c) => [c.object, c.operation, c.context?.userId, c.context?.isSystem === true])).toEqual([['deal', 'update', 'usr_maker', false]]); + expect(result.steps.find((s) => s.nodeId === 'as')).toMatchObject({ kind: 'assignment', values: { seen: 'won/10' } }); + }); + + it('a write the object-level check refuses carries PERMISSION_DENIED and ends the run failed, nothing written', async () => { + const h = harness({ canWrite: () => false }); + const result = await h.engine.dryRun(flow([ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'up', type: 'update_record', label: 'Update', config: { objectName: 'deal', filter: { id: 'd1' }, fields: { stage: 'won' } } }, + { id: 'after', type: 'assignment', label: 'After', config: { assignments: { x: 1 } } }, + { id: 'end', type: 'end', label: 'End' }, + ], chain('start', 'up', 'after', 'end')), { userId: 'usr_maker' }); + + expect(result.status).toBe('failed'); + expect(writes(h)).toEqual([]); + const last = result.steps[result.steps.length - 1]; + expect(last).toMatchObject({ nodeId: 'up', kind: 'write', permission: 'refused' }); + expect(last.refusal?.code).toBe('PERMISSION_DENIED'); + expect(result.error).toContain("Node 'up' failed"); + }); +}); + +describe('dryRun — assignment and decision (run as the live run runs them)', () => { + it('an assignment reports the variables it set with the values it computed', async () => { + const h = harness(); + const result = await h.engine.dryRun(flow([ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'as', type: 'assignment', label: 'Set', config: { assignments: { total: { dialect: 'cel', source: 'record.amount + 5' }, note: 'fixed' } } }, + { id: 'end', type: 'end', label: 'End' }, + ], chain('start', 'as', 'end')), { userId: 'usr_maker', record: { id: 'd1', amount: 10 } }); + expect(result.status).toBe('completed'); + expect(result.steps.find((s) => s.nodeId === 'as')).toEqual({ nodeId: 'as', nodeType: 'assignment', kind: 'assignment', values: { total: 15, note: 'fixed' } }); + }); + + it('a decision reports its branch, the expression that held and where the run went', async () => { + const h = harness(); + const result = await h.engine.dryRun(flow([ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'dec', type: 'decision', label: 'Big?', config: { conditions: [ + { label: 'big', expression: 'record.amount > 100' }, + { label: 'small', expression: 'record.amount <= 100' }, + ] } }, + { id: 'bigEnd', type: 'end', label: 'Big' }, + { id: 'smallEnd', type: 'end', label: 'Small' }, + ], [ + { id: 'e0', source: 'start', target: 'dec' }, + { id: 'e1', source: 'dec', target: 'bigEnd', label: 'big' }, + { id: 'e2', source: 'dec', target: 'smallEnd', label: 'small' }, + ]), { userId: 'usr_maker', record: { id: 'd1', amount: 10 } }); + expect(result.status).toBe('completed'); + expect(result.steps.find((s) => s.nodeId === 'dec')).toEqual({ + nodeId: 'dec', nodeType: 'decision', kind: 'decision', branch: 'small', expressions: ['record.amount <= 100'], next: ['smallEnd'], + }); + expect(result.steps.map((s) => s.nodeId)).toEqual(['start', 'dec', 'smallEnd']); + }); + + it('a gateway decision reports the conditioned out-edge it took, and no branch', async () => { + const h = harness(); + const result = await h.engine.dryRun(flow([ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'dec', type: 'decision', label: 'Gate' }, + { id: 'a', type: 'end', label: 'A' }, + { id: 'b', type: 'end', label: 'B' }, + ], [ + { id: 'e0', source: 'start', target: 'dec' }, + { id: 'e1', source: 'dec', target: 'a', condition: 'record.amount > 100' }, + { id: 'e2', source: 'dec', target: 'b', isDefault: true }, + ]), { userId: 'usr_maker', record: { id: 'd1', amount: 500 } }); + expect(result.steps.find((s) => s.nodeId === 'dec')).toEqual({ + nodeId: 'dec', nodeType: 'decision', kind: 'decision', expressions: ['record.amount > 100'], next: ['a'], + }); + }); +}); + +describe('dryRun — approval nodes and waits (the run stops)', () => { + it('stops at an approval node, reports it last, and never calls it', async () => { + const h = harness(); + const result = await h.engine.dryRun(flow([ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'as', type: 'assignment', label: 'Set', config: { assignments: { x: 1 } } }, + { id: 'ok', type: 'approval', label: 'Sign-off', config: { approvers: [{ type: 'user', value: 'u1' }] } }, + { id: 'mk', type: 'create_record', label: 'Create', config: { objectName: 'deal', fields: { stage: 'approved' } } }, + { id: 'end', type: 'end', label: 'End' }, + ], chain('start', 'as', 'ok', 'mk', 'end')), { userId: 'usr_maker' }); + expect(result.status).toBe('stopped'); + expect(h.approvalCalls).toBe(0); + expect(result.steps.map((s) => s.nodeId)).toEqual(['start', 'as', 'ok']); + expect(result.steps[2]).toEqual({ nodeId: 'ok', nodeType: 'approval', kind: 'stop', reason: 'approval' }); + expect(writes(h)).toEqual([]); + }); + + it('a node type outside every named class stops the run as not simulated', async () => { + const h = harness(); + h.engine.registerNodeExecutor({ type: 'custom_thing', async execute() { throw new Error('must not run'); } }); + const result = await h.engine.dryRun(flow([ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'c', type: 'custom_thing', label: 'Custom' }, + { id: 'end', type: 'end', label: 'End' }, + ], chain('start', 'c', 'end')), { userId: 'usr_maker' }); + expect(result.status).toBe('stopped'); + expect(result.steps[result.steps.length - 1]).toEqual({ nodeId: 'c', nodeType: 'custom_thing', kind: 'stop', reason: 'not_simulated' }); + }); +}); + +describe('dryRun — admission (the by-name start rules, ruling B for runAs system)', () => { + const gated = (extra: Record) => flow([ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'end', type: 'end', label: 'End' }, + ], chain('start', 'end'), extra); + + it('refuses a named user missing a capability requiredPermissions names, with the by-name message, and runs nothing', async () => { + const h = harness({ grants: { systemPermissions: ['other_cap'] } }); + const result = await h.engine.dryRun(gated({ type: 'screen', requiredPermissions: ['close_deals'] }), { userId: 'usr_maker' }); + const expected = requiredPermissionsRefusal(['close_deals'], ['close_deals']); + expect(result).toEqual({ status: 'refused', steps: [], refusal: { code: expected.code, message: expected.message } }); + }); + + it('refuses an AI service account a runAs system definition with the account rule\'s message', async () => { + const h = harness({ grants: { principalKind: 'agent' } }); + const result = await h.engine.dryRun(gated({ type: 'screen', runAs: 'system' }), { userId: 'usr_agent' }); + expect(result.status).toBe('refused'); + expect(result.refusal).toEqual({ code: AI_ACCOUNT_ELEVATED_START_REFUSAL.code, message: AI_ACCOUNT_ELEVATED_START_REFUSAL.message }); + }); + + it('refuses an organization the named user is not a member of', async () => { + const h = harness(); + const result = await h.engine.dryRun(gated({}), { userId: 'usr_maker', tenantId: 'org_other' }); + expect(result.status).toBe('refused'); + expect(result.refusal?.code).toBe('PERMISSION_DENIED'); + expect(result.steps).toEqual([]); + }); + + it.each([ + ['the read fails (the resolver throws)', { grantsFail: true }], + ['the resolver answers nothing', { grantsNone: true }], + ['no resolver is wired', { noGrantsResolver: true }], + ] as const)('refuses a runAs system definition when the named user\'s grants cannot be read: %s (the account rule fails closed)', async (_arm, unread) => { + const h = harness(unread); + const result = await h.engine.dryRun(gated({ type: 'schedule', runAs: 'system' }), { userId: 'usr_maker' }); + expect(result.status).toBe('refused'); + expect(result.steps).toEqual([]); + expect(result.refusal?.code).toBe('PERMISSION_DENIED'); + }); + + it('admits a runAs system schedule draft for the named user and never elevates it (ruling B)', async () => { + const h = harness({ canWrite: () => true }); + const result = await h.engine.dryRun(flow([ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'up', type: 'update_record', label: 'Update', config: { objectName: 'deal', filter: { id: 'd1' }, fields: { stage: 'stale' } } }, + { id: 'end', type: 'end', label: 'End' }, + ], chain('start', 'up', 'end'), { type: 'schedule', runAs: 'system' }), { userId: 'usr_maker', tenantId: 'org_1' }); + expect(result.status).toBe('completed'); + const contexts = [...h.calls.map((c) => c.q?.context), ...h.writeChecks.map((c) => c.context)].filter(Boolean); + expect(contexts.length).toBeGreaterThan(0); + for (const c of contexts) { + expect(c.isSystem === true).toBe(false); + expect(c.userId).toBe('usr_maker'); + } + }); +}); + +describe('dryRun — unarmed, unregistered, and its own answers', () => { + it('never registers the definition', async () => { + const h = harness(); + await h.engine.dryRun(flow([ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'end', type: 'end', label: 'End' }, + ], chain('start', 'end')), { userId: 'usr_maker' }); + expect(await h.engine.listFlows()).toEqual([]); + expect(await h.engine.getFlow('draft_flow')).toBeNull(); + }); + + it('throws a TypeError for a missing userId before reading the definition', async () => { + const h = harness(); + await expect(h.engine.dryRun(null, { userId: '' } as any)).rejects.toThrow(TypeError); + }); + + it('throws what registerFlow throws for a definition it refuses', async () => { + const h = harness(); + const bad = flow([{ id: 'end', type: 'end', label: 'End' }], []); + let registerError: unknown; + try { h.engine.registerFlow('draft_flow', bad); } catch (e) { registerError = e; } + expect(registerError).toBeInstanceOf(Error); + await expect(h.engine.dryRun(bad, { userId: 'usr_maker' })).rejects.toThrow((registerError as Error).message); + }); + + it('answers condition_not_met with the condition, and failed with the fault, before any node runs', async () => { + const h = harness(); + const gatedFlow = (condition: string) => flow([ + { id: 'start', type: 'start', label: 'Start', config: { condition } }, + { id: 'mk', type: 'create_record', label: 'Create', config: { objectName: 'deal', fields: { stage: 'x' } } }, + { id: 'end', type: 'end', label: 'End' }, + ], chain('start', 'mk', 'end')); + const notMet: FlowDryRunResult = await h.engine.dryRun(gatedFlow('record.stage == "won"'), { userId: 'usr_maker', record: { id: 'd1', stage: 'open' } }); + expect(notMet).toEqual({ status: 'condition_not_met', steps: [], startCondition: { expression: 'record.stage == "won"', result: false } }); + const faulted = await h.engine.dryRun(gatedFlow('record.missing.deeper == 1'), { userId: 'usr_maker', record: { id: 'd1' } }); + expect(faulted.status).toBe('failed'); + expect(faulted.steps).toEqual([]); + expect(faulted.startCondition?.expression).toBe('record.missing.deeper == 1'); + expect(faulted.startCondition?.fault).toBe(faulted.error); + }); + + it('a write inside a loop body is simulated too (the region runs the dry run\'s nodes)', async () => { + const h = harness(); + const result = await h.engine.dryRun(flow([ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'lp', type: 'loop', label: 'Each', config: { + collection: [1, 2], iteratorVariable: 'n', + body: { nodes: [{ id: 'mk', type: 'create_record', label: 'Create', config: { objectName: 'deal', fields: { n: { dialect: 'cel', source: 'n' } } } }], edges: [] }, + } }, + { id: 'end', type: 'end', label: 'End' }, + ], chain('start', 'lp', 'end')), { userId: 'usr_maker' }); + expect(result.status).toBe('completed'); + expect(writes(h)).toEqual([]); + expect(result.steps.map((s) => s.nodeId)).toEqual(['start', 'lp', 'mk', 'mk', 'end']); + expect(result.steps.filter((s) => s.kind === 'write').map((s: any) => s.values)).toEqual([{ n: 1 }, { n: 2 }]); + }); + + it('an outbound node reports its payload, sends nothing and binds no output', async () => { + const h = harness(); + let sent = 0; + h.engine.registerNodeExecutor({ type: 'http', async execute() { sent++; return { success: true, output: { status: 200 } }; } }); + const result = await h.engine.dryRun(flow([ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'call', type: 'http', label: 'Call', config: { url: 'https://example.test/deals/{{ record.id }}', method: 'POST', body: { dialect: 'cel', source: '{"amount": record.amount}' } } }, + { id: 'as', type: 'assignment', label: 'Read', config: { assignments: { got: { dialect: 'cel', source: 'has(vars.call) ? 1 : 0' } } } }, + { id: 'end', type: 'end', label: 'End' }, + ], chain('start', 'call', 'as', 'end')), { userId: 'usr_maker', record: { id: 'd1', amount: 7 } }); + expect(sent).toBe(0); + expect(result.steps.find((s) => s.nodeId === 'call')).toEqual({ + nodeId: 'call', nodeType: 'http', kind: 'outbound', + payload: { url: 'https://example.test/deals/d1', method: 'POST', body: { amount: 7 } }, + }); + }); +}); + +describe('dryRun — text slots render as the live executor renders them, in options.locale', () => { + const NOTICE = 'Sent {{ record.name }} for approval'; + const ZH_NOTICE = '已将 {{ record.name }} 提交审批'; + const noticeDraft = () => ({ + name: 'deal_submit', label: 'Deal submit', type: 'record_change', + nodes: [ + { id: 'start', type: 'start', label: 'Start', config: { objectName: 'deal', triggerType: 'record-after-update' } }, + { id: 'tell', type: 'save_notice', label: 'Tell', config: { message: NOTICE } }, + { id: 'done', type: 'end', label: 'Done' }, + ], + edges: chain('start', 'tell', 'done'), + }); + const record = { id: 'd1', name: 'Acme renewal' }; + + it('a save_notice payload carries the zh-CN translation at flows.NAME.notices.NODE.message, and the authored text with no locale', async () => { + const h = harness({ bundles: { 'zh-CN': bundleAt(flowNoticeMessageKey('deal_submit', 'tell'), ZH_NOTICE) } }); + + const zh = await h.engine.dryRun(noticeDraft(), { userId: 'usr_maker', record, locale: 'zh-CN' }); + const plain = await h.engine.dryRun(noticeDraft(), { userId: 'usr_maker', record }); + + expect(zh.status).toBe('completed'); + expect(zh.steps.find((s) => s.nodeId === 'tell')).toMatchObject({ kind: 'outbound', payload: { message: '已将 Acme renewal 提交审批' } }); + expect(plain.steps.find((s) => s.nodeId === 'tell')).toMatchObject({ kind: 'outbound', payload: { message: 'Sent Acme renewal for approval' } }); + }); + + it('a refusing end node carries the zh-CN translation of its message', async () => { + const h = harness({ bundles: { 'zh-CN': bundleAt(flowRefusalMessageKey('draft_flow', 'finish'), '{{ record.name }} 不能提交') } }); + const draft = flow([ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'finish', type: 'end', label: 'Finish', config: { outcome: 'refused', message: '{{ record.name }} cannot be submitted' } }, + ], chain('start', 'finish')); + + const zh = await h.engine.dryRun(draft, { userId: 'usr_maker', record, locale: 'zh-CN' }); + const plain = await h.engine.dryRun(draft, { userId: 'usr_maker', record }); + + expect(zh.steps.find((s) => s.nodeId === 'finish')).toMatchObject({ refusalMessage: 'Acme renewal 不能提交' }); + expect(plain.steps.find((s) => s.nodeId === 'finish')).toMatchObject({ refusalMessage: 'Acme renewal cannot be submitted' }); + }); +}); + +describe('dryRun — a refused write a fault edge contains', () => { + it('goes on along the fault edge: the write step carries the refusal and the handler runs after it', async () => { + const h = harness({ canWrite: () => false }); + const result = await h.engine.dryRun(flow([ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'mk', type: 'create_record', label: 'Create', config: { objectName: 'deal', fields: { stage: 'open' } } }, + { id: 'handler', type: 'assignment', label: 'Handle', config: { assignments: { handled: { dialect: 'cel', source: 'true' } } } }, + { id: 'ok', type: 'end', label: 'Ok' }, + { id: 'end', type: 'end', label: 'End' }, + ], [ + { id: 'e0', source: 'start', target: 'mk' }, + { id: 'e1', source: 'mk', target: 'ok' }, + { id: 'e_fault', source: 'mk', target: 'handler', type: 'fault' }, + { id: 'e2', source: 'handler', target: 'end' }, + ]), { userId: 'usr_maker' }); + + expect(result.status).not.toBe('failed'); + expect(writes(h)).toEqual([]); + const ids = result.steps.map((s) => s.nodeId); + expect(result.steps.find((s) => s.nodeId === 'mk')).toMatchObject({ + kind: 'write', permission: 'refused', refusal: { code: 'PERMISSION_DENIED' }, + }); + expect(ids.indexOf('handler')).toBeGreaterThan(ids.indexOf('mk')); + expect(ids).not.toContain('ok'); + }); +}); + +describe('dryRun — an object-level write check that throws', () => { + it('reports the write refused, as a denial, and the run fails there', async () => { + const h = harness({ canWrite: () => { throw new Error('permission store unreachable'); } }); + const result = await h.engine.dryRun(flow([ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'mk', type: 'create_record', label: 'Create', config: { objectName: 'deal', fields: { stage: 'open' } } }, + { id: 'end', type: 'end', label: 'End' }, + ], chain('start', 'mk', 'end')), { userId: 'usr_maker' }); + + expect(result.status).toBe('failed'); + expect(writes(h)).toEqual([]); + expect(result.steps.find((s) => s.nodeId === 'mk')).toMatchObject({ + kind: 'write', permission: 'refused', refusal: { code: 'PERMISSION_DENIED' }, + }); + }); +}); + +describe('dryRun — a predicate write the engine refuses without multi', () => { + const predicateWrite = (node: Record) => flow([ + { id: 'start', type: 'start', label: 'Start' }, + node, + { id: 'end', type: 'end', label: 'End' }, + ], chain('start', String(node.id), 'end')); + + it('an update by predicate with no multi fails with the engine\'s own error, targeting and reading no row', async () => { + const h = harness({ canWrite: () => true }); + const result = await h.engine.dryRun(predicateWrite( + { id: 'up', type: 'update_record', label: 'Update', config: { objectName: 'deal', filter: { stage: 'open' }, fields: { stage: 'won' } } }, + ), { userId: 'usr_maker' }); + + expect(result.status).toBe('failed'); + expect(writes(h)).toEqual([]); + expect(h.calls.filter((c) => c.op === 'find' || c.op === 'findOne')).toEqual([]); + expect(result.steps.find((s) => s.nodeId === 'up')).toMatchObject({ kind: 'write', operation: 'update', recordIds: [] }); + expect(String(result.steps.find((s) => s.nodeId === 'up')?.error)).toContain(ENGINE_UPDATE_REJECT_MESSAGE); + }); + + it('a delete by predicate with no multi fails with the engine\'s own error', async () => { + const h = harness(); + const result = await h.engine.dryRun(predicateWrite( + { id: 'rm', type: 'delete_record', label: 'Delete', config: { objectName: 'deal', filter: { stage: 'open' } } }, + ), { userId: 'usr_maker' }); + + expect(result.status).toBe('failed'); + expect(writes(h)).toEqual([]); + expect(result.steps.find((s) => s.nodeId === 'rm')).toMatchObject({ kind: 'write', operation: 'delete', recordIds: [] }); + expect(String(result.steps.find((s) => s.nodeId === 'rm')?.error)).toContain(ENGINE_DELETE_REJECT_MESSAGE); + }); + + it('CONTROL — the same update declaring multi lists every row it matches', async () => { + const h = harness({ canWrite: () => true }); + const result = await h.engine.dryRun(predicateWrite( + { id: 'up', type: 'update_record', label: 'Update', config: { objectName: 'deal', filter: { stage: 'open' }, fields: { stage: 'won' }, multi: true } }, + ), { userId: 'usr_maker' }); + + expect(result.status).toBe('completed'); + expect(result.steps.find((s) => s.nodeId === 'up')).toMatchObject({ kind: 'write', operation: 'update', recordIds: ['d1'] }); + }); +}); + +describe('dryRun — a write targets exactly the rows the engine dispatch names', () => { + const rows = () => ({ d1: { id: 'd1', stage: 'open', amount: 10 }, d2: { id: 'd2', stage: 'open', amount: 20 } }); + const readBoth = [ + { id: 'r1', type: 'get_record', label: 'Read d1', config: { objectName: 'deal', filter: { id: 'd1' }, outputVariable: 'one' } }, + { id: 'r2', type: 'get_record', label: 'Read d2', config: { objectName: 'deal', filter: { id: 'd2' }, outputVariable: 'two' } }, + { id: 'as', type: 'assignment', label: 'Keep', config: { assignments: { seen: { dialect: 'cel', source: 'one.stage + "/" + two.stage' } } } }, + ]; + + it('an update whose fields name the id, with no filter, targets that one row and lays its values over it alone', async () => { + const h = harness({ canWrite: () => true, rows: rows() }); + const result = await h.engine.dryRun(flow([ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'up', type: 'update_record', label: 'Update', config: { objectName: 'deal', fields: { id: 'd2', stage: 'won' } } }, + ...readBoth, + { id: 'end', type: 'end', label: 'End' }, + ], chain('start', 'up', 'r1', 'r2', 'as', 'end')), { userId: 'usr_maker' }); + + expect(result.status).toBe('completed'); + expect(writes(h)).toEqual([]); + expect(result.steps.find((s) => s.nodeId === 'up')).toMatchObject({ kind: 'write', operation: 'update', recordIds: ['d2'] }); + expect(result.steps.find((s) => s.nodeId === 'as')).toMatchObject({ kind: 'assignment', values: { seen: 'open/won' } }); + }); + + it('CONTROL — the same update declaring multi with no filter targets every row the named user can read', async () => { + const h = harness({ canWrite: () => true, rows: rows() }); + const result = await h.engine.dryRun(flow([ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'up', type: 'update_record', label: 'Update', config: { objectName: 'deal', fields: { stage: 'won' }, multi: true } }, + ...readBoth, + { id: 'end', type: 'end', label: 'End' }, + ], chain('start', 'up', 'r1', 'r2', 'as', 'end')), { userId: 'usr_maker' }); + + expect(result.status).toBe('completed'); + expect(result.steps.find((s) => s.nodeId === 'up')).toMatchObject({ kind: 'write', operation: 'update', recordIds: ['d1', 'd2'] }); + expect(result.steps.find((s) => s.nodeId === 'as')).toMatchObject({ kind: 'assignment', values: { seen: 'won/won' } }); + }); +}); diff --git a/packages/services/service-automation/src/dry-run.ts b/packages/services/service-automation/src/dry-run.ts new file mode 100644 index 00000000000..e74b1e09fd3 --- /dev/null +++ b/packages/services/service-automation/src/dry-run.ts @@ -0,0 +1,841 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * {@link AutomationEngine.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 is `IAutomationService.dryRun`'s docblock + * (`@objectstack/spec/contracts`, `automation-service.ts`); this module is its + * implementation, and every sentence below points at the sentence it honours. + * + * ## How a dry run runs the nodes + * + * Through the live run's OWN traversal: the bodies of `executeNode` and + * `traverseNext` (`dag-traversal.ts`), handed a host whose executor map is + * this module's. So edges, conditions, `fault` routing, `try_catch` regions + * and the runaway guard behave exactly as they do live, and nothing here + * re-spells them. + * + * - The nodes that route or compute (`decision`, `assignment`, `loop`, + * `parallel`, `try_catch`) run their registered executors, "as the live run + * runs them". A container's body runs through `AutomationEngine.runRegion`, + * which asks {@link activeDryRunExecuteNode} and so stays inside the dry + * run. + * - `get_record`, `create_record`, `update_record` and `delete_record` run + * their registered executors too, which compute the filter and the field + * values as live; the data engine they reach is {@link dryRunDataEngine}'s + * stand-in, which reads live data and simulates every write. + * - The nodes with an effect outside the data are never called: their payload + * is computed from the node's own value and text slots (the spec ledgers + * `FLOW_NODE_EXPRESSION_PATHS` and `FLOW_NODE_TEXT_SLOTS`) and reported. + * - A node whose descriptor declares `supportsPause: true`, and a node type + * outside every class the contract names, stops the run. + * + * ## Why an `AsyncLocalStorage` + * + * A container executor and a data node reach the engine and the data engine + * through what they closed over at registration, not through an argument, so + * the dry run is found by the async context it runs in: the frame is set + * around the traversal and nowhere else, and a live run on the same engine at + * the same time never sees it. The same idiom as `builtin/loop-frame.ts`. + * + * ## Step order + * + * Each node execution opens a segment under the segment of the node that + * called it, at the moment it is called, so a node's successors, a container's + * body and a `parallel` node's branches hang under it in call order. The steps + * are the segments read depth-first: a node's unconditional out-edges are one + * branch after another in declaration order, each branch's steps together. + */ + +import { AsyncLocalStorage } from 'node:async_hooks'; +import { randomUUID } from 'node:crypto'; +import type { FlowEdgeParsed, FlowNodeParsed, FlowParsed } from '@objectstack/spec/automation'; +import { flowNodeTextSlotSources, resolveFlowNodeExpressions } from '@objectstack/spec/automation'; +import type { FlowInnerRefusal } from '@objectstack/spec/api'; +import type { + AutomationContext, + FlowDryRunOptions, + FlowDryRunResult, + FlowDryRunStep, + FlowDryRunStopStep, + FlowDryRunWritePermission, +} from '@objectstack/spec/contracts'; +import { aiAccountElevatedStartRefusal, requiredPermissionsStartRefusal } from '@objectstack/core'; +import { + executeNode as executeNodeBody, + startConditionHolds, + traverseNext as traverseNextBody, +} from './dag-traversal.js'; +import { + isRefusalSignal, + isSuspendSignal, + type AutomationEngine, + type FlowUserGrants, + type NodeExecutionResult, + type NodeExecutor, + type StepLogEntry, +} from './engine.js'; +import { renderTextSlot } from './builtin/template.js'; +import { renderSaveNoticeMessage } from './builtin/save-notice-node.js'; +import { + engineUpdateDispatchRejectError, + resolveEngineDeleteDispatch, + resolveEngineUpdateDispatch, + type EngineDeleteDispatchInput, + type EngineUpdateDispatchData, + type EngineUpdateDispatchInput, +} from '@objectstack/metadata-core'; +import { readCarriedRefusal } from './inner-refusal.js'; + +/** The nodes that only route the run (`FlowDryRunRouteStep`). */ +const ROUTE_NODE_TYPES: ReadonlySet = new Set(['start', 'end', 'loop', 'parallel', 'try_catch']); +/** The data writes (`FlowDryRunWriteStep`), by the operation each reports. */ +const WRITE_NODE_OPERATIONS: Readonly> = { + create_record: 'create', + update_record: 'update', + delete_record: 'delete', +}; +/** The nodes with an effect outside the data (`FlowDryRunOutboundStep`). */ +const OUTBOUND_NODE_TYPES: ReadonlySet = new Set(['notify', 'http', 'connector_action', 'script', 'save_notice']); +/** The `stop` reason a pausing node type reports (`FlowDryRunStopStep.reason`). */ +const STOP_REASONS: Readonly> = { + approval: 'approval', + approval_revise: 'approval', + wait: 'wait', + screen: 'screen', + subflow: 'starts_flow', + map: 'starts_flow', +}; + +/** + * The `AutomationEngine` members a dry run reads, each typed as the member + * itself (the `DagTraversalHost` idiom), handed by {@link AutomationEngine.dryRun}. + */ +export interface DryRunHost { + readonly logger: AutomationEngine['logger']; + readonly nodeExecutors: ReadonlyMap; + readonly userGrantsResolver: () => AutomationEngine['userGrantsResolver']; + readonly judgeFlowRegistration: AutomationEngine['judgeFlowRegistration']; + readonly resolveRunContext: AutomationEngine['resolveRunContext']; + readonly seedRunVariables: AutomationEngine['seedRunVariables']; + readonly evaluateCondition: AutomationEngine['evaluateCondition']; + readonly evaluateValueEnvelope: AutomationEngine['evaluateValueEnvelope']; + readonly validateNodeInputSchemas: AutomationEngine['validateNodeInputSchemas']; + readonly isInputSchemaViolation: (err: unknown) => boolean; + readonly getActionDescriptor: AutomationEngine['getActionDescriptor']; + readonly renderRefusalMessage: AutomationEngine['renderRefusalMessage']; + readonly renderFlowTextSlot: AutomationEngine['renderFlowTextSlot']; + readonly executeWithTimeout: AutomationEngine['executeWithTimeout']; + readonly setNodeError: AutomationEngine['setNodeError']; +} + +type MutableStep = { -readonly [K in keyof FlowDryRunStep]?: unknown } & { + nodeId: string; + nodeType: string; + kind: FlowDryRunStep['kind']; + [key: string]: unknown; +}; + +interface Segment { + readonly parent?: Segment; + readonly node?: FlowNodeParsed; + readonly flow?: FlowParsed; + readonly step?: MutableStep; + readonly children: Segment[]; +} + +interface DryRunState { + readonly host: DryRunHost; + /** The definition's own `name`: the flow its nodes read their `flows..…` keys under (the contract's **The name.**). */ + readonly flowName: string; + readonly root: Segment; + /** Set once a node stops the run (`'stopped'`), or the run ended: no node runs after it. */ + halted: boolean; + stoppedAt?: Segment; + /** The node whose failure is travelling out (containers it passes through do not replace it). */ + failedAt?: Segment; + /** The run's simulated rows, by object. */ + readonly created: Map>>; + readonly updated: Map>>; + readonly deleted: Map>; + readonly placeholderPrefix: string; + placeholderCount: number; +} + +interface DryRunFrame { + readonly state: DryRunState; + readonly segment: Segment; +} + +const frames = new AsyncLocalStorage(); + +/** What a write step reports, filled by the data engine stand-in. */ +interface SimulatedWrite { + operation: 'create' | 'update' | 'delete'; + object: string; + recordIds: string[]; + values?: Record; + permission: FlowDryRunWritePermission; +} + +/** + * The `executeNode` a container's region runs its body through while a dry + * run is in progress, or `undefined` outside one. Asked by + * `AutomationEngine.runRegion`, so a `loop`, `parallel` or `try_catch` body + * stays inside the dry run. + */ +export function activeDryRunExecuteNode(): + | ((node: FlowNodeParsed, flow: FlowParsed, variables: Map, context: AutomationContext, steps: StepLogEntry[]) => Promise) + | undefined { + const frame = frames.getStore(); + if (!frame) return undefined; + const { state } = frame; + return (node, flow, variables, context, steps) => dryExecuteNode(state, node, flow, variables, context, steps); +} + +function isPlainObject(value: unknown): value is Record { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} + +/** The single id a `where` names (`{ id: X }`), or `undefined` for a filter that names none. */ +function namedId(where: unknown): string | undefined { + if (!isPlainObject(where)) return undefined; + const keys = Object.keys(where); + if (keys.length !== 1 || keys[0] !== 'id') return undefined; + const id = where.id; + return typeof id === 'string' || typeof id === 'number' ? String(id) : undefined; +} + +function project(row: Record, fields: unknown): Record { + if (!Array.isArray(fields) || fields.length === 0) return { ...row }; + const out: Record = {}; + for (const f of ['id', ...fields]) if (typeof f === 'string' && f in row) out[f] = row[f]; + return out; +} + +/** The refusal a write the object-level check refuses answers (`PERMISSION_DENIED`, 403). */ +function writeRefusedError(operation: 'insert' | 'update', object: string): Error { + return Object.assign( + new Error(`The named user may not ${operation} '${object}' records (object-level write check).`), + { status: 403, code: 'PERMISSION_DENIED' }, + ); +} + +type DataEngineLike = Record & { + find?: (object: string, query?: Record) => Promise; + findOne?: (object: string, query?: Record) => Promise; +}; + +/** + * The data engine a CRUD node reaches while a dry run is in progress, or + * `undefined` outside one (the node then uses `real` as always). Called by the + * CRUD executors' data lookup (`builtin/crud-nodes.ts`). + * + * - Writes are simulated ("Writes: simulated, never made"): `insert`, + * `update` and `delete` write nothing, record the write on the node's step, + * and lay it over the run's own view of the rows. An update or a delete + * targets exactly the rows the engine's own dispatch picks. + * - A read that names an id answers the run's view: a created row holds only + * the fields the flow set, an updated row is the live row with the + * simulated fields laid over it, a deleted row is nothing. + * - Any other read passes to the live engine, in the scope the node hands it + * (the named user's), and does not see the run's simulated writes. + * - `canWriteObject`, read off the `security` service the kernel serves + * (`security()`), judges an insert or an update, and a check that throws + * is a denial (`'refused'`); with none installed, or for a delete, the + * write answers `'not_judged'`. + */ +export function dryRunDataEngine(real: unknown, security: () => unknown): unknown { + const frame = frames.getStore(); + if (!frame) return undefined; + const { state } = frame; + const live = (real ?? undefined) as DataEngineLike | undefined; + + const judge = async ( + operation: 'insert' | 'update', + object: string, + context: unknown, + data: unknown, + ): Promise => { + let svc: unknown; + try { svc = security(); } catch { svc = undefined; } + const check = (svc as { canWriteObject?: unknown } | undefined)?.canWriteObject; + if (typeof check !== 'function') return 'not_judged'; + try { + const allowed = await (check as (o: string, op: string, c: unknown, d: unknown) => Promise) + .call(svc, object, operation, context, data); + return allowed ? 'allowed' : 'refused'; + } catch { + // The check's own contract: a throw is a denial. + return 'refused'; + } + }; + + const readById = async (object: string, id: string, query: Record): Promise | null> => { + if (state.deleted.get(object)?.has(id)) return null; + const created = state.created.get(object)?.get(id); + if (created) return project(created, query.fields); + const row = live?.findOne ? await live.findOne(object, query) : null; + if (!isPlainObject(row)) return null; + const patch = state.updated.get(object)?.get(id); + return patch ? { ...row, ...project(patch, query.fields) } : row; + }; + + /** + * The rows a write targets: exactly the engine dispatch's own answer + * (`resolveEngineUpdateDispatch` / `resolveEngineDeleteDispatch`), so + * `recordIds` is "the rows the write targets" on every arm. `by-id` is + * the one id the dispatch picked, wherever it came from (`where.id`, or + * an update's `data.id`), when the named user can read it; `multi` is + * the rows the filter matches in the named user's scope; `reject` + * targets no row and reads none. + */ + const targets = async ( + object: string, + dispatch: { readonly kind: 'by-id'; readonly id: unknown } | { readonly kind: 'multi' } | { readonly kind: 'reject' }, + where: unknown, + context: unknown, + ): Promise => { + if (dispatch.kind === 'reject') return []; + if (dispatch.kind === 'by-id') { + const id = String(dispatch.id); + if (state.deleted.get(object)?.has(id)) return []; + if (state.created.get(object)?.has(id)) return [id]; + const row = live?.findOne ? await live.findOne(object, { where: { id: dispatch.id }, fields: ['id'], context }) : null; + return isPlainObject(row) ? [id] : []; + } + const rows = live?.find ? await live.find(object, { where, fields: ['id'], context }) : []; + return Array.isArray(rows) + ? rows.map((r) => (isPlainObject(r) ? r.id : undefined)).filter((v) => v != null).map(String) + : []; + }; + + const record = (write: SimulatedWrite): void => { + const seg = frames.getStore()?.segment; + if (seg?.step) (seg as { write?: SimulatedWrite }).write = write; + }; + + const overrides: Record = { + async insert(object: string, data: unknown, options?: { context?: unknown }) { + const values = isPlainObject(data) ? { ...data } : {}; + const permission = await judge('insert', object, options?.context, data); + const id = `${state.placeholderPrefix}${++state.placeholderCount}`; + record({ operation: 'create', object, recordIds: [id], values, permission }); + if (permission === 'refused') throw writeRefusedError('insert', object); + let rows = state.created.get(object); + if (!rows) state.created.set(object, (rows = new Map())); + rows.set(id, { ...values, id }); + return { ...values, id }; + }, + async update(object: string, data: unknown, options?: { where?: unknown; context?: unknown }) { + const values = isPlainObject(data) ? { ...data } : {}; + // The engine's own dispatch decision, asked as the live update + // asks it, and its targets read off that answer: one row by id + // (from `where.id` or the values' own `id`), the filter's rows + // under `multi`, and none on a reject — a call naming neither one + // row nor `multi` is refused with the engine's own error, after + // the permission gate and before any row is read. + const dispatch = resolveEngineUpdateDispatch(data as EngineUpdateDispatchData, options as EngineUpdateDispatchInput | undefined); + const ids = await targets(object, dispatch, options?.where, options?.context); + const permission = await judge('update', object, options?.context, data); + record({ operation: 'update', object, recordIds: ids, values, permission }); + if (permission === 'refused') throw writeRefusedError('update', object); + if (dispatch.kind === 'reject') throw engineUpdateDispatchRejectError(dispatch); + for (const id of ids) { + const created = state.created.get(object)?.get(id); + if (created) { Object.assign(created, values); continue; } + let patches = state.updated.get(object); + if (!patches) state.updated.set(object, (patches = new Map())); + patches.set(id, { ...(patches.get(id) ?? {}), ...values }); + } + return ids.length; + }, + async delete(object: string, options?: { where?: unknown; context?: unknown }) { + // As `update`: the engine's own dispatch decision, its targets, + // and its own error. A delete's by-id arm reads `where.id` only. + const dispatch = resolveEngineDeleteDispatch(options as EngineDeleteDispatchInput | undefined); + const ids = await targets(object, dispatch, options?.where, options?.context); + record({ operation: 'delete', object, recordIds: ids, permission: 'not_judged' }); + if (dispatch.kind === 'reject') throw new Error(dispatch.message); + let gone = state.deleted.get(object); + if (!gone) state.deleted.set(object, (gone = new Set())); + for (const id of ids) gone.add(id); + return ids.length; + }, + async findOne(object: string, query: Record = {}) { + const id = namedId(query.where); + if (id !== undefined) return readById(object, id, query); + return live?.findOne ? live.findOne(object, query) : null; + }, + async find(object: string, query: Record = {}) { + const id = namedId(query.where); + if (id !== undefined) { + const row = await readById(object, id, query); + return row ? [row] : []; + } + return live?.find ? live.find(object, query) : []; + }, + }; + + return new Proxy(live ?? {}, { + get(target, prop, receiver) { + if (typeof prop === 'string' && Object.prototype.hasOwnProperty.call(overrides, prop)) return overrides[prop]; + const value = Reflect.get(target, prop, receiver); + return typeof value === 'function' ? value.bind(target) : value; + }, + }); +} + +/** The node's class, and the step it opens with. */ +function openStep(state: DryRunState, node: FlowNodeParsed): MutableStep { + const base = { nodeId: node.id, nodeType: node.type }; + if (ROUTE_NODE_TYPES.has(node.type)) return { ...base, kind: 'route' }; + if (node.type === 'assignment') return { ...base, kind: 'assignment', values: {} }; + if (node.type === 'decision') return { ...base, kind: 'decision', expressions: [], next: [] }; + if (node.type === 'get_record') { + return { ...base, kind: 'read', object: String((node.config as { objectName?: unknown } | undefined)?.objectName ?? ''), recordIds: [] }; + } + if (WRITE_NODE_OPERATIONS[node.type]) return { ...base, kind: 'write' }; + if (OUTBOUND_NODE_TYPES.has(node.type)) return { ...base, kind: 'outbound', payload: undefined }; + const pauses = state.host.getActionDescriptor(node.type)?.supportsPause === true; + return { ...base, kind: 'stop', reason: pauses ? (STOP_REASONS[node.type] ?? 'suspends') : 'not_simulated' }; +} + +function isAncestor(maybe: Segment, of: Segment): boolean { + for (let s: Segment | undefined = of.parent; s; s = s.parent) if (s === maybe) return true; + return false; +} + +/** Record a failure on `segment`'s step, unless it is a container the failure is travelling out through. */ +function noteFailure(state: DryRunState, segment: Segment, failure: { refusal?: FlowInnerRefusal; error?: string }): void { + const step = segment.step; + if (!step) return; + if (failure.refusal) step.refusal = failure.refusal; + else if (step.refusal === undefined && failure.error !== undefined) step.error = failure.error; + if (!state.failedAt || !isAncestor(segment, state.failedAt)) state.failedAt = segment; +} + +/** One node execution, in its own segment, through the live run's own `executeNode` body. */ +function dryExecuteNode( + state: DryRunState, + node: FlowNodeParsed, + flow: FlowParsed, + variables: Map, + context: AutomationContext, + steps: StepLogEntry[], +): Promise { + if (state.halted) return Promise.resolve(); + const parent = frames.getStore()?.segment ?? state.root; + const segment: Segment = { parent, node, flow, step: openStep(state, node), children: [] }; + parent.children.push(segment); + const nodeHost: ThisParameterType = { + renderRefusalMessage: state.host.renderRefusalMessage, + nodeExecutors: dryExecutorView(state), + executeWithTimeout: state.host.executeWithTimeout, + setNodeError: state.host.setNodeError, + executeNode: (...a) => dryExecuteNode(state, ...a), + // The dry executors decide their own stops (`supportsPause` and the + // types no class names), so the live run's declaration check on a + // suspension has nothing to judge here. + refuseUndeclaredSuspension: () => null, + traverseNext: (...a) => traverseNextBody.call(traverseHost(state), ...a), + }; + return frames.run({ state, segment }, () => executeNodeBody.call(nodeHost, node, flow, variables, context, steps)); +} + +function traverseHost(state: DryRunState): ThisParameterType { + return { + logger: state.host.logger, + evaluateCondition: state.host.evaluateCondition, + executeNode: (...a) => dryExecuteNode(state, ...a), + }; +} + +/** The executor map `executeNode`'s body reads during a dry run: one dry executor per type. */ +function dryExecutorView(state: DryRunState): Map { + const view = new Map(); + view.get = (type: string): NodeExecutor | undefined => dryExecutor(state, type); + return view; +} + +function currentSegment(): Segment | undefined { + return frames.getStore()?.segment; +} + +function dryExecutor(state: DryRunState, type: string): NodeExecutor | undefined { + const segment = currentSegment(); + const step = segment?.step; + if (!segment || !step) return undefined; + + if (type === 'start') return { type, execute: async () => ({ success: true }) }; + + if (step.kind === 'outbound') { + return { + type, + async execute(node, variables, context) { + try { + step.payload = outboundPayload(state, node, variables, context); + } catch (err) { + noteFailure(state, segment, { error: err instanceof Error ? err.message : String(err) }); + throw err; + } + // "binds no output": a later node that reads it finds it unset. + return { success: true }; + }, + }; + } + + if (step.kind === 'stop') { + return { + type, + async execute(node, variables, context) { + const stop = step as unknown as FlowDryRunStopStep; + if (stop.reason === 'wait') { + const wait = (node as { waitEventConfig?: { eventType?: unknown; timerDuration?: unknown; signalName?: unknown } }).waitEventConfig; + if (wait && typeof wait.eventType === 'string') { + stop.wait = { + eventType: wait.eventType, + ...(typeof wait.timerDuration === 'string' ? { timerDuration: wait.timerDuration } : {}), + ...(typeof wait.signalName === 'string' ? { signalName: wait.signalName } : {}), + }; + } + } else if (stop.reason === 'starts_flow') { + const flowName = (node.config as { flowName?: unknown } | undefined)?.flowName; + if (typeof flowName === 'string' && flowName) stop.flowName = flowName; + } else if (stop.reason === 'screen') { + // The screen executor only builds the screen it hands the + // runner; nothing is stored until a run parks, and a dry + // run parks nothing. + const screen = state.host.nodeExecutors.get('screen'); + if (screen) { + let built: NodeExecutionResult; + try { + built = await screen.execute(node, variables, context); + } catch (err) { + noteFailure(state, segment, { error: err instanceof Error ? err.message : String(err) }); + throw err; + } + if (!built.success) { + noteFailure(state, segment, { error: built.error ?? 'Unknown error' }); + return built; + } + if (built.screen) stop.screen = built.screen; + } + } + state.halted = true; + state.stoppedAt = segment; + return { success: true, suspend: true }; + }, + }; + } + + const real = state.host.nodeExecutors.get(type); + if (!real) { + // As live: no executor for a type that needs one fails the node. + noteFailure(state, segment, { error: `No executor registered for node type '${type}'` }); + return undefined; + } + return { + type, + descriptor: real.descriptor, + async execute(node, variables, context) { + let result: NodeExecutionResult; + try { + if (step.kind === 'assignment') { + // Every variable the node sets, with the value it set. + // An assignment sets synchronously, so the recorder is + // removed before any other branch can run. + const values = step.values as Record; + const set = variables.set; + variables.set = function recordSet(key: string, value: unknown) { + values[key] = value; + return set.call(this, key, value); + }; + let pending: Promise; + try { + pending = real.execute(node, variables, context); + } finally { + variables.set = set; + } + result = await pending; + } else { + result = await real.execute(node, variables, context); + } + } catch (err) { + if (!state.stoppedAt && !isSuspendSignal(err)) { + const { innerRefusal } = readCarriedRefusal(err); + noteFailure(state, segment, { + ...(innerRefusal ? { refusal: innerRefusal } : {}), + error: err instanceof Error ? err.message : String(err), + }); + } + throw err; + } + annotate(state, segment, node, result); + return result; + }, + }; +} + +function annotate(state: DryRunState, segment: Segment, node: FlowNodeParsed, result: NodeExecutionResult): void { + const step = segment.step!; + if (!result.success) { + noteFailure(state, segment, { + ...(result.innerRefusal ? { refusal: result.innerRefusal } : {}), + error: result.error ?? 'Unknown error', + }); + } + if (step.kind === 'decision') { + const conditions = (node.config as { conditions?: Array<{ label?: string; expression?: string }> } | undefined)?.conditions; + if (Array.isArray(conditions) && conditions.length > 0 && typeof result.branchLabel === 'string') { + step.branch = result.branchLabel; + const held = conditions.find((c) => c.label === result.branchLabel); + step.expressions = held && typeof held.expression === 'string' ? [held.expression] : []; + } + } else if (step.kind === 'read' && result.success) { + const output = result.output as { records?: unknown; record?: unknown } | undefined; + const rows = Array.isArray(output?.records) ? output.records : output?.record ? [output.record] : []; + step.recordIds = rows + .map((r) => (isPlainObject(r) ? r.id : undefined)) + .filter((v) => v != null) + .map(String); + } +} + +/** Write the value at a ledger path (`a.b`, `list[1]`, `input.key`) into `root`. */ +function setAtPath(root: Record, path: string, value: unknown): void { + const parts: Array = []; + for (const segment of path.split('.')) { + const match = /^(.*?)((?:\[\d+\])*)$/.exec(segment); + if (match?.[1]) parts.push(match[1]); + for (const idx of match?.[2]?.matchAll(/\[(\d+)\]/g) ?? []) parts.push(Number(idx[1])); + } + let cursor: unknown = root; + for (let i = 0; i < parts.length - 1; i++) { + cursor = (cursor as Record | undefined)?.[parts[i]]; + if (cursor === null || typeof cursor !== 'object') return; + } + (cursor as Record)[parts[parts.length - 1]] = value; +} + +/** + * What an outbound node would send, as it computed it: its config (and, for + * `connector_action`, its `connectorConfig`), with every CEL value slot + * evaluated and every text slot rendered in the run's scope. The slots are the + * spec's ledgers, the ones registration judges and the executors read. + * + * Each text slot renders as its live executor renders it, in the same locale + * (`options.locale`, on the run's context). Measured: the `notify` executor + * renders `title`, `message` and `actionUrl`, and the `http` executor `url` + * and each `headers` value, through `renderTextSlot` with no translation, so + * they render the authored text here too. The `save_notice` executor + * translates its `message` (`flows..notices..message`), so it + * is rendered here by that executor's own {@link renderSaveNoticeMessage}, + * under the definition's own name, never by a second lookup. + */ +function outboundPayload( + state: DryRunState, + node: FlowNodeParsed, + variables: Map, + context: AutomationContext, +): unknown { + const blocks: Record = { + config: structuredClone(node.config ?? {}), + ...(node.type === 'connector_action' ? { connectorConfig: structuredClone((node as { connectorConfig?: unknown }).connectorConfig ?? {}) } : {}), + }; + for (const slot of resolveFlowNodeExpressions(node.type, node.config, node as never)) { + if (slot.entry.role !== 'value') continue; + const value = state.host.evaluateValueEnvelope( + slot.value as { dialect?: string; source?: string }, + variables, + `${slot.block}.${slot.path}`, + context, + ); + const block = blocks[slot.block]; + if (isPlainObject(block)) setAtPath(block, slot.path, value); + } + const renderSlot = (path: string, source: string): string | undefined => ( + node.type === 'save_notice' && path === 'message' + ? renderSaveNoticeMessage(state.host, state.flowName, node.id, source, variables, context) + : renderTextSlot(source, variables, context.currency) + ); + for (const slot of flowNodeTextSlotSources(node.type, node.config)) { + const config = blocks.config as Record; + if (slot.path.includes('.')) { + const dot = slot.path.indexOf('.'); + const map = config[slot.path.slice(0, dot)]; + if (isPlainObject(map)) map[slot.path.slice(dot + 1)] = renderSlot(slot.path, slot.source); + } else { + config[slot.path] = renderSlot(slot.path, slot.source); + } + } + return node.type === 'connector_action' ? blocks : blocks.config; +} + +/** The authored text of a condition (its `source`, for an envelope). */ +function conditionText(condition: unknown): string { + if (typeof condition === 'string') return condition; + const source = (condition as { source?: unknown } | null | undefined)?.source; + return typeof source === 'string' ? source : ''; +} + +/** The steps, read off the segments depth-first, finished. */ +function finish(state: DryRunState, until?: Segment): FlowDryRunStep[] { + const out: FlowDryRunStep[] = []; + let done = false; + const visit = (segment: Segment): void => { + if (done) return; + if (segment.step) { + out.push(finishStep(segment)); + if (segment === until) { done = true; return; } + } + for (const child of segment.children) visit(child); + }; + visit(state.root); + return out; +} + +function finishStep(segment: Segment): FlowDryRunStep { + const step = segment.step!; + const node = segment.node!; + if (step.kind === 'decision') { + const next = segment.children.map((c) => c.node!.id); + step.next = next; + const conditions = (node.config as { conditions?: unknown[] } | undefined)?.conditions; + if (!(Array.isArray(conditions) && conditions.length > 0)) { + // A gateway: the out-edges carry the branching, so the + // expressions are the conditioned out-edges the run took. + const edges: FlowEdgeParsed[] = (segment.flow?.edges ?? []).filter( + (e) => e.source === node.id && e.type !== 'fault' && e.condition && next.includes(e.target), + ); + step.expressions = edges.map((e) => conditionText(e.condition)); + } + } else if (step.kind === 'write') { + const write = (segment as { write?: SimulatedWrite }).write; + const config = node.config as { objectName?: unknown } | undefined; + step.operation = write?.operation ?? WRITE_NODE_OPERATIONS[node.type]; + step.object = write?.object ?? String(config?.objectName ?? ''); + step.recordIds = write?.recordIds ?? []; + if (write?.values && step.operation !== 'delete') step.values = write.values; + step.permission = write?.permission ?? 'not_judged'; + } + const out: Record = {}; + for (const [key, value] of Object.entries(step)) if (value !== undefined) out[key] = value; + return out as unknown as FlowDryRunStep; +} + +/** The body of {@link AutomationEngine.dryRun}; that method's docblock is its contract. */ +export async function dryRun(this: DryRunHost, definition: unknown, options: FlowDryRunOptions): Promise { + // "In what order it answers" — the acting user first, before the definition is read. + const userId = (options as { userId?: unknown } | null | undefined)?.userId; + if (typeof userId !== 'string' || userId === '') { + throw new TypeError('dryRun: options.userId must be a non-empty string naming the acting user.'); + } + // "The name": the definition's own, judged as registration judges it; + // nothing is registered. + const ownName = (definition as { name?: unknown } | null | undefined)?.name; + const flow = this.judgeFlowRegistration(typeof ownName === 'string' ? ownName : '', definition); + + const tenantId = options.tenantId; + const needsGrants = tenantId !== undefined || flow.runAs === 'system' || (Array.isArray(flow.requiredPermissions) && flow.requiredPermissions.length > 0); + let grants: FlowUserGrants | undefined; + const resolver = this.userGrantsResolver(); + if (needsGrants && resolver) { + try { + grants = (await resolver(userId, tenantId)) ?? undefined; + } catch { + // Unread grants admit nothing below: refused, never admitted on a guess. + grants = undefined; + } + } + const refused = (message: string): FlowDryRunResult => ({ status: 'refused', steps: [], refusal: { code: 'PERMISSION_DENIED', message } }); + if (tenantId !== undefined && !(Array.isArray(grants?.accessible_org_ids) && grants.accessible_org_ids.includes(tenantId))) { + return refused(`The named user is not a member of organization '${tenantId}', so a dry run cannot run in it.`); + } + // "Admission: the by-name start rule" — the rules a start by name asks, + // one spelling (`@objectstack/core`'s `flow-start-rules.ts`), judged on + // the definition against the named user. A dry run starts with no action + // in hand, so no AI opt-in stands. The elevated self-triggered rule is the + // by-name doors' alone (ruling B, record 6917953931). + // Every arm fails closed on unread grants: the tenant above (no + // membership read), `requiredPermissions` (no capability read), and the AI + // service account rule, which cannot tell an account from a person + // without them, so a `runAs: 'system'` definition is refused here. + if (needsGrants && grants === undefined && flow.runAs === 'system') { + return refused("The named user's grants could not be read, so a dry run cannot admit a definition that runs as the system."); + } + const caller = { + ...(grants?.principalKind ? { principalKind: grants.principalKind } : {}), + systemPermissions: Array.isArray(grants?.systemPermissions) ? grants.systemPermissions : [], + }; + const admission = aiAccountElevatedStartRefusal(flow, caller, false) ?? requiredPermissionsStartRefusal(flow, caller); + if (admission) return refused(admission.message); + + // "Identity: the named user" — never elevated, `runAs: 'system'` included: + // run setup resolves the user's own grants as for a user run whose context + // carries none. No run id: nothing is persisted. + const start: AutomationContext = { + userId, + ...(tenantId !== undefined ? { tenantId } : {}), + ...(options.record !== undefined ? { record: options.record } : {}), + ...(options.previous !== undefined ? { previous: options.previous } : {}), + ...(options.object !== undefined ? { object: options.object } : {}), + ...(options.event !== undefined ? { event: options.event } : {}), + ...(options.params !== undefined ? { params: options.params } : {}), + ...(options.locale !== undefined ? { locale: options.locale } : {}), + }; + const variables: Map = this.seedRunVariables(flow, flow.name, start, ''); + variables.delete('$runId'); + const runContext = await this.resolveRunContext({ ...flow, runAs: 'user' }, start); + + const startNode = flow.nodes.find((n) => n.type === 'start')!; + const condition = (startNode.config as { condition?: unknown } | undefined)?.condition; + try { + if (!startConditionHolds.call({ evaluateCondition: this.evaluateCondition }, startNode, variables, runContext)) { + return { status: 'condition_not_met', steps: [], startCondition: { expression: conditionText(condition), result: false } }; + } + } catch (err) { + const fault = err instanceof Error ? err.message : String(err); + return { status: 'failed', steps: [], startCondition: { expression: conditionText(condition), fault }, error: fault }; + } + try { + this.validateNodeInputSchemas(flow, variables); + } catch (err) { + if (!this.isInputSchemaViolation(err)) throw err; + return { status: 'refused', steps: [], refusal: { code: 'FLOW_INPUT_SCHEMA_INVALID', message: (err as Error).message } }; + } + + const state: DryRunState = { + host: this, + flowName: flow.name, + root: { children: [] }, + halted: false, + created: new Map(), + updated: new Map(), + deleted: new Map(), + // Opaque, unique within the call, and never a live row's id. + placeholderPrefix: `dry-run:${randomUUID()}:`, + placeholderCount: 0, + }; + try { + await dryExecuteNode(state, startNode, flow, variables, runContext, []); + state.halted = true; + return { status: 'completed', steps: finish(state) }; + } catch (err) { + state.halted = true; + if (state.stoppedAt) return { status: 'stopped', steps: finish(state, state.stoppedAt) }; + if (isRefusalSignal(err)) { + // An `end` declaring `outcome: 'refused'` completes; its step + // carries the rendered message. + const steps = finish(state); + const end = [...steps].reverse().find((s) => s.nodeId === err.nodeId); + if (end && end.kind === 'route' && err.message !== undefined) end.refusalMessage = err.message; + return { status: 'completed', steps }; + } + return { + status: 'failed', + steps: finish(state, state.failedAt), + error: err instanceof Error ? err.message : String(err), + }; + } +} diff --git a/packages/services/service-automation/src/engine.ts b/packages/services/service-automation/src/engine.ts index ffb47b4129f..625f5651420 100644 --- a/packages/services/service-automation/src/engine.ts +++ b/packages/services/service-automation/src/engine.ts @@ -10,7 +10,7 @@ import type { FlowFunctionEffect, FlowRunSummary, } from '@objectstack/spec/automation'; -import type { AutomationContext, AutomationResult, ResumeSignal, IAutomationService, RunListResult, ScreenSpec, ScreenFieldSpec, ConnectorSourcePullRequest, ConnectorSourcePullResult, ConnectorCredentialRef, ConnectorCredentialSetRequest, ConnectorCredentialClearRequest, ConnectorConnectionState, ConnectorConnectionRequest, ConnectorConnectionBegin, ConnectorConnectionCallbackRequest } from '@objectstack/spec/contracts'; +import type { AutomationContext, AutomationResult, ResumeSignal, IAutomationService, RunListResult, ScreenSpec, ScreenFieldSpec, ConnectorSourcePullRequest, ConnectorSourcePullResult, ConnectorCredentialRef, ConnectorCredentialSetRequest, ConnectorCredentialClearRequest, ConnectorConnectionState, ConnectorConnectionRequest, ConnectorConnectionBegin, ConnectorConnectionCallbackRequest, FlowDryRunOptions, FlowDryRunResult } from '@objectstack/spec/contracts'; import type { MetadataActivationWriteOptions } from '@objectstack/core'; import type { FlowRegistration, FlowRegistrationRefusal, FlowInnerRefusal } from '@objectstack/spec/api'; import { RESUME_AUTHORITY_SERVICE } from '@objectstack/spec/contracts'; @@ -130,6 +130,7 @@ import { executeWithoutRetry, type runUserOf, } from './dag-traversal.js'; +import { activeDryRunExecuteNode, dryRun as dryRunBody, type DryRunHost } from './dry-run.js'; // [#25222] The run history's bodies: recording a run's log entry, finishing a // refused run, and reading runs and suspended runs back. Each // `AutomationEngine` method of the same name calls its body. @@ -887,6 +888,15 @@ export interface FlowUserGrants { * it beside the grants ({@link SeededRunContext.principalKind}). */ principalKind?: 'agent'; + /** + * The capabilities the user's permission sets grant + * (`resolveUserAuthzGrants`' own field, under its own name; an AI service + * account's is empty there). Read by a dry run's admission alone + * ({@link AutomationEngine.dryRun}: the flow's `requiredPermissions`); run + * setup does not seed it on a run context. A resolver that omits it admits + * no declared capability. + */ + systemPermissions?: string[]; } /** @@ -1592,6 +1602,15 @@ export interface ChildRunRefusal { */ class InputSchemaViolationError extends Error {} +/** + * Whether `err` is the node input-schema check's refusal + * ({@link AutomationEngine.validateNodeInputSchemas}), the one a dry run + * answers `FLOW_INPUT_SCHEMA_INVALID` for, as `execute` does. + */ +export function isInputSchemaViolation(err: unknown): boolean { + return err instanceof InputSchemaViolationError; +} + /** * The refusal codes {@link AutomationEngine.resumeInternal} answers for a * resume that NEVER RAN — the run is untouched, nothing executed, and the @@ -5495,10 +5514,15 @@ export class AutomationEngine implements IAutomationService { * putting back the definition it held), which keeps the arm it had. * {@link armedFlowPackage} reads it. */ - registerFlow(name: string, definition: unknown, armedFrom?: FlowContender): FlowParsed { - const arm: FlowContender = armedFrom - ?? (definition !== null && typeof definition === 'object' ? this.flowArms.get(definition) : undefined) - ?? { source: 'runtime' }; + /** + * Judge `definition` as {@link registerFlow} judges it under `name`, and + * register nothing: canonicalize and parse it, then run every + * registration check, throwing the first refusal. Returns the parsed + * flow. Shared by {@link registerFlow} and {@link dryRun} ("a definition + * registerFlow would refuse … throws what registerFlow throws for it"), + * so the two cannot disagree about what registers. + */ + private judgeFlowRegistration(name: string, definition: unknown): FlowParsed { // One canonicalization policy, shared with the stored-row migration so // the two can never disagree about what "canonical" means (#4454). // Execution takes the parsed shape (schema defaults materialized). @@ -5506,11 +5530,8 @@ export class AutomationEngine implements IAutomationService { // ADR-0018 §M1 — node types are validated against the live action // registry, but NOT here: the check moved to the moment the vocabulary - // is closed (see the end of this method and {@link - // sealNodeTypeVocabulary}). The protocol no longer gates `type` with a - // closed enum; membership is checked at that seam instead, and stays - // soft-fail — a flow authored against a currently-absent plugin must - // still register, and executeNode() throws NO_EXECUTOR at run time. + // is closed (see the end of {@link registerFlow} and {@link + // sealNodeTypeVocabulary}). // [#23317] Every registration check, in order, through the ONE list // the stored pass previews with ({@link registrationChecks}). The first @@ -5521,7 +5542,58 @@ export class AutomationEngine implements IAutomationService { const refusal = check(name, parsed); if (refusal) throw new Error(refusal.message); } + return parsed; + } + + /** + * Dry-run a flow definition that need not be published: once, unarmed, as + * a named user, against a supplied start, without changing live data — + * `IAutomationService.dryRun` (`@objectstack/spec/contracts`), whose + * docblock is this method's contract, implemented in `./dry-run.ts`. + */ + dryRun(definition: unknown, options: FlowDryRunOptions): Promise { + const readUserGrantsResolver = () => this.userGrantsResolver; + const host: DryRunHost = { + logger: this.logger, + nodeExecutors: this.nodeExecutors, + userGrantsResolver: readUserGrantsResolver, + judgeFlowRegistration: (...a) => this.judgeFlowRegistration(...a), + resolveRunContext: (...a) => this.resolveRunContext(...a), + seedRunVariables: (...a) => this.seedRunVariables(...a), + evaluateCondition: (...a) => this.evaluateCondition(...a), + evaluateValueEnvelope: (...a) => this.evaluateValueEnvelope(...a), + validateNodeInputSchemas: (...a) => this.validateNodeInputSchemas(...a), + isInputSchemaViolation, + getActionDescriptor: (...a) => this.getActionDescriptor(...a), + renderRefusalMessage: (...a) => this.renderRefusalMessage(...a), + renderFlowTextSlot: (...a) => this.renderFlowTextSlot(...a), + executeWithTimeout: (...a) => this.executeWithTimeout(...a), + setNodeError: (...a) => this.setNodeError(...a), + }; + // Called with no `options` object is a caller error the body reports + // as the contract's first answer (a `TypeError` naming `userId`). + return dryRunBody.call(host, definition, options ?? ({} as FlowDryRunOptions)); + } + registerFlow(name: string, definition: unknown, armedFrom?: FlowContender): FlowParsed { + const arm: FlowContender = armedFrom + ?? (definition !== null && typeof definition === 'object' ? this.flowArms.get(definition) : undefined) + ?? { source: 'runtime' }; + const parsed = this.judgeFlowRegistration(name, definition); + + // ADR-0018 §M1 — node types are validated against the live action + // registry, but NOT here: the check moved to the moment the vocabulary + // is closed (see the end of this method and {@link + // sealNodeTypeVocabulary}). The protocol no longer gates `type` with a + // closed enum; membership is checked at that seam instead, and stays + // soft-fail — a flow authored against a currently-absent plugin must + // still register, and executeNode() throws NO_EXECUTOR at run time. + + // [#23317] Every registration check, in order, through the ONE list + // the stored pass previews with ({@link registrationChecks}). The first + // refusal is thrown, so a flow is refused exactly as before; a check + // belongs in that list, never as a second call here, or the stored + // pass would read a flow this method refuses as on protocol. // [ADR-0150 D4, #31696] The slot the body is held in: its package's, // so two packages' flows of one name are both armed (the line #31677 // Q1 drew, "arming neither", moves here). Every record below is filed @@ -11130,8 +11202,11 @@ export class AutomationEngine implements IAutomationService { partialSteps?: StepLogEntry[], ): Promise { // The body lives in ./dag-traversal.ts (#25222). + // [#33661] Inside a dry run the body runs the dry run's nodes, so a + // container's region writes nothing and sends nothing either. + const dryExecuteNode = activeDryRunExecuteNode(); const host: ThisParameterType = { - executeNode: (...a) => this.executeNode(...a), + executeNode: dryExecuteNode ?? ((...a) => this.executeNode(...a)), resolveSuspensionChainForCancel: (...a) => this.resolveSuspensionChainForCancel(...a), cancelRun: (...a) => this.cancelRun(...a), logger: this.logger, diff --git a/packages/services/service-automation/src/plugin.ts b/packages/services/service-automation/src/plugin.ts index 706cb173e34..16b8d39a2cf 100644 --- a/packages/services/service-automation/src/plugin.ts +++ b/packages/services/service-automation/src/plugin.ts @@ -2608,6 +2608,10 @@ export class AutomationServicePlugin implements Plugin { ...(grants.posture ? { posture: grants.posture } : {}), // [ADR-0151 D3] An AI service account runs as an agent. ...(grants.principalKind ? { principalKind: grants.principalKind } : {}), + // [#33661] The capabilities the user holds, read by a + // dry run's admission (`requiredPermissions`) alone; + // run setup does not seed them on a run. + systemPermissions: grants.systemPermissions, ...(tenantId ? { tenantId } : {}), }; }); 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 c89998fded5..d25d761e187 100644 --- a/packages/spec/src/contracts/automation-dry-run.pin.test.ts +++ b/packages/spec/src/contracts/automation-dry-run.pin.test.ts @@ -215,7 +215,9 @@ describe('IAutomationService.dryRun — the contract (#33757)', () => { 'no other flow, no audit row.', 'never send or call anything', 'no child run starts.', - 'every named user.', + 'is admitted to a\n * dry run for the named user', + 'The run is\n * never elevated: every read and every permission judgement is the\n * named user\'s.', + 'the widening is the dry run\'s alone.', "`status: 'condition_not_met'`", "`'not_judged'` never means allowed.", 'the simulated fields laid over it', @@ -233,6 +235,12 @@ describe('IAutomationService.dryRun — the contract (#33757)', () => { ]) { expect(doc, sentence).toContain(sentence); } + // Ruling B (record 6917953931) replaced the by-name refusal of an + // elevated self-triggered draft; the refusal sentence is gone. + expect(doc).not.toContain('is refused for\n * every named user.'); + // After ruling B no dry-run admission rule reads the definition's `type`. + expect(doc).toContain("judged on the supplied definition's `runAs`\n * and `requiredPermissions` against the named user."); + expect(doc).not.toContain("judged on the supplied definition's `type`"); }); it('a faulting start condition follows the live run only on the default error strategy (#33935)', () => { diff --git a/packages/spec/src/contracts/automation-service.ts b/packages/spec/src/contracts/automation-service.ts index da99c730352..2c198f73171 100644 --- a/packages/spec/src/contracts/automation-service.ts +++ b/packages/spec/src/contracts/automation-service.ts @@ -1860,12 +1860,15 @@ export interface IAutomationService { * * **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 + * `flow-start-admission.ts`), judged on the supplied definition's `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. + * trigger (`autolaunched`, `record_change`, `schedule`) is admitted to a + * dry run for the named user (ruling B, record 6917953931). The run is + * never elevated: every read and every permission judgement is the + * named user's. A by-name start of a published flow keeps refusing it + * (`flowStartRefusal`); the widening is the dry run's alone. * - 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. diff --git a/scripts/engine-double-contract.pinned.json b/scripts/engine-double-contract.pinned.json index 45d1cf202bd..10fe8f13079 100644 --- a/scripts/engine-double-contract.pinned.json +++ b/scripts/engine-double-contract.pinned.json @@ -5586,6 +5586,21 @@ "verb": "delete", "pinned": 1 }, + { + "file": "packages/services/service-automation/src/dry-run.test.ts", + "verb": "delete", + "pinned": 1 + }, + { + "file": "packages/services/service-automation/src/dry-run.test.ts", + "verb": "findOne", + "pinned": 1 + }, + { + "file": "packages/services/service-automation/src/dry-run.test.ts", + "verb": "update", + "pinned": 1 + }, { "file": "packages/services/service-automation/src/flow-activation-ledger.test.ts", "verb": "update",