Skip to content

Commit a198945

Browse files
committed
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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FEkQ5nzgcVrZ8Neqqd1AFi
1 parent 4172ad6 commit a198945

11 files changed

Lines changed: 150 additions & 11 deletions

‎.changeset/37766-publish-gate-approvals.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ At kernel:ready the plugin adds publish gates for `flow` and `object` beside the
1313

1414
- **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.
1515
- **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.
16+
- **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.
1617

1718
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.
1819

‎.changeset/37766-publish-gate-door.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,12 @@ feat(metadata-protocol): a plugin can add an authoring gate beside a type's owne
77
Clause-②: yes (widening)
88
Metadata-protocol: none
99

10-
Widened: `ObjectStackProtocolImplementation` gains `addAuthoringGate(type, gate)`.
10+
Widened: `ObjectStackProtocolImplementation` gains `addAuthoringGate(type, gate)`, and `MetadataAuthoringGateContext` gains an optional `pending`.
1111

1212
`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.
1313

1414
- 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.
1515
- 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.
16+
- 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.
1617
- A declared `package-author` channel runs no added gate, as it runs no owner gate.
1718
- A throw from an added gate refuses the write before it is stored, as an owner gate's does.

‎packages/metadata-protocol/src/protocol-authoring-channel.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,15 @@ export interface MetadataAuthoringGateContext {
5151
* the same name.
5252
*/
5353
packageId?: string | null;
54+
/**
55+
* [#37766, ADR-0162 item 7] At a package publish's promotion of a draft:
56+
* the `object` and `flow` bodies of the batch's drafts, which go `active`
57+
* with this one. A gate that reads other items reads these in place of the
58+
* live ones of the same name, so a batch is judged as it will be live, not
59+
* draft by draft against the engine as it stood before the batch. Absent
60+
* on a save, a restore and a single publish.
61+
*/
62+
pending?: { objects: readonly unknown[]; flows: readonly unknown[] };
5463
}
5564

5665
export type MetadataAuthoringGate = (ctx: MetadataAuthoringGateContext) => void | Promise<void>;

‎packages/metadata-protocol/src/protocol-authoring-gate.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -214,6 +214,8 @@ type AuthoringGateEvent = {
214214
/** [#37766] Run the gates added beside the owner (`addAuthoringGate`) alone: a draft's promotion, which the owner gate does not run on. */
215215
addedOnly?: boolean;
216216
userTextLocales?: readonly (string | undefined)[]; packageId?: string | null;
217+
/** [#37766] A package publish's other drafts, handed to the gates as {@link MetadataAuthoringGateContext.pending}. */
218+
pending?: RuntimePendingDeclarations;
217219
};
218220

219221
/** The body of `ObjectStackProtocolImplementation#runAuthoringGate`; the method's docblock there is its contract. */
@@ -246,6 +248,10 @@ export async function runAuthoringGate(
246248
: {}),
247249
// [ADR-0150 D2, #34226] The package the write is addressed to.
248250
...(typeof evt.packageId === 'string' && evt.packageId !== '' ? { packageId: evt.packageId } : {}),
251+
// [#37766] A package publish's other drafts, as the batch will leave them live.
252+
...(evt.pending?.objects !== undefined || evt.pending?.flows !== undefined
253+
? { pending: { objects: evt.pending.objects ?? [], flows: evt.pending.flows ?? [] } }
254+
: {}),
249255
};
250256
if (gate) await gate(ctx);
251257
for (const extra of added) await extra(ctx);

‎packages/metadata-protocol/src/protocol-history-and-publish.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1473,6 +1473,8 @@ export class ProtocolHistoryAndPublishFacet {
14731473
body: storedFlowVerdictBody(singularType, draftForGate.body),
14741474
...(request.userTextLocales !== undefined ? { userTextLocales: request.userTextLocales } : {}),
14751475
...(request.packageId !== undefined ? { packageId: request.packageId } : {}),
1476+
// The batch's other drafts: an added gate judges the batch as it will be live.
1477+
...(request.pending !== undefined ? { pending: request.pending } : {}),
14761478
});
14771479
}
14781480

