diff --git a/.changeset/31677-connector-action-package-scoped.md b/.changeset/31677-connector-action-package-scoped.md new file mode 100644 index 00000000000..8d57799acb8 --- /dev/null +++ b/.changeset/31677-connector-action-package-scoped.md @@ -0,0 +1,14 @@ +--- +'@objectstack/service-automation': patch +--- + +feat: a `connector_action` names its connector from the calling flow's package (ADR-0150 D3/D4) + +Clause-②: no +Metadata-protocol: none + +A flow's `connectorConfig.connectorId` is now resolved through `resolvePackageScopedName` from `@objectstack/objectql`, as the package that ships the flow: its own declared connector instance, else the one holder in its declared dependency closure, else a refusal naming every candidate. An environment-authored flow names it with no package, as before. + +Who is affected: a packaged flow whose `connector_action` names a declared connector instance its package can't reach: one held only by a package outside its declared dependencies, one only the environment authored (ADR-0150 D3 (a)), or one two packages in its closure both declare. That node was dispatched to whatever instance the engine held under the name; it is now refused, and the error names every candidate. Declare the dependency, or ship the instance in the flow's own package. First-party count: 0. Every first-party packaged flow names its own package's instance or a connector a plugin registers in code, which is no registry item and dispatches as before. + +Corrected beside it: which package a flow run names its references from. It is the package only while that package's OWN body is armed under the flow's name (`AutomationEngine.armedFlowPackage`; the engine records where each armed body came from at every `registerFlow`). An environment override of a packaged flow, whether a package-less stored row or the shipping package's declared `.custom` override, names its `connector_action` connector and its `subflow`/`map` flow with no package, as ADR-0150 D3 says an overlay's references do. Before this, E1's subflow reader read the package that ships the flow name, so an override's subflow name resolved from that package; it now resolves as it did on main before E1. That is a loosening back to the earlier answer, not a new narrowing. diff --git a/packages/services/service-automation/src/builtin/connector-nodes.ts b/packages/services/service-automation/src/builtin/connector-nodes.ts index fa94d26e2e2..90f5f32a74b 100644 --- a/packages/services/service-automation/src/builtin/connector-nodes.ts +++ b/packages/services/service-automation/src/builtin/connector-nodes.ts @@ -62,6 +62,15 @@ export function registerConnectorNodes(engine: AutomationEngine, ctx: PluginCont ); } + // [ADR-0150 D3, epic #31527 child E5] A packaged flow names its + // connector from its package: refused (every candidate named) when + // the name does not resolve for that package — never dispatched on + // a guess. + const nameRefusal = engine.connectorNameRefusal(cfg.connectorId, context); + if (nameRefusal) { + return refuseNode(`connector_action '${node.id}': ${nameRefusal.message}`); + } + const handler = engine.resolveConnectorAction(cfg.connectorId, cfg.actionId); if (!handler) { // A degraded declarative instance (#3017) is registered but has no diff --git a/packages/services/service-automation/src/connector-package-scope.ts b/packages/services/service-automation/src/connector-package-scope.ts index d0425f2d56b..a6b537e4538 100644 --- a/packages/services/service-automation/src/connector-package-scope.ts +++ b/packages/services/service-automation/src/connector-package-scope.ts @@ -29,6 +29,7 @@ import { resolvePackageScopedName, type PackageScopedRefusal, type PackageScopedRegistry, + type PackageScopedResolution, } from '@objectstack/objectql'; /** The registry, when it carries the slice the package-scoped resolver reads. */ @@ -59,3 +60,29 @@ export function refusedConnectorNames( } return refused; } + +/** + * [ADR-0150 D3] The engine's reader over the one package-scoped resolver for + * the `connector` type (`AutomationEngine.setConnectorNameResolver`): which + * declared connector instance a bare `connectorConfig.connectorId` means for a + * caller of package `callerPackageId` (`null`: no package). + * + * Resolved at QUESTION time, never at boot, like the flow reader. A + * composition with no ObjectQL, or whose registry offers none of the + * package-scoped reads, has no registry to ask: the answer is `undefined` and + * `connector_action` dispatches by name as before. + */ +export function connectorNameResolver( + ctx: { getService(name: string): T }, +): (name: string, callerPackageId: string | null) => PackageScopedResolution | undefined { + return (name, callerPackageId) => { + let registry: PackageScopedRegistry | undefined; + try { + registry = packageScopedRegistryOf(ctx.getService<{ registry?: unknown }>('objectql')?.registry); + } catch { + return undefined; + } + if (!registry) return undefined; + return resolvePackageScopedName(registry, { type: 'connector', name, callerPackageId }); + }; +} diff --git a/packages/services/service-automation/src/engine.ts b/packages/services/service-automation/src/engine.ts index d08f5a5ae89..c05fef7ce09 100644 --- a/packages/services/service-automation/src/engine.ts +++ b/packages/services/service-automation/src/engine.ts @@ -2583,6 +2583,17 @@ export type PackagedFlowSource = (name: string) => string | undefined; */ export type FlowNameResolver = (name: string, callerPackageId: string | null) => PackageScopedResolution | undefined; +/** + * [ADR-0150 D3, epic #31527 child E5] The same reader for the `connector` type: + * which declared connector instance the bare name `name` means for a caller of + * package `callerPackageId` (`null` for a caller with no package). The + * automation plugin attaches `resolvePackageScopedName` over the ObjectQL + * registry ({@link AutomationEngine.setConnectorNameResolver}); `undefined` + * means the host serves no registry to ask. ⛔ Never a second implementation + * of the rule. + */ +export type ConnectorNameResolver = (name: string, callerPackageId: string | null) => PackageScopedResolution | undefined; + /** * [#28405] The stored body of flow `name` whose content identity is * `checksum` ({@link SuspendedRun.flowChecksum}), as the metadata history @@ -2823,6 +2834,19 @@ export class AutomationEngine implements IAutomationService { * knows, as before. */ private flowNameResolver?: FlowNameResolver; + /** + * [ADR-0150 D3, epic #31527 child E5] Where each armed body came from, keyed + * by the parsed body {@link registerFlow} stores — so {@link armedFlowPackage} + * reads the arm of exactly what `flows` holds under a name, and a withdrawn + * or replaced body takes its arm with it. Written at EVERY registration: + * the caller's classification when it hands one, else `runtime`. + */ + private readonly flowArms = new WeakMap(); + /** + * [ADR-0150 D3] The reader that answers which declared connector instance a + * bare name means for a caller — see {@link setConnectorNameResolver}. + */ + private connectorNameResolver?: ConnectorNameResolver; /** [#20790] The write-only flow credential channel — see {@link setFlowCredentialSource}. */ private flowCredentialSource?: FlowCredentialSource; /** [#20281 stage ③] The connector sync executor — see {@link setConnectorPullSource}. */ @@ -4556,7 +4580,21 @@ export class AutomationEngine implements IAutomationService { return canonicalizeFlow.call(host, name, definition, options); } - registerFlow(name: string, definition: unknown): FlowParsed { + /** + * @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. + */ + registerFlow(name: string, definition: unknown, armedFrom?: FlowContender): FlowParsed { + const arm: FlowContender = armedFrom + ?? (definition !== null && typeof definition === 'object' ? this.flowArms.get(definition) : undefined) + ?? { source: 'runtime' }; // 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). @@ -4601,6 +4639,7 @@ export class AutomationEngine implements IAutomationService { // 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(name, parsed); // [#23316] Held now, so no longer refused — see {@link flowRefusals}. this.flowRefusals.delete(name); @@ -5021,19 +5060,83 @@ export class AutomationEngine implements IAutomationService { return resolution?.status === 'refused' ? resolution : undefined; } + /** + * [ADR-0150 D3, epic #31527 child E5] Attach the reader that answers which + * declared connector instance a bare `connectorConfig.connectorId` means for + * the flow that names it ({@link connectorNameRefusal}). The automation + * plugin calls this at `init()`; with none attached, `connector_action` + * dispatches by name as before. + */ + setConnectorNameResolver(resolver: ConnectorNameResolver | undefined): void { + this.connectorNameResolver = resolver; + } + + /** + * [ADR-0150 D3, epic #31527 child E5] Why a `connector_action` in a run of + * `context`'s flow may not dispatch to the connector instance named + * `connectorId`, or `undefined` when it may. + * + * The name is resolved for the package that ships the calling flow + * ({@link flowCallerPackage}: a packaged flow names it from its package; an + * environment-authored flow, or a call outside a run, names it with no + * package). The engine holds ONE instance per name, materialized for the + * answer a caller with no package gets (the declared-connector reconcile, + * which already refuses a name two packages hold). So a package caller + * whose answer is a refusal — two holders in its closure, or holders only + * outside it, an environment-only instance included (ADR-0150 D3 (a)) — is + * refused with the resolver's own message, naming every candidate. Any + * other answer is the instance the engine serves: an environment item + * exists only for a name no package holds, so a package caller that + * resolves at all resolves to the one package holder the reconcile + * materialized. A name the registry holds nothing under (a connector a + * plugin registers in code), or a host with no resolver, dispatches by name + * as before. Read-only. + */ + connectorNameRefusal(connectorId: string, context: AutomationContext | undefined): PackageScopedRefusal | undefined { + const callerPackageId = this.flowCallerPackage(context); + if (callerPackageId === null) return undefined; + const meant = this.connectorNameResolver?.(connectorId, callerPackageId); + return meant?.status === 'refused' ? meant : undefined; + } + /** * [ADR-0150 D3] The package a call of {@link execute} comes from: the * package that ships the flow whose run made the call — `context.flowName`, * which the engine stamps on every run's context * (`resolveRunContext`), so a `subflow` or `map` child carries its parent's - * name — or `null` for a caller outside a run, and for a run of a flow no - * package ships (an environment-authored flow resolves as a caller with no - * package, ADR-0150 D3). + * name — or `null` for a caller outside a run, and for a run whose armed + * body is not the package's own ({@link armedFlowPackage}): an + * environment-authored flow, or an environment override of a packaged + * flow, resolves as a caller with no package (ADR-0150 D3). */ private flowCallerPackage(context: AutomationContext | undefined): string | null { const caller = context?.flowName; if (typeof caller !== 'string' || caller === '') return null; - return this.packagedFlowOwner(caller) ?? null; + return this.armedFlowPackage(caller) ?? null; + } + + /** + * [ADR-0150 D3, epic #31527 child E5] The package whose OWN body is armed + * under the flow name `name`: the loader's package + * ({@link packagedFlowOwner}) when the registration the engine holds was + * armed from the loader's body (`package`, {@link registerFlow}'s + * `armedFrom`), else `undefined` — for the shipping package's declared + * `.custom` override, for an environment-authored (`runtime`) body, and + * for a name the engine does not hold. + * + * This is the package a reference written in the armed body resolves + * from. ADR-0150 D3: "A reference written in an environment-authored + * overlay (ADR-0005) is the environment's reference. It resolves as a + * caller with no package … It never resolves from the package the overlay + * customizes." So the loader's set alone (which answers by bare name, for + * whichever body is armed) is never this answer, and neither is a stamp + * on the body: the boot hydration and the protocol's served override + * 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); } /** diff --git a/packages/services/service-automation/src/flow-declared-override-first-boot-pull.integration.test.ts b/packages/services/service-automation/src/flow-declared-override-first-boot-pull.integration.test.ts index 9f006fb21f9..2c432307237 100644 --- a/packages/services/service-automation/src/flow-declared-override-first-boot-pull.integration.test.ts +++ b/packages/services/service-automation/src/flow-declared-override-first-boot-pull.integration.test.ts @@ -296,6 +296,46 @@ describe('[#28717] a declared .custom flow override is armed from the first boot }); }); +/** + * [ADR-0150 D3, epic #31527 child E5] Which package a reference written in the + * armed body resolves from (`AutomationEngine.armedFlowPackage`, the caller + * package of a `subflow` / `map` name and of a `connector_action`'s + * `connectorId`). The loader's package only while the loader's OWN body is + * armed; the shipping package's declared `.custom` override is an + * environment-authored overlay, whose references resolve with no package + * (ADR-0150 D3: "It never resolves from the package the overlay customizes"). + * + * Read on the real composition at both arming steps: the boot pull arms from + * the registry's list (the override as a stored row, with its binding), and + * `kernel:ready` re-arms from the protocol's view (the override served in the + * base's slot, stamped with the base's `_packageId`), so a stamp-reading + * answer would read the base at one step or the other. + */ +describe('[ADR-0150 D3, #31677] the armed body\'s package is the loader\'s only while the loader\'s own body is armed', () => { + const CASES: ReadonlyArray = [ + ['the loader\'s body alone', [], BASE], + ['a package-less stored row beside it (shadowed, the loader\'s body armed)', ['legacy'], BASE], + ['the declared .custom override', ['override'], undefined], + ['the declared override and a package-less row', ['override', 'legacy'], undefined], + ]; + for (const [shape, rows, expected] of CASES) { + it(`${shape}: ${expected ?? 'no package'} at the boot pull and after kernel:ready`, async () => { + let atPull: { label?: string; pkg?: string } = {}; + const { automation } = await measuredBoot(rows, async (_ql, engine) => { + atPull = { + label: ((await engine.getFlow(FLOW)) as { label?: string } | null)?.label, + pkg: engine.armedFlowPackage(FLOW), + }; + }); + const armedLabel = expected === undefined ? 'OVERRIDE' : 'BASE'; + expect(automation.packagedFlowOwner(FLOW), 'control: the loader\'s set holds the name').toBe(BASE); + expect(atPull).toEqual({ label: armedLabel, pkg: expected }); + expect(((await automation.getFlow(FLOW)) as { label?: string } | null)?.label).toBe(armedLabel); + expect(automation.armedFlowPackage(FLOW)).toBe(expected); + }); + } +}); + /** * [#31754, ADR-0150 D3] The collision line agrees with the engine on a real * cold boot. A second package shipping FLOW's bare name (a clash sealed before diff --git a/packages/services/service-automation/src/flow-package-scoped-resolution.test.ts b/packages/services/service-automation/src/flow-package-scoped-resolution.test.ts index 8a20f82e929..6c64f4ceb34 100644 --- a/packages/services/service-automation/src/flow-package-scoped-resolution.test.ts +++ b/packages/services/service-automation/src/flow-package-scoped-resolution.test.ts @@ -21,7 +21,9 @@ import { SchemaRegistry } from '@objectstack/objectql'; import { AutomationEngine } from './engine.js'; import type { NodeExecutor } from './engine.js'; import { installBuiltinNodes } from './builtin/index.js'; -import { flowNameResolver } from './plugin.js'; +import { LiteKernel } from '@objectstack/core'; +import { AutomationServicePlugin, flowNameResolver } from './plugin.js'; +import { connectorNameResolver } from './connector-package-scope.js'; import { InMemoryFlowActivationStore } from './flow-activation-store.js'; import { FlowActivationProjection } from './flow-activation-projection.js'; import { resolveFlowPrecedence } from './flow-precedence.js'; @@ -94,11 +96,15 @@ let ran: string[]; const install = (id: string, deps: string[] = []) => registry.installPackage(manifest(id, deps), 'code'); -/** Package `packageId` ships flow `body`: in its registry slot, the loader's set and the engine. */ +/** + * Package `packageId` ships flow `body`: in its registry slot, the loader's set + * and the engine — armed from the loader's own body, as the automation + * plugin's arming steps record it (`registerFlow`'s `armedFrom`). + */ function ship(packageId: string, body: { name: string }) { registry.registerItem('flow', { ...body, _packageId: packageId }, 'name' as never, packageId); loaderSet[body.name] = packageId; - engine.registerFlow(body.name, body); + engine.registerFlow(body.name, body, { source: 'package', packageId }); } /** The environment authored flow `body`: a package-less row in the bare slot, and the engine. */ @@ -495,3 +501,267 @@ describe('[#31754] the collision line for a name two packages hold says neither ); }); }); + +// ── [epic #31527 child E5] connector_action names its connector from the flow's package ── + +/** A declared connector instance `name` in the registry: package `packageId`'s, or the environment's. */ +function declareConnector(name: string, packageId?: string) { + const item = { name, label: name, type: 'api', authentication: { type: 'none' }, actions: [{ key: 'ping', label: 'Ping' }] }; + if (packageId) registry.registerItem('connector', { ...item, _packageId: packageId }, 'name' as never, packageId); + else registry.registerItem('connector', { ...item, _provenance: 'org' }, 'name' as never); +} + +/** The engine's one live instance under `name`; `pings` records each dispatch to it. */ +let pings: string[]; +function liveConnector(name: string) { + engine.registerConnector( + { name, label: name, type: 'api', authentication: { type: 'none' }, actions: [{ key: 'ping', label: 'Ping' }] } as never, + { ping: async () => { pings.push(name); return { ok: true }; } }, + ); +} + +/** start → connector_action(connectorId.ping) → end. */ +function dispatcher(name: string, connectorId: string) { + return { + name, + label: name, + type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start', config: {} }, + { id: 'call', type: 'connector_action', label: 'Ping', connectorConfig: { connectorId, actionId: 'ping', input: {} } }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'call' }, + { id: 'e2', source: 'call', target: 'end' }, + ], + }; +} + +describe('ADR-0150 D3 — a connector_action names its connector from the calling flow\'s package (epic #31527 child E5)', () => { + beforeEach(() => { + pings = []; + const ctx = { getService(name: string) { if (name === 'objectql') return { registry }; throw new Error(`no ${name}`); } }; + engine.setConnectorNameResolver(connectorNameResolver(ctx as never)); + }); + + it("dispatches to the caller package's own instance, as before", async () => { + install(P); + declareConnector('billing', P); + liveConnector('billing'); + ship(P, dispatcher('charge', 'billing')); + const result = await engine.execute('charge'); + expect(result.success, String(result.error)).toBe(true); + expect(pings).toEqual(['billing']); + }); + + it('dispatches to the one holder in its declared dependency closure', async () => { + install(A); + install(P, [A]); + declareConnector('billing', A); + liveConnector('billing'); + ship(P, dispatcher('charge', 'billing')); + const result = await engine.execute('charge'); + expect(result.success, String(result.error)).toBe(true); + expect(pings).toEqual(['billing']); + }); + + it('an environment-authored flow dispatches to the one package holder (a caller with no package)', async () => { + install(A); + declareConnector('billing', A); + liveConnector('billing'); + author(dispatcher('my_charge', 'billing')); + const result = await engine.execute('my_charge'); + expect(result.success, String(result.error)).toBe(true); + expect(pings).toEqual(['billing']); + }); + + it('a connector a plugin registers in code is no registry item, and still dispatches', async () => { + install(P); + liveConnector('slack'); + ship(P, dispatcher('notify', 'slack')); + const result = await engine.execute('notify'); + expect(result.success, String(result.error)).toBe(true); + expect(pings).toEqual(['slack']); + }); + + it('red line 1 — a packaged flow is never served an instance held only outside its closure: refused naming the holder, nothing dispatched', async () => { + install(Q); + install(P); + declareConnector('billing', Q); + liveConnector('billing'); + ship(P, dispatcher('charge', 'billing')); + const result = await engine.execute('charge'); + expect(result.success).toBe(false); + expect(String(result.error)).toContain("connector_action 'call'"); + expect(String(result.error)).toContain(Q); + expect(pings).toEqual([]); + }); + + it('ADR-0150 D3 (a) — a packaged flow never resolves to an environment-only instance: refused, nothing dispatched', async () => { + install(P); + declareConnector('billing'); + liveConnector('billing'); + ship(P, dispatcher('charge', 'billing')); + const result = await engine.execute('charge'); + expect(result.success).toBe(false); + expect(String(result.error)).toContain("connector_action 'call'"); + expect(String(result.error)).toContain('environment'); + expect(pings).toEqual([]); + }); + + it('red line 2 — two holders in its closure: refused naming both, never the first listed', async () => { + install(A); + install(Q); + install(P, [A, Q]); + declareConnector('billing', A); + declareConnector('billing', Q); + liveConnector('billing'); + ship(P, dispatcher('charge', 'billing')); + const result = await engine.execute('charge'); + expect(result.success).toBe(false); + expect(String(result.error)).toContain(A); + expect(String(result.error)).toContain(Q); + expect(pings).toEqual([]); + }); + + it('the automation plugin attaches the resolver at init: a booted engine refuses the outside-closure name for the flow\'s package', async () => { + install(Q); + install(P); + declareConnector('billing', Q); + const kernel = new LiteKernel({ logger: { level: 'silent' } } as never); + kernel.use(new AutomationServicePlugin()); + kernel.use({ + name: 'test.harness', + type: 'standard' as const, + version: '1.0.0', + dependencies: ['com.objectstack.service-automation'], + async init(ctx: any) { + ctx.registerService('objectql', { registry }); + // The protocol's loader set: package P ships flow `charge`. + ctx.registerService('protocol', { + packagedArtifactOwner: ({ type, name }: { type: string; name: string }) => + type === 'flow' && name === 'charge' ? P : undefined, + }); + }, + async start() {}, + } as never); + await kernel.bootstrap(); + try { + const booted = kernel.getService('automation') as AutomationEngine; + // P's own body of `charge`, armed as the plugin's arming steps arm it. + booted.registerFlow('charge', dispatcher('charge', 'billing'), { source: 'package', packageId: P }); + const refusal = booted.connectorNameRefusal('billing', { flowName: 'charge' } as never); + expect(refusal?.status).toBe('refused'); + expect(refusal?.message).toContain(Q); + // An environment-authored flow (no package) is not refused here. + expect(booted.connectorNameRefusal('billing', { flowName: 'my_charge' } as never)).toBeUndefined(); + } finally { + await kernel.shutdown(); + } + }); +}); + +// ── [epic #31527 child E5, epic review R1] the armed body decides the caller package ── + +/** + * ADR-0150 D3, the paragraph after (a)–(d): "A reference written in an + * environment-authored overlay (ADR-0005) is the environment's reference. It + * resolves as a caller with no package … It never resolves from the package + * the overlay customizes." So a run of P's flow NAME whose armed body is an + * environment override names its `connectorId` and its `subflow` with no + * package — as on main before E1 — while P's own body still names them from P. + * + * Each body is armed the way the automation plugin arms it: classified by + * `resolveFlowPrecedence` (the winner's `contender`) and handed to + * `registerFlow` as `armedFrom`. Three override shapes: a package-less stored + * row, the `.custom` pair's declared override as the boot pull's registry list + * carries it (its stored binding), and the same override as the protocol's + * view serves it at `kernel:ready` (no binding; the base's `_packageId`). + */ +describe('ADR-0150 D3 — an environment override of a packaged flow names its references with no package (epic #31527 child E5, R1)', () => { + const PAIR = `${P}.custom`; + const declared = { overrides: { package: P, basedOn: '1.0.0' } }; + const SHAPES: ReadonlyArray unknown]> = [ + ['a package-less environment row', (body) => bindStoredRow({ ...body, _provenance: 'org' }, null)], + ['the .custom declared override (stored row, boot pull)', (body) => bindStoredRow({ ...body, ...declared, _provenance: 'org' }, PAIR)], + [ + 'the .custom declared override (served envelope, kernel:ready)', + (body) => ({ ...body, ...declared, _packageId: P, _packageVersion: '1.0.0', _provenance: 'package' }), + ], + ]; + /** P's own body, as the loader ships it. */ + const loaderBody = (body: { name: string }) => ({ ...body, _packageId: P, _packageVersion: '1.0.0', _provenance: 'package' }); + + /** P ships `body`'s name; the engine arms `armed` for it the way the plugin does. */ + function armOverName(body: { name: string }, armed: unknown) { + install(P); + registry.registerItem('flow', { ...body, _packageId: P }, 'name' as never, P); + loaderSet[body.name] = P; + const [winner] = resolveFlowPrecedence([armed], undefined, (name) => engine.packagedFlowOwner(name), installedManifestsOf(registry)); + engine.registerFlow(winner.name, winner.definition as never, winner.contender); + return winner.contender; + } + + beforeEach(() => { + pings = []; + const ctx = { getService(name: string) { if (name === 'objectql') return { registry }; throw new Error(`no ${name}`); } }; + engine.setConnectorNameResolver(connectorNameResolver(ctx as never)); + }); + + for (const [shape, overlay] of SHAPES) { + it(`connectorId — ${shape}: an environment-only instance is reached, as a caller with no package`, async () => { + declareConnector('billing'); + liveConnector('billing'); + const arm = armOverName(dispatcher('charge', 'billing'), overlay(dispatcher('charge', 'billing'))); + expect(arm.source).not.toBe('package'); + expect(engine.armedFlowPackage('charge')).toBeUndefined(); + const result = await engine.execute('charge'); + expect(result.success, String(result.error)).toBe(true); + expect(pings).toEqual(['billing']); + }); + + it(`subflow — ${shape}: an environment-only flow is reached, as a caller with no package`, async () => { + author(leaf('welcome')); + armOverName(caller('process', 'welcome'), overlay(caller('process', 'welcome'))); + expect(engine.armedFlowPackage('process')).toBeUndefined(); + const result = await engine.execute('process'); + expect(result.success, String(result.error)).toBe(true); + expect(ran).toEqual(['welcome']); + }); + } + + it("CONTROL: P's own body (a package arm) still names its connectorId from P — the environment-only instance is refused", async () => { + declareConnector('billing'); + liveConnector('billing'); + const arm = armOverName(dispatcher('charge', 'billing'), loaderBody(dispatcher('charge', 'billing'))); + expect(arm).toEqual({ source: 'package', packageId: P }); + expect(engine.armedFlowPackage('charge')).toBe(P); + const result = await engine.execute('charge'); + expect(result.success).toBe(false); + expect(String(result.error)).toContain('environment'); + expect(pings).toEqual([]); + }); + + it("CONTROL: P's own body (a package arm) still names its subflow from P — the environment-only flow is refused", async () => { + author(leaf('welcome')); + armOverName(caller('process', 'welcome'), loaderBody(caller('process', 'welcome'))); + expect(engine.armedFlowPackage('process')).toBe(P); + const result = await engine.execute('process'); + expect(result.success).toBe(false); + expect(result.error).toContain('the environment (an item authored in this environment, bound to no package)'); + expect(ran).toEqual([]); + }); + + it('a write door\'s body (no arm handed) is the environment\'s; the body the engine held keeps its arm when put back', async () => { + install(P); + ship(P, leaf('notify')); + expect(engine.armedFlowPackage('notify')).toBe(P); + const held = await engine.getFlow('notify'); + engine.registerFlow('notify', leaf('notify')); + expect(engine.armedFlowPackage('notify')).toBeUndefined(); + engine.registerFlow('notify', held); + expect(engine.armedFlowPackage('notify')).toBe(P); + expect(engine.armedFlowPackage('never_registered')).toBeUndefined(); + }); +}); diff --git a/packages/services/service-automation/src/flow-precedence-loader-set.test.ts b/packages/services/service-automation/src/flow-precedence-loader-set.test.ts index e5b78f2a85d..24790334f5e 100644 --- a/packages/services/service-automation/src/flow-precedence-loader-set.test.ts +++ b/packages/services/service-automation/src/flow-precedence-loader-set.test.ts @@ -145,10 +145,22 @@ describe('[#20864] boot-time precedence classifies by the loader\'s set, not by expect(describeFlowContender(loaderEntry(), () => '', NOTHING_INSTALLED)).toEqual({ source: 'runtime', packageId: 'crm' }); }); - it('asks the set once per contested name, and never for an uncontested one', () => { + // [ADR-0150 D3, epic #31527 child E5] An uncontested name is asked too: + // its one body is classified for the arm the engine records + // (`registerFlow`'s `armedFrom`), so a stamp on it can never make it the + // loader's own body. Still ONE question per name, every contender of a + // contested name judged against that one answer. + it('asks the set once per name, contested or not, and classifies an uncontested body by it', () => { const reader = vi.fn(HOLDS_FLOW); - resolveFlowPrecedence([flowBody('lonely_flow', 'L', CLAIMED), loaderEntry(), tenantRow()], silent(), reader, NOTHING_INSTALLED); - expect(reader.mock.calls).toEqual([[FLOW]]); + const winners = resolveFlowPrecedence( + [flowBody('lonely_flow', 'L', CLAIMED), loaderEntry(), tenantRow()], + silent(), + reader, + NOTHING_INSTALLED, + ); + expect(reader.mock.calls).toEqual([['lonely_flow'], [FLOW]]); + // The set does not hold `lonely_flow`, so its claimed id buys nothing. + expect(winners.find((w) => w.name === 'lonely_flow')?.contender.source).toBe('runtime'); }); }); diff --git a/packages/services/service-automation/src/flow-precedence.ts b/packages/services/service-automation/src/flow-precedence.ts index 56e9626922d..afcef3a2a38 100644 --- a/packages/services/service-automation/src/flow-precedence.ts +++ b/packages/services/service-automation/src/flow-precedence.ts @@ -109,6 +109,13 @@ export interface FlowPrecedenceWinner { name: string; /** The body to register — the winner under ADR-0005 precedence. */ definition: unknown; + /** + * [ADR-0150 D3, epic #31527 child E5] Where that body comes from, for + * EVERY name — one contender included — so the engine records the arm + * (`registerFlow`'s `armedFrom`) and `armedFlowPackage` answers the + * package only for the loader's own body. + */ + contender: FlowContender; /** Present only when this name had more than one contender. */ shadowing?: FlowShadowingRecord; } @@ -160,6 +167,25 @@ function classifyContender(item: unknown, owner: string | undefined, installed: if (isServedOverrideRowOf({ type: 'flow', package_id: binding, metadata: item }, owner, installed)) { return { source: 'override', packageId: binding as string }; } + // [ADR-0150 D3, epic #31527 child E5] The same override as the + // protocol's view serves it (the `kernel:ready` bind, the re-sync and + // the mutation sync read that view): no stored binding, and stamped + // with the base's own envelope (`_packageId` = the base) beside the + // declaration it was saved with — measured on the real composition, + // `flow-declared-override-first-boot-pull.integration.test.ts`. + // Without this that body passes `isCodeArtifactBody` below as the + // loader's own. The read-side reading the protocol's + // `servedOverrideBaseOf` makes: the base's envelope, AND the predicate + // above holding for the row the pair would store it as. A package-less + // row declaring the same thing carries no envelope and stays `runtime`. + const pair = pairOf(owner, installed); + if ( + pair.ok + && packageId === owner + && isServedOverrideRowOf({ type: 'flow', package_id: pair.value, metadata: item }, owner, installed) + ) { + return { source: 'override', packageId: pair.value }; + } } if (owner !== undefined && isCodeArtifactBody(item)) { return { source: 'package', packageId: String(packageId) }; @@ -309,7 +335,9 @@ function undeclaredRemedy(owner: string | undefined, installed: InstalledManifes * [#20864] Which contender is `package` is the loader's set's answer, asked * ONCE per contested name so every contender of that name is judged against * one answer — see {@link describeFlowContender}. A name with one contender - * asks nothing: precedence decides nothing there. + * is classified too, though precedence decides nothing there: the winner + * carries its `contender`, which the engine records as the arm (ADR-0150 D3, + * epic #31527 child E5). * * [#20913] ONE decision for BOTH boot steps. The automation plugin resolves * the boot pull's registry list and the `kernel:ready` / `metadata:reloaded` @@ -355,12 +383,13 @@ export function resolveFlowPrecedence( const winners: FlowPrecedenceWinner[] = []; for (const name of order) { const members = groups.get(name)!; + const owner = loaderSetOwner(packagedFlowOwner, name); if (members.length === 1) { - winners.push({ name, definition: members[0].definition }); + const definition = members[0].definition; + winners.push({ name, definition, contender: classifyContender(definition, owner, installed) }); continue; } - const owner = loaderSetOwner(packagedFlowOwner, name); const group = members.map((member) => ({ ...member, contender: classifyContender(member.definition, owner, installed), @@ -391,7 +420,7 @@ export function resolveFlowPrecedence( const overrideOverOwnBase = armed.contender.source === 'override' && shadowed.every((contender) => contender.source === 'package' && contender.packageId === owner); if (overrideOverOwnBase) { - winners.push({ name, definition: armed.definition }); + winners.push({ name, definition: armed.definition, contender: armed.contender }); continue; } // [#20913] Say WHY this one is armed, per case — the cases are @@ -430,6 +459,7 @@ export function resolveFlowPrecedence( winners.push({ name, definition: armed.definition, + contender: armed.contender, shadowing: { name, armed: armed.contender, shadowed }, }); continue; @@ -449,6 +479,7 @@ export function resolveFlowPrecedence( winners.push({ name, definition: armed.definition, + contender: armed.contender, shadowing: { name, armed: armed.contender, shadowed }, }); } diff --git a/packages/services/service-automation/src/plugin.ts b/packages/services/service-automation/src/plugin.ts index 68793fa1664..939eaf34b3b 100644 --- a/packages/services/service-automation/src/plugin.ts +++ b/packages/services/service-automation/src/plugin.ts @@ -71,7 +71,7 @@ import { } from './connector-credentials.js'; import { CONNECTOR_CREDENTIAL_SOURCE_SERVICE } from '@objectstack/types'; import { createConnectorCredentialSource } from './connector-credential-source.js'; -import { packageScopedRegistryOf, refusedConnectorNames } from './connector-package-scope.js'; +import { connectorNameResolver, packageScopedRegistryOf, refusedConnectorNames } from './connector-package-scope.js'; import type { PackageScopedRefusal, PackageScopedRegistry } from '@objectstack/objectql'; import { createConnectorRequestSigner } from './request-signing/index.js'; import { ConnectorConnectionStore, type ConnectorConnectionRecord } from './connector-connections.js'; @@ -1798,6 +1798,11 @@ export class AutomationServicePlugin implements Plugin { // the ObjectQL registry, read at question time. See `flowNameResolver`. this.engine.setFlowNameResolver(flowNameResolver(ctx)); + // [ADR-0150 D3, epic #31527 child E5] Which declared connector instance + // a flow's bare `connectorConfig.connectorId` means is the same + // resolver's answer for the flow's package. See `connectorNameResolver`. + this.engine.setConnectorNameResolver(connectorNameResolver(ctx)); + // [#28405] A waiting run resumes on the flow body it started on, read // back from the metadata history once the flow was republished. See // `flowHistoryReader`. @@ -2244,7 +2249,7 @@ export class AutomationServicePlugin implements Plugin { const def = entry.definition as { name?: string }; if (!def?.name) continue; try { - this.engine.registerFlow(entry.name, def as never); + this.engine.registerFlow(entry.name, def as never, entry.contender); this.syncedFlowNames.add(entry.name); // The receipt, so the shadowed contender is observable at all. if (entry.shadowing) this.engine.recordFlowShadowing(entry.shadowing); @@ -5394,7 +5399,7 @@ export class AutomationServicePlugin implements Plugin { continue; } try { - this.engine.registerFlow(entry.name, entry.definition as never); + this.engine.registerFlow(entry.name, entry.definition as never, entry.contender); resynced++; } catch (err) { // #5048 — see ./thrown-cause-diagnostics.ts. @@ -5470,7 +5475,7 @@ export class AutomationServicePlugin implements Plugin { // re-binding the body the boot pull armed is safe. for (const entry of this.resolveFlowContenders(ctx, defs)) { try { - this.engine.registerFlow(entry.name, entry.definition as never); + this.engine.registerFlow(entry.name, entry.definition as never, entry.contender); this.syncedFlowNames.add(entry.name); bound++; } catch (err) { @@ -5655,7 +5660,7 @@ export class AutomationServicePlugin implements Plugin { const held = await engine.getFlow(name); if (held && holdsFlowDefinition(engine, name, held, entry.definition)) continue; try { - engine.registerFlow(name, entry.definition as never); + engine.registerFlow(name, entry.definition as never, entry.contender); this.mutationArmedFlows.set(name, stableStringify(entry.definition)); armed.push(name); } catch (err) {