From d1ef745e185c01a62239ed506f90615bdbe444f7 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 07:28:31 +0000 Subject: [PATCH 1/4] feat(approvals): the opening check's conditions are reported where a flow or an object is published The metadata protocol gains addAuthoringGate: a gate added beside a type's owner gate, which runs after it on every save and restore and also when a draft is promoted to active. The approvals plugin adds publish gates on flow and object that judge an active write by the conditions an approval opens on (ADR-0162 D5), as the engine will hold things once the write lands, and refuse it with the same sentences an approval's first request is refused with, as a 422 VALIDATION_FAILED in the author's locale. A draft, a callee that cannot be read and a host with no job service are not refused at publish; the first request still refuses them. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5nzgcVrZ8Neqqd1AFi --- .changeset/37766-publish-gate-approvals.md | 25 ++ .changeset/37766-publish-gate-door.md | 17 + .../src/protocol-authoring-gate.ts | 31 +- .../src/protocol-class-head.ts | 12 + .../src/protocol-history-and-publish.ts | 19 +- .../protocol.add-authoring-gate-37766.test.ts | 287 +++++++++++++++++ packages/metadata-protocol/src/protocol.ts | 38 +-- .../src/approval-opening-check.ts | 2 +- .../src/approval-opening-refusal.ts | 33 +- .../src/approval-publish-check.test.ts | 295 ++++++++++++++++++ .../src/approval-publish-check.ts | 238 ++++++++++++++ ...val-publish-gate-37766.integration.test.ts | 164 ++++++++++ .../src/approval-publish-gate.ts | 93 ++++++ .../plugin-approvals/src/approval-service.ts | 48 +++ .../plugin-approvals/src/approvals-plugin.ts | 15 + .../src/translations/messages.ts | 11 + 16 files changed, 1292 insertions(+), 36 deletions(-) create mode 100644 .changeset/37766-publish-gate-approvals.md create mode 100644 .changeset/37766-publish-gate-door.md create mode 100644 packages/metadata-protocol/src/protocol.add-authoring-gate-37766.test.ts create mode 100644 packages/plugins/plugin-approvals/src/approval-publish-check.test.ts create mode 100644 packages/plugins/plugin-approvals/src/approval-publish-check.ts create mode 100644 packages/plugins/plugin-approvals/src/approval-publish-gate-37766.integration.test.ts create mode 100644 packages/plugins/plugin-approvals/src/approval-publish-gate.ts diff --git a/.changeset/37766-publish-gate-approvals.md b/.changeset/37766-publish-gate-approvals.md new file mode 100644 index 00000000000..75a24ecacb5 --- /dev/null +++ b/.changeset/37766-publish-gate-approvals.md @@ -0,0 +1,25 @@ +--- +'@objectstack/plugin-approvals': patch +--- + +feat(approvals): a flow or an object that an approval could not open on is refused where it is published (ADR-0162 Execution item 7, reported at authoring) + +Clause-②: yes (widening) +Metadata-protocol: none + +Widened: `ApprovalService` gains `judgePublishedItem(item)`. The plugin's message catalog gains the sentence `approvalPublishRefusedLead` in all 11 locale packs. + +At kernel:ready the plugin adds publish gates for `flow` and `object` beside the owners' gates. They judge a write that goes `active` by the conditions an approval opens on (the check at an approval's first request, ADR-0162 D5), as the engine will hold things once the write lands. + +- **A flow.** It is judged as an approval's root, together with every flow that calls it through a `subflow` or a `map`, to any depth, with the written body in place. The walk up the callers ends on a flow that calls itself and on flows that call each other. It stops after 64 roots: past that, nothing is refused for the cap, and one warning says so. +- **An object.** Every flow that can start on one of its records, or maps over them, is judged with the written object in place. Only gaps on the written object are reported. + +The refusal is a 422 `VALIDATION_FAILED` that names the item, then gives one sentence per gap: the flow, the step, the object, the field and what is missing, in the first locale the write door states. These are the same sentences an approval's first request is refused with. + +Not refused at publish: +- a draft (it is judged when it is promoted); +- a flow that a node calls and the engine does not hold; +- a host with no `job` service (the first request still refuses both); +- an application in which no object declares `closedStates`, where nothing is read. + +A judge that fails is logged, and the write goes ahead. The rule stays the refusal at the approval's first request: the objects and the flows are published apart, and only that request has them all in hand. diff --git a/.changeset/37766-publish-gate-door.md b/.changeset/37766-publish-gate-door.md new file mode 100644 index 00000000000..91a1734fecf --- /dev/null +++ b/.changeset/37766-publish-gate-door.md @@ -0,0 +1,17 @@ +--- +'@objectstack/metadata-protocol': patch +--- + +feat(metadata-protocol): a plugin can add an authoring gate beside a type's owner gate, and an added gate also judges a draft's promotion + +Clause-②: yes (widening) +Metadata-protocol: none + +Widened: `ObjectStackProtocolImplementation` gains `addAuthoringGate(type, gate)`. + +`registerAuthoringGate` keeps one gate per type, and a second registration still replaces the first. A plugin that needs to judge a type another plugin owns now adds its gate with `addAuthoringGate` instead. plugin-security owns `object`, for example. + +- An added gate runs after the owner gate, in the order gates were added, on every write the owner gate runs on: a save in either mode, and a restore. +- An added gate also runs when a draft is promoted to `active` (`publishMetaItem`, a package publish, a judge-only call), with `state: 'active'`. The owner gate still does not run there. +- A declared `package-author` channel runs no added gate, as it runs no owner gate. +- A throw from an added gate refuses the write before it is stored, as an owner gate's does. diff --git a/packages/metadata-protocol/src/protocol-authoring-gate.ts b/packages/metadata-protocol/src/protocol-authoring-gate.ts index 64eef5c1272..a486395935d 100644 --- a/packages/metadata-protocol/src/protocol-authoring-gate.ts +++ b/packages/metadata-protocol/src/protocol-authoring-gate.ts @@ -47,6 +47,7 @@ */ import type { ObjectStackProtocolImplementation } from './protocol.js'; +import type { MetadataAuthoringGateContext } from './protocol-authoring-channel.js'; import { permissionSetOwnerBindingRefusal, runtimeHookWithoutBodyRefusal } from './protocol.js'; import { objectBodyExtensionFieldSuffixRefusal } from './protocol-extension-field-suffix.js'; import { datasourceCredentialsRefSaveRefusal } from './protocol-datasource-credentials-ref.js'; @@ -76,6 +77,7 @@ export interface AuthoringGateHost { assertRuntimeAuthoringRules: ObjectStackProtocolImplementation['assertRuntimeAuthoringRules']; readonly authoringChannel: ObjectStackProtocolImplementation['authoringChannel']; readonly authoringGates: ObjectStackProtocolImplementation['authoringGates']; + readonly additionalAuthoringGates: ObjectStackProtocolImplementation['additionalAuthoringGates']; collectBatchPendingDeclarations: ObjectStackProtocolImplementation['collectBatchPendingDeclarations']; credentialChannelFor: ObjectStackProtocolImplementation['credentialChannelFor']; defaultRecordPageSaveRefusal: ObjectStackProtocolImplementation['defaultRecordPageSaveRefusal']; @@ -206,16 +208,25 @@ export async function refuseRestoredBodyTheSaveDoorRefuses( } } -/** The body of `ObjectStackProtocolImplementation#runAuthoringGate`; the method's docblock there is its contract. */ -export async function runAuthoringGate( - this: Pick, - evt: { +/** The write a gate is run for: what the save, restore and promotion doors state. */ +type AuthoringGateEvent = { type: string; name: string; state: 'draft' | 'active'; body: unknown; + /** [#37766] Run the gates added beside the owner (`addAuthoringGate`) alone: a draft's promotion, which the owner gate does not run on. */ + addedOnly?: boolean; userTextLocales?: readonly (string | undefined)[]; packageId?: string | null; -}): Promise { +}; + +/** The body of `ObjectStackProtocolImplementation#runAuthoringGate`; the method's docblock there is its contract. */ +export async function runAuthoringGate( + this: Pick, + evt: AuthoringGateEvent, +): Promise { const singular = PLURAL_TO_SINGULAR[evt.type] ?? evt.type; - const gate = this.authoringGates.get(singular); - if (!gate) return; + const gate = evt.addedOnly ? undefined : this.authoringGates.get(singular); + // [ADR-0162 item 7, #37766] The gates added beside the owner + // (`addAuthoringGate`) run after it, in the order they were added. + const added = this.additionalAuthoringGates.get(singular) ?? []; + if (!gate && added.length === 0) return; const artifactBacked = this.isArtifactBacked(evt.type, evt.name); let declaredBody: unknown; if (artifactBacked && typeof this.engine.registry?.getItem === 'function') { @@ -223,7 +234,7 @@ export async function runAuthoringGate( declaredBody = this.engine.registry.getItem(evt.type, evt.name) ?? (alt ? this.engine.registry.getItem(alt, evt.name) : undefined); } - await gate({ + const ctx: MetadataAuthoringGateContext = { type: singular, name: evt.name, state: evt.state, @@ -235,7 +246,9 @@ export async function runAuthoringGate( : {}), // [ADR-0150 D2, #34226] The package the write is addressed to. ...(typeof evt.packageId === 'string' && evt.packageId !== '' ? { packageId: evt.packageId } : {}), - }); + }; + if (gate) await gate(ctx); + for (const extra of added) await extra(ctx); } /** diff --git a/packages/metadata-protocol/src/protocol-class-head.ts b/packages/metadata-protocol/src/protocol-class-head.ts index 40831746248..244fdf4094c 100644 --- a/packages/metadata-protocol/src/protocol-class-head.ts +++ b/packages/metadata-protocol/src/protocol-class-head.ts @@ -179,6 +179,18 @@ export class ProtocolClassHeadFacet { host.authoringGates.set(singular, gate); } + /** + * The body of `ObjectStackProtocolImplementation#addAuthoringGate`; the method's docblock there is its contract. + * Handed the protocol's map of added gates itself (the facade holds no host member for it, to stay within its + * line ceiling): singular or plural type names both resolve, and each call appends one gate. + */ + static addAuthoringGate(added: Map, type: string, gate: MetadataAuthoringGate): void { + const singular = PLURAL_TO_SINGULAR[type] ?? type; + const gates = added.get(singular); + if (gates) gates.push(gate); + else added.set(singular, [gate]); + } + /** The body of `ObjectStackProtocolImplementation#registerCredentialChannel`; the method's docblock there is its contract. */ static registerCredentialChannel(host: Pick, type: string, channel: MetadataCredentialChannel): void { const singular = PLURAL_TO_SINGULAR[type] ?? type; diff --git a/packages/metadata-protocol/src/protocol-history-and-publish.ts b/packages/metadata-protocol/src/protocol-history-and-publish.ts index 9f79c4ba1d1..b19df50ede7 100644 --- a/packages/metadata-protocol/src/protocol-history-and-publish.ts +++ b/packages/metadata-protocol/src/protocol-history-and-publish.ts @@ -689,7 +689,7 @@ export class ProtocolHistoryAndPublishFacet { * `recordPendingDenialAudit`, rethrow. Skip it and the refusal is silent * again — the pre-#7748 state, not merely a worse one. */ - static async promoteDraftForPublish(host: Pick, request: { + static async promoteDraftForPublish(host: Pick, request: { type: string; name: string; actor?: string; message?: string; /** * [#8907] ADR-0048 — the package binding of the draft being promoted, @@ -1459,6 +1459,23 @@ export class ProtocolHistoryAndPublishFacet { }) : []; + // [ADR-0162 item 7, #37766] The gates a plugin added beside the type's + // owner gate (`addAuthoringGate`) judge the body as it goes `active`. + // The owner gate ran at the draft's save and is not run again; an added + // gate that judges only `active` bodies meets a draft's body here, on + // the save door's channel rule, and a judge-only call meets it too. + if (draftForGate && host.authoringChannel !== 'package-author') { + await host.runAuthoringGate({ + type: singularType, + name: request.name, + state: 'active', + addedOnly: true, + body: storedFlowVerdictBody(singularType, draftForGate.body), + ...(request.userTextLocales !== undefined ? { userTextLocales: request.userTextLocales } : {}), + ...(request.packageId !== undefined ? { packageId: request.packageId } : {}), + }); + } + // [ADR-0146 D2] The override write gate's refusal, the last before the store. if (overrideVerdict.verdict === 'refuse') throw overrideWriteRefusalError(overrideVerdict); // [#32396] Every refusal above has had its turn; a judge-only call stops diff --git a/packages/metadata-protocol/src/protocol.add-authoring-gate-37766.test.ts b/packages/metadata-protocol/src/protocol.add-authoring-gate-37766.test.ts new file mode 100644 index 00000000000..fdcd0b26d96 --- /dev/null +++ b/packages/metadata-protocol/src/protocol.add-authoring-gate-37766.test.ts @@ -0,0 +1,287 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 item 7, #37766 slice N45] `addAuthoringGate`: a gate added beside a + * type's owner gate (`registerAuthoringGate`). It runs after the owner gate, + * in the order the gates were added, on every write the owner gate runs on, + * and also when a draft is promoted to `active`, which the owner gate does not + * run on. The single slot and its replace rule stay as published. + * + * The harness (a table-keyed stub engine and the approval flow bodies) is the + * one `protocol.runtime-authoring-gate.test.ts` drives the save and publish + * doors with, copied so the two files move apart. + */ + +import { describe, expect, it, vi } from 'vitest'; +import { + assertEngineDeleteDispatch, + assertEngineUpdateDispatch, + assertEngineFindOnePredicate, +} from '@objectstack/metadata-core'; +import { ObjectStackProtocolImplementation } from './protocol.js'; +import { NO_PACKAGE_SCOPED_READS } from './no-package-scoped-reads.testkit.js'; +import type { MetadataAuthoringChannel } from './protocol.js'; + +const INSTALLED_PACKAGES: ReadonlySet = new Set(['app.fx']); +const installedPackage = (id: string) => (INSTALLED_PACKAGES.has(id) ? { manifest: { id } } : undefined); + +/** The issue's body. Zod-valid: `approvers[].value` is just a string to the schema. */ +const brokenApprovalFlow = () => ({ + name: 'leave_approval', + label: 'Leave Approval', + type: 'autolaunched', + status: 'active', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + { + id: 'approve', + type: 'approval', + label: 'Approve', + config: { approvers: [{ type: 'expression', value: 'record.owner ==' }] }, + }, + ], + edges: [{ id: 'e1', source: 'start', target: 'approve' }], +}); + +/** The same flow with an approver expression that parses and uses a legal root. */ +const validApprovalFlow = () => { + const flow = brokenApprovalFlow(); + flow.nodes[1]!.config = { + approvers: [{ type: 'expression', value: 'current.owner' }], + } as any; + return flow; +}; + +interface Row { + id: string; + type: string; + name: string; + organization_id: string | null; + state: string; + metadata: string; + checksum?: string; +} + +const keyOf = (w: Record) => + `${w.type}|${w.name}|${w.organization_id ?? '__env__'}|${w.state ?? 'active'}`; + +function makeStubEngine() { + // ⚠️ Keyed BY TABLE, and that is a correctness property of this harness + // rather than tidiness. One flat row map answers a read of `sys_metadata` + // with rows the protocol wrote to `sys_metadata_history` and + // `sys_metadata_commit`: a DRAFT save appends a history row carrying no + // `state`, the declared `defaultValue: 'active'` modelled below fills it + // in, and the draft comes back as an ACTIVE metadata row. Measured in + // #16223, where one assertion's polarity was the only thing that caught it. + const tables = new Map>(); + const tableOf = (table: string): Map => { + const existing = tables.get(table); + if (existing) return existing; + const created = new Map(); + tables.set(table, created); + return created; + }; + /** The store table these tests assert on; the journals get their own. */ + const rows = tableOf('sys_metadata'); + let nextId = 0; + const findRow = (table: string, w: Record): { key: string; row: Row } | null => { + if (w.id !== undefined) { + for (const [k, r] of tableOf(table)) if (r.id === w.id) return { key: k, row: r }; + return null; + } + for (const [k, r] of tableOf(table)) { + if (w.type !== undefined && r.type !== w.type) continue; + if (w.name !== undefined && r.name !== w.name) continue; + if (w.organization_id !== undefined && r.organization_id !== w.organization_id) continue; + if (w.state !== undefined && r.state !== w.state) continue; + return { key: k, row: r }; + } + return null; + }; + const engine: any = { + async findOne(table: string, opts: { where: Record }) { + assertEngineFindOnePredicate(table, opts); + return findRow(table, opts.where)?.row ?? null; + }, + async find(table: string, opts: { where: Record }) { + return Array.from(tableOf(table).values()).filter((r) => { + if (opts.where.type && !whereValueMatches(r.type, opts.where.type)) return false; + if (opts.where.name !== undefined && r.name !== opts.where.name) return false; + if (opts.where.organization_id !== undefined + && r.organization_id !== opts.where.organization_id) return false; + if (opts.where.state && r.state !== opts.where.state) return false; + return true; + }); + }, + async insert(table: string, data: Record) { + nextId += 1; + const row = { id: `r_${nextId}`, ...(data as any) } as Row; + tableOf(table).set(keyOf(data), row); + return { id: row.id }; + }, + async update(table: string, data: Record, opts: { where: Record }) { + assertEngineUpdateDispatch(data, opts); + const found = findRow(table, opts.where); + if (!found) return { id: null }; + tableOf(table).set(found.key, { ...found.row, ...(data as any) }); + return { id: found.row.id }; + }, + async delete(table: string, opts: { where: Record }) { + assertEngineDeleteDispatch(opts); + const found = findRow(table, opts.where); + if (!found) return { deleted: 0 }; + tableOf(table).delete(found.key); + return { deleted: 1 }; + }, + // [#30635] A publish syncs the object's storage, and a refused sync + // rides the answer's `advisories`. This double's sync succeeds, so the + // advisories these pins read are the gate's alone. + async syncObjectSchema() { + return true; + }, + registry: { + ...NO_PACKAGE_SCOPED_READS, + registerItem: () => {}, + registerObject: () => {}, + // The live object universe the rules resolve names against — the + // input `os lint` cannot have and this surface can (#4463 D2). + listItems: (type: string) => + type === 'object' + ? [{ name: 'leave_request', fields: { owner: { type: 'text' } } }] + : [], + getItem: () => undefined, + getPackage: installedPackage as (id: string) => { manifest: Record } | undefined, + }, + }; + return { engine, rows }; +} + +/** [#24371] One `where` value as the store reads it: `{ $in: [...] }` (the by-name read's both-spellings `type`) or equality. */ +const whereValueMatches = (actual: unknown, want: unknown): boolean => + want !== null && typeof want === 'object' && Array.isArray((want as { $in?: unknown }).$in) + ? (want as { $in: unknown[] }).$in.includes(actual) + : actual === want; + +function makeProtocolOn(authoringChannel?: MetadataAuthoringChannel) { + const { engine, rows } = makeStubEngine(); + const protocol = authoringChannel === undefined + ? new ObjectStackProtocolImplementation(engine, () => new Map(), 'env_test') + : new ObjectStackProtocolImplementation(engine, () => new Map(), 'env_test', authoringChannel); + return { protocol: protocol as any, rows }; +} + +const flowRows = (rows: Map) => Array.from(rows.values()).filter((r) => r.type === 'flow'); + +const gateEvent = (over: Record = {}) => ({ + type: 'object', name: 'crm_account', state: 'active' as const, body: { sharingModel: 'private' }, ...over, +}); + +describe('addAuthoringGate: a gate beside the owner gate (#37766)', () => { + it('runs after the owner gate, and the added gates run in the order they were added', async () => { + const { protocol } = makeProtocolOn(); + const order: string[] = []; + protocol.addAuthoringGate('object', () => { order.push('added-1'); }); + protocol.registerAuthoringGate('object', () => { order.push('owner'); }); + protocol.addAuthoringGate('object', () => { order.push('added-2'); }); + await protocol.runAuthoringGate(gateEvent()); + expect(order).toEqual(['owner', 'added-1', 'added-2']); + }); + + it('hands every gate the same context: type, name, state, body, locales and package', async () => { + const { protocol } = makeProtocolOn(); + const seen: any[] = []; + protocol.registerAuthoringGate('object', (ctx: any) => { seen.push(ctx); }); + protocol.addAuthoringGate('object', (ctx: any) => { seen.push(ctx); }); + await protocol.runAuthoringGate(gateEvent({ state: 'draft', userTextLocales: ['zh-CN', ''], packageId: 'app.fx' })); + expect(seen).toHaveLength(2); + expect(seen[1]).toMatchObject({ + type: 'object', name: 'crm_account', state: 'draft', body: { sharingModel: 'private' }, + isArtifactBacked: false, userTextLocales: ['zh-CN'], packageId: 'app.fx', + }); + expect(seen[1]).toEqual(seen[0]); + }); + + it('does not displace the owner gate, and a second owner registration still replaces only the owner', async () => { + const { protocol } = makeProtocolOn(); + const first = vi.fn(); const second = vi.fn(); const added = vi.fn(); + protocol.registerAuthoringGate('object', first); + protocol.addAuthoringGate('object', added); + protocol.registerAuthoringGate('object', second); + await protocol.runAuthoringGate(gateEvent()); + expect(first).not.toHaveBeenCalled(); + expect(second).toHaveBeenCalledTimes(1); + expect(added).toHaveBeenCalledTimes(1); + }); + + it('runs with no owner gate registered, and a plural type resolves to the singular', async () => { + const { protocol } = makeProtocolOn(); + const added = vi.fn(); + protocol.addAuthoringGate('flows', added); + await protocol.runAuthoringGate(gateEvent({ type: 'flow', name: 'f' })); + expect(added).toHaveBeenCalledTimes(1); + }); + + it('a throw of an added gate PROPAGATES with its status and code', async () => { + const { protocol } = makeProtocolOn(); + protocol.addAuthoringGate('object', () => { + const err: any = new Error('refused'); + err.code = 'VALIDATION_FAILED'; err.status = 422; + throw err; + }); + await expect(protocol.runAuthoringGate(gateEvent())).rejects.toMatchObject({ code: 'VALIDATION_FAILED', status: 422 }); + }); + + it('a throw of the owner gate stops the write before any added gate runs', async () => { + const { protocol } = makeProtocolOn(); + const added = vi.fn(); + protocol.registerAuthoringGate('object', () => { throw Object.assign(new Error('owner'), { status: 403 }); }); + protocol.addAuthoringGate('object', added); + await expect(protocol.runAuthoringGate(gateEvent())).rejects.toMatchObject({ status: 403 }); + expect(added).not.toHaveBeenCalled(); + }); +}); + +describe('addAuthoringGate through the save and publish doors (#37766)', () => { + it('a draft save runs the added gate with state draft, and an active save with state active', async () => { + const { protocol } = makeProtocolOn(); + const states: string[] = []; + protocol.addAuthoringGate('flow', (ctx: any) => { states.push(ctx.state); }); + await protocol.saveMetaItem({ type: 'flow', name: 'leave_approval', item: validApprovalFlow(), mode: 'draft' }); + await protocol.saveMetaItem({ type: 'flow', name: 'leave_approval', item: validApprovalFlow() }); + expect(states).toEqual(['draft', 'active']); + }); + + it('the promotion of a draft runs the added gate with state active, and not the owner gate', async () => { + const { protocol } = makeProtocolOn(); + const owner: string[] = []; + const added: Array<{ state: string; name: string }> = []; + protocol.registerAuthoringGate('flow', (ctx: any) => { owner.push(ctx.state); }); + protocol.addAuthoringGate('flow', (ctx: any) => { added.push({ state: ctx.state, name: ctx.name }); }); + await protocol.saveMetaItem({ type: 'flow', name: 'leave_approval', item: validApprovalFlow(), mode: 'draft' }); + const result = await protocol.publishMetaItem({ type: 'flow', name: 'leave_approval' }); + expect(result.success).toBe(true); + expect(owner, 'the owner gate ran at the draft save only').toEqual(['draft']); + expect(added).toEqual([{ state: 'draft', name: 'leave_approval' }, { state: 'active', name: 'leave_approval' }]); + }); + + it('a throw of the added gate at promotion refuses the publish before it writes', async () => { + const { protocol, rows } = makeProtocolOn(); + protocol.addAuthoringGate('flow', (ctx: any) => { + if (ctx.state !== 'active') return; + throw Object.assign(new Error('VALIDATION_FAILED: refused'), { code: 'VALIDATION_FAILED', status: 422 }); + }); + await protocol.saveMetaItem({ type: 'flow', name: 'leave_approval', item: validApprovalFlow(), mode: 'draft' }); + const err = await protocol.publishMetaItem({ type: 'flow', name: 'leave_approval' }).catch((e: any) => e); + expect(err).toMatchObject({ code: 'VALIDATION_FAILED', status: 422 }); + expect(flowRows(rows).map((r) => r.state), 'no active row').not.toContain('active'); + }); + + it('a declared package-author channel runs no added gate, at save or at promotion', async () => { + const { protocol } = makeProtocolOn('package-author'); + const added = vi.fn(); + protocol.addAuthoringGate('flow', added); + await protocol.saveMetaItem({ type: 'flow', name: 'leave_approval', item: validApprovalFlow(), mode: 'draft' }); + await protocol.publishMetaItem({ type: 'flow', name: 'leave_approval' }); + expect(added).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/metadata-protocol/src/protocol.ts b/packages/metadata-protocol/src/protocol.ts index a050b6f169d..38f0bb03af8 100644 --- a/packages/metadata-protocol/src/protocol.ts +++ b/packages/metadata-protocol/src/protocol.ts @@ -789,12 +789,12 @@ export class ObjectStackProtocolImplementation implements private mutationProjectors = new Map(); /** - * Pre-persistence authoring gates (#3050). One per type; a second - * registration replaces the first (idempotent re-init). Unlike - * projectors these THROW to reject the write — see - * {@link MetadataAuthoringGate}. + * Pre-persistence authoring gates (#3050). One per type; a second registration replaces the first (idempotent + * re-init). Unlike projectors these THROW to reject the write — see {@link MetadataAuthoringGate}. [#37766] Beside + * them, the gates added per type in order ({@link addAuthoringGate}). */ private authoringGates = new Map(); + private additionalAuthoringGates = new Map(); /** [#20790] Per-type write-only credential channels — see {@link registerCredentialChannel}. */ private credentialChannels = new Map(); @@ -1541,17 +1541,19 @@ export class ObjectStackProtocolImplementation implements return ProtocolClassHeadFacet.registerMutationProjector(protocolHost(this), type, projector); } - /** - * Register the pre-persistence authoring gate for a metadata type - * (ADR-0094 addendum seam; #3050). Called by domain plugins at init — - * e.g. plugin-security registers the `object` OWD posture gate. The gate - * THROWS to reject the write. Singular or plural type names both resolve; - * one gate per type, a second registration replaces the first. - */ + /** Register the pre-persistence authoring gate for a metadata type (ADR-0094 addendum seam; #3050). Called by + * domain plugins at init — e.g. plugin-security registers the `object` OWD posture gate. The gate THROWS to + * reject the write. Singular or plural type names both resolve; one gate per type, a second replaces the first. */ registerAuthoringGate(type: string, gate: MetadataAuthoringGate): void { // [#29985 codemod] The body moved to `protocol-class-head.ts`; it reaches this class through `protocol-host.ts`. return ProtocolClassHeadFacet.registerAuthoringGate(protocolHost(this), type, gate); } + /** [ADR-0162 item 7, #37766] Add a gate BESIDE the type's owner gate, never displacing it: it runs after the owner + * gate, in the order added, on each write the owner runs on, and also when a draft is promoted to `active`, which + * the owner gate does not run on. It reads `ctx.state`, and THROWS to reject the write. */ + addAuthoringGate(type: string, gate: MetadataAuthoringGate): void { + return ProtocolClassHeadFacet.addAuthoringGate(this.additionalAuthoringGates, type, gate); + } /** * [#20790] Register the write-only credential channel for a metadata type @@ -1758,15 +1760,12 @@ export class ObjectStackProtocolImplementation implements return refuseRestoredBodyTheSaveDoorRefuses.call(host, type, name, body, binding, source); } - /** - * Run the registered authoring gate for an about-to-persist body (#3050). - * No-op when no gate is registered for the type. A gate throw PROPAGATES - * (with its status/code) — that is the contract: the write is rejected - * before persistence. Resolves the artifact-backed flag and the packaged - * declaration body (the baseline an overlay customizes) for the gate. - */ + /** Run the registered authoring gate, then the gates added beside it, for an about-to-persist body (#3050; #37766: + * `addedOnly`, on a draft's promotion, runs the added ones alone). No-op when none is registered. A gate throw + * PROPAGATES (with its status/code): the write is rejected before persistence. Resolves the artifact-backed flag + * and the packaged declaration body (the baseline an overlay customizes) for the gate. */ private runAuthoringGate(evt: { - type: string; name: string; state: 'draft' | 'active'; body: unknown; + type: string; name: string; state: 'draft' | 'active'; body: unknown; addedOnly?: boolean; userTextLocales?: readonly (string | undefined)[]; packageId?: string | null; }): Promise { // [#25467 cut 8] The body moved to `protocol-authoring-gate.ts` (see `AuthoringGateHost`). @@ -1774,6 +1773,7 @@ export class ObjectStackProtocolImplementation implements const readEngine = () => this.engine; const host: ThisParameterType = { get authoringGates() { return readAuthoringGates(); }, + additionalAuthoringGates: this.additionalAuthoringGates, get engine() { return readEngine(); }, isArtifactBacked: (...a) => this.isArtifactBacked(...a), }; diff --git a/packages/plugins/plugin-approvals/src/approval-opening-check.ts b/packages/plugins/plugin-approvals/src/approval-opening-check.ts index 7bf8bd0ec74..d0800ddaa1a 100644 --- a/packages/plugins/plugin-approvals/src/approval-opening-check.ts +++ b/packages/plugins/plugin-approvals/src/approval-opening-check.ts @@ -417,7 +417,7 @@ function canPause(node: OpeningFlowNode, source: OpeningCheckSource): boolean { } /** Every node of a body, its regions' nodes included, to {@link MAX_REGION_DEPTH}. */ -function allNodes(body: OpeningFlowBody): OpeningFlowNode[] { +export function allNodes(body: OpeningFlowBody): OpeningFlowNode[] { const out: OpeningFlowNode[] = []; const visit = (nodes: ReadonlyArray | undefined, depth: number) => { for (const node of nodes ?? []) { diff --git a/packages/plugins/plugin-approvals/src/approval-opening-refusal.ts b/packages/plugins/plugin-approvals/src/approval-opening-refusal.ts index 3018bdec513..145f0215f42 100644 --- a/packages/plugins/plugin-approvals/src/approval-opening-refusal.ts +++ b/packages/plugins/plugin-approvals/src/approval-opening-refusal.ts @@ -3,7 +3,9 @@ * check (ADR-0162 Execution item 7, #37766 slice B) finds a gap: one lead * naming the record, then one sentence per gap naming the flow, step, object, * field and what is missing — in the run's locale, from the plugin's own - * catalog (`translations/messages.ts`), falling back to `en`. + * catalog (`translations/messages.ts`), falling back to `en`. The same + * sentences report the gaps where a flow or an object is published (#37766, + * N45), under a lead that names the published item. */ import { interpolate } from './approval-notification-text.js'; @@ -44,6 +46,14 @@ export function openingRefusalPack(locale: string | undefined): Pack { return same ? packs[same]! : approvalMessages.en; } +/** One sentence per gap, in `pack`. */ +function gapSentences(gaps: readonly OpeningGap[], pack: Pack): string[] { + return gaps.map((gap) => { + const { kind, ...params } = gap; + return interpolate(pack[GAP_SENTENCE[kind]], params as Record); + }); +} + /** The refusal text for `gaps`, on the record `subject`, in `locale`. */ export function openingRefusalText( gaps: readonly OpeningGap[], @@ -52,9 +62,20 @@ export function openingRefusalText( ): string { const pack = openingRefusalPack(locale); const lead = interpolate(pack.approvalOpeningRefusedLead, { object: subject.object, record: subject.record }); - const sentences = gaps.map((gap) => { - const { kind, ...params } = gap; - return interpolate(pack[GAP_SENTENCE[kind]], params as Record); - }); - return [lead, ...sentences].join(' '); + return [lead, ...gapSentences(gaps, pack)].join(' '); +} + +/** + * [#37766, N45] The refusal text for `gaps` found where the metadata item + * `subject` is published: a lead naming the item, then the same sentence per + * gap as {@link openingRefusalText}, in `locale`. + */ +export function publishRefusalText( + gaps: readonly OpeningGap[], + subject: { type: string; name: string }, + locale?: string, +): string { + const pack = openingRefusalPack(locale); + const lead = interpolate(pack.approvalPublishRefusedLead, { type: subject.type, name: subject.name }); + return [lead, ...gapSentences(gaps, pack)].join(' '); } diff --git a/packages/plugins/plugin-approvals/src/approval-publish-check.test.ts b/packages/plugins/plugin-approvals/src/approval-publish-check.test.ts new file mode 100644 index 00000000000..eb4ac9f8226 --- /dev/null +++ b/packages/plugins/plugin-approvals/src/approval-publish-check.test.ts @@ -0,0 +1,295 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 Execution item 7; #37766 slice N45] The opening check's + * conditions, reported where a flow or an object is published, over fixtures: + * the flow publish and the walk up its callers (the written body in place, a + * flow that calls itself, two that call each other, the cap), the object + * publish (the written object in place, only its own gaps), and the four + * things a publish does not refuse: a draft, a callee that cannot be read, a + * host with no `job` service, an application with no declaration. The gate's + * registration and its refusal are pinned below; the real metadata door in + * `approval-publish-gate-37766.integration.test.ts`. + */ + +import { describe, expect, it, vi } from 'vitest'; +import type { OpeningFlowBody, OpeningFlowNode } from './approval-opening-check.js'; +import { + MAX_PUBLISH_ROOTS, + judgeApprovalPublish, + rootObjectsOf, + type PublishCheckSource, + type PublishedItem, +} from './approval-publish-check.js'; +import { ApprovalPublishRefusedError, registerApprovalPublishGates, type ApprovalPublishGateContext } from './approval-publish-gate.js'; + +const STATUSES = ['draft', 'pending', 'returned', 'approved', 'rejected', 'recalled']; +const statusField = (options: unknown[] = STATUSES.map((v) => ({ value: v, label: v }))) => ({ type: 'select', options }); + +/** An object that closes on `approved` and `rejected` of `status`, and meets every condition. */ +const invoice = (over: Record = {}) => + ({ name: 'invoice', closedStates: { status: ['approved', 'rejected'] }, fields: { status: statusField() }, ...over }); +/** The same object, declaring no `closedStates`. */ +const openInvoice = () => ({ name: 'invoice', fields: { status: statusField() } }); +/** An object that does not declare `pending` on its approval field: the first D5 condition fails. */ +const noPendingInvoice = () => invoice({ fields: { status: statusField(['draft', 'approved', 'rejected']) } }); +const memo = { name: 'memo', closedStates: { status: ['approved'] }, fields: { status: statusField(['draft', 'approved']) } }; + +const DESCRIPTORS: Record = { + wait: { supportsPause: true }, approval: { supportsPause: true }, decision: {}, subflow: {}, map: {}, +}; + +const n = (id: string, type: string, config: Record = {}): OpeningFlowNode => ({ id, type, config }); +const step = (id: string): OpeningFlowNode => n(id, 'approval', { approvalStatusField: 'status' }); +const sub = (id: string, flowName: string): OpeningFlowNode => n(id, 'subflow', { flowName }); + +/** A body whose nodes run one after another; `start` names `object` where given. */ +function chain(object: string | null, ...nodes: OpeningFlowNode[]): OpeningFlowBody { + const all = [n('start', 'start', object ? { objectName: object } : {}), ...nodes, n('end', 'end')]; + return { nodes: all, edges: all.slice(1).map((b, i) => ({ source: all[i]!.id, target: b.id })) }; +} + +function source(spec: { objects?: Record; flows?: Record; listFlows?: boolean }): PublishCheckSource & { flowReads: string[] } { + const objects = spec.objects ?? { invoice: invoice() }; + const flows = spec.flows ?? {}; + const flowReads: string[] = []; + return { + flowReads, + objectSchema: (name) => objects[name], + allObjects: () => Object.values(objects), + flowNames: async () => (spec.listFlows === false ? undefined : Object.keys(flows)), + flow: async (name) => { flowReads.push(name); return flows[name] ? { key: name, body: flows[name]! } : null; }, + calleeFlow: async (name) => (flows[name] ? { key: name, body: flows[name]! } : null), + nodeDescriptor: (type) => DESCRIPTORS[type], + }; +} + +const flowWrite = (name: string, body: OpeningFlowBody): PublishedItem => ({ type: 'flow', name, body }); +const objectWrite = (body: Record): PublishedItem => ({ type: 'object', name: String(body.name), body }); +const kinds = (gaps: { kind: string }[]) => gaps.map((g) => g.kind); + +describe('the publish check: a flow', () => { + it('refuses a flow whose approval cannot show itself in progress on the field its object closes on', async () => { + const out = await judgeApprovalPublish(flowWrite('F', chain('invoice', step('a1'))), source({ objects: { invoice: noPendingInvoice() } })); + expect(out.gaps).toEqual([{ kind: 'no_pending_option', flow: 'F', step: 'a1', object: 'invoice', field: 'status' }]); + expect(out.capped).toBe(false); + }); + + it('lets a flow through that meets every condition', async () => { + const out = await judgeApprovalPublish(flowWrite('F', chain('invoice', step('a1'), n('d', 'decision'), step('a2'))), source({})); + expect(out.gaps).toEqual([]); + }); + + it('judges the written body, not the one the engine holds', async () => { + const held = { F: chain('invoice', step('a1'), step('a2')) }; + const written = chain('invoice', step('a1'), n('w', 'wait'), step('a2')); + const out = await judgeApprovalPublish(flowWrite('F', written), source({ flows: held })); + expect(kinds(out.gaps)).toEqual(['pause_between_steps']); + }); + + it('judges a flow that calls the written flow as a root, with the written body in place', async () => { + // The written subflow holds a pause between two steps; it starts on no + // record itself, so only its caller, which starts on an invoice, shows it. + const flows = { P: chain('invoice', sub('s', 'C')), C: chain(null, step('a1'), step('a2')) }; + const written = chain(null, step('a1'), n('w', 'wait'), step('a2')); + const out = await judgeApprovalPublish(flowWrite('C', written), source({ flows })); + expect(out.gaps).toEqual([{ kind: 'pause_between_steps', flow: 'C', node: 'w', type: 'wait', object: 'invoice' }]); + }); + + it('walks up the callers to any depth', async () => { + const flows = { + G: chain('invoice', sub('s', 'P')), + P: chain(null, sub('s', 'C')), + C: chain(null, step('a1')), + }; + const out = await judgeApprovalPublish(flowWrite('C', chain(null, step('a1'))), source({ flows, objects: { invoice: noPendingInvoice() } })); + expect(out.gaps).toEqual([{ kind: 'no_pending_option', flow: 'C', step: 'a1', object: 'invoice', field: 'status' }]); + }); + + it('ends the walk on a flow that calls itself', async () => { + const self = chain('invoice', step('a1'), sub('again', 'F')); + const out = await judgeApprovalPublish(flowWrite('F', self), source({ flows: { F: self }, objects: { invoice: noPendingInvoice() } })); + expect(kinds(out.gaps)).toContain('no_pending_option'); + expect(out.capped).toBe(false); + }); + + it('ends the walk on two flows that call each other', async () => { + const flows = { A: chain('invoice', sub('s', 'B')), B: chain(null, step('b1'), sub('s', 'A')) }; + const out = await judgeApprovalPublish(flowWrite('B', flows.B), source({ flows, objects: { invoice: noPendingInvoice() } })); + expect(out.gaps).toEqual([{ kind: 'no_pending_option', flow: 'B', step: 'b1', object: 'invoice', field: 'status' }]); + expect(out.capped).toBe(false); + }); + + it(`stops at ${MAX_PUBLISH_ROOTS} roots, refuses nothing for the cap, and says it stopped`, async () => { + // The written flow and MAX_PUBLISH_ROOTS callers: one root past the cap. + // Each caller starts on a memo, whose field meets every condition, so the + // roots the walk reaches find nothing, and the one past it is not judged. + const flows: Record = { C: chain(null, step('a1')) }; + for (let i = 0; i < MAX_PUBLISH_ROOTS; i++) flows[`P${String(i).padStart(3, '0')}`] = chain('memo', sub('s', 'C')); + const objects = { invoice: invoice(), memo: { ...memo, fields: { status: statusField() } } }; + const out = await judgeApprovalPublish(flowWrite('C', flows.C!), source({ flows, objects })); + expect(out.capped).toBe(true); + expect(out.gaps).toEqual([]); + }); + + it('judges a flow whose start input is a record of a closing object (#29425) on that object', async () => { + const body = { ...chain(null, step('a1')), variables: [{ name: 'doc', type: 'record', isInput: true, objectName: 'invoice' }] }; + expect(rootObjectsOf(body)).toEqual(['invoice']); + const out = await judgeApprovalPublish(flowWrite('F', body), source({ objects: { invoice: noPendingInvoice() } })); + expect(kinds(out.gaps)).toEqual(['no_pending_option']); + }); +}); + +describe('the publish check: an object', () => { + it('refuses an object that starts to close on its approval field where a held approval cannot show itself in progress', async () => { + const flows = { F: chain('invoice', step('a1'), n('w', 'wait'), step('a2')) }; + const out = await judgeApprovalPublish(objectWrite(invoice()), source({ flows, objects: { invoice: openInvoice() } })); + expect(out.gaps).toEqual([{ kind: 'pause_between_steps', flow: 'F', node: 'w', type: 'wait', object: 'invoice' }]); + }); + + it('judges the written object, not the one the engine holds', async () => { + const flows = { F: chain('invoice', step('a1')) }; + const out = await judgeApprovalPublish(objectWrite(noPendingInvoice()), source({ flows, objects: { invoice: invoice() } })); + expect(kinds(out.gaps)).toEqual(['no_pending_option']); + }); + + it('lets an object through that drops its closedStates, in an application where no other object declares the key', async () => { + const flows = { F: chain('invoice', step('a1'), n('w', 'wait'), step('a2')) }; + const src = source({ flows, objects: { invoice: invoice() } }); + const out = await judgeApprovalPublish(objectWrite(openInvoice()), src); + expect(out.gaps).toEqual([]); + expect(src.flowReads, 'nothing is read').toEqual([]); + }); + + it('reports only the written object\'s gaps', async () => { + // F acts on the invoice (closing, sound) and maps over memos (closing, no pending). + const flows = { + F: chain('invoice', step('a1'), n('m', 'map', { flowName: 'M', itemObject: 'memo' })), + M: chain(null, step('m1')), + }; + const objects = { invoice: invoice(), memo }; + const onInvoice = await judgeApprovalPublish(objectWrite(invoice()), source({ flows, objects })); + expect(onInvoice.gaps.every((g) => (g as { object?: string }).object === 'invoice')).toBe(true); + const onMemo = await judgeApprovalPublish(objectWrite(memo), source({ flows, objects })); + expect(onMemo.gaps.length).toBeGreaterThan(0); + expect(onMemo.gaps.every((g) => (g as { object?: string }).object === 'memo')).toBe(true); + }); + + it('judges a flow that maps over the object\'s records', async () => { + const flows = { F: chain(null, n('m', 'map', { flowName: 'M', itemObject: 'invoice' })), M: chain(null, step('a1')) }; + const out = await judgeApprovalPublish(objectWrite(noPendingInvoice()), source({ flows, objects: { invoice: openInvoice() } })); + expect(kinds(out.gaps)).toEqual(['no_pending_option']); + }); + + it('judges no flow where the engine cannot list its flows', async () => { + const flows = { F: chain('invoice', step('a1')) }; + const out = await judgeApprovalPublish(objectWrite(noPendingInvoice()), source({ flows, objects: { invoice: openInvoice() }, listFlows: false })); + expect(out.gaps).toEqual([]); + }); +}); + +describe('the publish check: what it does not refuse', () => { + it('does not refuse a callee it cannot read', async () => { + const out = await judgeApprovalPublish(flowWrite('F', chain('invoice', step('a1'), sub('s', 'missing'))), source({})); + expect(out.gaps).toEqual([]); + }); + + it('judges what it can read beside a callee it cannot read', async () => { + const out = await judgeApprovalPublish( + flowWrite('F', chain('invoice', step('a1'), sub('s', 'missing'))), + source({ objects: { invoice: noPendingInvoice() } }), + ); + expect(kinds(out.gaps)).toEqual(['no_pending_option']); + }); + + it('does not refuse for the host: it judges as if the host ran a job service', async () => { + // At the first request, an approval on a closing object refuses on a host + // with no job service; at publish, that host fact is not judged. + const out = await judgeApprovalPublish(flowWrite('F', chain('invoice', step('a1'))), source({})); + expect(kinds(out.gaps)).not.toContain('no_job_service'); + expect(out.gaps).toEqual([]); + }); + + it('reads nothing in an application where no object declares closedStates', async () => { + const flows = { P: chain('invoice', sub('s', 'F')) }; + const src = source({ flows, objects: { invoice: openInvoice() } }); + const out = await judgeApprovalPublish(flowWrite('F', chain('invoice', step('a1'), n('w', 'wait'), step('a2'))), src); + expect(out.gaps).toEqual([]); + expect(src.flowReads).toEqual([]); + }); + + it('judges nothing for a flow body with no nodes', async () => { + const out = await judgeApprovalPublish({ type: 'flow', name: 'F', body: { name: 'F' } }, source({})); + expect(out).toEqual({ gaps: [], capped: false }); + }); +}); + +describe('the publish gates', () => { + type Gate = (ctx: ApprovalPublishGateContext) => Promise; + function protocolDouble() { + const gates = new Map(); + return { + gates, + addAuthoringGate: (type: string, gate: Gate) => { gates.set(type, [...(gates.get(type) ?? []), gate]); }, + }; + } + const ctx = (over: Partial = {}): ApprovalPublishGateContext => + ({ type: 'flow', name: 'F', state: 'active', body: chain('invoice', step('a1')), ...over }); + const refusing = async () => ({ gaps: [{ kind: 'no_pending_option' as const, flow: 'F', step: 'a1', object: 'invoice', field: 'status' }], capped: false }); + + it('adds one gate on flow and one on object, and none to a protocol with no addAuthoringGate', () => { + const p = protocolDouble(); + expect(registerApprovalPublishGates(p, refusing)).toBe(true); + expect([...p.gates.keys()]).toEqual(['flow', 'object']); + expect(registerApprovalPublishGates({ registerAuthoringGate: () => {} }, refusing)).toBe(false); + expect(registerApprovalPublishGates(undefined, refusing)).toBe(false); + }); + + it('refuses an active write with a 422 VALIDATION_FAILED, in en and in the first locale the door states', async () => { + const p = protocolDouble(); + registerApprovalPublishGates(p, refusing); + const err = await p.gates.get('flow')![0]!(ctx({ userTextLocales: ['zh-CN', 'en'] })).catch((e) => e); + expect(err).toBeInstanceOf(ApprovalPublishRefusedError); + expect(err).toMatchObject({ code: 'VALIDATION_FAILED', status: 422, statusCode: 422 }); + expect(err.message).toMatch(/^flow F was not published: /); + expect(err.message).toContain('Field status of invoice (step a1 of flow F) does not declare the value pending'); + expect(err.userMessage).toMatch(/^flow F 没有发布:/); + expect(err.userMessage).toContain('没有声明值 pending'); + }); + + it('does not judge a draft', async () => { + const p = protocolDouble(); + const judge = vi.fn(refusing); + registerApprovalPublishGates(p, judge); + await expect(p.gates.get('flow')![0]!(ctx({ state: 'draft' }))).resolves.toBeUndefined(); + await expect(p.gates.get('object')![0]!(ctx({ type: 'object', state: 'draft' }))).resolves.toBeUndefined(); + expect(judge).not.toHaveBeenCalled(); + }); + + it('refuses nothing when the judge fails, and logs it', async () => { + const p = protocolDouble(); + const warn = vi.fn(); + registerApprovalPublishGates(p, async () => { throw new Error('boom'); }, { warn }); + await expect(p.gates.get('object')![0]!(ctx({ type: 'object' }))).resolves.toBeUndefined(); + expect(warn).toHaveBeenCalledTimes(1); + expect(warn.mock.calls[0]![1]).toMatchObject({ type: 'object', name: 'F', error: 'boom' }); + }); + + it('says one sentence when the walk stopped at the cap, and refuses nothing for it', async () => { + const p = protocolDouble(); + const warn = vi.fn(); + registerApprovalPublishGates(p, async () => ({ gaps: [], capped: true }), { warn }); + await expect(p.gates.get('flow')![0]!(ctx())).resolves.toBeUndefined(); + expect(warn).toHaveBeenCalledTimes(1); + expect(String(warn.mock.calls[0]![0])).toContain(`first ${MAX_PUBLISH_ROOTS} approval flows`); + }); + + it('hands the judge the type the gate is on, the name and the written body', async () => { + const p = protocolDouble(); + const judge = vi.fn(async () => ({ gaps: [], capped: false })); + registerApprovalPublishGates(p, judge); + const body = { name: 'invoice' }; + await p.gates.get('object')![0]!(ctx({ type: 'object', name: 'invoice', body })); + expect(judge).toHaveBeenCalledWith({ type: 'object', name: 'invoice', body }); + }); +}); diff --git a/packages/plugins/plugin-approvals/src/approval-publish-check.ts b/packages/plugins/plugin-approvals/src/approval-publish-check.ts new file mode 100644 index 00000000000..1dadfd3cb32 --- /dev/null +++ b/packages/plugins/plugin-approvals/src/approval-publish-check.ts @@ -0,0 +1,238 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 D5, Execution item 7; #37766 slice N45] The opening check's + * conditions, reported where a flow or an object is published. + * + * The rule is the refusal at an approval's first request + * (`approval-opening-check.ts`, slice B): the objects and the flows are + * published apart, and only the first request has them all in hand. This + * report is early notice, made wherever the parts are in view together. On the + * seat's reading of 2026-11-29 05:24Z it is an error: the publish is refused + * with the same sentences the first request would be refused with. + * + * What is judged, for a write that goes `active`: + * + * - **A flow.** The written flow as an approval's root, and every flow the + * engine holds that calls it through a `subflow` or a `map`, to any depth, + * as a root too, each with the written body in place of the held one. The + * walk up the callers keeps a visited set, so a flow that calls itself and + * two flows that call each other end it, and it stops at + * {@link MAX_PUBLISH_ROOTS} roots: past that it judges the roots it holds, + * refuses nothing for the cap, and says so in {@link PublishJudgement.capped}. + * - **An object.** Every flow the engine holds that can start on a record of + * the object (its `start` node's `objectName`, or a start input that is a + * record of the object), or whose `map` names the object for its items, as + * a root, with the written object in place of the held one. Only gaps on + * the written object are reported: the publish of one object is not + * refused for another's. + * + * What is not judged at publish, each a reading pinned by a test: + * + * - **A draft.** Only a write that goes `active` is judged (ADR-0094 D1). A + * draft is judged when it is promoted. + * - **A part that cannot be read.** A callee the engine does not hold is not + * refused here (`unreadable_flow`). The first request refuses an approval + * it cannot read whole, and the publish gate of #35143 owns a call to a + * flow the deployment does not hold. + * - **The host.** A host with no `job` service is not refused at publish + * (`no_job_service`): it is a fact of the host, not of what is authored, + * and the first request refuses it. + * - **An application in which no object declares `closedStates`**, with the + * written object in place: nothing is read. + */ + +import { + allNodes, + closedValuesOf, + judgeApprovalOpening, + type OpeningCheckSource, + type OpeningFlow, + type OpeningFlowBody, + type OpeningGap, +} from './approval-opening-check.js'; + +/** How many flows a publish judges as an approval's root before it stops. */ +export const MAX_PUBLISH_ROOTS = 64; +/** The gap kinds a publish does not report (see the module header). */ +const NOT_AT_PUBLISH: ReadonlySet = new Set(['unreadable_flow', 'no_job_service']); + +/** The write a publish gate judges. */ +export interface PublishedItem { + type: 'flow' | 'object'; + name: string; + body: unknown; +} + +/** The readers the publish check needs, as the engine holds things before the write. Every one answers, never throws. */ +export interface PublishCheckSource { + /** The object definition the engine holds under `name`, or `undefined`. */ + objectSchema(name: string): unknown; + /** Every object definition the engine holds, or `undefined` where it cannot list them. */ + allObjects(): readonly unknown[] | undefined; + /** Every flow name the engine holds, or `undefined` where it cannot list them. */ + flowNames(): Promise; + /** The flow the engine holds under `name`; `null` when it cannot be read. */ + flow(name: string): Promise; + /** The flow a `subflow` or a `map` of the flow filed under `callerKey` names as `name`; `null` when it cannot be read. */ + calleeFlow(name: string, callerKey: string): Promise; + /** As {@link OpeningCheckSource.nodeDescriptor}. */ + nodeDescriptor: OpeningCheckSource['nodeDescriptor']; +} + +/** What the publish check answers. */ +export interface PublishJudgement { + /** What the publish is refused for; empty when it goes ahead. */ + gaps: OpeningGap[]; + /** The walk stopped at {@link MAX_PUBLISH_ROOTS} roots: the roots past it were not judged. */ + capped: boolean; +} + +/** Judge a write that goes `active`. */ +export async function judgeApprovalPublish(item: PublishedItem, source: PublishCheckSource): Promise { + const none: PublishJudgement = { gaps: [], capped: false }; + const writtenFlow = item.type === 'flow' && isFlowBody(item.body) ? item.body : undefined; + if (item.type === 'flow' && !writtenFlow) return none; + + // The engine as it will hold things once the write lands. + const objectSchema = (name: string): unknown => + (item.type === 'object' && name === item.name ? item.body : source.objectSchema(name)); + const flow = async (name: string): Promise => + (writtenFlow && name === item.name ? { key: item.name, body: writtenFlow } : source.flow(name)); + const calleeFlow = async (name: string, callerKey: string): Promise => + (writtenFlow && name === item.name ? { key: item.name, body: writtenFlow } : source.calleeFlow(name, callerKey)); + + // Nothing is read in an application where no object declares the key. + const listed = source.allObjects(); + const declares = (schema: unknown): boolean => closedValuesOf(schema) !== undefined; + const appDeclares = item.type === 'object' && declares(item.body) + ? true + : Array.isArray(listed) + ? listed.some((o) => !(item.type === 'object' && nameOf(o) === item.name) && declares(o)) + : false; + if (!appDeclares) return none; + + const names = (await source.flowNames()) ?? []; + const roots: string[] = []; + let capped = false; + if (item.type === 'flow') { + // The written flow, then every flow that calls it, to any depth. + const callers = new Map>(); + for (const name of new Set(names)) { + if (name === item.name) continue; + const held = await flow(name); + if (!held) continue; + for (const callee of calledNames(held.body)) { + let set = callers.get(callee); + if (!set) callers.set(callee, (set = new Set())); + set.add(name); + } + } + if (writtenFlow) { + for (const callee of calledNames(writtenFlow)) { + let set = callers.get(callee); + if (!set) callers.set(callee, (set = new Set())); + set.add(item.name); + } + } + const seen = new Set([item.name]); + const queue = [item.name]; + while (queue.length > 0) { + const name = queue.shift()!; + if (roots.length >= MAX_PUBLISH_ROOTS) { capped = true; break; } + roots.push(name); + for (const caller of [...(callers.get(name) ?? [])].sort(cmp)) { + if (seen.has(caller)) continue; + seen.add(caller); + queue.push(caller); + } + } + } else { + // Every flow that can start on a record of the object, or maps over its records. + for (const name of [...new Set(names)].sort(cmp)) { + const held = await flow(name); + if (!held || !actsOnObject(held.body, item.name)) continue; + if (roots.length >= MAX_PUBLISH_ROOTS) { capped = true; break; } + roots.push(name); + } + } + + const checkSource: OpeningCheckSource = { + objectSchema, + calleeFlow, + nodeDescriptor: source.nodeDescriptor, + // A fact of the host, not of what is authored: the first request judges it. + hostRunsReconciler: true, + }; + const gaps: OpeningGap[] = []; + const seenGaps = new Set(); + for (const name of roots) { + const root = await flow(name); + if (!root) continue; + const objects = rootObjectsOf(root.body); + for (const rootObject of objects.length > 0 ? objects : [null]) { + const judgement = await judgeApprovalOpening({ rootFlow: root, rootFlowName: name, rootObject }, checkSource); + for (const gap of judgement.gaps) { + if (NOT_AT_PUBLISH.has(gap.kind)) continue; + if (item.type === 'object' && (gap as { object?: string }).object !== item.name) continue; + const key = JSON.stringify(gap); + if (seenGaps.has(key)) continue; + seenGaps.add(key); + gaps.push(gap); + } + } + } + return { gaps, capped }; +} + +/** + * The objects a flow can start on a record of: its `start` node's + * `objectName`, and the object of each start input that is a record + * (`variables[].objectName` with `isInput`, #29425). + */ +export function rootObjectsOf(body: OpeningFlowBody): string[] { + const out = new Set(); + for (const node of body.nodes ?? []) { + if (node.type !== 'start') continue; + const object = node.config?.objectName; + if (typeof object === 'string' && object) out.add(object); + } + const variables = (body as { variables?: unknown }).variables; + if (Array.isArray(variables)) { + for (const v of variables) { + const object = (v as { objectName?: unknown; isInput?: unknown } | null)?.objectName; + if ((v as { isInput?: unknown }).isInput === true && typeof object === 'string' && object) out.add(object); + } + } + return [...out].sort(cmp); +} + +/** Whether a flow can start on a record of `object`, or one of its `map` nodes names `object` for its items. */ +function actsOnObject(body: OpeningFlowBody, object: string): boolean { + if (rootObjectsOf(body).includes(object)) return true; + return allNodes(body).some((n) => n.type === 'map' && n.config?.itemObject === object); +} + +/** The flow names the `subflow` and `map` nodes of a flow call, at any region depth. */ +function calledNames(body: OpeningFlowBody): string[] { + const out = new Set(); + for (const node of allNodes(body)) { + if (node.type !== 'subflow' && node.type !== 'map') continue; + const name = node.config?.flowName; + if (typeof name === 'string' && name) out.add(name); + } + return [...out]; +} + +function isFlowBody(value: unknown): value is OpeningFlowBody { + return value !== null && typeof value === 'object' && Array.isArray((value as { nodes?: unknown }).nodes); +} + +function nameOf(schema: unknown): string | undefined { + const name = (schema as { name?: unknown } | null)?.name; + return typeof name === 'string' ? name : undefined; +} + +function cmp(a: string, b: string): number { + return a < b ? -1 : a > b ? 1 : 0; +} diff --git a/packages/plugins/plugin-approvals/src/approval-publish-gate-37766.integration.test.ts b/packages/plugins/plugin-approvals/src/approval-publish-gate-37766.integration.test.ts new file mode 100644 index 00000000000..8efac8488db --- /dev/null +++ b/packages/plugins/plugin-approvals/src/approval-publish-gate-37766.integration.test.ts @@ -0,0 +1,164 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 Execution item 7; #37766 slice N45] The opening check's + * conditions, reported at the real metadata door: the approvals plugin adds + * its gates beside each type's owner gate (`addAuthoringGate`) on + * kernel:ready, and a flow or an object that goes `active` where an approval + * could not open is refused with a 422 `VALIDATION_FAILED` that names what is + * missing. A draft is not refused; its promotion is. The read itself, arm by + * arm, is pinned over fixtures in `approval-publish-check.test.ts`. + * + * Real kernel, real ObjectQL engine and metadata protocol, real automation + * engine, the real approvals plugin, driver-sql on better-sqlite3 `:memory:`. + */ + +import { describe, it, expect, afterEach } from 'vitest'; +import { ObjectKernel } from '@objectstack/core'; +import { ObjectQLPlugin, type ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { AutomationServicePlugin, type AutomationEngine } from '@objectstack/service-automation'; +import { ApprovalsServicePlugin } from './approvals-plugin.js'; + +const text = (name: string) => ({ name, type: 'text' as const }); +const statusField = { + name: 'approval_status', type: 'select' as const, defaultValue: 'draft', + options: ['draft', 'pending', 'returned', 'approved', 'rejected', 'recalled'].map((value) => ({ label: value, value })), +}; +const fields = { name: text('name'), approval_status: statusField }; +/** Closes on its approval's outcome, and meets every condition of D5. */ +const invoice = { name: 'crm_invoice', label: 'Invoice', fields, closedStates: { approval_status: ['approved', 'rejected'] } }; +/** Declares no closed state. */ +const memo = { name: 'crm_memo', label: 'Memo', fields }; + +const step = (id: string, approver: string) => ({ + id, type: 'approval', label: id, + config: { approvers: [{ type: 'user', value: approver }], approvalStatusField: 'approval_status' }, +}); + +/** Two steps on `object`'s approval field, with a timer between them where `hold`: D5 condition 5. */ +function approvalFlow(name: string, object: string, hold: boolean) { + const nodes: any[] = [ + { id: 'start', type: 'start', label: 'Start', config: { objectName: object, triggerType: 'record-after-update' } }, + step('first', 'approver'), + ...(hold ? [{ id: 'hold', type: 'wait', label: 'Hold', waitEventConfig: { eventType: 'timer', timerDuration: 'PT1H' } }] : []), + step('second', 'approver2'), + { id: 'end', type: 'end', label: 'End' }, + ]; + const afterFirst = hold ? 'hold' : 'second'; + return { + name, label: name, type: 'autolaunched', + nodes, + edges: [ + { id: 'e0', source: 'start', target: 'first' }, + { id: 'e1a', source: 'first', target: afterFirst, label: 'approve' }, + { id: 'e1r', source: 'first', target: 'end', label: 'reject' }, + ...(hold ? [{ id: 'e2', source: 'hold', target: 'second' }] : []), + { id: 'e3a', source: 'second', target: 'end', label: 'approve' }, + { id: 'e3r', source: 'second', target: 'end', label: 'reject' }, + ], + }; +} + +describe('[ADR-0162 item 7, N45] the opening check reported at publish', () => { + let kernel: ObjectKernel; + let ql: ObjectQL; + let automation: AutomationEngine; + let protocol: any; + + afterEach(async () => { + try { await kernel?.shutdown(); } catch { /* noop */ } + }); + + async function boot() { + kernel = new ObjectKernel({ logger: { level: 'silent' } } as any); + await kernel.use(new ObjectQLPlugin()); + await kernel.use(new AutomationServicePlugin()); + await kernel.use(new ApprovalsServicePlugin()); + await kernel.bootstrap(); + ql = kernel.getService('objectql'); + automation = kernel.getService('automation'); + protocol = kernel.getService('protocol'); + + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); + await driver.connect(); + ql.registerDriver(driver, true); + // The plugin registers its own `sys_approval_*` objects. + for (const def of [invoice, memo]) ql.registry.registerObject(def as any, 'approvals-test', 'approvals-test'); + await ql.syncSchemas(); + } + + const flowRows = async (name: string) => + (await ql.find('sys_metadata', { where: { type: 'flow', name }, context: { isSystem: true } })) as any[]; + + it('the plugin adds its gates beside the owner gates on kernel:ready', async () => { + await boot(); + expect(typeof protocol.addAuthoringGate).toBe('function'); + const added = (protocol as { additionalAuthoringGates: Map }).additionalAuthoringGates; + expect(added.get('flow')).toHaveLength(1); + expect(added.get('object')).toHaveLength(1); + }); + + it('refuses an active save of a flow whose approval holds a pause between two steps on a closing field', async () => { + await boot(); + const err = await protocol.saveMetaItem({ + type: 'flow', name: 'invoice_wait', item: approvalFlow('invoice_wait', 'crm_invoice', true), + }).catch((e: any) => e); + expect(err).toBeInstanceOf(Error); + expect(err.status).toBe(422); + expect(err.code).toBe('VALIDATION_FAILED'); + expect(err.message).toContain('flow invoice_wait was not published'); + expect(err.message).toContain('Node hold (wait) of flow invoice_wait can pause the run between two approval steps of crm_invoice'); + expect((await flowRows('invoice_wait')).filter((r) => r.state === 'active')).toEqual([]); + }); + + it('words the refusal in the locale the door states', async () => { + await boot(); + const err = await protocol.saveMetaItem({ + type: 'flow', name: 'invoice_wait', item: approvalFlow('invoice_wait', 'crm_invoice', true), userTextLocales: ['zh-CN'], + }).catch((e: any) => e); + expect(err.status).toBe(422); + expect(err.userMessage).toMatch(/^flow invoice_wait 没有发布:/); + }); + + it('lets a flow through that meets every condition', async () => { + await boot(); + const out = await protocol.saveMetaItem({ type: 'flow', name: 'invoice_ok', item: approvalFlow('invoice_ok', 'crm_invoice', false) }); + expect(out.success).toBe(true); + }); + + it('does not refuse a flow on an object that declares no closed state', async () => { + await boot(); + const out = await protocol.saveMetaItem({ type: 'flow', name: 'memo_wait', item: approvalFlow('memo_wait', 'crm_memo', true) }); + expect(out.success).toBe(true); + }); + + it('does not refuse a draft, and refuses its promotion', async () => { + await boot(); + const saved = await protocol.saveMetaItem({ + type: 'flow', name: 'invoice_wait', item: approvalFlow('invoice_wait', 'crm_invoice', true), mode: 'draft', + }); + expect(saved.success).toBe(true); + const err = await protocol.publishMetaItem({ type: 'flow', name: 'invoice_wait' }).catch((e: any) => e); + expect(err.status).toBe(422); + expect(err.code).toBe('VALIDATION_FAILED'); + expect((await flowRows('invoice_wait')).filter((r) => r.state === 'active')).toEqual([]); + }); + + it('refuses an object that starts to close on its approval field where a held approval holds a pause between two steps', async () => { + await boot(); + // An object authored here (the code-registered ones are sealed), first + // with no closed state, and an approval flow on it the engine holds. + const authored = { name: 'crm_note', label: 'Note', sharingModel: 'private', fields }; + expect((await protocol.saveMetaItem({ type: 'object', name: 'crm_note', item: authored })).success).toBe(true); + automation.registerFlow('note_wait', approvalFlow('note_wait', 'crm_note', true) as any); + const err = await protocol.saveMetaItem({ + type: 'object', name: 'crm_note', item: { ...authored, closedStates: { approval_status: ['approved', 'rejected'] } }, + }).catch((e: any) => e); + expect(err).toBeInstanceOf(Error); + expect(err.status).toBe(422); + expect(err.code).toBe('VALIDATION_FAILED'); + expect(err.message).toContain('object crm_note was not published'); + expect(err.message).toContain('Node hold (wait) of flow note_wait can pause the run between two approval steps of crm_note'); + }); +}); diff --git a/packages/plugins/plugin-approvals/src/approval-publish-gate.ts b/packages/plugins/plugin-approvals/src/approval-publish-gate.ts new file mode 100644 index 00000000000..a258b4902e4 --- /dev/null +++ b/packages/plugins/plugin-approvals/src/approval-publish-gate.ts @@ -0,0 +1,93 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 D5, Execution item 7; #37766 slice N45] The publish gates that + * report the opening check's conditions where a flow or an object goes + * `active` (`approval-publish-check.ts` says what is judged). + * + * Added beside each type's owner gate through the metadata protocol's + * `addAuthoringGate`: plugin-security owns the `object` slot, and the slot of + * `registerAuthoringGate` holds one gate per type. An added gate runs on every + * save and restore the owner gate runs on, and on the promotion of a draft, + * which the owner gate does not run on. It judges an `active` write only. + * + * The refusal is a 422 `VALIDATION_FAILED`: `message` in `en`, the + * diagnostic, and `userMessage` in the first locale the write door states + * (`userTextLocales`), from the plugin's own catalog. A judge that fails is + * logged and refuses nothing: the report is early notice, and the first + * request is the rule. + */ + +import type { OpeningGap } from './approval-opening-check.js'; +import { publishRefusalText } from './approval-opening-refusal.js'; +import type { PublishJudgement, PublishedItem } from './approval-publish-check.js'; +import { MAX_PUBLISH_ROOTS } from './approval-publish-check.js'; + +/** The write context the gate reads: the slice of the protocol's `MetadataAuthoringGateContext` it consumes. */ +export interface ApprovalPublishGateContext { + type: string; + name: string; + state: 'draft' | 'active'; + body: unknown; + userTextLocales?: readonly string[]; +} + +/** The publish of a flow or an object that an approval could not open on is refused. */ +export class ApprovalPublishRefusedError extends Error { + readonly code = 'VALIDATION_FAILED'; + readonly status = 422; + readonly statusCode = 422; + /** The refusal addressed to the author, in the first locale the write door states; `message` stays in `en`. */ + readonly userMessage: string; + readonly gaps: readonly OpeningGap[]; + + constructor(gaps: readonly OpeningGap[], subject: { type: string; name: string }, userTextLocales?: readonly string[]) { + super(publishRefusalText(gaps, subject, 'en')); + this.name = 'ApprovalPublishRefusedError'; + this.gaps = gaps; + const locale = userTextLocales?.find((l) => typeof l === 'string' && l.length > 0); + this.userMessage = publishRefusalText(gaps, subject, locale ?? 'en'); + } +} + +/** The protocol members the registration reads. */ +interface PublishGateProtocol { + addAuthoringGate?(type: string, gate: (ctx: ApprovalPublishGateContext) => Promise): void; +} + +/** + * Add the `flow` and `object` publish gates to `protocol`. Feature-detected: a + * protocol with no `addAuthoringGate` gets none, and the first request still + * refuses. Returns `true` when added. + */ +export function registerApprovalPublishGates( + protocol: unknown, + judge: (item: PublishedItem) => Promise, + logger?: { warn?: (message: string, meta?: Record) => void }, +): boolean { + const p = protocol as PublishGateProtocol | null | undefined; + if (!p || typeof p.addAuthoringGate !== 'function') return false; + for (const type of ['flow', 'object'] as const) { + p.addAuthoringGate(type, async (ctx) => { + if (ctx.state !== 'active') return; + let judgement: PublishJudgement; + try { + judgement = await judge({ type, name: ctx.name, body: ctx.body }); + } catch (err: any) { + logger?.warn?.('[approvals] the publish check could not judge a write; it is not refused, and the approval\'s first request still judges it (ADR-0162 item 7)', { + type, name: ctx.name, error: err?.message ?? String(err), + }); + return; + } + if (judgement.capped) { + logger?.warn?.(`[approvals] the publish check judged the first ${MAX_PUBLISH_ROOTS} approval flows this write reaches and stopped; the rest are not judged here, and each approval's first request still judges it (ADR-0162 item 7)`, { + type, name: ctx.name, + }); + } + if (judgement.gaps.length > 0) { + throw new ApprovalPublishRefusedError(judgement.gaps, { type, name: ctx.name }, ctx.userTextLocales); + } + }); + } + return true; +} diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index 6b0c526b581..892c10c82ef 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -180,6 +180,7 @@ import { consolePageLink, type ConsolePageComposer } from './public-base-url.js' import { APPROVAL_EMAIL_CHANNELS, EMAILED_APPROVAL_TOPICS } from './approval-email-templates.js'; import { enMessages } from './translations/messages.js'; import { closedValuesOf, judgeApprovalOpening, type OpeningFlow } from './approval-opening-check.js'; +import { judgeApprovalPublish, type PublishJudgement, type PublishedItem } from './approval-publish-check.js'; import { openingRefusalText } from './approval-opening-refusal.js'; import { approvalMessageKey, @@ -339,6 +340,16 @@ export interface ApprovalResumeSurface { * that can pause. */ getActionDescriptor?(type: string): { supportsPause?: unknown; aliasOf?: unknown } | undefined; + /** + * [#37766, N45] Every flow the engine holds, by name (one entry per slot). + * Read by the publish check ({@link ApprovalService.judgePublishedItem}) to + * find the flows that call a published flow and the flows that act on a + * published object. ⚠️ Declares a method `AutomationEngine` ALREADY + * implements publicly (`listFlows`, `IAutomationService`); it widens no + * engine surface. Optional: absent, a publish judges the published flow + * alone, and an object publish judges nothing. + */ + listFlows?(): Promise; /** * [#35863] A flow name's registrations, oldest first: each body and when it * was registered. Read by {@link ApprovalService.attachFlowRoute} to tell @@ -2702,6 +2713,43 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega this.sweepClockScheduled = true; } + /** + * [ADR-0162 Execution item 7; #37766 slice N45] Judge a flow or an object + * about to go `active` by the conditions an approval opens on, as the engine + * will hold things once the write lands ({@link judgeApprovalPublish}). The + * plugin's publish gates call it (`approval-publish-gate.ts`). Every reader + * answers, never throws: a read that fails is a part that cannot be read, + * which is not refused at publish. + */ + async judgePublishedItem(item: PublishedItem): Promise { + const automation = this.automation; + return judgeApprovalPublish(item, { + objectSchema: (name) => { try { return this.engine.getSchema?.(name); } catch { return undefined; } }, + allObjects: () => { + try { + const listed = this.engine.registry?.getAllObjects?.(); + return Array.isArray(listed) ? listed : undefined; + } catch { return undefined; } + }, + flowNames: async () => { + if (typeof automation?.listFlows !== 'function') return undefined; + try { return await automation.listFlows(); } catch { return undefined; } + }, + flow: async (name) => { + if (typeof automation?.getFlow !== 'function') return null; + try { + const body = await automation.getFlow(name); + return body && typeof body === 'object' ? { key: name, body } : null; + } catch { return null; } + }, + calleeFlow: (name, callerKey) => this.openingCalleeFlow(name, callerKey), + nodeDescriptor: (type) => { + if (typeof automation?.getActionDescriptor !== 'function') return 'unread'; + try { return automation.getActionDescriptor(type); } catch { return 'unread'; } + }, + }); + } + /** Attach (or replace) the messaging surface used for thread notifications. */ attachMessaging(messaging: ApprovalMessagingSurface): void { this.messaging = messaging; diff --git a/packages/plugins/plugin-approvals/src/approvals-plugin.ts b/packages/plugins/plugin-approvals/src/approvals-plugin.ts index be3dbb05f21..054ccb2d171 100644 --- a/packages/plugins/plugin-approvals/src/approvals-plugin.ts +++ b/packages/plugins/plugin-approvals/src/approvals-plugin.ts @@ -52,6 +52,7 @@ import { backfillApprovalDisplayLabels } from './display-label-backfill.js'; import { backfillProcessPackages, logProcessPackageBackfill, type FlowHolderSource } from './stored-process-package-backfill.js'; import { APPROVAL_EMAIL_TEMPLATES } from './approval-email-templates.js'; import { consolePageLink, resolvePublicBaseUrl } from './public-base-url.js'; +import { registerApprovalPublishGates } from './approval-publish-gate.js'; export interface ApprovalsPluginOptions { /** Disable runtime registration (schemas still register). */ @@ -557,6 +558,19 @@ export class ApprovalsServicePlugin implements Plugin { ctx.logger.info('ApprovalsServicePlugin: SLA escalation scan scheduled', { intervalMs }); } catch { /* job service not installed */ } }; + // [ADR-0162 Execution item 7; #37766 slice N45] The opening check's + // conditions, reported where a flow or an object goes `active`: gates added + // beside each type's owner gate on the metadata protocol. Wired on + // kernel:ready, when the protocol and the automation engine are in place. + // A protocol with no `addAuthoringGate` gets none; the first request of an + // approval still refuses (`approval-publish-gate.ts`). + const wirePublishGates = async () => { + if (!this.service) return; + let protocol: unknown; + try { protocol = ctx.getService('protocol'); } catch { return; } + const svc = this.service; + registerApprovalPublishGates(protocol, (item) => svc.judgePublishedItem(item), ctx.logger); + }; // Actionable-link pages (ADR-0043): session-less confirm + redemption, // mounted straight on the host Hono app. GET only renders; the decision // happens exclusively on the POST (mail-gateway prefetch safe). @@ -687,6 +701,7 @@ export class ApprovalsServicePlugin implements Plugin { if (typeof (ctx as any).hook === 'function') { (ctx as any).hook('kernel:ready', wireEscalationClock); + (ctx as any).hook('kernel:ready', wirePublishGates); (ctx as any).hook('kernel:ready', mountActionPages); (ctx as any).hook('kernel:ready', backfillApproverIndex); (ctx as any).hook('kernel:ready', backfillSlots); diff --git a/packages/plugins/plugin-approvals/src/translations/messages.ts b/packages/plugins/plugin-approvals/src/translations/messages.ts index ee99b8e5e41..de3b8d30c6b 100644 --- a/packages/plugins/plugin-approvals/src/translations/messages.ts +++ b/packages/plugins/plugin-approvals/src/translations/messages.ts @@ -134,6 +134,7 @@ const enSentences = { approvalOpeningMapApproval: 'The map node {{node}} of flow {{flow}} runs an approval step for each item, and the node does not show that no item is a record; an approval of another record would hold {{object}} between two steps.', approvalOpeningUnreadableFlow: 'Flow {{flow}}, which the approval runs, could not be read, so the approval cannot be checked.', approvalOpeningNoJobService: '{{object}} declares closedStates, and this host runs no job service, so nothing would end an approval nobody finishes; install a job service.', + approvalPublishRefusedLead: '{{type}} {{name}} was not published: an approval it takes part in could not show itself in progress on a field its object closes on.', approvalSlaBreachedSubmitterTitle: 'Your approval request breached its SLA', approvalSlaBreachedSubmitterBody: "{{object}} {{record}}: escalation action '{{action}}' was taken.", approvalApprovedTitle: 'Request approved', @@ -281,6 +282,7 @@ export const zhCNMessages: ApprovalMessages = { approvalOpeningMapApproval: '流程 {{flow}} 的 map 节点 {{node}} 为每一项运行一个审批步骤,而该节点无法表明所有项都不是记录;另一条记录的审批会让 {{object}} 停在两个步骤之间。', approvalOpeningUnreadableFlow: '审批要运行的流程 {{flow}} 无法读取,因此无法检查这次审批。', approvalOpeningNoJobService: '{{object}} 声明了 closedStates,而本宿主没有运行 job 服务,没人完成的审批将无法结束;请安装 job 服务。', + approvalPublishRefusedLead: '{{type}} {{name}} 没有发布:它参与的审批无法在对象会关闭的字段上显示「审批中」。', approvalSlaBreachedSubmitterTitle: '您的审批请求已超出时限', approvalSlaBreachedSubmitterBody: '{{object}} {{record}}:已执行升级操作「{{action}}」。', approvalApprovedTitle: '请求已批准', @@ -365,6 +367,7 @@ export const jaJPMessages: ApprovalMessages = { approvalOpeningMapApproval: 'フロー {{flow}} の map ノード {{node}} は項目ごとに承認ステップを実行しますが、どの項目もレコードでないことをノードが示していません。別のレコードの承認により {{object}} が二つのステップの間で保留されます。', approvalOpeningUnreadableFlow: '承認が実行するフロー {{flow}} を読み取れなかったため、承認を確認できません。', approvalOpeningNoJobService: '{{object}} は closedStates を宣言していますが、このホストでは job サービスが動いていないため、誰も完了しない承認を終わらせるものがありません。job サービスをインストールしてください。', + approvalPublishRefusedLead: '{{type}} {{name}} は公開されませんでした:これが関わる承認は、オブジェクトがクローズするフィールドに承認中を表示できません。', approvalSlaBreachedSubmitterTitle: 'あなたの承認申請が期限を超過しました', approvalSlaBreachedSubmitterBody: '{{object}} {{record}}:エスカレーション操作「{{action}}」が実行されました。', approvalApprovedTitle: '申請が承認されました', @@ -449,6 +452,7 @@ export const esESMessages: ApprovalMessages = { approvalOpeningMapApproval: 'El nodo map {{node}} del flujo {{flow}} ejecuta un paso de aprobación por cada elemento, y el nodo no muestra que ningún elemento sea un registro; la aprobación de otro registro retendría {{object}} entre dos pasos.', approvalOpeningUnreadableFlow: 'No se pudo leer el flujo {{flow}}, que la aprobación ejecuta, así que no se puede comprobar la aprobación.', approvalOpeningNoJobService: '{{object}} declara closedStates y este host no ejecuta ningún servicio job, así que nada terminaría una aprobación que nadie complete; instale un servicio job.', + approvalPublishRefusedLead: 'No se publicó {{type}} {{name}}: una aprobación en la que participa no puede mostrarse en curso en un campo en el que su objeto se cierra.', approvalSlaBreachedSubmitterTitle: 'Su solicitud de aprobación ha superado su plazo', approvalSlaBreachedSubmitterBody: "{{object}} {{record}}: se ha ejecutado la acción de escalado '{{action}}'.", approvalApprovedTitle: 'Solicitud aprobada', @@ -533,6 +537,7 @@ export const zhHantMessages: ApprovalMessages = { approvalOpeningMapApproval: '流程 {{flow}} 的 map 節點 {{node}} 為每一項執行一個核准步驟,而該節點無法表明所有項目都不是記錄;另一筆記錄的核准會讓 {{object}} 停在兩個步驟之間。', approvalOpeningUnreadableFlow: '核准要執行的流程 {{flow}} 無法讀取,因此無法檢查這次核准。', approvalOpeningNoJobService: '{{object}} 宣告了 closedStates,而本主機沒有執行 job 服務,沒有人完成的核准將無法結束;請安裝 job 服務。', + approvalPublishRefusedLead: '{{type}} {{name}} 沒有發布:它參與的核准無法在物件會關閉的欄位上顯示「核准中」。', approvalSlaBreachedSubmitterTitle: '你的核准請求已逾時', approvalSlaBreachedSubmitterBody: '{{object}} {{record}}:已執行升級動作「{{action}}」。', approvalApprovedTitle: '請求已核准', @@ -617,6 +622,7 @@ export const arMessages: ApprovalMessages = { approvalOpeningMapApproval: 'عقدة map {{node}} في التدفق {{flow}} تشغّل خطوة موافقة لكل عنصر، والعقدة لا تُظهر أن أي عنصر ليس سجلًا؛ موافقة سجل آخر ستحتجز {{object}} بين خطوتين.', approvalOpeningUnreadableFlow: 'تعذّرت قراءة التدفق {{flow}} الذي تشغّله الموافقة، لذا لا يمكن فحص الموافقة.', approvalOpeningNoJobService: 'يصرّح {{object}} بـ closedStates، وهذا المضيف لا يشغّل خدمة job، فلا شيء سينهي موافقة لا يكملها أحد؛ ثبّت خدمة job.', + approvalPublishRefusedLead: 'لم يُنشَر {{type}} {{name}}: موافقة يشارك فيها لا تستطيع أن تُظهر أنها جارية على حقل يُغلَق عليه كائنها.', approvalSlaBreachedSubmitterTitle: 'تجاوز طلب الموافقة الخاص بك مهلته', approvalSlaBreachedSubmitterBody: '{{object}} {{record}}: نُفِّذ إجراء التصعيد «{{action}}».', approvalApprovedTitle: 'تمت الموافقة على الطلب', @@ -701,6 +707,7 @@ export const frMessages: ApprovalMessages = { approvalOpeningMapApproval: 'Le nœud map {{node}} du flux {{flow}} exécute une étape d\'approbation pour chaque élément, et le nœud ne montre pas qu\'aucun élément n\'est un enregistrement ; l\'approbation d\'un autre enregistrement retiendrait {{object}} entre deux étapes.', approvalOpeningUnreadableFlow: 'Le flux {{flow}}, que l\'approbation exécute, n\'a pas pu être lu ; l\'approbation ne peut donc pas être vérifiée.', approvalOpeningNoJobService: '{{object}} déclare closedStates et cet hôte n\'exécute aucun service job : rien ne terminerait une approbation que personne n\'achève ; installez un service job.', + approvalPublishRefusedLead: '{{type}} {{name}} n\'a pas été publié : une approbation à laquelle il prend part ne peut pas s\'afficher en cours sur un champ sur lequel son objet se ferme.', approvalSlaBreachedSubmitterTitle: 'Votre demande d’approbation a dépassé son délai', approvalSlaBreachedSubmitterBody: '{{object}} {{record}} : l’action d’escalade « {{action}} » a été exécutée.', approvalApprovedTitle: 'Demande approuvée', @@ -785,6 +792,7 @@ export const ptBRMessages: ApprovalMessages = { approvalOpeningMapApproval: 'O nó map {{node}} do fluxo {{flow}} executa uma etapa de aprovação para cada item, e o nó não mostra que nenhum item é um registro; a aprovação de outro registro reteria {{object}} entre duas etapas.', approvalOpeningUnreadableFlow: 'O fluxo {{flow}}, que a aprovação executa, não pôde ser lido, então a aprovação não pode ser verificada.', approvalOpeningNoJobService: '{{object}} declara closedStates e este host não executa nenhum serviço job, então nada encerraria uma aprovação que ninguém conclua; instale um serviço job.', + approvalPublishRefusedLead: '{{type}} {{name}} não foi publicado: uma aprovação da qual ele participa não consegue se mostrar em andamento em um campo no qual seu objeto é fechado.', approvalSlaBreachedSubmitterTitle: 'Sua solicitação de aprovação estourou o prazo', approvalSlaBreachedSubmitterBody: '{{object}} {{record}}: a ação de escalonamento "{{action}}" foi executada.', approvalApprovedTitle: 'Solicitação aprovada', @@ -869,6 +877,7 @@ export const ruMessages: ApprovalMessages = { approvalOpeningMapApproval: 'Узел map {{node}} процесса {{flow}} запускает шаг согласования для каждого элемента, и узел не показывает, что ни один элемент не является записью; согласование другой записи задержит {{object}} между двумя шагами.', approvalOpeningUnreadableFlow: 'Не удалось прочитать процесс {{flow}}, который запускает согласование, поэтому согласование нельзя проверить.', approvalOpeningNoJobService: '{{object}} объявляет closedStates, а на этом хосте не работает служба job, поэтому согласование, которое никто не завершит, ничто не закончит; установите службу job.', + approvalPublishRefusedLead: '{{type}} {{name}} не опубликован: согласование, в котором он участвует, не может показать, что идёт, в поле, по которому закрывается его объект.', approvalSlaBreachedSubmitterTitle: 'Ваш запрос на согласование нарушил срок', approvalSlaBreachedSubmitterBody: '{{object}} {{record}}: выполнено действие эскалации «{{action}}».', approvalApprovedTitle: 'Запрос одобрен', @@ -953,6 +962,7 @@ export const deMessages: ApprovalMessages = { approvalOpeningMapApproval: 'Der map-Knoten {{node}} des Flows {{flow}} führt für jedes Element einen Genehmigungsschritt aus, und der Knoten zeigt nicht, dass kein Element ein Datensatz ist; die Genehmigung eines anderen Datensatzes würde {{object}} zwischen zwei Schritten festhalten.', approvalOpeningUnreadableFlow: 'Der Flow {{flow}}, den die Genehmigung ausführt, konnte nicht gelesen werden, daher kann die Genehmigung nicht geprüft werden.', approvalOpeningNoJobService: '{{object}} deklariert closedStates, und dieser Host betreibt keinen job-Dienst, sodass nichts eine Genehmigung beenden würde, die niemand abschließt; installieren Sie einen job-Dienst.', + approvalPublishRefusedLead: '{{type}} {{name}} wurde nicht veröffentlicht: Eine Genehmigung, an der es beteiligt ist, kann sich auf einem Feld, auf dem ihr Objekt schließt, nicht als laufend zeigen.', approvalSlaBreachedSubmitterTitle: 'Ihre Genehmigungsanfrage hat ihre Frist überschritten', approvalSlaBreachedSubmitterBody: '{{object}} {{record}}: Die Eskalationsaktion „{{action}}“ wurde ausgeführt.', approvalApprovedTitle: 'Anfrage genehmigt', @@ -1037,6 +1047,7 @@ export const koMessages: ApprovalMessages = { approvalOpeningMapApproval: '흐름 {{flow}}의 map 노드 {{node}}는 항목마다 승인 단계를 실행하며, 노드는 어떤 항목도 레코드가 아님을 보여 주지 않습니다. 다른 레코드의 승인이 {{object}}를 두 단계 사이에 붙잡아 둘 수 있습니다.', approvalOpeningUnreadableFlow: '승인이 실행하는 흐름 {{flow}}을 읽을 수 없어 승인을 확인할 수 없습니다.', approvalOpeningNoJobService: '{{object}}는 closedStates를 선언하지만 이 호스트는 job 서비스를 실행하지 않아, 아무도 끝내지 않는 승인을 종료할 수단이 없습니다. job 서비스를 설치하세요.', + approvalPublishRefusedLead: '{{type}} {{name}}이(가) 게시되지 않았습니다: 이것이 참여하는 승인은 개체가 닫히는 필드에 진행 중임을 표시할 수 없습니다.', approvalSlaBreachedSubmitterTitle: '승인 요청이 기한을 넘겼습니다', approvalSlaBreachedSubmitterBody: "{{object}} {{record}}: 에스컬레이션 작업 '{{action}}'이(가) 실행되었습니다.", approvalApprovedTitle: '요청 승인됨', From 4b91cd2e6f5e615fd571323a910a006c1aaad233 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 07:40:13 +0000 Subject: [PATCH 2/4] chore(gates): record the add-authoring-gate test's engine doubles in the pinned ledger Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5nzgcVrZ8Neqqd1AFi --- scripts/engine-double-contract.pinned.json | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/scripts/engine-double-contract.pinned.json b/scripts/engine-double-contract.pinned.json index 37a689920f6..5b2cb47b992 100644 --- a/scripts/engine-double-contract.pinned.json +++ b/scripts/engine-double-contract.pinned.json @@ -436,6 +436,21 @@ "verb": "update", "pinned": 1 }, + { + "file": "packages/metadata-protocol/src/protocol.add-authoring-gate-37766.test.ts", + "verb": "delete", + "pinned": 1 + }, + { + "file": "packages/metadata-protocol/src/protocol.add-authoring-gate-37766.test.ts", + "verb": "findOne", + "pinned": 1 + }, + { + "file": "packages/metadata-protocol/src/protocol.add-authoring-gate-37766.test.ts", + "verb": "update", + "pinned": 1 + }, { "file": "packages/metadata-protocol/src/protocol.adopt-orphans-owner-judges.test.ts", "verb": "findOne", From 4172ad6382f4aa1c24879ceda70b55c1a1bf12e6 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 07:48:29 +0000 Subject: [PATCH 3/4] fix(approvals): refuse the publish with the documented 400, and make the gate test doubles drivable The publish refusal carries VALIDATION_FAILED at 400, the status the error ledger documents for that code. The add-authoring-gate test loads @objectstack/lint at module top and its find double honours a caller's limit. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5nzgcVrZ8Neqqd1AFi --- .changeset/37766-publish-gate-approvals.md | 2 +- .../protocol.add-authoring-gate-37766.test.ts | 24 +++++++++---------- .../src/approval-publish-check.test.ts | 4 ++-- ...val-publish-gate-37766.integration.test.ts | 10 ++++---- .../src/approval-publish-gate.ts | 6 ++--- 5 files changed, 22 insertions(+), 24 deletions(-) diff --git a/.changeset/37766-publish-gate-approvals.md b/.changeset/37766-publish-gate-approvals.md index 75a24ecacb5..4fdbce7516f 100644 --- a/.changeset/37766-publish-gate-approvals.md +++ b/.changeset/37766-publish-gate-approvals.md @@ -14,7 +14,7 @@ At kernel:ready the plugin adds publish gates for `flow` and `object` beside the - **A flow.** It is judged as an approval's root, together with every flow that calls it through a `subflow` or a `map`, to any depth, with the written body in place. The walk up the callers ends on a flow that calls itself and on flows that call each other. It stops after 64 roots: past that, nothing is refused for the cap, and one warning says so. - **An object.** Every flow that can start on one of its records, or maps over them, is judged with the written object in place. Only gaps on the written object are reported. -The refusal is a 422 `VALIDATION_FAILED` that names the item, then gives one sentence per gap: the flow, the step, the object, the field and what is missing, in the first locale the write door states. These are the same sentences an approval's first request is refused with. +The refusal is a 400 `VALIDATION_FAILED` that names the item, then gives one sentence per gap: the flow, the step, the object, the field and what is missing, in the first locale the write door states. These are the same sentences an approval's first request is refused with. Not refused at publish: - a draft (it is judged when it is promoted); diff --git a/packages/metadata-protocol/src/protocol.add-authoring-gate-37766.test.ts b/packages/metadata-protocol/src/protocol.add-authoring-gate-37766.test.ts index fdcd0b26d96..abae024dbd3 100644 --- a/packages/metadata-protocol/src/protocol.add-authoring-gate-37766.test.ts +++ b/packages/metadata-protocol/src/protocol.add-authoring-gate-37766.test.ts @@ -13,6 +13,8 @@ */ import { describe, expect, it, vi } from 'vitest'; +// Pay the lazy `@objectstack/lint` load during collection, not inside a clocked case. +import '@objectstack/lint'; import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, @@ -103,15 +105,11 @@ function makeStubEngine() { assertEngineFindOnePredicate(table, opts); return findRow(table, opts.where)?.row ?? null; }, - async find(table: string, opts: { where: Record }) { - return Array.from(tableOf(table).values()).filter((r) => { - if (opts.where.type && !whereValueMatches(r.type, opts.where.type)) return false; - if (opts.where.name !== undefined && r.name !== opts.where.name) return false; - if (opts.where.organization_id !== undefined - && r.organization_id !== opts.where.organization_id) return false; - if (opts.where.state && r.state !== opts.where.state) return false; - return true; - }); + async find(table: string, opts: { where: Record; limit?: number }) { + // Every stated key of the `where` is matched (`$in` or equality), then the bound. + const matched = Array.from(tableOf(table).values()).filter((r) => + Object.entries(opts.where).every(([k, v]) => v === undefined || whereValueMatches(r[k], v))); + return typeof opts?.limit === 'number' ? matched.slice(0, opts.limit) : matched; }, async insert(table: string, data: Record) { nextId += 1; @@ -225,10 +223,10 @@ describe('addAuthoringGate: a gate beside the owner gate (#37766)', () => { const { protocol } = makeProtocolOn(); protocol.addAuthoringGate('object', () => { const err: any = new Error('refused'); - err.code = 'VALIDATION_FAILED'; err.status = 422; + err.code = 'VALIDATION_FAILED'; err.status = 400; throw err; }); - await expect(protocol.runAuthoringGate(gateEvent())).rejects.toMatchObject({ code: 'VALIDATION_FAILED', status: 422 }); + await expect(protocol.runAuthoringGate(gateEvent())).rejects.toMatchObject({ code: 'VALIDATION_FAILED', status: 400 }); }); it('a throw of the owner gate stops the write before any added gate runs', async () => { @@ -268,11 +266,11 @@ describe('addAuthoringGate through the save and publish doors (#37766)', () => { const { protocol, rows } = makeProtocolOn(); protocol.addAuthoringGate('flow', (ctx: any) => { if (ctx.state !== 'active') return; - throw Object.assign(new Error('VALIDATION_FAILED: refused'), { code: 'VALIDATION_FAILED', status: 422 }); + throw Object.assign(new Error('VALIDATION_FAILED: refused'), { code: 'VALIDATION_FAILED', status: 400 }); }); await protocol.saveMetaItem({ type: 'flow', name: 'leave_approval', item: validApprovalFlow(), mode: 'draft' }); const err = await protocol.publishMetaItem({ type: 'flow', name: 'leave_approval' }).catch((e: any) => e); - expect(err).toMatchObject({ code: 'VALIDATION_FAILED', status: 422 }); + expect(err).toMatchObject({ code: 'VALIDATION_FAILED', status: 400 }); expect(flowRows(rows).map((r) => r.state), 'no active row').not.toContain('active'); }); diff --git a/packages/plugins/plugin-approvals/src/approval-publish-check.test.ts b/packages/plugins/plugin-approvals/src/approval-publish-check.test.ts index eb4ac9f8226..e0430d992e8 100644 --- a/packages/plugins/plugin-approvals/src/approval-publish-check.test.ts +++ b/packages/plugins/plugin-approvals/src/approval-publish-check.test.ts @@ -245,12 +245,12 @@ describe('the publish gates', () => { expect(registerApprovalPublishGates(undefined, refusing)).toBe(false); }); - it('refuses an active write with a 422 VALIDATION_FAILED, in en and in the first locale the door states', async () => { + it('refuses an active write with a 400 VALIDATION_FAILED, in en and in the first locale the door states', async () => { const p = protocolDouble(); registerApprovalPublishGates(p, refusing); const err = await p.gates.get('flow')![0]!(ctx({ userTextLocales: ['zh-CN', 'en'] })).catch((e) => e); expect(err).toBeInstanceOf(ApprovalPublishRefusedError); - expect(err).toMatchObject({ code: 'VALIDATION_FAILED', status: 422, statusCode: 422 }); + expect(err).toMatchObject({ code: 'VALIDATION_FAILED', status: 400, statusCode: 400 }); expect(err.message).toMatch(/^flow F was not published: /); expect(err.message).toContain('Field status of invoice (step a1 of flow F) does not declare the value pending'); expect(err.userMessage).toMatch(/^flow F 没有发布:/); diff --git a/packages/plugins/plugin-approvals/src/approval-publish-gate-37766.integration.test.ts b/packages/plugins/plugin-approvals/src/approval-publish-gate-37766.integration.test.ts index 8efac8488db..8ad490f6653 100644 --- a/packages/plugins/plugin-approvals/src/approval-publish-gate-37766.integration.test.ts +++ b/packages/plugins/plugin-approvals/src/approval-publish-gate-37766.integration.test.ts @@ -5,7 +5,7 @@ * conditions, reported at the real metadata door: the approvals plugin adds * its gates beside each type's owner gate (`addAuthoringGate`) on * kernel:ready, and a flow or an object that goes `active` where an approval - * could not open is refused with a 422 `VALIDATION_FAILED` that names what is + * could not open is refused with a 400 `VALIDATION_FAILED` that names what is * missing. A draft is not refused; its promotion is. The read itself, arm by * arm, is pinned over fixtures in `approval-publish-check.test.ts`. * @@ -105,7 +105,7 @@ describe('[ADR-0162 item 7, N45] the opening check reported at publish', () => { type: 'flow', name: 'invoice_wait', item: approvalFlow('invoice_wait', 'crm_invoice', true), }).catch((e: any) => e); expect(err).toBeInstanceOf(Error); - expect(err.status).toBe(422); + expect(err.status).toBe(400); expect(err.code).toBe('VALIDATION_FAILED'); expect(err.message).toContain('flow invoice_wait was not published'); expect(err.message).toContain('Node hold (wait) of flow invoice_wait can pause the run between two approval steps of crm_invoice'); @@ -117,7 +117,7 @@ describe('[ADR-0162 item 7, N45] the opening check reported at publish', () => { const err = await protocol.saveMetaItem({ type: 'flow', name: 'invoice_wait', item: approvalFlow('invoice_wait', 'crm_invoice', true), userTextLocales: ['zh-CN'], }).catch((e: any) => e); - expect(err.status).toBe(422); + expect(err.status).toBe(400); expect(err.userMessage).toMatch(/^flow invoice_wait 没有发布:/); }); @@ -140,7 +140,7 @@ describe('[ADR-0162 item 7, N45] the opening check reported at publish', () => { }); expect(saved.success).toBe(true); const err = await protocol.publishMetaItem({ type: 'flow', name: 'invoice_wait' }).catch((e: any) => e); - expect(err.status).toBe(422); + expect(err.status).toBe(400); expect(err.code).toBe('VALIDATION_FAILED'); expect((await flowRows('invoice_wait')).filter((r) => r.state === 'active')).toEqual([]); }); @@ -156,7 +156,7 @@ describe('[ADR-0162 item 7, N45] the opening check reported at publish', () => { type: 'object', name: 'crm_note', item: { ...authored, closedStates: { approval_status: ['approved', 'rejected'] } }, }).catch((e: any) => e); expect(err).toBeInstanceOf(Error); - expect(err.status).toBe(422); + expect(err.status).toBe(400); expect(err.code).toBe('VALIDATION_FAILED'); expect(err.message).toContain('object crm_note was not published'); expect(err.message).toContain('Node hold (wait) of flow note_wait can pause the run between two approval steps of crm_note'); diff --git a/packages/plugins/plugin-approvals/src/approval-publish-gate.ts b/packages/plugins/plugin-approvals/src/approval-publish-gate.ts index a258b4902e4..83b77e1a575 100644 --- a/packages/plugins/plugin-approvals/src/approval-publish-gate.ts +++ b/packages/plugins/plugin-approvals/src/approval-publish-gate.ts @@ -11,7 +11,7 @@ * save and restore the owner gate runs on, and on the promotion of a draft, * which the owner gate does not run on. It judges an `active` write only. * - * The refusal is a 422 `VALIDATION_FAILED`: `message` in `en`, the + * The refusal is a 400 `VALIDATION_FAILED`: `message` in `en`, the * diagnostic, and `userMessage` in the first locale the write door states * (`userTextLocales`), from the plugin's own catalog. A judge that fails is * logged and refuses nothing: the report is early notice, and the first @@ -35,8 +35,8 @@ export interface ApprovalPublishGateContext { /** The publish of a flow or an object that an approval could not open on is refused. */ export class ApprovalPublishRefusedError extends Error { readonly code = 'VALIDATION_FAILED'; - readonly status = 422; - readonly statusCode = 422; + readonly status = 400; + readonly statusCode = 400; /** The refusal addressed to the author, in the first locale the write door states; `message` stays in `en`. */ readonly userMessage: string; readonly gaps: readonly OpeningGap[]; From a19894535435007a9ccc5f6c4f02355e5066b69f Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 08:06:30 +0000 Subject: [PATCH 4/4] feat(approvals): judge a package publish as the batch will leave it live At a package publish's promotion the added authoring gates are handed the batch's object and flow drafts, and the approvals publish check reads them in place of the live items of the same name. A package that declares closedStates and repairs the flow it closes on in one publish goes through in either order. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5nzgcVrZ8Neqqd1AFi --- .changeset/37766-publish-gate-approvals.md | 1 + .changeset/37766-publish-gate-door.md | 3 +- .../src/protocol-authoring-channel.ts | 9 ++++ .../src/protocol-authoring-gate.ts | 6 +++ .../src/protocol-history-and-publish.ts | 2 + .../protocol.add-authoring-gate-37766.test.ts | 13 +++++- packages/metadata-protocol/src/protocol.ts | 2 +- .../src/approval-publish-check.test.ts | 42 +++++++++++++++++++ .../src/approval-publish-check.ts | 41 ++++++++++++++---- ...val-publish-gate-37766.integration.test.ts | 38 +++++++++++++++++ .../src/approval-publish-gate.ts | 4 +- 11 files changed, 150 insertions(+), 11 deletions(-) diff --git a/.changeset/37766-publish-gate-approvals.md b/.changeset/37766-publish-gate-approvals.md index 4fdbce7516f..9e3d4e7af87 100644 --- a/.changeset/37766-publish-gate-approvals.md +++ b/.changeset/37766-publish-gate-approvals.md @@ -13,6 +13,7 @@ At kernel:ready the plugin adds publish gates for `flow` and `object` beside the - **A flow.** It is judged as an approval's root, together with every flow that calls it through a `subflow` or a `map`, to any depth, with the written body in place. The walk up the callers ends on a flow that calls itself and on flows that call each other. It stops after 64 roots: past that, nothing is refused for the cap, and one warning says so. - **An object.** Every flow that can start on one of its records, or maps over them, is judged with the written object in place. Only gaps on the written object are reported. +- **A package publish.** The batch's other objects and flows are read in place of the live ones of the same name. A package that declares `closedStates` and repairs the flow it closes on in the same publish goes through, whichever draft is promoted first. The refusal is a 400 `VALIDATION_FAILED` that names the item, then gives one sentence per gap: the flow, the step, the object, the field and what is missing, in the first locale the write door states. These are the same sentences an approval's first request is refused with. diff --git a/.changeset/37766-publish-gate-door.md b/.changeset/37766-publish-gate-door.md index 91a1734fecf..aa6483ae653 100644 --- a/.changeset/37766-publish-gate-door.md +++ b/.changeset/37766-publish-gate-door.md @@ -7,11 +7,12 @@ feat(metadata-protocol): a plugin can add an authoring gate beside a type's owne Clause-②: yes (widening) Metadata-protocol: none -Widened: `ObjectStackProtocolImplementation` gains `addAuthoringGate(type, gate)`. +Widened: `ObjectStackProtocolImplementation` gains `addAuthoringGate(type, gate)`, and `MetadataAuthoringGateContext` gains an optional `pending`. `registerAuthoringGate` keeps one gate per type, and a second registration still replaces the first. A plugin that needs to judge a type another plugin owns now adds its gate with `addAuthoringGate` instead. plugin-security owns `object`, for example. - An added gate runs after the owner gate, in the order gates were added, on every write the owner gate runs on: a save in either mode, and a restore. - An added gate also runs when a draft is promoted to `active` (`publishMetaItem`, a package publish, a judge-only call), with `state: 'active'`. The owner gate still does not run there. +- At a package publish's promotion, an added gate is handed `pending`: the `object` and `flow` bodies of the batch's drafts, which go `active` with this one. A gate that reads other items reads these in place of the live ones of the same name, so a batch is judged as it will be live. `pending` is absent on a save, a restore and a single publish. - A declared `package-author` channel runs no added gate, as it runs no owner gate. - A throw from an added gate refuses the write before it is stored, as an owner gate's does. diff --git a/packages/metadata-protocol/src/protocol-authoring-channel.ts b/packages/metadata-protocol/src/protocol-authoring-channel.ts index f893edb2f4d..c0748212df0 100644 --- a/packages/metadata-protocol/src/protocol-authoring-channel.ts +++ b/packages/metadata-protocol/src/protocol-authoring-channel.ts @@ -51,6 +51,15 @@ export interface MetadataAuthoringGateContext { * the same name. */ packageId?: string | null; + /** + * [#37766, ADR-0162 item 7] At a package publish's promotion of a draft: + * the `object` and `flow` bodies of the batch's drafts, which go `active` + * with this one. A gate that reads other items reads these in place of the + * live ones of the same name, so a batch is judged as it will be live, not + * draft by draft against the engine as it stood before the batch. Absent + * on a save, a restore and a single publish. + */ + pending?: { objects: readonly unknown[]; flows: readonly unknown[] }; } export type MetadataAuthoringGate = (ctx: MetadataAuthoringGateContext) => void | Promise; diff --git a/packages/metadata-protocol/src/protocol-authoring-gate.ts b/packages/metadata-protocol/src/protocol-authoring-gate.ts index a486395935d..2192a79dec2 100644 --- a/packages/metadata-protocol/src/protocol-authoring-gate.ts +++ b/packages/metadata-protocol/src/protocol-authoring-gate.ts @@ -214,6 +214,8 @@ type AuthoringGateEvent = { /** [#37766] Run the gates added beside the owner (`addAuthoringGate`) alone: a draft's promotion, which the owner gate does not run on. */ addedOnly?: boolean; userTextLocales?: readonly (string | undefined)[]; packageId?: string | null; + /** [#37766] A package publish's other drafts, handed to the gates as {@link MetadataAuthoringGateContext.pending}. */ + pending?: RuntimePendingDeclarations; }; /** The body of `ObjectStackProtocolImplementation#runAuthoringGate`; the method's docblock there is its contract. */ @@ -246,6 +248,10 @@ export async function runAuthoringGate( : {}), // [ADR-0150 D2, #34226] The package the write is addressed to. ...(typeof evt.packageId === 'string' && evt.packageId !== '' ? { packageId: evt.packageId } : {}), + // [#37766] A package publish's other drafts, as the batch will leave them live. + ...(evt.pending?.objects !== undefined || evt.pending?.flows !== undefined + ? { pending: { objects: evt.pending.objects ?? [], flows: evt.pending.flows ?? [] } } + : {}), }; if (gate) await gate(ctx); for (const extra of added) await extra(ctx); diff --git a/packages/metadata-protocol/src/protocol-history-and-publish.ts b/packages/metadata-protocol/src/protocol-history-and-publish.ts index b19df50ede7..5b900b7d07f 100644 --- a/packages/metadata-protocol/src/protocol-history-and-publish.ts +++ b/packages/metadata-protocol/src/protocol-history-and-publish.ts @@ -1473,6 +1473,8 @@ export class ProtocolHistoryAndPublishFacet { body: storedFlowVerdictBody(singularType, draftForGate.body), ...(request.userTextLocales !== undefined ? { userTextLocales: request.userTextLocales } : {}), ...(request.packageId !== undefined ? { packageId: request.packageId } : {}), + // The batch's other drafts: an added gate judges the batch as it will be live. + ...(request.pending !== undefined ? { pending: request.pending } : {}), }); } diff --git a/packages/metadata-protocol/src/protocol.add-authoring-gate-37766.test.ts b/packages/metadata-protocol/src/protocol.add-authoring-gate-37766.test.ts index abae024dbd3..d59b3eab28c 100644 --- a/packages/metadata-protocol/src/protocol.add-authoring-gate-37766.test.ts +++ b/packages/metadata-protocol/src/protocol.add-authoring-gate-37766.test.ts @@ -108,7 +108,7 @@ function makeStubEngine() { async find(table: string, opts: { where: Record; limit?: number }) { // Every stated key of the `where` is matched (`$in` or equality), then the bound. const matched = Array.from(tableOf(table).values()).filter((r) => - Object.entries(opts.where).every(([k, v]) => v === undefined || whereValueMatches(r[k], v))); + Object.entries(opts.where).every(([k, v]) => v === undefined || whereValueMatches((r as unknown as Record)[k], v))); return typeof opts?.limit === 'number' ? matched.slice(0, opts.limit) : matched; }, async insert(table: string, data: Record) { @@ -274,6 +274,17 @@ describe('addAuthoringGate through the save and publish doors (#37766)', () => { expect(flowRows(rows).map((r) => r.state), 'no active row').not.toContain('active'); }); + it('hands the gates a package publish\'s other object and flow drafts, and nothing on a write that has none', async () => { + const { protocol } = makeProtocolOn(); + const seen: any[] = []; + protocol.addAuthoringGate('object', (ctx: any) => { seen.push(ctx); }); + const pending = { objects: [{ name: 'crm_account' }], flows: [{ name: 'f1', nodes: [] }], permissions: [{ name: 'p' }] }; + await protocol.runAuthoringGate(gateEvent({ pending })); + await protocol.runAuthoringGate(gateEvent()); + expect(seen[0].pending).toEqual({ objects: pending.objects, flows: pending.flows }); + expect(seen[1]).not.toHaveProperty('pending'); + }); + it('a declared package-author channel runs no added gate, at save or at promotion', async () => { const { protocol } = makeProtocolOn('package-author'); const added = vi.fn(); diff --git a/packages/metadata-protocol/src/protocol.ts b/packages/metadata-protocol/src/protocol.ts index 38f0bb03af8..48ae3a959b6 100644 --- a/packages/metadata-protocol/src/protocol.ts +++ b/packages/metadata-protocol/src/protocol.ts @@ -1766,7 +1766,7 @@ export class ObjectStackProtocolImplementation implements * and the packaged declaration body (the baseline an overlay customizes) for the gate. */ private runAuthoringGate(evt: { type: string; name: string; state: 'draft' | 'active'; body: unknown; addedOnly?: boolean; - userTextLocales?: readonly (string | undefined)[]; packageId?: string | null; + userTextLocales?: readonly (string | undefined)[]; packageId?: string | null; pending?: RuntimePendingDeclarations; }): Promise { // [#25467 cut 8] The body moved to `protocol-authoring-gate.ts` (see `AuthoringGateHost`). const readAuthoringGates = () => this.authoringGates; diff --git a/packages/plugins/plugin-approvals/src/approval-publish-check.test.ts b/packages/plugins/plugin-approvals/src/approval-publish-check.test.ts index e0430d992e8..203a802cd4a 100644 --- a/packages/plugins/plugin-approvals/src/approval-publish-check.test.ts +++ b/packages/plugins/plugin-approvals/src/approval-publish-check.test.ts @@ -188,6 +188,38 @@ describe('the publish check: an object', () => { }); }); +describe('the publish check: a package publish', () => { + // The batch adds `closedStates` to invoice and repairs the held flow F (the wait goes) in one publish. + const heldF = chain('invoice', step('a1'), n('w', 'wait'), step('a2')); + const fixedF = { name: 'F', ...chain('invoice', step('a1'), n('d', 'decision'), step('a2')) }; + + it('judges the object against the batch\'s repaired flow when the object is promoted first', async () => { + const item: PublishedItem = { ...objectWrite(invoice()), pending: { objects: [invoice()], flows: [fixedF] } }; + const out = await judgeApprovalPublish(item, source({ flows: { F: heldF }, objects: { invoice: openInvoice() } })); + expect(out.gaps).toEqual([]); + }); + + it('judges the flow against the batch\'s closing object when the flow is promoted first', async () => { + const pausing = { name: 'F', ...heldF }; + const item: PublishedItem = { ...flowWrite('F', heldF), pending: { objects: [invoice()], flows: [pausing] } }; + const out = await judgeApprovalPublish(item, source({ flows: { F: heldF }, objects: { invoice: openInvoice() } })); + expect(out.gaps).toEqual([{ kind: 'pause_between_steps', flow: 'F', node: 'w', type: 'wait', object: 'invoice' }]); + }); + + it('still refuses the object where the batch leaves the held flow pausing', async () => { + const item: PublishedItem = { ...objectWrite(invoice()), pending: { objects: [invoice()], flows: [] } }; + const out = await judgeApprovalPublish(item, source({ flows: { F: heldF }, objects: { invoice: openInvoice() } })); + expect(kinds(out.gaps)).toEqual(['pause_between_steps']); + }); + + it('judges a flow the batch adds and the engine does not hold yet', async () => { + const newG = { name: 'G', ...chain('invoice', step('a1'), n('w', 'wait'), step('a2')) }; + const item: PublishedItem = { ...objectWrite(invoice()), pending: { objects: [invoice()], flows: [newG] } }; + const out = await judgeApprovalPublish(item, source({ flows: {}, objects: { invoice: openInvoice() } })); + expect(out.gaps).toEqual([{ kind: 'pause_between_steps', flow: 'G', node: 'w', type: 'wait', object: 'invoice' }]); + }); +}); + describe('the publish check: what it does not refuse', () => { it('does not refuse a callee it cannot read', async () => { const out = await judgeApprovalPublish(flowWrite('F', chain('invoice', step('a1'), sub('s', 'missing'))), source({})); @@ -292,4 +324,14 @@ describe('the publish gates', () => { await p.gates.get('object')![0]!(ctx({ type: 'object', name: 'invoice', body })); expect(judge).toHaveBeenCalledWith({ type: 'object', name: 'invoice', body }); }); + + it('hands the judge a package publish\'s other drafts', async () => { + const p = protocolDouble(); + const judge = vi.fn(async () => ({ gaps: [], capped: false })); + registerApprovalPublishGates(p, judge); + const body = { name: 'invoice' }; + const pending = { objects: [body], flows: [{ name: 'F', nodes: [] }] }; + await p.gates.get('object')![0]!(ctx({ type: 'object', name: 'invoice', body, pending })); + expect(judge).toHaveBeenCalledWith({ type: 'object', name: 'invoice', body, pending }); + }); }); diff --git a/packages/plugins/plugin-approvals/src/approval-publish-check.ts b/packages/plugins/plugin-approvals/src/approval-publish-check.ts index 1dadfd3cb32..9422ea50e94 100644 --- a/packages/plugins/plugin-approvals/src/approval-publish-check.ts +++ b/packages/plugins/plugin-approvals/src/approval-publish-check.ts @@ -26,6 +26,10 @@ * a root, with the written object in place of the held one. Only gaps on * the written object are reported: the publish of one object is not * refused for another's. + * - **A package publish.** The batch's other `object` and `flow` drafts are + * read in place of the held items of their names, so a package that + * declares `closedStates` and repairs the flow it closes on in one publish + * is judged as it will be live, whichever draft is promoted first. * * What is not judged at publish, each a reading pinned by a test: * @@ -62,6 +66,12 @@ export interface PublishedItem { type: 'flow' | 'object'; name: string; body: unknown; + /** + * A package publish's other `object` and `flow` drafts, which go `active` + * with this write: each is read in place of the held item of its name, so a + * batch is judged as it will be live, in any order. + */ + pending?: { objects?: readonly unknown[]; flows?: readonly unknown[] }; } /** The readers the publish check needs, as the engine holds things before the write. Every one answers, never throws. */ @@ -94,16 +104,33 @@ export async function judgeApprovalPublish(item: PublishedItem, source: PublishC const writtenFlow = item.type === 'flow' && isFlowBody(item.body) ? item.body : undefined; if (item.type === 'flow' && !writtenFlow) return none; - // The engine as it will hold things once the write lands. + // The engine as it will hold things once the write (and its batch) lands: + // the written item, then the batch's other drafts, then what the engine holds. + const batchObjects = new Map(); + for (const o of item.pending?.objects ?? []) { + const name = nameOf(o); + if (name && !(item.type === 'object' && name === item.name)) batchObjects.set(name, o); + } + const batchFlows = new Map(); + for (const f of item.pending?.flows ?? []) { + const name = nameOf(f); + if (name && isFlowBody(f) && !(item.type === 'flow' && name === item.name)) batchFlows.set(name, f); + } const objectSchema = (name: string): unknown => - (item.type === 'object' && name === item.name ? item.body : source.objectSchema(name)); - const flow = async (name: string): Promise => - (writtenFlow && name === item.name ? { key: item.name, body: writtenFlow } : source.flow(name)); + (item.type === 'object' && name === item.name ? item.body + : batchObjects.has(name) ? batchObjects.get(name) : source.objectSchema(name)); + const overlay = (name: string): OpeningFlow | undefined => + (writtenFlow && name === item.name ? { key: item.name, body: writtenFlow } + : batchFlows.has(name) ? { key: name, body: batchFlows.get(name)! } : undefined); + const flow = async (name: string): Promise => overlay(name) ?? source.flow(name); const calleeFlow = async (name: string, callerKey: string): Promise => - (writtenFlow && name === item.name ? { key: item.name, body: writtenFlow } : source.calleeFlow(name, callerKey)); + overlay(name) ?? source.calleeFlow(name, callerKey); // Nothing is read in an application where no object declares the key. - const listed = source.allObjects(); + const heldObjects = source.allObjects(); + const listed = Array.isArray(heldObjects) || batchObjects.size > 0 + ? [...(heldObjects ?? []).filter((o) => !batchObjects.has(nameOf(o) ?? '')), ...batchObjects.values()] + : undefined; const declares = (schema: unknown): boolean => closedValuesOf(schema) !== undefined; const appDeclares = item.type === 'object' && declares(item.body) ? true @@ -112,7 +139,7 @@ export async function judgeApprovalPublish(item: PublishedItem, source: PublishC : false; if (!appDeclares) return none; - const names = (await source.flowNames()) ?? []; + const names = [...((await source.flowNames()) ?? []), ...batchFlows.keys()]; const roots: string[] = []; let capped = false; if (item.type === 'flow') { diff --git a/packages/plugins/plugin-approvals/src/approval-publish-gate-37766.integration.test.ts b/packages/plugins/plugin-approvals/src/approval-publish-gate-37766.integration.test.ts index 8ad490f6653..50b6ce46c32 100644 --- a/packages/plugins/plugin-approvals/src/approval-publish-gate-37766.integration.test.ts +++ b/packages/plugins/plugin-approvals/src/approval-publish-gate-37766.integration.test.ts @@ -88,6 +88,12 @@ describe('[ADR-0162 item 7, N45] the opening check reported at publish', () => { await ql.syncSchemas(); } + /** An authored package the batch tests save their drafts into, as `POST /packages` installs one. */ + const PKG = 'app.crm'; + function installPackage() { + (ql.registry as any).installPackage({ id: PKG, name: PKG, version: '1.0.0', type: 'app', namespace: 'crm' }, 'authored'); + } + const flowRows = async (name: string) => (await ql.find('sys_metadata', { where: { type: 'flow', name }, context: { isSystem: true } })) as any[]; @@ -161,4 +167,36 @@ describe('[ADR-0162 item 7, N45] the opening check reported at publish', () => { expect(err.message).toContain('object crm_note was not published'); expect(err.message).toContain('Node hold (wait) of flow note_wait can pause the run between two approval steps of crm_note'); }); + + it('judges a package publish as it will be live: the object that starts to close and the flow it repairs, in one batch', async () => { + await boot(); + installPackage(); + const authored = { name: 'crm_note', label: 'Note', sharingModel: 'private', fields }; + expect((await protocol.saveMetaItem({ type: 'object', name: 'crm_note', item: authored, packageId: PKG })).success).toBe(true); + automation.registerFlow('note_wait', approvalFlow('note_wait', 'crm_note', true) as any); + // Both orders: the object promoted before the flow it repairs, and after. + await protocol.saveMetaItem({ + type: 'object', name: 'crm_note', packageId: PKG, mode: 'draft', + item: { ...authored, closedStates: { approval_status: ['approved', 'rejected'] } }, + }); + await protocol.saveMetaItem({ type: 'flow', name: 'note_wait', packageId: PKG, mode: 'draft', item: approvalFlow('note_wait', 'crm_note', false) }); + const out = await protocol.publishPackageDrafts({ packageId: PKG }); + expect(out.failed ?? []).toEqual([]); + expect(out.success).toBe(true); + }); + + it('refuses a package publish whose object starts to close while the batch leaves the held flow pausing', async () => { + await boot(); + installPackage(); + const authored = { name: 'crm_note', label: 'Note', sharingModel: 'private', fields }; + expect((await protocol.saveMetaItem({ type: 'object', name: 'crm_note', item: authored, packageId: PKG })).success).toBe(true); + automation.registerFlow('note_wait', approvalFlow('note_wait', 'crm_note', true) as any); + await protocol.saveMetaItem({ + type: 'object', name: 'crm_note', packageId: PKG, mode: 'draft', + item: { ...authored, closedStates: { approval_status: ['approved', 'rejected'] } }, + }); + const out = await protocol.publishPackageDrafts({ packageId: PKG }); + expect(out.success).toBe(false); + expect(JSON.stringify(out.failed)).toContain('Node hold (wait) of flow note_wait can pause the run between two approval steps of crm_note'); + }); }); diff --git a/packages/plugins/plugin-approvals/src/approval-publish-gate.ts b/packages/plugins/plugin-approvals/src/approval-publish-gate.ts index 83b77e1a575..1eb2079a7f9 100644 --- a/packages/plugins/plugin-approvals/src/approval-publish-gate.ts +++ b/packages/plugins/plugin-approvals/src/approval-publish-gate.ts @@ -30,6 +30,8 @@ export interface ApprovalPublishGateContext { state: 'draft' | 'active'; body: unknown; userTextLocales?: readonly string[]; + /** A package publish's other `object` and `flow` drafts, which go `active` with this one. */ + pending?: { objects?: readonly unknown[]; flows?: readonly unknown[] }; } /** The publish of a flow or an object that an approval could not open on is refused. */ @@ -72,7 +74,7 @@ export function registerApprovalPublishGates( if (ctx.state !== 'active') return; let judgement: PublishJudgement; try { - judgement = await judge({ type, name: ctx.name, body: ctx.body }); + judgement = await judge({ type, name: ctx.name, body: ctx.body, ...(ctx.pending ? { pending: ctx.pending } : {}) }); } catch (err: any) { logger?.warn?.('[approvals] the publish check could not judge a write; it is not refused, and the approval\'s first request still judges it (ADR-0162 item 7)', { type, name: ctx.name, error: err?.message ?? String(err),