‎packages/metadata-protocol/src/protocol.add-authoring-gate-37766.test.ts‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ function makeStubEngine() {
108108
async find(table: string, opts: { where: Record<string, unknown>; limit?: number }) {
109109
// Every stated key of the `where` is matched (`$in` or equality), then the bound.
110110
const matched = Array.from(tableOf(table).values()).filter((r) =>
111-
Object.entries(opts.where).every(([k, v]) => v === undefined || whereValueMatches(r[k], v)));
111+
Object.entries(opts.where).every(([k, v]) => v === undefined || whereValueMatches((r as unknown as Record<string, unknown>)[k], v)));
112112
return typeof opts?.limit === 'number' ? matched.slice(0, opts.limit) : matched;
113113
},
114114
async insert(table: string, data: Record<string, unknown>) {
@@ -274,6 +274,17 @@ describe('addAuthoringGate through the save and publish doors (#37766)', () => {
274274
expect(flowRows(rows).map((r) => r.state), 'no active row').not.toContain('active');
275275
});
276276

277+
it('hands the gates a package publish\'s other object and flow drafts, and nothing on a write that has none', async () => {
278+
const { protocol } = makeProtocolOn();
279+
const seen: any[] = [];
280+
protocol.addAuthoringGate('object', (ctx: any) => { seen.push(ctx); });
281+
const pending = { objects: [{ name: 'crm_account' }], flows: [{ name: 'f1', nodes: [] }], permissions: [{ name: 'p' }] };
282+
await protocol.runAuthoringGate(gateEvent({ pending }));
283+
await protocol.runAuthoringGate(gateEvent());
284+
expect(seen[0].pending).toEqual({ objects: pending.objects, flows: pending.flows });
285+
expect(seen[1]).not.toHaveProperty('pending');
286+
});
287+
277288
it('a declared package-author channel runs no added gate, at save or at promotion', async () => {
278289
const { protocol } = makeProtocolOn('package-author');
279290
const added = vi.fn();

‎packages/metadata-protocol/src/protocol.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1766,7 +1766,7 @@ export class ObjectStackProtocolImplementation implements
17661766
* and the packaged declaration body (the baseline an overlay customizes) for the gate. */
17671767
private runAuthoringGate(evt: {
17681768
type: string; name: string; state: 'draft' | 'active'; body: unknown; addedOnly?: boolean;
1769-
userTextLocales?: readonly (string | undefined)[]; packageId?: string | null;
1769+
userTextLocales?: readonly (string | undefined)[]; packageId?: string | null; pending?: RuntimePendingDeclarations;
17701770
}): Promise<void> {
17711771
// [#25467 cut 8] The body moved to `protocol-authoring-gate.ts` (see `AuthoringGateHost`).
17721772
const readAuthoringGates = () => this.authoringGates;

‎packages/plugins/plugin-approvals/src/approval-publish-check.test.ts‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,38 @@ describe('the publish check: an object', () => {
188188
});
189189
});
190190

191+
describe('the publish check: a package publish', () => {
192+
// The batch adds `closedStates` to invoice and repairs the held flow F (the wait goes) in one publish.
193+
const heldF = chain('invoice', step('a1'), n('w', 'wait'), step('a2'));
194+
const fixedF = { name: 'F', ...chain('invoice', step('a1'), n('d', 'decision'), step('a2')) };
195+
196+
it('judges the object against the batch\'s repaired flow when the object is promoted first', async () => {
197+
const item: PublishedItem = { ...objectWrite(invoice()), pending: { objects: [invoice()], flows: [fixedF] } };
198+
const out = await judgeApprovalPublish(item, source({ flows: { F: heldF }, objects: { invoice: openInvoice() } }));
199+
expect(out.gaps).toEqual([]);
200+
});
201+
202+
it('judges the flow against the batch\'s closing object when the flow is promoted first', async () => {
203+
const pausing = { name: 'F', ...heldF };
204+
const item: PublishedItem = { ...flowWrite('F', heldF), pending: { objects: [invoice()], flows: [pausing] } };
205+
const out = await judgeApprovalPublish(item, source({ flows: { F: heldF }, objects: { invoice: openInvoice() } }));
206+
expect(out.gaps).toEqual([{ kind: 'pause_between_steps', flow: 'F', node: 'w', type: 'wait', object: 'invoice' }]);
207+
});
208+
209+
it('still refuses the object where the batch leaves the held flow pausing', async () => {
210+
const item: PublishedItem = { ...objectWrite(invoice()), pending: { objects: [invoice()], flows: [] } };
211+
const out = await judgeApprovalPublish(item, source({ flows: { F: heldF }, objects: { invoice: openInvoice() } }));
212+
expect(kinds(out.gaps)).toEqual(['pause_between_steps']);
213+
});
214+
215+
it('judges a flow the batch adds and the engine does not hold yet', async () => {
216+
const newG = { name: 'G', ...chain('invoice', step('a1'), n('w', 'wait'), step('a2')) };
217+
const item: PublishedItem = { ...objectWrite(invoice()), pending: { objects: [invoice()], flows: [newG] } };
218+
const out = await judgeApprovalPublish(item, source({ flows: {}, objects: { invoice: openInvoice() } }));
219+
expect(out.gaps).toEqual([{ kind: 'pause_between_steps', flow: 'G', node: 'w', type: 'wait', object: 'invoice' }]);
220+
});
221+
});
222+
191223
describe('the publish check: what it does not refuse', () => {
192224
it('does not refuse a callee it cannot read', async () => {
193225
const out = await judgeApprovalPublish(flowWrite('F', chain('invoice', step('a1'), sub('s', 'missing'))), source({}));
@@ -292,4 +324,14 @@ describe('the publish gates', () => {
292324
await p.gates.get('object')![0]!(ctx({ type: 'object', name: 'invoice', body }));
293325
expect(judge).toHaveBeenCalledWith({ type: 'object', name: 'invoice', body });
294326
});
327+
328+
it('hands the judge a package publish\'s other drafts', async () => {
329+
const p = protocolDouble();
330+
const judge = vi.fn(async () => ({ gaps: [], capped: false }));
331+
registerApprovalPublishGates(p, judge);
332+
const body = { name: 'invoice' };
333+
const pending = { objects: [body], flows: [{ name: 'F', nodes: [] }] };
334+
await p.gates.get('object')![0]!(ctx({ type: 'object', name: 'invoice', body, pending }));
335+
expect(judge).toHaveBeenCalledWith({ type: 'object', name: 'invoice', body, pending });
336+
});
295337
});

‎packages/plugins/plugin-approvals/src/approval-publish-check.ts‎

Lines changed: 34 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,10 @@
2626
* a root, with the written object in place of the held one. Only gaps on
2727
* the written object are reported: the publish of one object is not
2828
* refused for another's.
29+
* - **A package publish.** The batch's other `object` and `flow` drafts are
30+
* read in place of the held items of their names, so a package that
31+
* declares `closedStates` and repairs the flow it closes on in one publish
32+
* is judged as it will be live, whichever draft is promoted first.
2933
*
3034
* What is not judged at publish, each a reading pinned by a test:
3135
*
@@ -62,6 +66,12 @@ export interface PublishedItem {
6266
type: 'flow' | 'object';
6367
name: string;
6468
body: unknown;
69+
/**
70+
* A package publish's other `object` and `flow` drafts, which go `active`
71+
* with this write: each is read in place of the held item of its name, so a
72+
* batch is judged as it will be live, in any order.
73+
*/
74+
pending?: { objects?: readonly unknown[]; flows?: readonly unknown[] };
6575
}
6676

6777
/** 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
94104
const writtenFlow = item.type === 'flow' && isFlowBody(item.body) ? item.body : undefined;
95105
if (item.type === 'flow' && !writtenFlow) return none;
96106

97-
// The engine as it will hold things once the write lands.
107+
// The engine as it will hold things once the write (and its batch) lands:
108+
// the written item, then the batch's other drafts, then what the engine holds.
109+
const batchObjects = new Map<string, unknown>();
110+
for (const o of item.pending?.objects ?? []) {
111+
const name = nameOf(o);
112+
if (name && !(item.type === 'object' && name === item.name)) batchObjects.set(name, o);
113+
}
114+
const batchFlows = new Map<string, OpeningFlowBody>();
115+
for (const f of item.pending?.flows ?? []) {
116+
const name = nameOf(f);
117+
if (name && isFlowBody(f) && !(item.type === 'flow' && name === item.name)) batchFlows.set(name, f);
118+
}
98119
const objectSchema = (name: string): unknown =>
99-
(item.type === 'object' && name === item.name ? item.body : source.objectSchema(name));
100-
const flow = async (name: string): Promise<OpeningFlow | null> =>
101-
(writtenFlow && name === item.name ? { key: item.name, body: writtenFlow } : source.flow(name));
120+
(item.type === 'object' && name === item.name ? item.body
121+
: batchObjects.has(name) ? batchObjects.get(name) : source.objectSchema(name));
122+
const overlay = (name: string): OpeningFlow | undefined =>
123+
(writtenFlow && name === item.name ? { key: item.name, body: writtenFlow }
124+
: batchFlows.has(name) ? { key: name, body: batchFlows.get(name)! } : undefined);
125+
const flow = async (name: string): Promise<OpeningFlow | null> => overlay(name) ?? source.flow(name);
102126
const calleeFlow = async (name: string, callerKey: string): Promise<OpeningFlow | null> =>
103-
(writtenFlow && name === item.name ? { key: item.name, body: writtenFlow } : source.calleeFlow(name, callerKey));
127+
overlay(name) ?? source.calleeFlow(name, callerKey);
104128

105129
// Nothing is read in an application where no object declares the key.
106-
const listed = source.allObjects();
130+
const heldObjects = source.allObjects();
131+
const listed = Array.isArray(heldObjects) || batchObjects.size > 0
132+
? [...(heldObjects ?? []).filter((o) => !batchObjects.has(nameOf(o) ?? '')), ...batchObjects.values()]
133+
: undefined;
107134
const declares = (schema: unknown): boolean => closedValuesOf(schema) !== undefined;
108135
const appDeclares = item.type === 'object' && declares(item.body)
109136
? true
@@ -112,7 +139,7 @@ export async function judgeApprovalPublish(item: PublishedItem, source: PublishC
112139
: false;
113140
if (!appDeclares) return none;
114141

115-
const names = (await source.flowNames()) ?? [];
142+
const names = [...((await source.flowNames()) ?? []), ...batchFlows.keys()];
116143
const roots: string[] = [];
117144
let capped = false;
118145
if (item.type === 'flow') {

‎packages/plugins/plugin-approvals/src/approval-publish-gate-37766.integration.test.ts‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,12 @@ describe('[ADR-0162 item 7, N45] the opening check reported at publish', () => {
8888
await ql.syncSchemas();
8989
}
9090

91+
/** An authored package the batch tests save their drafts into, as `POST /packages` installs one. */
92+
const PKG = 'app.crm';
93+
function installPackage() {
94+
(ql.registry as any).installPackage({ id: PKG, name: PKG, version: '1.0.0', type: 'app', namespace: 'crm' }, 'authored');
95+
}
96+
9197
const flowRows = async (name: string) =>
9298
(await ql.find('sys_metadata', { where: { type: 'flow', name }, context: { isSystem: true } })) as any[];
9399

@@ -161,4 +167,36 @@ describe('[ADR-0162 item 7, N45] the opening check reported at publish', () => {
161167
expect(err.message).toContain('object crm_note was not published');
162168
expect(err.message).toContain('Node hold (wait) of flow note_wait can pause the run between two approval steps of crm_note');
163169
});
170+
171+
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 () => {
172+
await boot();
173+
installPackage();
174+
const authored = { name: 'crm_note', label: 'Note', sharingModel: 'private', fields };
175+
expect((await protocol.saveMetaItem({ type: 'object', name: 'crm_note', item: authored, packageId: PKG })).success).toBe(true);
176+
automation.registerFlow('note_wait', approvalFlow('note_wait', 'crm_note', true) as any);
177+
// Both orders: the object promoted before the flow it repairs, and after.
178+
await protocol.saveMetaItem({
179+
type: 'object', name: 'crm_note', packageId: PKG, mode: 'draft',
180+
item: { ...authored, closedStates: { approval_status: ['approved', 'rejected'] } },
181+
});
182+
await protocol.saveMetaItem({ type: 'flow', name: 'note_wait', packageId: PKG, mode: 'draft', item: approvalFlow('note_wait', 'crm_note', false) });
183+
const out = await protocol.publishPackageDrafts({ packageId: PKG });
184+
expect(out.failed ?? []).toEqual([]);
185+
expect(out.success).toBe(true);
186+
});
187+
188+
it('refuses a package publish whose object starts to close while the batch leaves the held flow pausing', async () => {
189+
await boot();
190+
installPackage();
191+
const authored = { name: 'crm_note', label: 'Note', sharingModel: 'private', fields };
192+
expect((await protocol.saveMetaItem({ type: 'object', name: 'crm_note', item: authored, packageId: PKG })).success).toBe(true);
193+
automation.registerFlow('note_wait', approvalFlow('note_wait', 'crm_note', true) as any);
194+
await protocol.saveMetaItem({
195+
type: 'object', name: 'crm_note', packageId: PKG, mode: 'draft',
196+
item: { ...authored, closedStates: { approval_status: ['approved', 'rejected'] } },
197+
});
198+
const out = await protocol.publishPackageDrafts({ packageId: PKG });
199+
expect(out.success).toBe(false);
200+
expect(JSON.stringify(out.failed)).toContain('Node hold (wait) of flow note_wait can pause the run between two approval steps of crm_note');
201+
});
164202
});

0 commit comments

Comments
 (0)