diff --git a/.changeset/38667-automation-engine-facets.md b/.changeset/38667-automation-engine-facets.md new file mode 100644 index 00000000000..a4bc6c832e1 --- /dev/null +++ b/.changeset/38667-automation-engine-facets.md @@ -0,0 +1,13 @@ +--- +'@objectstack/service-automation': patch +'@objectstack/spec': patch +--- + +refactor(service-automation): `AutomationEngine` becomes a delegating facade over eight facet modules, unchanged + +Clause-②: no +Metadata-protocol: none + +Internal only: no behaviour changes and nothing is added to or removed from the package entry. The bodies of 145 `AutomationEngine` members move, byte for byte, into static methods of eight facet classes (dispatch, extensions, flow slots, registration, connector doors, enablement, run and resume); each member stays on the class with its signature (and, when public, its docblock) as a one-call stub, so the published declaration of `AutomationEngine`, an instance spy and a subclass override are what they were. The engine's state stays on the class, and a facet body reaches it through a host built once per engine. + +- `@objectstack/spec`: the `flow` and `connector` liveness ledgers cite the facet modules that now hold the bodies they name (`engine-run-facet.ts#retryExecution` and the three retry-backoff keys; `engine-extensions-facet.ts#getConnectorDescriptors`); no verdict changes. diff --git a/docs/audits/2026-08-tenant-audit-write-call-sites.counts/services/service-automation.md b/docs/audits/2026-08-tenant-audit-write-call-sites.counts/services/service-automation.md index 5e36fba7af1..aac739da881 100644 --- a/docs/audits/2026-08-tenant-audit-write-call-sites.counts/services/service-automation.md +++ b/docs/audits/2026-08-tenant-audit-write-call-sites.counts/services/service-automation.md @@ -14,17 +14,17 @@ a row or a number here — fix the code, or the census, and regenerate. | Measure | Value | |---|---:| -| Write call sites | 40 | +| Write call sites | 42 | | Object name statically decidable | 34 | -| Object name chosen at run time | 6 | +| Object name chosen at run time | 8 | | Object name spelled inline | 0 | | Object name spelled through a `const` | 34 | -| Object name is an `object: string` parameter | 1 | +| Object name is an `object: string` parameter | 3 | | Object name is some other run-time expression | 5 | | Against a tenancy-enabled object | 34 | | Against an object declaring tenancy off | 0 | | Threading a tenant context | 40 | -| Provably carrying none (options read, no context key) | 0 | +| Provably carrying none (options read, no context key) | 2 | | …and decidably tenancy-enabled | 0 | | Options argument unreadable | 0 | | …and decidably tenancy-enabled | 0 | @@ -33,7 +33,7 @@ a row or a number here — fix the code, or the census, and regenerate. | Threading a context of undecidable elevation | 9 | | Receiver carried a readable engine type | 30 | | Receiver erased, placed by the object NAME | 10 | -| Receiver erased, placed by an `object: string` PARAMETER | 0 | +| Receiver erased, placed by an `object: string` PARAMETER | 2 | | Receiver erased, placed by an `UNTYPED_RECEIVERS` row | 0 | ## Subtractions the census could NOT defend — enforced @@ -58,6 +58,7 @@ a row or a number here — fix the code, or the census, and regenerate. | `packages/services/service-automation/src/connector-credentials.ts` | `insert` | `sys_connector_credential` | enabled | context, elevation undecidable | 1 | | `packages/services/service-automation/src/connector-credentials.ts` | `update` | `sys_connector_credential` | enabled | context, elevation undecidable | 1 | | `packages/services/service-automation/src/connector-credentials.ts` | `update` | `sys_connector_credential` | enabled | elevated | 3 | +| `packages/services/service-automation/src/engine-registration-facet.ts` | `delete` | `name` | undecidable | PROVABLY NONE | 2 | | `packages/services/service-automation/src/flow-credential-channel.ts` | `delete` | `sys_flow_credential` | enabled | elevated | 5 | | `packages/services/service-automation/src/flow-credential-channel.ts` | `insert` | `sys_flow_credential` | enabled | elevated | 1 | | `packages/services/service-automation/src/flow-credential-channel.ts` | `update` | `sys_flow_credential` | enabled | elevated | 2 | diff --git a/packages/services/service-automation/src/engine-connector-doors-facet.ts b/packages/services/service-automation/src/engine-connector-doors-facet.ts new file mode 100644 index 00000000000..348995b5b31 --- /dev/null +++ b/packages/services/service-automation/src/engine-connector-doors-facet.ts @@ -0,0 +1,247 @@ +// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#38667] The credential and connection doors: the flow credential source, connector pulls, connector credentials and connections, and flow credential holdings: the bodies of + * `setFlowCredentialSource`, `pullConnectorSource`, + * `requireConnectorCredentialDoor`, `attachConnectorCredentialPubSub`, + * `resyncConnectorCredentialPubSub`, `listConnectorCredentialRefs`, + * `setConnectorCredential`, `clearConnectorCredential`, + * `requireConnectorConnectionDoor`, `getConnectorConnection`, + * `beginConnectorConnection`, `completeConnectorConnection`, + * `revokeConnectorConnection`, `holdsFlowCredential`, `resolveFlowCredential`, + * `flowCredentialHoldings` + * moved out of `engine.ts` whole. + * + * A MOVE, not a redesign. {@link ConnectorDoorsFacet} is a stateless facet of + * `AutomationEngine`: each static method of it is the body of the + * `AutomationEngine` method of the same name exactly as it stood, not + * re-indented, not formatted, not edited, with a `this` parameter added when + * the body reads the engine. The method stays on the class as a one-call stub + * with its signature, so the published declaration, an instance spy and a + * subclass override are what they were. A public method keeps its docblock on + * the class, the contract; a private method's docblock moved here with its + * body. The state stays on `AutomationEngine`. + * + * The bodies reach the engine through {@link ConnectorDoorsHost}: exactly the + * `AutomationEngine` members they read, private ones included. Every stub + * hands its body, by a `.call`, the same host: `connectorDoorsHost` in + * `engine-facet-hosts.ts`, built once per engine by the class's static block. + * Methods go as closures that call them on the engine at call time, so a spy + * or a subclass override is still the one reached; fields go as getters, read + * when the body reads them, and a field a body assigns also goes with a setter + * that assigns it on the engine. + * + * The module imports `engine.ts` for types only, so the two modules form no + * evaluation cycle. `index.ts` re-exports nothing from this module. + */ + +import type { + ConnectorSourcePullRequest, + ConnectorSourcePullResult, + ConnectorCredentialRef, + ConnectorCredentialSetRequest, + ConnectorCredentialClearRequest, + ConnectorConnectionState, + ConnectorConnectionRequest, + ConnectorConnectionBegin, + ConnectorConnectionCallbackRequest, + IPubSub, +} from '@objectstack/spec/contracts'; +import { FlowCredentialUnresolvableError } from './flow-credential-channel.js'; +import { flowCredentialHoldings } from './flow-definitions.js'; +import { PackageScopedNameRefusedError } from '@objectstack/core'; +import { isSlotKeySpelling } from './flow-slots.js'; +import type { + FlowCredentialSource, + ConnectorCredentialDoor, + ConnectorConnectionDoor, + FlowCredentialHolding, +} from './engine-registration.js'; +import type { AutomationEngine } from './engine.js'; + +/** + * The `AutomationEngine` members the bodies of {@link ConnectorDoorsFacet} read — every one + * of them, and no other. Each is typed AS the class member (an indexed access + * on the class), so a change to a member's signature on the class is a change + * here too. `readonly` members are the getters; the others are fields a body + * assigns. + */ +export interface ConnectorDoorsHost { + readonly connectorConnectionDoor: AutomationEngine['connectorConnectionDoor']; + readonly connectorCredentialDoor: AutomationEngine['connectorCredentialDoor']; + readonly connectorPullSource: AutomationEngine['connectorPullSource']; + flowCredentialSource: AutomationEngine['flowCredentialSource']; + readonly flowSlots: AutomationEngine['flowSlots']; + readonly flows: AutomationEngine['flows']; + readonly requireConnectorConnectionDoor: AutomationEngine['requireConnectorConnectionDoor']; + readonly requireConnectorCredentialDoor: AutomationEngine['requireConnectorCredentialDoor']; + readonly sharedFlowNameRefusal: AutomationEngine['sharedFlowNameRefusal']; +} + +/** The bodies of the "The credential and connection doors" members of `AutomationEngine`: a stateless facet, called by the class's stubs. */ +export class ConnectorDoorsFacet { + /** The body of `AutomationEngine#setFlowCredentialSource`; the method's docblock there is its contract. */ + static setFlowCredentialSource(this: Pick, source: FlowCredentialSource | undefined): void { + // [ADR-0150 D8 row R9, #31696] Asked by slot key, answered by the + // flow's name and — for a name two packages hold — its package. A + // bare name two packages hold names neither flow, so it is refused + // (409, naming both), as at every bare door. + const at = (key: string): [string, string | undefined] => { + const slot = this.flowSlots.slot(key); + if (!slot) { + if (this.flowSlots.isShared(key)) { + throw new PackageScopedNameRefusedError(this.sharedFlowNameRefusal(key, null)); + } + return [key, undefined]; + } + if (!this.flowSlots.isShared(slot.name)) return [slot.name, undefined]; + return [slot.name, slot.packageId ?? '']; + }; + // [S3] A source that does not answer by package is never asked for a + // slot of a shared name: it fails closed, naming the slot. + const scoped = source?.readsByPackage === true; + const unscopedRefusal = (name: string, flowPackage: string) => { + const others = this.flowSlots.slotsOf(name) + .map((slot) => slot.packageId ?? '') + .filter((packageId) => packageId !== flowPackage); + return new FlowCredentialUnresolvableError( + `Flow '${name}' of package "${flowPackage}": its credentials cannot be read. ` + + `${others.map((p) => `Package "${p}"`).join(', ')} also ${others.length === 1 ? 'holds' : 'hold'} a flow ` + + `named '${name}', and the flow credential source attached to this engine reads by flow name alone, ` + + 'so it could answer another package\'s secret. Nothing was read. Attach a source that reads by ' + + 'package (FlowCredentialSource.readsByPackage).', + ); + }; + this.flowCredentialSource = source && { + readsByPackage: true, + holds: (key, nodeId, credentialKey) => { + const [name, flowPackage] = at(key); + if (flowPackage === undefined) return source.holds(name, nodeId, credentialKey); + // [S1] By name alone, a "no" means no package holds one, so an unsigned node runs. + return scoped ? source.holds(name, nodeId, credentialKey, flowPackage) : source.holds(name, nodeId, credentialKey); + }, + held: (key) => { + const [name, flowPackage] = at(key); + if (flowPackage === undefined) return source.held(name); + if (!scoped) throw unscopedRefusal(name, flowPackage); + return source.held(name, flowPackage); + }, + resolve: async (key, nodeId, credentialKey) => { + const [name, flowPackage] = at(key); + if (flowPackage === undefined) return source.resolve(name, nodeId, credentialKey); + if (!scoped) throw unscopedRefusal(name, flowPackage); + return source.resolve(name, nodeId, credentialKey, flowPackage); + }, + }; + } + + /** The body of `AutomationEngine#pullConnectorSource`; the method's docblock there is its contract. */ + static async pullConnectorSource(this: Pick, request: ConnectorSourcePullRequest): Promise { + if (!this.connectorPullSource) { + // ADR-0112: the code the executor itself answers for "cannot pull + // now" (a degraded connector), so a caller branches on one pair. + throw Object.assign( + new Error( + `[Automation] pullConnectorSource('${request.mapping}'): this automation engine has no connector sync ` + + 'executor attached — it is attached by AutomationServicePlugin at init(); a bare engine cannot pull. Nothing was pulled.', + ), + { code: 'SERVICE_UNAVAILABLE', status: 503 }, + ); + } + return this.connectorPullSource(request); + } + + /** [#27237] The door, or the refusal a bare engine answers: nothing here can store a credential. */ + static requireConnectorCredentialDoor(this: Pick, verb: string): ConnectorCredentialDoor { + if (this.connectorCredentialDoor) return this.connectorCredentialDoor; + throw Object.assign( + new Error( + `[Automation] ${verb}: this automation engine has no connector credential door attached — it is attached by ` + + 'AutomationServicePlugin at init(); a bare engine has no declared connectors and no credential store.', + ), + { code: 'SERVICE_UNAVAILABLE', status: 503 }, + ); + } + + /** The body of `AutomationEngine#attachConnectorCredentialPubSub`; the method's docblock there is its contract. */ + static attachConnectorCredentialPubSub(this: Pick, pubsub: IPubSub, nodeId: string): () => void { + return this.requireConnectorCredentialDoor('attachConnectorCredentialPubSub()').attachClusterPubSub(pubsub, nodeId); + } + + /** The body of `AutomationEngine#resyncConnectorCredentialPubSub`; the method's docblock there is its contract. */ + static async resyncConnectorCredentialPubSub(this: Pick): Promise { + await this.requireConnectorCredentialDoor('resyncConnectorCredentialPubSub()').resyncFromCluster?.(); + } + + /** The body of `AutomationEngine#listConnectorCredentialRefs`; the method's docblock there is its contract. */ + static async listConnectorCredentialRefs(this: Pick): Promise { + return this.requireConnectorCredentialDoor('listConnectorCredentialRefs()').list(); + } + + /** The body of `AutomationEngine#setConnectorCredential`; the method's docblock there is its contract. */ + static async setConnectorCredential(this: Pick, request: ConnectorCredentialSetRequest): Promise { + return this.requireConnectorCredentialDoor(`setConnectorCredential('${request.ref}')`).set(request); + } + + /** The body of `AutomationEngine#clearConnectorCredential`; the method's docblock there is its contract. */ + static async clearConnectorCredential(this: Pick, request: ConnectorCredentialClearRequest): Promise { + return this.requireConnectorCredentialDoor(`clearConnectorCredential('${request.ref}')`).clear(request); + } + + /** ADR-0143 D5 — the door, or the refusal a bare engine answers: nothing here can connect an instance. */ + static requireConnectorConnectionDoor(this: Pick, verb: string): ConnectorConnectionDoor { + if (this.connectorConnectionDoor) return this.connectorConnectionDoor; + throw Object.assign( + new Error( + `[Automation] ${verb}: this automation engine has no connector connection door attached — it is attached by ` + + 'AutomationServicePlugin at init(); a bare engine has no declared connectors and no connection store.', + ), + { code: 'SERVICE_UNAVAILABLE', status: 503 }, + ); + } + + /** The body of `AutomationEngine#getConnectorConnection`; the method's docblock there is its contract. */ + static async getConnectorConnection(this: Pick, request: ConnectorConnectionRequest): Promise { + return this.requireConnectorConnectionDoor(`getConnectorConnection('${request.connector}')`).get(request); + } + + /** The body of `AutomationEngine#beginConnectorConnection`; the method's docblock there is its contract. */ + static async beginConnectorConnection(this: Pick, request: ConnectorConnectionRequest): Promise { + return this.requireConnectorConnectionDoor(`beginConnectorConnection('${request.connector}')`).begin(request); + } + + /** The body of `AutomationEngine#completeConnectorConnection`; the method's docblock there is its contract. */ + static async completeConnectorConnection(this: Pick, request: ConnectorConnectionCallbackRequest): Promise { + return this.requireConnectorConnectionDoor('completeConnectorConnection()').complete(request); + } + + /** The body of `AutomationEngine#revokeConnectorConnection`; the method's docblock there is its contract. */ + static async revokeConnectorConnection(this: Pick, request: ConnectorConnectionRequest): Promise { + return this.requireConnectorConnectionDoor(`revokeConnectorConnection('${request.connector}')`).revoke(request); + } + + /** The body of `AutomationEngine#holdsFlowCredential`; the method's docblock there is its contract. */ + static holdsFlowCredential(this: Pick, flowName: string, nodeId: string, key: string): boolean { + return this.flowCredentialSource?.holds(flowName, nodeId, key) ?? false; + } + + /** The body of `AutomationEngine#resolveFlowCredential`; the method's docblock there is its contract. */ + static async resolveFlowCredential(this: Pick, flowName: string, nodeId: string, key: string): Promise { + if (!this.flowCredentialSource) return undefined; + return this.flowCredentialSource.resolve(flowName, nodeId, key); + } + + /** The body of `AutomationEngine#flowCredentialHoldings`; the method's docblock there is its contract. */ + static flowCredentialHoldings(this: Pick, name: string): FlowCredentialHolding[] { + // [#31696] By name: a slot key is no flow's name, and a name two + // packages hold names neither flow (no slot is filed under it). + if (isSlotKeySpelling(name)) return []; + // The body lives in ./flow-definitions.ts (#25222). + const readFlowCredentialSource = () => this.flowCredentialSource; + const host: ThisParameterType = { + flows: this.flows, + get flowCredentialSource() { return readFlowCredentialSource(); }, + }; + return flowCredentialHoldings.call(host, name); + } +} diff --git a/packages/services/service-automation/src/engine-dispatch-facet.ts b/packages/services/service-automation/src/engine-dispatch-facet.ts new file mode 100644 index 00000000000..2864ef3b36c --- /dev/null +++ b/packages/services/service-automation/src/engine-dispatch-facet.ts @@ -0,0 +1,157 @@ +// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#38667] Dispatch and the run store: the scheduled-work policy, the slot-keyed run store, missed scheduled runs and the run-start ledger: the bodies of + * `readScheduledWorkPolicy`, `slotKeyedRunStore`, `missedRunLimit`, + * `recordMissedRun`, `noteRunStarted` + * moved out of `engine.ts` whole. + * + * A MOVE, not a redesign. {@link DispatchFacet} is a stateless facet of + * `AutomationEngine`: each static method of it is the body of the + * `AutomationEngine` method of the same name exactly as it stood, not + * re-indented, not formatted, not edited, with a `this` parameter added when + * the body reads the engine. The method stays on the class as a one-call stub + * with its signature, so the published declaration, an instance spy and a + * subclass override are what they were. A public method keeps its docblock on + * the class, the contract; a private method's docblock moved here with its + * body. The state stays on `AutomationEngine`. + * + * The bodies reach the engine through {@link DispatchHost}: exactly the + * `AutomationEngine` members they read, private ones included. Every stub + * hands its body, by a `.call`, the same host: `dispatchHost` in + * `engine-facet-hosts.ts`, built once per engine by the class's static block. + * Methods go as closures that call them on the engine at call time, so a spy + * or a subclass override is still the one reached; fields go as getters, read + * when the body reads them, and a field a body assigns also goes with a setter + * that assigns it on the engine. + * + * The module imports `engine.ts` for types only, so the two modules form no + * evaluation cycle. `index.ts` re-exports nothing from this module. + */ + +import type { AutomationContext } from '@objectstack/spec/contracts'; +import { resolveScheduledWorkPolicy, type ScheduledWorkPolicy } from '@objectstack/types'; +import { describeThrownForLog } from './thrown-cause-diagnostics.js'; +import { qualifiedFlowKey, unfiledFlowKey } from './flow-slots.js'; +import { flowSlotRunStore } from './flow-slot-run-store.js'; +import { buildRunTrigger, missedRunId } from './engine-run-trigger.js'; +import type { SuspendedRunStore } from './engine-resume.js'; +import type { MissedScheduledRun, MissedRunOutcome } from './engine-dispatch-store.js'; +import type { AutomationEngine } from './engine.js'; + +/** + * The `AutomationEngine` members the bodies of {@link DispatchFacet} read — every one + * of them, and no other. Each is typed AS the class member (an indexed access + * on the class), so a change to a member's signature on the class is a change + * here too. `readonly` members are the getters; the others are fields a body + * assigns. + */ +export interface DispatchHost { + readonly flowDispatchStore: AutomationEngine['flowDispatchStore']; + readonly flowSlots: AutomationEngine['flowSlots']; + readonly flows: AutomationEngine['flows']; + readonly logger: AutomationEngine['logger']; + readonly maxLogSize: AutomationEngine['maxLogSize']; + readonly recordLog: AutomationEngine['recordLog']; + readonly runsStartedByContext: AutomationEngine['runsStartedByContext']; + readonly scheduledWorkPolicy: AutomationEngine['scheduledWorkPolicy']; + readonly store: AutomationEngine['store']; +} + +/** The bodies of the "Dispatch and the run store" members of `AutomationEngine`: a stateless facet, called by the class's stubs. */ +export class DispatchFacet { + /** + * [#19834] The scheduled-work policy for THIS engine, read at each bind: + * the per-kernel option when one was given, else the zero-argument + * deployment resolver, unchanged. + */ + static readScheduledWorkPolicy(this: Pick): ScheduledWorkPolicy { + const source = this.scheduledWorkPolicy; + if (source === undefined) return resolveScheduledWorkPolicy(); + return typeof source === 'function' ? source() : source; + } + + /** + * [ADR-0150 D8 row R8, #31696] The attached store as the engine reads and + * writes it: records keyed by slot key here, by `(flow name, flow + * package)` in the store — see ./flow-slot-run-store.ts. + */ + static slotKeyedRunStore(this: Pick, store: SuspendedRunStore): SuspendedRunStore { + return flowSlotRunStore(store, { + // The flow's own name and package, never a key. The run's own + // package (stamped at start) comes first, so a run whose key moved + // in flight is still its own package's run. A key no slot files is + // a qualified key moved back to the bare name: split at its last `/`. + stored: (key, flowPackage) => { + // [S3, N8] An unfiled key stores its name and no slot's package: the lone slot of a shared name is not its. + if (key.startsWith('\u0000')) return { flowName: key.slice(1), ...(flowPackage ? { flowPackage } : {}) }; + const slot = this.flowSlots.slot(key); + const cut = key.lastIndexOf('/'); + const flowName = slot?.name ?? (cut >= 0 ? key.slice(cut + 1) : key); + const packageId = flowPackage || (slot ? slot.packageId ?? undefined : cut >= 0 ? key.slice(0, cut) : undefined); + return { flowName, ...(packageId ? { flowPackage: packageId } : {}) }; + }, + key: (flowName, flowPackage) => { + if (!flowPackage) return this.flowSlots.isShared(flowName) ? unfiledFlowKey(flowName) : flowName; + const key = this.flowSlots.keyOf(flowName, flowPackage); + if (key !== undefined) return key; + // The package holds no flow of the name now: a key no slot + // files, so the run reads as its flow's absence — never as + // another package's flow of that name. + return this.flowSlots.keysOf(flowName).length > 0 ? qualifiedFlowKey(flowPackage, flowName) : flowName; + }, + }); + } + + /** The body of `AutomationEngine#missedRunLimit`; the method's docblock there is its contract. */ + static missedRunLimit(this: Pick): number | null { + const ledger = this.flowDispatchStore; + if (!ledger || typeof ledger.read !== 'function') return null; + const cap = this.store?.maxTerminalRunsPerFlow; + return typeof cap === 'number' && cap > 0 ? cap : this.maxLogSize; + } + + /** The body of `AutomationEngine#recordMissedRun`; the method's docblock there is its contract. */ + static async recordMissedRun(this: Pick, missed: MissedScheduledRun): Promise { + const store = this.flowDispatchStore; + if (!store || typeof store.read !== 'function') return 'unverifiable'; + try { + if (await store.read(missed.dispatchKey)) return 'dispatched'; + // [ADR-0150 D8 row R10] The transition read: the same window + // claimed under its bare-shape key by a node of the previous release. + if (missed.legacyDispatchKey && missed.legacyDispatchKey !== missed.dispatchKey + && await store.read(missed.legacyDispatchKey)) return 'dispatched'; + } catch (err) { + this.logger.warn( + `[automation] missed-run check for flow '${missed.flowName}' due ${missed.dueAt} could not read ` + + `the dispatch ledger — NOT recording it as missed, since an unread claim may be a run that ` + + `landed. The store failure is in this record's meta.`, + describeThrownForLog(err), + ); + return 'unverifiable'; + } + const context: AutomationContext = { + event: 'schedule', + ...(missed.organization ? { tenantId: missed.organization } : {}), + }; + this.recordLog( + { + id: missedRunId(missed.flowName, missed.dueAt), + flowName: missed.flowName, + flowVersion: this.flows.get(missed.flowName)?.version, + status: 'missed', + startedAt: missed.dueAt, + completedAt: missed.detectedAt, + trigger: buildRunTrigger(context), + steps: [], + }, + context, + ); + return 'recorded'; + } + + /** Note that `runId` was started for the caller's `context` ({@link runsStartedByContext}). */ + static noteRunStarted(this: Pick, context: AutomationContext | undefined, runId: string): void { + if (context && typeof context === 'object') this.runsStartedByContext.set(context, runId); + } +} diff --git a/packages/services/service-automation/src/engine-enablement-facet.ts b/packages/services/service-automation/src/engine-enablement-facet.ts new file mode 100644 index 00000000000..a384069afe8 --- /dev/null +++ b/packages/services/service-automation/src/engine-enablement-facet.ts @@ -0,0 +1,410 @@ +// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#38667] Enablement: whether a flow is on, the subflow guards that decline a caller onto a disabled or suspending subflow, toggling, version history and rollback: the bodies of + * `isFlowEnabled`, `describeDisabledFlow`, `subflowTargets`, + * `resolvedFlowCallKey`, `declineOntoDisabledSubflows`, + * `declineOntoSuspendingSubflowNotice`, `declineOntoRegionSuspendingCall`, + * `declineOntoSubflowRetriedCallout`, `toggleFlow`, `toggleFlowSlot`, + * `getFlowVersionHistory`, `rollbackFlow` + * moved out of `engine.ts` whole. + * + * A MOVE, not a redesign. {@link EnablementFacet} is a stateless facet of + * `AutomationEngine`: each static method of it is the body of the + * `AutomationEngine` method of the same name exactly as it stood, not + * re-indented, not formatted, not edited, with a `this` parameter added when + * the body reads the engine. The method stays on the class as a one-call stub + * with its signature, so the published declaration, an instance spy and a + * subclass override are what they were. A public method keeps its docblock on + * the class, the contract; a private method's docblock moved here with its + * body. The state stays on `AutomationEngine`. + * + * The bodies reach the engine through {@link EnablementHost}: exactly the + * `AutomationEngine` members they read, private ones included. Every stub + * hands its body, by a `.call`, the same host: `enablementHost` in + * `engine-facet-hosts.ts`, built once per engine by the class's static block. + * Methods go as closures that call them on the engine at call time, so a spy + * or a subclass override is still the one reached; fields go as getters, read + * when the body reads them, and a field a body assigns also goes with a setter + * that assigns it on the engine. + * + * The module imports `engine.ts` for types only, so the two modules form no + * evaluation cycle. `index.ts` re-exports nothing from this module. + */ + +import type { FlowParsed } from '@objectstack/spec/automation'; +import type { AutomationContext } from '@objectstack/spec/contracts'; +import { rollbackFlow } from './flow-definitions.js'; +import { describeDisabledFlow, subflowTargets } from './subflow-guards.js'; +import { describeSubflowNoticeTrap, subflowNoticeTrap } from './subflow-notice-guard.js'; +import { isSlotKeySpelling, unfiledFlowKey } from './flow-slots.js'; +import { describeRegionSuspendingCall, regionSuspendingCall } from './subflow-region-guard.js'; +import { describeSubflowRetriedCallout, subflowRetriedCallout } from './subflow-retry-guard.js'; +import type { AutomationEngine } from './engine.js'; + +/** + * The `AutomationEngine` members the bodies of {@link EnablementFacet} read — every one + * of them, and no other. Each is typed AS the class member (an indexed access + * on the class), so a change to a member's signature on the class is a change + * here too. `readonly` members are the getters; the others are fields a body + * assigns. + */ +export interface EnablementHost { + readonly bareFlowKey: AutomationEngine['bareFlowKey']; + readonly describeDisabledSubflows: AutomationEngine['describeDisabledSubflows']; + readonly disabledPackagedSubflows: AutomationEngine['disabledPackagedSubflows']; + readonly flowArms: AutomationEngine['flowArms']; + readonly flowCallKey: AutomationEngine['flowCallKey']; + readonly flowLedgerDisabled: AutomationEngine['flowLedgerDisabled']; + readonly flowSlots: AutomationEngine['flowSlots']; + readonly flowStatusDisabled: AutomationEngine['flowStatusDisabled']; + readonly flowVersionHistory: AutomationEngine['flowVersionHistory']; + readonly flows: AutomationEngine['flows']; + readonly isPackagedFlow: AutomationEngine['isPackagedFlow']; + readonly logger: AutomationEngine['logger']; + readonly resolveFlowKey: AutomationEngine['resolveFlowKey']; + readonly resolvedFlowCallKey: AutomationEngine['resolvedFlowCallKey']; + readonly servedBareFlowKey: AutomationEngine['servedBareFlowKey']; + readonly subflowDeclinedFlows: AutomationEngine['subflowDeclinedFlows']; + readonly subflowNoticeDeclinedFlows: AutomationEngine['subflowNoticeDeclinedFlows']; + readonly subflowRegionDeclinedFlows: AutomationEngine['subflowRegionDeclinedFlows']; + readonly subflowRetryDeclinedFlows: AutomationEngine['subflowRetryDeclinedFlows']; + readonly toggleFlowKey: AutomationEngine['toggleFlowKey']; +} + +/** The bodies of the "Enablement" members of `AutomationEngine`: a stateless facet, called by the class's stubs. */ +export class EnablementFacet { + /** + * Is this flow allowed to run — the composition of the two INDEPENDENT + * disable dimensions. + * + * `flowStatusDisabled` is the authoring state (`obsolete` / `invalid`), + * owned by the definition. `flowLedgerDisabled` is the installation's + * activation choice (ADR-0126 §4), owned by `sys_metadata_activation`; + * with no row deciding, it is the package's default, which a packaged + * flow may declare off (`defaultActive: false`, #34655). + * Either one disarms; neither can override the other, because they answer + * different questions and an "override" would mean one silently undoing a + * decision it does not own. + */ + static isFlowEnabled(this: Pick, name: string): boolean { + return this.flowStatusDisabled.get(name) !== true && !this.flowLedgerDisabled.has(name); + } + + /** + * The `FLOW_DISABLED` refusal MESSAGE, which is where the ledger-vs-status + * distinction rides (ADR-0126 §7.2 reuses the CODE deliberately, so the + * message is the only channel left). + * + * [#27966] The ledger sentence is written for the caller, in the shape + * the switched-off action refusal reads as (`describeTurnedOffPackagedItem`, + * `@objectstack/types`), so it names no table and no ADR. Those, with the + * code and the flow's name, go to the log line written here: both refusal + * exits ask for this message exactly when they refuse, so this is the one + * place every ledger refusal passes that holds the logger. It is `info`, + * not `warn`: the refusal is handed to the caller, and nothing is degraded + * (AGENTS.md "Degradation log levels"). + */ + static describeDisabledFlow(this: Pick, flowName: string): string { + if (this.flowLedgerDisabled.offByDefault(flowName)) { + // [#34655] No row: the package ships it off and no administrator + // has switched it on here. + this.logger.info( + `FLOW_DISABLED: packaged flow '${flowName}' refused — its package ships it switched off ` + + '(defaultActive: false) and the activation ledger (sys_metadata_activation) holds no row ' + + 'switching it on.', + { flow: flowName, refusal: 'FLOW_DISABLED' }, + ); + } else if (this.flowLedgerDisabled.has(flowName)) { + this.logger.info( + `FLOW_DISABLED: packaged flow '${flowName}' refused — it is switched off in the activation ledger ` + + '(sys_metadata_activation, ADR-0126 §7.2).', + { flow: flowName, refusal: 'FLOW_DISABLED' }, + ); + } + // The body lives in ./subflow-guards.ts (#25222). + const host: ThisParameterType = { + flowLedgerDisabled: this.flowLedgerDisabled, + }; + return describeDisabledFlow.call(host, flowName); + } + + /** + * [ADR-0126 §7.3] The flow names `flow` invokes as a subflow — the ONE + * reading of "flow A calls flow B" that both directions of the subflow + * guard share ({@link packagedSubflowCallers} on disable, + * {@link disabledPackagedSubflows} on enable), so the two can never + * disagree about which pairs exist. + * + * A DEFINITION SCAN — ⛔ deliberately not an index. ADR-0126 §9 records + * that no reference index exists and that building one is not chartered + * (#11665 §3.2); the flow map is small, the guard runs once per flip, and + * an index would be a durable structure to keep correct forever for a + * check that happens when an administrator clicks a switch. + * + * Two node types invoke another flow by name, and BOTH count: `subflow` + * (config.flowName) and `map`, whose own descriptor calls its per-item + * target "the per-item subflow" and reaches it through the same + * `engine.execute`. Scanning only `subflow` would let a `map` caller break + * exactly the way §7.3 exists to prevent. + * + * [#28846] At EVERY region depth: a `subflow` / `map` node inside a + * `loop` body, a `parallel` branch or a `try_catch` slot calls its child + * on each pass exactly as a top-level one does, so a guard that read only + * the top-level `nodes` armed a caller onto a disabled child and let that + * child be switched off under it. The regions are read through + * `collectFlowGraphs`, the spec's one region walk, never a second walker. + * + * [#28897] That reading is `subflowCalls` (`subflow-region-guard.ts`), + * which also keeps each call's node and the container holding it: the + * arming gate's region half ({@link declineOntoRegionSuspendingCall}) + * reads the same calls, never a walk of its own. + * + * ⛔ The historical `flow` alias for `config.flowName` is NOT read here. + * ADR-0087 D2's conversion `flow-node-subflow-flow-alias` canonicalizes it + * at load, so only the canonical key reaches a registered definition; + * re-reading the alias in this consumer would be a tolerant fallback + * papering over a producer that is already correct. + */ + static subflowTargets(this: Pick, flow: FlowParsed): string[] { + // The body lives in ./subflow-guards.ts (#25222). + const targets = subflowTargets(flow); + // [ADR-0150 D3/D4, #31696] A name two slots hold is the slot the + // calling flow's package resolves it to — what its run dispatches. + if (!targets.some((target) => this.flowSlots.isShared(target) || isSlotKeySpelling(target))) return targets; + const arm = this.flowArms.get(flow); + const caller = arm?.source === 'package' ? (arm.holder ?? arm.packageId ?? null) : null; + return targets.map((target) => (this.flowSlots.isShared(target) || isSlotKeySpelling(target) ? this.resolvedFlowCallKey(target, caller) : target)); + } + + /** + * [ADR-0150 D3/D4, #31696] The key the bare `name` a `subflow` / `map` + * node calls resolves to from `callerPackageId`; the name itself, which + * no slot files, when it is refused — read as an absent child, the way a + * run's node reads the refusal. + */ + static resolvedFlowCallKey(this: Pick, name: string, callerPackageId: string | null): string { + // [#33386] Over every holder: the guards record an arming verdict. + const resolved = this.resolveFlowKey(name, callerPackageId, { durable: true }); + return 'key' in resolved ? resolved.key : unfiledFlowKey(name); + } + + /** + * [#20725, ADR-0126 §7.3] The arming gate's subflow half, asked by + * {@link activateFlowTrigger} of an ENABLED flow it is about to arm: is it + * a packaged caller of a packaged subflow that is disabled? Then it is + * declined — recorded on {@link subflowDeclinedFlows} for `/_status` and + * the binding audit, and said once as a `warn` naming each subflow and the + * step that re-arms it. + * + * "Disabled" is {@link disabledPackagedSubflows}, the SAME reading the + * enable refusal takes — ⛔ no second reading of "A calls B": a `subflow` + * or `map` target that is ledger-disabled OR status-disabled, the child + * and the caller both packaged. Its cycle exemption never applies here, + * because the flow being armed is enabled (see that method). + * + * #4632 verdict: FUNCTIONAL — `warn`. A flow is visibly smaller than + * declared (its trigger is not armed), `/_status` reports it `bound: false` + * with this reason, and nothing claimed-persisted is lost. Said once per + * decline: a re-registration that declines the flow for the same subflows + * (a hot reload, the kernel:ready re-bind) records it without repeating it. + * + * @returns `true` when the flow is declined and must not be armed. + */ + static declineOntoDisabledSubflows(this: Pick, flowName: string, triggerType: string): boolean { + const flow = this.flows.get(flowName); + const disabled = flow && this.isPackagedFlow(flowName) + ? this.disabledPackagedSubflows(flowName) + : []; + if (disabled.length === 0) { + this.subflowDeclinedFlows.delete(flowName); + return false; + } + const { reasons, remedy } = this.describeDisabledSubflows(disabled, 'the activation switch'); + const many = disabled.length !== 1; + const reason = + `not armed while the packaged subflow${many ? 's' : ''} it calls ${many ? 'are' : 'is'} disabled — ` + + `${reasons.join(', ')}; ${remedy} and it is armed (ADR-0126 §7.3)`; + const previous = this.subflowDeclinedFlows.get(flowName); + this.subflowDeclinedFlows.set(flowName, reason); + if (previous === reason) return true; + this.logger.warn( + `Flow '${flowName}' is registered but NOT armed on trigger '${triggerType}' — ${disabled.length} packaged ` + + `subflow${many ? 's' : ''} it calls ${many ? 'are' : 'is'} disabled: ${reasons.join(', ')}. Armed, it ` + + `would fail at its subflow node on a disabled child — the late, inexplicable failure ADR-0126 §7.3 ` + + `refuses to cause. It is armed the moment ${many ? 'they are' : 'that subflow is'} enabled: ` + + `${remedy}.`, + ); + return true; + } + + /** + * [#28840] The arming gate's save-notice half, asked by + * {@link activateFlowTrigger} of an enabled flow it is about to arm: does a + * `save_notice` of it run after a `subflow` / `map` node whose child flow + * can suspend ({@link subflowNoticeTrap}: a pausing node reachable from the + * child's start, or a child of the child that can suspend, transitively)? + * Then it is declined: recorded on {@link subflowNoticeDeclinedFlows} for + * `/_status` and the binding audit, and said once as a `warn` naming the + * notice, the call node and where the child suspends. + * + * Any flow, packaged or authored here: the stranded decision is the same. + * ⛔ A decline, never a refusal, for {@link declineOntoDisabledSubflows}'s + * reason and one of its own: which flows suspend depends on what else is + * registered, so `registerFlow` cannot refuse it without depending on load + * order. + * + * #4632 verdict: FUNCTIONAL, `warn`, as the disabled-subflow decline: the + * flow is visibly smaller than declared and `/_status` says why. Said once + * per decline reason. + * + * @returns `true` when the flow is declined and must not be armed. + */ + static declineOntoSuspendingSubflowNotice(this: Pick, flowName: string, triggerType: string): boolean { + const trap = subflowNoticeTrap(this.flows, flowName, this.flowCallKey); + if (!trap) { + this.subflowNoticeDeclinedFlows.delete(flowName); + return false; + } + const why = describeSubflowNoticeTrap(trap); + const reason = + `not armed — ${why}, and it is armed; it is also armed once '${trap.child}' is republished without a ` + + `node that suspends`; + const previous = this.subflowNoticeDeclinedFlows.get(flowName); + this.subflowNoticeDeclinedFlows.set(flowName, reason); + if (previous === reason) return true; + this.logger.warn( + `Flow '${flowName}' is registered but NOT armed on trigger '${triggerType}' — ${why}. It is armed the ` + + `moment the \`save_notice\` moves, or '${trap.child}' is republished without a node that suspends.`, + ); + return true; + } + + /** + * [#28897] The arming gate's region half, asked by + * {@link activateFlowTrigger} of an enabled flow it is about to arm: does a + * `subflow` / `map` node inside one of its region bodies (a `loop` body, a + * `parallel` branch, a `try_catch` slot, at any depth) call a child flow + * that can suspend ({@link regionSuspendingCall}, which reads the calls + * through {@link subflowTargets}' reading and where the child suspends + * through the save-notice half's)? A region body cannot carry a durable + * pause, so that run would fail at the region boundary the first time the + * child suspends (`region-suspension-refusal.ts`). Then it is declined: + * recorded on {@link subflowRegionDeclinedFlows} for `/_status` and the + * binding audit, and said once as a `warn` naming the region node, the call + * node and where the child suspends. + * + * Any flow, packaged or authored here, as the save-notice half: the failed + * run is the same. ⛔ A decline, never a refusal, for that half's reasons. + * + * #4632 verdict: FUNCTIONAL, `warn`, as the other halves. Said once per + * decline reason. + * + * @returns `true` when the flow is declined and must not be armed. + */ + static declineOntoRegionSuspendingCall(this: Pick, flowName: string, triggerType: string): boolean { + const trap = regionSuspendingCall(this.flows, flowName, this.flowCallKey); + if (!trap) { + this.subflowRegionDeclinedFlows.delete(flowName); + return false; + } + const why = describeRegionSuspendingCall(trap); + const reason = + `not armed — ${why}, and it is armed; it is also armed once '${trap.child}' is republished without a ` + + `node that suspends`; + const previous = this.subflowRegionDeclinedFlows.get(flowName); + this.subflowRegionDeclinedFlows.set(flowName, reason); + if (previous === reason) return true; + this.logger.warn( + `Flow '${flowName}' is registered but NOT armed on trigger '${triggerType}' — ${why}. It is armed the ` + + `moment '${trap.callNode.id}' moves, or '${trap.child}' is republished without a node that suspends.`, + ); + return true; + } + + /** + * The arming gate's subflow-retry half, asked by + * {@link activateFlowTrigger} of an enabled flow it is about to arm: does + * it run after a record change and reach, through a `subflow` / `map` node + * (top-level or in a region body), an inline outbound call that something + * on the call chain retries ({@link subflowRetriedCallout})? The save waits + * for the run and the run waits for its child, so a failing call would + * hold the user's save for the whole backoff ladder (ruling 6810500711, + * letter D). Then it is declined: recorded on + * {@link subflowRetryDeclinedFlows} for `/_status` and the binding audit, + * and said once as a `warn` naming the call node, the retried call and + * what retries it. + * + * ⛔ A decline, never a refusal, for the other halves' reasons: the child + * may register after this flow, so `registerFlow` cannot refuse it without + * depending on load order. The after-save judge refuses the same shape in + * the flow's own graph at registration, where no other flow is read. + * + * #4632 verdict: FUNCTIONAL, `warn`, as the other halves: the flow is + * visibly smaller than declared and `/_status` says why. Said once per + * decline reason. + * + * @returns `true` when the flow is declined and must not be armed. + */ + static declineOntoSubflowRetriedCallout(this: Pick, flowName: string, triggerType: string): boolean { + const trap = subflowRetriedCallout(this.flows, flowName, this.flowCallKey); + if (!trap) { + this.subflowRetryDeclinedFlows.delete(flowName); + return false; + } + const why = describeSubflowRetriedCallout(trap); + const reason = + `not armed — ${why} It is armed once '${trap.callout.flow}' is republished without that retried ` + + `inline call`; + const previous = this.subflowRetryDeclinedFlows.get(flowName); + this.subflowRetryDeclinedFlows.set(flowName, reason); + if (previous === reason) return true; + this.logger.warn( + `Flow '${flowName}' is registered but NOT armed on trigger '${triggerType}' — ${why} It is armed the ` + + `moment '${trap.callout.flow}' is republished without that retried inline call.`, + ); + return true; + } + + /** The body of `AutomationEngine#toggleFlow`; the method's docblock there is its contract. */ + static toggleFlow(this: Pick, name: string, enabled: boolean, caller?: Pick): Promise { + // [#31696] A name two packages hold is refused (409, naming both): + // {@link toggleFlowSlot} switches one package's flow. [#33386] Over + // the served holders: one served holder's flow is switched, none is + // not found ({@link servedBareFlowKey}). + let key: string | undefined; + try { + key = this.servedBareFlowKey(name); + } catch (err) { + return Promise.reject(err); + } + if (key === undefined) return Promise.reject(new Error(`Flow '${name}' not found`)); + return this.toggleFlowKey(key, enabled, caller); + } + + /** The body of `AutomationEngine#toggleFlowSlot`; the method's docblock there is its contract. */ + static toggleFlowSlot(this: Pick, packageId: string, name: string, enabled: boolean, caller?: Pick): Promise { + const key = this.flowSlots.keyOf(name, packageId); + if (key === undefined) return Promise.reject(new Error(`Flow '${name}' of package '${packageId}' not found`)); + return this.toggleFlowKey(key, enabled, caller); + } + + /** The body of `AutomationEngine#getFlowVersionHistory`; the method's docblock there is its contract. */ + static getFlowVersionHistory(this: Pick, name: string): Array<{ version: number; definition: FlowParsed; createdAt: string }> { + const key = this.bareFlowKey(name); + return key === undefined ? [] : this.flowVersionHistory.get(key) ?? []; + } + + /** The body of `AutomationEngine#rollbackFlow`; the method's docblock there is its contract. */ + static rollbackFlow(this: Pick, name: string, version: number): void { + // The body lives in ./flow-definitions.ts (#25222). + const host: ThisParameterType = { + flowVersionHistory: this.flowVersionHistory, + flows: this.flows, + logger: this.logger, + }; + const key = this.bareFlowKey(name); + if (key === undefined) throw new Error(`Flow '${name}' has no version history`); + rollbackFlow.call(host, key, version); + } +} diff --git a/packages/services/service-automation/src/engine-extensions-facet.ts b/packages/services/service-automation/src/engine-extensions-facet.ts new file mode 100644 index 00000000000..dd9cf298a3c --- /dev/null +++ b/packages/services/service-automation/src/engine-extensions-facet.ts @@ -0,0 +1,686 @@ +// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#38667] The Plugin Extension API: trigger bindings and activation, connectors and their providers, the resolvers a host attaches, and the node-type vocabulary: the bodies of + * `resolveTriggerBinding`, `activateFlowTrigger`, `triggerRun`, + * `deactivateFlowTrigger`, `getActiveTriggerBindings`, + * `assertSameOriginOrFree`, `connectorInstance`, `resolveConnectorAction`, + * `resolveConnectorActionInputSchema`, `resolveConnectorActionEffect`, + * `organizationLocale`, `getConnectorOrigin`, `getConnectorDegradedReason`, + * `getConnectorDegradedHold`, `registerConnectorProvider`, + * `unregisterConnectorProvider`, `getRegisteredConnectorProviders`, + * `getConnectorDescriptors`, `getRegisteredNodeTypes`, `getActionDescriptors`, + * `getRegisteredTriggerTypes`, `knownNodeTypes`, `getUnknownNodeTypeAudit`, + * `sealNodeTypeVocabulary`, `getSealedNodeTypeVocabulary`, + * `warnUnknownNodeTypes` + * moved out of `engine.ts` whole. + * + * A MOVE, not a redesign. {@link ExtensionsFacet} is a stateless facet of + * `AutomationEngine`: each static method of it is the body of the + * `AutomationEngine` method of the same name exactly as it stood, not + * re-indented, not formatted, not edited, with a `this` parameter added when + * the body reads the engine. The method stays on the class as a one-call stub + * with its signature, so the published declaration, an instance spy and a + * subclass override are what they were. A public method keeps its docblock on + * the class, the contract; a private method's docblock moved here with its + * body. The state stays on `AutomationEngine`. + * + * The bodies reach the engine through {@link ExtensionsHost}: exactly the + * `AutomationEngine` members they read, private ones included. Every stub + * hands its body, by a `.call`, the same host: `extensionsHost` in + * `engine-facet-hosts.ts`, built once per engine by the class's static block. + * Methods go as closures that call them on the engine at call time, so a spy + * or a subclass override is still the one reached; fields go as getters, read + * when the body reads them, and a field a body assigns also goes with a setter + * that assigns it on the engine. + * + * The module imports `engine.ts` for types only, so the two modules form no + * evaluation cycle. `index.ts` re-exports nothing from this module. + */ + +import { type ActionDescriptor, FLOW_STRUCTURAL_NODE_TYPES } from '@objectstack/spec/automation'; +import type { AutomationContext, AutomationResult } from '@objectstack/spec/contracts'; +import { scheduledWorkDisabledReason } from '@objectstack/types'; +import type { + ConnectorActionEffect, + ConnectorProviderFactory, + ConnectorOrigin, + ConnectorDescriptor, +} from '@objectstack/spec/integration'; +import { describeThrownForLog } from './thrown-cause-diagnostics.js'; +import { assertSameOriginOrFree } from './plugin-extension-api.js'; +import { registerConnectorProvider, unregisterConnectorProvider } from './flow-definitions.js'; +import { isSlotKeySpelling, qualifiedFlowKey } from './flow-slots.js'; +import type { + FlowTriggerBinding, + ConnectorActionHandler, + RegisteredConnector, + ConnectorHold, +} from './engine-extension-contracts.js'; +import type { UnknownNodeTypeAuditEntry } from './engine-run-log.js'; +import { isTimeTriggeredKind } from './engine-registration.js'; +import type { AutomationEngine } from './engine.js'; + +/** + * The `AutomationEngine` members the bodies of {@link ExtensionsFacet} read — every one + * of them, and no other. Each is typed AS the class member (an indexed access + * on the class), so a change to a member's signature on the class is a change + * here too. `readonly` members are the getters; the others are fields a body + * assigns. + */ +export interface ExtensionsHost { + readonly actionDescriptors: AutomationEngine['actionDescriptors']; + readonly boundFlowTriggers: AutomationEngine['boundFlowTriggers']; + readonly connectorInstance: AutomationEngine['connectorInstance']; + readonly connectorProviders: AutomationEngine['connectorProviders']; + readonly connectors: AutomationEngine['connectors']; + readonly credentialHandleProviders: AutomationEngine['credentialHandleProviders']; + readonly declineOntoDisabledSubflows: AutomationEngine['declineOntoDisabledSubflows']; + readonly declineOntoRegionSuspendingCall: AutomationEngine['declineOntoRegionSuspendingCall']; + readonly declineOntoSubflowRetriedCallout: AutomationEngine['declineOntoSubflowRetriedCallout']; + readonly declineOntoSuspendingSubflowNotice: AutomationEngine['declineOntoSuspendingSubflowNotice']; + readonly deriveTriggerBinding: AutomationEngine['deriveTriggerBinding']; + readonly disabledHolderDispatchSaid: AutomationEngine['disabledHolderDispatchSaid']; + readonly execute: AutomationEngine['execute']; + readonly executeKey: AutomationEngine['executeKey']; + readonly flowKeyNow: AutomationEngine['flowKeyNow']; + readonly flowRefusals: AutomationEngine['flowRefusals']; + readonly flowSlotName: AutomationEngine['flowSlotName']; + readonly flowSlots: AutomationEngine['flowSlots']; + readonly flows: AutomationEngine['flows']; + readonly getUnknownNodeTypeAudit: AutomationEngine['getUnknownNodeTypeAudit']; + readonly isDisabledHolderSlot: AutomationEngine['isDisabledHolderSlot']; + readonly isFlowEnabled: AutomationEngine['isFlowEnabled']; + readonly knownNodeTypes: AutomationEngine['knownNodeTypes']; + readonly logger: AutomationEngine['logger']; + readonly loneSharedFlowKey: AutomationEngine['loneSharedFlowKey']; + readonly nodeExecutors: AutomationEngine['nodeExecutors']; + nodeTypeVocabularySealed: AutomationEngine['nodeTypeVocabularySealed']; + readonly organizationLocaleResolver: AutomationEngine['organizationLocaleResolver']; + readonly policyDisabledFlows: AutomationEngine['policyDisabledFlows']; + readonly readScheduledWorkPolicy: AutomationEngine['readScheduledWorkPolicy']; + readonly resolveTriggerBinding: AutomationEngine['resolveTriggerBinding']; + readonly settleFlowName: AutomationEngine['settleFlowName']; + readonly sharedSlotTriggerWarned: AutomationEngine['sharedSlotTriggerWarned']; + readonly triggerRun: AutomationEngine['triggerRun']; + readonly triggers: AutomationEngine['triggers']; + readonly unknownNodeTypes: AutomationEngine['unknownNodeTypes']; + readonly warnUnknownNodeTypes: AutomationEngine['warnUnknownNodeTypes']; +} + +/** The bodies of the "The Plugin Extension API" members of `AutomationEngine`: a stateless facet, called by the class's stubs. */ +export class ExtensionsFacet { + /** + * Derive a flow's trigger binding from its `start` node, or `undefined` if + * the flow has no auto-trigger (manual / screen). The convention — + * established by the showcase flows — is that the start node carries the + * trigger details in its `config`: `{ objectName, triggerType, condition }` + * for record-change, or a `schedule` descriptor for time-based flows. + * + * [#14328] WHICH KIND a flow asks for is not decided here: it is + * {@link resolveFlowTriggerKind}'s answer, the one `@objectstack/spec` + * export that `defineStack`'s trigger-capability refusal and + * `@objectstack/lint`'s `validate-flow-trigger-readiness` already read. + * This method keeps only the per-kind BINDING construction — which start-node + * fields each trigger needs. Before #14328 the chain was hand-kept here in + * parallel with the spec one, and nothing pinned them together: a branch + * added on one side left `defineStack` accepting a stack the runtime leaves + * inert, or refusing one it would arm. Now `getTriggerBindingAudit` and the + * boot banner name the kind authoring named, by construction. + */ + static resolveTriggerBinding( + this: Pick, + flowName: string, + ): { triggerType: string; binding: FlowTriggerBinding } | undefined { + const flow = this.flows.get(flowName); + if (!flow) return undefined; + return this.deriveTriggerBinding(flowName, flow); + } + + /** + * Bind a flow to its matching registered trigger (idempotent). No-op when + * the flow may not run ({@link isFlowEnabled}), when it has no trigger + * binding, or when no trigger is registered for its type yet — + * {@link registerTrigger} re-attempts activation when one arrives. + */ + static activateFlowTrigger(this: Pick, flowName: string): void { + if (this.boundFlowTriggers.has(flowName)) return; + // [ADR-0126 §7.2] THE enablement gate for arming — here, at the one + // point every arming path crosses, and not in its callers. A flow + // either disable dimension switches off (the activation ledger, or an + // `obsolete` / `invalid` status) is never handed to a trigger, whichever + // path asks: {@link registerFlow} (boot pull, publish, hot reload), + // {@link registerTrigger}, the enable half of {@link toggleFlow}, and + // any path added later. + // + // Why it cannot live in the callers: `registerTrigger` runs when a + // trigger plugin registers at `kernel:ready`, AFTER `start()` pulled + // the flows and {@link hydrateFlowActivations} unbound the switched-off + // ones. While only `registerFlow` asked, that later registration + // re-armed every one of them on every cold boot — `/_status` reported a + // disabled flow `bound: true`, and each matching event fired a run + // `execute()` then refused. + // + // Silent on purpose: an unarmed disabled flow is the state the switch + // exists to produce, the host's hydration line already named it, and + // `getFlowRuntimeStates()` reports it `enabled: false`. Ahead of the + // scheduled-work policy gate below for the same reason — a flow that + // may not run has no policy refusal to record. + if (!this.isFlowEnabled(flowName)) return; + const resolved = this.resolveTriggerBinding(flowName); + if (!resolved) return; + // [ADR-0150 D4, #31696] A trigger binds a slot by its key and fires + // that slot ({@link triggerRun}). The one slot of a name the registry + // holds under two packages (the other's body refused, M1) still holds + // the bare key, which would read as the name's one holder: it is not + // armed, behind this warning, and runs when called by its package. + // [#33893] Both served ({@link loneSharedFlowKey}): beside a disabled + // co-holder the slot is the name's one served holder, filed under its + // qualified key, and is armed; the warning names no refused body. + // Filed under its qualified key, it is declined only once another + // package's body of the name was refused (recorded): a co-holder the + // re-sync has not registered yet is no refusal. + const slotName = this.flowSlotName(flowName); + if (this.loneSharedFlowKey(slotName) === flowName && (flowName === slotName || this.flowRefusals.has(slotName))) { + if (!this.sharedSlotTriggerWarned.has(flowName)) { + this.sharedSlotTriggerWarned.add(flowName); + this.logger.warn( + `Flow '${flowName}' is registered but NOT armed on trigger '${resolved.triggerType}' — another ` + + `package holds a flow named '${this.flowSlotName(flowName)}' whose body was refused, so this ` + + 'flow holds the bare name it cannot be addressed by. It runs when called by its package.', + { flow: this.flowSlotName(flowName), slot: flowName, triggerType: resolved.triggerType }, + ); + } + return; + } + // [#17396] The deployment gate, read HERE rather than only inside the + // trigger. The trigger has its own copy of this gate and throws, which + // is what protects a host that binds without this engine — but a + // refusal that arrives as a THROW can only be reported through this + // method's catch, and that catch says "Failed to bind", which is the + // one thing ruled item 6 forbids this state from reading as. Asking the + // policy before `start()` keeps the two apart at the source: nothing is + // called, nothing throws, nothing is logged as a failure. + // + // ⚠️ AHEAD of the trigger lookup, deliberately. With the switch off, + // registering the missing trigger would change nothing, so reporting + // "no 'schedule' trigger is registered — add requires: ['triggers']" + // hands the operator a remedy that cannot work. The switch outranks it + // because it is the fact that decides the outcome. + // + // ⛔ The POLICY is not cached — the resolver reads `process.env` live, + // so a host that rebinds after changing the environment (the CLI's + // `--fresh` harness, a test flipping the switch between kernels in one + // process) sees the value current at the bind. [#19834] A per-kernel + // `scheduledWorkPolicy` option replaces that read for this engine only; + // a resolver given there is likewise called at each bind. What IS recorded is the + // REFUSAL, on {@link policyDisabledFlows}, and that is the difference + // between the two: see its own docblock for why the audit must read + // what happened rather than re-derive it from an environment that may + // have moved since. + // + // The policy is read only for a time-triggered kind, as before: a + // record-change or api flow never asks it. + const policy = isTimeTriggeredKind(resolved.triggerType) ? this.readScheduledWorkPolicy() : undefined; + if (policy !== undefined && !policy.enabled) { + // [#21110] The sentence comes from the SAME reading that refused — + // the host's own reason when its per-kernel policy carries one, else + // the deployment sentence — and the bind log, the audit and the + // `/_status` row all read this one recorded value. + const reason = scheduledWorkDisabledReason(policy); + if (this.policyDisabledFlows.get(flowName) !== reason) { + this.policyDisabledFlows.set(flowName, reason); + // Said once per flow while it stays refused for the same + // reason, at `info`, for the reason the trigger's own refusal + // records: this is the DEFAULT state of every deployment and the + // deployment declared it, so nothing is wrong and nothing looks + // normal-but-broken. The structured channel is the audit below, + // which the `kernel:bootstrapped` hook and the CLI startup + // summary read. + this.logger.info( + `Flow '${flowName}' is not armed on trigger '${resolved.triggerType}' — ${reason}`, + ); + } + // [#25235] A refusal on purpose disarms what a previous kernel left + // armed — see {@link FlowTrigger.release}. On every pass, not once: + // the trigger may register after the flow, and a cancel by name of + // an already-disarmed job changes nothing. + const refusing = this.triggers.get(resolved.triggerType); + if (refusing && typeof refusing.release === 'function') { + try { + refusing.release(flowName); + } catch (err) { + this.logger.warn( + `Flow '${flowName}' is not armed on trigger '${resolved.triggerType}', and disarming what ` + + `an earlier start left armed for it failed. The failure is in this record's meta.`, + describeThrownForLog(err), + ); + } + } + return; + } + // Past the gate the refusal no longer describes this flow: either it + // binds below, or it fails/waits for its trigger with a reason of its + // own. Cleared BEFORE the trigger lookup so a flow whose trigger has + // not arrived yet is reported as waiting for a trigger, not as + // policy-disabled — with the switch on, the missing trigger really is + // the reason. + this.policyDisabledFlows.delete(flowName); + // [#20725, ADR-0126 §7.3] The subflow half of the same gate: a PACKAGED + // flow is not armed while a packaged subflow it calls is disabled — + // armed, it would fail at its subflow node on the child's refusal, the + // late, inexplicable failure §7.3 exists to prevent. Here rather than + // in the callers for this gate's own reason: every arming path — + // create, republish, upgrade, hot reload, the kernel:ready trigger + // registration, the enable toggle — crosses this line, so none of them + // can arm onto a disabled child and none can forget to ask. + // + // ⛔ A DECLINE, never a refusal: `registerFlow` still registers, so a + // boot or an upgrade never fails on an installation's choice. The flow + // stays unarmed, `/_status` says why ({@link describeUnboundReason}), + // and it is armed the moment its subflow is enabled + // ({@link rejudgeSubflowCallers}). Ahead of the trigger lookup for the + // policy gate's reason: with the child off, registering the missing + // trigger would change nothing, so "no trigger registered" would name + // a remedy that cannot work. + if (this.declineOntoDisabledSubflows(flowName, resolved.triggerType)) return; + // [#28840] The save-notice half, a decline for the same reasons: a + // `save_notice` after a `subflow` / `map` node whose child can suspend + // is refused by name when the suspended run resumes, after the write + // answered, and a decision that resumes it is stranded. The flow parse + // cannot see the child (#28806), which may register after this flow, + // so the gate asks here and {@link rejudgeSubflowCallers} asks again + // when the child arrives or changes. + if (this.declineOntoSuspendingSubflowNotice(flowName, resolved.triggerType)) return; + // [#28897] The region half, a decline for the same reasons: a region + // body cannot carry a durable pause, so a region-nested `subflow` / + // `map` whose child suspends fails the run at the region boundary + // (`region-suspension-refusal.ts`), the first time that child + // suspends. That refusal stays as the second door; this is the first. + // Last of the halves, and {@link describeUnboundReason} reads the + // records in the same order, so a record an earlier half's decline + // left unasked is never the one reported. + if (this.declineOntoRegionSuspendingCall(flowName, resolved.triggerType)) return; + // The subflow-retry half, a decline for the same reasons: an + // after-record-change run waits for its `subflow` / `map` children, so + // an inline outbound call a child retries holds the save through the + // backoff ladder (ruling 6810500711, letter D). The after-save judge + // refuses that shape in the flow's own graph at registration; it cannot + // see the child, which may register after this flow. Last, and + // {@link describeUnboundReason} reads its record last. + if (this.declineOntoSubflowRetriedCallout(flowName, resolved.triggerType)) return; + const trigger = this.triggers.get(resolved.triggerType); + if (!trigger) return; + try { + // A trigger-fired run's result must not vanish (2026-07-17 eval: + // a failing record-change flow produced zero output — the failure + // lived only in the run-history row). Condition-skipped runs stay + // quiet (execute() already debug-logs them — they are high-frequency). + // + // #6587 — `result.error` is the envelope field that carries a + // failing node's / driver's text VERBATIM (#5912 left it that way + // on purpose), so foreign newlines reach this message second-hand; + // it goes to the structured slot — the identical class as + // `bubbleToParent`'s envelope branch, on the fired-run path. See + // `forgetSuspendedRun`'s catch for the full mechanism (#6299). + // + // #4632 verdict: stays `error`, on its own reasoning rather than + // inertia. This is the fire-and-forget path: NO caller holds this + // result envelope, so after the failure the system looks normal + // from the outside — the triggering event was handled and nothing + // retries the run — while the flow's declared effects never + // landed; the only other trace is the passive run-history row. + // That stderr also survives the CLI's boot-quiet stdout window is + // stream mechanics, not the verdict. + // + // [ADR-0126 §7.2] The line states only what happened. Two kinds of + // `execute()` answer are not a failed run: + // - `FLOW_DISABLED`: the flow was switched off after the trigger + // took the event — an event in flight at the switch-off, or a + // trigger whose `stop()` failed. The refusal IS the switch + // working, so it is said at `info`, never as an `error` that + // reads as a production failure. The enablement gate above + // keeps a disabled flow from being armed at all, so this is the + // residue, not the steady state. + // - every other never-dispatched exit (a `code` or a missing + // flow, and no `status`): no node ran, so the line claims no + // run-history row. Only a run that dispatched and failed + // carries `status: 'failed'` — the verdict that exit also wrote + // to the run history. + const run = this.triggerRun(flowName); + trigger.start(resolved.binding, (ctx: AutomationContext) => + run(ctx).then((result) => { + if (result === undefined) return; + if (result.success) return; + if (result.code === 'FLOW_DISABLED') { + this.logger.info( + `Trigger '${resolved.triggerType}' fired flow '${flowName}', which is disabled — the ` + + `run was refused before it started, nothing ran, and no run-history row records ` + + `it. The refusal is in this record's meta.`, + { error: result.error }, + ); + return; + } + this.logger.error( + `Trigger-fired run of flow '${flowName}' failed (trigger '${resolved.triggerType}') — ` + + `no caller holds this result and nothing retries the run; ` + + (result.status === 'failed' + ? `the terminal failure is recorded in the flow's run history, and the run's ` + + `failure envelope is in this record's meta.` + : `it was refused before it dispatched, and the refusal envelope is in this ` + + `record's meta.`), + undefined, + { error: result.error ?? 'unknown error' }, + ); + }), + ); + this.boundFlowTriggers.set(flowName, resolved.triggerType); + this.logger.info(`Flow '${flowName}' bound to trigger '${resolved.triggerType}'`); + } catch (err) { + // #6499 — plugin-supplied thrown text (`FlowTrigger.start`) to the + // structured slot; see `forgetSuspendedRun`'s catch above for the + // full mechanism (#6299). + // + // #4632 verdict: FUNCTIONAL — stays `warn`: "a trigger is not + // armed" is the rule's own canonical `warn` example. The flow is + // visibly smaller than declared (its runs never appear), and the + // kernel:bootstrapped binding audit re-reports every unbound + // triggered flow. + this.logger.warn( + `Failed to bind flow '${flowName}' to trigger '${resolved.triggerType}' — the flow stays ` + + `registered but will NOT fire on this trigger until the flow or the trigger is ` + + `re-registered. The trigger's own failure is in this record's meta.`, + describeThrownForLog(err), + ); + } + } + + /** + * [ADR-0150 D4, #31696] The run a trigger armed under `armedKey` fires: + * the slot it armed, at whatever key the slot holds now, never the bare + * name re-resolved. A slot whose key moved and whose old binding was + * released (an event the trigger took before the release landed) fires + * nothing (`undefined`): the binding under its new key fires it once. A + * slot of an unshared name runs through {@link execute}, as before. + * + * [ADR-0150 D3, #33748; seat ruling 6884403301, amendment 3] A slot whose + * package is disabled is not dispatched: no flow, no run, never another + * slot's. Asked when the trigger fires, not when it was armed: a runtime + * disable leaves the slot armed (a disable is reversible and moves no key, + * amendment 7), so the slot dispatches again the moment its package is + * enabled, with no re-arm. [#33905] The same for the slot of a name one + * package holds (ADR-0150 D3: a disabled package holds no name), which the + * re-sync of the disable withdraws on the normal path; a package-less slot + * is no package's, and runs as before. + */ + static triggerRun(this: Pick, armedKey: string): (ctx: AutomationContext) => Promise { + const slot = this.flowSlots.slot(armedKey); + return async (ctx) => { + let key = slot ? this.flowSlots.keyOf(slot.name, slot.packageId) : armedKey; + if (key === undefined && !isSlotKeySpelling(armedKey)) return this.execute(armedKey, ctx); + if (key === undefined || (key !== armedKey && !this.boundFlowTriggers.has(armedKey))) { + this.logger.debug(`Trigger fired flow '${armedKey}' after it moved or left and was released: not run.`); + return undefined; + } + // [#33893] A lone slot left under its qualified key (its disabled + // co-holder since uninstalled) folds back here, and this run goes + // to where it lands. + if (slot && this.settleFlowName(slot.name)) key = this.flowKeyNow(key); + if (slot && slot.packageId !== null) { + const said = qualifiedFlowKey(slot.packageId, slot.name); + if (this.isDisabledHolderSlot(slot.name, slot.packageId)) { + // Said once per slot while its package stays disabled, at + // `info`: the skip IS the package switch working, and + // nothing that claims to be persisted is lost. + if (!this.disabledHolderDispatchSaid.has(said)) { + this.disabledHolderDispatchSaid.add(said); + this.logger.info( + `Trigger fired flow '${slot.name}' of package '${slot.packageId}', which is disabled — ` + + 'the flow was not run, no other package\'s flow of the name was run in its place, ' + + 'and no run-history row records it. It runs on its trigger again once the package ' + + 'is enabled.', + { flow: slot.name, package: slot.packageId, slot: key }, + ); + } + return undefined; + } + this.disabledHolderDispatchSaid.delete(said); + } + if (!slot || !this.flowSlots.isShared(slot.name)) return this.execute(key, ctx); + // A trigger seeds `params.flowName` with the key it was armed + // under; the run reads its flow's name there, never a slot key. + const params = ctx.params as Record | undefined; + const named = params?.flowName === armedKey && armedKey !== slot.name ? { ...ctx, params: { ...params, flowName: slot.name } } : ctx; + return this.executeKey(key, named, Date.now()); + }; + } + + /** Unbind a flow from its trigger, if bound. */ + static deactivateFlowTrigger(this: Pick, flowName: string): void { + const boundType = this.boundFlowTriggers.get(flowName); + if (!boundType) return; + try { + this.triggers.get(boundType)?.stop(flowName); + } catch (err) { + // #6499 — plugin-supplied thrown text (`FlowTrigger.stop`) to the + // structured slot; see `forgetSuspendedRun`'s catch above for the + // full mechanism (#6299). + // + // #4632 verdict: FUNCTIONAL — stays `warn`, same consequence shape + // as `unregisterTrigger`'s stop above: the binding is dropped + // either way, and a subscription the trigger failed to tear down + // fires into execute()'s own disabled/unregistered-flow guards, + // visibly. + this.logger.warn( + `Trigger '${boundType}' stop('${flowName}') failed while unbinding the flow — the binding is ` + + `dropped anyway; whatever the trigger armed for it may keep firing until the process ` + + `restarts. The trigger's own failure is in this record's meta.`, + describeThrownForLog(err), + ); + } + this.boundFlowTriggers.delete(flowName); + } + + /** The body of `AutomationEngine#getActiveTriggerBindings`; the method's docblock there is its contract. */ + static getActiveTriggerBindings(this: Pick): Array<{ flowName: string; triggerType: string }> { + return [...this.boundFlowTriggers].map(([flowName, triggerType]) => ({ flowName, triggerType })); + } + + /** Enforce the ADR-0097 §4 two-sources-of-truth rule; warn on same-origin replace. */ + static assertSameOriginOrFree(this: Pick, name: string, origin: ConnectorOrigin, packageId?: string | null, soleOfName?: boolean): void { + // The body lives in ./plugin-extension-api.ts (#25222). + const host: ThisParameterType = { + connectors: this.connectors, + logger: this.logger, + }; + assertSameOriginOrFree.call(host, name, origin, packageId ?? null, soleOfName ?? false); + } + + /** + * [#31699] The registered instance `packageId` addresses: exactly that + * package's instance of `name` (`null`: the one of no package), or, with + * `packageId` absent, the one instance of the name, `undefined` when there + * are two (never one of them, ADR-0150 red line 2). + */ + static connectorInstance(this: Pick, name: string, packageId?: string | null): RegisteredConnector | undefined { + return packageId === undefined ? this.connectors.sole(name)?.registered : this.connectors.get(name, packageId); + } + + /** The body of `AutomationEngine#resolveConnectorAction`; the method's docblock there is its contract. */ + static resolveConnectorAction(this: Pick, connectorId: string, actionId: string, packageId?: string | null): ConnectorActionHandler | undefined { + return this.connectorInstance(connectorId, packageId)?.handlers[actionId]; + } + + /** The body of `AutomationEngine#resolveConnectorActionInputSchema`; the method's docblock there is its contract. */ + static resolveConnectorActionInputSchema(this: Pick, connectorId: string, actionId: string, packageId?: string | null): unknown { + return this.connectorInstance(connectorId, packageId)?.def.actions?.find((a) => a.key === actionId)?.inputSchema; + } + + /** The body of `AutomationEngine#resolveConnectorActionEffect`; the method's docblock there is its contract. */ + static resolveConnectorActionEffect(this: Pick, connectorId: string, actionId: string, packageId?: string | null): ConnectorActionEffect | undefined { + return this.connectorInstance(connectorId, packageId)?.def.actions?.find((a) => a.key === actionId)?.effect; + } + + /** The body of `AutomationEngine#organizationLocale`; the method's docblock there is its contract. */ + static async organizationLocale(this: Pick, context: AutomationContext): Promise { + const resolver = this.organizationLocaleResolver; + if (!resolver) return undefined; + const locale = await resolver(context?.tenantId); + return typeof locale === 'string' && locale.trim() !== '' ? locale.trim() : undefined; + } + + /** The body of `AutomationEngine#getConnectorOrigin`; the method's docblock there is its contract. */ + static getConnectorOrigin(this: Pick, name: string, packageId?: string | null): ConnectorOrigin | undefined { + return this.connectorInstance(name, packageId)?.origin; + } + + /** The body of `AutomationEngine#getConnectorDegradedReason`; the method's docblock there is its contract. */ + static getConnectorDegradedReason(this: Pick, name: string, packageId?: string | null): string | undefined { + const reg = this.connectorInstance(name, packageId); + return reg?.state === 'degraded' ? (reg.degradedReason ?? 'upstream unavailable') : undefined; + } + + /** The body of `AutomationEngine#getConnectorDegradedHold`; the method's docblock there is its contract. */ + static getConnectorDegradedHold(this: Pick, name: string, packageId?: string | null): ConnectorHold | undefined { + const reg = this.connectorInstance(name, packageId); + return reg?.state === 'degraded' ? reg.degradedHold : undefined; + } + + /** The body of `AutomationEngine#registerConnectorProvider`; the method's docblock there is its contract. */ + static registerConnectorProvider( + this: Pick, + providerKey: string, + factory: ConnectorProviderFactory, + options?: { readonly credentialHandle?: boolean }, + ): void { + // The body lives in ./flow-definitions.ts (#25222). + const host: ThisParameterType = { + connectorProviders: this.connectorProviders, + logger: this.logger, + }; + registerConnectorProvider.call(host, providerKey, factory); + if (options?.credentialHandle === true) this.credentialHandleProviders.add(providerKey); + else this.credentialHandleProviders.delete(providerKey); + } + + /** The body of `AutomationEngine#unregisterConnectorProvider`; the method's docblock there is its contract. */ + static unregisterConnectorProvider(this: Pick, providerKey: string): void { + // The body lives in ./flow-definitions.ts (#25222). + const host: ThisParameterType = { + connectorProviders: this.connectorProviders, + logger: this.logger, + }; + unregisterConnectorProvider.call(host, providerKey); + this.credentialHandleProviders.delete(providerKey); + } + + /** The body of `AutomationEngine#getRegisteredConnectorProviders`; the method's docblock there is its contract. */ + static getRegisteredConnectorProviders(this: Pick): string[] { + return [...this.connectorProviders.keys()]; + } + + /** The body of `AutomationEngine#getConnectorDescriptors`; the method's docblock there is its contract. */ + static getConnectorDescriptors(this: Pick): ConnectorDescriptor[] { + return this.connectors.entries().map(({ packageId, registered: { def, origin, state, degradedReason } }) => ({ + name: def.name, + // [ADR-0150 D9, #31699] two packages' instances of one name are two + // descriptors: the package tells them apart. + ...(packageId === null ? {} : { packageId }), + label: def.label, + type: def.type, + description: def.description, + icon: def.icon, + origin, + state, + degradedReason, + actions: (def.actions ?? []).map((a) => ({ + key: a.key, + label: a.label, + description: a.description, + inputSchema: a.inputSchema, + outputSchema: a.outputSchema, + // #4395 — the declared upstream effect travels to the designer + // too, not only to the executor: `GET /connectors` is where a + // flow author picks the action, and "this one writes" is a fact + // about the pick. + effect: a.effect, + })), + })); + } + + /** The body of `AutomationEngine#getRegisteredNodeTypes`; the method's docblock there is its contract. */ + static getRegisteredNodeTypes(this: Pick): string[] { + return [...this.nodeExecutors.keys()]; + } + + /** The body of `AutomationEngine#getActionDescriptors`; the method's docblock there is its contract. */ + static getActionDescriptors(this: Pick): ActionDescriptor[] { + return [...this.actionDescriptors.values()]; + } + + /** The body of `AutomationEngine#getRegisteredTriggerTypes`; the method's docblock there is its contract. */ + static getRegisteredTriggerTypes(this: Pick): string[] { + return [...this.triggers.keys()]; + } + + /** + * The node-type vocabulary this engine can validate against (ADR-0018). + * A type is known if it is structural (start/end), has a registered + * executor, or has a published action descriptor. + */ + static knownNodeTypes(this: Pick): Set { + return new Set([ + ...FLOW_STRUCTURAL_NODE_TYPES, + ...this.nodeExecutors.keys(), + ...this.actionDescriptors.keys(), + ]); + } + + /** The body of `AutomationEngine#getUnknownNodeTypeAudit`; the method's docblock there is its contract. */ + static getUnknownNodeTypeAudit(this: Pick): UnknownNodeTypeAuditEntry[] { + const known = this.knownNodeTypes(); + const audit: UnknownNodeTypeAuditEntry[] = []; + for (const [flowName, flow] of this.flows) { + if (!this.isFlowEnabled(flowName)) continue; + const unknownTypes = this.unknownNodeTypes(flow, known); + if (unknownTypes.length > 0) { + audit.push({ flowName, unknownTypes, knownTypes: [...known] }); + } + } + return audit; + } + + /** The body of `AutomationEngine#sealNodeTypeVocabulary`; the method's docblock there is its contract. */ + static sealNodeTypeVocabulary(this: Pick): UnknownNodeTypeAuditEntry[] { + const alreadySealed = this.nodeTypeVocabularySealed; + this.nodeTypeVocabularySealed = true; + const audit = this.getUnknownNodeTypeAudit(); + if (!alreadySealed) { + for (const entry of audit) this.warnUnknownNodeTypes(entry); + } + return audit; + } + + /** The body of `AutomationEngine#getSealedNodeTypeVocabulary`; the method's docblock there is its contract. */ + static getSealedNodeTypeVocabulary(this: Pick): string[] | undefined { + return this.nodeTypeVocabularySealed ? [...this.knownNodeTypes()].sort() : undefined; + } + + /** One warning per flow, shared by the boot audit and the post-seal path. */ + static warnUnknownNodeTypes(this: Pick, entry: UnknownNodeTypeAuditEntry): void { + // #6654 — the unknown type names are FLOW-AUTHOR metadata and the + // registered vocabulary is plugin-supplied (neither is + // schema-constrained against newlines), so both lists ride the + // structured slot, never the message; see `forgetSuspendedRun`'s + // catch for the full mechanism (#6299). The "no registered executor + // or descriptor" phrase is load-bearing — tests and log filters count + // per-flow findings by it. #4632: FUNCTIONAL — stays `warn`. + this.logger.warn( + `Flow '${entry.flowName}' references node type(s) with no registered executor or descriptor — ` + + `the unknown type names and the registered vocabulary are in this record's meta. Every plugin ` + + `has started, so nothing will register them now — these nodes fail at execution time with ` + + `NO_EXECUTOR. Install/enable the plugin that contributes them.`, + { unknownTypes: entry.unknownTypes, knownTypes: entry.knownTypes }, + ); + } +} diff --git a/packages/services/service-automation/src/engine-facet-hosts.ts b/packages/services/service-automation/src/engine-facet-hosts.ts new file mode 100644 index 00000000000..2133316108c --- /dev/null +++ b/packages/services/service-automation/src/engine-facet-hosts.ts @@ -0,0 +1,61 @@ +// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#38667] The host of each facet of `AutomationEngine`, built ONCE per engine: + * what every stub of a facet hands that facet's bodies as `this`. Each host + * below is filled by the factory `AutomationEngine`'s static block installs, + * the one place that can read the class's private members; it is built on the + * first call that needs it and kept for the engine's life. A method goes as a + * closure that calls it on the engine at call time, a field as a getter (and a + * setter when a body assigns it), so a body reads and writes the engine as it + * did on the class. + * + * It imports types only, so it forms no evaluation cycle and is evaluated + * before the class whichever module loads first. `index.ts` re-exports nothing + * from this module. + */ + +import type { AutomationEngine } from './engine.js'; +import type { DispatchHost } from './engine-dispatch-facet.js'; +import type { ExtensionsHost } from './engine-extensions-facet.js'; +import type { FlowSlotsHost } from './engine-flow-slots-facet.js'; +import type { RegistrationHost } from './engine-registration-facet.js'; +import type { ConnectorDoorsHost } from './engine-connector-doors-facet.js'; +import type { EnablementHost } from './engine-enablement-facet.js'; +import type { RunHost } from './engine-run-facet.js'; +import type { ResumeHost } from './engine-resume-facet.js'; + +/** One facet's host for each engine: built on first use, kept for the engine's life. */ +export class FacetHost { + private readonly hosts = new WeakMap(); + private build: ((engine: AutomationEngine) => H) | undefined; + + constructor(private readonly facet: string) {} + + /** Called once, from `AutomationEngine`'s static block. */ + install(build: (engine: AutomationEngine) => H): void { + this.build = build; + } + + /** The host of `engine`, built on first use. */ + of(engine: AutomationEngine): H { + let host = this.hosts.get(engine); + if (host === undefined) { + if (this.build === undefined) { + throw new Error(`${this.facet}: AutomationEngine has not installed its host factory`); + } + host = this.build(engine); + this.hosts.set(engine, host); + } + return host; + } +} + +export const dispatchHost = new FacetHost('DispatchFacet'); +export const extensionsHost = new FacetHost('ExtensionsFacet'); +export const flowSlotsHost = new FacetHost('FlowSlotsFacet'); +export const registrationHost = new FacetHost('RegistrationFacet'); +export const connectorDoorsHost = new FacetHost('ConnectorDoorsFacet'); +export const enablementHost = new FacetHost('EnablementFacet'); +export const runHost = new FacetHost('RunFacet'); +export const resumeHost = new FacetHost('ResumeFacet'); diff --git a/packages/services/service-automation/src/engine-flow-slots-facet.ts b/packages/services/service-automation/src/engine-flow-slots-facet.ts new file mode 100644 index 00000000000..a853c6b4b71 --- /dev/null +++ b/packages/services/service-automation/src/engine-flow-slots-facet.ts @@ -0,0 +1,814 @@ +// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#38667] Flow slots and holders: the `(package, name)` slot keys, arming holders, packaged flow ownership and defaults, and the name and connector-instance resolution: the bodies of + * `flowArmHolder`, `loaderOwnerOf`, `placeFlowSlot`, + * `bindPackagelessActivation`, `flowActivationBinds`, `moveFlowRecords`, + * `flowKeyNow`, `sharedFlowNameRefusal`, `resolveFlowKey`, `bareFlowKey`, + * `servedBareFlowKey`, `isDisabledHolderSlot`, `isDisabledSoleHolder`, + * `flowSlotPackage`, `flowSlotName`, `flowSlotKeysOf`, `loneSharedFlowKey`, + * `settleFlowName`, `isSharedFlowKey`, `executeSlot`, `setPackagedFlowSource`, + * `setPackagedFlowDefaultSource`, `packagedFlowOwner`, `inboundHookSlot`, + * `disabledHolderHookRefused`, `packagedFlowSlotOwner`, `isPackagedFlow`, + * `refuseUnpackagedDefaultActive`, `isShippedFlowName`, `packagedFlowDefault`, + * `refreshPackagedFlowDefaults`, `flowNameRefusal`, `connectorNameRefusal`, + * `resolveConnectorInstanceFor`, `codeRegisteredInstance`, `flowCallerPackage`, + * `armedFlowPackage`, `flowHolder`, `durableFlowHolder`, `flowHolderPackage`, + * `flowDispatchHolder` + * moved out of `engine.ts` whole. + * + * A MOVE, not a redesign. {@link FlowSlotsFacet} is a stateless facet of + * `AutomationEngine`: each static method of it is the body of the + * `AutomationEngine` method of the same name exactly as it stood, not + * re-indented, not formatted, not edited, with a `this` parameter added when + * the body reads the engine. The method stays on the class as a one-call stub + * with its signature, so the published declaration, an instance spy and a + * subclass override are what they were. A public method keeps its docblock on + * the class, the contract; a private method's docblock moved here with its + * body. The state stays on `AutomationEngine`. + * + * The bodies reach the engine through {@link FlowSlotsHost}: exactly the + * `AutomationEngine` members they read, private ones included. Every stub + * hands its body, by a `.call`, the same host: `flowSlotsHost` in + * `engine-facet-hosts.ts`, built once per engine by the class's static block. + * Methods go as closures that call them on the engine at call time, so a spy + * or a subclass override is still the one reached; fields go as getters, read + * when the body reads them, and a field a body assigns also goes with a setter + * that assigns it on the engine. + * + * The module imports `engine.ts` for types only, so the two modules form no + * evaluation cycle. `index.ts` re-exports nothing from this module. + */ + +import type { FlowParsed } from '@objectstack/spec/automation'; +import type { AutomationContext, AutomationResult } from '@objectstack/spec/contracts'; +import { describeThrownForLog } from './thrown-cause-diagnostics.js'; +import type { RegistrationCheckRefusal } from './flow-registration-checks.js'; +import type { PackageScopedRefusal, PackageScopedResolution } from '@objectstack/objectql'; +import { packageScopedRefusalMessage, PackageScopedNameRefusedError } from '@objectstack/core'; +import { ENVIRONMENT_ADDRESS_SEGMENT } from '@objectstack/spec/kernel'; +import { isSlotKeySpelling, unfiledFlowKey, type FlowKeyMove } from './flow-slots.js'; +import type { + FlowContender, + PackagedFlowSource, + PackagedFlowDefaultSource, + ConnectorInstanceResolution, +} from './engine-registration.js'; +import type { AutomationEngine } from './engine.js'; + +/** + * The `AutomationEngine` members the bodies of {@link FlowSlotsFacet} read — every one + * of them, and no other. Each is typed AS the class member (an indexed access + * on the class), so a change to a member's signature on the class is a change + * here too. `readonly` members are the getters; the others are fields a body + * assigns. + */ +export interface FlowSlotsHost { + readonly activateFlowTrigger: AutomationEngine['activateFlowTrigger']; + readonly armedFlowPackage: AutomationEngine['armedFlowPackage']; + readonly bindPackagelessActivation: AutomationEngine['bindPackagelessActivation']; + readonly codeRegisteredInstance: AutomationEngine['codeRegisteredInstance']; + readonly connectorNameResolver: AutomationEngine['connectorNameResolver']; + readonly connectors: AutomationEngine['connectors']; + readonly deactivateFlowTrigger: AutomationEngine['deactivateFlowTrigger']; + readonly disabledHolderHookRefused: AutomationEngine['disabledHolderHookRefused']; + readonly durableFlowHolder: AutomationEngine['durableFlowHolder']; + readonly executeKey: AutomationEngine['executeKey']; + readonly executionLogs: AutomationEngine['executionLogs']; + readonly flowActivationStore: AutomationEngine['flowActivationStore']; + readonly flowArmHolder: AutomationEngine['flowArmHolder']; + readonly flowArms: AutomationEngine['flowArms']; + readonly flowCallerPackage: AutomationEngine['flowCallerPackage']; + readonly flowHolder: AutomationEngine['flowHolder']; + readonly flowHoldersSealed: AutomationEngine['flowHoldersSealed']; + readonly flowKeyNow: AutomationEngine['flowKeyNow']; + readonly flowKeyOfRun: AutomationEngine['flowKeyOfRun']; + readonly flowLedgerDisabled: AutomationEngine['flowLedgerDisabled']; + readonly flowNameRefusal: AutomationEngine['flowNameRefusal']; + readonly flowNameResolver: AutomationEngine['flowNameResolver']; + readonly flowShadowing: AutomationEngine['flowShadowing']; + readonly flowSlotPackage: AutomationEngine['flowSlotPackage']; + readonly flowSlots: AutomationEngine['flowSlots']; + readonly flowStatusDisabled: AutomationEngine['flowStatusDisabled']; + readonly flowVersionHistory: AutomationEngine['flowVersionHistory']; + readonly flows: AutomationEngine['flows']; + readonly isDisabledHolderSlot: AutomationEngine['isDisabledHolderSlot']; + readonly isDisabledSoleHolder: AutomationEngine['isDisabledSoleHolder']; + readonly isFlowEnabled: AutomationEngine['isFlowEnabled']; + readonly isPackagedFlow: AutomationEngine['isPackagedFlow']; + readonly isShippedFlowName: AutomationEngine['isShippedFlowName']; + readonly loaderOwnerOf: AutomationEngine['loaderOwnerOf']; + readonly logger: AutomationEngine['logger']; + readonly moveFlowRecords: AutomationEngine['moveFlowRecords']; + readonly movedFlowKeys: AutomationEngine['movedFlowKeys']; + packagedFlowDefaultSource: AutomationEngine['packagedFlowDefaultSource']; + packagedFlowDefaults: AutomationEngine['packagedFlowDefaults']; + readonly packagedFlowOwner: AutomationEngine['packagedFlowOwner']; + readonly packagedFlowSlotOwner: AutomationEngine['packagedFlowSlotOwner']; + packagedFlowSource: AutomationEngine['packagedFlowSource']; + readonly pendingFlowActivationBinds: AutomationEngine['pendingFlowActivationBinds']; + readonly policyDisabledFlows: AutomationEngine['policyDisabledFlows']; + readonly rejudgeSubflowCallers: AutomationEngine['rejudgeSubflowCallers']; + readonly resolveConnectorInstanceFor: AutomationEngine['resolveConnectorInstanceFor']; + readonly resolveFlowKey: AutomationEngine['resolveFlowKey']; + readonly settleFlowName: AutomationEngine['settleFlowName']; + readonly sharedFlowNameRefusal: AutomationEngine['sharedFlowNameRefusal']; + readonly sharedSlotTriggerWarned: AutomationEngine['sharedSlotTriggerWarned']; + readonly subflowDeclinedFlows: AutomationEngine['subflowDeclinedFlows']; + readonly subflowNoticeDeclinedFlows: AutomationEngine['subflowNoticeDeclinedFlows']; + readonly subflowRegionDeclinedFlows: AutomationEngine['subflowRegionDeclinedFlows']; + readonly subflowRetryDeclinedFlows: AutomationEngine['subflowRetryDeclinedFlows']; + readonly suspendedRuns: AutomationEngine['suspendedRuns']; +} + +/** The bodies of the "Flow slots and holders" members of `AutomationEngine`: a stateless facet, called by the class's stubs. */ +export class FlowSlotsFacet { + /** + * [ADR-0150 D4, #31696] The package whose item a registration is — the + * slot it is held in — or `undefined` for a body no package holds (an + * environment-authored row, a write door's body), which lands in the + * name's one slot ({@link placeFlowSlot}). + */ + static flowArmHolder(this: Pick, name: string, arm: FlowContender): string | undefined { + if (arm.holder) return arm.holder; + if (arm.source === 'package') return arm.packageId || undefined; + if (arm.source === 'override') { + const keys = this.flowSlots.keysOf(name); + if (keys.length === 1) return this.flowSlots.slot(keys[0])?.packageId ?? this.loaderOwnerOf(name); + // Two slots and no `holder`: no package's, so placeFlowSlot refuses it. + return keys.length === 0 ? this.loaderOwnerOf(name) : undefined; + } + return undefined; + } + + /** The loader's set's one owner of the bare name, asked by name alone. */ + static loaderOwnerOf(this: Pick, name: string): string | undefined { + const owner = this.packagedFlowSource?.(name); + return typeof owner === 'string' && owner !== '' ? owner : undefined; + } + + /** + * [ADR-0150 D4, #31696] The key `name`'s registration is filed under, + * creating the slot when it is new. A package's body goes in its own slot + * (taking over a package-less one: D4, that flow is its customization); a + * second package's slot moves the incumbent's records to its qualified + * key ({@link moveFlowRecords}). A body no package holds goes in the + * name's one slot, and throws, with nothing changed, over two (nothing + * picks whose customization it is), or where the resolver refuses the + * bare name for a caller with no package (E1). + */ + static placeFlowSlot(this: Pick, name: string, arm: FlowContender): string { + // E1 (#31677 Q1), unchanged for every arm that names no slot: a name + // the resolver refuses for a caller with no package is refused, never + // armed by package id or by arrival. Only precedence's per-package + // winner names its slot (`holder`), and arms beside the others. + if (arm.holder === undefined) { + const refusal = this.flowNameRefusal(name, null); + if (refusal) throw new Error(refusal.message); + } + const packageId = this.flowArmHolder(name, arm); + if (packageId === undefined) { + const keys = this.flowSlots.keysOf(name); + if (keys.length > 1) throw new PackageScopedNameRefusedError(this.sharedFlowNameRefusal(name, null)); + return keys[0] ?? this.flowSlots.add({ packageId: null, name }).key; + } + const own = this.flowSlots.keyOf(name, packageId); + if (own !== undefined) { + // [#33893] A lone slot kept under its qualified key beside a + // disabled co-holder folds back once that holder is gone (the + // uninstall's re-sync re-registers this one). + return this.settleFlowName(name) ? this.flowKeyNow(own) : own; + } + const packageless = this.flowSlots.keyOf(name, null); + if (packageless !== undefined) { + this.flowSlots.adopt(packageless, packageId); + return packageless; + } + const incumbents = this.flowSlots.slotsOf(name); + const incumbent = incumbents.length === 1 ? incumbents[0].packageId : null; + if (incumbent !== null && this.flowHoldersSealed) this.bindPackagelessActivation(name, incumbent); + const incumbentKey = incumbents.length === 1 ? this.flowSlots.keyOf(name, incumbent) : undefined; + const { key, moved } = this.flowSlots.add({ packageId, name }); + this.moveFlowRecords(moved); + // [#33893] An incumbent already under its qualified key (filed so + // beside a disabled co-holder) moves no key as its co-holder returns, + // so the move's re-arm is done here: the M1 decline it may have taken + // while it was the name's one slot no longer applies. + if (incumbentKey !== undefined && incumbentKey !== name && moved.length === 0 && this.flows.has(incumbentKey)) { + this.sharedSlotTriggerWarned.delete(incumbentKey); + this.activateFlowTrigger(incumbentKey); + } + if (incumbent !== null && !this.flowHoldersSealed) this.flowLedgerDisabled.refusePackagelessBind(name, incumbent); + return key; + } + + /** + * [#31696, ADR-0150 D4, epic red line 1] After the boot's holders have + * converged ({@link sealFlowHolders}), a name's one holder is getting a + * second: an activation row naming no package was that holder's switch + * (D8), so it is bound to it, in the ledger first and in the projection + * once that write lands. Until then the row keeps every holder off + * ({@link FlowActivationProjection}); a failed write leaves it so (past a + * restart too), said once. A row read over two holders is never bound. + * {@link flowActivationBinds} settles once the write has. + */ + static bindPackagelessActivation(this: Pick, name: string, holder: string): void { + if (!this.flowLedgerDisabled.canBindPackageless(name, holder)) return; + const store = this.flowActivationStore; + const bound = () => { + this.flowLedgerDisabled.bindPackageless(name, holder); + this.logger.info( + `[Automation] The flow "${name}" is switched off by an activation row that names no package, and a second ` + + `package now holds a flow of that name: the row is now the switch of package "${holder}", which held ` + + 'the name alone.', + { flow: name, packageId: holder }, + ); + // The other holders were held off while the row named no package. + for (const key of this.flowSlots.keysOf(name)) { + if (!this.flows.has(key) || this.flowLedgerDisabled.has(key)) continue; + this.activateFlowTrigger(key); + this.rejudgeSubflowCallers(key); + } + }; + if (!store) { + bound(); + return; + } + this.flowLedgerDisabled.beginBindPackageless(name); + const write = Promise.resolve() + .then(() => store.setActive({ name, packageId: holder, active: false }, { adoptPackageless: true })) + .then(bound, (err: unknown) => { + this.flowLedgerDisabled.failBindPackageless(name); + this.logger.warn( + `[Automation] The flow "${name}" is switched off by an activation row that names no package, and a ` + + `second package now holds a flow of that name. Writing that row as package "${holder}"'s own ` + + 'row failed, so the row still names no package and keeps every package\'s flow of that name ' + + 'off. To turn one on, switch that package\'s flow: that writes its own row.', + { flow: name, packageId: holder, ...describeThrownForLog(err) }, + ); + }) + .finally(() => this.pendingFlowActivationBinds.delete(write)); + this.pendingFlowActivationBinds.add(write); + } + + /** The body of `AutomationEngine#flowActivationBinds`; the method's docblock there is its contract. */ + static async flowActivationBinds(this: Pick): Promise { + while (this.pendingFlowActivationBinds.size > 0) { + await Promise.allSettled([...this.pendingFlowActivationBinds]); + } + } + + /** + * [#31696] Move every per-flow record from the keys a slot change moved + * off to the keys it moved onto. Each moved flow's trigger is released + * under the old key first and armed under the new one after, through the + * one arming gate. + */ + static moveFlowRecords(this: Pick, moved: readonly FlowKeyMove[]): void { + if (moved.length === 0) return; + for (const { from } of moved) { + this.deactivateFlowTrigger(from); + // A key that moves leaves the sharing it was declined under, so + // a later share of the name says the decline again. + this.sharedSlotTriggerWarned.delete(from); + } + const maps: Array> = [ + this.flows, + this.flowShadowing, + this.flowStatusDisabled, + this.flowVersionHistory, + this.policyDisabledFlows, + this.subflowDeclinedFlows, + this.subflowNoticeDeclinedFlows, + this.subflowRegionDeclinedFlows, + this.subflowRetryDeclinedFlows, + ]; + for (const { from, to } of moved) { + for (const map of maps) { + const records: Map = map; + if (!records.has(from)) continue; + records.set(to, records.get(from)); + records.delete(from); + } + for (const [runId, run] of this.suspendedRuns) { + if (run.flowName === from) this.suspendedRuns.set(runId, { ...run, flowName: to }); + } + // Every run the ring holds moves with it, finished runs included; + // a run still in flight, or a consumed pause put back later, is + // filed where it lands ({@link flowKeyNow}). + for (let i = 0; i < this.executionLogs.length; i++) { + const entry = this.executionLogs[i]; + if (entry.flowName === from) this.executionLogs[i] = { ...entry, flowName: to }; + } + this.movedFlowKeys.delete(to); + this.movedFlowKeys.set(from, to); + } + for (const { to } of moved) { + if (this.flows.has(to)) this.activateFlowTrigger(to); + } + } + + /** + * [#31696] The key a run started under `key` is filed under now: `key` + * while a slot holds it, else where the slot changes moved it. + */ + static flowKeyNow(this: Pick, key: string): string { + for (let next = this.movedFlowKeys.get(key); next !== undefined && !this.flows.has(key); next = this.movedFlowKeys.get(key)) key = next; + return key; + } + + /** + * [#31696, ADR-0150 D3] The refusal a bare `name` two slots hold gets + * from a caller of package `callerPackageId` that reaches neither: every + * holder named, nothing picked — the package-scoped rule's own sentence. + */ + static sharedFlowNameRefusal(this: Pick, name: string, callerPackageId: string | null): PackageScopedRefusal { + // [M1] Every holder the registry names, a holder whose body was refused included. + // [#32183, R4-G] A disabled holder too: its slot stays armed, so the + // refusal names it, as on `main`. + const held = this.durableFlowHolder(name); + const candidates = held?.status === 'refused' ? held.candidates : this.flowSlots.slotsOf(name).map((slot) => + slot.packageId === null ? { kind: 'environment' as const } : { kind: 'package' as const, packageId: slot.packageId }, + ); + const base = { + status: 'refused' as const, + reason: 'ambiguous-in-environment' as const, + type: 'flow' as const, + name, + callerPackageId, + candidates, + }; + return { ...base, message: packageScopedRefusalMessage(base) }; + } + + /** + * [ADR-0150 D3, #31696] The key the bare flow name `name` means for a + * caller of package `callerPackageId` (`null`: a caller with no package), + * the refusal, or `absent`. A name one slot holds is its own key, refused + * only by the resolver, as before slots. A name two slots hold resolves + * through the resolver to the holder it reaches; the caller's own slot, + * when no resolver is attached; else it is refused, naming every holder. + * + * [ADR-0150 D3, #33386; seat ruling 6884403301] A name two slots hold is + * resolved over the SERVED holders (a disabled package holds no name): + * one served holder is that holder's slot, two or more are refused naming + * the served holders only, and none is `absent` (no flow). A caller whose + * own holding is the disabled one is `absent`, never a closure holder's + * (`servedCaller`, amendment 4). The slots themselves stay keyed over every + * holder ({@link flowSlots}, amendment 7): a disable re-points no slot, it + * only moves which slot a bare name reaches. `durable` asks over every + * holder instead, as `main` did: the subflow guards' recorded arming + * verdicts ({@link flowCallKey}), which a reversible disable re-judges + * nowhere. + */ + static resolveFlowKey( + this: Pick, + name: string, + callerPackageId: string | null, + options?: { readonly durable?: boolean }, + ): { key: string } | { refusal: PackageScopedRefusal } | { absent: true } { + // [#31696] A slot key is no flow's name: it names no flow here. + if (isSlotKeySpelling(name)) return { key: unfiledFlowKey(name) }; + this.settleFlowName(name); + if (!this.flowSlots.isShared(name)) { + const refusal = this.flowNameRefusal(name, callerPackageId); + if (refusal) return { refusal }; + // [#33905] Its one holder's package is disabled: no flow, as for a + // name two packages hold that no served holder reaches. + if (options?.durable !== true && this.isDisabledSoleHolder(name)) return { absent: true }; + return { key: name }; + } + const resolution = this.flowNameResolver?.(name, callerPackageId, + options?.durable === true ? { includeDisabledPackages: true } : { servedCaller: true }); + if (resolution?.status === 'refused') return { refusal: resolution }; + if (resolution?.status === 'resolved' && resolution.holder.kind === 'package') { + const key = this.flowSlots.keyOf(name, resolution.holder.packageId); + if (key !== undefined) return { key }; + } + // [#33386] No served holder reaches the name: no flow, never another slot. + if (resolution?.status === 'not-found' && options?.durable !== true) return { absent: true }; + if (resolution === undefined && callerPackageId !== null) { + const own = this.flowSlots.keyOf(name, callerPackageId); + if (own !== undefined) return { key: own }; + } + return { refusal: this.sharedFlowNameRefusal(name, callerPackageId) }; + } + + /** + * [ADR-0150 D3, #31696] {@link resolveFlowKey} for a caller with no + * package, the refusal thrown (409, every holder named). `undefined` for a + * slot-key spelling (`PACKAGE/NAME`): no flow is named so, so the door + * answers as for a flow it does not hold ({@link getFlowSlot} takes one). + * The removal and history entries read it: a shared name stays refused + * there over every holder, served or not. + */ + static bareFlowKey(this: Pick, name: string): string | undefined { + if (isSlotKeySpelling(name)) return undefined; + this.settleFlowName(name); + if (!this.flowSlots.isShared(name)) return name; + throw new PackageScopedNameRefusedError(this.sharedFlowNameRefusal(name, null)); + } + + /** + * [ADR-0150 D3, #33386] The key the bare entries that READ or RUN a flow + * ({@link execute}'s caller-less twin, {@link getFlow}, {@link toggleFlow}) + * serve for `name`, judged over the served holders ({@link resolveFlowKey}): + * a name two slots hold is its one served holder's slot, refused naming + * the served holders when two or more serve it, and `undefined` (no flow) + * when none does. Seat ruling 6884403301, amendment 9: these entries move + * with the doors. [#33905] A name one package holds whose package is + * disabled is no flow here either ({@link isDisabledSoleHolder}): the + * entries answer as for a flow this engine does not hold, which is the + * namespaced address's answer. + */ + static servedBareFlowKey(this: Pick, name: string): string | undefined { + if (isSlotKeySpelling(name)) return undefined; + this.settleFlowName(name); + if (!this.flowSlots.isShared(name)) return this.isDisabledSoleHolder(name) ? undefined : name; + const resolved = this.resolveFlowKey(name, null); + if ('refusal' in resolved) throw new PackageScopedNameRefusedError(resolved.refusal); + return 'key' in resolved ? resolved.key : undefined; + } + + /** + * [ADR-0150 D3, #33748; seat ruling 6884403301, amendment 3] Is the slot + * `(packageId, name)` held by a package that is disabled now? Asked of + * the one resolver ({@link flowNameResolver}), with that package as the + * caller: its own holding answers on the served read, and the run's read + * (`servedCaller`) answers `not-found` for it only while the package is + * disabled (amendment 4's caller-first rule). Both readings are needed: + * `not-found` alone would also cover a slot whose package the registry + * does not hold at all, which this question does not judge. No resolver + * attached: nothing is disabled here. + */ + static isDisabledHolderSlot(this: Pick, name: string, packageId: string): boolean { + const resolver = this.flowNameResolver; + if (resolver === undefined) return false; + const held = resolver(name, packageId); + if (held?.status !== 'resolved' || held.via !== 'own') return false; + return resolver(name, packageId, { servedCaller: true })?.status === 'not-found'; + } + + /** + * [ADR-0150 D3, #33905; #28117 ruling A] Is the one slot of the unshared + * name `name` held by a package that is disabled now + * ({@link isDisabledHolderSlot})? A package-less slot, or none, is not: + * a flow registered straight into the engine, or the environment's own, + * is no package's to disable. Only the entries that read or run a flow + * ask it; the durable reads (slot and run keys, {@link flowDispatchHolder}, + * credentials, history) stay judged over every holder (amendment 7). + */ + static isDisabledSoleHolder(this: Pick, name: string): boolean { + const packageId = this.flowSlotPackage(name); + return packageId !== undefined && this.isDisabledHolderSlot(name, packageId); + } + + /** [#31696] The package of the slot `key` files, or `undefined` (a package-less slot, or none). */ + static flowSlotPackage(this: Pick, key: string): string | undefined { + return this.flowSlots.slot(key)?.packageId ?? undefined; + } + + /** [#31696] The flow name a slot key files: the key itself for a key no slot files. */ + static flowSlotName(this: Pick, key: string): string { + return this.flowSlots.slot(key)?.name ?? key; + } + + /** [#31696] Every key a slot of the bare `name` is filed under; the name itself when none is. */ + static flowSlotKeysOf(this: Pick, name: string): string[] { + const keys = this.flowSlots.keysOf(name); + return keys.length > 0 ? keys : [name]; + } + + /** + * [M1] The key of `name`'s one slot while the registry holds `name` under + * two packages SERVED, so another served package's body of it is not held + * here (refused), else `undefined`. [#33893] A co-holder that is only + * disabled is no M1: the slot is the name's one served holder, keeps its + * qualified key (amendment 7) and is armed, and no body was refused. + */ + static loneSharedFlowKey(this: Pick, name: string): string | undefined { + const keys = this.flowSlots.keysOf(name); + return keys.length === 1 && this.flowSlots.isShared(name) && this.flowHolder(name)?.status === 'refused' ? keys[0] : undefined; + } + + /** + * [#33893] Fold `name`'s lone slot back to the bare name if it is still + * under its qualified key while the registry no longer holds the name + * twice ({@link FlowSlotTable.settle}), moving its records and trigger. + * True when it moved. + */ + static settleFlowName(this: Pick, name: string): boolean { + const moved = this.flowSlots.settle(name); + this.moveFlowRecords(moved); + return moved.length > 0; + } + + /** [#31696] Is `key` the key of a slot whose name another slot holds too? */ + static isSharedFlowKey(this: Pick, key: string): boolean { + const slot = this.flowSlots.slot(key); + return slot !== undefined && this.flowSlots.isShared(slot.name); + } + + /** The body of `AutomationEngine#executeSlot`; the method's docblock there is its contract. */ + static async executeSlot(this: Pick, packageId: string | null, name: string, context?: AutomationContext): Promise { + const key = this.flowSlots.keyOf(name, packageId); + if (key === undefined) { + return { + success: false, + error: packageId === null + ? `Flow '${name}' not found` + : `Flow '${name}' of package '${packageId}' not found`, + }; + } + return this.executeKey(key, context, Date.now()); + } + + /** The body of `AutomationEngine#setPackagedFlowSource`; the method's docblock there is its contract. */ + static setPackagedFlowSource(this: Pick, source: PackagedFlowSource | undefined): void { + this.packagedFlowSource = source; + this.packagedFlowDefaults = new WeakMap(); + } + + /** The body of `AutomationEngine#setPackagedFlowDefaultSource`; the method's docblock there is its contract. */ + static setPackagedFlowDefaultSource(this: Pick, source: PackagedFlowDefaultSource | undefined): void { + this.packagedFlowDefaultSource = source; + this.packagedFlowDefaults = new WeakMap(); + } + + /** The body of `AutomationEngine#packagedFlowOwner`; the method's docblock there is its contract. */ + static packagedFlowOwner(this: Pick, name: string): string | undefined { + // [ADR-0150 D4, #31696] `name` may be a slot key. A slot of a name two + // slots hold asks the loader's set for its own package's flow; a bare + // name two slots hold has no one owner, and answers none. + const slot = this.flowSlots.slot(name); + if (slot !== undefined && this.flowSlots.isShared(slot.name)) { + if (slot.packageId === null) return undefined; + return this.packagedFlowSource?.(slot.name, slot.packageId) === slot.packageId ? slot.packageId : undefined; + } + if (slot === undefined && this.flowSlots.isShared(name)) return undefined; + const owner = this.packagedFlowSource?.(name); + return typeof owner === 'string' && owner !== '' ? owner : undefined; + } + + /** The body of `AutomationEngine#inboundHookSlot`; the method's docblock there is its contract. */ + static inboundHookSlot( + this: Pick, + flowName: string, + address?: { readonly qualifier: string; readonly namespaceOwners: readonly string[] }, + ): + | undefined + | { readonly status: 'served'; readonly key: string } + | { readonly status: 'unadmitted' } + | { readonly status: 'refused'; readonly candidates: PackageScopedRefusal['candidates'] } { + if (isSlotKeySpelling(flowName) || flowName.startsWith('\u0000')) return { status: 'unadmitted' }; + this.settleFlowName(flowName); + if (!this.flowSlots.isShared(flowName)) { + const packageId = this.flowSlotPackage(flowName); + return packageId !== undefined && this.isDisabledHolderSlot(flowName, packageId) + ? this.disabledHolderHookRefused(flowName, packageId, flowName) + : undefined; + } + if (address === undefined) return { status: 'refused', candidates: this.sharedFlowNameRefusal(flowName, null).candidates }; + const environment = address.qualifier === ENVIRONMENT_ADDRESS_SEGMENT; + const keys = this.flowSlots.keysOf(flowName).filter((key) => { + const slot = this.flowSlots.slot(key)!; + if (environment) return slot.packageId === null; + return slot.packageId !== null && address.namespaceOwners.includes(slot.packageId) + && this.packagedFlowOwner(key) === slot.packageId; + }); + if (keys.length !== 1) return { status: 'unadmitted' }; + const packageId = this.flowSlotPackage(keys[0]); + if (packageId !== undefined && this.isDisabledHolderSlot(flowName, packageId)) { + return this.disabledHolderHookRefused(flowName, packageId, keys[0]); + } + return { status: 'served', key: keys[0] }; + } + + /** + * [#33906] {@link inboundHookSlot}'s answer for the slot `key` of package + * `packageId`'s flow `name` while that package is disabled: `unadmitted`, + * its cause logged here at `info` (the sender is told, with the door's one + * refusal, so nothing that claims to be persisted is lost). + */ + static disabledHolderHookRefused(this: Pick, name: string, packageId: string, key: string): { readonly status: 'unadmitted' } { + this.logger.info( + `Inbound hook post for flow '${name}' of package '${packageId}', which is disabled — refused with the ` + + 'one answer every unverified post gets: nothing was enqueued, and no other package\'s flow of the ' + + 'name was reached in its place. A sender that retries on a non-2xx keeps the event and can ' + + 'redeliver it once the package is enabled.', + { cause: 'disabled-holder', flow: name, package: packageId, slot: key }, + ); + return { status: 'unadmitted' }; + } + + /** The body of `AutomationEngine#packagedFlowSlotOwner`; the method's docblock there is its contract. */ + static packagedFlowSlotOwner(this: Pick, name: string, packageId: string): string | undefined { + return this.packagedFlowSource?.(name, packageId) === packageId ? packageId : undefined; + } + + /** [#20761] Is `name` a packaged flow — {@link packagedFlowOwner}, as a verdict. */ + static isPackagedFlow(this: Pick, name: string): boolean { + return this.packagedFlowOwner(name) !== undefined; + } + + /** + * [#34655, ADR-0126 §4] Refuse a body that declares `defaultActive` for a + * flow no package ships. The key is the default of the packaged-flow + * switch (the activation ledger), and a flow authored in this deployment + * has no such switch: its switch is its own `status`, so the key could + * only be a declaration the engine does not honour. + * + * A flow is packaged when any package's loader set holds its name + * ({@link isShippedFlowName}: the loader's own answer, a name two + * packages hold included); every other flow is the environment's. Judged by NAME, never by the arm a + * registration names, because it is one of the {@link registrationChecks} + * (#23317): {@link registerFlow} throws it, {@link dryRun} refuses a draft + * for it, and the stored pass ({@link canonicalizeStoredFlow}) lists a + * stored row it would refuse, all three asking the same question. A + * package's declared `.custom` override is served at the base's name, so + * it passes; the default it carries is not read ({@link packagedFlowDefault}). + * + * Registration refuses it as it refuses every check: `registerFlow` throws + * an `Error`, which the automation write doors (`registerAndSaveFlow` in + * `@objectstack/runtime`) answer `VALIDATION_FAILED` / 400 with nothing + * stored. The metadata door (`PUT /api/v1/meta/flow/:name`) parses + * without registering, so it stores such a row; the engine then refuses + * to arm it, and the stored pass names it. + */ + static refuseUnpackagedDefaultActive(this: Pick, flowName: string, flow: FlowParsed): RegistrationCheckRefusal | undefined { + if (flow.defaultActive === undefined || this.isShippedFlowName(flowName, flow)) return undefined; + const why = + `'${flowName}' declares defaultActive, which is the default of the switch an administrator turns a ` + + `PACKAGED flow on and off with, and '${flowName}' was authored in this deployment, not shipped by a ` + + `package. A flow authored here is switched by its own status: remove defaultActive, and publish ` + + `it with status 'obsolete' to keep it off or 'active' to arm it.`; + return { + message: `Flow ${why}`, + sites: [{ path: 'flows[0].defaultActive', from: JSON.stringify(flow.defaultActive), detail: `the flow ${why}` }], + }; + } + + /** + * [#34655, L2 S3] Does ANY package's loader set hold a flow `name`? The + * question {@link refuseUnpackagedDefaultActive} asks — not "is there ONE + * owner": {@link packagedFlowOwner} answers none for a bare name two + * packages hold (ADR-0150 D4), and a package's body re-registered under + * such a name (a re-sync, a hot upgrade, a third holder arriving) is + * still a package's. Every answer is the loader's own, asked per package + * ({@link packagedFlowSlotOwner}) of each package that may hold it: the + * packages whose slots hold the name now, and the package the body names + * itself as (`_packageId`). The stamp is only which package to ASK; a + * stamp naming a package that ships no such flow answers no. + */ + static isShippedFlowName(this: Pick, name: string, flow: FlowParsed): boolean { + if (this.isPackagedFlow(name)) return true; + const bare = this.flowSlots.slot(name)?.name ?? name; + const stamped = (flow as { _packageId?: unknown })._packageId; + const candidates = new Set(typeof stamped === 'string' && stamped !== '' ? [stamped] : []); + for (const slot of this.flowSlots.slotsOf(bare)) if (slot.packageId !== null) candidates.add(slot.packageId); + return [...candidates].some((packageId) => this.packagedFlowSlotOwner(bare, packageId) !== undefined); + } + + /** + * [#34655, ADR-0126 §4, seat ruling on S2] The `defaultActive` the + * PACKAGE declares for the flow held under `key`, or `undefined` for none + * (and for a flow no package ships). Read off the package's own body: + * the armed body when the loader's body is what is armed, else the body + * the loader's set holds for the slot's package + * ({@link setPackagedFlowDefaultSource}). So a declared `.custom` override + * does not change the default, in either direction: an override that + * omits the key does not arm a flow its package ships off, and one that + * writes `false` does not switch off a flow its package ships on. The + * administrator's switch (the activation ledger) decides either way. + * With no reader attached, only an armed loader's body answers. + * + * [L2 N9] The reader's answer is asked once per armed body + * ({@link packagedFlowDefaults}), not on every {@link isFlowEnabled}, + * and asked again after each change to the loader's set + * ({@link refreshPackagedFlowDefaults}). + */ + static packagedFlowDefault(this: Pick, key: string): boolean | undefined { + const armed = this.flows.get(key); + if (!armed) return undefined; + if (this.flowArms.get(armed)?.source === 'package') return armed.defaultActive; + const source = this.packagedFlowDefaultSource; + if (source === undefined) return undefined; + const asked = this.packagedFlowDefaults.get(armed); + if (asked !== undefined) return asked.value; + const owner = this.packagedFlowOwner(key); + const value = owner === undefined ? undefined : source(this.flowSlots.slot(key)?.name ?? key, owner); + this.packagedFlowDefaults.set(armed, { value }); + return value; + } + + /** The body of `AutomationEngine#refreshPackagedFlowDefaults`; the method's docblock there is its contract. */ + static refreshPackagedFlowDefaults(this: Pick): string[] { + const before = new Map(); + for (const [key, armed] of this.flows) { + if (this.flowArms.get(armed)?.source !== 'package') before.set(key, this.isFlowEnabled(key)); + } + this.packagedFlowDefaults = new WeakMap(); + const moved: string[] = []; + for (const [key, wasEnabled] of before) { + if (this.isFlowEnabled(key) === wasEnabled) continue; + if (wasEnabled) this.deactivateFlowTrigger(key); + else this.activateFlowTrigger(key); + moved.push(key); + } + // [#20725, ADR-0126 §7.3] The callers of a subflow that moved, through the same gate. + for (const key of moved) this.rejudgeSubflowCallers(key); + return moved; + } + + /** + * [ADR-0150 D3] The resolver's refusal of the bare flow name `name` for a + * caller of package `callerPackageId` (`null`: no package), or `undefined` + * when the name resolves, names nothing in the registry, or no resolver is + * attached. Read-only; records nothing. + */ + static flowNameRefusal(this: Pick, name: string, callerPackageId: string | null): PackageScopedRefusal | undefined { + const resolution = this.flowNameResolver?.(name, callerPackageId); + return resolution?.status === 'refused' ? resolution : undefined; + } + + /** The body of `AutomationEngine#connectorNameRefusal`; the method's docblock there is its contract. */ + static connectorNameRefusal(this: Pick, connectorId: string, context: AutomationContext | undefined): PackageScopedRefusal | undefined { + const resolved = this.resolveConnectorInstanceFor(connectorId, this.flowCallerPackage(context)); + return resolved.status === 'refused' ? resolved.refusal : undefined; + } + + /** The body of `AutomationEngine#resolveConnectorInstanceFor`; the method's docblock there is its contract. */ + static resolveConnectorInstanceFor(this: Pick, connectorId: string, callerPackageId: string | null): ConnectorInstanceResolution { + const resolver = this.connectorNameResolver; + const meant = resolver?.(connectorId, callerPackageId); + if (meant?.status === 'refused') return { status: 'refused', refusal: meant }; + if (meant?.status === 'resolved') { + const packageId = meant.holder.kind === 'package' ? meant.holder.packageId : null; + return this.connectors.get(connectorId, packageId) ? { status: 'instance', packageId } : this.codeRegisteredInstance(connectorId); + } + if (meant?.status === 'not-found' + && resolver?.(connectorId, callerPackageId, { includeDisabledPackages: true })?.status !== 'not-found') { + return this.codeRegisteredInstance(connectorId); + } + const sole = this.connectors.sole(connectorId); + return sole ? { status: 'instance', packageId: sole.packageId } : { status: 'none' }; + } + + /** + * [#31699] The instance a plugin registered in code under `connectorId` + * (package `null`, origin `plugin`), or `none`: what a name answers when + * the holder it resolves to has no instance of its own. + */ + static codeRegisteredInstance(this: Pick, connectorId: string): ConnectorInstanceResolution { + return this.connectors.get(connectorId, null)?.origin === 'plugin' ? { status: 'instance', packageId: null } : { status: 'none' }; + } + + /** The body of `AutomationEngine#flowCallerPackage`; the method's docblock there is its contract. */ + static flowCallerPackage(this: Pick, context: AutomationContext | undefined): string | null { + // [#31696] The slot key the run stamped, where its flow's name is one + // two slots hold; else the name, which is then its key. + const caller = this.flowKeyOfRun(context); + if (caller === undefined) return null; + return this.armedFlowPackage(caller) ?? null; + } + + /** The body of `AutomationEngine#armedFlowPackage`; the method's docblock there is its contract. */ + static armedFlowPackage(this: Pick, name: string): string | undefined { + const armed = this.flows.get(name); + if (!armed || this.flowArms.get(armed)?.source !== 'package') return undefined; + return this.packagedFlowOwner(name); + } + + /** The body of `AutomationEngine#flowHolder`; the method's docblock there is its contract. */ + static flowHolder(this: Pick, name: string): PackageScopedResolution | undefined { + return this.flowNameResolver?.(name, null); + } + + /** The body of `AutomationEngine#durableFlowHolder`; the method's docblock there is its contract. */ + static durableFlowHolder(this: Pick, name: string): PackageScopedResolution | undefined { + return this.flowNameResolver?.(name, null, { includeDisabledPackages: true }); + } + + /** The body of `AutomationEngine#flowHolderPackage`; the method's docblock there is its contract. */ + static flowHolderPackage(this: Pick, name: string): string | null { + const answer = this.flowHolder(name); + return answer?.status === 'resolved' && answer.holder.kind === 'package' ? answer.holder.packageId : null; + } + + /** The body of `AutomationEngine#flowDispatchHolder`; the method's docblock there is its contract. */ + static flowDispatchHolder(this: Pick, name: string): { packageId: string | null; claimBare: boolean; name?: string } { + if (isSlotKeySpelling(name)) { + const slot = this.flowSlots.slot(name); + if (slot) return { packageId: slot.packageId, claimBare: false, name: slot.name }; + } + // [#32183] Over every holder, a disabled package's included + // (`durableFlowHolder`): a dispatch key names a row of the ledger, the + // row the re-key backfill scopes over every holder, and a disable is + // reversible, so it moves no key. A flow only a disabled package holds + // keeps that package's scope; a name an enabled and a disabled package + // hold keeps the collision guard, as on `main`. + const answer = this.durableFlowHolder(name); + if (answer?.status === 'refused') return { packageId: this.armedFlowPackage(name) ?? null, claimBare: false }; + return { packageId: answer?.status === 'resolved' && answer.holder.kind === 'package' ? answer.holder.packageId : null, claimBare: true }; + } +} diff --git a/packages/services/service-automation/src/engine-registration-facet.ts b/packages/services/service-automation/src/engine-registration-facet.ts new file mode 100644 index 00000000000..23564504196 --- /dev/null +++ b/packages/services/service-automation/src/engine-registration-facet.ts @@ -0,0 +1,585 @@ +// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#38667] Flow registration: judging, registering, withdrawing and refusing a flow, shadowing, reading flows back, and the registration-time checks: the bodies of + * `judgeFlowRegistration`, `dryRun`, `registerFlow`, `unregisterFlow`, + * `withdrawFlow`, `withdrawFlowSlot`, `withdrawFlowKey`, `recordFlowRefusal`, + * `getFlowRegistration`, `recordFlowShadowing`, `getShadowedFlows`, + * `listFlows`, `getFlow`, `getRunFlow`, `flowKeyOfRun`, `getFlowSlot`, + * `getHeldFlow`, `registrationChecks`, `validateFlowExpressions`, + * `getValueType`, `validateNodeInputSchemas` + * moved out of `engine.ts` whole. + * + * A MOVE, not a redesign. {@link RegistrationFacet} is a stateless facet of + * `AutomationEngine`: each static method of it is the body of the + * `AutomationEngine` method of the same name exactly as it stood, not + * re-indented, not formatted, not edited, with a `this` parameter added when + * the body reads the engine. The method stays on the class as a one-call stub + * with its signature, so the published declaration, an instance spy and a + * subclass override are what they were. A public method keeps its docblock on + * the class, the contract; a private method's docblock moved here with its + * body. The state stays on `AutomationEngine`. + * + * The bodies reach the engine through {@link RegistrationHost}: exactly the + * `AutomationEngine` members they read, private ones included. Every stub + * hands its body, by a `.call`, the same host: `registrationHost` in + * `engine-facet-hosts.ts`, built once per engine by the class's static block. + * Methods go as closures that call them on the engine at call time, so a spy + * or a subclass override is still the one reached; fields go as getters, read + * when the body reads them, and a field a body assigns also goes with a setter + * that assigns it on the engine. + * + * The module imports `engine.ts` for types only, so the two modules form no + * evaluation cycle. `index.ts` re-exports nothing from this module. + */ + +import type { FlowParsed } from '@objectstack/spec/automation'; +import type { AutomationContext, FlowDryRunOptions, FlowDryRunResult } from '@objectstack/spec/contracts'; +import type { FlowRegistration } from '@objectstack/spec/api'; +import { flowContentChecksum } from './flow-identity.js'; +import { + registrationChecks, + validateFlowExpressions, + type RegistrationCheckRefusal, +} from './flow-registration-checks.js'; +import { dryRun as dryRunBody, type DryRunHost } from './dry-run.js'; +import { unregisterFlow, recordFlowRefusal, withdrawFlow } from './flow-definitions.js'; +import { flowRunKey, flowRunPackage, isSlotKeySpelling } from './flow-slots.js'; +import { InputSchemaViolationError, isInputSchemaViolation } from './engine-signals.js'; +import type { FlowContender, FlowShadowingRecord } from './engine-registration.js'; +import type { AutomationEngine } from './engine.js'; + +/** + * The `AutomationEngine` members the bodies of {@link RegistrationFacet} read — every one + * of them, and no other. Each is typed AS the class member (an indexed access + * on the class), so a change to a member's signature on the class is a change + * here too. `readonly` members are the getters; the others are fields a body + * assigns. + */ +export interface RegistrationHost { + readonly activateFlowTrigger: AutomationEngine['activateFlowTrigger']; + readonly bareFlowKey: AutomationEngine['bareFlowKey']; + readonly canonicalizeFlow: AutomationEngine['canonicalizeFlow']; + readonly deactivateFlowTrigger: AutomationEngine['deactivateFlowTrigger']; + readonly deriveTriggerBinding: AutomationEngine['deriveTriggerBinding']; + readonly evaluateCondition: AutomationEngine['evaluateCondition']; + readonly evaluateValueEnvelope: AutomationEngine['evaluateValueEnvelope']; + readonly executeWithTimeout: AutomationEngine['executeWithTimeout']; + readonly flowArms: AutomationEngine['flowArms']; + readonly flowChecksums: AutomationEngine['flowChecksums']; + readonly flowKeyOfRun: AutomationEngine['flowKeyOfRun']; + readonly flowRefusals: AutomationEngine['flowRefusals']; + readonly flowShadowing: AutomationEngine['flowShadowing']; + readonly flowSlotName: AutomationEngine['flowSlotName']; + readonly flowSlots: AutomationEngine['flowSlots']; + readonly flowStatusDisabled: AutomationEngine['flowStatusDisabled']; + readonly flowVersionHistory: AutomationEngine['flowVersionHistory']; + readonly flows: AutomationEngine['flows']; + readonly getActionDescriptor: AutomationEngine['getActionDescriptor']; + readonly getValueType: AutomationEngine['getValueType']; + readonly isFlowEnabled: AutomationEngine['isFlowEnabled']; + readonly isPackagedFlow: AutomationEngine['isPackagedFlow']; + readonly judgeFlowRegistration: AutomationEngine['judgeFlowRegistration']; + readonly knownNodeTypes: AutomationEngine['knownNodeTypes']; + readonly logger: AutomationEngine['logger']; + readonly loneSharedFlowKey: AutomationEngine['loneSharedFlowKey']; + readonly moveFlowRecords: AutomationEngine['moveFlowRecords']; + readonly nodeExecutors: AutomationEngine['nodeExecutors']; + readonly nodeTypeVocabularySealed: AutomationEngine['nodeTypeVocabularySealed']; + readonly objectSchemaResolver: AutomationEngine['objectSchemaResolver']; + readonly packagedSubflowCallers: AutomationEngine['packagedSubflowCallers']; + readonly placeFlowSlot: AutomationEngine['placeFlowSlot']; + readonly policyDisabledFlows: AutomationEngine['policyDisabledFlows']; + readonly refuseUnderReachingCallers: AutomationEngine['refuseUnderReachingCallers']; + readonly refuseUnpackagedDefaultActive: AutomationEngine['refuseUnpackagedDefaultActive']; + readonly registrationChecks: AutomationEngine['registrationChecks']; + readonly rejudgeSubflowCallers: AutomationEngine['rejudgeSubflowCallers']; + readonly renderFlowTextSlot: AutomationEngine['renderFlowTextSlot']; + readonly renderRefusalMessage: AutomationEngine['renderRefusalMessage']; + readonly resolveRunContext: AutomationEngine['resolveRunContext']; + readonly seedRunVariables: AutomationEngine['seedRunVariables']; + readonly servedBareFlowKey: AutomationEngine['servedBareFlowKey']; + readonly setNodeError: AutomationEngine['setNodeError']; + readonly sharedSlotTriggerWarned: AutomationEngine['sharedSlotTriggerWarned']; + readonly subflowDeclinedFlows: AutomationEngine['subflowDeclinedFlows']; + readonly subflowNoticeDeclinedFlows: AutomationEngine['subflowNoticeDeclinedFlows']; + readonly subflowRegionDeclinedFlows: AutomationEngine['subflowRegionDeclinedFlows']; + readonly subflowRetryDeclinedFlows: AutomationEngine['subflowRetryDeclinedFlows']; + readonly unknownNodeTypes: AutomationEngine['unknownNodeTypes']; + readonly userGrantsResolver: AutomationEngine['userGrantsResolver']; + readonly validateApiTriggerSecret: AutomationEngine['validateApiTriggerSecret']; + readonly validateDecisionModes: AutomationEngine['validateDecisionModes']; + readonly validateFlowExpressions: AutomationEngine['validateFlowExpressions']; + readonly validateNodeConfigKeys: AutomationEngine['validateNodeConfigKeys']; + readonly validateNodeInputSchemas: AutomationEngine['validateNodeInputSchemas']; + readonly valueEnvelopeRefusals: AutomationEngine['valueEnvelopeRefusals']; + readonly warnUnknownNodeTypes: AutomationEngine['warnUnknownNodeTypes']; + readonly withdrawFlowKey: AutomationEngine['withdrawFlowKey']; +} + +/** The bodies of the "Flow registration" members of `AutomationEngine`: a stateless facet, called by the class's stubs. */ +export class RegistrationFacet { + /** + * @param armedFrom [ADR-0150 D3, epic #31527 child E5] Where `definition` + * comes from: the automation plugin's arming steps hand the precedence + * winner's classification (`resolveFlowPrecedence`) — `package` for the + * loader's own body, `override` for the shipping package's declared + * `.custom` override, `runtime` for an environment-authored row. Absent, + * the body is the caller's own — a write door's request body — and arms + * as `runtime`, unless it IS the parsed body this engine armed (a door + * putting back the definition it held), which keeps the arm it had. + * {@link armedFlowPackage} reads it. + */ + /** + * 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. + */ + static judgeFlowRegistration(this: Pick, 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). + const { parsed } = this.canonicalizeFlow(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 {@link registerFlow} and {@link + // sealNodeTypeVocabulary}). + + // [#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. + for (const check of this.registrationChecks({ advisory: true })) { + const refusal = check(name, parsed); + if (refusal) throw new Error(refusal.message); + } + return parsed; + } + + /** The body of `AutomationEngine#dryRun`; the method's docblock there is its contract. */ + static dryRun(this: Pick, 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)); + } + + /** The body of `AutomationEngine#registerFlow`; the method's docblock there is its contract. */ + static registerFlow(this: Pick, 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 + // under the slot's key. + const key = this.placeFlowSlot(name, arm); + + // Version history management + const history = this.flowVersionHistory.get(key) ?? []; + history.push({ + version: parsed.version, + definition: parsed, + createdAt: new Date().toISOString(), + }); + this.flowVersionHistory.set(key, history); + + // [#28405] The identity of the body as handed over — the stored body, + // for a flow the protocol serves — so it is the checksum the metadata + // history keys this version by. See {@link SuspendedRun.flowChecksum}. + const checksum = flowContentChecksum(definition); + if (checksum !== undefined) this.flowChecksums.set(parsed, checksum); + this.flowArms.set(parsed, arm); + this.flows.set(key, parsed); + // [#23316] Held now, so no longer refused — see {@link flowRefusals}. + if (this.loneSharedFlowKey(name) === undefined) this.flowRefusals.delete(name); + this.flowRefusals.delete(key); + // Enable/disable from the persisted deployment `status`. `obsolete`/`invalid` + // flows are DISABLED (unbound + guarded in execute); `draft`/`active` — and + // any legacy flow with no explicit status — stay enabled, so existing flows + // are unaffected (zero regression). This is how the Studio's on/off switch + // persists: it flips `status` active↔obsolete, applied on the next publish + // rebind. + // + // [ADR-0126 §7.2] Recording the STATUS dimension is now all this does. + // It used to also fold that dimension into the `flowEnabled` map and + // then work to preserve the OTHER dimension living in the same map — + // hence the old `wasStatusDisabled || !flowEnabled.has(name)` arm, + // whose job was to re-enable on a status flip without clobbering a + // runtime toggle. With the activation ledger holding the toggle + // dimension separately ({@link flowLedgerDisabled}) the two no longer + // share a slot, so there is nothing to reconcile: a status flip moves + // the status bit, a ledger flip moves the ledger bit, and + // {@link isFlowEnabled} composes them. That the reconciliation + // DISAPPEARS rather than moving is the sign the two were always + // distinct facts crammed into one map. + const flowStatus = (parsed as { status?: string }).status; + this.flowStatusDisabled.set(key, flowStatus === 'obsolete' || flowStatus === 'invalid'); + this.logger.info(`Flow registered: ${key} (version ${parsed.version})`); + + // ADR-0018 §M1 node-type check, inline — but ONLY once the vocabulary + // is closed (#4771). During boot the registry is still filling up + // (plugins contribute executors from their own init()/start(), which + // runs after the flow pull), so a verdict here would judge a world that + // has not finished forming — that is what warned about every showcase + // `approval` flow 0.8s before the `approval` executor existed. The + // authoritative boot pass runs in sealNodeTypeVocabulary(); after it, + // every later registration (Studio publish, dev reload, a runtime + // registerFlow) IS against a complete vocabulary, so it warns at once. + // Placed after the enable/disable resolution above so it can honor the + // same "a flow that cannot run cannot fail" rule as the audit. + if (this.nodeTypeVocabularySealed && this.isFlowEnabled(key)) { + const known = this.knownNodeTypes(); + const unknownTypes = this.unknownNodeTypes(parsed, known); + if (unknownTypes.length > 0) { + this.warnUnknownNodeTypes({ flowName: key, unknownTypes, knownTypes: [...known] }); + } + } + + // Re-bind in case the definition changed its trigger, then (re)activate. + // [ADR-0126 §7.2] A disabled flow — ledger or status — is NOT re-armed + // here, which is what makes the unbind survive a republish and a + // restart: the boot pull re-registers every flow, so a hydrated ledger + // row has to be able to keep a trigger unbound through exactly this + // path. The refusal is `activateFlowTrigger`'s own enablement gate, + // the one every arming path shares — ⛔ not re-asked here, where a + // caller-side check once stood alone and `registerTrigger` had none. + this.deactivateFlowTrigger(key); + this.activateFlowTrigger(key); + // [#20725, ADR-0126 §7.3] And the flows that call THIS one: a subflow + // republished `obsolete` disarms its packaged callers, republished + // `active` re-arms the ones the gate declined — both through the gate. + this.rejudgeSubflowCallers(key); + + // #12206 (Option A) — hand the caller the canonicalized flow this + // registration stored: the same object `this.flows` now holds and + // {@link getFlow} answers. The `/automation` write doors relay it, so + // a write answers the shape the subsequent read serves. + return parsed; + } + + /** The body of `AutomationEngine#unregisterFlow`; the method's docblock there is its contract. */ + static unregisterFlow(this: Pick, name: string): void { + // The body lives in ./flow-definitions.ts (#25222). + const host: ThisParameterType = { + flows: this.flows, + isPackagedFlow: (...a) => this.isPackagedFlow(...a), + packagedSubflowCallers: (...a) => this.packagedSubflowCallers(...a), + refuseUnderReachingCallers: (...a) => this.refuseUnderReachingCallers(...a), + withdrawFlow: (...a) => this.withdrawFlowKey(...a), + }; + const key = this.bareFlowKey(name); + if (key !== undefined) unregisterFlow.call(host, key); + } + + /** The body of `AutomationEngine#withdrawFlow`; the method's docblock there is its contract. */ + static withdrawFlow(this: Pick, name: string): void { + // [#31696] A bare name two slots hold is refused; one slot is + // withdrawn by {@link withdrawFlowSlot}. + const key = this.bareFlowKey(name); + if (key !== undefined) this.withdrawFlowKey(key); + } + + /** The body of `AutomationEngine#withdrawFlowSlot`; the method's docblock there is its contract. */ + static withdrawFlowSlot(this: Pick, packageId: string | null, name: string): void { + const key = this.flowSlots.keyOf(name, packageId); + if (key !== undefined) this.withdrawFlowKey(key); + } + + static withdrawFlowKey(this: Pick, name: string): void { + this.sharedSlotTriggerWarned.delete(name); + // The body lives in ./flow-definitions.ts (#25222). + const host: ThisParameterType = { + deactivateFlowTrigger: (...a) => this.deactivateFlowTrigger(...a), + flows: this.flows, + flowStatusDisabled: this.flowStatusDisabled, + flowVersionHistory: this.flowVersionHistory, + policyDisabledFlows: this.policyDisabledFlows, + subflowDeclinedFlows: this.subflowDeclinedFlows, + subflowNoticeDeclinedFlows: this.subflowNoticeDeclinedFlows, + subflowRegionDeclinedFlows: this.subflowRegionDeclinedFlows, + subflowRetryDeclinedFlows: this.subflowRetryDeclinedFlows, + flowRefusals: this.flowRefusals, + logger: this.logger, + }; + withdrawFlow.call(host, name); + // [#31696] The slot goes with its flow; a name left with one slot + // files it under the bare name again. [#33893] Not while the registry + // still holds the name under a disabled package (the re-sync of a + // disable withdraws its slot): the served holder keeps its key and + // its binding (amendment 7). + this.moveFlowRecords(this.flowSlots.remove(name)); + } + + /** The body of `AutomationEngine#recordFlowRefusal`; the method's docblock there is its contract. */ + static recordFlowRefusal(this: Pick, name: string, error: unknown): void { + // The body lives in ./flow-definitions.ts (#25222). + // [M1] Recorded beside a lone slot of a name the registry holds twice + // (another package's body), and that slot leaves its trigger. + const lone = this.loneSharedFlowKey(name); + const host: ThisParameterType = { + flows: lone === undefined ? this.flows : new Map(), + flowRefusals: this.flowRefusals, + }; + recordFlowRefusal.call(host, name, error); + if (lone !== undefined) this.deactivateFlowTrigger(lone); + // [#33893] A lone slot under its qualified key was armed while the + // co-holder was not yet registered; asked again, it takes the decline + // and says it. + if (lone !== undefined && lone !== name) this.activateFlowTrigger(lone); + } + + /** The body of `AutomationEngine#getFlowRegistration`; the method's docblock there is its contract. */ + static getFlowRegistration(this: Pick, name: string): FlowRegistration { + // [#31696] Registered while any slot holds the name. A slot key is + // no flow's name. + if (isSlotKeySpelling(name)) return { state: 'unregistered' }; + const refusal = this.flowRefusals.get(name); + const lone = refusal !== undefined && this.loneSharedFlowKey(name) !== undefined; + if (!lone && (this.flows.has(name) || this.flowSlots.keysOf(name).length > 0)) return { state: 'registered' }; + return refusal ? { state: 'refused', reason: { ...refusal } } : { state: 'unregistered' }; + } + + /** The body of `AutomationEngine#recordFlowShadowing`; the method's docblock there is its contract. */ + static recordFlowShadowing(this: Pick, record: FlowShadowingRecord): void { + if (!record.shadowed.length) return; + // [#31696] Filed under the armed contender's slot. + const holder = record.armed.holder ?? (record.armed.source === 'package' ? record.armed.packageId : undefined); + const keys = this.flowSlots.keysOf(record.name); + const key = (holder !== undefined ? this.flowSlots.keyOf(record.name, holder) : undefined) + ?? (keys.length === 1 ? keys[0] : record.name); + this.flowShadowing.set(key, record); + } + + /** The body of `AutomationEngine#getShadowedFlows`; the method's docblock there is its contract. */ + static getShadowedFlows(this: Pick): FlowShadowingRecord[] { + return [...this.flowShadowing.values()]; + } + + /** The body of `AutomationEngine#listFlows`; the method's docblock there is its contract. */ + static async listFlows(this: Pick): Promise { + return [...this.flows.keys()].map((key) => this.flowSlotName(key)); + } + + /** The body of `AutomationEngine#getFlow`; the method's docblock there is its contract. */ + static async getFlow(this: Pick, name: string): Promise { + const key = this.servedBareFlowKey(name); + return key === undefined ? null : this.flows.get(key) ?? null; + } + + /** The body of `AutomationEngine#getRunFlow`; the method's docblock there is its contract. */ + static getRunFlow(this: Pick, context: AutomationContext | undefined): FlowParsed | null { + const key = this.flowKeyOfRun(context); + return key === undefined ? null : this.flows.get(key) ?? null; + } + + /** The body of `AutomationEngine#flowKeyOfRun`; the method's docblock there is its contract. */ + static flowKeyOfRun(this: Pick, context: AutomationContext | undefined): string | undefined { + const key = flowRunKey(context); + if (key === undefined || this.flows.has(key)) return key; + const name = (context as { flowName?: unknown } | undefined)?.flowName; + if (typeof name !== 'string') return key; + return this.flowSlots.keyOf(name, flowRunPackage(context) ?? null) ?? key; + } + + /** The body of `AutomationEngine#getFlowSlot`; the method's docblock there is its contract. */ + static getFlowSlot(this: Pick, packageId: string | null, name: string): FlowParsed | null { + const key = this.flowSlots.keyOf(name, packageId); + return key === undefined ? null : this.flows.get(key) ?? null; + } + + /** The body of `AutomationEngine#getHeldFlow`; the method's docblock there is its contract. */ + static getHeldFlow(this: Pick, name: string): FlowParsed | null { + const key = this.bareFlowKey(name); + return key === undefined ? null : this.flows.get(key) ?? null; + } + + /** + * [#23317] What {@link registerFlow} judges a canonical flow by after the + * parse — every registration check, in the order it runs them. The ONE + * list: `registerFlow` throws the first refusal, and + * {@link registrationCheckRefusals} collects them all for the stored pass, + * so a check added here is refused at registration and previewed by + * `os migrate meta --stored` alike. + * + * `advisory` turns on the schema-aware expression pass, which logs and + * never refuses: registration runs it, the stored pass does not, so the + * doors that canonicalize without registering log nothing new. + */ + static registrationChecks( + this: Pick, + { advisory }: { advisory: boolean }, + ): ReadonlyArray<(flowName: string, flow: FlowParsed) => RegistrationCheckRefusal | undefined> { + // The body lives in ./flow-registration-checks.ts (#25222). + const host: ThisParameterType = { + validateNodeConfigKeys: (...a) => this.validateNodeConfigKeys(...a), + validateDecisionModes: (...a) => this.validateDecisionModes(...a), + validateFlowExpressions: (...a) => this.validateFlowExpressions(...a), + validateApiTriggerSecret: (...a) => this.validateApiTriggerSecret(...a), + refuseUnpackagedDefaultActive: (...a) => this.refuseUnpackagedDefaultActive(...a), + }; + return registrationChecks.call(host, { advisory }); + } + + /** + * ADR-0032 §Decision 1a — parse-validate every predicate in the flow at + * registration. Predicates are bare CEL; this catches the #1491 class + * (`{record.x}` template braces in a condition → CEL parse error) and any + * other malformed predicate LOUDLY, with the offending location + source + + * a corrective hint, instead of letting it fail silently at run time. + * + * Two families of surface are checked: + * + * 1. The *structural* predicates every flow has — start/node + * `config.condition` and `edge.condition`. Always bare CEL. + * 2. Every **descriptor-declared** bare-CEL slot named by + * `FLOW_NODE_EXPRESSION_PATHS` (#4027) — the ledger records the dialect + * each declared slot takes, and the `predicate` ones are checked here. + * + * (2) exists because assuming "node string fields are templates" is what let + * #3528 ship: `screen.fields[].visibleWhen` is declared *bare CEL*, this pass + * never traversed it, and an app authored it in the `{var}` template dialect + * its sibling config keys use. Nothing complained at any layer. The ledger is + * the declared list of such slots and is reconciled against the live + * descriptors by a test, so a newly declared expression key cannot go + * unvalidated again. + * + * Recording the dialect is what makes (2) safe rather than a regression: + * `{…}` is the #1491 brace-trap in a bare-CEL slot, and a `value` slot's + * expression is an envelope rather than a string. Until #19939 a third + * role recorded the single-brace `{var}` slots (`loop` / `map` + * `collection`), skipped because no validator implements that dialect; both + * are value slots now, and the role is gone. + * + * #1928 — when an object-schema resolver is wired ({@link setObjectSchemaResolver}), + * a second, schema-aware pass surfaces the checks `objectstack build` runs + * (unknown-field refs, likely bare-field typos, text/boolean fields misused + * in arithmetic) as ADVISORY warnings (logged, never thrown). Flow conditions + * bind the record's fields flat, so the schema pass uses `flattened` scope. + * The object they are typed against is the one the run binds: a + * time-relative flow's swept object, read off {@link deriveTriggerBinding} + * (#30396). + * The fatal set is unchanged by it but for one verdict: a flow VALUE + * envelope is typed with the same object where the run's `record` is that + * object's row — a record-triggered flow, or a time-relative sweep of the + * typed object, that rebinds neither `record` nor `previous` — and the date-text + * family it fails (#34451, {@link valueEnvelopeRefusals}) is thrown — in + * both modes, so the stored pass previews it. Any other flow's envelopes + * are judged untyped, as before. `advisory: false` skips the advisory pass: the stored pass + * previews refusals ({@link registrationCheckRefusals}), and an advisory + * finding is none. + * + * [#23317] The refusal is returned, not thrown: `registerFlow` throws it. + * Each failure is recorded with its site, so the stored pass lists it + * where the author wrote it. + */ + static validateFlowExpressions( + this: Pick, + flowName: string, + flow: FlowParsed, + { advisory }: { advisory: boolean }, + ): RegistrationCheckRefusal | undefined { + // The body lives in ./flow-registration-checks.ts (#25222). + const host: ThisParameterType = { + logger: this.logger, + objectSchemaResolver: this.objectSchemaResolver, + valueEnvelopeRefusals: (...a) => this.valueEnvelopeRefusals(...a), + deriveTriggerBinding: (...a) => this.deriveTriggerBinding(...a), + }; + return validateFlowExpressions.call(host, flowName, flow, { advisory }); + } + + /** + * Get the runtime type name of a value for schema validation. + */ + static getValueType(value: unknown): string { + if (Array.isArray(value)) return 'array'; + if (typeof value === 'object' && value !== null) return 'object'; + return typeof value; + } + + /** + * Validate node input schemas before execution. + * Checks that node config matches declared inputSchema if present. + * + * [#9889] The ONE definition-level input-schema chokepoint, called by BOTH + * attempt paths — `execute()` (attempt 1) and `executeWithoutRetry` (every + * retry attempt) — the same chokepoint discipline `seedRunVariables` + * carries for the variable environment (#9704). Its verdict is a pure + * function of the flow definition (`_variables` is deliberately unused), + * so a refusal on attempt 1 must hold on every attempt: when only + * `execute()` called it, `errorHandling.strategy: 'retry'` ran the very + * nodes attempt 1 refused to run. ⛔ A repair to the validation rules + * belongs HERE, in the shared method — re-inlining either caller's copy + * re-opens the execute/executeWithoutRetry drift this file has now paid + * for six times (#9378, #9415, #9414, #9510, #9704, #9889). + * + * [#10025] Throws {@link InputSchemaViolationError}, not a bare `Error`: + * because the verdict cannot change between attempts, the maintainer ruled + * the refusal NON-RETRYABLE (2026-08-20, Option B taken whole), and + * `execute()`'s catch needs a typed throw to classify it as the + * never-dispatched `FLOW_INPUT_SCHEMA_INVALID` exit without sniffing + * message prose. The chokepoint contract above is unchanged — both attempt + * paths still call this method identically; what changed is what + * `execute()` does with the throw. + */ + static validateNodeInputSchemas(this: Pick, flow: FlowParsed, _variables: Map): void { + for (const node of flow.nodes) { + if (node.inputSchema && node.config) { + for (const [paramName, paramDef] of Object.entries(node.inputSchema)) { + if (paramDef.required && !(paramName in (node.config as Record))) { + throw new InputSchemaViolationError( + `Node '${node.id}' missing required input parameter '${paramName}'`, + ); + } + const value = (node.config as Record)[paramName]; + if (value !== undefined) { + const actualType = this.getValueType(value); + if (actualType !== paramDef.type) { + throw new InputSchemaViolationError( + `Node '${node.id}' parameter '${paramName}' expected type '${paramDef.type}' but got '${actualType}'`, + ); + } + } + } + } + } + } +} diff --git a/packages/services/service-automation/src/engine-resume-facet.ts b/packages/services/service-automation/src/engine-resume-facet.ts new file mode 100644 index 00000000000..fc9e753e6ce --- /dev/null +++ b/packages/services/service-automation/src/engine-resume-facet.ts @@ -0,0 +1,676 @@ +// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#38667] Resume and suspension: persisting and claiming a suspended run, resume authority, the suspension chain, recovering the stored flow, screen input, bubbling a subflow child to its parent, and restore refusals: the bodies of + * `persistSuspendedRun`, `claimAdvance`, `resolveSuspendedNodeType`, + * `resolveDeclaredResumeAuthority`, `resolveSuspensionChainForCancel`, + * `hasSuspendedRun`, `unresumableSuspensionCause`, `recoverStoredFlow`, + * `heldFlowVersion`, `suspendedMapParentOf`, `suspensionOf`, + * `refuseInvalidScreenInput`, `buildSubflowResumeSignal`, `bubbleToParent`, + * `refuseRestore`, `getSuspendedScreen` + * moved out of `engine.ts` whole. + * + * A MOVE, not a redesign. {@link ResumeFacet} is a stateless facet of + * `AutomationEngine`: each static method of it is the body of the + * `AutomationEngine` method of the same name exactly as it stood, not + * re-indented, not formatted, not edited, with a `this` parameter added when + * the body reads the engine. The method stays on the class as a one-call stub + * with its signature, so the published declaration, an instance spy and a + * subclass override are what they were. A public method keeps its docblock on + * the class, the contract; a private method's docblock moved here with its + * body. The state stays on `AutomationEngine`. + * + * The bodies reach the engine through {@link ResumeHost}: exactly the + * `AutomationEngine` members they read, private ones included. Every stub + * hands its body, by a `.call`, the same host: `resumeHost` in + * `engine-facet-hosts.ts`, built once per engine by the class's static block. + * Methods go as closures that call them on the engine at call time, so a spy + * or a subclass override is still the one reached; fields go as getters, read + * when the body reads them, and a field a body assigns also goes with a setter + * that assigns it on the engine. + * + * The module imports `engine.ts` for types only, so the two modules form no + * evaluation cycle. `index.ts` re-exports nothing from this module. + */ + +import type { FlowParsed, ActionDescriptor, FlowRunSummary } from '@objectstack/spec/automation'; +import type { + AutomationContext, + AutomationResult, + ResumeSignal, + ScreenSpec, + ScreenFieldSpec, +} from '@objectstack/spec/contracts'; +import { + validateScreenInputs, + screenDeclaresInputContract, + declaredScreenFieldNames, + type ScreenFieldVisibility, +} from './screen-input-contract.js'; +import { carriedRefusalOfResult } from './inner-refusal.js'; +import type { DroppedFieldsEvent } from '@objectstack/spec/data'; +import { describeThrownForLog } from './thrown-cause-diagnostics.js'; +import { persistSuspendedRun } from './run-resume.js'; +import { flowRunPackage } from './flow-slots.js'; +import { MAX_CONSUMED_SUSPENSIONS } from './engine-run-log.js'; +import type { ChildRunRefusal } from './engine-signals.js'; +import { + ENGINE_BUILT_SIGNAL, + engineBuilt, + type SuspendedRun, + type SuspensionRestoreRefusal, + type SuspensionRestoreResult, + type SuspensionClaimOutcome, + type AdvanceClaim, +} from './engine-resume.js'; +import type { AutomationEngine } from './engine.js'; + +/** + * The `AutomationEngine` members the bodies of {@link ResumeFacet} read — every one + * of them, and no other. Each is typed AS the class member (an indexed access + * on the class), so a change to a member's signature on the class is a change + * here too. `readonly` members are the getters; the others are fields a body + * assigns. + */ +export interface ResumeHost { + readonly buildSubflowResumeSignal: AutomationEngine['buildSubflowResumeSignal']; + readonly cacheOnlySuspensions: AutomationEngine['cacheOnlySuspensions']; + readonly canonicalizeFlow: AutomationEngine['canonicalizeFlow']; + readonly evaluateCondition: AutomationEngine['evaluateCondition']; + readonly flowChecksums: AutomationEngine['flowChecksums']; + readonly flowHistorySource: AutomationEngine['flowHistorySource']; + readonly flowKeyNow: AutomationEngine['flowKeyNow']; + readonly flowVersionHistory: AutomationEngine['flowVersionHistory']; + readonly flows: AutomationEngine['flows']; + readonly loadSuspendedRun: AutomationEngine['loadSuspendedRun']; + readonly loadSuspendedRunStrict: AutomationEngine['loadSuspendedRunStrict']; + readonly logger: AutomationEngine['logger']; + readonly resolveCanonicalDescriptor: AutomationEngine['resolveCanonicalDescriptor']; + readonly resolveResumeTarget: AutomationEngine['resolveResumeTarget']; + readonly resumeInternal: AutomationEngine['resumeInternal']; + readonly store: AutomationEngine['store']; + readonly subflowParentStrands: AutomationEngine['subflowParentStrands']; + readonly suspendedRuns: AutomationEngine['suspendedRuns']; + readonly walkSuspensionChain: AutomationEngine['walkSuspensionChain']; + readonly warnAdvanceClaimDegraded: AutomationEngine['warnAdvanceClaimDegraded']; +} + +/** The bodies of the "Resume and suspension" members of `AutomationEngine`: a stateless facet, called by the class's stubs. */ +export class ResumeFacet { + /** + * Persist a suspended run to the in-memory cache and (best-effort) the + * durable store. A store failure does not fail the run — the in-memory copy + * still allows in-process resume; only cross-restart durability is lost. + * + * Logged at ERROR, not warn: a durable pause that silently stayed + * in-memory is data-loss-in-waiting. #4420 was exactly this — a store + * pointed at a table that was never created, every save failing into a warn + * nobody read, and every in-flight approval zombified by the next restart. + */ + static persistSuspendedRun(this: Pick, run: SuspendedRun): Promise { + // [ADR-0150 D8 row R8, #31696] The run names the package whose flow + // it runs, as stamped when it started, whatever key its slot is filed + // under by the time it pauses. + if (run.flowPackage === undefined) { + const flowPackage = flowRunPackage(run.context); + if (flowPackage !== undefined) run = { ...run, flowPackage }; + } + const filed = this.flowKeyNow(run.flowName); + if (filed !== run.flowName) run = { ...run, flowName: filed }; + // The body lives in ./run-resume.ts (#25222). + const readStore = () => this.store; + const host: ThisParameterType = { + suspendedRuns: this.suspendedRuns, + get store() { return readStore(); }, + cacheOnlySuspensions: this.cacheOnlySuspensions, + logger: this.logger, + }; + return persistSuspendedRun.call(host, run); + } + + /** + * [#14333] Claim the right to advance this run past the node it is parked + * at — the CROSS-REPLICA half of the resume idempotency guard. + * + * {@link resuming} is a per-PROCESS `Set`, which is a complete guard for + * exactly one deployment shape: a single process. Put two replicas behind + * a load balancer over one store and two decisions on one run arriving in + * the same instant each pass their OWN `resuming` check, both read the + * same fresh row through {@link loadSuspendedRunStrict}, both consume it, + * and both traverse forward — every downstream side effect runs twice. + * Measured on the two-engines-over-one-shared-store harness at 25/25 + * raced runs before this claim existed. + * + * So the decision is taken where the shared state lives: + * {@link SuspendedRunStore.claimSuspension} removes the row only if it is + * still parked at the node this replica read, atomically, and the loser is + * TOLD. `resuming` stays as the cheap first gate — it is not replaced, and + * it still refuses a same-process duplicate without any store round-trip. + * + * Four cases never reach the store, and each is a deliberate `unguarded`: + * - **no store** — nothing is shared, so there is no second replica to + * race and `resuming` is already the whole guarantee. Not a + * degradation: there is no cross-replica guarantee to weaken. + * - **a run the store never accepted** ({@link cacheOnlySuspensions}, + * #13617) — the store holds no row for it, so a compare-and-set would + * answer `lost` for a run that is legitimately resumable in this + * process, converting {@link persistSuspendedRun}'s documented + * degradation (a failed save costs cross-RESTART durability, not + * in-process resumability) into an unresumable run. + * - **a store without the member** — a third-party store predating it. + * - **a store answering `'unsupported'`** — one that cannot express the + * condition against its backing engine. + * + * The last two are announced once per engine rather than assumed silently, + * which is the whole difference between a degradation and a lie. + */ + static async claimAdvance(this: Pick, run: SuspendedRun): Promise { + const store = this.store; + if (!store) return { kind: 'unguarded' }; + if (this.cacheOnlySuspensions.has(run.runId)) return { kind: 'unguarded' }; + if (typeof store.claimSuspension !== 'function') { + this.warnAdvanceClaimDegraded('the attached suspended-run store has no claimSuspension()'); + return { kind: 'unguarded' }; + } + let outcome: SuspensionClaimOutcome; + try { + outcome = await store.claimSuspension(run.runId, { + nodeId: run.nodeId, + ...(run.correlation !== undefined ? { correlation: run.correlation } : {}), + }); + } catch (err) { + // Handed to the CALLER, so not a degradation and deliberately NOT a + // log site (AGENTS.md "Degradation log levels": a failure the + // requester was told about does not look normal from the outside). + // The envelope is the same STORE_UNAVAILABLE the strict load + // answers, for the same reason — existence is UNKNOWN, not "gone + // for good" (#4420). + // + // ⛔ What this branch may NOT claim is that the suspension was not + // consumed. A throw can arrive AFTER a committed delete — a dropped + // connection on the way back from a landed statement — so the one + // thing known here is that THIS resume did not continue the run. + // The result text says exactly that and no more; a retry is what + // resolves the ambiguity, answering RUN_NOT_FOUND if the row is in + // fact gone. + return { kind: 'unavailable', message: (err as Error).message }; + } + if (outcome === 'unsupported') { + this.warnAdvanceClaimDegraded("the attached suspended-run store answered 'unsupported'"); + return { kind: 'unguarded' }; + } + return outcome === 'claimed' ? { kind: 'claimed' } : { kind: 'lost' }; + } + + /** + * The registry type of the node a run is paused at: what the suspension + * recorded at pause time, falling back to the live flow definition for rows + * persisted before `nodeType` existed. Recorded-first on purpose — a flow + * republished mid-pause must not re-type the node out from under a run + * (see {@link SuspendedRun.nodeType}). + */ + static resolveSuspendedNodeType(this: Pick, run: SuspendedRun): string | undefined { + return run.nodeType ?? this.flows.get(run.flowName)?.nodes.find(n => n.id === run.nodeId)?.type; + } + + /** + * The authority a node type **declared**, following a deprecated ADR-0018 + * alias to its canonical type — `undefined` when nothing declared one. + * + * An alias's descriptor is synthesized by {@link registerNodeAlias} and does + * NOT copy the canonical's capabilities, so reading it directly would hand + * anyone who authors the old type name an ungated pause — the gate is + * declared and not enforced, one rename away. Resolving live (rather than + * snapshotting at alias-registration time) also keeps it correct whichever + * order the two register in. No alias of a pausing type exists today; this + * keeps it from becoming a hole the day one does. + * + * Split out from {@link resolveResumeAuthority} because since #5561 step two + * the two facts differ: a type that declared `'service'` and a type that + * declared nothing are both refused, but for opposite reasons, and the + * refusal has to say which (one is working as designed, the other is a + * missing one-line declaration). One walk, so the alias hop can never be + * implemented twice and drift. + */ + static resolveDeclaredResumeAuthority(this: Pick, nodeType: string): ActionDescriptor['resumeAuthority'] { + return this.resolveCanonicalDescriptor(nodeType)?.resumeAuthority; + } + + /** + * [#29333] {@link resolveSuspensionChain} for a caller that is about to + * CANCEL the chain, read through the STRICT loader + * ({@link loadSuspendedRunStrict}, the read {@link cancelRun} itself takes). + * + * The degrading walk answers a link it cannot read as "nothing suspended + * there" and stops, which is right for the incidental readers (the resume + * gate) and wrong for a cancel: the runs below that link are left parked + * and nothing at `error` says so. This walk stops at the same place but + * says WHY: `unreadable` names the link whose read threw, with the cause, + * so the caller can still cancel what it read and record the rest. A link + * that is simply not found ends the chain as it does in the degrading walk. + * + * Same walk, same bounds: only the loader differs. + */ + static async resolveSuspensionChainForCancel( + this: Pick, + runId: string, + ): Promise<{ chain: SuspendedRun[]; unreadable?: { runId: string; cause: unknown } }> { + let unreadable: { runId: string; cause: unknown } | undefined; + const chain = await this.walkSuspensionChain(runId, async (id) => { + try { + return await this.loadSuspendedRunStrict(id); + } catch (cause) { + unreadable = { runId: id, cause }; + return null; + } + }); + return unreadable ? { chain, unreadable } : { chain }; + } + + /** The body of `AutomationEngine#hasSuspendedRun`; the method's docblock there is its contract. */ + static async hasSuspendedRun(this: Pick, runId: string): Promise { + return (await this.loadSuspendedRunStrict(runId)) !== null; + } + + /** The body of `AutomationEngine#unresumableSuspensionCause`; the method's docblock there is its contract. */ + static async unresumableSuspensionCause(this: Pick, runId: string): Promise { + const run = await this.loadSuspendedRunStrict(runId); + if (!run) return undefined; + const target = await this.resolveResumeTarget(runId, run); + return 'cause' in target ? target.cause : undefined; + } + + /** + * [#28405] The stored version of flow `name` whose identity is `checksum`, + * read back through {@link setFlowHistorySource} and parsed the way + * {@link registerFlow} parses (the shared canonicalization, no arming and + * no registration checks: it executes one waiting run, it is not armed). + * `undefined` when no source is attached, nothing is stored under that + * identity, or the stored body no longer parses. REJECTS when the source + * does — see {@link FlowHistorySource}. + */ + static async recoverStoredFlow(this: Pick, name: string, checksum: string): Promise { + const source = this.flowHistorySource; + if (!source) return undefined; + const body = await source(name, checksum); + if (body === null || body === undefined) return undefined; + let parsed: FlowParsed; + try { + parsed = this.canonicalizeFlow(name, body).parsed; + } catch (err) { + this.logger.warn( + `[automation] the stored version of flow '${name}' with checksum ${checksum} no longer parses, so a ` + + `run that started on it cannot resume on it.`, + describeThrownForLog(err), + ); + return undefined; + } + // The identity it was found by, so a run resumed on it and paused + // again stays pinned to it. + this.flowChecksums.set(parsed, checksum); + return parsed; + } + + /** + * [#28405] A body this process registered under `name` whose identity is + * `checksum` — a code-loaded version, which has no history row (ADR-0009 + * §2.4) — or `undefined`. Read from {@link flowVersionHistory}, so it is + * lost on restart and on {@link withdrawFlow}. + */ + static heldFlowVersion(this: Pick, name: string, checksum: string): FlowParsed | undefined { + const versions = this.flowVersionHistory.get(name) ?? []; + for (let i = versions.length - 1; i >= 0; i--) { + const definition = versions[i].definition; + if (this.flowChecksums.get(definition) === checksum) return definition; + } + return undefined; + } + + /** The body of `AutomationEngine#suspendedMapParentOf`; the method's docblock there is its contract. */ + static async suspendedMapParentOf( + this: Pick, + itemRunId: string, + ): Promise<{ runId: string; flowName: string; nodeId: string; correlation?: string } | undefined> { + const item = await this.loadSuspendedRunStrict(itemRunId); + const ctx = item?.context as Record | undefined; + const parentRunId = ctx?.$parentRunId; + const mapNode = ctx?.$parentMapNode; + if (typeof parentRunId !== 'string' || !parentRunId) return undefined; + const parent = await this.loadSuspendedRunStrict(parentRunId); + if (!parent || parent.nodeId !== mapNode || parent.correlation !== `map:${itemRunId}`) return undefined; + return { runId: parent.runId, flowName: parent.flowName, nodeId: parent.nodeId, correlation: parent.correlation }; + } + + /** The body of `AutomationEngine#suspensionOf`; the method's docblock there is its contract. */ + static async suspensionOf( + this: Pick, + runId: string, + ): Promise<{ runId: string; flowName: string; nodeId: string; correlation?: string } | undefined> { + const run = await this.loadSuspendedRunStrict(runId); + if (!run) return undefined; + return { runId: run.runId, flowName: run.flowName, nodeId: run.nodeId, correlation: run.correlation }; + } + + /** + * Enforce a suspended `screen` node's declared field contract against the + * submitted bag, returning a refusal or `null` to allow (#4477). + * + * The render half of `screen` always worked — the trigger response and + * `GET …/runs/:runId/screen` carry `required` and `visibleWhen` intact, so + * a renderer had everything it needed. There was no validation half: + * `resume` accepted `{}` on a screen with an unconditional `required` + * field, accepted a visible conditional field's value being absent, and + * accepted keys the screen never declared — every one of them completing + * the run. A client that skipped the dialog and posted here directly was + * unconstrained by anything the flow author wrote. + * + * Scope, and the reasons for each edge: + * + * - **Only `signal.variables`.** That is the screen's collected-values + * channel (the executor surfaces `fields`, the runner posts `inputs`). + * `signal.output` is the node-OUTPUT namespace, lands under + * `${nodeId}.${key}`, and belongs to the approval-style resume envelope + * — a different contract, not this one's to police. + * - **Only a screen that declares fields** — see + * {@link screenDeclaresInputContract}. An object-form screen and a + * message-only screen declare no keys, so they constrain none (the same + * pass-through `enforceActionParams` gives a param-less action). + * - **Never an engine-built signal.** The subflow output mapping and the + * `map` item handoff are the engine's own continuations; they carry + * author-named output variables, not a screen submission. This is the + * ONLY exemption, and it is spelled once: an absent signal is not a + * case here — `resume` normalises it to `{}` (commit 7307191db) — because a bare + * `if (!signal)` beside the flag was a second, unnamed spelling of the + * same exemption that let `resume(runId)` skip every `required` the + * author wrote. + * + * `visibleWhen` is evaluated against the SUBMITTED values first (layered + * over the run's variables, so a predicate may reference a prior node), + * because a hidden field's `required` must not fire — that is #3528's + * dead-end reproduced server-side. An unevaluable predicate is reported and + * treated as hidden: the client decides what the user saw, and a broken + * predicate is not evidence a field was shown. + */ + static refuseInvalidScreenInput( + this: Pick, + run: SuspendedRun, + runId: string, + signal: ResumeSignal, + ): AutomationResult | null { + if ((signal as Record)[ENGINE_BUILT_SIGNAL] === true) return null; + if (!screenDeclaresInputContract(run.screen)) return null; + const fields = run.screen!.fields; + + const bag = (signal.variables ?? {}) as Record; + // Submitted values win over the snapshot: the predicate is about what + // the user is filling in NOW, and the run's variables only supply the + // wider context a `visibleWhen` may legitimately reference. + const scope = new Map(Object.entries(run.variables)); + for (const [k, v] of Object.entries(bag)) scope.set(k, v); + + const visibility = (field: ScreenFieldSpec): ScreenFieldVisibility => { + try { + return this.evaluateCondition(String(field.visibleWhen), scope, run.context); + } catch (err) { + // #6499 — BOTH spliced pieces were uncontrolled: the author's + // own `visibleWhen` source (metadata text of any shape) and + // the evaluator's thrown message (`evaluateCondition` composes + // a deliberately multi-line one). Both go to the structured + // slot; see `forgetSuspendedRun`'s catch above for the full + // mechanism (#6299). + // + // #4632 verdict: FUNCTIONAL — stays `warn`: one field's + // `required` is not enforced for one submission, the resume + // caller reads the outcome directly, and nothing + // claimed-persisted is involved. + this.logger.warn( + `[automation] run '${runId}': screen field '${field.name}' has a visibleWhen that could not be ` + + `evaluated — its \`required\` is not enforced for this submission. The predicate and the ` + + `evaluator's failure are in this record's meta.`, + { visibleWhen: String(field.visibleWhen), ...describeThrownForLog(err) }, + ); + return undefined; + } + }; + + const issues = validateScreenInputs(fields, bag, visibility); + if (!issues.length) return null; + + const declared = declaredScreenFieldNames(fields); + const summary = issues.map((i) => i.message).join('; '); + // #6654 — the issue messages embed USER-SUBMITTED keys + // (`validateScreenInputs`' `Unknown screen field "…"`, + // screen-input-contract.ts), which nothing constrains against + // newlines, so the findings ride the structured slot, never the + // message; see `forgetSuspendedRun`'s catch for the full mechanism + // (#6299). The returned INVALID_SCREEN_INPUT envelope below is + // caller-facing refusal text, not a log record — it keeps the summary + // (the envelope class is ruled elsewhere). #4632: FUNCTIONAL — stays + // `warn`. + this.logger.warn( + `[automation] refused resume of run '${runId}': screen '${run.nodeId}' input violates its declared ` + + `field contract — ${issues.length} issue(s); the field-level findings are in this record's meta.`, + { issues }, + ); + return { + success: false, + code: 'INVALID_SCREEN_INPUT', + error: + `Invalid screen input: ${summary} — declared fields: ` + + `${declared.map((n) => `'${n}'`).join(', ') || '(none)'}`, + // [#37526] The same findings, one entry per finding, so a runner can place + // each at its field in its own language rather than show `error`, + // which names the screen's declared fields for logs and API callers. + fields: issues.map(({ field, code, message }) => ({ field, code, message })), + }; + } + + /** + * Build the resume signal that maps a completed subflow child's output + * into its parent — mirroring the synchronous path exactly: the engine's + * standard `signal.output` merge lands it under `${subflowNodeId}.output`, + * and `signal.variables` writes the bare `config.outputVariable` when the + * child's context carries one (`$parentOutputVariable`). + */ + static buildSubflowResumeSignal(childContext: AutomationContext | undefined, childOutput: unknown): ResumeSignal { + const outVar = (childContext as Record | undefined)?.$parentOutputVariable; + // Engine-built: `outVar` is the author's `config.outputVariable`, so the + // reserved-name check would be a false positive on an oddly-named one. + return engineBuilt({ + output: { output: childOutput ?? null }, + ...(typeof outVar === 'string' && outVar + ? { variables: { [outVar]: childOutput ?? null } } + : {}), + }); + } + + /** + * Up-bubble for the subflow chain: when a TERMINAL run carries + * `$parentRunId`, resume that parent with this run's output. Recursion via + * the parent's own terminal exit bubbles multi-level chains. Best-effort — + * a failed parent continuation is logged, never thrown back at the + * caller who resumed the child. + * + * [#18714] "Terminal" is two outcomes, not one. The completion path was the + * only caller until this card, so a child that resumed to a REFUSAL left + * its parent parked at the awaiting node forever — visible in + * `listSuspendedRuns()`, resumable by nobody, because the child it waits on + * no longer exists. The refusal arm calls this with `refusal` set; every + * other thing this method does is identical on both outcomes. + * + * [#15556] Best-effort at the ENGINE layer only, since this call never + * throws either way: on the `'stranded'` exit — the one #15556's ruling + * names — it also records a {@link SubflowParentStrand} under the CHILD's + * own run id in {@link subflowParentStrands}, so the caller who resumed + * that child (`resumeInternal` returns before this method's caller sees + * anything beyond `success: true`) can retrieve it via + * {@link takeSubflowParentStrand} and tell its OWN caller the truth. The + * two tolerated arms below (`RESUME_IN_PROGRESS` / `STORE_UNAVAILABLE`) + * record nothing — #15556's ruling is scoped to the strand, and those two + * stay the functional degradation the old verdict already had right. + */ + static async bubbleToParent( + this: Pick, + run: SuspendedRun, + output: Record, + /** #4354 — this child's totals, credited to the parent's awaiting step. */ + summary?: FlowRunSummary, + /** + * [#18714] Set when this child finished `refused` rather than + * `completed`. Everything about the bubble is unchanged — the same + * mapped signal, the same best-effort contract, the same per-outcome + * #4632 grading below — except that the parent ends on the child's + * refusal instead of continuing past its awaiting node. Carried to + * {@link resumeInternal} as its own argument, ⛔ never folded into + * `sig`: the signal is the parent's variable map, and a refusal is + * control flow, not a variable. + */ + refusal?: ChildRunRefusal, + /** + * #33019 — this child's drop events (the ones its own terminal answer + * carries), credited to the parent's awaiting step beside `summary`. + */ + droppedFields?: readonly DroppedFieldsEvent[], + ): Promise { + const ctx = run.context as Record | undefined; + const parentRunId = ctx?.$parentRunId; + if (typeof parentRunId !== 'string' || !parentRunId) return; + try { + // A `map` child (ADR-0037 A2): hand the unit's output to the map + // node + flag the completion, so on re-entry it records this item + // and starts the next. A plain subflow child uses the 1:1 mapping. + const mapNode = ctx?.$parentMapNode; + const sig = typeof mapNode === 'string' && mapNode + // Engine-built: these ARE the reserved handoff keys, and this is + // the one writer allowed to set them (#3853 follow-up). + ? engineBuilt({ variables: { [`${mapNode}.$mapItemOutput`]: output ?? null, [`${mapNode}.$mapItemDone`]: true } }) + : this.buildSubflowResumeSignal(run.context, output); + const parentRes = await this.resumeInternal(parentRunId, sig, false, summary, refusal, droppedFields); + if (!parentRes.success) { + // #6499 — `parentRes.error` is the envelope field that carries + // a failing node's / driver's text VERBATIM (#5912 left it + // that way on purpose), so foreign newlines reach this message + // second-hand; it goes to the structured slot. See + // `forgetSuspendedRun`'s catch above for the full mechanism + // (#6299). + // + // [#15556] The #4632 verdict is taken PER OUTCOME here, graded + // by the engine's own discriminator and never by this seam's + // guess at what went wrong upstream. + // + // The old verdict was FUNCTIONAL for the whole arm, on this + // enumeration: "the parent either failed terminally (recorded + // in run history) or stays visibly parked and resumable". A + // reproduction of the composition the enumeration never + // covered — a parent parked at a `subflow` node whose child + // hosts an approval, resumed by the approvals decision door — + // measured a THIRD outcome: `resumeInternal` answers + // `{ success: false, status: 'stranded' }` (and no `code`), + // because the parent consumed its suspension and then threw + // downstream. That exit journals a repair snapshot and records + // the parent `failed`, so the parent is neither parked nor + // merely failed: nothing in the engine will ever move it again + // and only {@link restoreConsumedSuspension} can re-arm it. + // + // That is AGENTS.md's DURABILITY class verbatim — persisted + // state and runtime state disagree and nothing looks broken + // from the outside: the approval row is durably terminal, the + // child's own resume genuinely succeeded, and the decision + // door therefore answered its caller success. ⛔ And the rule's + // third legal answer (a failure handed to the CALLER is not a + // degradation) does NOT apply: measured, no caller is told. + // + // ⛔ Deliberately NOT the whole arm. `RESUME_IN_PROGRESS` (a + // replica is already advancing the parent) and + // `STORE_UNAVAILABLE` (the parent's suspension was not + // consumed, so it stays parked and the identical resume works + // once the store recovers) are exactly the functional cases + // the old verdict was right about, and escalating those is how + // `error` becomes unreadable. `status === 'stranded'` is the + // ONE exit that journalled a snapshot, so it is the one an + // operator can and must act on. + // + // #15556 family ruling (#16472, maintainer 2026-09-07, decision + // batch #76, option A): the LOG half stays exactly as it was + // (below, unchanged) — the door's status code does not move — + // and the strand is ALSO recorded here, under the CHILD's own + // run id, so `takeSubflowParentStrand` can hand it to whichever + // caller resumed that child. Not a widening of what this + // method tells ITS OWN caller (still `void`, still never + // thrown) — a sibling side-channel, read only by a caller that + // asks for it by name. + if (parentRes.status === 'stranded') { + this.subflowParentStrands.set(run.runId, { + runId: parentRunId, + repairable: true, + error: parentRes.error ?? 'unknown error', + // [#34638] The refusal the parent met, off its own + // result (`{}` when it met none) — so the caller that + // takes this strand tells WHY, not only THAT. + ...carriedRefusalOfResult(parentRes), + }); + while (this.subflowParentStrands.size > MAX_CONSUMED_SUSPENSIONS) { + const oldest = this.subflowParentStrands.keys().next().value; + if (oldest === undefined) break; + this.subflowParentStrands.delete(oldest); + } + // THIRD argument per the `Logger` contract + // (`error(message, error?, meta?)`); the `Error` slot stays + // empty on purpose (#5575). The message owes the two things + // AGENTS.md's durability rule asks of an `error`: the + // CONSEQUENCE, concretely, and the FIX. + this.logger.error( + `[automation] subflow run '${run.runId}' completed, but its parent run ` + + `'${parentRunId}' is STRANDED — the parent consumed its suspension and then failed ` + + `downstream, so no resume, timer or restart will move it again, while this child's ` + + `resumer (an approvals decision door, a wait timer) was told the resume SUCCEEDED and ` + + `nothing else reports the parent. Repair it with ` + + `restoreConsumedSuspension('${parentRunId}') and re-issue the continuation. The ` + + `parent's failure envelope is in this record's meta.`, + undefined, + { error: parentRes.error ?? 'unknown error', parentRunId, status: parentRes.status }, + ); + } else { + // #4632 verdict: FUNCTIONAL — stays `warn`, unchanged: on + // every other exit nothing claimed-persisted fails to land + // — the parent either failed terminally (recorded in run + // history) or stays visibly parked and resumable — and the + // child's own completion, which is what its resumer was + // told, is genuine. + this.logger.warn( + `[automation] subflow run '${run.runId}' completed but resuming parent '${parentRunId}' ` + + `failed — the parent's failure envelope is in this record's meta.`, + { error: parentRes.error ?? 'unknown error' }, + ); + } + } + } catch (err) { + // #6499 — thrown text to the structured slot; see + // `forgetSuspendedRun`'s catch above for the full mechanism + // (#6299). #4632 verdict: FUNCTIONAL — stays `warn`, the same + // consequence envelope as the branch above: the parent's + // suspension was either consumed with a recorded outcome or + // survives parked and resumable; nothing reads as success that + // is not. + this.logger.warn( + `[automation] subflow run '${run.runId}' completed but resuming parent '${parentRunId}' ` + + `threw — the thrown failure is in this record's meta.`, + describeThrownForLog(err), + ); + } + } + + /** Build a refusal from {@link restoreConsumedSuspension}. */ + static refuseRestore( + runId: string, + refusal: SuspensionRestoreRefusal, + reason: string, + ): SuspensionRestoreResult { + return { restored: false, runId, refusal, reason }; + } + + /** The body of `AutomationEngine#getSuspendedScreen`; the method's docblock there is its contract. */ + static async getSuspendedScreen(this: Pick, runId: string): Promise { + return (await this.loadSuspendedRun(runId))?.screen ?? null; + } +} diff --git a/packages/services/service-automation/src/engine-run-facet.ts b/packages/services/service-automation/src/engine-run-facet.ts new file mode 100644 index 00000000000..51c7ee85e8e --- /dev/null +++ b/packages/services/service-automation/src/engine-run-facet.ts @@ -0,0 +1,1084 @@ +// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#38667] Running a flow: the body checksum, executing a flow and its regions, retries, failing a run before its first node, and recording the run log: the bodies of + * `getFlowBodyChecksum`, `execute`, `failRunBeforeFirstNode`, `executeKey`, + * `runRegion`, `retryExecution`, `recordLog`, `compactStepsForHistory` + * moved out of `engine.ts` whole. + * + * A MOVE, not a redesign. {@link RunFacet} is a stateless facet of + * `AutomationEngine`: each static method of it is the body of the + * `AutomationEngine` method of the same name exactly as it stood, not + * re-indented, not formatted, not edited, with a `this` parameter added when + * the body reads the engine. The method stays on the class as a one-call stub + * with its signature, so the published declaration, an instance spy and a + * subclass override are what they were. A public method keeps its docblock on + * the class, the contract; a private method's docblock moved here with its + * body. The state stays on `AutomationEngine`. + * + * The bodies reach the engine through {@link RunHost}: exactly the + * `AutomationEngine` members they read, private ones included. Every stub + * hands its body, by a `.call`, the same host: `runHost` in + * `engine-facet-hosts.ts`, built once per engine by the class's static block. + * Methods go as closures that call them on the engine at call time, so a spy + * or a subclass override is still the one reached; fields go as getters, read + * when the body reads them, and a field a body assigns also goes with a setter + * that assigns it on the engine. + * + * The module imports `engine.ts` for types only, so the two modules form no + * evaluation cycle. `index.ts` re-exports nothing from this module. + */ + +import type { FlowParsed, FlowRegionParsed } from '@objectstack/spec/automation'; +import type { AutomationContext, AutomationResult } from '@objectstack/spec/contracts'; +import { runRecordFlowChecksum, stampRunFlowChecksum } from './run-flow-checksum.js'; +import { HeldValueCycleError } from './scope-key-segments.js'; +import { carriedRefusalOfResult, readCarriedRefusal, type CarriedRefusal } from './inner-refusal.js'; +import { summarizeRun } from './run-summary.js'; +import { withDroppedFields } from './run-dropped-fields.js'; +import { describeThrownForLog } from './thrown-cause-diagnostics.js'; +import { runRegion, startConditionHolds } from './dag-traversal.js'; +import { activeDryRunExecuteNode } from './dry-run.js'; +import { recordLog } from './run-history.js'; +import { isSlotKeySpelling, stampFlowRunSlot } from './flow-slots.js'; +import { stampRootRun } from './root-run.js'; +import { + MAX_PERSISTED_HISTORY_STEPS, + type StepLogEntry, + compactStepLogForHistory, + type ExecutionLogEntry, +} from './engine-run-log.js'; +import { buildRunTrigger } from './engine-run-trigger.js'; +import { isSuspendSignal, isRefusalSignal, InputSchemaViolationError } from './engine-signals.js'; +import { type SuspendedRun, activeMsAtPause, isTerminalRunStatus } from './engine-resume.js'; +import type { AutomationEngine } from './engine.js'; + +/** + * The `AutomationEngine` members the bodies of {@link RunFacet} read — every one + * of them, and no other. Each is typed AS the class member (an indexed access + * on the class), so a change to a member's signature on the class is a change + * here too. `readonly` members are the getters; the others are fields a body + * assigns. + */ +export interface RunHost { + readonly activeRecordFlows: AutomationEngine['activeRecordFlows']; + readonly cancelRun: AutomationEngine['cancelRun']; + readonly compactStepsForHistory: AutomationEngine['compactStepsForHistory']; + readonly consumedSuspensions: AutomationEngine['consumedSuspensions']; + readonly describeDisabledFlow: AutomationEngine['describeDisabledFlow']; + readonly entryFlowChecksums: AutomationEngine['entryFlowChecksums']; + readonly evaluateCondition: AutomationEngine['evaluateCondition']; + readonly executeKey: AutomationEngine['executeKey']; + readonly executeNode: AutomationEngine['executeNode']; + readonly executeWithoutRetry: AutomationEngine['executeWithoutRetry']; + readonly executionLogs: AutomationEngine['executionLogs']; + readonly failRunBeforeFirstNode: AutomationEngine['failRunBeforeFirstNode']; + readonly finishRefusedRun: AutomationEngine['finishRefusedRun']; + readonly flowCallerPackage: AutomationEngine['flowCallerPackage']; + readonly flowChecksumOf: AutomationEngine['flowChecksumOf']; + readonly flowKeyNow: AutomationEngine['flowKeyNow']; + readonly flowSlotPackage: AutomationEngine['flowSlotPackage']; + readonly flows: AutomationEngine['flows']; + readonly isFlowEnabled: AutomationEngine['isFlowEnabled']; + readonly logger: AutomationEngine['logger']; + readonly maxLogSize: AutomationEngine['maxLogSize']; + readonly nextRunId: AutomationEngine['nextRunId']; + readonly noteRunStarted: AutomationEngine['noteRunStarted']; + readonly persistSuspendedRun: AutomationEngine['persistSuspendedRun']; + readonly recordLog: AutomationEngine['recordLog']; + readonly renderFlowTerminalMessage: AutomationEngine['renderFlowTerminalMessage']; + readonly resolveFlowKey: AutomationEngine['resolveFlowKey']; + readonly resolveRunContext: AutomationEngine['resolveRunContext']; + readonly resolveSuspensionChainForCancel: AutomationEngine['resolveSuspensionChainForCancel']; + readonly retryExecution: AutomationEngine['retryExecution']; + readonly runSummaryLog: AutomationEngine['runSummaryLog']; + readonly seedRunVariables: AutomationEngine['seedRunVariables']; + readonly store: AutomationEngine['store']; + readonly validateNodeInputSchemas: AutomationEngine['validateNodeInputSchemas']; + readonly warnIfNodeTypeVocabularyNeverSealed: AutomationEngine['warnIfNodeTypeVocabularyNeverSealed']; +} + +/** The bodies of the "Running a flow" members of `AutomationEngine`: a stateless facet, called by the class's stubs. */ +export class RunFacet { + /** The body of `AutomationEngine#getFlowBodyChecksum`; the method's docblock there is its contract. */ + static getFlowBodyChecksum(this: Pick, flow: unknown): string | undefined { + return flow !== null && typeof flow === 'object' ? this.flowChecksumOf(flow as FlowParsed) : undefined; + } + + /** The body of `AutomationEngine#execute`; the method's docblock there is its contract. */ + static async execute(this: Pick, flowName: string, context?: AutomationContext): Promise { + const startTime = Date.now(); + // [ADR-0150 D3] The bare name resolves for the caller's package first: + // a run of package P's flow reaches P's own flow, else the one holder + // in P's declared dependency closure; anything else is refused with + // every candidate named, and nothing runs. Never dispatched, so no + // `status`, for the reason the disabled exit below states. + // [#31696] A name two packages hold resolves to the slot the caller + // reaches, the same way; a caller that reaches neither is refused. + // [#31696] A slot key is no flow's name: not found, as for any name + // this engine holds no flow of. + if (isSlotKeySpelling(flowName)) return { success: false, error: `Flow '${flowName}' not found` }; + const resolved = this.resolveFlowKey(flowName, this.flowCallerPackage(context)); + if ('refusal' in resolved) return { success: false, error: resolved.refusal.message }; + // [#33386] No served holder reaches the name: as for a flow this engine does not hold. + // [#33905] Nor does a disabled package's flow of a name it holds alone. + if ('absent' in resolved) return { success: false, error: `Flow '${flowName}' not found` }; + return this.executeKey(resolved.key, context, startTime); + } + + /** + * The answer {@link executeKey} gives a run that fails while its values + * are seeded, before its first node: a value it was handed contains itself + * ({@link HeldValueCycleError}), so the run cannot take its own copy. The + * failed-run shape of `execute()`'s failure exit — `status: 'failed'` + * (the run was dispatched and failed), `error`, `durationMs`, `summary`, + * `flowLabel` — with one `failed` history row, and no `errorMessage` + * (there are no run variables to render the author's text over). Never + * retried: the same value fails the same way on every attempt. + */ + static failRunBeforeFirstNode(this: Pick, run: { + runId: string; flowName: string; flow: FlowParsed; startedAt: string; startTime: number; + context: AutomationContext | undefined; error: string; + }): AutomationResult { + const { runId, flowName, flow, startedAt, context, error } = run; + const durationMs = Date.now() - run.startTime; + const steps: StepLogEntry[] = []; + let logged: ExecutionLogEntry | undefined; + try { + logged = this.recordLog({ + id: runId, + flowName, + flowVersion: flow.version, + status: 'failed', + startedAt, + completedAt: new Date().toISOString(), + durationMs, + waitMs: 0, + trigger: buildRunTrigger(context), + steps, + error, + }, context); + } catch (bookkeeping) { + // DURABILITY, so `error`, as at `execute()`'s failure exit: the + // caller is told the run failed, and the history row is lost. + this.logger.error( + `[Automation] run '${runId}' of flow '${flowName}' FAILED before its first node and its run-history ` + + `bookkeeping threw, so its terminal 'failed' row never landed — nothing retries the write, and ` + + `this run is invisible to the Runs surfaces. The caller was answered status 'failed' carrying ` + + `the run's error, so nothing needs re-driving on account of this line. Fix the history failure ` + + `in this record's meta.`, + undefined, + describeThrownForLog(bookkeeping), + ); + } + return { + success: false, + error, + durationMs, + status: 'failed', + flowLabel: flow.label, + summary: logged?.summary ?? summarizeRun(steps), + }; + } + + /** + * [#31696] {@link execute} for the flow filed under the slot key + * `flowName`, already resolved. Every record of the run is keyed by it. + */ + static async executeKey(this: Pick, flowName: string, context: AutomationContext | undefined, startTime: number): Promise { + const flow = this.flows.get(flowName); + // [#31696] Read with the flow, before any await: the slot's key can + // move while the run is in flight, its package cannot. + const runPackage = this.flowSlotPackage(flowName); + + if (!flow) { + return { success: false, error: `Flow '${flowName}' not found` }; + } + + // Check if flow is disabled. + // + // [ADR-0126 §7.2] THE consult point for the activation ledger. This is + // the one seam every entry path crosses (#11665 §2.3) — record-change, + // schedule, time-relative, api and subflow all arrive here — which is + // why the ADR puts the runtime refusal beside this guard instead of + // teaching each trigger its own check. + if (!this.isFlowEnabled(flowName)) { + // [#9415] NEVER DISPATCHED, and the producer says which kind — the + // remaining half of #9378's classification. `status` stays ABSENT + // here on purpose (see the `status: 'failed'` exit below): its + // absence is what proves the transport's 400 arm reads a verdict + // instead of guessing, so a later edit that stamps `'failed'` on + // this exit "for consistency" must fail a test. What the exit + // gained is a `code`, which is the classification's own channel. + // + // [ADR-0126 §7.2] The ledger refusal REUSES `FLOW_DISABLED` — ⛔ no + // new ADR-0112 ledger entry — so the distinction has to ride the + // MESSAGE. It is a real distinction to an operator: a status + // disable is an authoring state fixed in Studio, a ledger disable + // is an installation choice fixed by re-enabling the packaged + // flow, and the two have different remedies. + return { + success: false, + code: 'FLOW_DISABLED', + error: this.describeDisabledFlow(flowName), + }; + } + + // #4792 — a real run is about to start, so if the vocabulary was never + // sealed the ADR-0018 §M1 node-type check never ran on this engine at + // all. Say so once. Placed after the two guards above so the trigger is + // an execution and not a typo'd flow name (which is already loud) or a + // flow that cannot run. See the helper for why here and not earlier. + this.warnIfNodeTypeVocabularyNeverSealed(); + + // Re-entrancy loop guard KEY (see `activeRecordFlows`). Only the key is + // computed here; the CHECK itself lives downstream of the start-condition + // gate inside the `try` below, and that placement is load-bearing — see + // the guard block there (#8689). + const guardRecordId = (context?.record as { id?: unknown } | undefined)?.id; + const reentryKey = guardRecordId != null ? `${flowName}::${String(guardRecordId)}` : undefined; + // Set ONLY by the run that actually added `reentryKey` to the active set. + // The `finally` releases the key on this flag, never on `reentryKey` + // alone: a re-entrant dispatch now returns from INSIDE the try (the guard + // block below), and an unconditional delete there would release the key + // belonging to the OUTER run still on the stack — disarming the breaker + // for every later re-entry in that same cascade, which is precisely the + // runaway it exists to stop. + let reentryHeld = false; + + // Initialize the run's variable environment. Every binding a run is + // entitled to — the flow's declared variables, the trigger record and + // its flattened fields, `previous`, and the engine-owned `$runId` / + // `$flowName` / `$flowLabel` — is seeded by `seedRunVariables`, the one + // chokepoint `executeWithoutRetry` shares (#9704). See that helper for + // why the seeding is not written out here any more. + // + // The run id is minted BEFORE the seeding because `$runId` is part of + // that environment. Order-safe: `nextRunId()` is a stateless random id + // (no counter to advance), and nothing between the old call site and + // this one reads or mints one. + const runId = this.nextRunId(); + const startedAt = new Date().toISOString(); + const steps: StepLogEntry[] = []; + + // ADR-0049 / #1888 — establish the run's effective execution identity + // from flow.runAs (a COPY, never mutating the caller's context, so the + // elevation is scoped to this run and the caller's identity is restored + // when execute() returns). Surfaces the user-less fail-open (see helper) + // and resolves the triggering user's real grants for `runAs:'user'` (#3356). + // Also stamps `flowRunId` so this run's data writes are attributable to it + // (#3456). + let runContext: AutomationContext; + let variables: Map; + try { + runContext = await this.resolveRunContext(flow, context, runId); + // Seeded AFTER the context resolves, from the resolved context: its + // record is the run's own copy, carrying the lookups the start node + // declares (`expand`, grafted while the context resolves). + variables = this.seedRunVariables(flow, flowName, runContext, runId); + } catch (err) { + // A value the run is handed that contains itself (the record, + // `previous`) has no copy for the run to take: the run fails + // before its first node, answered in the failed-run shape below + // and recorded as such, never a throw out of `execute()`. Any + // other throw is unchanged. + if (!(err instanceof HeldValueCycleError)) throw err; + // [ADR-0162 Execution item 8] A run that fails before its first + // node is recorded as a failed run: it started. + this.noteRunStarted(context, runId); + return this.failRunBeforeFirstNode({ runId, flowName, flow, startedAt, startTime, context, error: err.message }); + } + stampFlowRunSlot(runContext, flowName, runPackage); + // [ADR-0162 item 7] The run's root run: itself, or its parent's. + stampRootRun(runContext, { runId, flowName, startedAt }); + // The body this run runs, by content: its own, never its parent's. + stampRunFlowChecksum(runContext, runId, this.flowChecksumOf(flow)); + + try { + // Find the start node + const startNode = flow.nodes.find(n => n.type === 'start'); + if (!startNode) { + // [#9415] Inside the `try`, but still a NEVER-DISPATCHED exit: + // nothing has executed at this point — the run id and the run + // context exist, no node does. Since #32273 registration + // refuses a flow with no `start` node, so no door can arm one + // and this is a defensive exit that none reaches: a trigger of + // such a stored flow finds no flow and answers `404`. The exit + // and its `422` mapping stay as a declared defensive path. No + // `status`, for the reason the disabled exit above states. + return { success: false, code: 'FLOW_NO_START_NODE', error: 'Flow has no start node' }; + } + + // Trigger-condition gate. The start node's `condition` is the predicate + // that decides whether the trigger event should launch this flow (e.g. + // `status == "done" && previous.status != "done"`). The engine — not the + // trigger — owns evaluating it, so every trigger type (record-change, + // schedule, …) and a manual `execute()` share one gate. Plain-string + // conditions are routed through CEL so bare field references resolve. + // + // The evaluator is shared with `executeWithoutRetry`, which re-runs + // this gate on every retry attempt: a condition that throws here + // is a fault the catch below hands to the error strategy, and + // under `strategy: 'retry'` each later attempt evaluates it again + // rather than running the nodes ungated (see `startConditionHolds`). + if (!startConditionHolds.call(this, startNode, variables, runContext)) { + this.logger.debug(`Flow '${flowName}' skipped: start condition not met`); + // `flowLabel` rides even here, unlike `successMessage` / + // `summary`: it names the flow, it claims no work done, and + // this answer reaches a runner as a 200 like any other. + return { success: true, output: { skipped: true, reason: 'condition_not_met' }, flowLabel: flow.label }; + } + + // Re-entrancy loop guard (see `activeRecordFlows`). Breaks the SAME + // flow re-firing for the SAME record while a prior execution is still + // active — a self-trigger cascade whose start condition is genuinely + // true on every pass (the 2026-07-06 incident: a `boolean` persists as + // integer 1 on SQLite/libsql and CEL `1 != true` is true, so + // `is_escalated != true` never tripped) would otherwise loop forever + // and wedge the caller, fatally mid seed. + // + // #8689 — this check sits AFTER the start-condition gate above, and + // the order is the contract, not a detail. The declared behaviour is + // "a record-change flow fires only when its start condition is true", + // and that has to hold on the re-entrant dispatch a flow's OWN write + // causes — it cannot if the breaker returns first, because then the + // gate is never reached on that dispatch at all. Measured before the + // reorder, on the real kernel (a `record-after-update` flow guarded on + // `record.status != "escalated"` whose data node writes + // `status = "escalated"`): TWO dispatches for the record, exactly ONE + // start-condition evaluation, and one breaker WARN. So the author's + // guard was never what stopped the loop — the breaker was, and its own + // message said so. The re-entrant dispatch already carries the + // POST-write row, so evaluating first suppresses it with + // `condition_not_met` and the breaker returns to being a backstop. + // + // The breaker is UNCHANGED in strength (deliberately — a stronger + // breaker is not the repair): a condition that really is true on + // re-entry still lands here, at the same depth, with the same WARN and + // the same skip envelope. What changed is that reaching it now MEANS + // something — the condition was evaluated and returned true — which is + // why the message can state that as fact. + if (reentryKey && this.activeRecordFlows.has(reentryKey)) { + // #6654 — the record id is CALLER data (nothing schema-constrains + // it against newlines), so it rides the logger's structured slot, + // never the message; see `forgetSuspendedRun`'s catch for the full + // mechanism (#6299). #4632: FUNCTIONAL — stays `warn` (the run is + // deliberately skipped and the caller reads the skip envelope). + this.logger.warn( + `[automation] flow '${flowName}' re-entered for the same record while still running — breaking ` + + `self-trigger loop; the triggering record's id is in this record's meta. Its start condition ` + + `WAS evaluated on this re-fire and returned true, so the guard as authored does not exclude ` + + `the flow's own write-back; if it guards on a boolean field (e.g. \`is_escalated != true\`), ` + + `note booleans persist as 0/1 on SQLite/libsql and CEL \`1 != true\` is true.`, + { recordId: String(guardRecordId) }, + ); + return { success: true, output: { skipped: true, reason: 'reentrancy_loop_guard' }, flowLabel: flow.label }; + } + if (reentryKey) { + this.activeRecordFlows.add(reentryKey); + reentryHeld = true; + } + // [ADR-0162 Execution item 8] Past both gates the run is dispatched + // and leaves a history row whatever it ends in. Neither skip above + // records one, so neither names a run here ({@link runStartedFor}). + this.noteRunStarted(context, runId); + + // Validate node input schemas before execution. [#9889] The same + // call sits in `executeWithoutRetry` — every retry attempt must be + // refused by the same guard that refused attempt 1; see the guard's + // own doc for the chokepoint contract. + this.validateNodeInputSchemas(flow, variables); + + // DAG traversal execution + await this.executeNode(startNode, flow, variables, runContext, steps); + + // Collect output variables + const output: Record = {}; + if (flow.variables) { + for (const v of flow.variables) { + if (v.isOutput) { + output[v.name] = variables.get(v.name); + } + } + } + + const durationMs = Date.now() - startTime; + + // [#16274] THE RUN IS OVER AND IT SUCCEEDED. Everything from here + // to the return is BOOKKEEPING ABOUT that fact, and the `catch` + // below this `try` exists for NODE failures — so a throw out of the + // history write was handled as though a node had thrown: the arm + // recorded a `failed` row carrying the history driver's own text as + // the run's error and answered `status: 'failed'` for a run whose + // every node succeeded. This is the guard PR #16273 landed on + // {@link resumeInternal}'s completion path, now on the two + // INITIAL-execution paths that card deliberately scoped out — this + // one and {@link executeWithoutRetry}'s. + // + // ⚠️ MEASURED, and sharper than the report assumed: under + // `errorHandling.strategy: 'retry'` that false `failed` is handed + // to {@link retryExecution} by the strategy branch in the catch + // below, whose loop reads `result.success` — so it RE-EXECUTES a + // flow that already finished. `1 + maxRetries` runs of every node, + // unattended, inside this one call, with the side effects repeated + // each time and one `failed` history row per attempt. That is the + // DOUBLE RUN #15944 was graded sharp for, reached here with no + // operator action at all, where #15944's needed an operator to + // restore and resume. + // + // Two statements inside `recordLog` reach that catch on the + // terminal path, and neither is hypothetical: + // + // 1. the run-summary line `this.logger.info(line, meta)` — on by + // default (`runSummaryLog: 'info'`) and calling a + // HOST-INJECTED `Logger`, so it needs no store at all; + // 2. `store.recordTerminal(record)` throwing SYNCHRONOUSLY — the + // `void write.catch(...)` beneath that call only ever sees a + // returned promise's rejection (both shipped stores are + // `async` and cannot; `SuspendedRunStore` is an exported + // interface with an optional `recordTerminal`, so a host store + // is unconstrained, and one returning a non-thenable makes + // `write.catch` itself a synchronous `TypeError`). On THAT + // variant the unguarded code did not even answer `failed`: the + // catch arm's own `recordLog({ status: 'failed' })` threw again + // out of the same store and escaped `execute()` entirely, + // rejecting a promise `AutomationResult` is declared for. + // + // The guard restores the invariant `recordLog`'s own doc states — + // "a history write must NEVER block or break the run that produced + // it" — which that call was relied upon to keep and did not. + // + // ⛔ NOT a widening of anything: no exit gains a status it did not + // have, the node-failure arm below is untouched (a genuine node + // throw still lands there, still records `failed`, still retries), + // and the failure is REPORTED rather than swallowed — see the + // catch. + let logged: ExecutionLogEntry | undefined; + try { + logged = this.recordLog({ + id: runId, + flowName, + flowVersion: flow.version, + status: 'completed', + startedAt, + completedAt: new Date().toISOString(), + durationMs, + // [#32284] The initial execution never paused: a measured 0. + waitMs: 0, + trigger: buildRunTrigger(context), + steps, + output, + }, context); + } catch (bookkeeping) { + // #4632 verdict: DURABILITY, so `error` — the caller is told + // the truthful thing (the run completed), which is exactly + // what makes the rest invisible from the outside: the terminal + // history row never landed, nothing retries it, and no + // envelope carries a word about it. Consequence and fix in the + // first line, per AGENTS.md. Said ONCE per run, not once per + // failed write. + // + // ⚠️ The level is the precedent's (#16273, #15555) and is NOT + // a raise under the published-sink ruling (commit e238c79f0): that ruling forbids raising a site to + // `error` where doing so means GROWING `error?` onto a + // published sink that lacks it, and this sink — `Logger` from + // `@objectstack/spec/contracts` — declares `error(message, + // error?, meta?)` as a REQUIRED member (only `fatal?`, + // `child?` and `withTrace?` are optional). Nothing is widened, + // which is also why the two precedents on this same sink could + // land `error`. + // + // THIRD argument per `error(message, error?, meta?)`; the + // `Error` slot stays empty on purpose (#5575), and the thrown + // text goes to the structured slot rather than into the + // message (#6499). + this.logger.error( + `[Automation] run '${runId}' of flow '${flowName}' COMPLETED successfully but its ` + + `run-history bookkeeping threw, so its terminal history row never landed — nothing ` + + `retries it, the caller is told the run succeeded, and after the next restart this ` + + `run is invisible to the Runs surfaces while the approvals sweeps read it as ` + + `never-finished. The run itself is COMPLETE and must NOT be re-run or retried. Fix ` + + `the history failure in this record's meta.`, + undefined, + describeThrownForLog(bookkeeping), + ); + } + // [#16274] Recomputed when the guard above had to abandon + // `recordLog`: the same pure function of the same steps that + // `recordLog`'s own first statement runs, so the two spellings + // cannot disagree. Same shape as `resumeInternal`'s (#15944). + const summary = logged?.summary ?? summarizeRun(steps); + + return { + success: true, + output, + durationMs, + // [#9414] The flow author's own completion text, on the exit + // every TRIGGERED run leaves through. `AutomationResult` + // declares this pair as a general terminal-result feature — + // "`successMessage` is set on terminal success, `errorMessage` + // on failure" — but `resumeInternal` was the only producer, so + // the author's words reached a caller only when the run + // happened to pause and be resumed. A flow dispatched straight + // through `POST /api/v1/automation/:name/trigger` (or the + // legacy `trigger/:name` the SDK calls) carried nothing. Same + // declaration, two behaviours decided by ROUTE rather than by + // authoring — the shape ADR-0049's enforce-or-remove exists to + // stop, and this is the restoration half of it, not a new key. + // + // ⚠️ TERMINAL exits only, which is the whole boundary. The + // paused return below carries neither (the run has not + // finished; `resumeInternal` stamps the message when it later + // ends). Neither do the SKIP exits above — `condition_not_met` + // and `reentrancy_loop_guard` return `success: true` for a run + // that executed no node, so stamping "Opportunity created!" on + // one would be a toast about work nobody did. They carry no + // `summary` for exactly the same reason. + // + // [#28054] Rendered, not copied: a `{{ }}` template over the + // variables the run finished with, in the run's locale. + successMessage: this.renderFlowTerminalMessage( + flowName, 'successMessage', flow.successMessage, variables, runContext, + ), + // The authored flow name for the runner header and the + // completion toast — on EVERY evaluation's result, paused and + // terminal alike (see `AutomationResult.flowLabel`). + flowLabel: flow.label, + // #4354 — hand the counts back synchronously so a caller + // (a `subflow` roll-up, a runtime test asserting the sweep wrote + // something) never has to re-read the run to learn what it did. + summary, + // #32861 — the values a write step did not store, so the door + // that started the run can tell its caller. Omitted when none. + ...withDroppedFields(steps), + }; + } catch (err: unknown) { + // [#15788] The run REFUSED — an `end` node declaring + // `outcome: 'refused'`, or (#18110 / #18555) a node whose own child + // run refused. Tested FIRST, beside the + // pause and for the same reason: this is NOT a failure either, and + // a signal recognised only by the arm below would be recorded as + // one. The shape is `finishRefusedRun`'s — one method, all three + // producers. + if (isRefusalSignal(err)) { + return this.finishRefusedRun({ + runId, flowName, flowVersion: flow.version, + startedAt, durationMs: Date.now() - startTime, waitMs: 0, + steps, flow, variables, + refusalMessage: err.message, context, + }); + } + // A node asked to suspend the run (ADR-0019 durable pause). Snapshot + // the live state, record a `paused` log, and return the run id so the + // caller can later `resume()` it. This is NOT a failure. + if (isSuspendSignal(err)) { + const durationMs = Date.now() - startTime; + // [#32284] The run's first pause: nothing waited yet, so all + // of `durationMs` was execution — the clock the resume reads. + const waitMs = 0; + // #7639 — ONE snapshot expression feeding BOTH consumers: the + // continuation the run will resume from, and the `paused` log + // entry run-detail serves. Same object, so what an operator + // reads can never disagree with what the run holds. See + // {@link ExecutionLogEntry.variables} for why the log carries it. + const variablesSnapshot = Object.fromEntries(variables); + await this.persistSuspendedRun({ + runId, + flowName, + flowVersion: flow.version, + flowChecksum: this.flowChecksumOf(flow), + nodeId: err.nodeId, + nodeType: err.nodeType, + variables: variablesSnapshot, + steps, + context: runContext, + startedAt, + startTime, + activeMs: activeMsAtPause(durationMs, waitMs), + correlation: err.correlation, + screen: err.screen, + }); + this.recordLog({ + id: runId, + flowName, + flowVersion: flow.version, + status: 'paused', + startedAt, + durationMs, + waitMs, + trigger: buildRunTrigger(context), + steps, + variables: variablesSnapshot, + }, context); + return { + success: true, + status: 'paused', + runId, + durationMs, + screen: err.screen, + flowLabel: flow.label, + }; + } + + const errorMessage = err instanceof Error ? err.message : String(err); + + // Record failed execution log + const durationMs = Date.now() - startTime; + // [#17562] THE RUN IS OVER AND IT FAILED, and this `catch` IS the + // handler for that failure — there is no outer one. So a throw out + // of THIS history write escaped `execute()` entirely and left it a + // REJECTED PROMISE, where its declared return type is an + // `AutomationResult`. The FAILURE-arm half of the guard #16274 + // landed on the completion arm of this same method, and the same + // shape #15555 landed on {@link resumeInternal}'s failure arm. + // + // ⚠️ What is lost is the SHAPE, not the verdict — which is why this + // is a narrower defect than #16274's and still a contract + // violation. The run genuinely failed, so nothing misleads an + // operator: no false `failed`, no double run. But the caller that + // branches on `{ success: false, status: 'failed' }` gets an + // exception instead, so the transport's `status` arm (#9378) is + // bypassed and `errorMessage` (#9414) and `summary` (#4354) never + // arrive — a REST route or SDK caller sees a 500-class throw for a + // run that had a perfectly good failure envelope waiting, and the + // NODE's own error text is replaced by the history driver's. + // + // The two statements inside `recordLog` that reach here are the + // ones stated at the completion site above: the default-on + // run-summary line `this.logger.info(line, meta)` calling a + // HOST-INJECTED `Logger`, and `store.recordTerminal(record)` + // throwing SYNCHRONOUSLY — which the `void write.catch(...)` + // beneath that call cannot see, because it only ever observes a + // RETURNED promise's rejection. + // + // The guard restores the invariant `recordLog`'s own doc states — + // "a history write must NEVER block or break the run that produced + // it" — which this call was relied upon to keep and did not. + // + // ⛔ NOT a widening of this arm's meaning: the suspend arm above, + // the `InputSchemaViolationError` refusal below and the + // `strategy: 'retry'` branch are all untouched, a genuine node + // failure still records `failed` with the node's own text, and the + // retry budget is unchanged — pinned by two controls. + let logged: ExecutionLogEntry | undefined; + try { + logged = this.recordLog({ + id: runId, + flowName, + flowVersion: flow.version, + status: 'failed', + startedAt, + completedAt: new Date().toISOString(), + durationMs, + waitMs: 0, + trigger: buildRunTrigger(context), + steps, + error: errorMessage, + }, context); + } catch (bookkeeping) { + // #4632 verdict: DURABILITY, so `error` — the caller is told a + // truthful thing (the run failed, with the node's own text), + // which is exactly what makes the rest invisible from the + // outside: the terminal history row never landed, nothing + // retries it, and no envelope carries a word about it. + // Consequence and fix in the first line, per AGENTS.md. Said + // ONCE per abandoned write. + // + // ⚠️ NOT the rule's third answer ("a failure handed to the + // CALLER is not a degradation at all"): what is handed to the + // caller is the NODE's failure. The bookkeeping failure is + // handed to nobody, and it is a durability loss — which is why + // `recordLog` is in `DURABILITY_CRITICAL_CALLEES`. + // + // ⚠️ The level is the precedent's (#15555, #16273, #16274) and + // is NOT a raise under the published-sink ruling (commit e238c79f0): that ruling forbids raising a + // site to `error` where doing so means GROWING `error?` onto a + // published sink that lacks it, and this sink — `Logger` from + // `@objectstack/spec/contracts` — declares `error(message, + // error?, meta?)` as a REQUIRED member. Nothing is widened and + // no sink type changes in this diff. + // + // THIRD argument per `error(message, error?, meta?)`; the + // `Error` slot stays empty on purpose (#5575), and the thrown + // text goes to the structured slot rather than into the message + // (#6499). + this.logger.error( + `[Automation] run '${runId}' of flow '${flowName}' FAILED and its run-history ` + + `bookkeeping threw, so its terminal 'failed' row never landed — nothing retries the ` + + `write, and after the next restart this run is invisible to the Runs surfaces while ` + + `the approvals sweeps read it as never-finished. The run's OWN failure IS reported: ` + + `the caller was answered status 'failed' carrying the node's error, so nothing ` + + `needs re-driving on account of this line. Fix the history failure in this record's ` + + `meta.`, + undefined, + describeThrownForLog(bookkeeping), + ); + } + + // [#10025] NEVER DISPATCHED, ruled NON-RETRYABLE (maintainer, + // 2026-08-20, Option B taken whole). The guard's verdict is a pure + // function of the flow definition — `validateNodeInputSchemas` + // deliberately ignores its variables parameter — so attempt 2 + // cannot answer differently than attempt 1, and handing this throw + // to `retryExecution` below would burn the whole retry budget + // (backoff delays included) re-deriving a certainty into + // 1 + maxRetries identical failed rows. Short-circuiting HERE, + // before the strategy branch, is the ruling's whole content: + // `strategy: 'retry'` changes nothing about this exit, and the ONE + // failed row recorded above is the run history's entire account of + // the refusal. + // + // The envelope matches its never-dispatched siblings + // (`FLOW_DISABLED`, `FLOW_NO_START_NODE` — #9378/#9415): a `code` + // and NO `status`, whose absence is the discriminator the + // transport's 422 arm reads (see the `status: 'failed'` exit + // below). No `errorMessage` / `summary` either — those are a RUN's + // artefacts, and no node executed. + // + // The #9889 parity floor underneath is UNTOUCHED: the guard is + // still called identically by both attempt paths, so if any route + // ever reaches `executeWithoutRetry` without crossing this catch, + // the refusal still fires — just without this classification. + // This arm decides what `execute()` does with the verdict; it + // never weakens who renders it. + if (err instanceof InputSchemaViolationError) { + return { + success: false, + code: 'FLOW_INPUT_SCHEMA_INVALID', + error: errorMessage, + }; + } + + // Error handling strategy. + // + // [#9510] ⚠️ This handoff can now return a NON-TERMINAL result: a + // retry attempt that reaches a pausing node comes back as + // `{ success: true, status: 'paused', runId }` — the same shape the + // suspend arm above returns — and `execute()` forwards it + // unchanged, so its contract is ONE answer per situation rather + // than one per attempt number. Deliberate, not incidental: a caller + // branching on `status` sees no difference between a pause on + // attempt 1 and a pause on attempt 3, which is what + // `AutomationResult` already promises. + // + // ⚠️ The `runId` that comes back is then the PAUSED ATTEMPT's, not + // this failed first attempt's. They are different runs with + // different log rows, and the paused one is the key + // `persistSuspendedRun` stored the continuation under — so it is + // the only id `resume()` can be called with. + if (flow.errorHandling?.strategy === 'retry') { + return this.retryExecution( + flowName, context, startTime, flow.errorHandling, flow.errorMessage, flow.label, + ); + } + return { + success: false, + error: errorMessage, + durationMs, + // [#9378] RAN AND FAILED, said by the producer that knows — + // the same lifecycle verdict this exit just wrote to the run + // log two statements up, now also on the result. + // + // Load-bearing, not decoration: `execute()` has four OTHER + // `success: false` exits that never dispatched anything (flow + // not found, flow disabled, no start node, and the + // input-schema refusal in the arm above), and a transport + // cannot tell them from this one without either a message + // regex or sniffing `summary` / `durationMs` — the + // tolerant-consumer shape PD #12 forbids, and the one #8684 + // deliberately did not reproduce on the resume route. Those + // four exits carry NO `status`, this one carries `'failed'`, + // so "the run dispatched and was rejected" is a fact the route + // reads rather than infers. + // + // [#9415] Three of those four now also carry a `code` + // (`FLOW_DISABLED`, `FLOW_NO_START_NODE`, and #10025's + // `FLOW_INPUT_SCHEMA_INVALID`) so the transport can + // answer them 409/422 instead of 200. That did NOT retire the + // rule above — it sharpened it. The `status` absence is still + // the discriminator this arm is read by, and it is the reason + // the never-dispatched exits must never acquire `status`: a + // tidy-up that stamped `'failed'` on all of them would put + // every refusal back on this 400 arm, silently. + // + // `status` and not a `code`, and that division SURVIVED the + // union widening: #9415 added `'FLOW_DISABLED'` / + // `'FLOW_NO_START_NODE'` for the two never-dispatched exits, + // and this exit still classifies with `status` alone. The two + // fields answer different questions — `code` says WHY a + // dispatch was refused, `status` says how a run that started + // ended — and a run that reached here has no refusal to name. + // `status?: 'completed' | 'paused' | 'failed'` is declared, + // documented as the run's lifecycle verdict, and already the + // value recorded in the log. + status: 'failed', + // [#9414] The author's failure text, BESIDE the raw `error` + // rather than instead of it. The transport folds `error` into + // the ADR-0112 message and carries this one in + // `error.details.errorMessage` — the single place the console + // reads it from (objectui `flowResponse.ts`, PR #4899). The + // envelope has no `data`, so a producer that leaves this absent + // does not degrade to a plainer toast: the consumer falls back + // to the raw node error text, which is what every non-screen + // flow showed until now. + // + // [#28054] Rendered over the variables at the failure point + // (`$error` included), in the run's locale. + errorMessage: this.renderFlowTerminalMessage( + flowName, 'errorMessage', flow.errorMessage, variables, runContext, + ), + flowLabel: flow.label, + // A failed run's counts matter MORE, not less: they say how far + // it got before dying — how many rows it had already written. + // [#17562] Recomputed when the guard above had to abandon + // `recordLog`: the same pure function of the same steps that + // `recordLog`'s own first statement runs, so the two spellings + // cannot disagree. Same shape as #15555's. + summary: logged?.summary ?? summarizeRun(steps), + // [#24914, ruling B′] The refusal the failing node's data call met, + // beside the unchanged `error`: `userMessage` / `innerRefusal`, read + // off the brand the node's throw carries (`inner-refusal.ts`) — `{}` + // for a throw that met none, so nothing is invented. + ...readCarriedRefusal(err), + }; + } finally { + // Release the re-entrancy guard for this (flow, record). Runs before + // the returned promise settles, so an error-retry re-run (whose inner + // execute happens after its own await) is not falsely blocked. + // + // Gated on `reentryHeld`, NOT on `reentryKey` (#8689): since the guard + // check moved below the start-condition gate, a run can now leave this + // try WITHOUT owning the key — the re-entrant dispatch that tripped the + // breaker, and a condition-not-met skip. Deleting then would release + // the OUTER run's key and disarm the breaker mid-cascade. + if (reentryHeld && reentryKey) this.activeRecordFlows.delete(reentryKey); + } + } + + /** The body of `AutomationEngine#runRegion`; the method's docblock there is its contract. */ + static runRegion( + this: Pick, + region: FlowRegionParsed, + variables: Map, + context: AutomationContext, + grouping?: { parentNodeId: string; iteration?: number; branch?: number; regionKind?: string; retryAttempt?: number }, + 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: dryExecuteNode ?? ((...a) => this.executeNode(...a)), + resolveSuspensionChainForCancel: (...a) => this.resolveSuspensionChainForCancel(...a), + cancelRun: (...a) => this.cancelRun(...a), + logger: this.logger, + }; + return runRegion.call(host, region, variables, context, grouping, partialSteps); + } + + /** + * Retry execution with exponential backoff, jitter, and recursive protection. + * Uses an iterative loop with an internal retry flag to prevent recursive call stacking. + * + * ⚠️ [#9510] NOT a terminal-only method. Three results leave it: an attempt + * that succeeded, the exhausted-budget failure at the bottom, and — since + * the ADR-0019 suspend arm was restored to `executeWithoutRetry` — an + * attempt that PAUSED, returned unchanged from inside the loop. The paused + * one is non-terminal: the run is durably suspended and finishes later + * through `resume()`, not here. Its readers are told so explicitly (the + * loop below, `execute()`'s handoff, and the flow-dispatch status table in + * `@objectstack/runtime`) rather than discovering it by falling through a + * `success` check — a non-terminal result reaching a reader that assumes + * terminal is how this defect becomes a different one. + * + * Reads the PARSED `errorHandling` block straight — no `??` fallbacks + * (#4247). It used to declare every knob optional and re-state a default + * for each, and one of those copies disagreed with the schema + * (`maxRetries ?? 3` against `.default(0)`), which made the retry count a + * function of how the flow reached the engine rather than of what its + * author wrote. `this.flows` only ever holds `FlowSchema.parse` output — + * `registerFlow` parses, and the version-history rollback re-seats a + * previously parsed snapshot — so every field below is present, and typing + * the parameter as the parsed shape is what keeps a second set of defaults + * from growing back here: a knob the spec stops defaulting becomes a + * compile error, not a silent engine-side guess. + * + * `flowErrorMessage` is the author's terminal failure text + * (`flow.errorMessage`), passed for the same reason `errorHandling` is + * passed rather than re-read: `execute()` already holds the parsed flow, + * and the exhausted exit below must report the definition THIS dispatch + * started under — not whatever a hot-reload re-registered under the same + * name while the loop slept between attempts (#9414). `flowLabel` is + * passed for the same reason. + * + * [#28054] `flowErrorMessage` is a `{{ }}` template, rendered over the + * variables at the failure point — and those are the LAST attempt's, which + * only that attempt holds. So each attempt is handed this template and + * renders it at its own failure exit, and the exhausted exit reports the + * last attempt's rendering: still the definition this dispatch started + * under, filled from the run that failed last. An attempt that never + * dispatched (its flow vanished or was disabled between attempts) bound no + * variable, so the template renders over none. + */ + static async retryExecution( + this: Pick, + flowName: string, + context: AutomationContext | undefined, + startTime: number, + errorHandling: NonNullable, + flowErrorMessage: string | undefined, + flowLabel: string, + ): Promise { + // `maxRetries >= 1` is guaranteed under `strategy: 'retry'` — the schema + // refuses the zero-attempt spelling of "retry" (#4247), so reaching this + // method always means at least one re-run. + // `backoffMs` (was `retryDelayMs`) since spec 17.0.0 — `errorHandling` + // now carries the converged `RetryPolicySchema` contract, so this reads + // the same key the `try_catch` executor and `runWithPolicy` read + // (#4661, #4964). Destructured, not `??`-defaulted: the parsed block is + // the only source of these numbers (#4247). + const { + maxRetries, + backoffMs: baseDelay, + backoffMultiplier: multiplier, + maxRetryDelayMs: maxDelay, + jitter: useJitter, + } = errorHandling; + + let lastError = 'Max retries exceeded'; + // [#24914, ruling B′] The refusal the LAST attempt met, kept paired + // with `lastError` so the exhausted exit never reports one attempt's + // text beside another attempt's refusal. + let lastCarried: CarriedRefusal = {}; + // [#28054] The last attempt's rendering of `flowErrorMessage`, paired + // with `lastError` the same way. + let lastErrorMessage: string | undefined; + for (let i = 0; i < maxRetries; i++) { + // Calculate delay with exponential backoff + let delay = Math.min(baseDelay * Math.pow(multiplier, i), maxDelay); + if (useJitter) { + delay = delay * (0.5 + Math.random() * 0.5); + } + await new Promise(r => setTimeout(r, delay)); + + // Execute directly without recursion into retryExecution again + const result = await this.executeWithoutRetry(flowName, context, { errorMessage: flowErrorMessage }); + // [#9510] THE THIRD STATE, read deliberately and BEFORE `success`. + // Since the ADR-0019 suspend arm was restored to + // `executeWithoutRetry`, an attempt can end NON-TERMINAL: the run + // asked to pause, its continuation is persisted under + // `result.runId`, and it is waiting for a `resume()` that may + // arrive days later. Returning it is the only correct answer — + // re-running the flow would start the paused work a SECOND time + // while the first continuation is still live and resumable, which + // is what the pre-repair loop did on every remaining attempt. + // + // ⛔ Not left to the `result.success` line below, even though a + // paused result is `success: true` and would fall through it today. + // That line means "this attempt SUCCEEDED, stop retrying" — a + // different sentence about a different outcome — and a + // non-terminal result recognised only by a branch that names + // something else is one edit away from being misread again. The + // reason this returns is the PAUSE, so the pause is what it tests. + // + // ⛔ And it weakens no retry accounting: nothing above is skipped, + // reset or shortened, `maxRetries` still bounds the loop, and a + // genuinely failing attempt still consumes one. The loop stops here + // only because this attempt did not fail. + if (result.status === 'paused') return result; + if (result.success) return result; + lastError = result.error ?? 'Unknown error'; + lastCarried = carriedRefusalOfResult(result); + lastErrorMessage = result.status === 'failed' + ? result.errorMessage + : this.renderFlowTerminalMessage(flowName, 'errorMessage', flowErrorMessage, new Map(), context ?? {}); + } + // [#9378] Same "ran and was rejected" class as `execute()`'s own failure + // exit — every attempt above dispatched the flow — so it carries the + // same lifecycle verdict, and a transport answers it the same way. + // Without it, a flow whose author chose `errorHandling.strategy: + // 'retry'` would be the ONE failure shape that still rode HTTP 200. + // + // [#9414] `errorMessage` for the same structural reason: this is a + // DIFFERENT terminal exit from `execute()`'s own failure return — a + // flow under `strategy: 'retry'` is handed off above and never reaches + // that one — so a repair that stopped at `execute()` would leave the + // author's message missing for precisely the runs most likely to need + // it, the ones that failed over and over. + return { + success: false, + error: lastError, + durationMs: Date.now() - startTime, + status: 'failed', + errorMessage: lastErrorMessage, + flowLabel, + ...lastCarried, + }; + } + + /** + * Append a run to the in-memory ring buffer, fold its {@link FlowRunSummary}, + * log the one-line-per-run summary (#4354) and mirror a terminal run to + * durable history. + * + * @returns the same entry, now carrying `summary` — so a caller returning an + * {@link AutomationResult} hands the counts straight back without a second + * fold or a `getRun` round-trip. + */ + // [#10101] `context` is the run's {@link AutomationContext}, passed by + // every call site (the same value each already hands `buildRunTrigger`) so + // a TERMINAL record can carry the two organization-attribution inputs the + // durable store resolves from: the triggering record snapshot (the + // SUBJECT — primary, per the cloud#1395 Option A ruling) and the acting + // tenant (the ruled fallback). Threaded as a parameter rather than read + // off the entry because `ExecutionLogEntry` deliberately keeps the + // published `trigger` block's shape (`ExecutionLogSchema`). + // [#13909] `consumedSuspension` is the suspension a resume consumed before + // the downstream node threw, passed ONLY by that one call site and copied + // straight onto the {@link RunRecord} below. It is deliberately a parameter + // rather than a field of {@link ExecutionLogEntry}: that interface is + // served verbatim by `GET /automation/:name/runs/:runId`, so carrying a + // whole variable map and run context on it would publish a paused run's + // internals for every failed run — a disclosure change with no card behind + // it, and the exact widening #7639 refused when it added `variables` to the + // `paused` sites only. + static recordLog( + this: Pick, + entry: ExecutionLogEntry, + context?: AutomationContext, + consumedSuspension?: SuspendedRun, + ): ExecutionLogEntry { + // [#31696] A run whose key moved in flight is recorded where it moved. + const filed = this.flowKeyNow(entry.flowName); + if (filed !== entry.flowName) entry = { ...entry, flowName: filed }; + // The body lives in ./run-history.ts (#25222). + const readStore = () => this.store; + const host: ThisParameterType = { + executionLogs: this.executionLogs, + maxLogSize: this.maxLogSize, + runSummaryLog: this.runSummaryLog, + logger: this.logger, + get store() { return readStore(); }, + compactStepsForHistory: (...a) => this.compactStepsForHistory(...a), + consumedSuspensions: this.consumedSuspensions, + }; + const logged = recordLog.call(host, entry, context, consumedSuspension); + // The body a finished run ran, beside its ring entry (see {@link getRunFlowChecksum}). + const checksum = runRecordFlowChecksum(context, logged.id, consumedSuspension); + if (checksum !== undefined && isTerminalRunStatus(logged.status)) this.entryFlowChecksums.set(logged, checksum); + return logged; + } + + /** + * Compact a run's step log for durable history. Delegates to the region-aware + * {@link compactStepLogForHistory} (#3234): under {@link MAX_PERSISTED_HISTORY_STEPS} + * the log is kept whole (stacks stripped); over budget it keeps the run's + * structural backbone (top-level + container steps + every failure) plus the + * most recent body steps, so a long loop's container survives and the Runs + * surface can still nest what it retains. + */ + static compactStepsForHistory(steps: StepLogEntry[]): StepLogEntry[] { + return compactStepLogForHistory(steps, MAX_PERSISTED_HISTORY_STEPS); + } +} diff --git a/packages/services/service-automation/src/engine.ts b/packages/services/service-automation/src/engine.ts index 2eae378dd5f..3d492400f3b 100644 --- a/packages/services/service-automation/src/engine.ts +++ b/packages/services/service-automation/src/engine.ts @@ -6,20 +6,14 @@ import type { ActionDescriptor, FlowRunSummary, } from '@objectstack/spec/automation'; -import type { AutomationContext, AutomationResult, ResumeSignal, IAutomationService, RunListResult, ScreenSpec, ScreenFieldSpec, ConnectorSourcePullRequest, ConnectorSourcePullResult, ConnectorCredentialRef, ConnectorCredentialSetRequest, ConnectorCredentialClearRequest, ConnectorConnectionState, ConnectorConnectionRequest, ConnectorConnectionBegin, ConnectorConnectionCallbackRequest, FlowDryRunOptions, FlowDryRunResult, RecordUpdateStartsInput } from '@objectstack/spec/contracts'; +import type { AutomationContext, AutomationResult, ResumeSignal, IAutomationService, RunListResult, ScreenSpec, ConnectorSourcePullRequest, ConnectorSourcePullResult, ConnectorCredentialRef, ConnectorCredentialSetRequest, ConnectorCredentialClearRequest, ConnectorConnectionState, ConnectorConnectionRequest, ConnectorConnectionBegin, ConnectorConnectionCallbackRequest, FlowDryRunOptions, FlowDryRunResult, RecordUpdateStartsInput } from '@objectstack/spec/contracts'; import type { FlowRegistration, FlowRegistrationRefusal, RecordUpdateStart } from '@objectstack/spec/api'; import { - validateScreenInputs, screenDeclaresInputContract, - declaredScreenFieldNames, - type ScreenFieldVisibility, } from './screen-input-contract.js'; import type { IPubSub, Logger } from '@objectstack/spec/contracts'; import type { FlowUnboundCause } from '@objectstack/spec/contracts'; -import { FLOW_STRUCTURAL_NODE_TYPES } from '@objectstack/spec/automation'; import { - resolveScheduledWorkPolicy, - scheduledWorkDisabledReason, type ScheduledWorkPolicy, } from '@objectstack/types'; import { type ConversionNotice, type ConversionTodoNotice } from '@objectstack/spec'; @@ -36,19 +30,14 @@ import type { ConnectorOrigin, ConnectorDescriptor, } from '@objectstack/spec/integration'; -import { flowContentChecksum } from './flow-identity.js'; -import { getRunFlowChecksum, runRecordFlowChecksum, stampRunFlowChecksum } from './run-flow-checksum.js'; +import { getRunFlowChecksum } from './run-flow-checksum.js'; import { HeldValueCycleError } from './scope-key-segments.js'; -import { carriedRefusalOfResult, readCarriedRefusal, type CarriedRefusal } from './inner-refusal.js'; -import { summarizeRun } from './run-summary.js'; -import { withDroppedFields } from './run-dropped-fields.js'; import type { DroppedFieldsEvent } from '@objectstack/spec/data'; // #5660 — the degrade registration reports a FOREIGN failure (a third-party // provider factory's text), so it renders it as structured `meta` rather than // interpolating it into the log message. See ./thrown-cause-diagnostics.ts. import { describeThrownForLog } from './thrown-cause-diagnostics.js'; import { defaultEnvCredentialResolver, type CredentialResolver } from './credential-resolver.js'; -import { FlowCredentialUnresolvableError } from './flow-credential-channel.js'; // [#22450] The one bundle-locale negotiation rule (`resolveLocaleAmong`'s five // steps: exact → case-insensitive → platform locale table language, so `zh-TW` // reaches `zh-Hant` → base language → variant expansion), asked about the @@ -80,7 +69,6 @@ import { deriveTriggerBinding, registerConnector, registerDegradedConnector, - assertSameOriginOrFree, unregisterNodeExecutor, unregisterTrigger, unregisterConnector, @@ -91,7 +79,6 @@ import { import { executeNode, traverseNext, - runRegion, executeWithTimeout, celScope, valueEnvelopeRefusals, @@ -99,11 +86,9 @@ import { evaluateCondition, seedDeclaredVariables, seedRunVariables, - startConditionHolds, executeWithoutRetry, type ValueEnvelopeRefusal, } from './dag-traversal.js'; -import { activeDryRunExecuteNode, dryRun as dryRunBody, type DryRunHost } from './dry-run.js'; // [#35928] The record-update preview's body. import { listRecordUpdateStarts, type RecordUpdateStartsHost } from './record-update-starts.js'; // [#25222] The run history's bodies: recording a run's log entry, finishing a @@ -171,7 +156,6 @@ import { // `AutomationEngine` method of the same name calls its body. import { resolveFunction, - registerConnectorProvider, canonicalizeStoredFlow, canonicalizeFlow, unregisterFlow, @@ -179,10 +163,8 @@ import { getFlowRuntimeStates, describeUnboundReason, getTriggerBindingAudit, - flowCredentialHoldings, hookSecretResolver, rollbackFlow, - unregisterConnectorProvider, withdrawFlow, hydrateFlowActivations, toggleFlow, @@ -192,7 +174,6 @@ import { // packaged subflows and their callers, and refusing what would reach a disabled // subflow. Each `AutomationEngine` method of the same name calls its body. import { - describeDisabledFlow, subflowTargets, packagedSubflowCallers, parkedRunsOf, @@ -204,22 +185,19 @@ import { rejudgeSubflowCallers, refuseCustomerAuthoredToggle, } from './subflow-guards.js'; -import { describeSubflowNoticeTrap, subflowNoticeTrap } from './subflow-notice-guard.js'; +import { subflowNoticeTrap } from './subflow-notice-guard.js'; // [ADR-0150 D3/D4] The one package-scoped resolver's answer, read through the // reader the host attaches (`setFlowNameResolver`), and the activation // projection keyed by `(package, name)`. import type { PackageScopedRefusal, PackageScopedResolution } from '@objectstack/objectql'; import { FlowActivationProjection } from './flow-activation-projection.js'; // [ADR-0150 D4, #31696] The engine holds flows by `(package, name)` slot. -import { packageScopedRefusalMessage, PackageScopedNameRefusedError } from '@objectstack/core'; -import { ENVIRONMENT_ADDRESS_SEGMENT } from '@objectstack/spec/kernel'; -import { FlowSlotTable, flowRunKey, flowRunPackage, isSlotKeySpelling, qualifiedFlowKey, unfiledFlowKey, stampFlowRunSlot, type FlowKeyMove, type FlowSlot } from './flow-slots.js'; -import { readRecordRun, readRootRun, stampRootRun, type RecordRun, type RootRun } from './root-run.js'; -import { flowSlotRunStore } from './flow-slot-run-store.js'; +import { FlowSlotTable, isSlotKeySpelling, unfiledFlowKey, type FlowKeyMove, type FlowSlot } from './flow-slots.js'; +import { readRecordRun, readRootRun, type RecordRun, type RootRun } from './root-run.js'; import { ConnectorInstances } from './connector-instances.js'; import type { ConnectorInstanceOptions } from './plugin-extension-api.js'; -import { describeRegionSuspendingCall, regionSuspendingCall } from './subflow-region-guard.js'; -import { describeSubflowRetriedCallout, subflowRetriedCallout } from './subflow-retry-guard.js'; +import { regionSuspendingCall } from './subflow-region-guard.js'; +import { subflowRetriedCallout } from './subflow-retry-guard.js'; // [#25222] The consumed-suspension restore's bodies: journaling a consumed // suspension, resolving its witnesses, and restoring, peeking at or inspecting // one. Each `AutomationEngine` method of the same name calls its body. @@ -323,20 +301,16 @@ export { } from './engine-run-log.js'; import { buildRunTrigger, - missedRunId, } from './engine-run-trigger.js'; export { buildRunTrigger, missedRunId, } from './engine-run-trigger.js'; import { - isSuspendSignal, - isRefusalSignal, type RefusalI18nService, type FlowTextSlotTranslation, type ChildRunRefusal, InputSchemaViolationError, - isInputSchemaViolation, } from './engine-signals.js'; export { FlowSuspendSignal, @@ -350,11 +324,7 @@ export { isInputSchemaViolation, } from './engine-signals.js'; import { - ENGINE_BUILT_SIGNAL, - engineBuilt, type SuspendedRun, - activeMsAtPause, - isTerminalRunStatus, type RunRecord, type ConsumedSuspensionDropNotice, type ConsumedSuspension, @@ -362,7 +332,6 @@ import { type SuspensionRestoreRefusal, type SuspensionRestoreResult, type ConsumedSuspensionInspection, - type SuspensionClaimOutcome, type AdvanceClaim, type SuspendedRunStore, } from './engine-resume.js'; @@ -421,8 +390,27 @@ import { type ConnectorConnectionDoor, type FlowCredentialHolding, type FlowShadowingRecord, - isTimeTriggeredKind, } from './engine-registration.js'; + +// [#38667] The facets the stubs below forward to, and the host each stub hands its body. +import { DispatchFacet } from './engine-dispatch-facet.js'; +import { ExtensionsFacet } from './engine-extensions-facet.js'; +import { FlowSlotsFacet } from './engine-flow-slots-facet.js'; +import { RegistrationFacet } from './engine-registration-facet.js'; +import { ConnectorDoorsFacet } from './engine-connector-doors-facet.js'; +import { EnablementFacet } from './engine-enablement-facet.js'; +import { RunFacet } from './engine-run-facet.js'; +import { ResumeFacet } from './engine-resume-facet.js'; +import { + dispatchHost, + extensionsHost, + flowSlotsHost, + registrationHost, + connectorDoorsHost, + enablementHost, + runHost, + resumeHost, +} from './engine-facet-hosts.js'; export { CONVERSIONS_NOT_REPLAYED_AT_REHYDRATION, FLOW_REGISTRATION_TODO_ID, @@ -989,9 +977,7 @@ export class AutomationEngine implements IAutomationService { * deployment resolver, unchanged. */ private readScheduledWorkPolicy(): ScheduledWorkPolicy { - const source = this.scheduledWorkPolicy; - if (source === undefined) return resolveScheduledWorkPolicy(); - return typeof source === 'function' ? source() : source; + return DispatchFacet.readScheduledWorkPolicy.call(dispatchHost.of(this)); } /** @@ -1010,30 +996,7 @@ export class AutomationEngine implements IAutomationService { * package)` in the store — see ./flow-slot-run-store.ts. */ private slotKeyedRunStore(store: SuspendedRunStore): SuspendedRunStore { - return flowSlotRunStore(store, { - // The flow's own name and package, never a key. The run's own - // package (stamped at start) comes first, so a run whose key moved - // in flight is still its own package's run. A key no slot files is - // a qualified key moved back to the bare name: split at its last `/`. - stored: (key, flowPackage) => { - // [S3, N8] An unfiled key stores its name and no slot's package: the lone slot of a shared name is not its. - if (key.startsWith('\u0000')) return { flowName: key.slice(1), ...(flowPackage ? { flowPackage } : {}) }; - const slot = this.flowSlots.slot(key); - const cut = key.lastIndexOf('/'); - const flowName = slot?.name ?? (cut >= 0 ? key.slice(cut + 1) : key); - const packageId = flowPackage || (slot ? slot.packageId ?? undefined : cut >= 0 ? key.slice(0, cut) : undefined); - return { flowName, ...(packageId ? { flowPackage: packageId } : {}) }; - }, - key: (flowName, flowPackage) => { - if (!flowPackage) return this.flowSlots.isShared(flowName) ? unfiledFlowKey(flowName) : flowName; - const key = this.flowSlots.keyOf(flowName, flowPackage); - if (key !== undefined) return key; - // The package holds no flow of the name now: a key no slot - // files, so the run reads as its flow's absence — never as - // another package's flow of that name. - return this.flowSlots.keysOf(flowName).length > 0 ? qualifiedFlowKey(flowPackage, flowName) : flowName; - }, - }); + return DispatchFacet.slotKeyedRunStore.call(dispatchHost.of(this), store); } /** @@ -1169,10 +1132,7 @@ export class AutomationEngine implements IAutomationService { * instead — never a number of this method's own. */ missedRunLimit(): number | null { - const ledger = this.flowDispatchStore; - if (!ledger || typeof ledger.read !== 'function') return null; - const cap = this.store?.maxTerminalRunsPerFlow; - return typeof cap === 'number' && cap > 0 ? cap : this.maxLogSize; + return DispatchFacet.missedRunLimit.call(dispatchHost.of(this)); } /** @@ -1200,42 +1160,8 @@ export class AutomationEngine implements IAutomationService { * documents that reading of the two for `missed`; no step ran, so `steps` * is empty. */ - async recordMissedRun(missed: MissedScheduledRun): Promise { - const store = this.flowDispatchStore; - if (!store || typeof store.read !== 'function') return 'unverifiable'; - try { - if (await store.read(missed.dispatchKey)) return 'dispatched'; - // [ADR-0150 D8 row R10] The transition read: the same window - // claimed under its bare-shape key by a node of the previous release. - if (missed.legacyDispatchKey && missed.legacyDispatchKey !== missed.dispatchKey - && await store.read(missed.legacyDispatchKey)) return 'dispatched'; - } catch (err) { - this.logger.warn( - `[automation] missed-run check for flow '${missed.flowName}' due ${missed.dueAt} could not read ` + - `the dispatch ledger — NOT recording it as missed, since an unread claim may be a run that ` + - `landed. The store failure is in this record's meta.`, - describeThrownForLog(err), - ); - return 'unverifiable'; - } - const context: AutomationContext = { - event: 'schedule', - ...(missed.organization ? { tenantId: missed.organization } : {}), - }; - this.recordLog( - { - id: missedRunId(missed.flowName, missed.dueAt), - flowName: missed.flowName, - flowVersion: this.flows.get(missed.flowName)?.version, - status: 'missed', - startedAt: missed.dueAt, - completedAt: missed.detectedAt, - trigger: buildRunTrigger(context), - steps: [], - }, - context, - ); - return 'recorded'; + recordMissedRun(missed: MissedScheduledRun): Promise { + return DispatchFacet.recordMissedRun.call(dispatchHost.of(this), missed); } /** @@ -1261,7 +1187,7 @@ export class AutomationEngine implements IAutomationService { /** Note that `runId` was started for the caller's `context` ({@link runsStartedByContext}). */ private noteRunStarted(context: AutomationContext | undefined, runId: string): void { - if (context && typeof context === 'object') this.runsStartedByContext.set(context, runId); + return DispatchFacet.noteRunStarted.call(dispatchHost.of(this), context, runId); } /** @@ -1290,24 +1216,7 @@ export class AutomationEngine implements IAutomationService { * nobody read, and every in-flight approval zombified by the next restart. */ private persistSuspendedRun(run: SuspendedRun): Promise { - // [ADR-0150 D8 row R8, #31696] The run names the package whose flow - // it runs, as stamped when it started, whatever key its slot is filed - // under by the time it pauses. - if (run.flowPackage === undefined) { - const flowPackage = flowRunPackage(run.context); - if (flowPackage !== undefined) run = { ...run, flowPackage }; - } - const filed = this.flowKeyNow(run.flowName); - if (filed !== run.flowName) run = { ...run, flowName: filed }; - // The body lives in ./run-resume.ts (#25222). - const readStore = () => this.store; - const host: ThisParameterType = { - suspendedRuns: this.suspendedRuns, - get store() { return readStore(); }, - cacheOnlySuspensions: this.cacheOnlySuspensions, - logger: this.logger, - }; - return persistSuspendedRun.call(host, run); + return ResumeFacet.persistSuspendedRun.call(resumeHost.of(this), run); } /** @@ -1477,42 +1386,8 @@ export class AutomationEngine implements IAutomationService { * The last two are announced once per engine rather than assumed silently, * which is the whole difference between a degradation and a lie. */ - private async claimAdvance(run: SuspendedRun): Promise { - const store = this.store; - if (!store) return { kind: 'unguarded' }; - if (this.cacheOnlySuspensions.has(run.runId)) return { kind: 'unguarded' }; - if (typeof store.claimSuspension !== 'function') { - this.warnAdvanceClaimDegraded('the attached suspended-run store has no claimSuspension()'); - return { kind: 'unguarded' }; - } - let outcome: SuspensionClaimOutcome; - try { - outcome = await store.claimSuspension(run.runId, { - nodeId: run.nodeId, - ...(run.correlation !== undefined ? { correlation: run.correlation } : {}), - }); - } catch (err) { - // Handed to the CALLER, so not a degradation and deliberately NOT a - // log site (AGENTS.md "Degradation log levels": a failure the - // requester was told about does not look normal from the outside). - // The envelope is the same STORE_UNAVAILABLE the strict load - // answers, for the same reason — existence is UNKNOWN, not "gone - // for good" (#4420). - // - // ⛔ What this branch may NOT claim is that the suspension was not - // consumed. A throw can arrive AFTER a committed delete — a dropped - // connection on the way back from a landed statement — so the one - // thing known here is that THIS resume did not continue the run. - // The result text says exactly that and no more; a retry is what - // resolves the ambiguity, answering RUN_NOT_FOUND if the row is in - // fact gone. - return { kind: 'unavailable', message: (err as Error).message }; - } - if (outcome === 'unsupported') { - this.warnAdvanceClaimDegraded("the attached suspended-run store answered 'unsupported'"); - return { kind: 'unguarded' }; - } - return outcome === 'claimed' ? { kind: 'claimed' } : { kind: 'lost' }; + private claimAdvance(run: SuspendedRun): Promise { + return ResumeFacet.claimAdvance.call(resumeHost.of(this), run); } /** @@ -1574,7 +1449,7 @@ export class AutomationEngine implements IAutomationService { * (see {@link SuspendedRun.nodeType}). */ private resolveSuspendedNodeType(run: SuspendedRun): string | undefined { - return run.nodeType ?? this.flows.get(run.flowName)?.nodes.find(n => n.id === run.nodeId)?.type; + return ResumeFacet.resolveSuspendedNodeType.call(resumeHost.of(this), run); } // ── Plugin Extension API ────────────────────────────── @@ -1740,9 +1615,7 @@ export class AutomationEngine implements IAutomationService { private resolveTriggerBinding( flowName: string, ): { triggerType: string; binding: FlowTriggerBinding } | undefined { - const flow = this.flows.get(flowName); - if (!flow) return undefined; - return this.deriveTriggerBinding(flowName, flow); + return ExtensionsFacet.resolveTriggerBinding.call(extensionsHost.of(this), flowName); } /** @@ -1769,255 +1642,7 @@ export class AutomationEngine implements IAutomationService { * {@link registerTrigger} re-attempts activation when one arrives. */ private activateFlowTrigger(flowName: string): void { - if (this.boundFlowTriggers.has(flowName)) return; - // [ADR-0126 §7.2] THE enablement gate for arming — here, at the one - // point every arming path crosses, and not in its callers. A flow - // either disable dimension switches off (the activation ledger, or an - // `obsolete` / `invalid` status) is never handed to a trigger, whichever - // path asks: {@link registerFlow} (boot pull, publish, hot reload), - // {@link registerTrigger}, the enable half of {@link toggleFlow}, and - // any path added later. - // - // Why it cannot live in the callers: `registerTrigger` runs when a - // trigger plugin registers at `kernel:ready`, AFTER `start()` pulled - // the flows and {@link hydrateFlowActivations} unbound the switched-off - // ones. While only `registerFlow` asked, that later registration - // re-armed every one of them on every cold boot — `/_status` reported a - // disabled flow `bound: true`, and each matching event fired a run - // `execute()` then refused. - // - // Silent on purpose: an unarmed disabled flow is the state the switch - // exists to produce, the host's hydration line already named it, and - // `getFlowRuntimeStates()` reports it `enabled: false`. Ahead of the - // scheduled-work policy gate below for the same reason — a flow that - // may not run has no policy refusal to record. - if (!this.isFlowEnabled(flowName)) return; - const resolved = this.resolveTriggerBinding(flowName); - if (!resolved) return; - // [ADR-0150 D4, #31696] A trigger binds a slot by its key and fires - // that slot ({@link triggerRun}). The one slot of a name the registry - // holds under two packages (the other's body refused, M1) still holds - // the bare key, which would read as the name's one holder: it is not - // armed, behind this warning, and runs when called by its package. - // [#33893] Both served ({@link loneSharedFlowKey}): beside a disabled - // co-holder the slot is the name's one served holder, filed under its - // qualified key, and is armed; the warning names no refused body. - // Filed under its qualified key, it is declined only once another - // package's body of the name was refused (recorded): a co-holder the - // re-sync has not registered yet is no refusal. - const slotName = this.flowSlotName(flowName); - if (this.loneSharedFlowKey(slotName) === flowName && (flowName === slotName || this.flowRefusals.has(slotName))) { - if (!this.sharedSlotTriggerWarned.has(flowName)) { - this.sharedSlotTriggerWarned.add(flowName); - this.logger.warn( - `Flow '${flowName}' is registered but NOT armed on trigger '${resolved.triggerType}' — another ` - + `package holds a flow named '${this.flowSlotName(flowName)}' whose body was refused, so this ` - + 'flow holds the bare name it cannot be addressed by. It runs when called by its package.', - { flow: this.flowSlotName(flowName), slot: flowName, triggerType: resolved.triggerType }, - ); - } - return; - } - // [#17396] The deployment gate, read HERE rather than only inside the - // trigger. The trigger has its own copy of this gate and throws, which - // is what protects a host that binds without this engine — but a - // refusal that arrives as a THROW can only be reported through this - // method's catch, and that catch says "Failed to bind", which is the - // one thing ruled item 6 forbids this state from reading as. Asking the - // policy before `start()` keeps the two apart at the source: nothing is - // called, nothing throws, nothing is logged as a failure. - // - // ⚠️ AHEAD of the trigger lookup, deliberately. With the switch off, - // registering the missing trigger would change nothing, so reporting - // "no 'schedule' trigger is registered — add requires: ['triggers']" - // hands the operator a remedy that cannot work. The switch outranks it - // because it is the fact that decides the outcome. - // - // ⛔ The POLICY is not cached — the resolver reads `process.env` live, - // so a host that rebinds after changing the environment (the CLI's - // `--fresh` harness, a test flipping the switch between kernels in one - // process) sees the value current at the bind. [#19834] A per-kernel - // `scheduledWorkPolicy` option replaces that read for this engine only; - // a resolver given there is likewise called at each bind. What IS recorded is the - // REFUSAL, on {@link policyDisabledFlows}, and that is the difference - // between the two: see its own docblock for why the audit must read - // what happened rather than re-derive it from an environment that may - // have moved since. - // - // The policy is read only for a time-triggered kind, as before: a - // record-change or api flow never asks it. - const policy = isTimeTriggeredKind(resolved.triggerType) ? this.readScheduledWorkPolicy() : undefined; - if (policy !== undefined && !policy.enabled) { - // [#21110] The sentence comes from the SAME reading that refused — - // the host's own reason when its per-kernel policy carries one, else - // the deployment sentence — and the bind log, the audit and the - // `/_status` row all read this one recorded value. - const reason = scheduledWorkDisabledReason(policy); - if (this.policyDisabledFlows.get(flowName) !== reason) { - this.policyDisabledFlows.set(flowName, reason); - // Said once per flow while it stays refused for the same - // reason, at `info`, for the reason the trigger's own refusal - // records: this is the DEFAULT state of every deployment and the - // deployment declared it, so nothing is wrong and nothing looks - // normal-but-broken. The structured channel is the audit below, - // which the `kernel:bootstrapped` hook and the CLI startup - // summary read. - this.logger.info( - `Flow '${flowName}' is not armed on trigger '${resolved.triggerType}' — ${reason}`, - ); - } - // [#25235] A refusal on purpose disarms what a previous kernel left - // armed — see {@link FlowTrigger.release}. On every pass, not once: - // the trigger may register after the flow, and a cancel by name of - // an already-disarmed job changes nothing. - const refusing = this.triggers.get(resolved.triggerType); - if (refusing && typeof refusing.release === 'function') { - try { - refusing.release(flowName); - } catch (err) { - this.logger.warn( - `Flow '${flowName}' is not armed on trigger '${resolved.triggerType}', and disarming what ` + - `an earlier start left armed for it failed. The failure is in this record's meta.`, - describeThrownForLog(err), - ); - } - } - return; - } - // Past the gate the refusal no longer describes this flow: either it - // binds below, or it fails/waits for its trigger with a reason of its - // own. Cleared BEFORE the trigger lookup so a flow whose trigger has - // not arrived yet is reported as waiting for a trigger, not as - // policy-disabled — with the switch on, the missing trigger really is - // the reason. - this.policyDisabledFlows.delete(flowName); - // [#20725, ADR-0126 §7.3] The subflow half of the same gate: a PACKAGED - // flow is not armed while a packaged subflow it calls is disabled — - // armed, it would fail at its subflow node on the child's refusal, the - // late, inexplicable failure §7.3 exists to prevent. Here rather than - // in the callers for this gate's own reason: every arming path — - // create, republish, upgrade, hot reload, the kernel:ready trigger - // registration, the enable toggle — crosses this line, so none of them - // can arm onto a disabled child and none can forget to ask. - // - // ⛔ A DECLINE, never a refusal: `registerFlow` still registers, so a - // boot or an upgrade never fails on an installation's choice. The flow - // stays unarmed, `/_status` says why ({@link describeUnboundReason}), - // and it is armed the moment its subflow is enabled - // ({@link rejudgeSubflowCallers}). Ahead of the trigger lookup for the - // policy gate's reason: with the child off, registering the missing - // trigger would change nothing, so "no trigger registered" would name - // a remedy that cannot work. - if (this.declineOntoDisabledSubflows(flowName, resolved.triggerType)) return; - // [#28840] The save-notice half, a decline for the same reasons: a - // `save_notice` after a `subflow` / `map` node whose child can suspend - // is refused by name when the suspended run resumes, after the write - // answered, and a decision that resumes it is stranded. The flow parse - // cannot see the child (#28806), which may register after this flow, - // so the gate asks here and {@link rejudgeSubflowCallers} asks again - // when the child arrives or changes. - if (this.declineOntoSuspendingSubflowNotice(flowName, resolved.triggerType)) return; - // [#28897] The region half, a decline for the same reasons: a region - // body cannot carry a durable pause, so a region-nested `subflow` / - // `map` whose child suspends fails the run at the region boundary - // (`region-suspension-refusal.ts`), the first time that child - // suspends. That refusal stays as the second door; this is the first. - // Last of the halves, and {@link describeUnboundReason} reads the - // records in the same order, so a record an earlier half's decline - // left unasked is never the one reported. - if (this.declineOntoRegionSuspendingCall(flowName, resolved.triggerType)) return; - // The subflow-retry half, a decline for the same reasons: an - // after-record-change run waits for its `subflow` / `map` children, so - // an inline outbound call a child retries holds the save through the - // backoff ladder (ruling 6810500711, letter D). The after-save judge - // refuses that shape in the flow's own graph at registration; it cannot - // see the child, which may register after this flow. Last, and - // {@link describeUnboundReason} reads its record last. - if (this.declineOntoSubflowRetriedCallout(flowName, resolved.triggerType)) return; - const trigger = this.triggers.get(resolved.triggerType); - if (!trigger) return; - try { - // A trigger-fired run's result must not vanish (2026-07-17 eval: - // a failing record-change flow produced zero output — the failure - // lived only in the run-history row). Condition-skipped runs stay - // quiet (execute() already debug-logs them — they are high-frequency). - // - // #6587 — `result.error` is the envelope field that carries a - // failing node's / driver's text VERBATIM (#5912 left it that way - // on purpose), so foreign newlines reach this message second-hand; - // it goes to the structured slot — the identical class as - // `bubbleToParent`'s envelope branch, on the fired-run path. See - // `forgetSuspendedRun`'s catch for the full mechanism (#6299). - // - // #4632 verdict: stays `error`, on its own reasoning rather than - // inertia. This is the fire-and-forget path: NO caller holds this - // result envelope, so after the failure the system looks normal - // from the outside — the triggering event was handled and nothing - // retries the run — while the flow's declared effects never - // landed; the only other trace is the passive run-history row. - // That stderr also survives the CLI's boot-quiet stdout window is - // stream mechanics, not the verdict. - // - // [ADR-0126 §7.2] The line states only what happened. Two kinds of - // `execute()` answer are not a failed run: - // - `FLOW_DISABLED`: the flow was switched off after the trigger - // took the event — an event in flight at the switch-off, or a - // trigger whose `stop()` failed. The refusal IS the switch - // working, so it is said at `info`, never as an `error` that - // reads as a production failure. The enablement gate above - // keeps a disabled flow from being armed at all, so this is the - // residue, not the steady state. - // - every other never-dispatched exit (a `code` or a missing - // flow, and no `status`): no node ran, so the line claims no - // run-history row. Only a run that dispatched and failed - // carries `status: 'failed'` — the verdict that exit also wrote - // to the run history. - const run = this.triggerRun(flowName); - trigger.start(resolved.binding, (ctx: AutomationContext) => - run(ctx).then((result) => { - if (result === undefined) return; - if (result.success) return; - if (result.code === 'FLOW_DISABLED') { - this.logger.info( - `Trigger '${resolved.triggerType}' fired flow '${flowName}', which is disabled — the ` + - `run was refused before it started, nothing ran, and no run-history row records ` + - `it. The refusal is in this record's meta.`, - { error: result.error }, - ); - return; - } - this.logger.error( - `Trigger-fired run of flow '${flowName}' failed (trigger '${resolved.triggerType}') — ` + - `no caller holds this result and nothing retries the run; ` + - (result.status === 'failed' - ? `the terminal failure is recorded in the flow's run history, and the run's ` + - `failure envelope is in this record's meta.` - : `it was refused before it dispatched, and the refusal envelope is in this ` + - `record's meta.`), - undefined, - { error: result.error ?? 'unknown error' }, - ); - }), - ); - this.boundFlowTriggers.set(flowName, resolved.triggerType); - this.logger.info(`Flow '${flowName}' bound to trigger '${resolved.triggerType}'`); - } catch (err) { - // #6499 — plugin-supplied thrown text (`FlowTrigger.start`) to the - // structured slot; see `forgetSuspendedRun`'s catch above for the - // full mechanism (#6299). - // - // #4632 verdict: FUNCTIONAL — stays `warn`: "a trigger is not - // armed" is the rule's own canonical `warn` example. The flow is - // visibly smaller than declared (its runs never appear), and the - // kernel:bootstrapped binding audit re-reports every unbound - // triggered flow. - this.logger.warn( - `Failed to bind flow '${flowName}' to trigger '${resolved.triggerType}' — the flow stays ` + - `registered but will NOT fire on this trigger until the flow or the trigger is ` + - `re-registered. The trigger's own failure is in this record's meta.`, - describeThrownForLog(err), - ); - } + return ExtensionsFacet.activateFlowTrigger.call(extensionsHost.of(this), flowName); } /** @@ -2039,76 +1664,17 @@ export class AutomationEngine implements IAutomationService { * is no package's, and runs as before. */ private triggerRun(armedKey: string): (ctx: AutomationContext) => Promise { - const slot = this.flowSlots.slot(armedKey); - return async (ctx) => { - let key = slot ? this.flowSlots.keyOf(slot.name, slot.packageId) : armedKey; - if (key === undefined && !isSlotKeySpelling(armedKey)) return this.execute(armedKey, ctx); - if (key === undefined || (key !== armedKey && !this.boundFlowTriggers.has(armedKey))) { - this.logger.debug(`Trigger fired flow '${armedKey}' after it moved or left and was released: not run.`); - return undefined; - } - // [#33893] A lone slot left under its qualified key (its disabled - // co-holder since uninstalled) folds back here, and this run goes - // to where it lands. - if (slot && this.settleFlowName(slot.name)) key = this.flowKeyNow(key); - if (slot && slot.packageId !== null) { - const said = qualifiedFlowKey(slot.packageId, slot.name); - if (this.isDisabledHolderSlot(slot.name, slot.packageId)) { - // Said once per slot while its package stays disabled, at - // `info`: the skip IS the package switch working, and - // nothing that claims to be persisted is lost. - if (!this.disabledHolderDispatchSaid.has(said)) { - this.disabledHolderDispatchSaid.add(said); - this.logger.info( - `Trigger fired flow '${slot.name}' of package '${slot.packageId}', which is disabled — ` - + 'the flow was not run, no other package\'s flow of the name was run in its place, ' - + 'and no run-history row records it. It runs on its trigger again once the package ' - + 'is enabled.', - { flow: slot.name, package: slot.packageId, slot: key }, - ); - } - return undefined; - } - this.disabledHolderDispatchSaid.delete(said); - } - if (!slot || !this.flowSlots.isShared(slot.name)) return this.execute(key, ctx); - // A trigger seeds `params.flowName` with the key it was armed - // under; the run reads its flow's name there, never a slot key. - const params = ctx.params as Record | undefined; - const named = params?.flowName === armedKey && armedKey !== slot.name ? { ...ctx, params: { ...params, flowName: slot.name } } : ctx; - return this.executeKey(key, named, Date.now()); - }; + return ExtensionsFacet.triggerRun.call(extensionsHost.of(this), armedKey); } /** Unbind a flow from its trigger, if bound. */ private deactivateFlowTrigger(flowName: string): void { - const boundType = this.boundFlowTriggers.get(flowName); - if (!boundType) return; - try { - this.triggers.get(boundType)?.stop(flowName); - } catch (err) { - // #6499 — plugin-supplied thrown text (`FlowTrigger.stop`) to the - // structured slot; see `forgetSuspendedRun`'s catch above for the - // full mechanism (#6299). - // - // #4632 verdict: FUNCTIONAL — stays `warn`, same consequence shape - // as `unregisterTrigger`'s stop above: the binding is dropped - // either way, and a subscription the trigger failed to tear down - // fires into execute()'s own disabled/unregistered-flow guards, - // visibly. - this.logger.warn( - `Trigger '${boundType}' stop('${flowName}') failed while unbinding the flow — the binding is ` + - `dropped anyway; whatever the trigger armed for it may keep firing until the process ` + - `restarts. The trigger's own failure is in this record's meta.`, - describeThrownForLog(err), - ); - } - this.boundFlowTriggers.delete(flowName); + return ExtensionsFacet.deactivateFlowTrigger.call(extensionsHost.of(this), flowName); } /** Active flow→trigger bindings (observability / tests). */ getActiveTriggerBindings(): Array<{ flowName: string; triggerType: string }> { - return [...this.boundFlowTriggers].map(([flowName, triggerType]) => ({ flowName, triggerType })); + return ExtensionsFacet.getActiveTriggerBindings.call(extensionsHost.of(this)); } /** @@ -2223,12 +1789,7 @@ export class AutomationEngine implements IAutomationService { /** Enforce the ADR-0097 §4 two-sources-of-truth rule; warn on same-origin replace. */ private assertSameOriginOrFree(name: string, origin: ConnectorOrigin, packageId?: string | null, soleOfName?: boolean): void { - // The body lives in ./plugin-extension-api.ts (#25222). - const host: ThisParameterType = { - connectors: this.connectors, - logger: this.logger, - }; - assertSameOriginOrFree.call(host, name, origin, packageId ?? null, soleOfName ?? false); + return ExtensionsFacet.assertSameOriginOrFree.call(extensionsHost.of(this), name, origin, packageId, soleOfName); } /** @@ -2251,7 +1812,7 @@ export class AutomationEngine implements IAutomationService { * are two (never one of them, ADR-0150 red line 2). */ private connectorInstance(name: string, packageId?: string | null): RegisteredConnector | undefined { - return packageId === undefined ? this.connectors.sole(name)?.registered : this.connectors.get(name, packageId); + return ExtensionsFacet.connectorInstance.call(extensionsHost.of(this), name, packageId); } /** @@ -2261,7 +1822,7 @@ export class AutomationEngine implements IAutomationService { * [#31699] `packageId` addresses the instance ({@link connectorInstance}). */ resolveConnectorAction(connectorId: string, actionId: string, packageId?: string | null): ConnectorActionHandler | undefined { - return this.connectorInstance(connectorId, packageId)?.handlers[actionId]; + return ExtensionsFacet.resolveConnectorAction.call(extensionsHost.of(this), connectorId, actionId, packageId); } /** @@ -2271,7 +1832,7 @@ export class AutomationEngine implements IAutomationService { * declares none or is not registered. */ resolveConnectorActionInputSchema(connectorId: string, actionId: string, packageId?: string | null): unknown { - return this.connectorInstance(connectorId, packageId)?.def.actions?.find((a) => a.key === actionId)?.inputSchema; + return ExtensionsFacet.resolveConnectorActionInputSchema.call(extensionsHost.of(this), connectorId, actionId, packageId); } /** @@ -2288,7 +1849,7 @@ export class AutomationEngine implements IAutomationService { * lookup covers both origins. */ resolveConnectorActionEffect(connectorId: string, actionId: string, packageId?: string | null): ConnectorActionEffect | undefined { - return this.connectorInstance(connectorId, packageId)?.def.actions?.find((a) => a.key === actionId)?.effect; + return ExtensionsFacet.resolveConnectorActionEffect.call(extensionsHost.of(this), connectorId, actionId, packageId); } /** @@ -2367,11 +1928,8 @@ export class AutomationEngine implements IAutomationService { * writes no marked text pays no read. `undefined` when unwired or when no * rung answers; rejects when the read failed ({@link FlowOrganizationLocaleResolver}). */ - async organizationLocale(context: AutomationContext): Promise { - const resolver = this.organizationLocaleResolver; - if (!resolver) return undefined; - const locale = await resolver(context?.tenantId); - return typeof locale === 'string' && locale.trim() !== '' ? locale.trim() : undefined; + organizationLocale(context: AutomationContext): Promise { + return ExtensionsFacet.organizationLocale.call(extensionsHost.of(this), context); } /** @@ -2423,7 +1981,7 @@ export class AutomationEngine implements IAutomationService { * ({@link connectorInstance}). */ getConnectorOrigin(name: string, packageId?: string | null): ConnectorOrigin | undefined { - return this.connectorInstance(name, packageId)?.origin; + return ExtensionsFacet.getConnectorOrigin.call(extensionsHost.of(this), name, packageId); } /** @@ -2433,8 +1991,7 @@ export class AutomationEngine implements IAutomationService { * connector/action" in its failure message (#3017). */ getConnectorDegradedReason(name: string, packageId?: string | null): string | undefined { - const reg = this.connectorInstance(name, packageId); - return reg?.state === 'degraded' ? (reg.degradedReason ?? 'upstream unavailable') : undefined; + return ExtensionsFacet.getConnectorDegradedReason.call(extensionsHost.of(this), name, packageId); } /** @@ -2444,8 +2001,7 @@ export class AutomationEngine implements IAutomationService { * that is true. */ getConnectorDegradedHold(name: string, packageId?: string | null): ConnectorHold | undefined { - const reg = this.connectorInstance(name, packageId); - return reg?.state === 'degraded' ? reg.degradedHold : undefined; + return ExtensionsFacet.getConnectorDegradedHold.call(extensionsHost.of(this), name, packageId); } /** @@ -2468,14 +2024,7 @@ export class AutomationEngine implements IAutomationService { factory: ConnectorProviderFactory, options?: { readonly credentialHandle?: boolean }, ): void { - // The body lives in ./flow-definitions.ts (#25222). - const host: ThisParameterType = { - connectorProviders: this.connectorProviders, - logger: this.logger, - }; - registerConnectorProvider.call(host, providerKey, factory); - if (options?.credentialHandle === true) this.credentialHandleProviders.add(providerKey); - else this.credentialHandleProviders.delete(providerKey); + return ExtensionsFacet.registerConnectorProvider.call(extensionsHost.of(this), providerKey, factory, options); } /** ADR-0143 D4 — whether the provider under `providerKey` was registered as asking the credential handle. */ @@ -2485,13 +2034,7 @@ export class AutomationEngine implements IAutomationService { /** Unregister a connector provider factory (hot-unplug). */ unregisterConnectorProvider(providerKey: string): void { - // The body lives in ./flow-definitions.ts (#25222). - const host: ThisParameterType = { - connectorProviders: this.connectorProviders, - logger: this.logger, - }; - unregisterConnectorProvider.call(host, providerKey); - this.credentialHandleProviders.delete(providerKey); + return ExtensionsFacet.unregisterConnectorProvider.call(extensionsHost.of(this), providerKey); } /** Resolve a provider factory by key, or `undefined` when none is installed. */ @@ -2501,7 +2044,7 @@ export class AutomationEngine implements IAutomationService { /** All registered connector-provider keys (observability / boot diagnostics). */ getRegisteredConnectorProviders(): string[] { - return [...this.connectorProviders.keys()]; + return ExtensionsFacet.getRegisteredConnectorProviders.call(extensionsHost.of(this)); } /** @@ -2512,36 +2055,12 @@ export class AutomationEngine implements IAutomationService { * Handlers are omitted — they are runtime code, not metadata. */ getConnectorDescriptors(): ConnectorDescriptor[] { - return this.connectors.entries().map(({ packageId, registered: { def, origin, state, degradedReason } }) => ({ - name: def.name, - // [ADR-0150 D9, #31699] two packages' instances of one name are two - // descriptors: the package tells them apart. - ...(packageId === null ? {} : { packageId }), - label: def.label, - type: def.type, - description: def.description, - icon: def.icon, - origin, - state, - degradedReason, - actions: (def.actions ?? []).map((a) => ({ - key: a.key, - label: a.label, - description: a.description, - inputSchema: a.inputSchema, - outputSchema: a.outputSchema, - // #4395 — the declared upstream effect travels to the designer - // too, not only to the executor: `GET /connectors` is where a - // flow author picks the action, and "this one writes" is a fact - // about the pick. - effect: a.effect, - })), - })); + return ExtensionsFacet.getConnectorDescriptors.call(extensionsHost.of(this)); } /** Get all registered node types */ getRegisteredNodeTypes(): string[] { - return [...this.nodeExecutors.keys()]; + return ExtensionsFacet.getRegisteredNodeTypes.call(extensionsHost.of(this)); } /** @@ -2550,7 +2069,7 @@ export class AutomationEngine implements IAutomationService { * Only executors that published a descriptor appear here. */ getActionDescriptors(): ActionDescriptor[] { - return [...this.actionDescriptors.values()]; + return ExtensionsFacet.getActionDescriptors.call(extensionsHost.of(this)); } /** Get the action descriptor for a single node type, if published. */ @@ -2560,7 +2079,7 @@ export class AutomationEngine implements IAutomationService { /** Get all registered trigger types */ getRegisteredTriggerTypes(): string[] { - return [...this.triggers.keys()]; + return ExtensionsFacet.getRegisteredTriggerTypes.call(extensionsHost.of(this)); } // ── IAutomationService Contract Implementation ──────── @@ -2666,21 +2185,12 @@ export class AutomationEngine implements IAutomationService { * name's one slot ({@link placeFlowSlot}). */ private flowArmHolder(name: string, arm: FlowContender): string | undefined { - if (arm.holder) return arm.holder; - if (arm.source === 'package') return arm.packageId || undefined; - if (arm.source === 'override') { - const keys = this.flowSlots.keysOf(name); - if (keys.length === 1) return this.flowSlots.slot(keys[0])?.packageId ?? this.loaderOwnerOf(name); - // Two slots and no `holder`: no package's, so placeFlowSlot refuses it. - return keys.length === 0 ? this.loaderOwnerOf(name) : undefined; - } - return undefined; + return FlowSlotsFacet.flowArmHolder.call(flowSlotsHost.of(this), name, arm); } /** The loader's set's one owner of the bare name, asked by name alone. */ private loaderOwnerOf(name: string): string | undefined { - const owner = this.packagedFlowSource?.(name); - return typeof owner === 'string' && owner !== '' ? owner : undefined; + return FlowSlotsFacet.loaderOwnerOf.call(flowSlotsHost.of(this), name); } /** @@ -2694,48 +2204,7 @@ export class AutomationEngine implements IAutomationService { * bare name for a caller with no package (E1). */ private placeFlowSlot(name: string, arm: FlowContender): string { - // E1 (#31677 Q1), unchanged for every arm that names no slot: a name - // the resolver refuses for a caller with no package is refused, never - // armed by package id or by arrival. Only precedence's per-package - // winner names its slot (`holder`), and arms beside the others. - if (arm.holder === undefined) { - const refusal = this.flowNameRefusal(name, null); - if (refusal) throw new Error(refusal.message); - } - const packageId = this.flowArmHolder(name, arm); - if (packageId === undefined) { - const keys = this.flowSlots.keysOf(name); - if (keys.length > 1) throw new PackageScopedNameRefusedError(this.sharedFlowNameRefusal(name, null)); - return keys[0] ?? this.flowSlots.add({ packageId: null, name }).key; - } - const own = this.flowSlots.keyOf(name, packageId); - if (own !== undefined) { - // [#33893] A lone slot kept under its qualified key beside a - // disabled co-holder folds back once that holder is gone (the - // uninstall's re-sync re-registers this one). - return this.settleFlowName(name) ? this.flowKeyNow(own) : own; - } - const packageless = this.flowSlots.keyOf(name, null); - if (packageless !== undefined) { - this.flowSlots.adopt(packageless, packageId); - return packageless; - } - const incumbents = this.flowSlots.slotsOf(name); - const incumbent = incumbents.length === 1 ? incumbents[0].packageId : null; - if (incumbent !== null && this.flowHoldersSealed) this.bindPackagelessActivation(name, incumbent); - const incumbentKey = incumbents.length === 1 ? this.flowSlots.keyOf(name, incumbent) : undefined; - const { key, moved } = this.flowSlots.add({ packageId, name }); - this.moveFlowRecords(moved); - // [#33893] An incumbent already under its qualified key (filed so - // beside a disabled co-holder) moves no key as its co-holder returns, - // so the move's re-arm is done here: the M1 decline it may have taken - // while it was the name's one slot no longer applies. - if (incumbentKey !== undefined && incumbentKey !== name && moved.length === 0 && this.flows.has(incumbentKey)) { - this.sharedSlotTriggerWarned.delete(incumbentKey); - this.activateFlowTrigger(incumbentKey); - } - if (incumbent !== null && !this.flowHoldersSealed) this.flowLedgerDisabled.refusePackagelessBind(name, incumbent); - return key; + return FlowSlotsFacet.placeFlowSlot.call(flowSlotsHost.of(this), name, arm); } /** @@ -2749,42 +2218,7 @@ export class AutomationEngine implements IAutomationService { * {@link flowActivationBinds} settles once the write has. */ private bindPackagelessActivation(name: string, holder: string): void { - if (!this.flowLedgerDisabled.canBindPackageless(name, holder)) return; - const store = this.flowActivationStore; - const bound = () => { - this.flowLedgerDisabled.bindPackageless(name, holder); - this.logger.info( - `[Automation] The flow "${name}" is switched off by an activation row that names no package, and a second ` - + `package now holds a flow of that name: the row is now the switch of package "${holder}", which held ` - + 'the name alone.', - { flow: name, packageId: holder }, - ); - // The other holders were held off while the row named no package. - for (const key of this.flowSlots.keysOf(name)) { - if (!this.flows.has(key) || this.flowLedgerDisabled.has(key)) continue; - this.activateFlowTrigger(key); - this.rejudgeSubflowCallers(key); - } - }; - if (!store) { - bound(); - return; - } - this.flowLedgerDisabled.beginBindPackageless(name); - const write = Promise.resolve() - .then(() => store.setActive({ name, packageId: holder, active: false }, { adoptPackageless: true })) - .then(bound, (err: unknown) => { - this.flowLedgerDisabled.failBindPackageless(name); - this.logger.warn( - `[Automation] The flow "${name}" is switched off by an activation row that names no package, and a ` - + `second package now holds a flow of that name. Writing that row as package "${holder}"'s own ` - + 'row failed, so the row still names no package and keeps every package\'s flow of that name ' - + 'off. To turn one on, switch that package\'s flow: that writes its own row.', - { flow: name, packageId: holder, ...describeThrownForLog(err) }, - ); - }) - .finally(() => this.pendingFlowActivationBinds.delete(write)); - this.pendingFlowActivationBinds.add(write); + return FlowSlotsFacet.bindPackagelessActivation.call(flowSlotsHost.of(this), name, holder); } /** @@ -2815,10 +2249,8 @@ export class AutomationEngine implements IAutomationService { * far ({@link bindPackagelessActivation}) has landed or failed; until * then, the flows it is for stay off. */ - async flowActivationBinds(): Promise { - while (this.pendingFlowActivationBinds.size > 0) { - await Promise.allSettled([...this.pendingFlowActivationBinds]); - } + flowActivationBinds(): Promise { + return FlowSlotsFacet.flowActivationBinds.call(flowSlotsHost.of(this)); } /** @@ -2828,47 +2260,7 @@ export class AutomationEngine implements IAutomationService { * one arming gate. */ private moveFlowRecords(moved: readonly FlowKeyMove[]): void { - if (moved.length === 0) return; - for (const { from } of moved) { - this.deactivateFlowTrigger(from); - // A key that moves leaves the sharing it was declined under, so - // a later share of the name says the decline again. - this.sharedSlotTriggerWarned.delete(from); - } - const maps: Array> = [ - this.flows, - this.flowShadowing, - this.flowStatusDisabled, - this.flowVersionHistory, - this.policyDisabledFlows, - this.subflowDeclinedFlows, - this.subflowNoticeDeclinedFlows, - this.subflowRegionDeclinedFlows, - this.subflowRetryDeclinedFlows, - ]; - for (const { from, to } of moved) { - for (const map of maps) { - const records: Map = map; - if (!records.has(from)) continue; - records.set(to, records.get(from)); - records.delete(from); - } - for (const [runId, run] of this.suspendedRuns) { - if (run.flowName === from) this.suspendedRuns.set(runId, { ...run, flowName: to }); - } - // Every run the ring holds moves with it, finished runs included; - // a run still in flight, or a consumed pause put back later, is - // filed where it lands ({@link flowKeyNow}). - for (let i = 0; i < this.executionLogs.length; i++) { - const entry = this.executionLogs[i]; - if (entry.flowName === from) this.executionLogs[i] = { ...entry, flowName: to }; - } - this.movedFlowKeys.delete(to); - this.movedFlowKeys.set(from, to); - } - for (const { to } of moved) { - if (this.flows.has(to)) this.activateFlowTrigger(to); - } + return FlowSlotsFacet.moveFlowRecords.call(flowSlotsHost.of(this), moved); } /** @@ -2876,8 +2268,7 @@ export class AutomationEngine implements IAutomationService { * while a slot holds it, else where the slot changes moved it. */ private flowKeyNow(key: string): string { - for (let next = this.movedFlowKeys.get(key); next !== undefined && !this.flows.has(key); next = this.movedFlowKeys.get(key)) key = next; - return key; + return FlowSlotsFacet.flowKeyNow.call(flowSlotsHost.of(this), key); } /** @@ -2886,22 +2277,7 @@ export class AutomationEngine implements IAutomationService { * holder named, nothing picked — the package-scoped rule's own sentence. */ private sharedFlowNameRefusal(name: string, callerPackageId: string | null): PackageScopedRefusal { - // [M1] Every holder the registry names, a holder whose body was refused included. - // [#32183, R4-G] A disabled holder too: its slot stays armed, so the - // refusal names it, as on `main`. - const held = this.durableFlowHolder(name); - const candidates = held?.status === 'refused' ? held.candidates : this.flowSlots.slotsOf(name).map((slot) => - slot.packageId === null ? { kind: 'environment' as const } : { kind: 'package' as const, packageId: slot.packageId }, - ); - const base = { - status: 'refused' as const, - reason: 'ambiguous-in-environment' as const, - type: 'flow' as const, - name, - callerPackageId, - candidates, - }; - return { ...base, message: packageScopedRefusalMessage(base) }; + return FlowSlotsFacet.sharedFlowNameRefusal.call(flowSlotsHost.of(this), name, callerPackageId); } /** @@ -2929,31 +2305,7 @@ export class AutomationEngine implements IAutomationService { callerPackageId: string | null, options?: { readonly durable?: boolean }, ): { key: string } | { refusal: PackageScopedRefusal } | { absent: true } { - // [#31696] A slot key is no flow's name: it names no flow here. - if (isSlotKeySpelling(name)) return { key: unfiledFlowKey(name) }; - this.settleFlowName(name); - if (!this.flowSlots.isShared(name)) { - const refusal = this.flowNameRefusal(name, callerPackageId); - if (refusal) return { refusal }; - // [#33905] Its one holder's package is disabled: no flow, as for a - // name two packages hold that no served holder reaches. - if (options?.durable !== true && this.isDisabledSoleHolder(name)) return { absent: true }; - return { key: name }; - } - const resolution = this.flowNameResolver?.(name, callerPackageId, - options?.durable === true ? { includeDisabledPackages: true } : { servedCaller: true }); - if (resolution?.status === 'refused') return { refusal: resolution }; - if (resolution?.status === 'resolved' && resolution.holder.kind === 'package') { - const key = this.flowSlots.keyOf(name, resolution.holder.packageId); - if (key !== undefined) return { key }; - } - // [#33386] No served holder reaches the name: no flow, never another slot. - if (resolution?.status === 'not-found' && options?.durable !== true) return { absent: true }; - if (resolution === undefined && callerPackageId !== null) { - const own = this.flowSlots.keyOf(name, callerPackageId); - if (own !== undefined) return { key: own }; - } - return { refusal: this.sharedFlowNameRefusal(name, callerPackageId) }; + return FlowSlotsFacet.resolveFlowKey.call(flowSlotsHost.of(this), name, callerPackageId, options); } /** @@ -2965,10 +2317,7 @@ export class AutomationEngine implements IAutomationService { * there over every holder, served or not. */ private bareFlowKey(name: string): string | undefined { - if (isSlotKeySpelling(name)) return undefined; - this.settleFlowName(name); - if (!this.flowSlots.isShared(name)) return name; - throw new PackageScopedNameRefusedError(this.sharedFlowNameRefusal(name, null)); + return FlowSlotsFacet.bareFlowKey.call(flowSlotsHost.of(this), name); } /** @@ -2984,12 +2333,7 @@ export class AutomationEngine implements IAutomationService { * namespaced address's answer. */ private servedBareFlowKey(name: string): string | undefined { - if (isSlotKeySpelling(name)) return undefined; - this.settleFlowName(name); - if (!this.flowSlots.isShared(name)) return this.isDisabledSoleHolder(name) ? undefined : name; - const resolved = this.resolveFlowKey(name, null); - if ('refusal' in resolved) throw new PackageScopedNameRefusedError(resolved.refusal); - return 'key' in resolved ? resolved.key : undefined; + return FlowSlotsFacet.servedBareFlowKey.call(flowSlotsHost.of(this), name); } /** @@ -3004,11 +2348,7 @@ export class AutomationEngine implements IAutomationService { * attached: nothing is disabled here. */ private isDisabledHolderSlot(name: string, packageId: string): boolean { - const resolver = this.flowNameResolver; - if (resolver === undefined) return false; - const held = resolver(name, packageId); - if (held?.status !== 'resolved' || held.via !== 'own') return false; - return resolver(name, packageId, { servedCaller: true })?.status === 'not-found'; + return FlowSlotsFacet.isDisabledHolderSlot.call(flowSlotsHost.of(this), name, packageId); } /** @@ -3021,24 +2361,22 @@ export class AutomationEngine implements IAutomationService { * credentials, history) stay judged over every holder (amendment 7). */ private isDisabledSoleHolder(name: string): boolean { - const packageId = this.flowSlotPackage(name); - return packageId !== undefined && this.isDisabledHolderSlot(name, packageId); + return FlowSlotsFacet.isDisabledSoleHolder.call(flowSlotsHost.of(this), name); } /** [#31696] The package of the slot `key` files, or `undefined` (a package-less slot, or none). */ private flowSlotPackage(key: string): string | undefined { - return this.flowSlots.slot(key)?.packageId ?? undefined; + return FlowSlotsFacet.flowSlotPackage.call(flowSlotsHost.of(this), key); } /** [#31696] The flow name a slot key files: the key itself for a key no slot files. */ private flowSlotName(key: string): string { - return this.flowSlots.slot(key)?.name ?? key; + return FlowSlotsFacet.flowSlotName.call(flowSlotsHost.of(this), key); } /** [#31696] Every key a slot of the bare `name` is filed under; the name itself when none is. */ private flowSlotKeysOf(name: string): string[] { - const keys = this.flowSlots.keysOf(name); - return keys.length > 0 ? keys : [name]; + return FlowSlotsFacet.flowSlotKeysOf.call(flowSlotsHost.of(this), name); } /** @@ -3049,8 +2387,7 @@ export class AutomationEngine implements IAutomationService { * qualified key (amendment 7) and is armed, and no body was refused. */ private loneSharedFlowKey(name: string): string | undefined { - const keys = this.flowSlots.keysOf(name); - return keys.length === 1 && this.flowSlots.isShared(name) && this.flowHolder(name)?.status === 'refused' ? keys[0] : undefined; + return FlowSlotsFacet.loneSharedFlowKey.call(flowSlotsHost.of(this), name); } /** @@ -3060,15 +2397,12 @@ export class AutomationEngine implements IAutomationService { * True when it moved. */ private settleFlowName(name: string): boolean { - const moved = this.flowSlots.settle(name); - this.moveFlowRecords(moved); - return moved.length > 0; + return FlowSlotsFacet.settleFlowName.call(flowSlotsHost.of(this), name); } /** [#31696] Is `key` the key of a slot whose name another slot holds too? */ private isSharedFlowKey(key: string): boolean { - const slot = this.flowSlots.slot(key); - return slot !== undefined && this.flowSlots.isShared(slot.name); + return FlowSlotsFacet.isSharedFlowKey.call(flowSlotsHost.of(this), key); } /** @@ -3095,17 +2429,8 @@ export class AutomationEngine implements IAutomationService { * names the package dispatches through, where the bare {@link execute} * refuses a name two packages hold. Engine-local. */ - async executeSlot(packageId: string | null, name: string, context?: AutomationContext): Promise { - const key = this.flowSlots.keyOf(name, packageId); - if (key === undefined) { - return { - success: false, - error: packageId === null - ? `Flow '${name}' not found` - : `Flow '${name}' of package '${packageId}' not found`, - }; - } - return this.executeKey(key, context, Date.now()); + executeSlot(packageId: string | null, name: string, context?: AutomationContext): Promise { + return FlowSlotsFacet.executeSlot.call(flowSlotsHost.of(this), packageId, name, context); } /** @@ -3128,26 +2453,7 @@ export class AutomationEngine implements IAutomationService { * 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). - const { parsed } = this.canonicalizeFlow(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 {@link registerFlow} and {@link - // sealNodeTypeVocabulary}). - - // [#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. - for (const check of this.registrationChecks({ advisory: true })) { - const refusal = check(name, parsed); - if (refusal) throw new Error(refusal.message); - } - return parsed; + return RegistrationFacet.judgeFlowRegistration.call(registrationHost.of(this), name, definition); } /** @@ -3157,135 +2463,11 @@ export class AutomationEngine implements IAutomationService { * 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)); + return RegistrationFacet.dryRun.call(registrationHost.of(this), definition, options); } 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 - // under the slot's key. - const key = this.placeFlowSlot(name, arm); - - // Version history management - const history = this.flowVersionHistory.get(key) ?? []; - history.push({ - version: parsed.version, - definition: parsed, - createdAt: new Date().toISOString(), - }); - this.flowVersionHistory.set(key, history); - - // [#28405] The identity of the body as handed over — the stored body, - // for a flow the protocol serves — so it is the checksum the metadata - // history keys this version by. See {@link SuspendedRun.flowChecksum}. - const checksum = flowContentChecksum(definition); - if (checksum !== undefined) this.flowChecksums.set(parsed, checksum); - this.flowArms.set(parsed, arm); - this.flows.set(key, parsed); - // [#23316] Held now, so no longer refused — see {@link flowRefusals}. - if (this.loneSharedFlowKey(name) === undefined) this.flowRefusals.delete(name); - this.flowRefusals.delete(key); - // Enable/disable from the persisted deployment `status`. `obsolete`/`invalid` - // flows are DISABLED (unbound + guarded in execute); `draft`/`active` — and - // any legacy flow with no explicit status — stay enabled, so existing flows - // are unaffected (zero regression). This is how the Studio's on/off switch - // persists: it flips `status` active↔obsolete, applied on the next publish - // rebind. - // - // [ADR-0126 §7.2] Recording the STATUS dimension is now all this does. - // It used to also fold that dimension into the `flowEnabled` map and - // then work to preserve the OTHER dimension living in the same map — - // hence the old `wasStatusDisabled || !flowEnabled.has(name)` arm, - // whose job was to re-enable on a status flip without clobbering a - // runtime toggle. With the activation ledger holding the toggle - // dimension separately ({@link flowLedgerDisabled}) the two no longer - // share a slot, so there is nothing to reconcile: a status flip moves - // the status bit, a ledger flip moves the ledger bit, and - // {@link isFlowEnabled} composes them. That the reconciliation - // DISAPPEARS rather than moving is the sign the two were always - // distinct facts crammed into one map. - const flowStatus = (parsed as { status?: string }).status; - this.flowStatusDisabled.set(key, flowStatus === 'obsolete' || flowStatus === 'invalid'); - this.logger.info(`Flow registered: ${key} (version ${parsed.version})`); - - // ADR-0018 §M1 node-type check, inline — but ONLY once the vocabulary - // is closed (#4771). During boot the registry is still filling up - // (plugins contribute executors from their own init()/start(), which - // runs after the flow pull), so a verdict here would judge a world that - // has not finished forming — that is what warned about every showcase - // `approval` flow 0.8s before the `approval` executor existed. The - // authoritative boot pass runs in sealNodeTypeVocabulary(); after it, - // every later registration (Studio publish, dev reload, a runtime - // registerFlow) IS against a complete vocabulary, so it warns at once. - // Placed after the enable/disable resolution above so it can honor the - // same "a flow that cannot run cannot fail" rule as the audit. - if (this.nodeTypeVocabularySealed && this.isFlowEnabled(key)) { - const known = this.knownNodeTypes(); - const unknownTypes = this.unknownNodeTypes(parsed, known); - if (unknownTypes.length > 0) { - this.warnUnknownNodeTypes({ flowName: key, unknownTypes, knownTypes: [...known] }); - } - } - - // Re-bind in case the definition changed its trigger, then (re)activate. - // [ADR-0126 §7.2] A disabled flow — ledger or status — is NOT re-armed - // here, which is what makes the unbind survive a republish and a - // restart: the boot pull re-registers every flow, so a hydrated ledger - // row has to be able to keep a trigger unbound through exactly this - // path. The refusal is `activateFlowTrigger`'s own enablement gate, - // the one every arming path shares — ⛔ not re-asked here, where a - // caller-side check once stood alone and `registerTrigger` had none. - this.deactivateFlowTrigger(key); - this.activateFlowTrigger(key); - // [#20725, ADR-0126 §7.3] And the flows that call THIS one: a subflow - // republished `obsolete` disarms its packaged callers, republished - // `active` re-arms the ones the gate declined — both through the gate. - this.rejudgeSubflowCallers(key); - - // #12206 (Option A) — hand the caller the canonicalized flow this - // registration stored: the same object `this.flows` now holds and - // {@link getFlow} answers. The `/automation` write doors relay it, so - // a write answers the shape the subsequent read serves. - return parsed; + return RegistrationFacet.registerFlow.call(registrationHost.of(this), name, definition, armedFrom); } /** @@ -3309,16 +2491,7 @@ export class AutomationEngine implements IAutomationService { * @throws `DELETE_RESTRICTED` / 409 as above; nothing is removed. */ unregisterFlow(name: string): void { - // The body lives in ./flow-definitions.ts (#25222). - const host: ThisParameterType = { - flows: this.flows, - isPackagedFlow: (...a) => this.isPackagedFlow(...a), - packagedSubflowCallers: (...a) => this.packagedSubflowCallers(...a), - refuseUnderReachingCallers: (...a) => this.refuseUnderReachingCallers(...a), - withdrawFlow: (...a) => this.withdrawFlowKey(...a), - }; - const key = this.bareFlowKey(name); - if (key !== undefined) unregisterFlow.call(host, key); + return RegistrationFacet.unregisterFlow.call(registrationHost.of(this), name); } /** @@ -3339,10 +2512,7 @@ export class AutomationEngine implements IAutomationService { * that package, reported at the caller's subflow node. */ withdrawFlow(name: string): void { - // [#31696] A bare name two slots hold is refused; one slot is - // withdrawn by {@link withdrawFlowSlot}. - const key = this.bareFlowKey(name); - if (key !== undefined) this.withdrawFlowKey(key); + return RegistrationFacet.withdrawFlow.call(registrationHost.of(this), name); } /** @@ -3351,33 +2521,11 @@ export class AutomationEngine implements IAutomationService { * A no-op for a slot the engine does not hold. Engine-local. */ withdrawFlowSlot(packageId: string | null, name: string): void { - const key = this.flowSlots.keyOf(name, packageId); - if (key !== undefined) this.withdrawFlowKey(key); + return RegistrationFacet.withdrawFlowSlot.call(registrationHost.of(this), packageId, name); } private withdrawFlowKey(name: string): void { - this.sharedSlotTriggerWarned.delete(name); - // The body lives in ./flow-definitions.ts (#25222). - const host: ThisParameterType = { - deactivateFlowTrigger: (...a) => this.deactivateFlowTrigger(...a), - flows: this.flows, - flowStatusDisabled: this.flowStatusDisabled, - flowVersionHistory: this.flowVersionHistory, - policyDisabledFlows: this.policyDisabledFlows, - subflowDeclinedFlows: this.subflowDeclinedFlows, - subflowNoticeDeclinedFlows: this.subflowNoticeDeclinedFlows, - subflowRegionDeclinedFlows: this.subflowRegionDeclinedFlows, - subflowRetryDeclinedFlows: this.subflowRetryDeclinedFlows, - flowRefusals: this.flowRefusals, - logger: this.logger, - }; - withdrawFlow.call(host, name); - // [#31696] The slot goes with its flow; a name left with one slot - // files it under the bare name again. [#33893] Not while the registry - // still holds the name under a disabled package (the re-sync of a - // disable withdraws its slot): the served holder keeps its key and - // its binding (amendment 7). - this.moveFlowRecords(this.flowSlots.remove(name)); + return RegistrationFacet.withdrawFlowKey.call(registrationHost.of(this), name); } /** @@ -3395,20 +2543,7 @@ export class AutomationEngine implements IAutomationService { * before it changes anything), and that flow is registered, not refused. */ recordFlowRefusal(name: string, error: unknown): void { - // The body lives in ./flow-definitions.ts (#25222). - // [M1] Recorded beside a lone slot of a name the registry holds twice - // (another package's body), and that slot leaves its trigger. - const lone = this.loneSharedFlowKey(name); - const host: ThisParameterType = { - flows: lone === undefined ? this.flows : new Map(), - flowRefusals: this.flowRefusals, - }; - recordFlowRefusal.call(host, name, error); - if (lone !== undefined) this.deactivateFlowTrigger(lone); - // [#33893] A lone slot under its qualified key was armed while the - // co-holder was not yet registered; asked again, it takes the decline - // and says it. - if (lone !== undefined && lone !== name) this.activateFlowTrigger(lone); + return RegistrationFacet.recordFlowRefusal.call(registrationHost.of(this), name, error); } /** @@ -3420,13 +2555,7 @@ export class AutomationEngine implements IAutomationService { * otherwise. A read: it records nothing. */ getFlowRegistration(name: string): FlowRegistration { - // [#31696] Registered while any slot holds the name. A slot key is - // no flow's name. - if (isSlotKeySpelling(name)) return { state: 'unregistered' }; - const refusal = this.flowRefusals.get(name); - const lone = refusal !== undefined && this.loneSharedFlowKey(name) !== undefined; - if (!lone && (this.flows.has(name) || this.flowSlots.keysOf(name).length > 0)) return { state: 'registered' }; - return refusal ? { state: 'refused', reason: { ...refusal } } : { state: 'unregistered' }; + return RegistrationFacet.getFlowRegistration.call(registrationHost.of(this), name); } /** @@ -3569,13 +2698,7 @@ export class AutomationEngine implements IAutomationService { * {@link registerFlow} path by the time this is called. */ recordFlowShadowing(record: FlowShadowingRecord): void { - if (!record.shadowed.length) return; - // [#31696] Filed under the armed contender's slot. - const holder = record.armed.holder ?? (record.armed.source === 'package' ? record.armed.packageId : undefined); - const keys = this.flowSlots.keysOf(record.name); - const key = (holder !== undefined ? this.flowSlots.keyOf(record.name, holder) : undefined) - ?? (keys.length === 1 ? keys[0] : record.name); - this.flowShadowing.set(key, record); + return RegistrationFacet.recordFlowShadowing.call(registrationHost.of(this), record); } /** @@ -3589,15 +2712,15 @@ export class AutomationEngine implements IAutomationService { * there to be listed. */ getShadowedFlows(): FlowShadowingRecord[] { - return [...this.flowShadowing.values()]; + return RegistrationFacet.getShadowedFlows.call(registrationHost.of(this)); } /** * Every flow this engine holds, by name. [#31696] One entry per slot, so * two packages' flows of one name list that name twice. */ - async listFlows(): Promise { - return [...this.flows.keys()].map((key) => this.flowSlotName(key)); + listFlows(): Promise { + return RegistrationFacet.listFlows.call(registrationHost.of(this)); } /** @@ -3607,9 +2730,8 @@ export class AutomationEngine implements IAutomationService { * [#33905] `null` too for a name one package holds whose package is * disabled. */ - async getFlow(name: string): Promise { - const key = this.servedBareFlowKey(name); - return key === undefined ? null : this.flows.get(key) ?? null; + getFlow(name: string): Promise { + return RegistrationFacet.getFlow.call(registrationHost.of(this), name); } /** @@ -3618,8 +2740,7 @@ export class AutomationEngine implements IAutomationService { * Engine-local. */ getRunFlow(context: AutomationContext | undefined): FlowParsed | null { - const key = this.flowKeyOfRun(context); - return key === undefined ? null : this.flows.get(key) ?? null; + return RegistrationFacet.getRunFlow.call(registrationHost.of(this), context); } /** @@ -3652,11 +2773,7 @@ export class AutomationEngine implements IAutomationService { * package's slot moved to. `undefined` for no run. Engine-local. */ flowKeyOfRun(context: AutomationContext | undefined): string | undefined { - const key = flowRunKey(context); - if (key === undefined || this.flows.has(key)) return key; - const name = (context as { flowName?: unknown } | undefined)?.flowName; - if (typeof name !== 'string') return key; - return this.flowSlots.keyOf(name, flowRunPackage(context) ?? null) ?? key; + return RegistrationFacet.flowKeyOfRun.call(registrationHost.of(this), context); } /** @@ -3664,8 +2781,7 @@ export class AutomationEngine implements IAutomationService { * (`null`: the package-less flow of that name), or `null`. Engine-local. */ getFlowSlot(packageId: string | null, name: string): FlowParsed | null { - const key = this.flowSlots.keyOf(name, packageId); - return key === undefined ? null : this.flows.get(key) ?? null; + return RegistrationFacet.getFlowSlot.call(registrationHost.of(this), packageId, name); } /** @@ -3683,8 +2799,7 @@ export class AutomationEngine implements IAutomationService { * bare name. */ getHeldFlow(name: string): FlowParsed | null { - const key = this.bareFlowKey(name); - return key === undefined ? null : this.flows.get(key) ?? null; + return RegistrationFacet.getHeldFlow.call(registrationHost.of(this), name); } /** @@ -3713,8 +2828,7 @@ export class AutomationEngine implements IAutomationService { * kept on the definition for display only. */ setPackagedFlowSource(source: PackagedFlowSource | undefined): void { - this.packagedFlowSource = source; - this.packagedFlowDefaults = new WeakMap(); + return FlowSlotsFacet.setPackagedFlowSource.call(flowSlotsHost.of(this), source); } /** @@ -3727,8 +2841,7 @@ export class AutomationEngine implements IAutomationService { * ({@link packagedFlowDefault}). */ setPackagedFlowDefaultSource(source: PackagedFlowDefaultSource | undefined): void { - this.packagedFlowDefaultSource = source; - this.packagedFlowDefaults = new WeakMap(); + return FlowSlotsFacet.setPackagedFlowDefaultSource.call(flowSlotsHost.of(this), source); } /** @@ -3756,17 +2869,7 @@ export class AutomationEngine implements IAutomationService { * deployment — and for every flow while no reader is attached. */ packagedFlowOwner(name: string): string | undefined { - // [ADR-0150 D4, #31696] `name` may be a slot key. A slot of a name two - // slots hold asks the loader's set for its own package's flow; a bare - // name two slots hold has no one owner, and answers none. - const slot = this.flowSlots.slot(name); - if (slot !== undefined && this.flowSlots.isShared(slot.name)) { - if (slot.packageId === null) return undefined; - return this.packagedFlowSource?.(slot.name, slot.packageId) === slot.packageId ? slot.packageId : undefined; - } - if (slot === undefined && this.flowSlots.isShared(name)) return undefined; - const owner = this.packagedFlowSource?.(name); - return typeof owner === 'string' && owner !== '' ? owner : undefined; + return FlowSlotsFacet.packagedFlowOwner.call(flowSlotsHost.of(this), name); } /** @@ -3810,28 +2913,7 @@ export class AutomationEngine implements IAutomationService { | { readonly status: 'served'; readonly key: string } | { readonly status: 'unadmitted' } | { readonly status: 'refused'; readonly candidates: PackageScopedRefusal['candidates'] } { - if (isSlotKeySpelling(flowName) || flowName.startsWith('\u0000')) return { status: 'unadmitted' }; - this.settleFlowName(flowName); - if (!this.flowSlots.isShared(flowName)) { - const packageId = this.flowSlotPackage(flowName); - return packageId !== undefined && this.isDisabledHolderSlot(flowName, packageId) - ? this.disabledHolderHookRefused(flowName, packageId, flowName) - : undefined; - } - if (address === undefined) return { status: 'refused', candidates: this.sharedFlowNameRefusal(flowName, null).candidates }; - const environment = address.qualifier === ENVIRONMENT_ADDRESS_SEGMENT; - const keys = this.flowSlots.keysOf(flowName).filter((key) => { - const slot = this.flowSlots.slot(key)!; - if (environment) return slot.packageId === null; - return slot.packageId !== null && address.namespaceOwners.includes(slot.packageId) - && this.packagedFlowOwner(key) === slot.packageId; - }); - if (keys.length !== 1) return { status: 'unadmitted' }; - const packageId = this.flowSlotPackage(keys[0]); - if (packageId !== undefined && this.isDisabledHolderSlot(flowName, packageId)) { - return this.disabledHolderHookRefused(flowName, packageId, keys[0]); - } - return { status: 'served', key: keys[0] }; + return FlowSlotsFacet.inboundHookSlot.call(flowSlotsHost.of(this), flowName, address); } /** @@ -3841,14 +2923,7 @@ export class AutomationEngine implements IAutomationService { * refusal, so nothing that claims to be persisted is lost). */ private disabledHolderHookRefused(name: string, packageId: string, key: string): { readonly status: 'unadmitted' } { - this.logger.info( - `Inbound hook post for flow '${name}' of package '${packageId}', which is disabled — refused with the ` - + 'one answer every unverified post gets: nothing was enqueued, and no other package\'s flow of the ' - + 'name was reached in its place. A sender that retries on a non-2xx keeps the event and can ' - + 'redeliver it once the package is enabled.', - { cause: 'disabled-holder', flow: name, package: packageId, slot: key }, - ); - return { status: 'unadmitted' }; + return FlowSlotsFacet.disabledHolderHookRefused.call(flowSlotsHost.of(this), name, packageId, key); } /** @@ -3857,12 +2932,12 @@ export class AutomationEngine implements IAutomationService { * precedence asks of a name two packages may hold. */ packagedFlowSlotOwner(name: string, packageId: string): string | undefined { - return this.packagedFlowSource?.(name, packageId) === packageId ? packageId : undefined; + return FlowSlotsFacet.packagedFlowSlotOwner.call(flowSlotsHost.of(this), name, packageId); } /** [#20761] Is `name` a packaged flow — {@link packagedFlowOwner}, as a verdict. */ private isPackagedFlow(name: string): boolean { - return this.packagedFlowOwner(name) !== undefined; + return FlowSlotsFacet.isPackagedFlow.call(flowSlotsHost.of(this), name); } /** @@ -3890,16 +2965,7 @@ export class AutomationEngine implements IAutomationService { * to arm it, and the stored pass names it. */ private refuseUnpackagedDefaultActive(flowName: string, flow: FlowParsed): RegistrationCheckRefusal | undefined { - if (flow.defaultActive === undefined || this.isShippedFlowName(flowName, flow)) return undefined; - const why = - `'${flowName}' declares defaultActive, which is the default of the switch an administrator turns a ` + - `PACKAGED flow on and off with, and '${flowName}' was authored in this deployment, not shipped by a ` + - `package. A flow authored here is switched by its own status: remove defaultActive, and publish ` + - `it with status 'obsolete' to keep it off or 'active' to arm it.`; - return { - message: `Flow ${why}`, - sites: [{ path: 'flows[0].defaultActive', from: JSON.stringify(flow.defaultActive), detail: `the flow ${why}` }], - }; + return FlowSlotsFacet.refuseUnpackagedDefaultActive.call(flowSlotsHost.of(this), flowName, flow); } /** @@ -3915,12 +2981,7 @@ export class AutomationEngine implements IAutomationService { * stamp naming a package that ships no such flow answers no. */ private isShippedFlowName(name: string, flow: FlowParsed): boolean { - if (this.isPackagedFlow(name)) return true; - const bare = this.flowSlots.slot(name)?.name ?? name; - const stamped = (flow as { _packageId?: unknown })._packageId; - const candidates = new Set(typeof stamped === 'string' && stamped !== '' ? [stamped] : []); - for (const slot of this.flowSlots.slotsOf(bare)) if (slot.packageId !== null) candidates.add(slot.packageId); - return [...candidates].some((packageId) => this.packagedFlowSlotOwner(bare, packageId) !== undefined); + return FlowSlotsFacet.isShippedFlowName.call(flowSlotsHost.of(this), name, flow); } /** @@ -3942,17 +3003,7 @@ export class AutomationEngine implements IAutomationService { * ({@link refreshPackagedFlowDefaults}). */ private packagedFlowDefault(key: string): boolean | undefined { - const armed = this.flows.get(key); - if (!armed) return undefined; - if (this.flowArms.get(armed)?.source === 'package') return armed.defaultActive; - const source = this.packagedFlowDefaultSource; - if (source === undefined) return undefined; - const asked = this.packagedFlowDefaults.get(armed); - if (asked !== undefined) return asked.value; - const owner = this.packagedFlowOwner(key); - const value = owner === undefined ? undefined : source(this.flowSlots.slot(key)?.name ?? key, owner); - this.packagedFlowDefaults.set(armed, { value }); - return value; + return FlowSlotsFacet.packagedFlowDefault.call(flowSlotsHost.of(this), key); } /** @@ -3980,21 +3031,7 @@ export class AutomationEngine implements IAutomationService { * flow an administrator switched does not move. */ refreshPackagedFlowDefaults(): string[] { - const before = new Map(); - for (const [key, armed] of this.flows) { - if (this.flowArms.get(armed)?.source !== 'package') before.set(key, this.isFlowEnabled(key)); - } - this.packagedFlowDefaults = new WeakMap(); - const moved: string[] = []; - for (const [key, wasEnabled] of before) { - if (this.isFlowEnabled(key) === wasEnabled) continue; - if (wasEnabled) this.deactivateFlowTrigger(key); - else this.activateFlowTrigger(key); - moved.push(key); - } - // [#20725, ADR-0126 §7.3] The callers of a subflow that moved, through the same gate. - for (const key of moved) this.rejudgeSubflowCallers(key); - return moved; + return FlowSlotsFacet.refreshPackagedFlowDefaults.call(flowSlotsHost.of(this)); } /** @@ -4033,8 +3070,7 @@ export class AutomationEngine implements IAutomationService { * attached. Read-only; records nothing. */ private flowNameRefusal(name: string, callerPackageId: string | null): PackageScopedRefusal | undefined { - const resolution = this.flowNameResolver?.(name, callerPackageId); - return resolution?.status === 'refused' ? resolution : undefined; + return FlowSlotsFacet.flowNameRefusal.call(flowSlotsHost.of(this), name, callerPackageId); } /** @@ -4066,8 +3102,7 @@ export class AutomationEngine implements IAutomationService { * as before. Read-only. */ connectorNameRefusal(connectorId: string, context: AutomationContext | undefined): PackageScopedRefusal | undefined { - const resolved = this.resolveConnectorInstanceFor(connectorId, this.flowCallerPackage(context)); - return resolved.status === 'refused' ? resolved.refusal : undefined; + return FlowSlotsFacet.connectorNameRefusal.call(flowSlotsHost.of(this), connectorId, context); } /** @@ -4112,19 +3147,7 @@ export class AutomationEngine implements IAutomationService { * Read-only. */ resolveConnectorInstanceFor(connectorId: string, callerPackageId: string | null): ConnectorInstanceResolution { - const resolver = this.connectorNameResolver; - const meant = resolver?.(connectorId, callerPackageId); - if (meant?.status === 'refused') return { status: 'refused', refusal: meant }; - if (meant?.status === 'resolved') { - const packageId = meant.holder.kind === 'package' ? meant.holder.packageId : null; - return this.connectors.get(connectorId, packageId) ? { status: 'instance', packageId } : this.codeRegisteredInstance(connectorId); - } - if (meant?.status === 'not-found' - && resolver?.(connectorId, callerPackageId, { includeDisabledPackages: true })?.status !== 'not-found') { - return this.codeRegisteredInstance(connectorId); - } - const sole = this.connectors.sole(connectorId); - return sole ? { status: 'instance', packageId: sole.packageId } : { status: 'none' }; + return FlowSlotsFacet.resolveConnectorInstanceFor.call(flowSlotsHost.of(this), connectorId, callerPackageId); } /** @@ -4133,7 +3156,7 @@ export class AutomationEngine implements IAutomationService { * the holder it resolves to has no instance of its own. */ private codeRegisteredInstance(connectorId: string): ConnectorInstanceResolution { - return this.connectors.get(connectorId, null)?.origin === 'plugin' ? { status: 'instance', packageId: null } : { status: 'none' }; + return FlowSlotsFacet.codeRegisteredInstance.call(flowSlotsHost.of(this), connectorId); } /** @@ -4152,11 +3175,7 @@ export class AutomationEngine implements IAutomationService { * (#31699). Read-only. */ flowCallerPackage(context: AutomationContext | undefined): string | null { - // [#31696] The slot key the run stamped, where its flow's name is one - // two slots hold; else the name, which is then its key. - const caller = this.flowKeyOfRun(context); - if (caller === undefined) return null; - return this.armedFlowPackage(caller) ?? null; + return FlowSlotsFacet.flowCallerPackage.call(flowSlotsHost.of(this), context); } /** @@ -4178,9 +3197,7 @@ export class AutomationEngine implements IAutomationService { * both carry the base's `_packageId`. Read-only. */ armedFlowPackage(name: string): string | undefined { - const armed = this.flows.get(name); - if (!armed || this.flowArms.get(armed)?.source !== 'package') return undefined; - return this.packagedFlowOwner(name); + return FlowSlotsFacet.armedFlowPackage.call(flowSlotsHost.of(this), name); } /** @@ -4198,7 +3215,7 @@ export class AutomationEngine implements IAutomationService { * never this answer. */ flowHolder(name: string): PackageScopedResolution | undefined { - return this.flowNameResolver?.(name, null); + return FlowSlotsFacet.flowHolder.call(flowSlotsHost.of(this), name); } /** @@ -4211,7 +3228,7 @@ export class AutomationEngine implements IAutomationService { * doors keep judging the served holders. Read-only; records nothing. */ durableFlowHolder(name: string): PackageScopedResolution | undefined { - return this.flowNameResolver?.(name, null, { includeDisabledPackages: true }); + return FlowSlotsFacet.durableFlowHolder.call(flowSlotsHost.of(this), name); } /** @@ -4224,8 +3241,7 @@ export class AutomationEngine implements IAutomationService { * refusal is `null`. */ flowHolderPackage(name: string): string | null { - const answer = this.flowHolder(name); - return answer?.status === 'resolved' && answer.holder.kind === 'package' ? answer.holder.packageId : null; + return FlowSlotsFacet.flowHolderPackage.call(flowSlotsHost.of(this), name); } /** @@ -4254,19 +3270,7 @@ export class AutomationEngine implements IAutomationService { * claimBare: true }` — the bare key, as before. */ flowDispatchHolder(name: string): { packageId: string | null; claimBare: boolean; name?: string } { - if (isSlotKeySpelling(name)) { - const slot = this.flowSlots.slot(name); - if (slot) return { packageId: slot.packageId, claimBare: false, name: slot.name }; - } - // [#32183] Over every holder, a disabled package's included - // (`durableFlowHolder`): a dispatch key names a row of the ledger, the - // row the re-key backfill scopes over every holder, and a disable is - // reversible, so it moves no key. A flow only a disabled package holds - // keeps that package's scope; a name an enabled and a disabled package - // hold keeps the collision guard, as on `main`. - const answer = this.durableFlowHolder(name); - if (answer?.status === 'refused') return { packageId: this.armedFlowPackage(name) ?? null, claimBare: false }; - return { packageId: answer?.status === 'resolved' && answer.holder.kind === 'package' ? answer.holder.packageId : null, claimBare: true }; + return FlowSlotsFacet.flowDispatchHolder.call(flowSlotsHost.of(this), name); } /** @@ -4276,57 +3280,7 @@ export class AutomationEngine implements IAutomationService { * carries, as before. */ setFlowCredentialSource(source: FlowCredentialSource | undefined): void { - // [ADR-0150 D8 row R9, #31696] Asked by slot key, answered by the - // flow's name and — for a name two packages hold — its package. A - // bare name two packages hold names neither flow, so it is refused - // (409, naming both), as at every bare door. - const at = (key: string): [string, string | undefined] => { - const slot = this.flowSlots.slot(key); - if (!slot) { - if (this.flowSlots.isShared(key)) { - throw new PackageScopedNameRefusedError(this.sharedFlowNameRefusal(key, null)); - } - return [key, undefined]; - } - if (!this.flowSlots.isShared(slot.name)) return [slot.name, undefined]; - return [slot.name, slot.packageId ?? '']; - }; - // [S3] A source that does not answer by package is never asked for a - // slot of a shared name: it fails closed, naming the slot. - const scoped = source?.readsByPackage === true; - const unscopedRefusal = (name: string, flowPackage: string) => { - const others = this.flowSlots.slotsOf(name) - .map((slot) => slot.packageId ?? '') - .filter((packageId) => packageId !== flowPackage); - return new FlowCredentialUnresolvableError( - `Flow '${name}' of package "${flowPackage}": its credentials cannot be read. ` - + `${others.map((p) => `Package "${p}"`).join(', ')} also ${others.length === 1 ? 'holds' : 'hold'} a flow ` - + `named '${name}', and the flow credential source attached to this engine reads by flow name alone, ` - + 'so it could answer another package\'s secret. Nothing was read. Attach a source that reads by ' - + 'package (FlowCredentialSource.readsByPackage).', - ); - }; - this.flowCredentialSource = source && { - readsByPackage: true, - holds: (key, nodeId, credentialKey) => { - const [name, flowPackage] = at(key); - if (flowPackage === undefined) return source.holds(name, nodeId, credentialKey); - // [S1] By name alone, a "no" means no package holds one, so an unsigned node runs. - return scoped ? source.holds(name, nodeId, credentialKey, flowPackage) : source.holds(name, nodeId, credentialKey); - }, - held: (key) => { - const [name, flowPackage] = at(key); - if (flowPackage === undefined) return source.held(name); - if (!scoped) throw unscopedRefusal(name, flowPackage); - return source.held(name, flowPackage); - }, - resolve: async (key, nodeId, credentialKey) => { - const [name, flowPackage] = at(key); - if (flowPackage === undefined) return source.resolve(name, nodeId, credentialKey); - if (!scoped) throw unscopedRefusal(name, flowPackage); - return source.resolve(name, nodeId, credentialKey, flowPackage); - }, - }; + return ConnectorDoorsFacet.setFlowCredentialSource.call(connectorDoorsHost.of(this), source); } /** @@ -4367,19 +3321,8 @@ export class AutomationEngine implements IAutomationService { * pull ran would be the silent no-op the contract's rejection rule exists * to rule out. */ - async pullConnectorSource(request: ConnectorSourcePullRequest): Promise { - if (!this.connectorPullSource) { - // ADR-0112: the code the executor itself answers for "cannot pull - // now" (a degraded connector), so a caller branches on one pair. - throw Object.assign( - new Error( - `[Automation] pullConnectorSource('${request.mapping}'): this automation engine has no connector sync ` - + 'executor attached — it is attached by AutomationServicePlugin at init(); a bare engine cannot pull. Nothing was pulled.', - ), - { code: 'SERVICE_UNAVAILABLE', status: 503 }, - ); - } - return this.connectorPullSource(request); + pullConnectorSource(request: ConnectorSourcePullRequest): Promise { + return ConnectorDoorsFacet.pullConnectorSource.call(connectorDoorsHost.of(this), request); } /** @@ -4393,14 +3336,7 @@ export class AutomationEngine implements IAutomationService { /** [#27237] The door, or the refusal a bare engine answers: nothing here can store a credential. */ private requireConnectorCredentialDoor(verb: string): ConnectorCredentialDoor { - if (this.connectorCredentialDoor) return this.connectorCredentialDoor; - throw Object.assign( - new Error( - `[Automation] ${verb}: this automation engine has no connector credential door attached — it is attached by ` - + 'AutomationServicePlugin at init(); a bare engine has no declared connectors and no credential store.', - ), - { code: 'SERVICE_UNAVAILABLE', status: 503 }, - ); + return ConnectorDoorsFacet.requireConnectorCredentialDoor.call(connectorDoorsHost.of(this), verb); } /** @@ -4415,7 +3351,7 @@ export class AutomationEngine implements IAutomationService { * @returns a disposer that detaches the transport. */ attachConnectorCredentialPubSub(pubsub: IPubSub, nodeId: string): () => void { - return this.requireConnectorCredentialDoor('attachConnectorCredentialPubSub()').attachClusterPubSub(pubsub, nodeId); + return ConnectorDoorsFacet.attachConnectorCredentialPubSub.call(connectorDoorsHost.of(this), pubsub, nodeId); } /** @@ -4427,23 +3363,23 @@ export class AutomationEngine implements IAutomationService { * credential rows, so every instance naming a reference that changed during * the outage re-materializes. A no-op until a transport is attached. */ - async resyncConnectorCredentialPubSub(): Promise { - await this.requireConnectorCredentialDoor('resyncConnectorCredentialPubSub()').resyncFromCluster?.(); + resyncConnectorCredentialPubSub(): Promise { + return ConnectorDoorsFacet.resyncConnectorCredentialPubSub.call(connectorDoorsHost.of(this)); } /** [#27237] `IAutomationService.listConnectorCredentialRefs` — references and states, never a value. */ - async listConnectorCredentialRefs(): Promise { - return this.requireConnectorCredentialDoor('listConnectorCredentialRefs()').list(); + listConnectorCredentialRefs(): Promise { + return ConnectorDoorsFacet.listConnectorCredentialRefs.call(connectorDoorsHost.of(this)); } /** [#27237] `IAutomationService.setConnectorCredential` — store one value, re-materialize its instances. */ - async setConnectorCredential(request: ConnectorCredentialSetRequest): Promise { - return this.requireConnectorCredentialDoor(`setConnectorCredential('${request.ref}')`).set(request); + setConnectorCredential(request: ConnectorCredentialSetRequest): Promise { + return ConnectorDoorsFacet.setConnectorCredential.call(connectorDoorsHost.of(this), request); } /** [#27237] `IAutomationService.clearConnectorCredential` — remove one value, degrade its instances. */ - async clearConnectorCredential(request: ConnectorCredentialClearRequest): Promise { - return this.requireConnectorCredentialDoor(`clearConnectorCredential('${request.ref}')`).clear(request); + clearConnectorCredential(request: ConnectorCredentialClearRequest): Promise { + return ConnectorDoorsFacet.clearConnectorCredential.call(connectorDoorsHost.of(this), request); } /** ADR-0143 D5 — attach (or detach) the connector connection door; the automation plugin does it at `init()`. */ @@ -4453,39 +3389,32 @@ export class AutomationEngine implements IAutomationService { /** ADR-0143 D5 — the door, or the refusal a bare engine answers: nothing here can connect an instance. */ private requireConnectorConnectionDoor(verb: string): ConnectorConnectionDoor { - if (this.connectorConnectionDoor) return this.connectorConnectionDoor; - throw Object.assign( - new Error( - `[Automation] ${verb}: this automation engine has no connector connection door attached — it is attached by ` - + 'AutomationServicePlugin at init(); a bare engine has no declared connectors and no connection store.', - ), - { code: 'SERVICE_UNAVAILABLE', status: 503 }, - ); + return ConnectorDoorsFacet.requireConnectorConnectionDoor.call(connectorDoorsHost.of(this), verb); } /** ADR-0143 D3 — `IAutomationService.getConnectorConnection`: a status, never a token. */ - async getConnectorConnection(request: ConnectorConnectionRequest): Promise { - return this.requireConnectorConnectionDoor(`getConnectorConnection('${request.connector}')`).get(request); + getConnectorConnection(request: ConnectorConnectionRequest): Promise { + return ConnectorDoorsFacet.getConnectorConnection.call(connectorDoorsHost.of(this), request); } /** ADR-0143 D5 — `IAutomationService.beginConnectorConnection`: the authorization URL to send the browser to. */ - async beginConnectorConnection(request: ConnectorConnectionRequest): Promise { - return this.requireConnectorConnectionDoor(`beginConnectorConnection('${request.connector}')`).begin(request); + beginConnectorConnection(request: ConnectorConnectionRequest): Promise { + return ConnectorDoorsFacet.beginConnectorConnection.call(connectorDoorsHost.of(this), request); } /** ADR-0143 D5 — `IAutomationService.completeConnectorConnection`: the redirect's code exchanged and stored. */ - async completeConnectorConnection(request: ConnectorConnectionCallbackRequest): Promise { - return this.requireConnectorConnectionDoor('completeConnectorConnection()').complete(request); + completeConnectorConnection(request: ConnectorConnectionCallbackRequest): Promise { + return ConnectorDoorsFacet.completeConnectorConnection.call(connectorDoorsHost.of(this), request); } /** ADR-0143 D5 — `IAutomationService.revokeConnectorConnection`: the organization's connection removed. */ - async revokeConnectorConnection(request: ConnectorConnectionRequest): Promise { - return this.requireConnectorConnectionDoor(`revokeConnectorConnection('${request.connector}')`).revoke(request); + revokeConnectorConnection(request: ConnectorConnectionRequest): Promise { + return ConnectorDoorsFacet.revokeConnectorConnection.call(connectorDoorsHost.of(this), request); } /** [#20790] Does the credential channel hold the LIVE credential at this position? */ holdsFlowCredential(flowName: string, nodeId: string, key: string): boolean { - return this.flowCredentialSource?.holds(flowName, nodeId, key) ?? false; + return ConnectorDoorsFacet.holdsFlowCredential.call(connectorDoorsHost.of(this), flowName, nodeId, key); } /** @@ -4493,9 +3422,8 @@ export class AutomationEngine implements IAutomationService { * `undefined` when it holds none; throws when it holds one that does not * come back (see {@link FlowCredentialSource.resolve}). */ - async resolveFlowCredential(flowName: string, nodeId: string, key: string): Promise { - if (!this.flowCredentialSource) return undefined; - return this.flowCredentialSource.resolve(flowName, nodeId, key); + resolveFlowCredential(flowName: string, nodeId: string, key: string): Promise { + return ConnectorDoorsFacet.resolveFlowCredential.call(connectorDoorsHost.of(this), flowName, nodeId, key); } /** @@ -4506,16 +3434,7 @@ export class AutomationEngine implements IAutomationService { * copy would share it. */ flowCredentialHoldings(name: string): FlowCredentialHolding[] { - // [#31696] By name: a slot key is no flow's name, and a name two - // packages hold names neither flow (no slot is filed under it). - if (isSlotKeySpelling(name)) return []; - // The body lives in ./flow-definitions.ts (#25222). - const readFlowCredentialSource = () => this.flowCredentialSource; - const host: ThisParameterType = { - flows: this.flows, - get flowCredentialSource() { return readFlowCredentialSource(); }, - }; - return flowCredentialHoldings.call(host, name); + return ConnectorDoorsFacet.flowCredentialHoldings.call(connectorDoorsHost.of(this), name); } /** @@ -4610,7 +3529,7 @@ export class AutomationEngine implements IAutomationService { * decision it does not own. */ private isFlowEnabled(name: string): boolean { - return this.flowStatusDisabled.get(name) !== true && !this.flowLedgerDisabled.has(name); + return EnablementFacet.isFlowEnabled.call(enablementHost.of(this), name); } /** @@ -4628,27 +3547,7 @@ export class AutomationEngine implements IAutomationService { * (AGENTS.md "Degradation log levels"). */ private describeDisabledFlow(flowName: string): string { - if (this.flowLedgerDisabled.offByDefault(flowName)) { - // [#34655] No row: the package ships it off and no administrator - // has switched it on here. - this.logger.info( - `FLOW_DISABLED: packaged flow '${flowName}' refused — its package ships it switched off ` + - '(defaultActive: false) and the activation ledger (sys_metadata_activation) holds no row ' + - 'switching it on.', - { flow: flowName, refusal: 'FLOW_DISABLED' }, - ); - } else if (this.flowLedgerDisabled.has(flowName)) { - this.logger.info( - `FLOW_DISABLED: packaged flow '${flowName}' refused — it is switched off in the activation ledger ` + - '(sys_metadata_activation, ADR-0126 §7.2).', - { flow: flowName, refusal: 'FLOW_DISABLED' }, - ); - } - // The body lives in ./subflow-guards.ts (#25222). - const host: ThisParameterType = { - flowLedgerDisabled: this.flowLedgerDisabled, - }; - return describeDisabledFlow.call(host, flowName); + return EnablementFacet.describeDisabledFlow.call(enablementHost.of(this), flowName); } /** @@ -4689,14 +3588,7 @@ export class AutomationEngine implements IAutomationService { * papering over a producer that is already correct. */ private subflowTargets(flow: FlowParsed): string[] { - // The body lives in ./subflow-guards.ts (#25222). - const targets = subflowTargets(flow); - // [ADR-0150 D3/D4, #31696] A name two slots hold is the slot the - // calling flow's package resolves it to — what its run dispatches. - if (!targets.some((target) => this.flowSlots.isShared(target) || isSlotKeySpelling(target))) return targets; - const arm = this.flowArms.get(flow); - const caller = arm?.source === 'package' ? (arm.holder ?? arm.packageId ?? null) : null; - return targets.map((target) => (this.flowSlots.isShared(target) || isSlotKeySpelling(target) ? this.resolvedFlowCallKey(target, caller) : target)); + return EnablementFacet.subflowTargets.call(enablementHost.of(this), flow); } /** @@ -4706,9 +3598,7 @@ export class AutomationEngine implements IAutomationService { * run's node reads the refusal. */ private resolvedFlowCallKey(name: string, callerPackageId: string | null): string { - // [#33386] Over every holder: the guards record an arming verdict. - const resolved = this.resolveFlowKey(name, callerPackageId, { durable: true }); - return 'key' in resolved ? resolved.key : unfiledFlowKey(name); + return EnablementFacet.resolvedFlowCallKey.call(enablementHost.of(this), name, callerPackageId); } /** @@ -4981,30 +3871,7 @@ export class AutomationEngine implements IAutomationService { * @returns `true` when the flow is declined and must not be armed. */ private declineOntoDisabledSubflows(flowName: string, triggerType: string): boolean { - const flow = this.flows.get(flowName); - const disabled = flow && this.isPackagedFlow(flowName) - ? this.disabledPackagedSubflows(flowName) - : []; - if (disabled.length === 0) { - this.subflowDeclinedFlows.delete(flowName); - return false; - } - const { reasons, remedy } = this.describeDisabledSubflows(disabled, 'the activation switch'); - const many = disabled.length !== 1; - const reason = - `not armed while the packaged subflow${many ? 's' : ''} it calls ${many ? 'are' : 'is'} disabled — ` + - `${reasons.join(', ')}; ${remedy} and it is armed (ADR-0126 §7.3)`; - const previous = this.subflowDeclinedFlows.get(flowName); - this.subflowDeclinedFlows.set(flowName, reason); - if (previous === reason) return true; - this.logger.warn( - `Flow '${flowName}' is registered but NOT armed on trigger '${triggerType}' — ${disabled.length} packaged ` + - `subflow${many ? 's' : ''} it calls ${many ? 'are' : 'is'} disabled: ${reasons.join(', ')}. Armed, it ` + - `would fail at its subflow node on a disabled child — the late, inexplicable failure ADR-0126 §7.3 ` + - `refuses to cause. It is armed the moment ${many ? 'they are' : 'that subflow is'} enabled: ` + - `${remedy}.`, - ); - return true; + return EnablementFacet.declineOntoDisabledSubflows.call(enablementHost.of(this), flowName, triggerType); } /** @@ -5030,23 +3897,7 @@ export class AutomationEngine implements IAutomationService { * @returns `true` when the flow is declined and must not be armed. */ private declineOntoSuspendingSubflowNotice(flowName: string, triggerType: string): boolean { - const trap = subflowNoticeTrap(this.flows, flowName, this.flowCallKey); - if (!trap) { - this.subflowNoticeDeclinedFlows.delete(flowName); - return false; - } - const why = describeSubflowNoticeTrap(trap); - const reason = - `not armed — ${why}, and it is armed; it is also armed once '${trap.child}' is republished without a ` + - `node that suspends`; - const previous = this.subflowNoticeDeclinedFlows.get(flowName); - this.subflowNoticeDeclinedFlows.set(flowName, reason); - if (previous === reason) return true; - this.logger.warn( - `Flow '${flowName}' is registered but NOT armed on trigger '${triggerType}' — ${why}. It is armed the ` + - `moment the \`save_notice\` moves, or '${trap.child}' is republished without a node that suspends.`, - ); - return true; + return EnablementFacet.declineOntoSuspendingSubflowNotice.call(enablementHost.of(this), flowName, triggerType); } /** @@ -5072,23 +3923,7 @@ export class AutomationEngine implements IAutomationService { * @returns `true` when the flow is declined and must not be armed. */ private declineOntoRegionSuspendingCall(flowName: string, triggerType: string): boolean { - const trap = regionSuspendingCall(this.flows, flowName, this.flowCallKey); - if (!trap) { - this.subflowRegionDeclinedFlows.delete(flowName); - return false; - } - const why = describeRegionSuspendingCall(trap); - const reason = - `not armed — ${why}, and it is armed; it is also armed once '${trap.child}' is republished without a ` + - `node that suspends`; - const previous = this.subflowRegionDeclinedFlows.get(flowName); - this.subflowRegionDeclinedFlows.set(flowName, reason); - if (previous === reason) return true; - this.logger.warn( - `Flow '${flowName}' is registered but NOT armed on trigger '${triggerType}' — ${why}. It is armed the ` + - `moment '${trap.callNode.id}' moves, or '${trap.child}' is republished without a node that suspends.`, - ); - return true; + return EnablementFacet.declineOntoRegionSuspendingCall.call(enablementHost.of(this), flowName, triggerType); } /** @@ -5116,23 +3951,7 @@ export class AutomationEngine implements IAutomationService { * @returns `true` when the flow is declined and must not be armed. */ private declineOntoSubflowRetriedCallout(flowName: string, triggerType: string): boolean { - const trap = subflowRetriedCallout(this.flows, flowName, this.flowCallKey); - if (!trap) { - this.subflowRetryDeclinedFlows.delete(flowName); - return false; - } - const why = describeSubflowRetriedCallout(trap); - const reason = - `not armed — ${why} It is armed once '${trap.callout.flow}' is republished without that retried ` + - `inline call`; - const previous = this.subflowRetryDeclinedFlows.get(flowName); - this.subflowRetryDeclinedFlows.set(flowName, reason); - if (previous === reason) return true; - this.logger.warn( - `Flow '${flowName}' is registered but NOT armed on trigger '${triggerType}' — ${why} It is armed the ` + - `moment '${trap.callout.flow}' is republished without that retried inline call.`, - ); - return true; + return EnablementFacet.declineOntoSubflowRetriedCallout.call(enablementHost.of(this), flowName, triggerType); } /** @@ -5295,18 +4114,7 @@ export class AutomationEngine implements IAutomationService { * exists to remove. */ toggleFlow(name: string, enabled: boolean, caller?: Pick): Promise { - // [#31696] A name two packages hold is refused (409, naming both): - // {@link toggleFlowSlot} switches one package's flow. [#33386] Over - // the served holders: one served holder's flow is switched, none is - // not found ({@link servedBareFlowKey}). - let key: string | undefined; - try { - key = this.servedBareFlowKey(name); - } catch (err) { - return Promise.reject(err); - } - if (key === undefined) return Promise.reject(new Error(`Flow '${name}' not found`)); - return this.toggleFlowKey(key, enabled, caller); + return EnablementFacet.toggleFlow.call(enablementHost.of(this), name, enabled, caller); } /** @@ -5315,9 +4123,7 @@ export class AutomationEngine implements IAutomationService { * ledger row names that package. Engine-local. */ toggleFlowSlot(packageId: string, name: string, enabled: boolean, caller?: Pick): Promise { - const key = this.flowSlots.keyOf(name, packageId); - if (key === undefined) return Promise.reject(new Error(`Flow '${name}' of package '${packageId}' not found`)); - return this.toggleFlowKey(key, enabled, caller); + return EnablementFacet.toggleFlowSlot.call(enablementHost.of(this), packageId, name, enabled, caller); } private toggleFlowKey(name: string, enabled: boolean, caller?: Pick): Promise { @@ -5347,8 +4153,7 @@ export class AutomationEngine implements IAutomationService { /** Get flow version history */ getFlowVersionHistory(name: string): Array<{ version: number; definition: FlowParsed; createdAt: string }> { - const key = this.bareFlowKey(name); - return key === undefined ? [] : this.flowVersionHistory.get(key) ?? []; + return EnablementFacet.getFlowVersionHistory.call(enablementHost.of(this), name); } /** @@ -5379,20 +4184,12 @@ export class AutomationEngine implements IAutomationService { * could not be hashed. */ getFlowBodyChecksum(flow: unknown): string | undefined { - return flow !== null && typeof flow === 'object' ? this.flowChecksumOf(flow as FlowParsed) : undefined; + return RunFacet.getFlowBodyChecksum.call(runHost.of(this), flow); } /** Rollback flow to a specific version */ rollbackFlow(name: string, version: number): void { - // The body lives in ./flow-definitions.ts (#25222). - const host: ThisParameterType = { - flowVersionHistory: this.flowVersionHistory, - flows: this.flows, - logger: this.logger, - }; - const key = this.bareFlowKey(name); - if (key === undefined) throw new Error(`Flow '${name}' has no version history`); - rollbackFlow.call(host, key, version); + return EnablementFacet.rollbackFlow.call(enablementHost.of(this), name, version); } listRuns( @@ -5717,24 +4514,8 @@ export class AutomationEngine implements IAutomationService { return expandDeclaredLookups.call(host, flow, runContext); } - async execute(flowName: string, context?: AutomationContext): Promise { - const startTime = Date.now(); - // [ADR-0150 D3] The bare name resolves for the caller's package first: - // a run of package P's flow reaches P's own flow, else the one holder - // in P's declared dependency closure; anything else is refused with - // every candidate named, and nothing runs. Never dispatched, so no - // `status`, for the reason the disabled exit below states. - // [#31696] A name two packages hold resolves to the slot the caller - // reaches, the same way; a caller that reaches neither is refused. - // [#31696] A slot key is no flow's name: not found, as for any name - // this engine holds no flow of. - if (isSlotKeySpelling(flowName)) return { success: false, error: `Flow '${flowName}' not found` }; - const resolved = this.resolveFlowKey(flowName, this.flowCallerPackage(context)); - if ('refusal' in resolved) return { success: false, error: resolved.refusal.message }; - // [#33386] No served holder reaches the name: as for a flow this engine does not hold. - // [#33905] Nor does a disabled package's flow of a name it holds alone. - if ('absent' in resolved) return { success: false, error: `Flow '${flowName}' not found` }; - return this.executeKey(resolved.key, context, startTime); + execute(flowName: string, context?: AutomationContext): Promise { + return RunFacet.execute.call(runHost.of(this), flowName, context); } /** @@ -5751,719 +4532,15 @@ export class AutomationEngine implements IAutomationService { runId: string; flowName: string; flow: FlowParsed; startedAt: string; startTime: number; context: AutomationContext | undefined; error: string; }): AutomationResult { - const { runId, flowName, flow, startedAt, context, error } = run; - const durationMs = Date.now() - run.startTime; - const steps: StepLogEntry[] = []; - let logged: ExecutionLogEntry | undefined; - try { - logged = this.recordLog({ - id: runId, - flowName, - flowVersion: flow.version, - status: 'failed', - startedAt, - completedAt: new Date().toISOString(), - durationMs, - waitMs: 0, - trigger: buildRunTrigger(context), - steps, - error, - }, context); - } catch (bookkeeping) { - // DURABILITY, so `error`, as at `execute()`'s failure exit: the - // caller is told the run failed, and the history row is lost. - this.logger.error( - `[Automation] run '${runId}' of flow '${flowName}' FAILED before its first node and its run-history ` + - `bookkeeping threw, so its terminal 'failed' row never landed — nothing retries the write, and ` + - `this run is invisible to the Runs surfaces. The caller was answered status 'failed' carrying ` + - `the run's error, so nothing needs re-driving on account of this line. Fix the history failure ` + - `in this record's meta.`, - undefined, - describeThrownForLog(bookkeeping), - ); - } - return { - success: false, - error, - durationMs, - status: 'failed', - flowLabel: flow.label, - summary: logged?.summary ?? summarizeRun(steps), - }; + return RunFacet.failRunBeforeFirstNode.call(runHost.of(this), run); } /** * [#31696] {@link execute} for the flow filed under the slot key * `flowName`, already resolved. Every record of the run is keyed by it. */ - private async executeKey(flowName: string, context: AutomationContext | undefined, startTime: number): Promise { - const flow = this.flows.get(flowName); - // [#31696] Read with the flow, before any await: the slot's key can - // move while the run is in flight, its package cannot. - const runPackage = this.flowSlotPackage(flowName); - - if (!flow) { - return { success: false, error: `Flow '${flowName}' not found` }; - } - - // Check if flow is disabled. - // - // [ADR-0126 §7.2] THE consult point for the activation ledger. This is - // the one seam every entry path crosses (#11665 §2.3) — record-change, - // schedule, time-relative, api and subflow all arrive here — which is - // why the ADR puts the runtime refusal beside this guard instead of - // teaching each trigger its own check. - if (!this.isFlowEnabled(flowName)) { - // [#9415] NEVER DISPATCHED, and the producer says which kind — the - // remaining half of #9378's classification. `status` stays ABSENT - // here on purpose (see the `status: 'failed'` exit below): its - // absence is what proves the transport's 400 arm reads a verdict - // instead of guessing, so a later edit that stamps `'failed'` on - // this exit "for consistency" must fail a test. What the exit - // gained is a `code`, which is the classification's own channel. - // - // [ADR-0126 §7.2] The ledger refusal REUSES `FLOW_DISABLED` — ⛔ no - // new ADR-0112 ledger entry — so the distinction has to ride the - // MESSAGE. It is a real distinction to an operator: a status - // disable is an authoring state fixed in Studio, a ledger disable - // is an installation choice fixed by re-enabling the packaged - // flow, and the two have different remedies. - return { - success: false, - code: 'FLOW_DISABLED', - error: this.describeDisabledFlow(flowName), - }; - } - - // #4792 — a real run is about to start, so if the vocabulary was never - // sealed the ADR-0018 §M1 node-type check never ran on this engine at - // all. Say so once. Placed after the two guards above so the trigger is - // an execution and not a typo'd flow name (which is already loud) or a - // flow that cannot run. See the helper for why here and not earlier. - this.warnIfNodeTypeVocabularyNeverSealed(); - - // Re-entrancy loop guard KEY (see `activeRecordFlows`). Only the key is - // computed here; the CHECK itself lives downstream of the start-condition - // gate inside the `try` below, and that placement is load-bearing — see - // the guard block there (#8689). - const guardRecordId = (context?.record as { id?: unknown } | undefined)?.id; - const reentryKey = guardRecordId != null ? `${flowName}::${String(guardRecordId)}` : undefined; - // Set ONLY by the run that actually added `reentryKey` to the active set. - // The `finally` releases the key on this flag, never on `reentryKey` - // alone: a re-entrant dispatch now returns from INSIDE the try (the guard - // block below), and an unconditional delete there would release the key - // belonging to the OUTER run still on the stack — disarming the breaker - // for every later re-entry in that same cascade, which is precisely the - // runaway it exists to stop. - let reentryHeld = false; - - // Initialize the run's variable environment. Every binding a run is - // entitled to — the flow's declared variables, the trigger record and - // its flattened fields, `previous`, and the engine-owned `$runId` / - // `$flowName` / `$flowLabel` — is seeded by `seedRunVariables`, the one - // chokepoint `executeWithoutRetry` shares (#9704). See that helper for - // why the seeding is not written out here any more. - // - // The run id is minted BEFORE the seeding because `$runId` is part of - // that environment. Order-safe: `nextRunId()` is a stateless random id - // (no counter to advance), and nothing between the old call site and - // this one reads or mints one. - const runId = this.nextRunId(); - const startedAt = new Date().toISOString(); - const steps: StepLogEntry[] = []; - - // ADR-0049 / #1888 — establish the run's effective execution identity - // from flow.runAs (a COPY, never mutating the caller's context, so the - // elevation is scoped to this run and the caller's identity is restored - // when execute() returns). Surfaces the user-less fail-open (see helper) - // and resolves the triggering user's real grants for `runAs:'user'` (#3356). - // Also stamps `flowRunId` so this run's data writes are attributable to it - // (#3456). - let runContext: AutomationContext; - let variables: Map; - try { - runContext = await this.resolveRunContext(flow, context, runId); - // Seeded AFTER the context resolves, from the resolved context: its - // record is the run's own copy, carrying the lookups the start node - // declares (`expand`, grafted while the context resolves). - variables = this.seedRunVariables(flow, flowName, runContext, runId); - } catch (err) { - // A value the run is handed that contains itself (the record, - // `previous`) has no copy for the run to take: the run fails - // before its first node, answered in the failed-run shape below - // and recorded as such, never a throw out of `execute()`. Any - // other throw is unchanged. - if (!(err instanceof HeldValueCycleError)) throw err; - // [ADR-0162 Execution item 8] A run that fails before its first - // node is recorded as a failed run: it started. - this.noteRunStarted(context, runId); - return this.failRunBeforeFirstNode({ runId, flowName, flow, startedAt, startTime, context, error: err.message }); - } - stampFlowRunSlot(runContext, flowName, runPackage); - // [ADR-0162 item 7] The run's root run: itself, or its parent's. - stampRootRun(runContext, { runId, flowName, startedAt }); - // The body this run runs, by content: its own, never its parent's. - stampRunFlowChecksum(runContext, runId, this.flowChecksumOf(flow)); - - try { - // Find the start node - const startNode = flow.nodes.find(n => n.type === 'start'); - if (!startNode) { - // [#9415] Inside the `try`, but still a NEVER-DISPATCHED exit: - // nothing has executed at this point — the run id and the run - // context exist, no node does. Since #32273 registration - // refuses a flow with no `start` node, so no door can arm one - // and this is a defensive exit that none reaches: a trigger of - // such a stored flow finds no flow and answers `404`. The exit - // and its `422` mapping stay as a declared defensive path. No - // `status`, for the reason the disabled exit above states. - return { success: false, code: 'FLOW_NO_START_NODE', error: 'Flow has no start node' }; - } - - // Trigger-condition gate. The start node's `condition` is the predicate - // that decides whether the trigger event should launch this flow (e.g. - // `status == "done" && previous.status != "done"`). The engine — not the - // trigger — owns evaluating it, so every trigger type (record-change, - // schedule, …) and a manual `execute()` share one gate. Plain-string - // conditions are routed through CEL so bare field references resolve. - // - // The evaluator is shared with `executeWithoutRetry`, which re-runs - // this gate on every retry attempt: a condition that throws here - // is a fault the catch below hands to the error strategy, and - // under `strategy: 'retry'` each later attempt evaluates it again - // rather than running the nodes ungated (see `startConditionHolds`). - if (!startConditionHolds.call(this, startNode, variables, runContext)) { - this.logger.debug(`Flow '${flowName}' skipped: start condition not met`); - // `flowLabel` rides even here, unlike `successMessage` / - // `summary`: it names the flow, it claims no work done, and - // this answer reaches a runner as a 200 like any other. - return { success: true, output: { skipped: true, reason: 'condition_not_met' }, flowLabel: flow.label }; - } - - // Re-entrancy loop guard (see `activeRecordFlows`). Breaks the SAME - // flow re-firing for the SAME record while a prior execution is still - // active — a self-trigger cascade whose start condition is genuinely - // true on every pass (the 2026-07-06 incident: a `boolean` persists as - // integer 1 on SQLite/libsql and CEL `1 != true` is true, so - // `is_escalated != true` never tripped) would otherwise loop forever - // and wedge the caller, fatally mid seed. - // - // #8689 — this check sits AFTER the start-condition gate above, and - // the order is the contract, not a detail. The declared behaviour is - // "a record-change flow fires only when its start condition is true", - // and that has to hold on the re-entrant dispatch a flow's OWN write - // causes — it cannot if the breaker returns first, because then the - // gate is never reached on that dispatch at all. Measured before the - // reorder, on the real kernel (a `record-after-update` flow guarded on - // `record.status != "escalated"` whose data node writes - // `status = "escalated"`): TWO dispatches for the record, exactly ONE - // start-condition evaluation, and one breaker WARN. So the author's - // guard was never what stopped the loop — the breaker was, and its own - // message said so. The re-entrant dispatch already carries the - // POST-write row, so evaluating first suppresses it with - // `condition_not_met` and the breaker returns to being a backstop. - // - // The breaker is UNCHANGED in strength (deliberately — a stronger - // breaker is not the repair): a condition that really is true on - // re-entry still lands here, at the same depth, with the same WARN and - // the same skip envelope. What changed is that reaching it now MEANS - // something — the condition was evaluated and returned true — which is - // why the message can state that as fact. - if (reentryKey && this.activeRecordFlows.has(reentryKey)) { - // #6654 — the record id is CALLER data (nothing schema-constrains - // it against newlines), so it rides the logger's structured slot, - // never the message; see `forgetSuspendedRun`'s catch for the full - // mechanism (#6299). #4632: FUNCTIONAL — stays `warn` (the run is - // deliberately skipped and the caller reads the skip envelope). - this.logger.warn( - `[automation] flow '${flowName}' re-entered for the same record while still running — breaking ` + - `self-trigger loop; the triggering record's id is in this record's meta. Its start condition ` + - `WAS evaluated on this re-fire and returned true, so the guard as authored does not exclude ` + - `the flow's own write-back; if it guards on a boolean field (e.g. \`is_escalated != true\`), ` + - `note booleans persist as 0/1 on SQLite/libsql and CEL \`1 != true\` is true.`, - { recordId: String(guardRecordId) }, - ); - return { success: true, output: { skipped: true, reason: 'reentrancy_loop_guard' }, flowLabel: flow.label }; - } - if (reentryKey) { - this.activeRecordFlows.add(reentryKey); - reentryHeld = true; - } - // [ADR-0162 Execution item 8] Past both gates the run is dispatched - // and leaves a history row whatever it ends in. Neither skip above - // records one, so neither names a run here ({@link runStartedFor}). - this.noteRunStarted(context, runId); - - // Validate node input schemas before execution. [#9889] The same - // call sits in `executeWithoutRetry` — every retry attempt must be - // refused by the same guard that refused attempt 1; see the guard's - // own doc for the chokepoint contract. - this.validateNodeInputSchemas(flow, variables); - - // DAG traversal execution - await this.executeNode(startNode, flow, variables, runContext, steps); - - // Collect output variables - const output: Record = {}; - if (flow.variables) { - for (const v of flow.variables) { - if (v.isOutput) { - output[v.name] = variables.get(v.name); - } - } - } - - const durationMs = Date.now() - startTime; - - // [#16274] THE RUN IS OVER AND IT SUCCEEDED. Everything from here - // to the return is BOOKKEEPING ABOUT that fact, and the `catch` - // below this `try` exists for NODE failures — so a throw out of the - // history write was handled as though a node had thrown: the arm - // recorded a `failed` row carrying the history driver's own text as - // the run's error and answered `status: 'failed'` for a run whose - // every node succeeded. This is the guard PR #16273 landed on - // {@link resumeInternal}'s completion path, now on the two - // INITIAL-execution paths that card deliberately scoped out — this - // one and {@link executeWithoutRetry}'s. - // - // ⚠️ MEASURED, and sharper than the report assumed: under - // `errorHandling.strategy: 'retry'` that false `failed` is handed - // to {@link retryExecution} by the strategy branch in the catch - // below, whose loop reads `result.success` — so it RE-EXECUTES a - // flow that already finished. `1 + maxRetries` runs of every node, - // unattended, inside this one call, with the side effects repeated - // each time and one `failed` history row per attempt. That is the - // DOUBLE RUN #15944 was graded sharp for, reached here with no - // operator action at all, where #15944's needed an operator to - // restore and resume. - // - // Two statements inside `recordLog` reach that catch on the - // terminal path, and neither is hypothetical: - // - // 1. the run-summary line `this.logger.info(line, meta)` — on by - // default (`runSummaryLog: 'info'`) and calling a - // HOST-INJECTED `Logger`, so it needs no store at all; - // 2. `store.recordTerminal(record)` throwing SYNCHRONOUSLY — the - // `void write.catch(...)` beneath that call only ever sees a - // returned promise's rejection (both shipped stores are - // `async` and cannot; `SuspendedRunStore` is an exported - // interface with an optional `recordTerminal`, so a host store - // is unconstrained, and one returning a non-thenable makes - // `write.catch` itself a synchronous `TypeError`). On THAT - // variant the unguarded code did not even answer `failed`: the - // catch arm's own `recordLog({ status: 'failed' })` threw again - // out of the same store and escaped `execute()` entirely, - // rejecting a promise `AutomationResult` is declared for. - // - // The guard restores the invariant `recordLog`'s own doc states — - // "a history write must NEVER block or break the run that produced - // it" — which that call was relied upon to keep and did not. - // - // ⛔ NOT a widening of anything: no exit gains a status it did not - // have, the node-failure arm below is untouched (a genuine node - // throw still lands there, still records `failed`, still retries), - // and the failure is REPORTED rather than swallowed — see the - // catch. - let logged: ExecutionLogEntry | undefined; - try { - logged = this.recordLog({ - id: runId, - flowName, - flowVersion: flow.version, - status: 'completed', - startedAt, - completedAt: new Date().toISOString(), - durationMs, - // [#32284] The initial execution never paused: a measured 0. - waitMs: 0, - trigger: buildRunTrigger(context), - steps, - output, - }, context); - } catch (bookkeeping) { - // #4632 verdict: DURABILITY, so `error` — the caller is told - // the truthful thing (the run completed), which is exactly - // what makes the rest invisible from the outside: the terminal - // history row never landed, nothing retries it, and no - // envelope carries a word about it. Consequence and fix in the - // first line, per AGENTS.md. Said ONCE per run, not once per - // failed write. - // - // ⚠️ The level is the precedent's (#16273, #15555) and is NOT - // a raise under the published-sink ruling (commit e238c79f0): that ruling forbids raising a site to - // `error` where doing so means GROWING `error?` onto a - // published sink that lacks it, and this sink — `Logger` from - // `@objectstack/spec/contracts` — declares `error(message, - // error?, meta?)` as a REQUIRED member (only `fatal?`, - // `child?` and `withTrace?` are optional). Nothing is widened, - // which is also why the two precedents on this same sink could - // land `error`. - // - // THIRD argument per `error(message, error?, meta?)`; the - // `Error` slot stays empty on purpose (#5575), and the thrown - // text goes to the structured slot rather than into the - // message (#6499). - this.logger.error( - `[Automation] run '${runId}' of flow '${flowName}' COMPLETED successfully but its ` + - `run-history bookkeeping threw, so its terminal history row never landed — nothing ` + - `retries it, the caller is told the run succeeded, and after the next restart this ` + - `run is invisible to the Runs surfaces while the approvals sweeps read it as ` + - `never-finished. The run itself is COMPLETE and must NOT be re-run or retried. Fix ` + - `the history failure in this record's meta.`, - undefined, - describeThrownForLog(bookkeeping), - ); - } - // [#16274] Recomputed when the guard above had to abandon - // `recordLog`: the same pure function of the same steps that - // `recordLog`'s own first statement runs, so the two spellings - // cannot disagree. Same shape as `resumeInternal`'s (#15944). - const summary = logged?.summary ?? summarizeRun(steps); - - return { - success: true, - output, - durationMs, - // [#9414] The flow author's own completion text, on the exit - // every TRIGGERED run leaves through. `AutomationResult` - // declares this pair as a general terminal-result feature — - // "`successMessage` is set on terminal success, `errorMessage` - // on failure" — but `resumeInternal` was the only producer, so - // the author's words reached a caller only when the run - // happened to pause and be resumed. A flow dispatched straight - // through `POST /api/v1/automation/:name/trigger` (or the - // legacy `trigger/:name` the SDK calls) carried nothing. Same - // declaration, two behaviours decided by ROUTE rather than by - // authoring — the shape ADR-0049's enforce-or-remove exists to - // stop, and this is the restoration half of it, not a new key. - // - // ⚠️ TERMINAL exits only, which is the whole boundary. The - // paused return below carries neither (the run has not - // finished; `resumeInternal` stamps the message when it later - // ends). Neither do the SKIP exits above — `condition_not_met` - // and `reentrancy_loop_guard` return `success: true` for a run - // that executed no node, so stamping "Opportunity created!" on - // one would be a toast about work nobody did. They carry no - // `summary` for exactly the same reason. - // - // [#28054] Rendered, not copied: a `{{ }}` template over the - // variables the run finished with, in the run's locale. - successMessage: this.renderFlowTerminalMessage( - flowName, 'successMessage', flow.successMessage, variables, runContext, - ), - // The authored flow name for the runner header and the - // completion toast — on EVERY evaluation's result, paused and - // terminal alike (see `AutomationResult.flowLabel`). - flowLabel: flow.label, - // #4354 — hand the counts back synchronously so a caller - // (a `subflow` roll-up, a runtime test asserting the sweep wrote - // something) never has to re-read the run to learn what it did. - summary, - // #32861 — the values a write step did not store, so the door - // that started the run can tell its caller. Omitted when none. - ...withDroppedFields(steps), - }; - } catch (err: unknown) { - // [#15788] The run REFUSED — an `end` node declaring - // `outcome: 'refused'`, or (#18110 / #18555) a node whose own child - // run refused. Tested FIRST, beside the - // pause and for the same reason: this is NOT a failure either, and - // a signal recognised only by the arm below would be recorded as - // one. The shape is `finishRefusedRun`'s — one method, all three - // producers. - if (isRefusalSignal(err)) { - return this.finishRefusedRun({ - runId, flowName, flowVersion: flow.version, - startedAt, durationMs: Date.now() - startTime, waitMs: 0, - steps, flow, variables, - refusalMessage: err.message, context, - }); - } - // A node asked to suspend the run (ADR-0019 durable pause). Snapshot - // the live state, record a `paused` log, and return the run id so the - // caller can later `resume()` it. This is NOT a failure. - if (isSuspendSignal(err)) { - const durationMs = Date.now() - startTime; - // [#32284] The run's first pause: nothing waited yet, so all - // of `durationMs` was execution — the clock the resume reads. - const waitMs = 0; - // #7639 — ONE snapshot expression feeding BOTH consumers: the - // continuation the run will resume from, and the `paused` log - // entry run-detail serves. Same object, so what an operator - // reads can never disagree with what the run holds. See - // {@link ExecutionLogEntry.variables} for why the log carries it. - const variablesSnapshot = Object.fromEntries(variables); - await this.persistSuspendedRun({ - runId, - flowName, - flowVersion: flow.version, - flowChecksum: this.flowChecksumOf(flow), - nodeId: err.nodeId, - nodeType: err.nodeType, - variables: variablesSnapshot, - steps, - context: runContext, - startedAt, - startTime, - activeMs: activeMsAtPause(durationMs, waitMs), - correlation: err.correlation, - screen: err.screen, - }); - this.recordLog({ - id: runId, - flowName, - flowVersion: flow.version, - status: 'paused', - startedAt, - durationMs, - waitMs, - trigger: buildRunTrigger(context), - steps, - variables: variablesSnapshot, - }, context); - return { - success: true, - status: 'paused', - runId, - durationMs, - screen: err.screen, - flowLabel: flow.label, - }; - } - - const errorMessage = err instanceof Error ? err.message : String(err); - - // Record failed execution log - const durationMs = Date.now() - startTime; - // [#17562] THE RUN IS OVER AND IT FAILED, and this `catch` IS the - // handler for that failure — there is no outer one. So a throw out - // of THIS history write escaped `execute()` entirely and left it a - // REJECTED PROMISE, where its declared return type is an - // `AutomationResult`. The FAILURE-arm half of the guard #16274 - // landed on the completion arm of this same method, and the same - // shape #15555 landed on {@link resumeInternal}'s failure arm. - // - // ⚠️ What is lost is the SHAPE, not the verdict — which is why this - // is a narrower defect than #16274's and still a contract - // violation. The run genuinely failed, so nothing misleads an - // operator: no false `failed`, no double run. But the caller that - // branches on `{ success: false, status: 'failed' }` gets an - // exception instead, so the transport's `status` arm (#9378) is - // bypassed and `errorMessage` (#9414) and `summary` (#4354) never - // arrive — a REST route or SDK caller sees a 500-class throw for a - // run that had a perfectly good failure envelope waiting, and the - // NODE's own error text is replaced by the history driver's. - // - // The two statements inside `recordLog` that reach here are the - // ones stated at the completion site above: the default-on - // run-summary line `this.logger.info(line, meta)` calling a - // HOST-INJECTED `Logger`, and `store.recordTerminal(record)` - // throwing SYNCHRONOUSLY — which the `void write.catch(...)` - // beneath that call cannot see, because it only ever observes a - // RETURNED promise's rejection. - // - // The guard restores the invariant `recordLog`'s own doc states — - // "a history write must NEVER block or break the run that produced - // it" — which this call was relied upon to keep and did not. - // - // ⛔ NOT a widening of this arm's meaning: the suspend arm above, - // the `InputSchemaViolationError` refusal below and the - // `strategy: 'retry'` branch are all untouched, a genuine node - // failure still records `failed` with the node's own text, and the - // retry budget is unchanged — pinned by two controls. - let logged: ExecutionLogEntry | undefined; - try { - logged = this.recordLog({ - id: runId, - flowName, - flowVersion: flow.version, - status: 'failed', - startedAt, - completedAt: new Date().toISOString(), - durationMs, - waitMs: 0, - trigger: buildRunTrigger(context), - steps, - error: errorMessage, - }, context); - } catch (bookkeeping) { - // #4632 verdict: DURABILITY, so `error` — the caller is told a - // truthful thing (the run failed, with the node's own text), - // which is exactly what makes the rest invisible from the - // outside: the terminal history row never landed, nothing - // retries it, and no envelope carries a word about it. - // Consequence and fix in the first line, per AGENTS.md. Said - // ONCE per abandoned write. - // - // ⚠️ NOT the rule's third answer ("a failure handed to the - // CALLER is not a degradation at all"): what is handed to the - // caller is the NODE's failure. The bookkeeping failure is - // handed to nobody, and it is a durability loss — which is why - // `recordLog` is in `DURABILITY_CRITICAL_CALLEES`. - // - // ⚠️ The level is the precedent's (#15555, #16273, #16274) and - // is NOT a raise under the published-sink ruling (commit e238c79f0): that ruling forbids raising a - // site to `error` where doing so means GROWING `error?` onto a - // published sink that lacks it, and this sink — `Logger` from - // `@objectstack/spec/contracts` — declares `error(message, - // error?, meta?)` as a REQUIRED member. Nothing is widened and - // no sink type changes in this diff. - // - // THIRD argument per `error(message, error?, meta?)`; the - // `Error` slot stays empty on purpose (#5575), and the thrown - // text goes to the structured slot rather than into the message - // (#6499). - this.logger.error( - `[Automation] run '${runId}' of flow '${flowName}' FAILED and its run-history ` + - `bookkeeping threw, so its terminal 'failed' row never landed — nothing retries the ` + - `write, and after the next restart this run is invisible to the Runs surfaces while ` + - `the approvals sweeps read it as never-finished. The run's OWN failure IS reported: ` + - `the caller was answered status 'failed' carrying the node's error, so nothing ` + - `needs re-driving on account of this line. Fix the history failure in this record's ` + - `meta.`, - undefined, - describeThrownForLog(bookkeeping), - ); - } - - // [#10025] NEVER DISPATCHED, ruled NON-RETRYABLE (maintainer, - // 2026-08-20, Option B taken whole). The guard's verdict is a pure - // function of the flow definition — `validateNodeInputSchemas` - // deliberately ignores its variables parameter — so attempt 2 - // cannot answer differently than attempt 1, and handing this throw - // to `retryExecution` below would burn the whole retry budget - // (backoff delays included) re-deriving a certainty into - // 1 + maxRetries identical failed rows. Short-circuiting HERE, - // before the strategy branch, is the ruling's whole content: - // `strategy: 'retry'` changes nothing about this exit, and the ONE - // failed row recorded above is the run history's entire account of - // the refusal. - // - // The envelope matches its never-dispatched siblings - // (`FLOW_DISABLED`, `FLOW_NO_START_NODE` — #9378/#9415): a `code` - // and NO `status`, whose absence is the discriminator the - // transport's 422 arm reads (see the `status: 'failed'` exit - // below). No `errorMessage` / `summary` either — those are a RUN's - // artefacts, and no node executed. - // - // The #9889 parity floor underneath is UNTOUCHED: the guard is - // still called identically by both attempt paths, so if any route - // ever reaches `executeWithoutRetry` without crossing this catch, - // the refusal still fires — just without this classification. - // This arm decides what `execute()` does with the verdict; it - // never weakens who renders it. - if (err instanceof InputSchemaViolationError) { - return { - success: false, - code: 'FLOW_INPUT_SCHEMA_INVALID', - error: errorMessage, - }; - } - - // Error handling strategy. - // - // [#9510] ⚠️ This handoff can now return a NON-TERMINAL result: a - // retry attempt that reaches a pausing node comes back as - // `{ success: true, status: 'paused', runId }` — the same shape the - // suspend arm above returns — and `execute()` forwards it - // unchanged, so its contract is ONE answer per situation rather - // than one per attempt number. Deliberate, not incidental: a caller - // branching on `status` sees no difference between a pause on - // attempt 1 and a pause on attempt 3, which is what - // `AutomationResult` already promises. - // - // ⚠️ The `runId` that comes back is then the PAUSED ATTEMPT's, not - // this failed first attempt's. They are different runs with - // different log rows, and the paused one is the key - // `persistSuspendedRun` stored the continuation under — so it is - // the only id `resume()` can be called with. - if (flow.errorHandling?.strategy === 'retry') { - return this.retryExecution( - flowName, context, startTime, flow.errorHandling, flow.errorMessage, flow.label, - ); - } - return { - success: false, - error: errorMessage, - durationMs, - // [#9378] RAN AND FAILED, said by the producer that knows — - // the same lifecycle verdict this exit just wrote to the run - // log two statements up, now also on the result. - // - // Load-bearing, not decoration: `execute()` has four OTHER - // `success: false` exits that never dispatched anything (flow - // not found, flow disabled, no start node, and the - // input-schema refusal in the arm above), and a transport - // cannot tell them from this one without either a message - // regex or sniffing `summary` / `durationMs` — the - // tolerant-consumer shape PD #12 forbids, and the one #8684 - // deliberately did not reproduce on the resume route. Those - // four exits carry NO `status`, this one carries `'failed'`, - // so "the run dispatched and was rejected" is a fact the route - // reads rather than infers. - // - // [#9415] Three of those four now also carry a `code` - // (`FLOW_DISABLED`, `FLOW_NO_START_NODE`, and #10025's - // `FLOW_INPUT_SCHEMA_INVALID`) so the transport can - // answer them 409/422 instead of 200. That did NOT retire the - // rule above — it sharpened it. The `status` absence is still - // the discriminator this arm is read by, and it is the reason - // the never-dispatched exits must never acquire `status`: a - // tidy-up that stamped `'failed'` on all of them would put - // every refusal back on this 400 arm, silently. - // - // `status` and not a `code`, and that division SURVIVED the - // union widening: #9415 added `'FLOW_DISABLED'` / - // `'FLOW_NO_START_NODE'` for the two never-dispatched exits, - // and this exit still classifies with `status` alone. The two - // fields answer different questions — `code` says WHY a - // dispatch was refused, `status` says how a run that started - // ended — and a run that reached here has no refusal to name. - // `status?: 'completed' | 'paused' | 'failed'` is declared, - // documented as the run's lifecycle verdict, and already the - // value recorded in the log. - status: 'failed', - // [#9414] The author's failure text, BESIDE the raw `error` - // rather than instead of it. The transport folds `error` into - // the ADR-0112 message and carries this one in - // `error.details.errorMessage` — the single place the console - // reads it from (objectui `flowResponse.ts`, PR #4899). The - // envelope has no `data`, so a producer that leaves this absent - // does not degrade to a plainer toast: the consumer falls back - // to the raw node error text, which is what every non-screen - // flow showed until now. - // - // [#28054] Rendered over the variables at the failure point - // (`$error` included), in the run's locale. - errorMessage: this.renderFlowTerminalMessage( - flowName, 'errorMessage', flow.errorMessage, variables, runContext, - ), - flowLabel: flow.label, - // A failed run's counts matter MORE, not less: they say how far - // it got before dying — how many rows it had already written. - // [#17562] Recomputed when the guard above had to abandon - // `recordLog`: the same pure function of the same steps that - // `recordLog`'s own first statement runs, so the two spellings - // cannot disagree. Same shape as #15555's. - summary: logged?.summary ?? summarizeRun(steps), - // [#24914, ruling B′] The refusal the failing node's data call met, - // beside the unchanged `error`: `userMessage` / `innerRefusal`, read - // off the brand the node's throw carries (`inner-refusal.ts`) — `{}` - // for a throw that met none, so nothing is invented. - ...readCarriedRefusal(err), - }; - } finally { - // Release the re-entrancy guard for this (flow, record). Runs before - // the returned promise settles, so an error-retry re-run (whose inner - // execute happens after its own await) is not falsely blocked. - // - // Gated on `reentryHeld`, NOT on `reentryKey` (#8689): since the guard - // check moved below the start-condition gate, a run can now leave this - // try WITHOUT owning the key — the re-entrant dispatch that tripped the - // breaker, and a condition-not-met skip. Deleting then would release - // the OUTER run's key and disarm the breaker mid-cascade. - if (reentryHeld && reentryKey) this.activeRecordFlows.delete(reentryKey); - } + private executeKey(flowName: string, context: AutomationContext | undefined, startTime: number): Promise { + return RunFacet.executeKey.call(runHost.of(this), flowName, context, startTime); } /** @@ -6591,7 +4668,7 @@ export class AutomationEngine implements IAutomationService { * implemented twice and drift. */ private resolveDeclaredResumeAuthority(nodeType: string): ActionDescriptor['resumeAuthority'] { - return this.resolveCanonicalDescriptor(nodeType)?.resumeAuthority; + return ResumeFacet.resolveDeclaredResumeAuthority.call(resumeHost.of(this), nodeType); } /** @@ -6784,19 +4861,10 @@ export class AutomationEngine implements IAutomationService { * * Same walk, same bounds: only the loader differs. */ - private async resolveSuspensionChainForCancel( + private resolveSuspensionChainForCancel( runId: string, ): Promise<{ chain: SuspendedRun[]; unreadable?: { runId: string; cause: unknown } }> { - let unreadable: { runId: string; cause: unknown } | undefined; - const chain = await this.walkSuspensionChain(runId, async (id) => { - try { - return await this.loadSuspendedRunStrict(id); - } catch (cause) { - unreadable = { runId: id, cause }; - return null; - } - }); - return unreadable ? { chain, unreadable } : { chain }; + return ResumeFacet.resolveSuspensionChainForCancel.call(resumeHost.of(this), runId); } /** The one chain walk behind {@link resolveSuspensionChain} and @@ -6911,8 +4979,8 @@ export class AutomationEngine implements IAutomationService { * a store failure to `null` with a warning rather than throwing. Use this * one before writing anything of your own; use `getRun` to display. */ - async hasSuspendedRun(runId: string): Promise { - return (await this.loadSuspendedRunStrict(runId)) !== null; + hasSuspendedRun(runId: string): Promise { + return ResumeFacet.hasSuspendedRun.call(resumeHost.of(this), runId); } /** @@ -6943,11 +5011,8 @@ export class AutomationEngine implements IAutomationService { * THROWS when the durable store cannot be read, as {@link hasSuspendedRun} * does: an outage means "unknown", never "can continue". */ - async unresumableSuspensionCause(runId: string): Promise { - const run = await this.loadSuspendedRunStrict(runId); - if (!run) return undefined; - const target = await this.resolveResumeTarget(runId, run); - return 'cause' in target ? target.cause : undefined; + unresumableSuspensionCause(runId: string): Promise { + return ResumeFacet.unresumableSuspensionCause.call(resumeHost.of(this), runId); } /** @@ -6978,26 +5043,8 @@ export class AutomationEngine implements IAutomationService { * identity, or the stored body no longer parses. REJECTS when the source * does — see {@link FlowHistorySource}. */ - private async recoverStoredFlow(name: string, checksum: string): Promise { - const source = this.flowHistorySource; - if (!source) return undefined; - const body = await source(name, checksum); - if (body === null || body === undefined) return undefined; - let parsed: FlowParsed; - try { - parsed = this.canonicalizeFlow(name, body).parsed; - } catch (err) { - this.logger.warn( - `[automation] the stored version of flow '${name}' with checksum ${checksum} no longer parses, so a ` + - `run that started on it cannot resume on it.`, - describeThrownForLog(err), - ); - return undefined; - } - // The identity it was found by, so a run resumed on it and paused - // again stays pinned to it. - this.flowChecksums.set(parsed, checksum); - return parsed; + private recoverStoredFlow(name: string, checksum: string): Promise { + return ResumeFacet.recoverStoredFlow.call(resumeHost.of(this), name, checksum); } /** @@ -7007,12 +5054,7 @@ export class AutomationEngine implements IAutomationService { * lost on restart and on {@link withdrawFlow}. */ private heldFlowVersion(name: string, checksum: string): FlowParsed | undefined { - const versions = this.flowVersionHistory.get(name) ?? []; - for (let i = versions.length - 1; i >= 0; i--) { - const definition = versions[i].definition; - if (this.flowChecksums.get(definition) === checksum) return definition; - } - return undefined; + return ResumeFacet.heldFlowVersion.call(resumeHost.of(this), name, checksum); } /** @@ -7033,17 +5075,10 @@ export class AutomationEngine implements IAutomationService { * {@link hasSuspendedRun} does: an outage means "unknown", never "no * parent". */ - async suspendedMapParentOf( + suspendedMapParentOf( itemRunId: string, ): Promise<{ runId: string; flowName: string; nodeId: string; correlation?: string } | undefined> { - const item = await this.loadSuspendedRunStrict(itemRunId); - const ctx = item?.context as Record | undefined; - const parentRunId = ctx?.$parentRunId; - const mapNode = ctx?.$parentMapNode; - if (typeof parentRunId !== 'string' || !parentRunId) return undefined; - const parent = await this.loadSuspendedRunStrict(parentRunId); - if (!parent || parent.nodeId !== mapNode || parent.correlation !== `map:${itemRunId}`) return undefined; - return { runId: parent.runId, flowName: parent.flowName, nodeId: parent.nodeId, correlation: parent.correlation }; + return ResumeFacet.suspendedMapParentOf.call(resumeHost.of(this), itemRunId); } /** @@ -7058,12 +5093,10 @@ export class AutomationEngine implements IAutomationService { * {@link hasSuspendedRun} does: an outage means "unknown", never "not * parked". */ - async suspensionOf( + suspensionOf( runId: string, ): Promise<{ runId: string; flowName: string; nodeId: string; correlation?: string } | undefined> { - const run = await this.loadSuspendedRunStrict(runId); - if (!run) return undefined; - return { runId: run.runId, flowName: run.flowName, nodeId: run.nodeId, correlation: run.correlation }; + return ResumeFacet.suspensionOf.call(resumeHost.of(this), runId); } /** @@ -7213,72 +5246,7 @@ export class AutomationEngine implements IAutomationService { runId: string, signal: ResumeSignal, ): AutomationResult | null { - if ((signal as Record)[ENGINE_BUILT_SIGNAL] === true) return null; - if (!screenDeclaresInputContract(run.screen)) return null; - const fields = run.screen!.fields; - - const bag = (signal.variables ?? {}) as Record; - // Submitted values win over the snapshot: the predicate is about what - // the user is filling in NOW, and the run's variables only supply the - // wider context a `visibleWhen` may legitimately reference. - const scope = new Map(Object.entries(run.variables)); - for (const [k, v] of Object.entries(bag)) scope.set(k, v); - - const visibility = (field: ScreenFieldSpec): ScreenFieldVisibility => { - try { - return this.evaluateCondition(String(field.visibleWhen), scope, run.context); - } catch (err) { - // #6499 — BOTH spliced pieces were uncontrolled: the author's - // own `visibleWhen` source (metadata text of any shape) and - // the evaluator's thrown message (`evaluateCondition` composes - // a deliberately multi-line one). Both go to the structured - // slot; see `forgetSuspendedRun`'s catch above for the full - // mechanism (#6299). - // - // #4632 verdict: FUNCTIONAL — stays `warn`: one field's - // `required` is not enforced for one submission, the resume - // caller reads the outcome directly, and nothing - // claimed-persisted is involved. - this.logger.warn( - `[automation] run '${runId}': screen field '${field.name}' has a visibleWhen that could not be ` + - `evaluated — its \`required\` is not enforced for this submission. The predicate and the ` + - `evaluator's failure are in this record's meta.`, - { visibleWhen: String(field.visibleWhen), ...describeThrownForLog(err) }, - ); - return undefined; - } - }; - - const issues = validateScreenInputs(fields, bag, visibility); - if (!issues.length) return null; - - const declared = declaredScreenFieldNames(fields); - const summary = issues.map((i) => i.message).join('; '); - // #6654 — the issue messages embed USER-SUBMITTED keys - // (`validateScreenInputs`' `Unknown screen field "…"`, - // screen-input-contract.ts), which nothing constrains against - // newlines, so the findings ride the structured slot, never the - // message; see `forgetSuspendedRun`'s catch for the full mechanism - // (#6299). The returned INVALID_SCREEN_INPUT envelope below is - // caller-facing refusal text, not a log record — it keeps the summary - // (the envelope class is ruled elsewhere). #4632: FUNCTIONAL — stays - // `warn`. - this.logger.warn( - `[automation] refused resume of run '${runId}': screen '${run.nodeId}' input violates its declared ` + - `field contract — ${issues.length} issue(s); the field-level findings are in this record's meta.`, - { issues }, - ); - return { - success: false, - code: 'INVALID_SCREEN_INPUT', - error: - `Invalid screen input: ${summary} — declared fields: ` + - `${declared.map((n) => `'${n}'`).join(', ') || '(none)'}`, - // [#37526] The same findings, one entry per finding, so a runner can place - // each at its field in its own language rather than show `error`, - // which names the screen's declared fields for logs and API callers. - fields: issues.map(({ field, code, message }) => ({ field, code, message })), - }; + return ResumeFacet.refuseInvalidScreenInput.call(resumeHost.of(this), run, runId, signal); } /** @@ -7289,15 +5257,7 @@ export class AutomationEngine implements IAutomationService { * child's context carries one (`$parentOutputVariable`). */ private buildSubflowResumeSignal(childContext: AutomationContext | undefined, childOutput: unknown): ResumeSignal { - const outVar = (childContext as Record | undefined)?.$parentOutputVariable; - // Engine-built: `outVar` is the author's `config.outputVariable`, so the - // reserved-name check would be a false positive on an oddly-named one. - return engineBuilt({ - output: { output: childOutput ?? null }, - ...(typeof outVar === 'string' && outVar - ? { variables: { [outVar]: childOutput ?? null } } - : {}), - }); + return ResumeFacet.buildSubflowResumeSignal(childContext, childOutput); } /** @@ -7325,7 +5285,7 @@ export class AutomationEngine implements IAutomationService { * record nothing — #15556's ruling is scoped to the strand, and those two * stay the functional degradation the old verdict already had right. */ - private async bubbleToParent( + private bubbleToParent( run: SuspendedRun, output: Record, /** #4354 — this child's totals, credited to the parent's awaiting step. */ @@ -7347,132 +5307,7 @@ export class AutomationEngine implements IAutomationService { */ droppedFields?: readonly DroppedFieldsEvent[], ): Promise { - const ctx = run.context as Record | undefined; - const parentRunId = ctx?.$parentRunId; - if (typeof parentRunId !== 'string' || !parentRunId) return; - try { - // A `map` child (ADR-0037 A2): hand the unit's output to the map - // node + flag the completion, so on re-entry it records this item - // and starts the next. A plain subflow child uses the 1:1 mapping. - const mapNode = ctx?.$parentMapNode; - const sig = typeof mapNode === 'string' && mapNode - // Engine-built: these ARE the reserved handoff keys, and this is - // the one writer allowed to set them (#3853 follow-up). - ? engineBuilt({ variables: { [`${mapNode}.$mapItemOutput`]: output ?? null, [`${mapNode}.$mapItemDone`]: true } }) - : this.buildSubflowResumeSignal(run.context, output); - const parentRes = await this.resumeInternal(parentRunId, sig, false, summary, refusal, droppedFields); - if (!parentRes.success) { - // #6499 — `parentRes.error` is the envelope field that carries - // a failing node's / driver's text VERBATIM (#5912 left it - // that way on purpose), so foreign newlines reach this message - // second-hand; it goes to the structured slot. See - // `forgetSuspendedRun`'s catch above for the full mechanism - // (#6299). - // - // [#15556] The #4632 verdict is taken PER OUTCOME here, graded - // by the engine's own discriminator and never by this seam's - // guess at what went wrong upstream. - // - // The old verdict was FUNCTIONAL for the whole arm, on this - // enumeration: "the parent either failed terminally (recorded - // in run history) or stays visibly parked and resumable". A - // reproduction of the composition the enumeration never - // covered — a parent parked at a `subflow` node whose child - // hosts an approval, resumed by the approvals decision door — - // measured a THIRD outcome: `resumeInternal` answers - // `{ success: false, status: 'stranded' }` (and no `code`), - // because the parent consumed its suspension and then threw - // downstream. That exit journals a repair snapshot and records - // the parent `failed`, so the parent is neither parked nor - // merely failed: nothing in the engine will ever move it again - // and only {@link restoreConsumedSuspension} can re-arm it. - // - // That is AGENTS.md's DURABILITY class verbatim — persisted - // state and runtime state disagree and nothing looks broken - // from the outside: the approval row is durably terminal, the - // child's own resume genuinely succeeded, and the decision - // door therefore answered its caller success. ⛔ And the rule's - // third legal answer (a failure handed to the CALLER is not a - // degradation) does NOT apply: measured, no caller is told. - // - // ⛔ Deliberately NOT the whole arm. `RESUME_IN_PROGRESS` (a - // replica is already advancing the parent) and - // `STORE_UNAVAILABLE` (the parent's suspension was not - // consumed, so it stays parked and the identical resume works - // once the store recovers) are exactly the functional cases - // the old verdict was right about, and escalating those is how - // `error` becomes unreadable. `status === 'stranded'` is the - // ONE exit that journalled a snapshot, so it is the one an - // operator can and must act on. - // - // #15556 family ruling (#16472, maintainer 2026-09-07, decision - // batch #76, option A): the LOG half stays exactly as it was - // (below, unchanged) — the door's status code does not move — - // and the strand is ALSO recorded here, under the CHILD's own - // run id, so `takeSubflowParentStrand` can hand it to whichever - // caller resumed that child. Not a widening of what this - // method tells ITS OWN caller (still `void`, still never - // thrown) — a sibling side-channel, read only by a caller that - // asks for it by name. - if (parentRes.status === 'stranded') { - this.subflowParentStrands.set(run.runId, { - runId: parentRunId, - repairable: true, - error: parentRes.error ?? 'unknown error', - // [#34638] The refusal the parent met, off its own - // result (`{}` when it met none) — so the caller that - // takes this strand tells WHY, not only THAT. - ...carriedRefusalOfResult(parentRes), - }); - while (this.subflowParentStrands.size > MAX_CONSUMED_SUSPENSIONS) { - const oldest = this.subflowParentStrands.keys().next().value; - if (oldest === undefined) break; - this.subflowParentStrands.delete(oldest); - } - // THIRD argument per the `Logger` contract - // (`error(message, error?, meta?)`); the `Error` slot stays - // empty on purpose (#5575). The message owes the two things - // AGENTS.md's durability rule asks of an `error`: the - // CONSEQUENCE, concretely, and the FIX. - this.logger.error( - `[automation] subflow run '${run.runId}' completed, but its parent run ` + - `'${parentRunId}' is STRANDED — the parent consumed its suspension and then failed ` + - `downstream, so no resume, timer or restart will move it again, while this child's ` + - `resumer (an approvals decision door, a wait timer) was told the resume SUCCEEDED and ` + - `nothing else reports the parent. Repair it with ` + - `restoreConsumedSuspension('${parentRunId}') and re-issue the continuation. The ` + - `parent's failure envelope is in this record's meta.`, - undefined, - { error: parentRes.error ?? 'unknown error', parentRunId, status: parentRes.status }, - ); - } else { - // #4632 verdict: FUNCTIONAL — stays `warn`, unchanged: on - // every other exit nothing claimed-persisted fails to land - // — the parent either failed terminally (recorded in run - // history) or stays visibly parked and resumable — and the - // child's own completion, which is what its resumer was - // told, is genuine. - this.logger.warn( - `[automation] subflow run '${run.runId}' completed but resuming parent '${parentRunId}' ` + - `failed — the parent's failure envelope is in this record's meta.`, - { error: parentRes.error ?? 'unknown error' }, - ); - } - } - } catch (err) { - // #6499 — thrown text to the structured slot; see - // `forgetSuspendedRun`'s catch above for the full mechanism - // (#6299). #4632 verdict: FUNCTIONAL — stays `warn`, the same - // consequence envelope as the branch above: the parent's - // suspension was either consumed with a recorded outcome or - // survives parked and resumable; nothing reads as success that - // is not. - this.logger.warn( - `[automation] subflow run '${run.runId}' completed but resuming parent '${parentRunId}' ` + - `threw — the thrown failure is in this record's meta.`, - describeThrownForLog(err), - ); - } + return ResumeFacet.bubbleToParent.call(resumeHost.of(this), run, output, summary, refusal, droppedFields); } /** @@ -7829,7 +5664,7 @@ export class AutomationEngine implements IAutomationService { refusal: SuspensionRestoreRefusal, reason: string, ): SuspensionRestoreResult { - return { restored: false, runId, refusal, reason }; + return ResumeFacet.refuseRestore(runId, refusal, reason); } /** @@ -8210,8 +6045,8 @@ export class AutomationEngine implements IAutomationService { * "unknown" before writing anything wants {@link hasSuspendedRun}, which * throws instead. */ - async getSuspendedScreen(runId: string): Promise { - return (await this.loadSuspendedRun(runId))?.screen ?? null; + getSuspendedScreen(runId: string): Promise { + return ResumeFacet.getSuspendedScreen.call(resumeHost.of(this), runId); } // ── DAG Traversal Core ────────────────────────────────── @@ -8247,25 +6082,7 @@ export class AutomationEngine implements IAutomationService { context?: AutomationContext, consumedSuspension?: SuspendedRun, ): ExecutionLogEntry { - // [#31696] A run whose key moved in flight is recorded where it moved. - const filed = this.flowKeyNow(entry.flowName); - if (filed !== entry.flowName) entry = { ...entry, flowName: filed }; - // The body lives in ./run-history.ts (#25222). - const readStore = () => this.store; - const host: ThisParameterType = { - executionLogs: this.executionLogs, - maxLogSize: this.maxLogSize, - runSummaryLog: this.runSummaryLog, - logger: this.logger, - get store() { return readStore(); }, - compactStepsForHistory: (...a) => this.compactStepsForHistory(...a), - consumedSuspensions: this.consumedSuspensions, - }; - const logged = recordLog.call(host, entry, context, consumedSuspension); - // The body a finished run ran, beside its ring entry (see {@link getRunFlowChecksum}). - const checksum = runRecordFlowChecksum(context, logged.id, consumedSuspension); - if (checksum !== undefined && isTerminalRunStatus(logged.status)) this.entryFlowChecksums.set(logged, checksum); - return logged; + return RunFacet.recordLog.call(runHost.of(this), entry, context, consumedSuspension); } /** @@ -8344,7 +6161,7 @@ export class AutomationEngine implements IAutomationService { * surface can still nest what it retains. */ private compactStepsForHistory(steps: StepLogEntry[]): StepLogEntry[] { - return compactStepLogForHistory(steps, MAX_PERSISTED_HISTORY_STEPS); + return RunFacet.compactStepsForHistory(steps); } /** @@ -8353,11 +6170,7 @@ export class AutomationEngine implements IAutomationService { * executor, or has a published action descriptor. */ private knownNodeTypes(): Set { - return new Set([ - ...FLOW_STRUCTURAL_NODE_TYPES, - ...this.nodeExecutors.keys(), - ...this.actionDescriptors.keys(), - ]); + return ExtensionsFacet.knownNodeTypes.call(extensionsHost.of(this)); } /** @@ -8389,16 +6202,7 @@ export class AutomationEngine implements IAutomationService { * sequence and not a property of the engine. */ getUnknownNodeTypeAudit(): UnknownNodeTypeAuditEntry[] { - const known = this.knownNodeTypes(); - const audit: UnknownNodeTypeAuditEntry[] = []; - for (const [flowName, flow] of this.flows) { - if (!this.isFlowEnabled(flowName)) continue; - const unknownTypes = this.unknownNodeTypes(flow, known); - if (unknownTypes.length > 0) { - audit.push({ flowName, unknownTypes, knownTypes: [...known] }); - } - } - return audit; + return ExtensionsFacet.getUnknownNodeTypeAudit.call(extensionsHost.of(this)); } /** @@ -8430,13 +6234,7 @@ export class AutomationEngine implements IAutomationService { * summary reads engine state rather than scraping log lines. */ sealNodeTypeVocabulary(): UnknownNodeTypeAuditEntry[] { - const alreadySealed = this.nodeTypeVocabularySealed; - this.nodeTypeVocabularySealed = true; - const audit = this.getUnknownNodeTypeAudit(); - if (!alreadySealed) { - for (const entry of audit) this.warnUnknownNodeTypes(entry); - } - return audit; + return ExtensionsFacet.sealNodeTypeVocabulary.call(extensionsHost.of(this)); } /** @@ -8451,7 +6249,7 @@ export class AutomationEngine implements IAutomationService { * than record a refusal the boot can contradict. Read-only; it never seals. */ getSealedNodeTypeVocabulary(): string[] | undefined { - return this.nodeTypeVocabularySealed ? [...this.knownNodeTypes()].sort() : undefined; + return ExtensionsFacet.getSealedNodeTypeVocabulary.call(extensionsHost.of(this)); } /** @@ -8517,20 +6315,7 @@ export class AutomationEngine implements IAutomationService { /** One warning per flow, shared by the boot audit and the post-seal path. */ private warnUnknownNodeTypes(entry: UnknownNodeTypeAuditEntry): void { - // #6654 — the unknown type names are FLOW-AUTHOR metadata and the - // registered vocabulary is plugin-supplied (neither is - // schema-constrained against newlines), so both lists ride the - // structured slot, never the message; see `forgetSuspendedRun`'s - // catch for the full mechanism (#6299). The "no registered executor - // or descriptor" phrase is load-bearing — tests and log filters count - // per-flow findings by it. #4632: FUNCTIONAL — stays `warn`. - this.logger.warn( - `Flow '${entry.flowName}' references node type(s) with no registered executor or descriptor — ` + - `the unknown type names and the registered vocabulary are in this record's meta. Every plugin ` + - `has started, so nothing will register them now — these nodes fail at execution time with ` + - `NO_EXECUTOR. Install/enable the plugin that contributes them.`, - { unknownTypes: entry.unknownTypes, knownTypes: entry.knownTypes }, - ); + return ExtensionsFacet.warnUnknownNodeTypes.call(extensionsHost.of(this), entry); } /** @@ -8546,17 +6331,9 @@ export class AutomationEngine implements IAutomationService { * doors that canonicalize without registering log nothing new. */ private registrationChecks( - { advisory }: { advisory: boolean }, + options: { advisory: boolean }, ): ReadonlyArray<(flowName: string, flow: FlowParsed) => RegistrationCheckRefusal | undefined> { - // The body lives in ./flow-registration-checks.ts (#25222). - const host: ThisParameterType = { - validateNodeConfigKeys: (...a) => this.validateNodeConfigKeys(...a), - validateDecisionModes: (...a) => this.validateDecisionModes(...a), - validateFlowExpressions: (...a) => this.validateFlowExpressions(...a), - validateApiTriggerSecret: (...a) => this.validateApiTriggerSecret(...a), - refuseUnpackagedDefaultActive: (...a) => this.refuseUnpackagedDefaultActive(...a), - }; - return registrationChecks.call(host, { advisory }); + return RegistrationFacet.registrationChecks.call(registrationHost.of(this), options); } /** @@ -8805,16 +6582,9 @@ export class AutomationEngine implements IAutomationService { private validateFlowExpressions( flowName: string, flow: FlowParsed, - { advisory }: { advisory: boolean }, + options: { advisory: boolean }, ): RegistrationCheckRefusal | undefined { - // The body lives in ./flow-registration-checks.ts (#25222). - const host: ThisParameterType = { - logger: this.logger, - objectSchemaResolver: this.objectSchemaResolver, - valueEnvelopeRefusals: (...a) => this.valueEnvelopeRefusals(...a), - deriveTriggerBinding: (...a) => this.deriveTriggerBinding(...a), - }; - return validateFlowExpressions.call(host, flowName, flow, { advisory }); + return RegistrationFacet.validateFlowExpressions.call(registrationHost.of(this), flowName, flow, options); } /** @@ -8838,9 +6608,7 @@ export class AutomationEngine implements IAutomationService { * Get the runtime type name of a value for schema validation. */ private getValueType(value: unknown): string { - if (Array.isArray(value)) return 'array'; - if (typeof value === 'object' && value !== null) return 'object'; - return typeof value; + return RegistrationFacet.getValueType(value); } /** @@ -8869,26 +6637,7 @@ export class AutomationEngine implements IAutomationService { * `execute()` does with the throw. */ private validateNodeInputSchemas(flow: FlowParsed, _variables: Map): void { - for (const node of flow.nodes) { - if (node.inputSchema && node.config) { - for (const [paramName, paramDef] of Object.entries(node.inputSchema)) { - if (paramDef.required && !(paramName in (node.config as Record))) { - throw new InputSchemaViolationError( - `Node '${node.id}' missing required input parameter '${paramName}'`, - ); - } - const value = (node.config as Record)[paramName]; - if (value !== undefined) { - const actualType = this.getValueType(value); - if (actualType !== paramDef.type) { - throw new InputSchemaViolationError( - `Node '${node.id}' parameter '${paramName}' expected type '${paramDef.type}' but got '${actualType}'`, - ); - } - } - } - } - } + return RegistrationFacet.validateNodeInputSchemas.call(registrationHost.of(this), flow, _variables); } /** @@ -9184,17 +6933,7 @@ export class AutomationEngine implements IAutomationService { grouping?: { parentNodeId: string; iteration?: number; branch?: number; regionKind?: string; retryAttempt?: number }, 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: dryExecuteNode ?? ((...a) => this.executeNode(...a)), - resolveSuspensionChainForCancel: (...a) => this.resolveSuspensionChainForCancel(...a), - cancelRun: (...a) => this.cancelRun(...a), - logger: this.logger, - }; - return runRegion.call(host, region, variables, context, grouping, partialSteps); + return RunFacet.runRegion.call(runHost.of(this), region, variables, context, grouping, partialSteps); } /** @@ -9560,7 +7299,7 @@ export class AutomationEngine implements IAutomationService { * dispatched (its flow vanished or was disabled between attempts) bound no * variable, so the template renders over none. */ - private async retryExecution( + private retryExecution( flowName: string, context: AutomationContext | undefined, startTime: number, @@ -9568,91 +7307,7 @@ export class AutomationEngine implements IAutomationService { flowErrorMessage: string | undefined, flowLabel: string, ): Promise { - // `maxRetries >= 1` is guaranteed under `strategy: 'retry'` — the schema - // refuses the zero-attempt spelling of "retry" (#4247), so reaching this - // method always means at least one re-run. - // `backoffMs` (was `retryDelayMs`) since spec 17.0.0 — `errorHandling` - // now carries the converged `RetryPolicySchema` contract, so this reads - // the same key the `try_catch` executor and `runWithPolicy` read - // (#4661, #4964). Destructured, not `??`-defaulted: the parsed block is - // the only source of these numbers (#4247). - const { - maxRetries, - backoffMs: baseDelay, - backoffMultiplier: multiplier, - maxRetryDelayMs: maxDelay, - jitter: useJitter, - } = errorHandling; - - let lastError = 'Max retries exceeded'; - // [#24914, ruling B′] The refusal the LAST attempt met, kept paired - // with `lastError` so the exhausted exit never reports one attempt's - // text beside another attempt's refusal. - let lastCarried: CarriedRefusal = {}; - // [#28054] The last attempt's rendering of `flowErrorMessage`, paired - // with `lastError` the same way. - let lastErrorMessage: string | undefined; - for (let i = 0; i < maxRetries; i++) { - // Calculate delay with exponential backoff - let delay = Math.min(baseDelay * Math.pow(multiplier, i), maxDelay); - if (useJitter) { - delay = delay * (0.5 + Math.random() * 0.5); - } - await new Promise(r => setTimeout(r, delay)); - - // Execute directly without recursion into retryExecution again - const result = await this.executeWithoutRetry(flowName, context, { errorMessage: flowErrorMessage }); - // [#9510] THE THIRD STATE, read deliberately and BEFORE `success`. - // Since the ADR-0019 suspend arm was restored to - // `executeWithoutRetry`, an attempt can end NON-TERMINAL: the run - // asked to pause, its continuation is persisted under - // `result.runId`, and it is waiting for a `resume()` that may - // arrive days later. Returning it is the only correct answer — - // re-running the flow would start the paused work a SECOND time - // while the first continuation is still live and resumable, which - // is what the pre-repair loop did on every remaining attempt. - // - // ⛔ Not left to the `result.success` line below, even though a - // paused result is `success: true` and would fall through it today. - // That line means "this attempt SUCCEEDED, stop retrying" — a - // different sentence about a different outcome — and a - // non-terminal result recognised only by a branch that names - // something else is one edit away from being misread again. The - // reason this returns is the PAUSE, so the pause is what it tests. - // - // ⛔ And it weakens no retry accounting: nothing above is skipped, - // reset or shortened, `maxRetries` still bounds the loop, and a - // genuinely failing attempt still consumes one. The loop stops here - // only because this attempt did not fail. - if (result.status === 'paused') return result; - if (result.success) return result; - lastError = result.error ?? 'Unknown error'; - lastCarried = carriedRefusalOfResult(result); - lastErrorMessage = result.status === 'failed' - ? result.errorMessage - : this.renderFlowTerminalMessage(flowName, 'errorMessage', flowErrorMessage, new Map(), context ?? {}); - } - // [#9378] Same "ran and was rejected" class as `execute()`'s own failure - // exit — every attempt above dispatched the flow — so it carries the - // same lifecycle verdict, and a transport answers it the same way. - // Without it, a flow whose author chose `errorHandling.strategy: - // 'retry'` would be the ONE failure shape that still rode HTTP 200. - // - // [#9414] `errorMessage` for the same structural reason: this is a - // DIFFERENT terminal exit from `execute()`'s own failure return — a - // flow under `strategy: 'retry'` is handed off above and never reaches - // that one — so a repair that stopped at `execute()` would leave the - // author's message missing for precisely the runs most likely to need - // it, the ones that failed over and over. - return { - success: false, - error: lastError, - durationMs: Date.now() - startTime, - status: 'failed', - errorMessage: lastErrorMessage, - flowLabel, - ...lastCarried, - }; + return RunFacet.retryExecution.call(runHost.of(this), flowName, context, startTime, errorHandling, flowErrorMessage, flowLabel); } /** @@ -9810,4 +7465,271 @@ export class AutomationEngine implements IAutomationService { }; return executeWithoutRetry.call(host, flowName, context, dispatched); } + + static { + dispatchHost.install((engine) => ({ + get flowDispatchStore() { return engine.flowDispatchStore; }, + get flowSlots() { return engine.flowSlots; }, + get flows() { return engine.flows; }, + get logger() { return engine.logger; }, + get maxLogSize() { return engine.maxLogSize; }, + recordLog: (...a) => engine.recordLog(...a), + get runsStartedByContext() { return engine.runsStartedByContext; }, + get scheduledWorkPolicy() { return engine.scheduledWorkPolicy; }, + get store() { return engine.store; }, + })); + extensionsHost.install((engine) => ({ + get actionDescriptors() { return engine.actionDescriptors; }, + get boundFlowTriggers() { return engine.boundFlowTriggers; }, + connectorInstance: (...a) => engine.connectorInstance(...a), + get connectorProviders() { return engine.connectorProviders; }, + get connectors() { return engine.connectors; }, + get credentialHandleProviders() { return engine.credentialHandleProviders; }, + declineOntoDisabledSubflows: (...a) => engine.declineOntoDisabledSubflows(...a), + declineOntoRegionSuspendingCall: (...a) => engine.declineOntoRegionSuspendingCall(...a), + declineOntoSubflowRetriedCallout: (...a) => engine.declineOntoSubflowRetriedCallout(...a), + declineOntoSuspendingSubflowNotice: (...a) => engine.declineOntoSuspendingSubflowNotice(...a), + deriveTriggerBinding: (...a) => engine.deriveTriggerBinding(...a), + get disabledHolderDispatchSaid() { return engine.disabledHolderDispatchSaid; }, + execute: (...a) => engine.execute(...a), + executeKey: (...a) => engine.executeKey(...a), + flowKeyNow: (...a) => engine.flowKeyNow(...a), + get flowRefusals() { return engine.flowRefusals; }, + flowSlotName: (...a) => engine.flowSlotName(...a), + get flowSlots() { return engine.flowSlots; }, + get flows() { return engine.flows; }, + getUnknownNodeTypeAudit: (...a) => engine.getUnknownNodeTypeAudit(...a), + isDisabledHolderSlot: (...a) => engine.isDisabledHolderSlot(...a), + isFlowEnabled: (...a) => engine.isFlowEnabled(...a), + knownNodeTypes: (...a) => engine.knownNodeTypes(...a), + get logger() { return engine.logger; }, + loneSharedFlowKey: (...a) => engine.loneSharedFlowKey(...a), + get nodeExecutors() { return engine.nodeExecutors; }, + get nodeTypeVocabularySealed() { return engine.nodeTypeVocabularySealed; }, + set nodeTypeVocabularySealed(v) { engine.nodeTypeVocabularySealed = v; }, + get organizationLocaleResolver() { return engine.organizationLocaleResolver; }, + get policyDisabledFlows() { return engine.policyDisabledFlows; }, + readScheduledWorkPolicy: (...a) => engine.readScheduledWorkPolicy(...a), + resolveTriggerBinding: (...a) => engine.resolveTriggerBinding(...a), + settleFlowName: (...a) => engine.settleFlowName(...a), + get sharedSlotTriggerWarned() { return engine.sharedSlotTriggerWarned; }, + triggerRun: (...a) => engine.triggerRun(...a), + get triggers() { return engine.triggers; }, + unknownNodeTypes: (...a) => engine.unknownNodeTypes(...a), + warnUnknownNodeTypes: (...a) => engine.warnUnknownNodeTypes(...a), + })); + flowSlotsHost.install((engine) => ({ + activateFlowTrigger: (...a) => engine.activateFlowTrigger(...a), + armedFlowPackage: (...a) => engine.armedFlowPackage(...a), + bindPackagelessActivation: (...a) => engine.bindPackagelessActivation(...a), + codeRegisteredInstance: (...a) => engine.codeRegisteredInstance(...a), + get connectorNameResolver() { return engine.connectorNameResolver; }, + get connectors() { return engine.connectors; }, + deactivateFlowTrigger: (...a) => engine.deactivateFlowTrigger(...a), + disabledHolderHookRefused: (...a) => engine.disabledHolderHookRefused(...a), + durableFlowHolder: (...a) => engine.durableFlowHolder(...a), + executeKey: (...a) => engine.executeKey(...a), + get executionLogs() { return engine.executionLogs; }, + get flowActivationStore() { return engine.flowActivationStore; }, + flowArmHolder: (...a) => engine.flowArmHolder(...a), + get flowArms() { return engine.flowArms; }, + flowCallerPackage: (...a) => engine.flowCallerPackage(...a), + flowHolder: (...a) => engine.flowHolder(...a), + get flowHoldersSealed() { return engine.flowHoldersSealed; }, + flowKeyNow: (...a) => engine.flowKeyNow(...a), + flowKeyOfRun: (...a) => engine.flowKeyOfRun(...a), + get flowLedgerDisabled() { return engine.flowLedgerDisabled; }, + flowNameRefusal: (...a) => engine.flowNameRefusal(...a), + get flowNameResolver() { return engine.flowNameResolver; }, + get flowShadowing() { return engine.flowShadowing; }, + flowSlotPackage: (...a) => engine.flowSlotPackage(...a), + get flowSlots() { return engine.flowSlots; }, + get flowStatusDisabled() { return engine.flowStatusDisabled; }, + get flowVersionHistory() { return engine.flowVersionHistory; }, + get flows() { return engine.flows; }, + isDisabledHolderSlot: (...a) => engine.isDisabledHolderSlot(...a), + isDisabledSoleHolder: (...a) => engine.isDisabledSoleHolder(...a), + isFlowEnabled: (...a) => engine.isFlowEnabled(...a), + isPackagedFlow: (...a) => engine.isPackagedFlow(...a), + isShippedFlowName: (...a) => engine.isShippedFlowName(...a), + loaderOwnerOf: (...a) => engine.loaderOwnerOf(...a), + get logger() { return engine.logger; }, + moveFlowRecords: (...a) => engine.moveFlowRecords(...a), + get movedFlowKeys() { return engine.movedFlowKeys; }, + get packagedFlowDefaultSource() { return engine.packagedFlowDefaultSource; }, + set packagedFlowDefaultSource(v) { engine.packagedFlowDefaultSource = v; }, + get packagedFlowDefaults() { return engine.packagedFlowDefaults; }, + set packagedFlowDefaults(v) { engine.packagedFlowDefaults = v; }, + packagedFlowOwner: (...a) => engine.packagedFlowOwner(...a), + packagedFlowSlotOwner: (...a) => engine.packagedFlowSlotOwner(...a), + get packagedFlowSource() { return engine.packagedFlowSource; }, + set packagedFlowSource(v) { engine.packagedFlowSource = v; }, + get pendingFlowActivationBinds() { return engine.pendingFlowActivationBinds; }, + get policyDisabledFlows() { return engine.policyDisabledFlows; }, + rejudgeSubflowCallers: (...a) => engine.rejudgeSubflowCallers(...a), + resolveConnectorInstanceFor: (...a) => engine.resolveConnectorInstanceFor(...a), + resolveFlowKey: (...a) => engine.resolveFlowKey(...a), + settleFlowName: (...a) => engine.settleFlowName(...a), + sharedFlowNameRefusal: (...a) => engine.sharedFlowNameRefusal(...a), + get sharedSlotTriggerWarned() { return engine.sharedSlotTriggerWarned; }, + get subflowDeclinedFlows() { return engine.subflowDeclinedFlows; }, + get subflowNoticeDeclinedFlows() { return engine.subflowNoticeDeclinedFlows; }, + get subflowRegionDeclinedFlows() { return engine.subflowRegionDeclinedFlows; }, + get subflowRetryDeclinedFlows() { return engine.subflowRetryDeclinedFlows; }, + get suspendedRuns() { return engine.suspendedRuns; }, + })); + registrationHost.install((engine) => ({ + activateFlowTrigger: (...a) => engine.activateFlowTrigger(...a), + bareFlowKey: (...a) => engine.bareFlowKey(...a), + canonicalizeFlow: (...a) => engine.canonicalizeFlow(...a), + deactivateFlowTrigger: (...a) => engine.deactivateFlowTrigger(...a), + deriveTriggerBinding: (...a) => engine.deriveTriggerBinding(...a), + evaluateCondition: (...a) => engine.evaluateCondition(...a), + evaluateValueEnvelope: (...a) => engine.evaluateValueEnvelope(...a), + executeWithTimeout: (...a) => engine.executeWithTimeout(...a), + get flowArms() { return engine.flowArms; }, + get flowChecksums() { return engine.flowChecksums; }, + flowKeyOfRun: (...a) => engine.flowKeyOfRun(...a), + get flowRefusals() { return engine.flowRefusals; }, + get flowShadowing() { return engine.flowShadowing; }, + flowSlotName: (...a) => engine.flowSlotName(...a), + get flowSlots() { return engine.flowSlots; }, + get flowStatusDisabled() { return engine.flowStatusDisabled; }, + get flowVersionHistory() { return engine.flowVersionHistory; }, + get flows() { return engine.flows; }, + getActionDescriptor: (...a) => engine.getActionDescriptor(...a), + getValueType: (...a) => engine.getValueType(...a), + isFlowEnabled: (...a) => engine.isFlowEnabled(...a), + isPackagedFlow: (...a) => engine.isPackagedFlow(...a), + judgeFlowRegistration: (...a) => engine.judgeFlowRegistration(...a), + knownNodeTypes: (...a) => engine.knownNodeTypes(...a), + get logger() { return engine.logger; }, + loneSharedFlowKey: (...a) => engine.loneSharedFlowKey(...a), + moveFlowRecords: (...a) => engine.moveFlowRecords(...a), + get nodeExecutors() { return engine.nodeExecutors; }, + get nodeTypeVocabularySealed() { return engine.nodeTypeVocabularySealed; }, + get objectSchemaResolver() { return engine.objectSchemaResolver; }, + packagedSubflowCallers: (...a) => engine.packagedSubflowCallers(...a), + placeFlowSlot: (...a) => engine.placeFlowSlot(...a), + get policyDisabledFlows() { return engine.policyDisabledFlows; }, + refuseUnderReachingCallers: (...a) => engine.refuseUnderReachingCallers(...a), + refuseUnpackagedDefaultActive: (...a) => engine.refuseUnpackagedDefaultActive(...a), + registrationChecks: (...a) => engine.registrationChecks(...a), + rejudgeSubflowCallers: (...a) => engine.rejudgeSubflowCallers(...a), + renderFlowTextSlot: (...a) => engine.renderFlowTextSlot(...a), + renderRefusalMessage: (...a) => engine.renderRefusalMessage(...a), + resolveRunContext: (...a) => engine.resolveRunContext(...a), + seedRunVariables: (...a) => engine.seedRunVariables(...a), + servedBareFlowKey: (...a) => engine.servedBareFlowKey(...a), + setNodeError: (...a) => engine.setNodeError(...a), + get sharedSlotTriggerWarned() { return engine.sharedSlotTriggerWarned; }, + get subflowDeclinedFlows() { return engine.subflowDeclinedFlows; }, + get subflowNoticeDeclinedFlows() { return engine.subflowNoticeDeclinedFlows; }, + get subflowRegionDeclinedFlows() { return engine.subflowRegionDeclinedFlows; }, + get subflowRetryDeclinedFlows() { return engine.subflowRetryDeclinedFlows; }, + unknownNodeTypes: (...a) => engine.unknownNodeTypes(...a), + get userGrantsResolver() { return engine.userGrantsResolver; }, + validateApiTriggerSecret: (...a) => engine.validateApiTriggerSecret(...a), + validateDecisionModes: (...a) => engine.validateDecisionModes(...a), + validateFlowExpressions: (...a) => engine.validateFlowExpressions(...a), + validateNodeConfigKeys: (...a) => engine.validateNodeConfigKeys(...a), + validateNodeInputSchemas: (...a) => engine.validateNodeInputSchemas(...a), + valueEnvelopeRefusals: (...a) => engine.valueEnvelopeRefusals(...a), + warnUnknownNodeTypes: (...a) => engine.warnUnknownNodeTypes(...a), + withdrawFlowKey: (...a) => engine.withdrawFlowKey(...a), + })); + connectorDoorsHost.install((engine) => ({ + get connectorConnectionDoor() { return engine.connectorConnectionDoor; }, + get connectorCredentialDoor() { return engine.connectorCredentialDoor; }, + get connectorPullSource() { return engine.connectorPullSource; }, + get flowCredentialSource() { return engine.flowCredentialSource; }, + set flowCredentialSource(v) { engine.flowCredentialSource = v; }, + get flowSlots() { return engine.flowSlots; }, + get flows() { return engine.flows; }, + requireConnectorConnectionDoor: (...a) => engine.requireConnectorConnectionDoor(...a), + requireConnectorCredentialDoor: (...a) => engine.requireConnectorCredentialDoor(...a), + sharedFlowNameRefusal: (...a) => engine.sharedFlowNameRefusal(...a), + })); + enablementHost.install((engine) => ({ + bareFlowKey: (...a) => engine.bareFlowKey(...a), + describeDisabledSubflows: (...a) => engine.describeDisabledSubflows(...a), + disabledPackagedSubflows: (...a) => engine.disabledPackagedSubflows(...a), + get flowArms() { return engine.flowArms; }, + get flowCallKey() { return engine.flowCallKey; }, + get flowLedgerDisabled() { return engine.flowLedgerDisabled; }, + get flowSlots() { return engine.flowSlots; }, + get flowStatusDisabled() { return engine.flowStatusDisabled; }, + get flowVersionHistory() { return engine.flowVersionHistory; }, + get flows() { return engine.flows; }, + isPackagedFlow: (...a) => engine.isPackagedFlow(...a), + get logger() { return engine.logger; }, + resolveFlowKey: (...a) => engine.resolveFlowKey(...a), + resolvedFlowCallKey: (...a) => engine.resolvedFlowCallKey(...a), + servedBareFlowKey: (...a) => engine.servedBareFlowKey(...a), + get subflowDeclinedFlows() { return engine.subflowDeclinedFlows; }, + get subflowNoticeDeclinedFlows() { return engine.subflowNoticeDeclinedFlows; }, + get subflowRegionDeclinedFlows() { return engine.subflowRegionDeclinedFlows; }, + get subflowRetryDeclinedFlows() { return engine.subflowRetryDeclinedFlows; }, + toggleFlowKey: (...a) => engine.toggleFlowKey(...a), + })); + runHost.install((engine) => ({ + get activeRecordFlows() { return engine.activeRecordFlows; }, + cancelRun: (...a) => engine.cancelRun(...a), + compactStepsForHistory: (...a) => engine.compactStepsForHistory(...a), + get consumedSuspensions() { return engine.consumedSuspensions; }, + describeDisabledFlow: (...a) => engine.describeDisabledFlow(...a), + get entryFlowChecksums() { return engine.entryFlowChecksums; }, + evaluateCondition: (...a) => engine.evaluateCondition(...a), + executeKey: (...a) => engine.executeKey(...a), + executeNode: (...a) => engine.executeNode(...a), + executeWithoutRetry: (...a) => engine.executeWithoutRetry(...a), + get executionLogs() { return engine.executionLogs; }, + failRunBeforeFirstNode: (...a) => engine.failRunBeforeFirstNode(...a), + finishRefusedRun: (...a) => engine.finishRefusedRun(...a), + flowCallerPackage: (...a) => engine.flowCallerPackage(...a), + flowChecksumOf: (...a) => engine.flowChecksumOf(...a), + flowKeyNow: (...a) => engine.flowKeyNow(...a), + flowSlotPackage: (...a) => engine.flowSlotPackage(...a), + get flows() { return engine.flows; }, + isFlowEnabled: (...a) => engine.isFlowEnabled(...a), + get logger() { return engine.logger; }, + get maxLogSize() { return engine.maxLogSize; }, + nextRunId: (...a) => engine.nextRunId(...a), + noteRunStarted: (...a) => engine.noteRunStarted(...a), + persistSuspendedRun: (...a) => engine.persistSuspendedRun(...a), + recordLog: (...a) => engine.recordLog(...a), + renderFlowTerminalMessage: (...a) => engine.renderFlowTerminalMessage(...a), + resolveFlowKey: (...a) => engine.resolveFlowKey(...a), + resolveRunContext: (...a) => engine.resolveRunContext(...a), + resolveSuspensionChainForCancel: (...a) => engine.resolveSuspensionChainForCancel(...a), + retryExecution: (...a) => engine.retryExecution(...a), + get runSummaryLog() { return engine.runSummaryLog; }, + seedRunVariables: (...a) => engine.seedRunVariables(...a), + get store() { return engine.store; }, + validateNodeInputSchemas: (...a) => engine.validateNodeInputSchemas(...a), + warnIfNodeTypeVocabularyNeverSealed: (...a) => engine.warnIfNodeTypeVocabularyNeverSealed(...a), + })); + resumeHost.install((engine) => ({ + buildSubflowResumeSignal: (...a) => engine.buildSubflowResumeSignal(...a), + get cacheOnlySuspensions() { return engine.cacheOnlySuspensions; }, + canonicalizeFlow: (...a) => engine.canonicalizeFlow(...a), + evaluateCondition: (...a) => engine.evaluateCondition(...a), + get flowChecksums() { return engine.flowChecksums; }, + get flowHistorySource() { return engine.flowHistorySource; }, + flowKeyNow: (...a) => engine.flowKeyNow(...a), + get flowVersionHistory() { return engine.flowVersionHistory; }, + get flows() { return engine.flows; }, + loadSuspendedRun: (...a) => engine.loadSuspendedRun(...a), + loadSuspendedRunStrict: (...a) => engine.loadSuspendedRunStrict(...a), + get logger() { return engine.logger; }, + resolveCanonicalDescriptor: (...a) => engine.resolveCanonicalDescriptor(...a), + resolveResumeTarget: (...a) => engine.resolveResumeTarget(...a), + resumeInternal: (...a) => engine.resumeInternal(...a), + get store() { return engine.store; }, + get subflowParentStrands() { return engine.subflowParentStrands; }, + get suspendedRuns() { return engine.suspendedRuns; }, + walkSuspensionChain: (...a) => engine.walkSuspensionChain(...a), + warnAdvanceClaimDegraded: (...a) => engine.warnAdvanceClaimDegraded(...a), + })); + } } diff --git a/packages/spec/liveness/connector.json b/packages/spec/liveness/connector.json index b3c425172af..be698fd8812 100644 --- a/packages/spec/liveness/connector.json +++ b/packages/spec/liveness/connector.json @@ -5,7 +5,7 @@ "name": { "status": "live", "verifiedAt": "2026-09-17", - "evidence": "packages/services/service-automation/src/plugin.ts#materializeDeclaredConnectors — the authored name keys the desired-set map, is the identity the §4 origin-conflict rule is checked against (`engine.getConnectorOrigin(name) === 'plugin'`), and is FORCED onto the provider's def (`const def = { ...materialization.def, name }`) so discovery and dispatch agree with the metadata; packages/services/service-automation/src/engine.ts#getConnectorDescriptors publishes it as the connector id on `GET /api/v1/automation/connectors`, which is what a `connector_action` flow node names in `connectorConfig.connectorId`.", + "evidence": "packages/services/service-automation/src/plugin.ts#materializeDeclaredConnectors — the authored name keys the desired-set map, is the identity the §4 origin-conflict rule is checked against (`engine.getConnectorOrigin(name) === 'plugin'`), and is FORCED onto the provider's def (`const def = { ...materialization.def, name }`) so discovery and dispatch agree with the metadata; packages/services/service-automation/src/engine-extensions-facet.ts#getConnectorDescriptors publishes it as the connector id on `GET /api/v1/automation/connectors`, which is what a `connector_action` flow node names in `connectorConfig.connectorId`.", "producer": "packages/services/service-automation/src/plugin.ts#materializeDeclaredConnectors — the ADR-0097 reconcile: it builds the desired set from the declared `connectors:` items, resolves the provider factory and calls `engine.registerConnector(def, handlers, 'declarative')`. This is the ONLY seam by which an authored entry reaches the connector registry, so it is the producer every `live` row below depends on (#4837): without it a declared connector is a stored document and nothing else.", "note": "Identity, not display. A duplicate declared name is refused by name (`duplicate declarative connector instance name`), so this key also decides whether a stack boots." }, @@ -13,28 +13,28 @@ "status": "live", "verifiedAt": "2026-09-17", "evidenceScope": "in-repo", - "evidence": "packages/services/service-automation/src/plugin.ts#materializeDeclaredConnectors — `label: entry.label ?? name` puts the authored label on `ConnectorProviderContext`; packages/connectors/connector-openapi/src/openapi-provider.ts, packages/connectors/connector-rest/src/rest-provider.ts and packages/connectors/connector-mcp/src/mcp-provider.ts each copy `label: ctx.label` onto the def they return; packages/services/service-automation/src/engine.ts#getConnectorDescriptors then publishes `label: def.label`; ui/packages/app-shell/src/views/metadata-admin/inspectors/FlowReferenceField.tsx#connectorsToOptions renders it as the connector picker's option text (`${label} (${name})`) in the flow designer.", + "evidence": "packages/services/service-automation/src/plugin.ts#materializeDeclaredConnectors — `label: entry.label ?? name` puts the authored label on `ConnectorProviderContext`; packages/connectors/connector-openapi/src/openapi-provider.ts, packages/connectors/connector-rest/src/rest-provider.ts and packages/connectors/connector-mcp/src/mcp-provider.ts each copy `label: ctx.label` onto the def they return; packages/services/service-automation/src/engine-extensions-facet.ts#getConnectorDescriptors then publishes `label: def.label`; ui/packages/app-shell/src/views/metadata-admin/inspectors/FlowReferenceField.tsx#connectorsToOptions renders it as the connector picker's option text (`${label} (${name})`) in the flow designer.", "producer": "packages/services/service-automation/src/plugin.ts#materializeDeclaredConnectors — the ADR-0097 reconcile: it builds the desired set from the declared `connectors:` items, resolves the provider factory and calls `engine.registerConnector(def, handlers, 'declarative')`. This is the ONLY seam by which an authored entry reaches the connector registry, so it is the producer every `live` row below depends on (#4837): without it a declared connector is a stored document and nothing else.", "note": "Display-shaped, so the #7131 split settles it: being shown to a human IS the whole claimed effect. All three shipped provider factories carry it, so this is the one authored display key that survives materialization intact — contrast `icon` and `type` below, which reach the same context object and are dropped." }, "type": { "status": "live", "verifiedAt": "2026-09-17", - "evidence": "packages/services/service-automation/src/engine.ts#getConnectorDescriptors — `type: def.type` is published on `GET /api/v1/automation/connectors`; packages/services/service-automation/src/plugin.ts#materializeDeclaredConnectors threads the authored value onto the provider context (`type: typeof entry.type === 'string' ? entry.type : 'api'`).", + "evidence": "packages/services/service-automation/src/engine-extensions-facet.ts#getConnectorDescriptors — `type: def.type` is published on `GET /api/v1/automation/connectors`; packages/services/service-automation/src/plugin.ts#materializeDeclaredConnectors threads the authored value onto the provider context (`type: typeof entry.type === 'string' ? entry.type : 'api'`).", "producer": "packages/connectors/connector-openapi/src/openapi-connector.ts (`type: 'api'` in the def literal), packages/connectors/connector-rest/src/rest-connector.ts and packages/connectors/connector-mcp/src/mcp-connector.ts — the def's `type` is supplied by the PLUGIN / provider factory, never carried over from the authored entry.", "note": "⚠️ THE PRODUCER IS NOT THE AUTHOR, and that is the finding on this row. The authored `type` reaches `ConnectorProviderContext.type` and is then dropped: not one of the three shipped provider factories reads `ctx.type`, and `openapi-connector.ts` hard-codes `type: 'api'` into the def it returns. So on the PLUGIN door the key is live (a plugin writes it, `/automation/connectors` publishes it); on the DECLARATIVE door an authored `type: 'database'` on a provider-bound instance is published as whatever the factory chose. `type` is REQUIRED, so every author writes one. ⛔ Not an ADR-0049 candidate — it is enforced on one of its two doors; what is owed is either a factory that honours `ctx.type` or a declaration that it is provider-owned." }, "description": { "status": "live", "verifiedAt": "2026-09-17", - "evidence": "packages/services/service-automation/src/plugin.ts#materializeDeclaredConnectors — `description: entry.description` on the provider context; packages/connectors/connector-openapi/src/openapi-provider.ts and packages/connectors/connector-mcp/src/mcp-provider.ts copy `description: ctx.description` onto the def; packages/services/service-automation/src/engine.ts#getConnectorDescriptors publishes `description: def.description`.", + "evidence": "packages/services/service-automation/src/plugin.ts#materializeDeclaredConnectors — `description: entry.description` on the provider context; packages/connectors/connector-openapi/src/openapi-provider.ts and packages/connectors/connector-mcp/src/mcp-provider.ts copy `description: ctx.description` onto the def; packages/services/service-automation/src/engine-extensions-facet.ts#getConnectorDescriptors publishes `description: def.description`.", "producer": "packages/services/service-automation/src/plugin.ts#materializeDeclaredConnectors — the ADR-0097 reconcile: it builds the desired set from the declared `connectors:` items, resolves the provider factory and calls `engine.registerConnector(def, handlers, 'declarative')`. This is the ONLY seam by which an authored entry reaches the connector registry, so it is the producer every `live` row below depends on (#4837): without it a declared connector is a stored document and nothing else.", "note": "Display-shaped (#7131). Two of the three shipped factories carry it — `connector-rest`'s does not, and writes its own fixed sentence instead — so an authored description survives on the openapi and mcp providers and is replaced on rest. The ADR-0097 §3 refusal message also points an author here (\"describe the auth scheme in `description`\"), which makes it the documented home for what `authentication` may not carry." }, "icon": { "status": "live", "verifiedAt": "2026-09-17", - "evidence": "packages/services/service-automation/src/engine.ts#getConnectorDescriptors — `icon: def.icon` is published on `GET /api/v1/automation/connectors`; packages/services/service-automation/src/plugin.ts#materializeDeclaredConnectors threads the authored value onto the provider context (`icon: entry.icon`).", + "evidence": "packages/services/service-automation/src/engine-extensions-facet.ts#getConnectorDescriptors — `icon: def.icon` is published on `GET /api/v1/automation/connectors`; packages/services/service-automation/src/plugin.ts#materializeDeclaredConnectors threads the authored value onto the provider context (`icon: entry.icon`).", "producer": "packages/connectors/connector-openapi/src/openapi-connector.ts — `icon: config.icon ?? 'globe'`, where `config` is the factory's OWN argument object; the def's icon is supplied by the plugin, not by the authored entry.", "note": "⚠️ Same split as `type`, and measured the same way: `ConnectorProviderContext.icon` is SET by the materializer and read by none of the three shipped provider factories (census: zero `ctx.icon` reads across packages/connectors, with `ctx.label` — four hits — as the lit control in the same scan). So an authored `icon:` on a declarative instance never reaches `/automation/connectors`, while a plugin-registered def's icon does. Optional, unlike `type`, so the trap is quieter." }, @@ -72,7 +72,7 @@ "status": "live", "verifiedAt": "2026-09-17", "evidenceScope": "in-repo", - "evidence": "packages/services/service-automation/src/plugin-extension-api.ts#registerConnector — `if (typeof handlers[action.key] !== 'function') throw` refuses a def whose declared action has no handler, so the key is the contract between declaration and implementation; packages/services/service-automation/src/engine.ts#resolveConnectorActionEffect looks the action up by `a.key === actionId`, and `resolveConnectorAction` returns `handlers[actionId]` for the node to dispatch; packages/services/service-automation/src/engine.ts#getConnectorDescriptors publishes it; ui/packages/app-shell/src/views/metadata-admin/inspectors/FlowReferenceField.tsx (`connectorActionsToOptions`) and .../connector-input-fields.ts#connectorActionInputSchema both resolve an action by `a.key === actionKey`.", + "evidence": "packages/services/service-automation/src/plugin-extension-api.ts#registerConnector — `if (typeof handlers[action.key] !== 'function') throw` refuses a def whose declared action has no handler, so the key is the contract between declaration and implementation; packages/services/service-automation/src/engine.ts#resolveConnectorActionEffect looks the action up by `a.key === actionId`, and `resolveConnectorAction` returns `handlers[actionId]` for the node to dispatch; packages/services/service-automation/src/engine-extensions-facet.ts#getConnectorDescriptors publishes it; ui/packages/app-shell/src/views/metadata-admin/inspectors/FlowReferenceField.tsx (`connectorActionsToOptions`) and .../connector-input-fields.ts#connectorActionInputSchema both resolve an action by `a.key === actionKey`.", "producer": "packages/connectors/connector-mcp/src/mcp-connector.ts — `actions: selected.map((tool) => ({ key: tool.name, … }))` derives the action set from the upstream `tools/list`; packages/connectors/connector-openapi/src/openapi-connector.ts derives one action per OpenAPI operation. ⚠️ THE METADATA AUTHOR IS NOT A PRODUCER HERE: packages/spec/src/integration/connector.zod.ts#DeclarativeConnectorEntrySchema REFUSES `actions` on a provider-bound instance (ADR-0097 §5 — the provider derives them), and on a descriptor (no `provider`) the entry never reaches the registry at all.", "note": "Live on the PLUGIN/provider door, inert-and-audited on the authoring door — the two-door fact in the file note, at its sharpest. What an authored `actions[]` on a descriptor DOES do is trigger a boot warning: packages/services/service-automation/src/plugin.ts#findInertDeclaredConnectors returns every declared connector that has at least one action, no runtime registration and no `enabled: false` opt-out, and `auditDeclaredConnectors` warns once per boot naming them and the remedy. That warning is the #2612 contract made audible; it is not dispatch." }, @@ -80,7 +80,7 @@ "status": "live", "verifiedAt": "2026-09-17", "evidenceScope": "in-repo", - "evidence": "packages/services/service-automation/src/engine.ts#getConnectorDescriptors — `label: a.label` on each projected action; ui/packages/app-shell/src/views/metadata-admin/inspectors/FlowReferenceField.tsx (`connectorActionsToOptions`, fed by `useConnectorActionOptions` off `GET /api/v1/automation/connectors`) renders it as the action picker's option text in the flow designer.", + "evidence": "packages/services/service-automation/src/engine-extensions-facet.ts#getConnectorDescriptors — `label: a.label` on each projected action; ui/packages/app-shell/src/views/metadata-admin/inspectors/FlowReferenceField.tsx (`connectorActionsToOptions`, fed by `useConnectorActionOptions` off `GET /api/v1/automation/connectors`) renders it as the action picker's option text in the flow designer.", "producer": "packages/connectors/connector-mcp/src/mcp-connector.ts — `label: titleize(slugify(tool.name))`; packages/connectors/connector-openapi/src/openapi-connector.ts derives one per operation. Same two-door caveat as `actions.key`.", "note": "Display-shaped and settled by the #7131 split — the designer's action picker IS the claimed effect. REQUIRED, so there is no empty state." }, @@ -88,7 +88,7 @@ "status": "live", "verifiedAt": "2026-09-30", "evidenceScope": "in-repo", - "evidence": "packages/services/service-automation/src/engine.ts#getConnectorDescriptors — `description: a.description` on each projected action, the `GET /api/v1/automation/connectors` payload; ui/packages/app-shell/src/views/metadata-admin/inspectors/FlowReferenceField.tsx#connectorActionsToOptions (a non-blank string `description` becomes the action option's `hint`, fed by `useConnectorActionOptions` off that payload); ui/packages/app-shell/src/views/metadata-admin/inspectors/FlowReferenceField.tsx#ReferenceCombobox (draws each option as `label — hint` in the `connector_action` node's Action picker)", + "evidence": "packages/services/service-automation/src/engine-extensions-facet.ts#getConnectorDescriptors — `description: a.description` on each projected action, the `GET /api/v1/automation/connectors` payload; ui/packages/app-shell/src/views/metadata-admin/inspectors/FlowReferenceField.tsx#connectorActionsToOptions (a non-blank string `description` becomes the action option's `hint`, fed by `useConnectorActionOptions` off that payload); ui/packages/app-shell/src/views/metadata-admin/inspectors/FlowReferenceField.tsx#ReferenceCombobox (draws each option as `label — hint` in the `connector_action` node's Action picker)", "producer": "packages/connectors/connector-slack/src/slack-connector.ts#createSlackConnector — a `description` on each of its three actions; packages/connectors/connector-openapi/src/openapi-connector.ts#createOpenApiConnector — `description: op.description`; packages/connectors/connector-mcp/src/mcp-connector.ts#createMcpConnector — the server's tool description verbatim; ui/packages/app-shell/src/views/metadata-admin/inspectors/flow-node-config.ts#FLOW_NODE_CONFIG (the `connector_action` node's `actionId` field is a `connector-action` reference, which is what mounts that picker). Same two-door caveat as `actions.key`.", "note": "RE-GRADED dead → live 2026-09-30 (#20287): objectui#11028, read at the `.objectui-sha` pin db11afd4967, shows it beside the action's label in the flow designer's Action picker. Display-shaped, so the picker IS the claimed effect (the #7131 split), as for `actions.label`. The superseded note — no consumer in either repo reads it back — was true until objectui#11028." }, @@ -96,7 +96,7 @@ "status": "live", "verifiedAt": "2026-09-17", "evidenceScope": "in-repo", - "evidence": "packages/services/service-automation/src/engine.ts#getConnectorDescriptors — `inputSchema: a.inputSchema` on the projected action; ui/packages/app-shell/src/views/metadata-admin/inspectors/connector-input-fields.ts#connectorActionInputSchema finds the committed action in that payload and returns its `inputSchema`, and `FlowNodeInspector.tsx` types the connector node's whole Input section from it (`connectorInputFields(connectorActionInputSchema(...))`, objectui #4305) — an action that declares none falls back to the generic key/value repeater, which is the observable difference.", + "evidence": "packages/services/service-automation/src/engine-extensions-facet.ts#getConnectorDescriptors — `inputSchema: a.inputSchema` on the projected action; ui/packages/app-shell/src/views/metadata-admin/inspectors/connector-input-fields.ts#connectorActionInputSchema finds the committed action in that payload and returns its `inputSchema`, and `FlowNodeInspector.tsx` types the connector node's whole Input section from it (`connectorInputFields(connectorActionInputSchema(...))`, objectui #4305) — an action that declares none falls back to the generic key/value repeater, which is the observable difference.", "producer": "packages/connectors/connector-mcp/src/mcp-connector.ts — the MCP tool's own JSON Schema is passed straight through ('The MCP inputSchema is already JSON Schema'); packages/connectors/connector-openapi/src/openapi-connector.ts derives it from the operation's parameters. Same two-door caveat as `actions.key`.", "note": "A structural (not display) consumer, cross-repo like `outputSchema`'s: the designer builds a typed form from it. Declared `z.record(z.string(), z.unknown())` — JSON Schema by convention, unvalidated here — so it has no child shape and nothing rides on a blanket verdict." }, @@ -104,14 +104,14 @@ "status": "live", "verifiedAt": "2026-09-30", "evidenceScope": "in-repo", - "evidence": "packages/services/service-automation/src/engine.ts#getConnectorDescriptors — `outputSchema: a.outputSchema` on each projected action, the `GET /api/v1/automation/connectors` payload; ui/packages/app-shell/src/views/metadata-admin/inspectors/flow-scope.ts#nodeOutputRefs (a committed `connector_action` node offers one `nodeId.key` reference per top-level `properties` key of its action's `outputSchema`, through `connectorActionOutputSchema` and `connectorActionOutputKeys`; no schema, no references); ui/packages/app-shell/src/views/metadata-admin/inspectors/flow-scope.ts#resolveFlowScope (hands those references to every downstream node's and edge's data picker)", + "evidence": "packages/services/service-automation/src/engine-extensions-facet.ts#getConnectorDescriptors — `outputSchema: a.outputSchema` on each projected action, the `GET /api/v1/automation/connectors` payload; ui/packages/app-shell/src/views/metadata-admin/inspectors/flow-scope.ts#nodeOutputRefs (a committed `connector_action` node offers one `nodeId.key` reference per top-level `properties` key of its action's `outputSchema`, through `connectorActionOutputSchema` and `connectorActionOutputKeys`; no schema, no references); ui/packages/app-shell/src/views/metadata-admin/inspectors/flow-scope.ts#resolveFlowScope (hands those references to every downstream node's and edge's data picker)", "producer": "ui/packages/app-shell/src/views/metadata-admin/inspectors/connector-input-fields.ts#useConnectorRegistry (reads that payload); ui/packages/app-shell/src/views/metadata-admin/inspectors/FlowNodeInspector.tsx#FlowNodeInspector and ui/packages/app-shell/src/views/metadata-admin/inspectors/FlowEdgeInspector.tsx#FlowEdgeInspector (each reads the registry when the flow holds a committed connector action and passes it to `useFlowScope` — the input the read depends on); framework: packages/connectors/connector-slack/src/slack-connector.ts#createSlackConnector — `outputSchema: slackOutputSchema()` on every action; packages/connectors/connector-openapi/src/openapi-connector.ts#buildOutputSchema; packages/connectors/connector-mcp/src/mcp-connector.ts#createMcpConnector — the tool's `outputSchema` when the server declares one. Same two-door caveat as `actions.key`.", "note": "RE-GRADED dead → live 2026-09-30 (#20287): objectui#11028, read at the `.objectui-sha` pin db11afd4967, types a connector node's downstream references from it — the repair the superseded note named. The engine stores each top-level key of a node's `output` as `nodeId.key`, so the offered references are the ones a run writes. The designer offers them and stops flagging them as out of scope; nothing validates a reference against the schema." }, "effect": { "status": "live", "verifiedAt": "2026-09-17", - "evidence": "packages/services/service-automation/src/builtin/connector-nodes.ts — `const effect = engine.resolveConnectorActionEffect(cfg.connectorId, cfg.actionId)` is resolved BEFORE dispatch and decides what the run reports: `write` → `{ acted: 1 }`, `read` → `{ acted: 0 }`, undeclared → `{ unmeasuredEffect: true }`, so the declaration is what lets a connector-driven flow contribute a signal to the broken-sweep alert at all (#4395); packages/services/service-automation/src/engine.ts#resolveConnectorActionEffect reads it off the stored def (`.def.actions?.find((a) => a.key === actionId)?.effect`); packages/services/service-automation/src/engine.ts#getConnectorDescriptors also carries it to the designer.", + "evidence": "packages/services/service-automation/src/builtin/connector-nodes.ts — `const effect = engine.resolveConnectorActionEffect(cfg.connectorId, cfg.actionId)` is resolved BEFORE dispatch and decides what the run reports: `write` → `{ acted: 1 }`, `read` → `{ acted: 0 }`, undeclared → `{ unmeasuredEffect: true }`, so the declaration is what lets a connector-driven flow contribute a signal to the broken-sweep alert at all (#4395); packages/services/service-automation/src/engine.ts#resolveConnectorActionEffect reads it off the stored def (`.def.actions?.find((a) => a.key === actionId)?.effect`); packages/services/service-automation/src/engine-extensions-facet.ts#getConnectorDescriptors also carries it to the designer.", "producer": "packages/spec/src/integration/connector.zod.ts#ConnectorActionSchema names the producer itself: 'This is the ONLY producer of the effect' — whoever writes the def writes it, and both the hand-registered path and the ADR-0097 materialization path read it from there. Same two-door caveat as `actions.key`.", "note": "Optional on purpose: a connector written before the key keeps reporting `unmeasuredEffect`, so declaring it is a strict improvement rather than a migration. The empty state is therefore meaningful and benign, which is why it is not `authorWarn`ed." } diff --git a/packages/spec/liveness/flow.json b/packages/spec/liveness/flow.json index b7f31c04bf1..d8b36edc765 100644 --- a/packages/spec/liveness/flow.json +++ b/packages/spec/liveness/flow.json @@ -15,7 +15,7 @@ "errorMessage": { "status": "live", "verifiedAt": "2026-08-28", - "evidence": "packages/services/service-automation/src/engine.ts#retryExecution (carries the authored text onto the last attempt's failure); packages/services/service-automation/src/run-resume.ts#resumeInternal (`errorMessage: flow.errorMessage` on the resumed run's failure envelope)", + "evidence": "packages/services/service-automation/src/engine-run-facet.ts#retryExecution (carries the authored text onto the last attempt's failure); packages/services/service-automation/src/run-resume.ts#resumeInternal (`errorMessage: flow.errorMessage` on the resumed run's failure envelope)", "note": "2026-08-28: RE-ANCHORED (commit 8f10a79f7) and REPOINTED — `:1348` had rotted onto a docblock heading (\"⛔ This is NOT the retired `flowEnabled` map under a new name\"), ~2,480 lines above the readers. As with `successMessage`, the top-level `execute` path reads the same field and is left as prose for the same reason. Re-closed by hand against 8cb96ec41." }, "label": { @@ -172,16 +172,16 @@ "backoffMs": { "status": "live", "verifiedAt": "2026-08-04", - "evidence": "packages/services/service-automation/src/engine.ts", + "evidence": "packages/services/service-automation/src/engine-run-facet.ts", "note": "Was `retryDelayMs` until 17.0.0 (#4964). This block was a THIRD encoding of the retry policy #4661 converged, invisible to that pass because it is an anonymous inline block with no exported name — the dual-source instrument judges duplicated export NAMES. It now builds from `retryPolicyShape()`, so the base delay is spelled `backoffMs` here exactly as on `job.retryPolicy` and a `try_catch` node's `retry`; `retryDelayMs` is tombstoned and rewritten by `retry-policy-converged`. `retryExecution` destructures the parsed key." }, "backoffMultiplier": { "status": "live", - "evidence": "packages/services/service-automation/src/engine.ts" + "evidence": "packages/services/service-automation/src/engine-run-facet.ts" }, "maxRetryDelayMs": { "status": "live", - "evidence": "packages/services/service-automation/src/engine.ts" + "evidence": "packages/services/service-automation/src/engine-run-facet.ts" }, "jitter": { "status": "live", diff --git a/scripts/check-facade-delegation-only.mjs b/scripts/check-facade-delegation-only.mjs index 91dc5553869..c71bb282a0b 100644 --- a/scripts/check-facade-delegation-only.mjs +++ b/scripts/check-facade-delegation-only.mjs @@ -228,6 +228,7 @@ const DECLARED_WATCH_HINTS = [ 'packages/drivers/driver-sql/src/sql-driver.ts', 'packages/objectql/src/registry.ts', 'packages/services/service-knowledge/src/knowledge-service.ts', + 'packages/services/service-automation/src/engine.ts', ]; const CARD_REF = /^#[1-9][0-9]*$/; diff --git a/scripts/facade-delegation-registry.json b/scripts/facade-delegation-registry.json index b95f7a70b2e..9e5a678d705 100644 --- a/scripts/facade-delegation-registry.json +++ b/scripts/facade-delegation-registry.json @@ -34,6 +34,11 @@ "file": "packages/services/service-knowledge/src/knowledge-service.ts", "class": "KnowledgeService", "card": "#38660" + }, + { + "file": "packages/services/service-automation/src/engine.ts", + "class": "AutomationEngine", + "card": "#38667" } ], "exceptions": [ @@ -177,6 +182,55 @@ "member": "knowledgeTools", "card": "#38660", "reason": "bare-this: its body hands the service itself to `createKnowledgeTools(this)`, so the tool executor calls the service; a facet body is handed the host, not the service, so moving it would hand the executor the host" + }, + { + "file": "packages/services/service-automation/src/engine.ts", + "class": "AutomationEngine", + "member": "constructor", + "card": "#38667", + "reason": "state-owning: the constructor writes the engine's own fields from its arguments (the logger, the run store wrapped slot-keyed, the execution-log bound, the run-summary log level, the scheduled-work policy and the credential resolver); the facade keeps the fields and the constructor" + }, + { + "file": "packages/services/service-automation/src/engine.ts", + "class": "AutomationEngine", + "member": "flowSlots", + "card": "#38667", + "reason": "state-owning: a field whose initializer builds the engine's slot table and hands it two arrow predicates over the engine's flow holders; it runs while the instance is constructed, so there is no stub to forward from" + }, + { + "file": "packages/services/service-automation/src/engine.ts", + "class": "AutomationEngine", + "member": "flowLedgerDisabled", + "card": "#38667", + "reason": "state-owning: a field whose initializer builds the activation projection with arrow readers over the engine's own state; it runs while the instance is constructed, so there is no stub to forward from" + }, + { + "file": "packages/services/service-automation/src/engine.ts", + "class": "AutomationEngine", + "member": "flowCallKey", + "card": "#38667", + "reason": "state-owning: a field holding the arrow the subflow guards are handed as the caller-to-flow key function; its identity is the field's value, so it stays a field" + }, + { + "file": "packages/services/service-automation/src/engine.ts", + "class": "AutomationEngine", + "member": "resolveCanonicalDescriptor", + "card": "#38667", + "reason": "private static: the body reads `AutomationEngine.MAX_ALIAS_HOPS`, a private static of the class, which a facet module outside the class cannot read" + }, + { + "file": "packages/services/service-automation/src/engine.ts", + "class": "AutomationEngine", + "member": "resolveResumeAuthority", + "card": "#38667", + "reason": "private static: the body reads `AutomationEngine.RESUME_AUTHORITY_WHEN_UNDECLARED`, a private static of the class, which a facet module outside the class cannot read" + }, + { + "file": "packages/services/service-automation/src/engine.ts", + "class": "AutomationEngine", + "member": "walkSuspensionChain", + "card": "#38667", + "reason": "private static: the body reads `AutomationEngine.MAX_SUSPENSION_CHAIN_DEPTH` and `AutomationEngine.LINKED_RUN_PREFIXES`, private statics of the class, which a facet module outside the class cannot read" } ], "ceilings": [ @@ -214,6 +268,13 @@ "baseCommit": "4c4a984345", "maxLines": 1758, "ruling": "6897467376" + }, + { + "file": "packages/services/service-automation/src/engine.ts", + "baseLines": 7735, + "baseCommit": "53e745f98a", + "maxLines": 7835, + "ruling": "6897467376" } ] } diff --git a/scripts/tenant-audit-census.mjs b/scripts/tenant-audit-census.mjs index b9356f90f95..5fb0533bb66 100644 --- a/scripts/tenant-audit-census.mjs +++ b/scripts/tenant-audit-census.mjs @@ -1763,6 +1763,90 @@ export const UNTYPED_RECEIVERS = [ engine: false, what: 'a knowledge search-index adapter (`this.adapterFor(source)`, read through the facet host) -- `delete([docId], context)` de-indexes documents', }, + { + file: 'packages/services/service-automation/src/engine-enablement-facet.ts', + receiver: 'this.subflowDeclinedFlows', + engine: false, + what: 'the automation engine\'s own in-memory `Map` field `subflowDeclinedFlows` (`AutomationEngine[\'subflowDeclinedFlows\']`, read through the facet host) -- `delete(key)` drops an entry from it', + }, + { + file: 'packages/services/service-automation/src/engine-enablement-facet.ts', + receiver: 'this.subflowNoticeDeclinedFlows', + engine: false, + what: 'the automation engine\'s own in-memory `Map` field `subflowNoticeDeclinedFlows` (`AutomationEngine[\'subflowNoticeDeclinedFlows\']`, read through the facet host) -- `delete(key)` drops an entry from it', + }, + { + file: 'packages/services/service-automation/src/engine-enablement-facet.ts', + receiver: 'this.subflowRegionDeclinedFlows', + engine: false, + what: 'the automation engine\'s own in-memory `Map` field `subflowRegionDeclinedFlows` (`AutomationEngine[\'subflowRegionDeclinedFlows\']`, read through the facet host) -- `delete(key)` drops an entry from it', + }, + { + file: 'packages/services/service-automation/src/engine-enablement-facet.ts', + receiver: 'this.subflowRetryDeclinedFlows', + engine: false, + what: 'the automation engine\'s own in-memory `Map` field `subflowRetryDeclinedFlows` (`AutomationEngine[\'subflowRetryDeclinedFlows\']`, read through the facet host) -- `delete(key)` drops an entry from it', + }, + { + file: 'packages/services/service-automation/src/engine-extensions-facet.ts', + receiver: 'this.boundFlowTriggers', + engine: false, + what: 'the automation engine\'s own in-memory `Map` field `boundFlowTriggers` (`AutomationEngine[\'boundFlowTriggers\']`, read through the facet host) -- `delete(key)` drops an entry from it', + }, + { + file: 'packages/services/service-automation/src/engine-extensions-facet.ts', + receiver: 'this.credentialHandleProviders', + engine: false, + what: 'the automation engine\'s own in-memory `Set` field `credentialHandleProviders` (`AutomationEngine[\'credentialHandleProviders\']`, read through the facet host) -- `delete(key)` drops an entry from it', + }, + { + file: 'packages/services/service-automation/src/engine-extensions-facet.ts', + receiver: 'this.disabledHolderDispatchSaid', + engine: false, + what: 'the automation engine\'s own in-memory `Set` field `disabledHolderDispatchSaid` (`AutomationEngine[\'disabledHolderDispatchSaid\']`, read through the facet host) -- `delete(key)` drops an entry from it', + }, + { + file: 'packages/services/service-automation/src/engine-extensions-facet.ts', + receiver: 'this.policyDisabledFlows', + engine: false, + what: 'the automation engine\'s own in-memory `Map` field `policyDisabledFlows` (`AutomationEngine[\'policyDisabledFlows\']`, read through the facet host) -- `delete(key)` drops an entry from it', + }, + { + file: 'packages/services/service-automation/src/engine-flow-slots-facet.ts', + receiver: 'this.movedFlowKeys', + engine: false, + what: 'the automation engine\'s own in-memory `Map` field `movedFlowKeys` (`AutomationEngine[\'movedFlowKeys\']`, read through the facet host) -- `delete(key)` drops an entry from it', + }, + { + file: 'packages/services/service-automation/src/engine-flow-slots-facet.ts', + receiver: 'this.pendingFlowActivationBinds', + engine: false, + what: 'the automation engine\'s own in-memory `Set>` field `pendingFlowActivationBinds` (`AutomationEngine[\'pendingFlowActivationBinds\']`, read through the facet host) -- `delete(key)` drops an entry from it', + }, + { + file: 'packages/services/service-automation/src/engine-flow-slots-facet.ts', + receiver: 'this.sharedSlotTriggerWarned', + engine: false, + what: 'the automation engine\'s own in-memory `Set` field `sharedSlotTriggerWarned` (`AutomationEngine[\'sharedSlotTriggerWarned\']`, read through the facet host) -- `delete(key)` drops an entry from it', + }, + { + file: 'packages/services/service-automation/src/engine-registration-facet.ts', + receiver: 'this.flowRefusals', + engine: false, + what: 'the automation engine\'s own in-memory `Map` field `flowRefusals` (`AutomationEngine[\'flowRefusals\']`, read through the facet host) -- `delete(key)` drops an entry from it', + }, + { + file: 'packages/services/service-automation/src/engine-resume-facet.ts', + receiver: 'this.subflowParentStrands', + engine: false, + what: 'the automation engine\'s own in-memory `Map` field `subflowParentStrands` (`AutomationEngine[\'subflowParentStrands\']`, read through the facet host) -- `delete(key)` drops an entry from it', + }, + { + file: 'packages/services/service-automation/src/engine-run-facet.ts', + receiver: 'this.activeRecordFlows', + engine: false, + what: 'the automation engine\'s own in-memory `Set` field `activeRecordFlows` (`AutomationEngine[\'activeRecordFlows\']`, read through the facet host) -- `delete(key)` drops an entry from it', + }, { file: 'packages/services/service-messaging/src/memory-http-outbox.ts', receiver: 'this',