From d6bcb8dbe0173325ac26421c90ac8ff2e702dc9f Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 05:51:40 +0000 Subject: [PATCH 1/8] feat(objectql, plugin-approvals): assignment rules and approval steps read queue names from their declaring package Claude-Session: https://claude.ai/code/session_01ADHkmPfjQpqnk93rr9esh8 Co-authored-by: Claude --- packages/objectql/src/assignment-rules.ts | 49 +++++- packages/objectql/src/ownership-queue.test.ts | 152 ++++++++++++++++++ .../src/approval-service.test.ts | 148 +++++++++++++++++ .../plugin-approvals/src/approval-service.ts | 65 +++++++- 4 files changed, 402 insertions(+), 12 deletions(-) diff --git a/packages/objectql/src/assignment-rules.ts b/packages/objectql/src/assignment-rules.ts index 255d9cc0611..81eb3b7ef66 100644 --- a/packages/objectql/src/assignment-rules.ts +++ b/packages/objectql/src/assignment-rules.ts @@ -34,6 +34,19 @@ * `load` through {@link assignmentExpressionRefusals}, the paths this module * evaluates them by. * + * ## Which queue a name means + * + * [ADR-0150 D3] A declared rule is written inside a package, so the queue it + * names is read from that package: the queue service is passed the package + * the rule's registry item is registered under (`_packageId`, the registry's + * stamp) as `callerPackageId`, and answers the package's own queue, else the + * one holder in its declared dependencies (plus `sys`), else a refusal naming + * every candidate. The rule never picks a holder itself: the one resolver is + * the queue service's (`IOwnershipQueueService`), and a refused name reads as + * a queue that does not resolve (the row is written ownerless, in no queue). + * An organization's authored rule, and a declared rule no package ships, is + * read with no package: environment-wide, as before the key existed. + * * ## As which identity * * A platform step, not app automation: every read — the queue's members, a @@ -142,6 +155,12 @@ interface ActiveRule { name: string; object: string; entries: RuleEntry[]; + /** + * [ADR-0150 D3] The package that ships the declared rule — the package its + * queue names are read from — or `null` for an organization's authored rule + * and a declared rule no package ships (read environment-wide). + */ + packageId: string | null; } /** One evaluation's memo: least-loaded counts and user-target standings, never older than the insert that asked. */ @@ -169,6 +188,11 @@ function expressionOf(v: unknown): { dialect: string; source: string } | undefin return undefined; } +/** The package a declared rule's registry item is registered under (`_packageId`, the registry's stamp), or `null`. */ +function declaredPackageOf(item: Record): string | null { + return typeof item._packageId === 'string' && item._packageId !== '' ? item._packageId : null; +} + function ruleOf(item: unknown): ActiveRule | null { if (!isRecord(item) || typeof item.name !== 'string' || typeof item.object !== 'string') return null; if (item.active === false) return null; @@ -186,7 +210,7 @@ function ruleOf(item: unknown): ActiveRule | null { ...(expressionOf(e.load) ? { load: expressionOf(e.load)!.source } : {}), }); } - return entries.length > 0 ? { name: item.name, object: item.object, entries } : null; + return entries.length > 0 ? { name: item.name, object: item.object, entries, packageId: declaredPackageOf(item) } : null; } /** @@ -197,7 +221,7 @@ function ruleOf(item: unknown): ActiveRule | null { function authoredRuleOf(row: Record): ActiveRule | null { const name = present(row.name); if (!name) return null; - return ruleOf({ + const rule = ruleOf({ name, object: row.object_name, entries: [{ @@ -208,6 +232,8 @@ function authoredRuleOf(row: Record): ActiveRule | null { load: row.load, }], }); + // An organization's row belongs to no package, whatever columns it carries. + return rule ? { ...rule, packageId: null } : null; } function sortOrderOf(row: Record): number { @@ -485,16 +511,23 @@ export class AssignmentRuleEvaluator { this.warnOnce(`no-service::${rule.name}`, `[assignment] rule '${rule.name}' routes into a queue, but no ownership-queue service is registered — the row is written ownerless`, { rule: rule.name }); return; } + // [ADR-0150 D3] The name is read from the rule's package; no package, no + // key — the environment-wide read, exactly as before the key existed. + const fromPackage = rule.packageId ? { callerPackageId: rule.packageId } : undefined; let resolved: unknown; try { - resolved = await queues.resolveQueue(queueName, organizationId); + resolved = fromPackage + ? await queues.resolveQueue(queueName, organizationId, fromPackage) + : await queues.resolveQueue(queueName, organizationId); } catch (err: any) { - this.host.logger?.warn?.('[assignment] the queue could not be resolved — the row is written as it stood', { rule: rule.name, queue: queueName, organization: organizationId, error: err?.message }); + this.host.logger?.warn?.('[assignment] the queue could not be resolved — the row is written as it stood', { rule: rule.name, queue: queueName, organization: organizationId, package: rule.packageId, error: err?.message }); return; } if (!resolved) { - this.warnOnce(`unresolved::${rule.name}::${queueName}::${organizationId}`, `[assignment] rule '${rule.name}' routes into queue '${queueName}', which does not resolve in organization '${organizationId}' — the row is written ownerless, in no queue. Declare the queue, or author it in that organization.`, { - rule: rule.name, queue: queueName, organization: organizationId, + this.warnOnce(`unresolved::${rule.name}::${queueName}::${organizationId}`, `[assignment] rule '${rule.name}' routes into queue '${queueName}', which does not resolve in organization '${organizationId}'` + + (rule.packageId ? ` from the rule's package '${rule.packageId}' (its own queue, else the one holder among its dependencies)` : '') + + ` — the row is written ownerless, in no queue. Declare the queue, or author it in that organization.`, { + rule: rule.name, queue: queueName, organization: organizationId, package: rule.packageId, }); return; } @@ -504,7 +537,9 @@ export class AssignmentRuleEvaluator { let members: string[]; try { - members = await queues.expandMembers(queueName, organizationId); + members = fromPackage + ? await queues.expandMembers(queueName, organizationId, fromPackage) + : await queues.expandMembers(queueName, organizationId); } catch (err: any) { this.host.logger?.warn?.('[assignment] the queue\'s members could not be read — the row parks in the queue', { rule: rule.name, queue: queueName, error: err?.message }); return; diff --git a/packages/objectql/src/ownership-queue.test.ts b/packages/objectql/src/ownership-queue.test.ts index 4cf0748faf7..55b3c790708 100644 --- a/packages/objectql/src/ownership-queue.test.ts +++ b/packages/objectql/src/ownership-queue.test.ts @@ -15,6 +15,8 @@ import { QUEUE_FIELD_DEF } from '@objectstack/spec/data'; import { ObjectQL } from './engine.js'; import { applySystemFields, objectQueueColumnRefusal } from './registry.js'; import { OWNERSHIP_QUEUE_SOURCE_SLOT, assignmentExpressionRefusals, describeMissingOwnershipQueueService, nextMember } from './assignment-rules.js'; +import { resolvePackageScopedName, type PackageScopedRefusal, type PackageScopedRegistry } from './package-scoped-resolver.js'; +import type { SchemaRegistry } from './registry.js'; type Row = Record; @@ -467,6 +469,156 @@ describe('[ADR-0142 D5] the assignment seam', () => { }); }); +// ─── ADR-0150 D3: a declared rule's queue is read from the rule's package ── + +describe('[ADR-0150 D3] a declared rule reads its queue name from the package that ships the rule', () => { + const P = 'com.acme.p'; + const D = 'com.acme.d'; + const U = 'com.acme.u'; + /** Who staffs each holder's `support` queue in org_a. */ + const STAFF: Record = { [D]: ['u_d'], [U]: ['u_u'], [P]: ['u_p'] }; + + let engine: ObjectQL; + let d: ReturnType; + let warn: ReturnType; + /** Every read the seam made of the queue service: [method, name, organization, options]. */ + let asked: unknown[][]; + /** Every refusal the queue service answered a read with. */ + let refusals: PackageScopedRefusal[]; + + const manifest = (id: string, deps: string[] = []) => ({ + id, name: id, version: '1.0.0', type: 'app', namespace: id.split('.').pop(), + ...(deps.length > 0 ? { dependencies: Object.fromEntries(deps.map((dep) => [dep, '^1.0.0'])) } : {}), + }) as never; + const queue = (name: string) => ({ name, label: name, members: [] }); + const rule = { name: 'ticket_intake', label: 'Intake', object: 'ticket', active: true, entries: [{ name: 'all', assignTo: { type: 'queue', value: 'support' }, strategy: 'round_robin' }] }; + + /** + * The ownership-queue service's D3 read, standing in for + * `@objectstack/plugin-sharing`'s (which depends on this package, so this + * suite cannot construct it): the ONE resolver, `resolvePackageScopedName`, + * over the holders the listing serves — a disabled package's left out, as + * plugin-sharing's `listedHoldersView` does — and a refused name read as + * nowhere (`null` / `[]`), the contract's answer for the `nobody` reader. + */ + function d3Queues(registry: SchemaRegistry) { + const listed = { + getPackage: (id: string) => registry.getPackage(id), + getAllPackages: () => registry.getAllPackages(), + packageScopedHoldersOf: (type: string, name: string) => + registry.packageScopedHoldersOf(type, name).filter((id) => !registry.isPackageDisabled(id)), + getPackageScopedItem: (type: string, name: string, packageId: string, member?: string) => registry.getPackageScopedItem(type, name, packageId, member), + getEnvironmentScopedItem: (type: string, name: string, member?: string) => registry.getEnvironmentScopedItem(type, name, member), + } as PackageScopedRegistry; + const holderOf = (name: string, options?: { callerPackageId?: string | null }): string | null => { + const resolution = resolvePackageScopedName(listed, { type: 'queue', name, callerPackageId: options?.callerPackageId || null }); + if (resolution.status === 'refused') { + refusals.push(resolution); + return null; + } + return resolution.status === 'resolved' ? (resolution.holder.kind === 'package' ? resolution.holder.packageId : 'environment') : null; + }; + return { + resolveQueue: async (name: string, org: string | null, options?: { callerPackageId?: string | null }) => { + asked.push(['resolveQueue', name, org, options]); + const holder = holderOf(name, options); + return holder && org === 'org_a' ? { name, label: name, source: 'declared', organizationId: null, members: [], packageId: holder } : null; + }, + expandMembers: async (name: string, org: string | null, options?: { callerPackageId?: string | null }) => { + asked.push(['expandMembers', name, org, options]); + const holder = holderOf(name, options); + return holder && org === 'org_a' ? [...(STAFF[holder] ?? [])] : []; + }, + }; + } + + /** Install the packages (`[id, deps]`, in order), declare `support` in each holder, and the rule in `rulePackage`. */ + async function boot(packages: Array<[string, string[]]>, holders: string[], rulePackage: string | null) { + engine = new ObjectQL(); + d = makeDriver(); + engine.registerDriver(d.driver, true); + await engine.init(); + engine.registry.registerObject(TICKET as any, 'pkg'); + engine.registry.registerObject(CURSOR as any, 'plugin-sharing'); + for (const [id, deps] of packages) engine.registry.installPackage(manifest(id, deps), 'code'); + for (const holder of holders) engine.registry.registerItem('queue', { ...queue('support'), _packageId: holder }, 'name', holder); + if (rulePackage) engine.registry.registerItem('assignment_rule', { ...rule, _packageId: rulePackage }, 'name', rulePackage); + else engine.registry.registerItem('assignment_rule', { ...rule }, 'name'); + asked = []; + refusals = []; + (engine as any)[OWNERSHIP_QUEUE_SOURCE_SLOT] = () => d3Queues(engine.registry); + warn = vi.spyOn((engine as any).logger, 'warn'); + } + + const insert = () => engine.insert('ticket', { subject: 'A', organization_id: 'org_a' }, { context: SYS }); + + it('a rule in P naming `support`, held by P\'s dependency D and by unrelated U, routes to D\'s queue', async () => { + await boot([[D, []], [U, []], [P, [D]]], [D, U], P); + const row = await insert(); + expect(row).toMatchObject({ queue: 'support', owner_id: 'u_d' }); + expect(asked).toEqual([ + ['resolveQueue', 'support', 'org_a', { callerPackageId: P }], + ['expandMembers', 'support', 'org_a', { callerPackageId: P }], + ]); + expect(refusals).toEqual([]); + }); + + it('two holders in P\'s closure: refused, naming both — the row is written ownerless, in no queue', async () => { + await boot([[D, []], [U, []], [P, [D, U]]], [D, U], P); + const row = await insert(); + expect(row.owner_id ?? null).toBeNull(); + expect(row.queue ?? null).toBeNull(); + expect(refusals).toHaveLength(1); + expect(refusals[0]).toMatchObject({ + reason: 'ambiguous-in-closure', + callerPackageId: P, + candidates: [{ kind: 'package', packageId: D }, { kind: 'package', packageId: U }], + }); + const hit = warn.mock.calls.find((c: unknown[]) => /does not resolve in organization 'org_a' from the rule's package 'com\.acme\.p'/.test(String(c[0]))); + expect(hit, 'the seam says the name did not resolve from the rule\'s package').toBeTruthy(); + expect(hit![1]).toMatchObject({ rule: 'ticket_intake', queue: 'support', package: P }); + }); + + it('D disabled, unrelated U holding `support`: refused as outside P\'s closure, naming U — U\'s members are never served', async () => { + await boot([[D, []], [U, []], [P, [D]]], [D, U], P); + engine.registry.disablePackage(D); + const row = await insert(); + expect(row.owner_id ?? null).toBeNull(); + expect(row.queue ?? null).toBeNull(); + expect(refusals).toHaveLength(1); + expect(refusals[0]).toMatchObject({ + reason: 'outside-closure', + callerPackageId: P, + candidates: [{ kind: 'package', packageId: U }], + }); + }); + + it('CONTROL — a declared rule no package ships reads environment-wide, as before: the same two holders are refused, naming both', async () => { + await boot([[D, []], [U, []], [P, [D]]], [D, U], null); + const row = await insert(); + expect(row.owner_id ?? null).toBeNull(); + expect(row.queue ?? null).toBeNull(); + expect(asked).toEqual([['resolveQueue', 'support', 'org_a', undefined]]); + expect(refusals).toHaveLength(1); + expect(refusals[0]).toMatchObject({ + reason: 'ambiguous-in-environment', + candidates: [{ kind: 'package', packageId: D }, { kind: 'package', packageId: U }], + }); + }); + + it('CONTROL — an organization\'s own rule belongs to no package: it reads environment-wide, whatever the declared rules carry', async () => { + await boot([[D, []], [P, [D]]], [D], P); + engine.registry.registerObject(AUTHORED_RULE as any, 'plugin-sharing'); + d.storeFor('sys_assignment_rule').set('ar1', { + id: 'ar1', name: 'org_intake', object_name: 'ticket', organization_id: 'org_a', sort_order: 1, + recipient_type: 'queue', recipient_id: 'support', strategy: 'round_robin', active: true, + }); + const row = await insert(); + expect(row).toMatchObject({ queue: 'support', owner_id: 'u_d' }); + expect(asked[0]).toEqual(['resolveQueue', 'support', 'org_a', undefined]); + }); +}); + // ─── D5: user targets, and an organization's own rules ───────────────────── describe('[ADR-0142 D5] a user target owns the row only while the user is an active member', () => { diff --git a/packages/plugins/plugin-approvals/src/approval-service.test.ts b/packages/plugins/plugin-approvals/src/approval-service.test.ts index 756ff2061e8..85b0ac0f96d 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.test.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.test.ts @@ -17,6 +17,7 @@ import { import { bindApprovalLockHook, bindDelegationWriteGuard, unbindAllHooks } from './lifecycle-hooks.js'; import { filterApproversWhoCanRead } from './approver-org-scope.js'; import { celEngine } from '@objectstack/formula'; +import { SchemaRegistry, resolvePackageScopedName, type PackageScopedRefusal, type PackageScopedRegistry } from '@objectstack/objectql'; import { SysApprovalRequest } from './sys-approval-request.object.js'; // [#29604] A pass-through spy on the ADR-0105 D9 read filter, so one describe @@ -4409,6 +4410,153 @@ describe('ApprovalService — a queue approver asks the queue service to refuse } }); +// [ADR-0150 D3] An approval step is declared inside its flow, so the queue a +// `queue` approver names is read from the package that ships the flow — the +// automation engine's `packagedFlowOwner` — passed to the queue service as +// `callerPackageId`. The double stands in for `@objectstack/plugin-sharing`'s +// service (not a dependency of this package): the ONE resolver, +// `resolvePackageScopedName`, over the holders the listing serves (a disabled +// package's left out, as plugin-sharing's `listedHoldersView` does), and under +// `onFailedRead: 'refuse'` a refused name rejects with the refusal, as the +// contract says. +describe('ApprovalService — a queue approver reads its queue name from the package that ships the flow (ADR-0150 D3)', () => { + const P = 'com.acme.p'; + const D = 'com.acme.d'; + const U = 'com.acme.u'; + /** Who staffs each holder's `support` queue in t1. */ + const STAFF: Record = { [D]: ['u_d'], [U]: ['u_u'] }; + + const manifest = (id: string, deps: string[] = []) => ({ + id, name: id, version: '1.0.0', type: 'app', namespace: id.split('.').pop(), + ...(deps.length > 0 ? { dependencies: Object.fromEntries(deps.map((dep) => [dep, '^1.0.0'])) } : {}), + }) as never; + + /** Install the packages (`[id, deps]`, in order) and declare queue `support` in each holder. */ + const registryOf = (packages: Array<[string, string[]]>, holders: string[]) => { + const registry = new SchemaRegistry(); + for (const [id, deps] of packages) registry.installPackage(manifest(id, deps), 'code'); + for (const holder of holders) registry.registerItem('queue', { name: 'support', label: 'Support', members: [], _packageId: holder }, 'name', holder); + return registry; + }; + + const setup = (registry: SchemaRegistry, flowPackage: string | undefined) => { + const engine = makeFakeEngine(); + const asked: unknown[] = []; + const refusals: PackageScopedRefusal[] = []; + const listed = { + getPackage: (id: string) => registry.getPackage(id), + getAllPackages: () => registry.getAllPackages(), + packageScopedHoldersOf: (type: string, name: string) => + registry.packageScopedHoldersOf(type, name).filter((id) => !registry.isPackageDisabled(id)), + getPackageScopedItem: (type: string, name: string, packageId: string, member?: string) => registry.getPackageScopedItem(type, name, packageId, member), + getEnvironmentScopedItem: (type: string, name: string, member?: string) => registry.getEnvironmentScopedItem(type, name, member), + } as PackageScopedRegistry; + let n = 0; + const svc = new ApprovalService({ + engine, + clock: { now: () => new Date(1757000000000 + (n++) * 1000) }, + logger: { warn: () => {} }, + ownershipQueues: () => ({ + expandMembers: async (name: string, org: string | null, options?: { onFailedRead?: string; callerPackageId?: string | null }) => { + asked.push([name, org, options]); + const resolution = resolvePackageScopedName(listed, { type: 'queue', name, callerPackageId: options?.callerPackageId || null }); + if (resolution.status === 'refused') { + refusals.push(resolution); + if (options?.onFailedRead === 'refuse') { + throw Object.assign(new Error(resolution.message), { code: 'RESOURCE_CONFLICT', status: 409, refusal: resolution }); + } + return []; + } + if (resolution.status !== 'resolved' || resolution.holder.kind !== 'package' || org !== 't1') return []; + return [...(STAFF[resolution.holder.packageId] ?? [])]; + }, + }), + }); + svc.attachAutomation({ packagedFlowOwner: (flow: string) => (flow === 'deal_approval' ? flowPackage : undefined) } as any); + return { engine, svc, asked, refusals }; + }; + const queueNode = (configExtra: Record = {}) => ({ + ...openInput([]), + config: { approvers: [{ type: 'queue' as const, value: 'support' }], behavior: 'first_response' as const, lockRecord: false, ...configExtra }, + }); + + it('a step in P\'s flow naming `support`, held by P\'s dependency D and by unrelated U, opens on D\'s members', async () => { + const { svc, asked, refusals } = setup(registryOf([[D, []], [U, []], [P, [D]]], [D, U]), P); + const req = await svc.openNodeRequest(queueNode(), CTX) as any; + expect(req.pending_approvers).toEqual(['u_d']); + expect(asked).toEqual([['support', 't1', { purpose: 'addressing', onFailedRead: 'refuse', callerPackageId: P }]]); + expect(refusals).toEqual([]); + }); + + it('two holders in P\'s closure: the node refuses to open, naming both — nothing is written', async () => { + const { engine, svc, refusals } = setup(registryOf([[D, []], [U, []], [P, [D, U]]], [D, U]), P); + const refusal = await svc.openNodeRequest(queueNode(), CTX).then(() => null, (e: unknown) => e); + expect(refusal).toBeInstanceOf(ApproverDirectoryUnreadableError); + expect(refusal).toMatchObject({ approverType: 'queue', approverValue: 'support' }); + expect((refusal as Error).message).toContain(D); + expect((refusal as Error).message).toContain(U); + expect((refusal as any).cause).toMatchObject({ code: 'RESOURCE_CONFLICT', status: 409 }); + expect(refusals).toHaveLength(1); + expect(refusals[0]).toMatchObject({ + reason: 'ambiguous-in-closure', + callerPackageId: P, + candidates: [{ kind: 'package', packageId: D }, { kind: 'package', packageId: U }], + }); + expect(engine._tables['sys_approval_request'] ?? []).toEqual([]); + }); + + it('D disabled, unrelated U holding `support`: the node refuses as outside P\'s closure, naming U — U\'s members are never asked', async () => { + const registry = registryOf([[D, []], [U, []], [P, [D]]], [D, U]); + registry.disablePackage(D); + const { engine, svc, refusals } = setup(registry, P); + const refusal = await svc.openNodeRequest(queueNode(), CTX).then(() => null, (e: unknown) => e); + expect(refusal).toBeInstanceOf(ApproverDirectoryUnreadableError); + expect((refusal as Error).message).toContain(U); + expect(refusals).toHaveLength(1); + expect(refusals[0]).toMatchObject({ reason: 'outside-closure', callerPackageId: P, candidates: [{ kind: 'package', packageId: U }] }); + expect(engine._tables['sys_approval_request'] ?? []).toEqual([]); + }); + + it('CONTROL — a flow authored in this deployment reads environment-wide, as before: the same two holders are refused, naming both', async () => { + const { svc, asked, refusals } = setup(registryOf([[D, []], [U, []], [P, [D]]], [D, U]), undefined); + const refusal = await svc.openNodeRequest(queueNode(), CTX).then(() => null, (e: unknown) => e); + expect(refusal).toBeInstanceOf(ApproverDirectoryUnreadableError); + expect(asked).toEqual([['support', 't1', { purpose: 'addressing', onFailedRead: 'refuse' }]]); + expect(refusals[0]).toMatchObject({ + reason: 'ambiguous-in-environment', + candidates: [{ kind: 'package', packageId: D }, { kind: 'package', packageId: U }], + }); + }); + + it('the fallback slate and decide\'s pre-snapshot re-resolution read the same package', async () => { + const { engine, svc, asked } = setup(registryOf([[D, []], [U, []], [P, [D]]], [D, U]), P); + // A slate of nobody falls back to the declared fallback, which names the queue. + const fallen = await svc.openNodeRequest(queueNode({ + approvers: [{ type: 'user', value: 'u_gone' }], + onEmptyApprovers: 'fallback', + fallbackApprovers: [{ type: 'queue', value: 'support' }], + }), CTX) as any; + expect(fallen.pending_approvers).toEqual(['u_d']); + expect(asked.at(-1)).toEqual(['support', 't1', { purpose: 'addressing', onFailedRead: 'refuse', callerPackageId: P }]); + + // A unanimous request stripped of its open-time snapshot, as one opened + // before the snapshot existed: the tally re-resolves the slate from the flow's package. + const req = await svc.openNodeRequest({ + ...queueNode({ approvers: [{ type: 'user', value: 'u2' }, { type: 'queue', value: 'support' }], behavior: 'unanimous' }), + recordId: 'opp2', runId: 'run_2', record: { id: 'opp2', amount: 100 }, + }, CTX) as any; + expect(req.pending_approvers).toEqual(['u2', 'u_d']); + const row = engine._tables['sys_approval_request'].find((r: any) => r.id === req.id)!; + const config = JSON.parse(row.node_config_json); + delete config.__approverGroups; + row.node_config_json = JSON.stringify(config); + const decided = await svc.decideNode(req.id, { decision: 'approve', actorId: 'u2' }, SYS); + expect(decided.finalized).toBe(false); + expect(asked.at(-1)).toEqual(['support', 't1', { purpose: 'addressing', onFailedRead: 'refuse', callerPackageId: P }]); + expect(engine._tables['sys_approval_request'].find((r: any) => r.id === req.id)!.pending_approvers).toBe('u_d'); + }); +}); + // [ADR-0142 D6 as amended; ruling record 6599731698 on #29604, letter B] The // ADR-0105 D9 cross-organization read filter is a read behind a `position` or // `team` approver as much as the directory expansion is. When it fails, the diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index 3ae15095f2a..9228864ceca 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -225,6 +225,18 @@ export interface ApprovalResumeSurface { }): Promise; /** Flow definition lookup, used to derive step-progress display data. */ getFlow?(name: string): Promise; + /** + * [ADR-0150 D3] The package that ships the flow `name`, per the loader's + * set, or `undefined` for a flow authored in this deployment. Read by + * {@link ApprovalService.flowPackageOf}: an approval step is declared inside + * its flow, so the queue an approver names is read from that package. + * + * ⚠️ Declares a method `AutomationEngine` ALREADY implements publicly + * (`packagedFlowOwner`, the one the engine's own subflow addressing reads); + * it widens no engine surface. Optional: absent, every step reads its queue + * names environment-wide, as before. + */ + packagedFlowOwner?(name: string): string | undefined; /** * Terminally cancel a suspended run (ADR-0044). Used when a recall lands * during a revision window — the run is paused at the revise-window node, @@ -2591,6 +2603,12 @@ export class ApprovalService implements IApprovalService { * was recorded and must not fail it (`decide`'s pre-snapshot tally). */ onDirectoryFailure?: 'refuse' | 'literal'; + /** + * [ADR-0150 D3] The package the step is declared in — its flow's + * ({@link flowPackageOf}) — which a `queue` approver's name is read + * from. `null` / omitted: environment-wide, as before. + */ + callerPackageId?: string | null; }, ): Promise { if (!step || !Array.isArray(step.approvers)) return []; @@ -2644,7 +2662,9 @@ export class ApprovalService implements IApprovalService { if (opts?.resolvedFrom && canonicalApproverType(String(a.type)) === 'field' && a.value != null) { opts.resolvedFrom[`field:${a.value}`] = (record as any)?.[a.value] ?? null; } - const ids = await this.resolveApproverSpec(a, record, organizationId, now, opts?.substitutions, onDirectoryFailure); + const ids = await this.resolveApproverSpec( + a, record, organizationId, now, opts?.substitutions, onDirectoryFailure, opts?.callerPackageId ?? null, + ); // per_group (#3266): tag each resolved id with this spec's group. for (const u of ids) { if (!u) continue; @@ -2674,6 +2694,7 @@ export class ApprovalService implements IApprovalService { now: number, substitutions?: OooSubstitution[], onDirectoryFailure: 'refuse' | 'literal' = 'refuse', + callerPackageId: string | null = null, ): Promise { // ADR-0090 D3: `role` is the deprecated spelling of `org_membership_level`. // Resolve on the canonical type, and write the canonical type in the @@ -2808,7 +2829,7 @@ export class ApprovalService implements IApprovalService { // organization (a queue is an organization's: APPROVER_ORG_SCOPED), on // the ADDRESSING purpose — the slate routes work, so the holders of a // switched-off position stay on it (D2). - const users = await bounded(await this.expandQueueUsers(String(a.value), directoryOrg)); + const users = await bounded(await this.expandQueueUsers(String(a.value), directoryOrg, callerPackageId)); if (users.length) return users; } else if (type === 'manager' && record) { const subject = (record as any)[a.value] ?? (record as any).owner_id; @@ -3560,12 +3581,35 @@ export class ApprovalService implements IApprovalService { * catch turns that rejection into the node's {@link ApproverDirectoryUnreadableError}, * so the slate is never opened without the people who could not be read. An * axis of its own beside `purpose`. + * + * [ADR-0150 D3] `callerPackageId` is the package the step is declared in + * ({@link flowPackageOf}): the name resolves from it — its own queue, else + * the one holder in its declared dependencies — through the queue service, + * the one resolver. A name it cannot pick rejects under `'refuse'` with the + * refusal naming every candidate, which the node answers as it answers a + * failed read: the slate is never opened on a guess. No package: the + * environment-wide read, as before. */ - private async expandQueueUsers(queueName: string, organizationId?: string | null): Promise { + private async expandQueueUsers(queueName: string, organizationId?: string | null, callerPackageId?: string | null): Promise { if (!queueName) return []; const queues = this.queueSource(); if (!queues) return []; - return queues.expandMembers(queueName, organizationId ?? null, { purpose: 'addressing', onFailedRead: 'refuse' }); + return queues.expandMembers(queueName, organizationId ?? null, { + purpose: 'addressing', onFailedRead: 'refuse', ...(callerPackageId ? { callerPackageId } : {}), + }); + } + + /** + * [ADR-0150 D3] The package the approval step of flow `flowName` is + * declared in: the package that ships the flow, as the automation engine + * answers it (`packagedFlowOwner`, the reader its own subflow addressing + * takes the caller's package from), or `null` for a flow authored in this + * deployment, a request with no flow, and an engine that cannot say. + */ + private flowPackageOf(flowName: string | null | undefined): string | null { + if (!flowName || typeof this.automation?.packagedFlowOwner !== 'function') return null; + const owner = this.automation.packagedFlowOwner(flowName); + return typeof owner === 'string' && owner !== '' ? owner : null; } /** @@ -4372,6 +4416,9 @@ export class ApprovalService implements IApprovalService { const requestOrg = subjectOrg ?? ctxOrg; const resolvedFrom: Record = {}; const exprCtx = { trigger: input.record ?? null, vars: input.variables ?? null }; + // [ADR-0150 D3] The package this step is declared in — its flow's — which + // every slate below reads a `queue` approver's name from. + const callerPackageId = this.flowPackageOf(input.flowName); const submitterId = input.submitterId !== undefined ? input.submitterId : (context.userId ?? null); // [#25573] `excludeSubmitter: true` (ruling 6377888641, letter B): the // submitter is taken off every slate this request can open on. It runs on @@ -4410,6 +4457,7 @@ export class ApprovalService implements IApprovalService { now: nowDate.getTime(), substitutions, groups, exprCtx, resolvedFrom, + callerPackageId, }, ), 'approvers', groups); @@ -4469,6 +4517,7 @@ export class ApprovalService implements IApprovalService { now: nowDate.getTime(), substitutions, groups, exprCtx, resolvedFrom: fallbackResolvedFrom, + callerPackageId, }, ), 'fallback', groups); // Keep the primary slate's resolution inputs (they explain WHY the @@ -5211,7 +5260,13 @@ export class ApprovalService implements IApprovalService { // always kept (ADR-0142 D6's refusal is the node's, at open time). original = await this.expandApprovers( { approvers: config.approvers }, parseJson(raw.payload_json, undefined), org, - { onDirectoryFailure: 'literal' }, + { + onDirectoryFailure: 'literal', + // [ADR-0150 D3] The step's flow is the row's `flow:` process. + callerPackageId: this.flowPackageOf( + typeof raw.process_name === 'string' && raw.process_name.startsWith('flow:') ? raw.process_name.slice('flow:'.length) : null, + ), + }, ); groupMap = {}; } From 0a1361e86381f8a744bcde65913ab5b4c1b78619 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 05:54:32 +0000 Subject: [PATCH 2/8] chore(changeset): queue reads from the declaring package Claude-Session: https://claude.ai/code/session_01ADHkmPfjQpqnk93rr9esh8 Co-authored-by: Claude --- .../31790-queue-reads-declaring-package.md | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 .changeset/31790-queue-reads-declaring-package.md diff --git a/.changeset/31790-queue-reads-declaring-package.md b/.changeset/31790-queue-reads-declaring-package.md new file mode 100644 index 00000000000..99cc4aa1e20 --- /dev/null +++ b/.changeset/31790-queue-reads-declaring-package.md @@ -0,0 +1,23 @@ +--- +'@objectstack/objectql': patch +'@objectstack/plugin-approvals': patch +--- + +feat(objectql, plugin-approvals): a declared assignment rule and an approval step read the queue they name from the package that declares them + +Clause-②: no (narrowing) +Metadata-protocol: none + + + +A declared assignment rule (`assignmentRules`) now passes the package that ships it as `callerPackageId` when it resolves its queue and reads the queue's members. An approval step passes the package that ships its flow (the automation engine's `packagedFlowOwner`) when it expands a `queue` approver, on the node's slate, its fallback slate and the tally of a request opened before the slate snapshot existed. The queue service resolves the name from that package (ADR-0150 D3): the package's own queue, else the one holder in its declared dependencies, else a refusal naming every candidate. An organization's own assignment rule, a declared rule no package ships and a flow authored in the deployment read environment-wide, exactly as before. + +So a rule or step in package P that names queue `q`, where P's dependency D and an unrelated package U both declare `q`, now reaches D's `q`. Before, it was refused because two packages declared the name. + +Narrowing, per ADR-0150 D3. A rule or step in package P whose queue name P cannot reach used to be served environment-wide and is now refused: + +- the only holder is a package outside P's dependencies (`outside-closure`, naming it); +- P's dependency D holds the name but is disabled, and an unrelated U holds it too (`outside-closure`, naming U; a disabled package holds no queue for this read); +- the only holder is an item authored in the environment (`outside-closure`, naming the environment). + +An assignment rule then writes the row ownerless and in no queue, and warns; an approval node refuses to open, naming every candidate, as it does for a queue whose read failed. An organization's `sys_queue` row under a name no package declares is unchanged. To resolve it, declare a dependency on the package whose queue you mean, enable it, or ship the queue in P. Measured first-party: 0 (no first-party package declares a queue, an assignment rule or a `queue` approver). From 0dccea6cfea9a2c38e38ece67eeea79325475cfb Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 06:21:09 +0000 Subject: [PATCH 3/8] test(plugin-approvals): declare the registry log level for the suite that now builds a registry Claude-Session: https://claude.ai/code/session_01ADHkmPfjQpqnk93rr9esh8 Co-authored-by: Claude --- packages/plugins/plugin-approvals/vitest.config.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/packages/plugins/plugin-approvals/vitest.config.ts b/packages/plugins/plugin-approvals/vitest.config.ts index 9722ccb1360..38243f13173 100644 --- a/packages/plugins/plugin-approvals/vitest.config.ts +++ b/packages/plugins/plugin-approvals/vitest.config.ts @@ -60,6 +60,10 @@ export default defineConfig({ // Mechanism + measured costs: examples/app-showcase/vitest.config.ts. // Enforced repo-wide by scripts/check-console-intercept-disarm.mjs. disableConsoleIntercept: true, + // #13517: quiet the registry's per-item registration chatter — the + // engine's own `OS_REGISTRY_LOG` seam, not a change to its shipped + // default. Enforced by scripts/check-registry-log-declared.mjs. + env: { OS_REGISTRY_LOG: 'warn' }, globals: true, environment: 'node', include: ['src/**/*.test.ts'], From 930d242f2cc47f2936965a16ff2d631fb51a8d15 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 07:22:12 +0000 Subject: [PATCH 4/8] fix(service-automation, plugin-approvals): an approval step reads its queue from the package of the flow body that runs AutomationEngine.armedFlowPackage(name) answers the package whose own body is armed under a flow name: the shipping package for the loader's body, nothing for a declared .custom override or any other environment-authored body. The automation plugin hands registerFlow the precedence's verdict at every arming step, and the precedence recognizes the override the protocol's view serves in the package's slot by its own overrides declaration. The approval service reads that package instead of packagedFlowOwner, so an override's step resolves environment-wide, as before. A refused queue name now reads as a refusal with its remedy, not as a failed read, and is not retryable. Claude-Session: https://claude.ai/code/session_01ADHkmPfjQpqnk93rr9esh8 Co-authored-by: Claude --- .../31790-queue-reads-declaring-package.md | 16 +- .../src/approval-service.test.ts | 72 ++++- .../plugin-approvals/src/approval-service.ts | 95 +++++-- .../services/service-automation/src/engine.ts | 48 +++- .../flow-armed-package.integration.test.ts | 269 ++++++++++++++++++ .../service-automation/src/flow-precedence.ts | 51 +++- .../services/service-automation/src/plugin.ts | 8 +- 7 files changed, 512 insertions(+), 47 deletions(-) create mode 100644 packages/services/service-automation/src/flow-armed-package.integration.test.ts diff --git a/.changeset/31790-queue-reads-declaring-package.md b/.changeset/31790-queue-reads-declaring-package.md index 99cc4aa1e20..9901a7c0995 100644 --- a/.changeset/31790-queue-reads-declaring-package.md +++ b/.changeset/31790-queue-reads-declaring-package.md @@ -1,18 +1,28 @@ --- '@objectstack/objectql': patch '@objectstack/plugin-approvals': patch +'@objectstack/service-automation': patch --- feat(objectql, plugin-approvals): a declared assignment rule and an approval step read the queue they name from the package that declares them -Clause-②: no (narrowing) +Clause-②: yes (widening); narrowing per ADR-0150 D3 declared below Metadata-protocol: none -A declared assignment rule (`assignmentRules`) now passes the package that ships it as `callerPackageId` when it resolves its queue and reads the queue's members. An approval step passes the package that ships its flow (the automation engine's `packagedFlowOwner`) when it expands a `queue` approver, on the node's slate, its fallback slate and the tally of a request opened before the slate snapshot existed. The queue service resolves the name from that package (ADR-0150 D3): the package's own queue, else the one holder in its declared dependencies, else a refusal naming every candidate. An organization's own assignment rule, a declared rule no package ships and a flow authored in the deployment read environment-wide, exactly as before. +A declared assignment rule (`assignmentRules`) now passes the package that ships it as `callerPackageId` when it resolves its queue and reads the queue's members. An approval step passes the package of the flow body the engine runs when it expands a `queue` approver, on the node's slate, its fallback slate and the tally of a request opened before the slate snapshot existed. The queue service resolves the name from that package (ADR-0150 D3): the package's own queue, else the one holder in its declared dependencies, else a refusal naming every candidate. An organization's own assignment rule, a declared rule no package ships and a flow authored in the deployment read environment-wide, exactly as before. So does a step in an environment-authored override of a packaged flow (a declared `.custom` override, ADR-0146 D9): a reference written in an overlay is the environment's (ADR-0150 D3), never read from the package it customizes. -So a rule or step in package P that names queue `q`, where P's dependency D and an unrelated package U both declare `q`, now reaches D's `q`. Before, it was refused because two packages declared the name. +`AutomationEngine.armedFlowPackage(name)` (`@objectstack/service-automation`) answers that package: the shipping package when the body armed under the name is the loader's own, and `undefined` for a declared override, a stored or runtime body, a body an authoring door registered, and a flow authored in the deployment. `packagedFlowOwner(name)` is unchanged and still names the package that ships the name, whichever body is armed. `registerFlow` takes an optional third argument, `{ armedFrom }`, the precedence's verdict on the body; the automation plugin passes it at every step that arms a flow. + +When a `queue` approver's name is refused this way, the approval node still refuses with `APPROVER_DIRECTORY_UNREADABLE`, but the message now says the name was refused (ADR-0150 D3), with the refusal and its remedy, instead of asking for the flow to run again once the directory can be read. Its `retryable` is `false`. + +Widening, per ADR-0150 D3. A rule or step in package P that names queue `q` used to be refused because two packages declared the name, and is now served: + +- P's dependency D and an unrelated package U both declare `q`: it reaches D's `q`; +- P declares `q` itself and an unrelated package U does too: it reaches P's own `q`. + +Measured first-party: 0 (no first-party package declares a queue, an assignment rule or a `queue` approver). Narrowing, per ADR-0150 D3. A rule or step in package P whose queue name P cannot reach used to be served environment-wide and is now refused: diff --git a/packages/plugins/plugin-approvals/src/approval-service.test.ts b/packages/plugins/plugin-approvals/src/approval-service.test.ts index 85b0ac0f96d..97f7e165589 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.test.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.test.ts @@ -4410,21 +4410,22 @@ describe('ApprovalService — a queue approver asks the queue service to refuse } }); -// [ADR-0150 D3] An approval step is declared inside its flow, so the queue a -// `queue` approver names is read from the package that ships the flow — the -// automation engine's `packagedFlowOwner` — passed to the queue service as -// `callerPackageId`. The double stands in for `@objectstack/plugin-sharing`'s +// [ADR-0150 D3] An approval step is written in the flow body the engine runs, +// so the queue a `queue` approver names is read from that body's package — the +// automation engine's `armedFlowPackage`: the shipping package for its own +// body, none for an environment-authored override of it — passed to the queue +// service as `callerPackageId`. The double stands in for `@objectstack/plugin-sharing`'s // service (not a dependency of this package): the ONE resolver, // `resolvePackageScopedName`, over the holders the listing serves (a disabled // package's left out, as plugin-sharing's `listedHoldersView` does), and under // `onFailedRead: 'refuse'` a refused name rejects with the refusal, as the // contract says. -describe('ApprovalService — a queue approver reads its queue name from the package that ships the flow (ADR-0150 D3)', () => { +describe('ApprovalService — a queue approver reads its queue name from the package of the flow body that runs (ADR-0150 D3)', () => { const P = 'com.acme.p'; const D = 'com.acme.d'; const U = 'com.acme.u'; - /** Who staffs each holder's `support` queue in t1. */ - const STAFF: Record = { [D]: ['u_d'], [U]: ['u_u'] }; + /** Who staffs each holder's `support` queue in t1 (`environment`: the item authored in the environment). */ + const STAFF: Record = { [D]: ['u_d'], [U]: ['u_u'], environment: ['u_env'] }; const manifest = (id: string, deps: string[] = []) => ({ id, name: id, version: '1.0.0', type: 'app', namespace: id.split('.').pop(), @@ -4439,7 +4440,13 @@ describe('ApprovalService — a queue approver reads its queue name from the pac return registry; }; - const setup = (registry: SchemaRegistry, flowPackage: string | undefined) => { + /** + * `flowPackage`: the package that ships `deal_approval`. `overridden`: the + * body armed under the name is an environment-authored override of it (a + * declared `.custom` override), so the engine answers no package for the + * body that runs while `packagedFlowOwner` still names the shipping one. + */ + const setup = (registry: SchemaRegistry, flowPackage: string | undefined, overridden = false) => { const engine = makeFakeEngine(); const asked: unknown[] = []; const refusals: PackageScopedRefusal[] = []; @@ -4467,12 +4474,15 @@ describe('ApprovalService — a queue approver reads its queue name from the pac } return []; } - if (resolution.status !== 'resolved' || resolution.holder.kind !== 'package' || org !== 't1') return []; - return [...(STAFF[resolution.holder.packageId] ?? [])]; + if (resolution.status !== 'resolved' || org !== 't1') return []; + return [...(STAFF[resolution.holder.kind === 'package' ? resolution.holder.packageId : resolution.holder.kind] ?? [])]; }, }), }); - svc.attachAutomation({ packagedFlowOwner: (flow: string) => (flow === 'deal_approval' ? flowPackage : undefined) } as any); + svc.attachAutomation({ + packagedFlowOwner: (flow: string) => (flow === 'deal_approval' ? flowPackage : undefined), + armedFlowPackage: (flow: string) => (flow === 'deal_approval' && !overridden ? flowPackage : undefined), + } as any); return { engine, svc, asked, refusals }; }; const queueNode = (configExtra: Record = {}) => ({ @@ -4496,6 +4506,16 @@ describe('ApprovalService — a queue approver reads its queue name from the pac expect((refusal as Error).message).toContain(D); expect((refusal as Error).message).toContain(U); expect((refusal as any).cause).toMatchObject({ code: 'RESOURCE_CONFLICT', status: 409 }); + // A refused name is not a failed read: worded as the refusal, with its remedy, and not retryable. + const message = (refusal as Error).message; + expect(message).toContain("approver 'queue:support' could not be expanded in organization 't1', because its name was refused (ADR-0150 D3, ambiguous-in-closure)"); + expect(message).toContain( + `Running the flow again changes nothing until the name resolves from package '${P}': declare a dependency on the ` + + `package whose queue it means, enable that package if it is disabled, or ship the queue in package '${P}'.`, + ); + expect(message).not.toContain('a read behind it failed'); + expect(message).not.toContain('once the directory can be read'); + expect(refusal).toMatchObject({ retryable: false }); expect(refusals).toHaveLength(1); expect(refusals[0]).toMatchObject({ reason: 'ambiguous-in-closure', @@ -4517,11 +4537,41 @@ describe('ApprovalService — a queue approver reads its queue name from the pac expect(engine._tables['sys_approval_request'] ?? []).toEqual([]); }); + it('an environment-authored override of P\'s flow reads environment-wide, as on main: its step reaches the environment\'s queue P cannot reach', async () => { + const registry = registryOf([[P, []]], []); + registry.registerItem('queue', { name: 'support', label: 'Support', members: [] }, 'name'); + // CONTROL: from P the name is refused outside P's closure — so a step read from P would not open. + expect(resolvePackageScopedName(registry as never, { type: 'queue', name: 'support', callerPackageId: P })) + .toMatchObject({ status: 'refused', reason: 'outside-closure' }); + const { engine, svc, asked, refusals } = setup(registry, P, true); + const req = await svc.openNodeRequest(queueNode(), CTX) as any; + expect(req.pending_approvers).toEqual(['u_env']); + expect(asked).toEqual([['support', 't1', { purpose: 'addressing', onFailedRead: 'refuse' }]]); + expect(refusals).toEqual([]); + + // The decide-time tally of a request opened before the slate snapshot reads the same body's package. + const tallied = await svc.openNodeRequest({ + ...queueNode({ approvers: [{ type: 'user', value: 'u2' }, { type: 'queue', value: 'support' }], behavior: 'unanimous' }), + recordId: 'opp2', runId: 'run_2', record: { id: 'opp2', amount: 100 }, + }, CTX) as any; + const row = engine._tables['sys_approval_request'].find((r: any) => r.id === tallied.id)!; + const config = JSON.parse(row.node_config_json); + delete config.__approverGroups; + row.node_config_json = JSON.stringify(config); + const decided = await svc.decideNode(tallied.id, { decision: 'approve', actorId: 'u2' }, SYS); + expect(decided.finalized).toBe(false); + expect(asked.at(-1)).toEqual(['support', 't1', { purpose: 'addressing', onFailedRead: 'refuse' }]); + expect(engine._tables['sys_approval_request'].find((r: any) => r.id === tallied.id)!.pending_approvers).toBe('u_env'); + expect(refusals).toEqual([]); + }); + it('CONTROL — a flow authored in this deployment reads environment-wide, as before: the same two holders are refused, naming both', async () => { const { svc, asked, refusals } = setup(registryOf([[D, []], [U, []], [P, [D]]], [D, U]), undefined); const refusal = await svc.openNodeRequest(queueNode(), CTX).then(() => null, (e: unknown) => e); expect(refusal).toBeInstanceOf(ApproverDirectoryUnreadableError); expect(asked).toEqual([['support', 't1', { purpose: 'addressing', onFailedRead: 'refuse' }]]); + expect((refusal as Error).message).toContain('because its name was refused (ADR-0150 D3, ambiguous-in-environment)'); + expect((refusal as Error).message).not.toContain('once the directory can be read'); expect(refusals[0]).toMatchObject({ reason: 'ambiguous-in-environment', candidates: [{ kind: 'package', packageId: D }, { kind: 'package', packageId: U }], diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index 9228864ceca..d84a0605da3 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -77,6 +77,7 @@ import { vetOrganizationClaim, withoutOperationPrivateKeys, } from '@objectstack/core'; +import type { PackageScopedRefusal } from '@objectstack/core'; import type { TenancyPosture } from '@objectstack/spec/security'; import { filterApproversWhoCanRead, @@ -226,17 +227,19 @@ export interface ApprovalResumeSurface { /** Flow definition lookup, used to derive step-progress display data. */ getFlow?(name: string): Promise; /** - * [ADR-0150 D3] The package that ships the flow `name`, per the loader's - * set, or `undefined` for a flow authored in this deployment. Read by - * {@link ApprovalService.flowPackageOf}: an approval step is declared inside - * its flow, so the queue an approver names is read from that package. + * [ADR-0150 D3] The package whose own body the engine runs for the flow + * `name` — the shipping package when the armed body is the loader's, and + * `undefined` for a declared `.custom` override, a stored or runtime body, + * and a flow authored in this deployment. Read by + * {@link ApprovalService.flowPackageOf}: an approval step is written in the + * body that runs, so the queue an approver names is read from that body's + * package, and an environment-authored override's step from no package. * - * ⚠️ Declares a method `AutomationEngine` ALREADY implements publicly - * (`packagedFlowOwner`, the one the engine's own subflow addressing reads); - * it widens no engine surface. Optional: absent, every step reads its queue - * names environment-wide, as before. + * ⚠️ Declares the method `AutomationEngine` implements + * (`armedFlowPackage`). Optional: absent, every step reads its queue names + * environment-wide, as before. */ - packagedFlowOwner?(name: string): string | undefined; + armedFlowPackage?(name: string): string | undefined; /** * Terminally cancel a suspended run (ADR-0044). Used when a recall lands * during a revision window — the run is paused at the revise-window node, @@ -1265,6 +1268,35 @@ function crossOrgFilterReadFailure(directoryOrg: unknown, organizationId: unknow + `${err instanceof Error ? err.message : String(err)}.`; } +/** + * [ADR-0150 D3] The resolver's refusal a rejection carries, when the + * rejection is a refused package-scoped name (the queue service's + * `PackageScopedNameRefusedError`, read by its shape: this package does not + * depend on the plugin that throws it). + */ +function packageScopedRefusalOf(err: unknown): PackageScopedRefusal | undefined { + const refusal = (err as { refusal?: Partial } | null | undefined)?.refusal; + return refusal?.status === 'refused' && typeof refusal.message === 'string' && typeof refusal.reason === 'string' + ? refusal as PackageScopedRefusal + : undefined; +} + +/** + * [ADR-0150 D3] What makes a refused queue name resolve, for the package the + * step was read from — the refusal's own remedy, said for a step. + */ +function refusalRemedy(refusal: PackageScopedRefusal): string { + const from = refusal.callerPackageId; + if (!from) { + return 'Running the flow again changes nothing until the name resolves: leave one holder of it in this ' + + 'environment, or name the queue from a step in a package that declares a dependency on the package ' + + 'whose queue it means.'; + } + return `Running the flow again changes nothing until the name resolves from package '${from}': declare a ` + + `dependency on the package whose queue it means, enable that package if it is disabled, or ship the queue ` + + `in package '${from}'.`; +} + /** * [ADR-0142 D6 as amended; ruling record 6599731698 on #29604, letter B] The * approval node refuses to open because a directory read behind one of its @@ -1279,8 +1311,12 @@ function crossOrgFilterReadFailure(directoryOrg: unknown, organizationId: unknow */ export class ApproverDirectoryUnreadableError extends Error { override readonly name = 'ApproverDirectoryUnreadableError'; - /** The run can be re-triggered once the directory reads again. */ - readonly retryable = true; + /** + * The run can be re-triggered once the directory reads again. `false` when + * the cause is an ADR-0150 D3 refusal of the name: a re-run is refused the + * same way until the remedy the message names is applied. + */ + readonly retryable: boolean; /** The approver whose directory read failed: its type and value as authored. */ readonly approverType: string; readonly approverValue: string; @@ -1301,13 +1337,24 @@ export class ApproverDirectoryUnreadableError extends Error { : `approver 'expression' (resolveAs '${input.type}', value '${input.value}')`; const inOrg = input.organizationId ? ` in organization '${input.organizationId}'` : ''; const read = input.failedRead.trim(); + const refusal = packageScopedRefusalOf(input.cause); + const notOpened = 'The approval node does not open: '; + const routedPast = ' would be routed past, so the request is not opened on the rest of the slate, on the ' + + 'declared fallbackApprovers or on the organization\'s administrators, and is not auto-approved, whatever ' + + 'the node\'s onEmptyApprovers says.'; super( - `APPROVER_DIRECTORY_UNREADABLE: ${approver} could not be expanded${inOrg}, because a read behind it failed: ` - + `${read}${/[.!?]$/.test(read) ? '' : '.'} The approval node does not open: the people who could not be ` - + `read would be routed past, so the request is not opened on the rest of the slate, on the declared ` - + `fallbackApprovers or on the organization's administrators, and is not auto-approved, whatever the node's ` - + `onEmptyApprovers says. Run the flow again once the directory can be read.`, + refusal + // [ADR-0150 D3] A refused name is not a failed read: running the flow + // again reads the same holders and is refused again. Its remedy is + // the refusal's own. + ? `APPROVER_DIRECTORY_UNREADABLE: ${approver} could not be expanded${inOrg}, because its name was refused ` + + `(ADR-0150 D3, ${refusal.reason}): ${refusal.message} ${notOpened}the people of whichever queue was ` + + `meant${routedPast} ${refusalRemedy(refusal)}` + : `APPROVER_DIRECTORY_UNREADABLE: ${approver} could not be expanded${inOrg}, because a read behind it failed: ` + + `${read}${/[.!?]$/.test(read) ? '' : '.'} ${notOpened}the people who could not be read${routedPast} ` + + `Run the flow again once the directory can be read.`, ); + this.retryable = refusal === undefined; if (input.cause !== undefined) Object.assign(this, { cause: input.cause }); this.approverType = input.type; this.approverValue = String(input.value); @@ -3601,14 +3648,18 @@ export class ApprovalService implements IApprovalService { /** * [ADR-0150 D3] The package the approval step of flow `flowName` is - * declared in: the package that ships the flow, as the automation engine - * answers it (`packagedFlowOwner`, the reader its own subflow addressing - * takes the caller's package from), or `null` for a flow authored in this - * deployment, a request with no flow, and an engine that cannot say. + * written in: the package of the body the engine runs for the flow, as the + * engine answers it (`armedFlowPackage`) — the shipping package for its own + * body, and `null` for a declared `.custom` override or any other + * environment-authored body (a reference in an overlay is the + * environment's, never the package's it customizes), a flow authored in + * this deployment, a request with no flow, and an engine that cannot say. + * ⛔ Not `packagedFlowOwner`: it names the package that ships the NAME, + * whichever body is armed under it. */ private flowPackageOf(flowName: string | null | undefined): string | null { - if (!flowName || typeof this.automation?.packagedFlowOwner !== 'function') return null; - const owner = this.automation.packagedFlowOwner(flowName); + if (!flowName || typeof this.automation?.armedFlowPackage !== 'function') return null; + const owner = this.automation.armedFlowPackage(flowName); return typeof owner === 'string' && owner !== '' ? owner : null; } diff --git a/packages/services/service-automation/src/engine.ts b/packages/services/service-automation/src/engine.ts index d08f5a5ae89..0f460bcda49 100644 --- a/packages/services/service-automation/src/engine.ts +++ b/packages/services/service-automation/src/engine.ts @@ -2867,6 +2867,15 @@ export class AutomationEngine implements IAutomationService { * {@link flowVersionHistory}, or a pinned body read back on resume. */ private readonly flowChecksums = new WeakMap(); + /** + * [ADR-0150 D3] The package whose own body each registered body IS: set + * only for a body the caller armed as the loader's (`armedFrom.source === + * 'package'`, {@link registerFlow}), to the package the loader's set names + * for it. Keyed by the parsed object the engine executes, as + * {@link flowChecksums} is, so a rollback to another version answers for + * that version's body. See {@link armedFlowPackage}. + */ + private readonly packageBodies = new WeakMap(); /** [#28405] Where a pinned body is read back by its identity — see {@link setFlowHistorySource}. */ private flowHistorySource?: FlowHistorySource; private nodeExecutors = new Map(); @@ -4556,7 +4565,16 @@ export class AutomationEngine implements IAutomationService { return canonicalizeFlow.call(host, name, definition, options); } - registerFlow(name: string, definition: unknown): FlowParsed { + /** + * @param options.armedFrom what the caller's ADR-0005/ADR-0126 precedence + * decided this body is (`resolveFlowPrecedence`'s winner). Only + * `'package'` — the loader's own body for a name the loader's set holds — + * makes the body its package's ({@link armedFlowPackage}); a declared + * override, a stored or runtime row, and a registration that says + * nothing (an authoring door, a rollback, a direct caller) are no + * package's. + */ + registerFlow(name: string, definition: unknown, options: { armedFrom?: FlowContender } = {}): 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). @@ -4601,6 +4619,11 @@ 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); + // [ADR-0150 D3] Whose body this is, from what the caller's precedence + // decided — never from the body's own `_packageId`, which a stored row + // carries too. See {@link armedFlowPackage}. + const loaderOwner = options.armedFrom?.source === 'package' ? this.packagedFlowOwner(name) : undefined; + if (loaderOwner !== undefined) this.packageBodies.set(parsed, loaderOwner); this.flows.set(name, parsed); // [#23316] Held now, so no longer refused — see {@link flowRefusals}. this.flowRefusals.delete(name); @@ -4977,6 +5000,29 @@ export class AutomationEngine implements IAutomationService { return typeof owner === 'string' && owner !== '' ? owner : undefined; } + /** + * [ADR-0150 D3] The package the body ARMED for `name` belongs to: the + * package the loader's set names, when the body the engine runs for the + * name is that package's own (registered as the precedence's `'package'` + * winner); `undefined` for every other body — a declared `.custom` + * override (ADR-0146 D9), a stored or runtime-authored row, a body an + * authoring door or a direct caller registered — and for a name the + * engine holds nothing under. + * + * The package a reference written in a flow's body is read from. ADR-0150 + * D3: a reference in an environment-authored overlay is the environment's + * and resolves as a caller with no package, never from the package the + * overlay customizes — so this differs from {@link packagedFlowOwner} + * (which classifies the NAME) exactly when an override of a packaged flow + * is armed. ⛔ Never the armed body's `_packageId`: the boot hydration + * stamps a stored row with its package too. + */ + armedFlowPackage(name: string): string | undefined { + const body = this.flows.get(name); + const owner = body ? this.packageBodies.get(body) : undefined; + return owner !== undefined && this.packagedFlowOwner(name) === owner ? owner : undefined; + } + /** [#20761] Is `name` a packaged flow — {@link packagedFlowOwner}, as a verdict. */ private isPackagedFlow(name: string): boolean { return this.packagedFlowOwner(name) !== undefined; diff --git a/packages/services/service-automation/src/flow-armed-package.integration.test.ts b/packages/services/service-automation/src/flow-armed-package.integration.test.ts new file mode 100644 index 00000000000..a7627744f2b --- /dev/null +++ b/packages/services/service-automation/src/flow-armed-package.integration.test.ts @@ -0,0 +1,269 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0150 D3] `AutomationEngine.armedFlowPackage` — the package whose own + * body the engine runs for a flow name — measured on a real kernel. + * + * A reference written in a flow's body (an approval step's `queue` approver, + * a connector id) is read from the package of the body that RUNS, not the + * package that ships the name: ADR-0150 D3 makes a reference in an + * environment-authored overlay the environment's, resolved as a caller with no + * package. So the reader has to tell the loader's own body from the shipping + * package's declared `.custom` override (ADR-0146 D9 item 1), which is armed + * over it under the same name — where `packagedFlowOwner` answers the + * shipping package for both. + * + * The harness is #28717's (`flow-declared-override-first-boot-pull`): an + * ObjectKernel, ObjectQL's metadata protocol over driver-sql on a + * better-sqlite3 file, the shipping package registered through the + * `manifest` service and the real automation plugin, booted twice on one file + * so the stored rows are read back cold. Measured at the boot pull (from a + * plugin `start()` after the automation plugin's) and after `kernel:ready`'s + * re-bind from the protocol's view, the two steps that arm a body. + */ + +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { ObjectKernel, ObjectLogger, type Plugin, type PluginContext } from '@objectstack/core'; +import { ObjectQLPlugin, type ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { defineStack } from '@objectstack/spec'; +import type { AutomationContext } from '@objectstack/spec/contracts'; +import { AutomationServicePlugin } from './plugin.js'; +import type { AutomationEngine, FlowTrigger, FlowTriggerBinding } from './engine.js'; +import { installDefaultOrganization } from './default-organization.testkit.js'; + +const BASE = 'com.acme.crm'; +const PAIR = `${BASE}.custom`; +const FLOW = 'crm_ticket_created'; +const TICKET = 'crm_ticket'; +const SYS = { isSystem: true } as const; + +/** The base flow, record-triggered on TICKET; `marker` names the body by its label and its end node. */ +const ticketFlow = (marker: string, extra: Record = {}) => ({ + name: FLOW, + label: marker, + type: 'autolaunched', + status: 'active', + nodes: [ + { + id: 'start', + type: 'start', + label: 'Start', + config: { objectName: TICKET, triggerType: 'record-after-create' }, + }, + { id: `end_${marker.toLowerCase()}`, type: 'end', label: 'End' }, + ], + edges: [{ id: 'e1', source: 'start', target: `end_${marker.toLowerCase()}` }], + ...extra, +}); + +const pluginManifest = (id: string) => ({ + id, + namespace: 'crm', + version: '1.0.0', + type: 'plugin', + name: 'crm', +}); + +/** The shipping package: one object and the base flow over it. */ +const shippingStack = () => + defineStack( + { + manifest: pluginManifest(BASE), + objects: [{ name: TICKET, label: 'Ticket', fields: { title: { name: 'title', label: 'Title', type: 'text' } } }], + flows: [ticketFlow('BASE')], + } as never, + { strict: false }, + ) as Record; + +type Row = 'override' | 'legacy'; + +const storedRow = (row: Row) => + row === 'override' + ? { + id: 'meta_override', + name: FLOW, + type: 'flow', + state: 'active', + package_id: PAIR, + metadata: JSON.stringify(ticketFlow('OVERRIDE', { overrides: { package: BASE, basedOn: '1.0.0' } })), + } + : { + id: 'meta_legacy', + name: FLOW, + type: 'flow', + state: 'active', + package_id: null, + metadata: JSON.stringify(ticketFlow('LEGACY')), + }; + +/** What each record change saw armed, and which body's end node its run reached. */ +interface Fired { + armedLabel: string | undefined; +} + +function objectqlRecordTrigger(ql: () => ObjectQL, automation: () => AutomationEngine, fired: Fired[]): FlowTrigger { + const packageOf = (flowName: string) => `qa-31790-trigger:${flowName}`; + return { + type: 'record_change', + start(binding: FlowTriggerBinding, callback: (ctx: AutomationContext) => Promise) { + ql().unregisterHooksByPackage(packageOf(binding.flowName)); + ql().registerHook( + 'afterInsert', + async (hook: { result?: unknown }) => { + const armed = (await automation().getFlow(binding.flowName)) as { label?: string } | null; + fired.push({ armedLabel: armed?.label }); + await callback({ record: hook.result, object: binding.object, event: 'afterInsert' } as never); + }, + { object: binding.object, packageId: packageOf(binding.flowName) }, + ); + }, + stop(flowName: string) { + ql().unregisterHooksByPackage(packageOf(flowName)); + }, + }; +} + +const kernels: ObjectKernel[] = []; +const dirs: string[] = []; +afterEach(async () => { + vi.restoreAllMocks(); + for (const k of kernels.splice(0)) await k.shutdown().catch(() => {}); + for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true }); +}); + +/** + * Boot the composition on `file`. `start` runs in a plugin that starts after + * the automation plugin: after the boot pull, before `kernel:ready`. + */ +async function boot(file: string, start: (ql: ObjectQL, automation: AutomationEngine) => Promise) { + const kernel = new ObjectKernel({ logger: { level: 'fatal' }, gracefulShutdown: false } as never); + kernels.push(kernel); + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: file }, useNullAsDefault: true }); + const fired: Fired[] = []; + let captured: PluginContext | undefined; + await kernel.use({ + name: 'test.driver.sqlite', + type: 'standard', + version: '1.0.0', + async init(ctx: PluginContext) { + ctx.registerService('driver.default', driver); + }, + } as Plugin); + await kernel.use(new ObjectQLPlugin()); + await kernel.use(new AutomationServicePlugin({ suspendedRunStore: 'memory' })); + await kernel.use({ + name: 'test.shipping-package', + type: 'standard', + version: '1.0.0', + dependencies: ['com.objectstack.engine.objectql', 'com.objectstack.service-automation'], + async init(ctx: PluginContext) { + captured = ctx; + const stack = shippingStack(); + await ctx.getService<{ register(m: unknown): Promise }>('manifest') + .register({ ...(stack.manifest as object), ...stack }); + const ql = () => ctx.getService('objectql'); + const automation = () => ctx.getService('automation'); + automation().registerTrigger(objectqlRecordTrigger(ql, automation, fired)); + }, + async start(ctx: PluginContext) { + const ql = ctx.getService('objectql'); + await installDefaultOrganization(ql as never); + await start(ql, ctx.getService('automation')); + }, + } as Plugin); + await kernel.bootstrap(); + return { kernel, fired, automation: kernel.getService('automation'), ctx: captured! }; +} + +/** The first boot stores `rows`, in this order; the second, cold, is measured. */ +async function measuredBoot(rows: readonly Row[], start: (ql: ObjectQL, automation: AutomationEngine) => Promise) { + const dir = mkdtempSync(join(tmpdir(), 'qa-31790-')); + dirs.push(dir); + const file = join(dir, 'store.db'); + const first = await boot(file, async (ql) => { + for (const row of rows) await ql.insert('sys_metadata', storedRow(row), { context: SYS } as never); + }); + await first.kernel.shutdown(); + kernels.splice(kernels.indexOf(first.kernel), 1); + const warn = vi.spyOn(ObjectLogger.prototype, 'warn'); + const measured = await boot(file, start); + const collisions = warn.mock.calls + .map(([message]) => String(message)) + .filter((message) => message.includes('Flow name collision') && message.includes(`'${FLOW}'`)); + return { ...measured, collisions }; +} + + +/** What the reader answers at the boot pull, and after `kernel:ready`. */ +async function readings(rows: readonly Row[]) { + let atPull: { armed: string | undefined; label: string | undefined } | undefined; + const { automation } = await measuredBoot(rows, async (_ql, engine) => { + atPull = { + armed: engine.armedFlowPackage(FLOW), + label: ((await engine.getFlow(FLOW)) as { label?: string } | null)?.label, + }; + }); + return { + atPull, + afterReady: { + armed: automation.armedFlowPackage(FLOW), + label: ((await automation.getFlow(FLOW)) as { label?: string } | null)?.label, + }, + owner: automation.packagedFlowOwner(FLOW), + }; +} + +describe('[ADR-0150 D3] armedFlowPackage names the package of the body the engine runs', () => { + it('the loader\'s own body, nothing stored: the shipping package, at the boot pull and after kernel:ready', async () => { + const r = await readings([]); + expect(r.owner).toBe(BASE); + expect(r.atPull).toEqual({ armed: BASE, label: 'BASE' }); + expect(r.afterReady).toEqual({ armed: BASE, label: 'BASE' }); + }); + + it('the declared .custom override armed over it: no package, while packagedFlowOwner still names the shipping package', async () => { + const r = await readings(['override']); + expect(r.owner, 'control: the loader\'s set holds the name').toBe(BASE); + expect(r.atPull).toEqual({ armed: undefined, label: 'OVERRIDE' }); + expect(r.afterReady).toEqual({ armed: undefined, label: 'OVERRIDE' }); + }); + + it('the override beside a legacy package-less row: no package', async () => { + const r = await readings(['legacy', 'override']); + expect(r.atPull).toEqual({ armed: undefined, label: 'OVERRIDE' }); + expect(r.afterReady).toEqual({ armed: undefined, label: 'OVERRIDE' }); + }); + + it('a legacy package-less row alone is shadowed (ADR-0126 §2), so the loader\'s body runs and it is the shipping package\'s', async () => { + const r = await readings(['legacy']); + expect(r.atPull).toEqual({ armed: BASE, label: 'BASE' }); + expect(r.afterReady).toEqual({ armed: BASE, label: 'BASE' }); + }); + + it('an override stored at runtime and re-armed by the metadata:reloaded re-sync: no package; deleted, the shipping package again', async () => { + const { automation, ctx } = await measuredBoot([], async () => {}); + expect(automation.armedFlowPackage(FLOW)).toBe(BASE); + const ql = ctx.getService('objectql'); + await ql.insert('sys_metadata', storedRow('override'), { context: SYS } as never); + await ctx.trigger('metadata:reloaded'); + expect(((await automation.getFlow(FLOW)) as { label?: string } | null)?.label).toBe('OVERRIDE'); + expect(automation.armedFlowPackage(FLOW)).toBeUndefined(); + await ql.delete('sys_metadata', { where: { id: 'meta_override' }, context: SYS } as never); + await ctx.trigger('metadata:reloaded'); + expect(((await automation.getFlow(FLOW)) as { label?: string } | null)?.label).toBe('BASE'); + expect(automation.armedFlowPackage(FLOW)).toBe(BASE); + }); + + it('a body registered with no precedence verdict (an authoring door, a direct caller) is no package\'s, even under a shipped name', async () => { + const { automation } = await measuredBoot([], async () => {}); + expect(automation.armedFlowPackage(FLOW)).toBe(BASE); + automation.registerFlow(FLOW, ticketFlow('DIRECT')); + expect(automation.packagedFlowOwner(FLOW)).toBe(BASE); + expect(automation.armedFlowPackage(FLOW)).toBeUndefined(); + expect(automation.armedFlowPackage('no_such_flow')).toBeUndefined(); + }); +}); diff --git a/packages/services/service-automation/src/flow-precedence.ts b/packages/services/service-automation/src/flow-precedence.ts index 25db2b1c807..c578a4a1ce4 100644 --- a/packages/services/service-automation/src/flow-precedence.ts +++ b/packages/services/service-automation/src/flow-precedence.ts @@ -100,6 +100,13 @@ export interface FlowPrecedenceWinner { definition: unknown; /** Present only when this name had more than one contender. */ shadowing?: FlowShadowingRecord; + /** + * [ADR-0150 D3] What the winner is, by the same classification the + * receipt's `armed` records, for every name — one contender or several. + * The caller hands it to `AutomationEngine.registerFlow`, so the engine + * knows whose body it runs (`armedFlowPackage`). + */ + armedFrom: FlowContender; } /** @@ -159,6 +166,32 @@ function classifyContender(item: unknown, owner: string | undefined, installed: }; } +/** + * [ADR-0150 D3] What a name's ONLY contender is, for its winner's `armedFrom`: + * {@link classifyContender}'s answer, except that a body the protocol's view + * serves in the shipping package's slot as that package's declared override + * is the `override` it is. + * + * The view serves the override (ADR-0146 D9 item 1) as one entry in place of + * the loader's body, with the package's envelope on it — measured on a real + * kernel: `_packageId` the base, `_provenance: 'package'` — and the stored + * row's binding ({@link storedRowBindingOf}) does not travel on that copy, so + * the classification reads it as the loader's body. What the copy keeps is + * its own declaration, `overrides.package` = the owner: the view serves a body + * in the owner's slot only after the one served-override predicate admitted + * its row by the row's column, and the loader's own body declares no override + * of its own package. ⛔ Only this narrows: a body that does not declare it + * stays as classified. Two or more contenders are judged on the registry's + * entries, which keep their binding, by the precedence below. + */ +function armedContender(item: unknown, contender: FlowContender, owner: string | undefined, installed: InstalledManifestLookup): FlowContender { + if (contender.source !== 'package' || owner === undefined) return contender; + const declared = (item as { overrides?: { package?: unknown } } | null | undefined)?.overrides?.package; + if (declared !== owner) return contender; + const pair = pairOf(owner, installed); + return { source: 'override', ...(pair.ok ? { packageId: pair.value } : {}) }; +} + /** * Classify one registry body's provenance. * @@ -295,9 +328,9 @@ function undeclaredRemedy(owner: string | undefined, installed: InstalledManifes * a body's own claim. * * [#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. + * ONCE per name so every contender of that name is judged against one answer + * — see {@link describeFlowContender}. A name with one contender is classified + * too, for the winner's `armedFrom` alone: precedence decides nothing there. * * [#20913] ONE decision for BOTH boot steps. The automation plugin resolves * the boot pull's registry list and the `kernel:ready` / `metadata:reloaded` @@ -337,12 +370,17 @@ 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 only = members[0].definition; + winners.push({ + name, + definition: only, + armedFrom: armedContender(only, classifyContender(only, owner, installed), owner, installed), + }); continue; } - const owner = loaderSetOwner(packagedFlowOwner, name); const group = members.map((member) => ({ ...member, contender: classifyContender(member.definition, owner, installed), @@ -373,7 +411,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, armedFrom: armed.contender }); continue; } // [#20913] Say WHY this one is armed, per case — the cases are @@ -407,6 +445,7 @@ export function resolveFlowPrecedence( name, definition: armed.definition, shadowing: { name, armed: armed.contender, shadowed }, + armedFrom: armed.contender, }); } return winners; diff --git a/packages/services/service-automation/src/plugin.ts b/packages/services/service-automation/src/plugin.ts index c1c0fc85878..e7efa1212bc 100644 --- a/packages/services/service-automation/src/plugin.ts +++ b/packages/services/service-automation/src/plugin.ts @@ -2244,7 +2244,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, { armedFrom: entry.armedFrom }); this.syncedFlowNames.add(entry.name); // The receipt, so the shadowed contender is observable at all. if (entry.shadowing) this.engine.recordFlowShadowing(entry.shadowing); @@ -5385,7 +5385,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, { armedFrom: entry.armedFrom }); resynced++; } catch (err) { // #5048 — see ./thrown-cause-diagnostics.ts. @@ -5461,7 +5461,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, { armedFrom: entry.armedFrom }); this.syncedFlowNames.add(entry.name); bound++; } catch (err) { @@ -5646,7 +5646,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, { armedFrom: entry.armedFrom }); this.mutationArmedFlows.set(name, stableStringify(entry.definition)); armed.push(name); } catch (err) { From 48b425dc74a75bd558c0a81c572adf3e08c19cb6 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 07:30:33 +0000 Subject: [PATCH 5/8] fix(service-automation): classify an uncontested flow winner outside the precedence resolveFlowPrecedence again asks the loader's set nothing for a name with one contender; the plugin classifies that winner with describeArmedFlowContender when it hands registerFlow its armedFrom. Claude-Session: https://claude.ai/code/session_01ADHkmPfjQpqnk93rr9esh8 Co-authored-by: Claude --- .../service-automation/src/flow-precedence.ts | 40 ++++++++++++------- .../services/service-automation/src/plugin.ts | 17 ++++---- 2 files changed, 36 insertions(+), 21 deletions(-) diff --git a/packages/services/service-automation/src/flow-precedence.ts b/packages/services/service-automation/src/flow-precedence.ts index c578a4a1ce4..f2b9c53d975 100644 --- a/packages/services/service-automation/src/flow-precedence.ts +++ b/packages/services/service-automation/src/flow-precedence.ts @@ -101,12 +101,14 @@ export interface FlowPrecedenceWinner { /** Present only when this name had more than one contender. */ shadowing?: FlowShadowingRecord; /** - * [ADR-0150 D3] What the winner is, by the same classification the - * receipt's `armed` records, for every name — one contender or several. - * The caller hands it to `AutomationEngine.registerFlow`, so the engine + * [ADR-0150 D3] What the winner is — the classification the receipt's + * `armed` records — for a name with more than one contender. A name with + * one is not classified here (precedence decides nothing there, and asks + * the loader's set nothing): ask {@link describeArmedFlowContender}. The + * caller hands the answer to `AutomationEngine.registerFlow`, so the engine * knows whose body it runs (`armedFlowPackage`). */ - armedFrom: FlowContender; + armedFrom?: FlowContender; } /** @@ -166,6 +168,21 @@ function classifyContender(item: unknown, owner: string | undefined, installed: }; } +/** + * [ADR-0150 D3] What a name's ONLY contender is — the body + * {@link resolveFlowPrecedence} arms for an uncontested name, which it does + * not classify — for `AutomationEngine.registerFlow`'s `armedFrom`. Asks the + * loader's set once, for that name. See {@link armedContender}. + */ +export function describeArmedFlowContender( + item: unknown, + packagedFlowOwner: PackagedFlowSource | undefined, + installed: InstalledManifestLookup, +): FlowContender { + const owner = loaderSetOwner(packagedFlowOwner, (item as { name?: unknown } | null | undefined)?.name); + return armedContender(item, classifyContender(item, owner, installed), owner, installed); +} + /** * [ADR-0150 D3] What a name's ONLY contender is, for its winner's `armedFrom`: * {@link classifyContender}'s answer, except that a body the protocol's view @@ -328,9 +345,9 @@ function undeclaredRemedy(owner: string | undefined, installed: InstalledManifes * a body's own claim. * * [#20864] Which contender is `package` is the loader's set's answer, asked - * ONCE per name so every contender of that name is judged against one answer - * — see {@link describeFlowContender}. A name with one contender is classified - * too, for the winner's `armedFrom` alone: precedence decides nothing there. + * 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. * * [#20913] ONE decision for BOTH boot steps. The automation plugin resolves * the boot pull's registry list and the `kernel:ready` / `metadata:reloaded` @@ -370,17 +387,12 @@ 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) { - const only = members[0].definition; - winners.push({ - name, - definition: only, - armedFrom: armedContender(only, classifyContender(only, owner, installed), owner, installed), - }); + winners.push({ name, definition: members[0].definition }); continue; } + const owner = loaderSetOwner(packagedFlowOwner, name); const group = members.map((member) => ({ ...member, contender: classifyContender(member.definition, owner, installed), diff --git a/packages/services/service-automation/src/plugin.ts b/packages/services/service-automation/src/plugin.ts index e7efa1212bc..9ebe8eb0103 100644 --- a/packages/services/service-automation/src/plugin.ts +++ b/packages/services/service-automation/src/plugin.ts @@ -28,7 +28,7 @@ import { resolvePackageScopedName } from '@objectstack/objectql'; import { describeThrownForLog, thrownMessageText } from './thrown-cause-diagnostics.js'; import { defaultEnvCredentialResolver, type CredentialResolver } from './credential-resolver.js'; import { registerFlowCredentialRedactor } from './flow-credential-projection.js'; -import { resolveFlowPrecedence, renderFlowContender } from './flow-precedence.js'; +import { describeArmedFlowContender, resolveFlowPrecedence, renderFlowContender } from './flow-precedence.js'; import { installBuiltinNodes, rearmSuspendedWaitTimers } from './builtin/index.js'; import { resolveRunDataContext } from './runtime-identity.js'; import { SysAutomationRun } from './sys-automation-run.object.js'; @@ -5327,12 +5327,15 @@ export class AutomationServicePlugin implements Plugin { */ private resolveFlowContenders(ctx: PluginContext, items: readonly unknown[]) { const engine = this.engine; - return resolveFlowPrecedence( - items, - ctx.logger, - engine ? (name) => engine.packagedFlowOwner(name) : undefined, - installedManifestsOf(objectqlRegistryOf(ctx)), - ); + const reader = engine ? (name: string) => engine.packagedFlowOwner(name) : undefined; + const installed = installedManifestsOf(objectqlRegistryOf(ctx)); + // [ADR-0150 D3] Every winner carries what it is, so `registerFlow` + // records whose body the engine runs (`armedFlowPackage`): a contested + // name's from the precedence, an uncontested one's asked here. + return resolveFlowPrecedence(items, ctx.logger, reader, installed).map((entry) => ({ + ...entry, + armedFrom: entry.armedFrom ?? describeArmedFlowContender(entry.definition, reader, installed), + })); } /** From fe45524b38b4c58939927c8e650eb1531e7e2f9e Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 08:01:49 +0000 Subject: [PATCH 6/8] revert(service-automation, plugin-approvals): leave the flow-body package reader to its shared home The reader of the package whose flow body runs is being built once, for every caller, in its own change. Until it lands, the approval step reads packagedFlowOwner as before; the engine, the precedence and the plugin are back to main. The refusal wording on the approval node stays. Claude-Session: https://claude.ai/code/session_01ADHkmPfjQpqnk93rr9esh8 Co-authored-by: Claude --- .../31790-queue-reads-declaring-package.md | 5 +- .../src/approval-service.test.ts | 60 +--- .../plugin-approvals/src/approval-service.ts | 36 +-- .../services/service-automation/src/engine.ts | 48 +--- .../flow-armed-package.integration.test.ts | 269 ------------------ .../service-automation/src/flow-precedence.ts | 53 +--- .../services/service-automation/src/plugin.ts | 24 +- 7 files changed, 37 insertions(+), 458 deletions(-) delete mode 100644 packages/services/service-automation/src/flow-armed-package.integration.test.ts diff --git a/.changeset/31790-queue-reads-declaring-package.md b/.changeset/31790-queue-reads-declaring-package.md index 9901a7c0995..f740f60c4fd 100644 --- a/.changeset/31790-queue-reads-declaring-package.md +++ b/.changeset/31790-queue-reads-declaring-package.md @@ -1,7 +1,6 @@ --- '@objectstack/objectql': patch '@objectstack/plugin-approvals': patch -'@objectstack/service-automation': patch --- feat(objectql, plugin-approvals): a declared assignment rule and an approval step read the queue they name from the package that declares them @@ -11,9 +10,7 @@ Metadata-protocol: none -A declared assignment rule (`assignmentRules`) now passes the package that ships it as `callerPackageId` when it resolves its queue and reads the queue's members. An approval step passes the package of the flow body the engine runs when it expands a `queue` approver, on the node's slate, its fallback slate and the tally of a request opened before the slate snapshot existed. The queue service resolves the name from that package (ADR-0150 D3): the package's own queue, else the one holder in its declared dependencies, else a refusal naming every candidate. An organization's own assignment rule, a declared rule no package ships and a flow authored in the deployment read environment-wide, exactly as before. So does a step in an environment-authored override of a packaged flow (a declared `.custom` override, ADR-0146 D9): a reference written in an overlay is the environment's (ADR-0150 D3), never read from the package it customizes. - -`AutomationEngine.armedFlowPackage(name)` (`@objectstack/service-automation`) answers that package: the shipping package when the body armed under the name is the loader's own, and `undefined` for a declared override, a stored or runtime body, a body an authoring door registered, and a flow authored in the deployment. `packagedFlowOwner(name)` is unchanged and still names the package that ships the name, whichever body is armed. `registerFlow` takes an optional third argument, `{ armedFrom }`, the precedence's verdict on the body; the automation plugin passes it at every step that arms a flow. +A declared assignment rule (`assignmentRules`) now passes the package that ships it as `callerPackageId` when it resolves its queue and reads the queue's members. An approval step passes the package that ships its flow (the automation engine's `packagedFlowOwner`) when it expands a `queue` approver, on the node's slate, its fallback slate and the tally of a request opened before the slate snapshot existed. The queue service resolves the name from that package (ADR-0150 D3): the package's own queue, else the one holder in its declared dependencies, else a refusal naming every candidate. An organization's own assignment rule, a declared rule no package ships and a flow authored in the deployment read environment-wide, exactly as before. When a `queue` approver's name is refused this way, the approval node still refuses with `APPROVER_DIRECTORY_UNREADABLE`, but the message now says the name was refused (ADR-0150 D3), with the refusal and its remedy, instead of asking for the flow to run again once the directory can be read. Its `retryable` is `false`. diff --git a/packages/plugins/plugin-approvals/src/approval-service.test.ts b/packages/plugins/plugin-approvals/src/approval-service.test.ts index 97f7e165589..937a11eb6dc 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.test.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.test.ts @@ -4410,22 +4410,21 @@ describe('ApprovalService — a queue approver asks the queue service to refuse } }); -// [ADR-0150 D3] An approval step is written in the flow body the engine runs, -// so the queue a `queue` approver names is read from that body's package — the -// automation engine's `armedFlowPackage`: the shipping package for its own -// body, none for an environment-authored override of it — passed to the queue -// service as `callerPackageId`. The double stands in for `@objectstack/plugin-sharing`'s +// [ADR-0150 D3] An approval step is declared inside its flow, so the queue a +// `queue` approver names is read from the package that ships the flow — the +// automation engine's `packagedFlowOwner` — passed to the queue service as +// `callerPackageId`. The double stands in for `@objectstack/plugin-sharing`'s // service (not a dependency of this package): the ONE resolver, // `resolvePackageScopedName`, over the holders the listing serves (a disabled // package's left out, as plugin-sharing's `listedHoldersView` does), and under // `onFailedRead: 'refuse'` a refused name rejects with the refusal, as the // contract says. -describe('ApprovalService — a queue approver reads its queue name from the package of the flow body that runs (ADR-0150 D3)', () => { +describe('ApprovalService — a queue approver reads its queue name from the package that ships the flow (ADR-0150 D3)', () => { const P = 'com.acme.p'; const D = 'com.acme.d'; const U = 'com.acme.u'; - /** Who staffs each holder's `support` queue in t1 (`environment`: the item authored in the environment). */ - const STAFF: Record = { [D]: ['u_d'], [U]: ['u_u'], environment: ['u_env'] }; + /** Who staffs each holder's `support` queue in t1. */ + const STAFF: Record = { [D]: ['u_d'], [U]: ['u_u'] }; const manifest = (id: string, deps: string[] = []) => ({ id, name: id, version: '1.0.0', type: 'app', namespace: id.split('.').pop(), @@ -4440,13 +4439,7 @@ describe('ApprovalService — a queue approver reads its queue name from the pac return registry; }; - /** - * `flowPackage`: the package that ships `deal_approval`. `overridden`: the - * body armed under the name is an environment-authored override of it (a - * declared `.custom` override), so the engine answers no package for the - * body that runs while `packagedFlowOwner` still names the shipping one. - */ - const setup = (registry: SchemaRegistry, flowPackage: string | undefined, overridden = false) => { + const setup = (registry: SchemaRegistry, flowPackage: string | undefined) => { const engine = makeFakeEngine(); const asked: unknown[] = []; const refusals: PackageScopedRefusal[] = []; @@ -4474,15 +4467,12 @@ describe('ApprovalService — a queue approver reads its queue name from the pac } return []; } - if (resolution.status !== 'resolved' || org !== 't1') return []; - return [...(STAFF[resolution.holder.kind === 'package' ? resolution.holder.packageId : resolution.holder.kind] ?? [])]; + if (resolution.status !== 'resolved' || resolution.holder.kind !== 'package' || org !== 't1') return []; + return [...(STAFF[resolution.holder.packageId] ?? [])]; }, }), }); - svc.attachAutomation({ - packagedFlowOwner: (flow: string) => (flow === 'deal_approval' ? flowPackage : undefined), - armedFlowPackage: (flow: string) => (flow === 'deal_approval' && !overridden ? flowPackage : undefined), - } as any); + svc.attachAutomation({ packagedFlowOwner: (flow: string) => (flow === 'deal_approval' ? flowPackage : undefined) } as any); return { engine, svc, asked, refusals }; }; const queueNode = (configExtra: Record = {}) => ({ @@ -4537,34 +4527,6 @@ describe('ApprovalService — a queue approver reads its queue name from the pac expect(engine._tables['sys_approval_request'] ?? []).toEqual([]); }); - it('an environment-authored override of P\'s flow reads environment-wide, as on main: its step reaches the environment\'s queue P cannot reach', async () => { - const registry = registryOf([[P, []]], []); - registry.registerItem('queue', { name: 'support', label: 'Support', members: [] }, 'name'); - // CONTROL: from P the name is refused outside P's closure — so a step read from P would not open. - expect(resolvePackageScopedName(registry as never, { type: 'queue', name: 'support', callerPackageId: P })) - .toMatchObject({ status: 'refused', reason: 'outside-closure' }); - const { engine, svc, asked, refusals } = setup(registry, P, true); - const req = await svc.openNodeRequest(queueNode(), CTX) as any; - expect(req.pending_approvers).toEqual(['u_env']); - expect(asked).toEqual([['support', 't1', { purpose: 'addressing', onFailedRead: 'refuse' }]]); - expect(refusals).toEqual([]); - - // The decide-time tally of a request opened before the slate snapshot reads the same body's package. - const tallied = await svc.openNodeRequest({ - ...queueNode({ approvers: [{ type: 'user', value: 'u2' }, { type: 'queue', value: 'support' }], behavior: 'unanimous' }), - recordId: 'opp2', runId: 'run_2', record: { id: 'opp2', amount: 100 }, - }, CTX) as any; - const row = engine._tables['sys_approval_request'].find((r: any) => r.id === tallied.id)!; - const config = JSON.parse(row.node_config_json); - delete config.__approverGroups; - row.node_config_json = JSON.stringify(config); - const decided = await svc.decideNode(tallied.id, { decision: 'approve', actorId: 'u2' }, SYS); - expect(decided.finalized).toBe(false); - expect(asked.at(-1)).toEqual(['support', 't1', { purpose: 'addressing', onFailedRead: 'refuse' }]); - expect(engine._tables['sys_approval_request'].find((r: any) => r.id === tallied.id)!.pending_approvers).toBe('u_env'); - expect(refusals).toEqual([]); - }); - it('CONTROL — a flow authored in this deployment reads environment-wide, as before: the same two holders are refused, naming both', async () => { const { svc, asked, refusals } = setup(registryOf([[D, []], [U, []], [P, [D]]], [D, U]), undefined); const refusal = await svc.openNodeRequest(queueNode(), CTX).then(() => null, (e: unknown) => e); diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index d84a0605da3..c66eb10d564 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -227,19 +227,17 @@ export interface ApprovalResumeSurface { /** Flow definition lookup, used to derive step-progress display data. */ getFlow?(name: string): Promise; /** - * [ADR-0150 D3] The package whose own body the engine runs for the flow - * `name` — the shipping package when the armed body is the loader's, and - * `undefined` for a declared `.custom` override, a stored or runtime body, - * and a flow authored in this deployment. Read by - * {@link ApprovalService.flowPackageOf}: an approval step is written in the - * body that runs, so the queue an approver names is read from that body's - * package, and an environment-authored override's step from no package. + * [ADR-0150 D3] The package that ships the flow `name`, per the loader's + * set, or `undefined` for a flow authored in this deployment. Read by + * {@link ApprovalService.flowPackageOf}: an approval step is declared inside + * its flow, so the queue an approver names is read from that package. * - * ⚠️ Declares the method `AutomationEngine` implements - * (`armedFlowPackage`). Optional: absent, every step reads its queue names - * environment-wide, as before. + * ⚠️ Declares a method `AutomationEngine` ALREADY implements publicly + * (`packagedFlowOwner`, the one the engine's own subflow addressing reads); + * it widens no engine surface. Optional: absent, every step reads its queue + * names environment-wide, as before. */ - armedFlowPackage?(name: string): string | undefined; + packagedFlowOwner?(name: string): string | undefined; /** * Terminally cancel a suspended run (ADR-0044). Used when a recall lands * during a revision window — the run is paused at the revise-window node, @@ -3648,18 +3646,14 @@ export class ApprovalService implements IApprovalService { /** * [ADR-0150 D3] The package the approval step of flow `flowName` is - * written in: the package of the body the engine runs for the flow, as the - * engine answers it (`armedFlowPackage`) — the shipping package for its own - * body, and `null` for a declared `.custom` override or any other - * environment-authored body (a reference in an overlay is the - * environment's, never the package's it customizes), a flow authored in - * this deployment, a request with no flow, and an engine that cannot say. - * ⛔ Not `packagedFlowOwner`: it names the package that ships the NAME, - * whichever body is armed under it. + * declared in: the package that ships the flow, as the automation engine + * answers it (`packagedFlowOwner`, the reader its own subflow addressing + * takes the caller's package from), or `null` for a flow authored in this + * deployment, a request with no flow, and an engine that cannot say. */ private flowPackageOf(flowName: string | null | undefined): string | null { - if (!flowName || typeof this.automation?.armedFlowPackage !== 'function') return null; - const owner = this.automation.armedFlowPackage(flowName); + if (!flowName || typeof this.automation?.packagedFlowOwner !== 'function') return null; + const owner = this.automation.packagedFlowOwner(flowName); return typeof owner === 'string' && owner !== '' ? owner : null; } diff --git a/packages/services/service-automation/src/engine.ts b/packages/services/service-automation/src/engine.ts index 0f460bcda49..d08f5a5ae89 100644 --- a/packages/services/service-automation/src/engine.ts +++ b/packages/services/service-automation/src/engine.ts @@ -2867,15 +2867,6 @@ export class AutomationEngine implements IAutomationService { * {@link flowVersionHistory}, or a pinned body read back on resume. */ private readonly flowChecksums = new WeakMap(); - /** - * [ADR-0150 D3] The package whose own body each registered body IS: set - * only for a body the caller armed as the loader's (`armedFrom.source === - * 'package'`, {@link registerFlow}), to the package the loader's set names - * for it. Keyed by the parsed object the engine executes, as - * {@link flowChecksums} is, so a rollback to another version answers for - * that version's body. See {@link armedFlowPackage}. - */ - private readonly packageBodies = new WeakMap(); /** [#28405] Where a pinned body is read back by its identity — see {@link setFlowHistorySource}. */ private flowHistorySource?: FlowHistorySource; private nodeExecutors = new Map(); @@ -4565,16 +4556,7 @@ export class AutomationEngine implements IAutomationService { return canonicalizeFlow.call(host, name, definition, options); } - /** - * @param options.armedFrom what the caller's ADR-0005/ADR-0126 precedence - * decided this body is (`resolveFlowPrecedence`'s winner). Only - * `'package'` — the loader's own body for a name the loader's set holds — - * makes the body its package's ({@link armedFlowPackage}); a declared - * override, a stored or runtime row, and a registration that says - * nothing (an authoring door, a rollback, a direct caller) are no - * package's. - */ - registerFlow(name: string, definition: unknown, options: { armedFrom?: FlowContender } = {}): FlowParsed { + registerFlow(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). @@ -4619,11 +4601,6 @@ 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); - // [ADR-0150 D3] Whose body this is, from what the caller's precedence - // decided — never from the body's own `_packageId`, which a stored row - // carries too. See {@link armedFlowPackage}. - const loaderOwner = options.armedFrom?.source === 'package' ? this.packagedFlowOwner(name) : undefined; - if (loaderOwner !== undefined) this.packageBodies.set(parsed, loaderOwner); this.flows.set(name, parsed); // [#23316] Held now, so no longer refused — see {@link flowRefusals}. this.flowRefusals.delete(name); @@ -5000,29 +4977,6 @@ export class AutomationEngine implements IAutomationService { return typeof owner === 'string' && owner !== '' ? owner : undefined; } - /** - * [ADR-0150 D3] The package the body ARMED for `name` belongs to: the - * package the loader's set names, when the body the engine runs for the - * name is that package's own (registered as the precedence's `'package'` - * winner); `undefined` for every other body — a declared `.custom` - * override (ADR-0146 D9), a stored or runtime-authored row, a body an - * authoring door or a direct caller registered — and for a name the - * engine holds nothing under. - * - * The package a reference written in a flow's body is read from. ADR-0150 - * D3: a reference in an environment-authored overlay is the environment's - * and resolves as a caller with no package, never from the package the - * overlay customizes — so this differs from {@link packagedFlowOwner} - * (which classifies the NAME) exactly when an override of a packaged flow - * is armed. ⛔ Never the armed body's `_packageId`: the boot hydration - * stamps a stored row with its package too. - */ - armedFlowPackage(name: string): string | undefined { - const body = this.flows.get(name); - const owner = body ? this.packageBodies.get(body) : undefined; - return owner !== undefined && this.packagedFlowOwner(name) === owner ? owner : undefined; - } - /** [#20761] Is `name` a packaged flow — {@link packagedFlowOwner}, as a verdict. */ private isPackagedFlow(name: string): boolean { return this.packagedFlowOwner(name) !== undefined; diff --git a/packages/services/service-automation/src/flow-armed-package.integration.test.ts b/packages/services/service-automation/src/flow-armed-package.integration.test.ts deleted file mode 100644 index a7627744f2b..00000000000 --- a/packages/services/service-automation/src/flow-armed-package.integration.test.ts +++ /dev/null @@ -1,269 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * [ADR-0150 D3] `AutomationEngine.armedFlowPackage` — the package whose own - * body the engine runs for a flow name — measured on a real kernel. - * - * A reference written in a flow's body (an approval step's `queue` approver, - * a connector id) is read from the package of the body that RUNS, not the - * package that ships the name: ADR-0150 D3 makes a reference in an - * environment-authored overlay the environment's, resolved as a caller with no - * package. So the reader has to tell the loader's own body from the shipping - * package's declared `.custom` override (ADR-0146 D9 item 1), which is armed - * over it under the same name — where `packagedFlowOwner` answers the - * shipping package for both. - * - * The harness is #28717's (`flow-declared-override-first-boot-pull`): an - * ObjectKernel, ObjectQL's metadata protocol over driver-sql on a - * better-sqlite3 file, the shipping package registered through the - * `manifest` service and the real automation plugin, booted twice on one file - * so the stored rows are read back cold. Measured at the boot pull (from a - * plugin `start()` after the automation plugin's) and after `kernel:ready`'s - * re-bind from the protocol's view, the two steps that arm a body. - */ - -import { afterEach, describe, expect, it, vi } from 'vitest'; -import { mkdtempSync, rmSync } from 'node:fs'; -import { tmpdir } from 'node:os'; -import { join } from 'node:path'; -import { ObjectKernel, ObjectLogger, type Plugin, type PluginContext } from '@objectstack/core'; -import { ObjectQLPlugin, type ObjectQL } from '@objectstack/objectql'; -import { SqlDriver } from '@objectstack/driver-sql'; -import { defineStack } from '@objectstack/spec'; -import type { AutomationContext } from '@objectstack/spec/contracts'; -import { AutomationServicePlugin } from './plugin.js'; -import type { AutomationEngine, FlowTrigger, FlowTriggerBinding } from './engine.js'; -import { installDefaultOrganization } from './default-organization.testkit.js'; - -const BASE = 'com.acme.crm'; -const PAIR = `${BASE}.custom`; -const FLOW = 'crm_ticket_created'; -const TICKET = 'crm_ticket'; -const SYS = { isSystem: true } as const; - -/** The base flow, record-triggered on TICKET; `marker` names the body by its label and its end node. */ -const ticketFlow = (marker: string, extra: Record = {}) => ({ - name: FLOW, - label: marker, - type: 'autolaunched', - status: 'active', - nodes: [ - { - id: 'start', - type: 'start', - label: 'Start', - config: { objectName: TICKET, triggerType: 'record-after-create' }, - }, - { id: `end_${marker.toLowerCase()}`, type: 'end', label: 'End' }, - ], - edges: [{ id: 'e1', source: 'start', target: `end_${marker.toLowerCase()}` }], - ...extra, -}); - -const pluginManifest = (id: string) => ({ - id, - namespace: 'crm', - version: '1.0.0', - type: 'plugin', - name: 'crm', -}); - -/** The shipping package: one object and the base flow over it. */ -const shippingStack = () => - defineStack( - { - manifest: pluginManifest(BASE), - objects: [{ name: TICKET, label: 'Ticket', fields: { title: { name: 'title', label: 'Title', type: 'text' } } }], - flows: [ticketFlow('BASE')], - } as never, - { strict: false }, - ) as Record; - -type Row = 'override' | 'legacy'; - -const storedRow = (row: Row) => - row === 'override' - ? { - id: 'meta_override', - name: FLOW, - type: 'flow', - state: 'active', - package_id: PAIR, - metadata: JSON.stringify(ticketFlow('OVERRIDE', { overrides: { package: BASE, basedOn: '1.0.0' } })), - } - : { - id: 'meta_legacy', - name: FLOW, - type: 'flow', - state: 'active', - package_id: null, - metadata: JSON.stringify(ticketFlow('LEGACY')), - }; - -/** What each record change saw armed, and which body's end node its run reached. */ -interface Fired { - armedLabel: string | undefined; -} - -function objectqlRecordTrigger(ql: () => ObjectQL, automation: () => AutomationEngine, fired: Fired[]): FlowTrigger { - const packageOf = (flowName: string) => `qa-31790-trigger:${flowName}`; - return { - type: 'record_change', - start(binding: FlowTriggerBinding, callback: (ctx: AutomationContext) => Promise) { - ql().unregisterHooksByPackage(packageOf(binding.flowName)); - ql().registerHook( - 'afterInsert', - async (hook: { result?: unknown }) => { - const armed = (await automation().getFlow(binding.flowName)) as { label?: string } | null; - fired.push({ armedLabel: armed?.label }); - await callback({ record: hook.result, object: binding.object, event: 'afterInsert' } as never); - }, - { object: binding.object, packageId: packageOf(binding.flowName) }, - ); - }, - stop(flowName: string) { - ql().unregisterHooksByPackage(packageOf(flowName)); - }, - }; -} - -const kernels: ObjectKernel[] = []; -const dirs: string[] = []; -afterEach(async () => { - vi.restoreAllMocks(); - for (const k of kernels.splice(0)) await k.shutdown().catch(() => {}); - for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true }); -}); - -/** - * Boot the composition on `file`. `start` runs in a plugin that starts after - * the automation plugin: after the boot pull, before `kernel:ready`. - */ -async function boot(file: string, start: (ql: ObjectQL, automation: AutomationEngine) => Promise) { - const kernel = new ObjectKernel({ logger: { level: 'fatal' }, gracefulShutdown: false } as never); - kernels.push(kernel); - const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: file }, useNullAsDefault: true }); - const fired: Fired[] = []; - let captured: PluginContext | undefined; - await kernel.use({ - name: 'test.driver.sqlite', - type: 'standard', - version: '1.0.0', - async init(ctx: PluginContext) { - ctx.registerService('driver.default', driver); - }, - } as Plugin); - await kernel.use(new ObjectQLPlugin()); - await kernel.use(new AutomationServicePlugin({ suspendedRunStore: 'memory' })); - await kernel.use({ - name: 'test.shipping-package', - type: 'standard', - version: '1.0.0', - dependencies: ['com.objectstack.engine.objectql', 'com.objectstack.service-automation'], - async init(ctx: PluginContext) { - captured = ctx; - const stack = shippingStack(); - await ctx.getService<{ register(m: unknown): Promise }>('manifest') - .register({ ...(stack.manifest as object), ...stack }); - const ql = () => ctx.getService('objectql'); - const automation = () => ctx.getService('automation'); - automation().registerTrigger(objectqlRecordTrigger(ql, automation, fired)); - }, - async start(ctx: PluginContext) { - const ql = ctx.getService('objectql'); - await installDefaultOrganization(ql as never); - await start(ql, ctx.getService('automation')); - }, - } as Plugin); - await kernel.bootstrap(); - return { kernel, fired, automation: kernel.getService('automation'), ctx: captured! }; -} - -/** The first boot stores `rows`, in this order; the second, cold, is measured. */ -async function measuredBoot(rows: readonly Row[], start: (ql: ObjectQL, automation: AutomationEngine) => Promise) { - const dir = mkdtempSync(join(tmpdir(), 'qa-31790-')); - dirs.push(dir); - const file = join(dir, 'store.db'); - const first = await boot(file, async (ql) => { - for (const row of rows) await ql.insert('sys_metadata', storedRow(row), { context: SYS } as never); - }); - await first.kernel.shutdown(); - kernels.splice(kernels.indexOf(first.kernel), 1); - const warn = vi.spyOn(ObjectLogger.prototype, 'warn'); - const measured = await boot(file, start); - const collisions = warn.mock.calls - .map(([message]) => String(message)) - .filter((message) => message.includes('Flow name collision') && message.includes(`'${FLOW}'`)); - return { ...measured, collisions }; -} - - -/** What the reader answers at the boot pull, and after `kernel:ready`. */ -async function readings(rows: readonly Row[]) { - let atPull: { armed: string | undefined; label: string | undefined } | undefined; - const { automation } = await measuredBoot(rows, async (_ql, engine) => { - atPull = { - armed: engine.armedFlowPackage(FLOW), - label: ((await engine.getFlow(FLOW)) as { label?: string } | null)?.label, - }; - }); - return { - atPull, - afterReady: { - armed: automation.armedFlowPackage(FLOW), - label: ((await automation.getFlow(FLOW)) as { label?: string } | null)?.label, - }, - owner: automation.packagedFlowOwner(FLOW), - }; -} - -describe('[ADR-0150 D3] armedFlowPackage names the package of the body the engine runs', () => { - it('the loader\'s own body, nothing stored: the shipping package, at the boot pull and after kernel:ready', async () => { - const r = await readings([]); - expect(r.owner).toBe(BASE); - expect(r.atPull).toEqual({ armed: BASE, label: 'BASE' }); - expect(r.afterReady).toEqual({ armed: BASE, label: 'BASE' }); - }); - - it('the declared .custom override armed over it: no package, while packagedFlowOwner still names the shipping package', async () => { - const r = await readings(['override']); - expect(r.owner, 'control: the loader\'s set holds the name').toBe(BASE); - expect(r.atPull).toEqual({ armed: undefined, label: 'OVERRIDE' }); - expect(r.afterReady).toEqual({ armed: undefined, label: 'OVERRIDE' }); - }); - - it('the override beside a legacy package-less row: no package', async () => { - const r = await readings(['legacy', 'override']); - expect(r.atPull).toEqual({ armed: undefined, label: 'OVERRIDE' }); - expect(r.afterReady).toEqual({ armed: undefined, label: 'OVERRIDE' }); - }); - - it('a legacy package-less row alone is shadowed (ADR-0126 §2), so the loader\'s body runs and it is the shipping package\'s', async () => { - const r = await readings(['legacy']); - expect(r.atPull).toEqual({ armed: BASE, label: 'BASE' }); - expect(r.afterReady).toEqual({ armed: BASE, label: 'BASE' }); - }); - - it('an override stored at runtime and re-armed by the metadata:reloaded re-sync: no package; deleted, the shipping package again', async () => { - const { automation, ctx } = await measuredBoot([], async () => {}); - expect(automation.armedFlowPackage(FLOW)).toBe(BASE); - const ql = ctx.getService('objectql'); - await ql.insert('sys_metadata', storedRow('override'), { context: SYS } as never); - await ctx.trigger('metadata:reloaded'); - expect(((await automation.getFlow(FLOW)) as { label?: string } | null)?.label).toBe('OVERRIDE'); - expect(automation.armedFlowPackage(FLOW)).toBeUndefined(); - await ql.delete('sys_metadata', { where: { id: 'meta_override' }, context: SYS } as never); - await ctx.trigger('metadata:reloaded'); - expect(((await automation.getFlow(FLOW)) as { label?: string } | null)?.label).toBe('BASE'); - expect(automation.armedFlowPackage(FLOW)).toBe(BASE); - }); - - it('a body registered with no precedence verdict (an authoring door, a direct caller) is no package\'s, even under a shipped name', async () => { - const { automation } = await measuredBoot([], async () => {}); - expect(automation.armedFlowPackage(FLOW)).toBe(BASE); - automation.registerFlow(FLOW, ticketFlow('DIRECT')); - expect(automation.packagedFlowOwner(FLOW)).toBe(BASE); - expect(automation.armedFlowPackage(FLOW)).toBeUndefined(); - expect(automation.armedFlowPackage('no_such_flow')).toBeUndefined(); - }); -}); diff --git a/packages/services/service-automation/src/flow-precedence.ts b/packages/services/service-automation/src/flow-precedence.ts index c5aa4a49bc7..56e9626922d 100644 --- a/packages/services/service-automation/src/flow-precedence.ts +++ b/packages/services/service-automation/src/flow-precedence.ts @@ -111,15 +111,6 @@ export interface FlowPrecedenceWinner { definition: unknown; /** Present only when this name had more than one contender. */ shadowing?: FlowShadowingRecord; - /** - * [ADR-0150 D3] What the winner is — the classification the receipt's - * `armed` records — for a name with more than one contender. A name with - * one is not classified here (precedence decides nothing there, and asks - * the loader's set nothing): ask {@link describeArmedFlowContender}. The - * caller hands the answer to `AutomationEngine.registerFlow`, so the engine - * knows whose body it runs (`armedFlowPackage`). - */ - armedFrom?: FlowContender; } /** @@ -179,47 +170,6 @@ function classifyContender(item: unknown, owner: string | undefined, installed: }; } -/** - * [ADR-0150 D3] What a name's ONLY contender is — the body - * {@link resolveFlowPrecedence} arms for an uncontested name, which it does - * not classify — for `AutomationEngine.registerFlow`'s `armedFrom`. Asks the - * loader's set once, for that name. See {@link armedContender}. - */ -export function describeArmedFlowContender( - item: unknown, - packagedFlowOwner: PackagedFlowSource | undefined, - installed: InstalledManifestLookup, -): FlowContender { - const owner = loaderSetOwner(packagedFlowOwner, (item as { name?: unknown } | null | undefined)?.name); - return armedContender(item, classifyContender(item, owner, installed), owner, installed); -} - -/** - * [ADR-0150 D3] What a name's ONLY contender is, for its winner's `armedFrom`: - * {@link classifyContender}'s answer, except that a body the protocol's view - * serves in the shipping package's slot as that package's declared override - * is the `override` it is. - * - * The view serves the override (ADR-0146 D9 item 1) as one entry in place of - * the loader's body, with the package's envelope on it — measured on a real - * kernel: `_packageId` the base, `_provenance: 'package'` — and the stored - * row's binding ({@link storedRowBindingOf}) does not travel on that copy, so - * the classification reads it as the loader's body. What the copy keeps is - * its own declaration, `overrides.package` = the owner: the view serves a body - * in the owner's slot only after the one served-override predicate admitted - * its row by the row's column, and the loader's own body declares no override - * of its own package. ⛔ Only this narrows: a body that does not declare it - * stays as classified. Two or more contenders are judged on the registry's - * entries, which keep their binding, by the precedence below. - */ -function armedContender(item: unknown, contender: FlowContender, owner: string | undefined, installed: InstalledManifestLookup): FlowContender { - if (contender.source !== 'package' || owner === undefined) return contender; - const declared = (item as { overrides?: { package?: unknown } } | null | undefined)?.overrides?.package; - if (declared !== owner) return contender; - const pair = pairOf(owner, installed); - return { source: 'override', ...(pair.ok ? { packageId: pair.value } : {}) }; -} - /** * Classify one registry body's provenance. * @@ -441,7 +391,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, armedFrom: armed.contender }); + winners.push({ name, definition: armed.definition }); continue; } // [#20913] Say WHY this one is armed, per case — the cases are @@ -500,7 +450,6 @@ export function resolveFlowPrecedence( name, definition: armed.definition, shadowing: { name, armed: armed.contender, shadowed }, - armedFrom: armed.contender, }); } return winners; diff --git a/packages/services/service-automation/src/plugin.ts b/packages/services/service-automation/src/plugin.ts index f29035dbb8f..68793fa1664 100644 --- a/packages/services/service-automation/src/plugin.ts +++ b/packages/services/service-automation/src/plugin.ts @@ -28,7 +28,7 @@ import { resolvePackageScopedName } from '@objectstack/objectql'; import { describeThrownForLog, thrownMessageText } from './thrown-cause-diagnostics.js'; import { defaultEnvCredentialResolver, type CredentialResolver } from './credential-resolver.js'; import { registerFlowCredentialRedactor } from './flow-credential-projection.js'; -import { describeArmedFlowContender, resolveFlowPrecedence, renderFlowContender } from './flow-precedence.js'; +import { resolveFlowPrecedence, renderFlowContender } from './flow-precedence.js'; import { installBuiltinNodes, rearmSuspendedWaitTimers } from './builtin/index.js'; import { resolveRunDataContext } from './runtime-identity.js'; import { SysAutomationRun } from './sys-automation-run.object.js'; @@ -2244,7 +2244,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, { armedFrom: entry.armedFrom }); + this.engine.registerFlow(entry.name, def as never); this.syncedFlowNames.add(entry.name); // The receipt, so the shadowed contender is observable at all. if (entry.shadowing) this.engine.recordFlowShadowing(entry.shadowing); @@ -5327,29 +5327,21 @@ export class AutomationServicePlugin implements Plugin { */ private resolveFlowContenders(ctx: PluginContext, items: readonly unknown[]) { const engine = this.engine; - const reader = engine ? (name: string) => engine.packagedFlowOwner(name) : undefined; - const installed = installedManifestsOf(objectqlRegistryOf(ctx)); // [ADR-0150 D3] The same reader `init()` attaches to the engine // (`setFlowNameResolver`), asked for a caller with no package — the // question `registerFlow` asks — so the collision warning says a name // is refused exactly when the engine refuses it. const resolver = flowNameResolver(ctx); - // [ADR-0150 D3] Every winner carries what it is, so `registerFlow` - // records whose body the engine runs (`armedFlowPackage`): a contested - // name's from the precedence, an uncontested one's asked here. return resolveFlowPrecedence( items, ctx.logger, - reader, - installed, + engine ? (name) => engine.packagedFlowOwner(name) : undefined, + installedManifestsOf(objectqlRegistryOf(ctx)), (name) => { const resolution = resolver(name, null); return resolution?.status === 'refused' ? resolution.message : undefined; }, - ).map((entry) => ({ - ...entry, - armedFrom: entry.armedFrom ?? describeArmedFlowContender(entry.definition, reader, installed), - })); + ); } /** @@ -5402,7 +5394,7 @@ export class AutomationServicePlugin implements Plugin { continue; } try { - this.engine.registerFlow(entry.name, entry.definition as never, { armedFrom: entry.armedFrom }); + this.engine.registerFlow(entry.name, entry.definition as never); resynced++; } catch (err) { // #5048 — see ./thrown-cause-diagnostics.ts. @@ -5478,7 +5470,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, { armedFrom: entry.armedFrom }); + this.engine.registerFlow(entry.name, entry.definition as never); this.syncedFlowNames.add(entry.name); bound++; } catch (err) { @@ -5663,7 +5655,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, { armedFrom: entry.armedFrom }); + engine.registerFlow(name, entry.definition as never); this.mutationArmedFlows.set(name, stableStringify(entry.definition)); armed.push(name); } catch (err) { From b7cf21da693d2bf13d74ea2dbca9fab14347e615 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 08:01:58 +0000 Subject: [PATCH 7/8] chore(changeset): the approval node's refusal names its remedy Claude-Session: https://claude.ai/code/session_01ADHkmPfjQpqnk93rr9esh8 Co-authored-by: Claude --- .changeset/31790-queue-reads-declaring-package.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/31790-queue-reads-declaring-package.md b/.changeset/31790-queue-reads-declaring-package.md index f740f60c4fd..44f4976f43e 100644 --- a/.changeset/31790-queue-reads-declaring-package.md +++ b/.changeset/31790-queue-reads-declaring-package.md @@ -27,4 +27,4 @@ Narrowing, per ADR-0150 D3. A rule or step in package P whose queue name P canno - P's dependency D holds the name but is disabled, and an unrelated U holds it too (`outside-closure`, naming U; a disabled package holds no queue for this read); - the only holder is an item authored in the environment (`outside-closure`, naming the environment). -An assignment rule then writes the row ownerless and in no queue, and warns; an approval node refuses to open, naming every candidate, as it does for a queue whose read failed. An organization's `sys_queue` row under a name no package declares is unchanged. To resolve it, declare a dependency on the package whose queue you mean, enable it, or ship the queue in P. Measured first-party: 0 (no first-party package declares a queue, an assignment rule or a `queue` approver). +An assignment rule then writes the row ownerless and in no queue, and warns; an approval node refuses to open, naming every candidate and the remedy below. An organization's `sys_queue` row under a name no package declares is unchanged. To resolve it, declare a dependency on the package whose queue you mean, enable it, or ship the queue in P. Measured first-party: 0 (no first-party package declares a queue, an assignment rule or a `queue` approver). From 00fb75d5e0dab9ee7092d4e8d36bcc070d3f6d0a Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 09:32:49 +0000 Subject: [PATCH 8/8] fix(plugin-approvals): an approval step reads its queue from the package of the flow body that runs The step's package is now the automation engine's armedFlowPackage: the shipping package for its own body, none for an environment-authored override of it. So an override's step, its fallback slate and the decide-time tally read their queue names environment-wide, as they did before package-scoped reads, instead of from the package the override customizes. Claude-Session: https://claude.ai/code/session_01ADHkmPfjQpqnk93rr9esh8 Co-authored-by: Claude --- .../31790-queue-reads-declaring-package.md | 2 +- .../src/approval-service.test.ts | 74 ++++++++++++++++--- .../plugin-approvals/src/approval-service.ts | 35 +++++---- 3 files changed, 85 insertions(+), 26 deletions(-) diff --git a/.changeset/31790-queue-reads-declaring-package.md b/.changeset/31790-queue-reads-declaring-package.md index 44f4976f43e..d6d6cccb16c 100644 --- a/.changeset/31790-queue-reads-declaring-package.md +++ b/.changeset/31790-queue-reads-declaring-package.md @@ -10,7 +10,7 @@ Metadata-protocol: none -A declared assignment rule (`assignmentRules`) now passes the package that ships it as `callerPackageId` when it resolves its queue and reads the queue's members. An approval step passes the package that ships its flow (the automation engine's `packagedFlowOwner`) when it expands a `queue` approver, on the node's slate, its fallback slate and the tally of a request opened before the slate snapshot existed. The queue service resolves the name from that package (ADR-0150 D3): the package's own queue, else the one holder in its declared dependencies, else a refusal naming every candidate. An organization's own assignment rule, a declared rule no package ships and a flow authored in the deployment read environment-wide, exactly as before. +A declared assignment rule (`assignmentRules`) now passes the package that ships it as `callerPackageId` when it resolves its queue and reads the queue's members. An approval step passes the package of the flow body the engine runs (the automation engine's `armedFlowPackage`) when it expands a `queue` approver, on the node's slate, its fallback slate and the tally of a request opened before the slate snapshot existed. The queue service resolves the name from that package (ADR-0150 D3): the package's own queue, else the one holder in its declared dependencies, else a refusal naming every candidate. An organization's own assignment rule, a declared rule no package ships and a flow authored in the deployment read environment-wide, exactly as before. So does a step in an environment-authored override of a packaged flow (a declared `.custom` override, ADR-0146 D9): a reference written in an overlay is the environment's (ADR-0150 D3), never read from the package it customizes. When a `queue` approver's name is refused this way, the approval node still refuses with `APPROVER_DIRECTORY_UNREADABLE`, but the message now says the name was refused (ADR-0150 D3), with the refusal and its remedy, instead of asking for the flow to run again once the directory can be read. Its `retryable` is `false`. diff --git a/packages/plugins/plugin-approvals/src/approval-service.test.ts b/packages/plugins/plugin-approvals/src/approval-service.test.ts index 937a11eb6dc..17a6b088794 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.test.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.test.ts @@ -4410,21 +4410,22 @@ describe('ApprovalService — a queue approver asks the queue service to refuse } }); -// [ADR-0150 D3] An approval step is declared inside its flow, so the queue a -// `queue` approver names is read from the package that ships the flow — the -// automation engine's `packagedFlowOwner` — passed to the queue service as -// `callerPackageId`. The double stands in for `@objectstack/plugin-sharing`'s +// [ADR-0150 D3] An approval step is written in the flow body the engine runs, +// so the queue a `queue` approver names is read from that body's package — the +// automation engine's `armedFlowPackage`: the shipping package for its own +// body, none for an environment-authored override of it — passed to the queue +// service as `callerPackageId`. The double stands in for `@objectstack/plugin-sharing`'s // service (not a dependency of this package): the ONE resolver, // `resolvePackageScopedName`, over the holders the listing serves (a disabled // package's left out, as plugin-sharing's `listedHoldersView` does), and under // `onFailedRead: 'refuse'` a refused name rejects with the refusal, as the // contract says. -describe('ApprovalService — a queue approver reads its queue name from the package that ships the flow (ADR-0150 D3)', () => { +describe('ApprovalService — a queue approver reads its queue name from the package of the flow body that runs (ADR-0150 D3)', () => { const P = 'com.acme.p'; const D = 'com.acme.d'; const U = 'com.acme.u'; - /** Who staffs each holder's `support` queue in t1. */ - const STAFF: Record = { [D]: ['u_d'], [U]: ['u_u'] }; + /** Who staffs each holder's `support` queue in t1 (`environment`: the item authored in the environment). */ + const STAFF: Record = { [D]: ['u_d'], [U]: ['u_u'], environment: ['u_env'] }; const manifest = (id: string, deps: string[] = []) => ({ id, name: id, version: '1.0.0', type: 'app', namespace: id.split('.').pop(), @@ -4439,7 +4440,13 @@ describe('ApprovalService — a queue approver reads its queue name from the pac return registry; }; - const setup = (registry: SchemaRegistry, flowPackage: string | undefined) => { + /** + * `flowPackage`: the package that ships `deal_approval`. `overridden`: the + * body armed under the name is an environment-authored override of it (a + * declared `.custom` override), so the engine answers no package for the + * body that runs while `packagedFlowOwner` still names the shipping one. + */ + const setup = (registry: SchemaRegistry, flowPackage: string | undefined, overridden = false) => { const engine = makeFakeEngine(); const asked: unknown[] = []; const refusals: PackageScopedRefusal[] = []; @@ -4467,12 +4474,15 @@ describe('ApprovalService — a queue approver reads its queue name from the pac } return []; } - if (resolution.status !== 'resolved' || resolution.holder.kind !== 'package' || org !== 't1') return []; - return [...(STAFF[resolution.holder.packageId] ?? [])]; + if (resolution.status !== 'resolved' || org !== 't1') return []; + return [...(STAFF[resolution.holder.kind === 'package' ? resolution.holder.packageId : resolution.holder.kind] ?? [])]; }, }), }); - svc.attachAutomation({ packagedFlowOwner: (flow: string) => (flow === 'deal_approval' ? flowPackage : undefined) } as any); + svc.attachAutomation({ + packagedFlowOwner: (flow: string) => (flow === 'deal_approval' ? flowPackage : undefined), + armedFlowPackage: (flow: string) => (flow === 'deal_approval' && !overridden ? flowPackage : undefined), + } as any); return { engine, svc, asked, refusals }; }; const queueNode = (configExtra: Record = {}) => ({ @@ -4527,6 +4537,48 @@ describe('ApprovalService — a queue approver reads its queue name from the pac expect(engine._tables['sys_approval_request'] ?? []).toEqual([]); }); + it('an environment-authored override of P\'s flow reads environment-wide, as on main: its step reaches the environment\'s queue P cannot reach', async () => { + const registry = registryOf([[P, []]], []); + registry.registerItem('queue', { name: 'support', label: 'Support', members: [] }, 'name'); + // CONTROL: from P the name is refused outside P's closure — so a step read from P would not open. + expect(resolvePackageScopedName(registry as never, { type: 'queue', name: 'support', callerPackageId: P })) + .toMatchObject({ status: 'refused', reason: 'outside-closure' }); + const { engine, svc, asked, refusals } = setup(registry, P, true); + const req = await svc.openNodeRequest(queueNode(), CTX) as any; + expect(req.pending_approvers).toEqual(['u_env']); + expect(asked).toEqual([['support', 't1', { purpose: 'addressing', onFailedRead: 'refuse' }]]); + expect(refusals).toEqual([]); + + // The decide-time tally of a request opened before the slate snapshot reads the same body's package. + const tallied = await svc.openNodeRequest({ + ...queueNode({ approvers: [{ type: 'user', value: 'u2' }, { type: 'queue', value: 'support' }], behavior: 'unanimous' }), + recordId: 'opp2', runId: 'run_2', record: { id: 'opp2', amount: 100 }, + }, CTX) as any; + const row = engine._tables['sys_approval_request'].find((r: any) => r.id === tallied.id)!; + const config = JSON.parse(row.node_config_json); + delete config.__approverGroups; + row.node_config_json = JSON.stringify(config); + const decided = await svc.decideNode(tallied.id, { decision: 'approve', actorId: 'u2' }, SYS); + expect(decided.finalized).toBe(false); + expect(asked.at(-1)).toEqual(['support', 't1', { purpose: 'addressing', onFailedRead: 'refuse' }]); + expect(engine._tables['sys_approval_request'].find((r: any) => r.id === tallied.id)!.pending_approvers).toBe('u_env'); + expect(refusals).toEqual([]); + }); + + it('the fallback slate of an environment-authored override reads environment-wide too', async () => { + const registry = registryOf([[P, []]], []); + registry.registerItem('queue', { name: 'support', label: 'Support', members: [] }, 'name'); + const { svc, asked, refusals } = setup(registry, P, true); + const fallen = await svc.openNodeRequest(queueNode({ + approvers: [{ type: 'user', value: 'u_gone' }], + onEmptyApprovers: 'fallback', + fallbackApprovers: [{ type: 'queue', value: 'support' }], + }), CTX) as any; + expect(fallen.pending_approvers).toEqual(['u_env']); + expect(asked.at(-1)).toEqual(['support', 't1', { purpose: 'addressing', onFailedRead: 'refuse' }]); + expect(refusals).toEqual([]); + }); + it('CONTROL — a flow authored in this deployment reads environment-wide, as before: the same two holders are refused, naming both', async () => { const { svc, asked, refusals } = setup(registryOf([[D, []], [U, []], [P, [D]]], [D, U]), undefined); const refusal = await svc.openNodeRequest(queueNode(), CTX).then(() => null, (e: unknown) => e); diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index c66eb10d564..13112f2c9e0 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -227,17 +227,21 @@ export interface ApprovalResumeSurface { /** Flow definition lookup, used to derive step-progress display data. */ getFlow?(name: string): Promise; /** - * [ADR-0150 D3] The package that ships the flow `name`, per the loader's - * set, or `undefined` for a flow authored in this deployment. Read by - * {@link ApprovalService.flowPackageOf}: an approval step is declared inside - * its flow, so the queue an approver names is read from that package. + * [ADR-0150 D3] The package whose OWN body the engine runs for the flow + * `name` — the shipping package when the armed body is the loader's, and + * `undefined` for a declared `.custom` override or any other + * environment-authored body, and for a flow authored in this deployment. + * Read by {@link ApprovalService.flowPackageOf}: an approval step is written + * in the body that runs, so the queue an approver names is read from that + * body's package, and an override's step from no package (ADR-0150 D3: a + * reference in an overlay is the environment's). * - * ⚠️ Declares a method `AutomationEngine` ALREADY implements publicly - * (`packagedFlowOwner`, the one the engine's own subflow addressing reads); - * it widens no engine surface. Optional: absent, every step reads its queue + * ⚠️ Declares a method `AutomationEngine` implements publicly + * (`armedFlowPackage`, the reader its own subflow addressing reads); it + * widens no engine surface. Optional: absent, every step reads its queue * names environment-wide, as before. */ - packagedFlowOwner?(name: string): string | undefined; + armedFlowPackage?(name: string): string | undefined; /** * Terminally cancel a suspended run (ADR-0044). Used when a recall lands * during a revision window — the run is paused at the revise-window node, @@ -3646,14 +3650,17 @@ export class ApprovalService implements IApprovalService { /** * [ADR-0150 D3] The package the approval step of flow `flowName` is - * declared in: the package that ships the flow, as the automation engine - * answers it (`packagedFlowOwner`, the reader its own subflow addressing - * takes the caller's package from), or `null` for a flow authored in this - * deployment, a request with no flow, and an engine that cannot say. + * written in: the package of the body the engine runs for the flow, as the + * engine answers it (`armedFlowPackage`, the reader its own subflow + * addressing takes the caller's package from) — the shipping package for + * its own body, and `null` for an environment-authored override of it, a + * flow authored in this deployment, a request with no flow, and an engine + * that cannot say. ⛔ Not `packagedFlowOwner`: it names the package that + * ships the NAME, whichever body is armed under it. */ private flowPackageOf(flowName: string | null | undefined): string | null { - if (!flowName || typeof this.automation?.packagedFlowOwner !== 'function') return null; - const owner = this.automation.packagedFlowOwner(flowName); + if (!flowName || typeof this.automation?.armedFlowPackage !== 'function') return null; + const owner = this.automation.armedFlowPackage(flowName); return typeof owner === 'string' && owner !== '' ? owner : null; }