diff --git a/.changeset/31790-queue-reads-declaring-package.md b/.changeset/31790-queue-reads-declaring-package.md new file mode 100644 index 00000000000..d6d6cccb16c --- /dev/null +++ b/.changeset/31790-queue-reads-declaring-package.md @@ -0,0 +1,30 @@ +--- +'@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-②: 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 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`. + +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: + +- 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 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). 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..17a6b088794 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,217 @@ 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 +// 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)', () => { + 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'] }; + + 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; + }; + + /** + * `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[] = []; + 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' || 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), + armedFlowPackage: (flow: string) => (flow === 'deal_approval' && !overridden ? 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 }); + // 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', + 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('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); + 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 }], + }); + }); + + 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..13112f2c9e0 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, @@ -225,6 +226,22 @@ export interface ApprovalResumeSurface { }): Promise; /** 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 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` 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. + */ + 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, @@ -1253,6 +1270,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 @@ -1267,8 +1313,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; @@ -1289,13 +1339,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); @@ -2591,6 +2652,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 +2711,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 +2743,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 +2878,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 +3630,38 @@ 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 + * 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?.armedFlowPackage !== 'function') return null; + const owner = this.automation.armedFlowPackage(flowName); + return typeof owner === 'string' && owner !== '' ? owner : null; } /** @@ -4372,6 +4468,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 +4509,7 @@ export class ApprovalService implements IApprovalService { now: nowDate.getTime(), substitutions, groups, exprCtx, resolvedFrom, + callerPackageId, }, ), 'approvers', groups); @@ -4469,6 +4569,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 +5312,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 = {}; } 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'],