diff --git a/.changeset/39126-decision-admission.md b/.changeset/39126-decision-admission.md new file mode 100644 index 00000000000..57e02f7d623 --- /dev/null +++ b/.changeset/39126-decision-admission.md @@ -0,0 +1,13 @@ +--- +'@objectstack/spec': patch +'@objectstack/plugin-approvals': patch +--- + +feat(approvals): the service that owns an approval step can refuse a decision before it is recorded + +Clause-②: yes +Metadata-protocol: none + +A service that owns a flow's approval steps registers a check with `approvals.registerDecisionAdmission({ flow, check })` (`ApprovalDecisionAdmission` in `@objectstack/spec/contracts`, an optional member of `IApprovalService`). Every decision on an approval step of that flow is asked of it after the approvals service's own refusals and before anything is written: an approve or a reject through any door (REST, the action door, the action link, the SLA sweep's auto-decision), for a slot holder and for the administrator override alike, and a send-back, asked as what it records: `revise`, or `reject` once the step's revision budget is spent. A recall is not asked. A refusal (`{ userMessage, message? }`) answers `403 FORBIDDEN` with that `userMessage`; nothing is recorded, the request stays pending with its approvers and approver index unchanged, the run stays parked and no one is notified. Any other non-nullish answer refuses too, without a `userMessage`. A check that throws fails closed: its throw reaches the caller and nothing is recorded. An SLA auto-decision the check refuses leaves the request pending; the sweep's single-shot `escalate` marker is already written, so the sweep does not ask again. One admission per flow name; a second registration throws. + +Before this, a rule the owning flow enforced in a node after the approval could only refuse after the decision was recorded: the door answered `500 RESUME_FAILED`, the request read decided and the submitter was told nothing. Nothing changes for a flow with no admission registered. To adopt it, register the check where the flow is registered, probing for the member first (an implementation without it still satisfies the contract). diff --git a/content/docs/automation/approvals.mdx b/content/docs/automation/approvals.mdx index 87350d80f6d..54d2525ab3f 100644 --- a/content/docs/automation/approvals.mdx +++ b/content/docs/automation/approvals.mdx @@ -917,6 +917,15 @@ decision still lands. The approver slate, the `sys_approval_action` row and the status mirror all live on this path; it is the only one that produces a consistent outcome. +A service that owns a flow's approval steps can refuse a decision **before it is +recorded** by registering a decision admission on the approvals service +(`registerDecisionAdmission({ flow, check })`, `ApprovalDecisionAdmission` in +`@objectstack/spec/contracts`). Every approve, reject and send-back on a step of +that flow is asked first (a send-back past its revision budget is asked as the +`reject` it records); a refusal answers 403 (`FORBIDDEN`) with the check's +`userMessage`, and nothing is recorded — the request stays pending and the run +stays parked. A recall is not asked. + A decision may carry **file attachments** — `attachments: string[]` of `sys_file` ids — recorded on its audit row (e.g. a signed contract on the approve): diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index 4874e040080..5e578ece182 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -45,6 +45,7 @@ import type { ApprovalRequestRow, ApprovalActionRow, ApprovalActionAttachment, + ApprovalDecisionAdmission, ApprovalDecisionInput, ApprovalDecisionResult, ApprovalRecallInput, @@ -68,6 +69,7 @@ import type { import type { ExecutionContext } from '@objectstack/spec/kernel'; import { FlowInnerRefusalSchema } from '@objectstack/spec/api'; import { RESUME_AUTHORITY_SERVICE } from '@objectstack/spec/contracts'; +import { DecisionAdmissions } from './decision-admission.js'; import type { IOwnershipQueueService } from '@objectstack/spec/contracts'; import type { IWorkCalendarService } from '@objectstack/spec/contracts'; import { @@ -3390,6 +3392,22 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega this.messaging = messaging; } + /** + * [Ruling record 7344644972, option A] The decision admissions the services + * that own approval steps registered ({@link registerDecisionAdmission}), + * asked by `decideNode` and `sendBack` before their first write. + */ + private readonly decisionAdmissions = new DecisionAdmissions(); + + /** + * Attach the check the service that owns a flow's approval steps runs + * before any decision on them is recorded (`IApprovalService`'s + * `registerDecisionAdmission`; the rules live in `decision-admission.ts`). + */ + registerDecisionAdmission(admission: ApprovalDecisionAdmission): () => void { + return this.decisionAdmissions.register(admission); + } + /** * Best-effort notification fan-out — failures only log. * @@ -8869,6 +8887,15 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega // resume is just as stuck, and catching it here keeps the tally honest. await this.assertRunResumable(runId, requestId); + // [Ruling record 7344644972, option A] The service that owns this step's + // flow judges the decision before any of it is written: a refusal answers + // 403 with its userMessage and leaves the request pending, its approver + // index unchanged and its run parked. Last of the refusals, for every + // verb and the override arm alike. + await this.decisionAdmissions.admit(raw, { + decision: input.decision, actorId: recordedActor(context), viaOverride, comment: input.comment, + }, context); + // Audit the decision first so the quorum/per_group tally below sees it. await this.engine.insert('sys_approval_action', await this.actionRow(raw, { id: uid('aact'), request_id: requestId, organization_id: org, @@ -10392,6 +10419,15 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega }); priorSendBacks = Array.isArray(siblings) ? siblings.length : 0; } + // [Ruling record 7344644972, option A] As in decideNode: the owning + // service judges the send-back before anything is written. Asked as what + // this call will record: a `revise`, or — past the revision budget, where + // it records a `reject` and resumes the reject edge — a `reject`. The + // override does not reach this door, so it is never `viaOverride`. + await this.decisionAdmissions.admit(raw, { + decision: priorSendBacks >= maxRevisions ? 'reject' : 'revise', + actorId: recordedActor(context), viaOverride: false, comment: input.comment, + }, context); // Audit the revise intent first (audit-first, like decideNode) — on the // auto-reject path the trail then reads `revise → reject`, preserving diff --git a/packages/plugins/plugin-approvals/src/decision-admission.test.ts b/packages/plugins/plugin-approvals/src/decision-admission.test.ts new file mode 100644 index 00000000000..835729c36a1 --- /dev/null +++ b/packages/plugins/plugin-approvals/src/decision-admission.test.ts @@ -0,0 +1,457 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A decision admission — the check the service that owns an approval step + * runs BEFORE a decision on it is recorded (ruling record 7344644972, option + * A; `decision-admission.ts`). + * + * ## The defect, as the hosted cloud measured it + * + * The owning flow enforced "only a platform administrator decides this" in a + * node after the approval. An organization administrator, admitted by the + * override on a slate that names no platform slot, approved: `decideNode` + * recorded the decision, the resume reached the owning node, the node refused, + * and the door answered `500 RESUME_FAILED` with the request reading + * `approved` and the submitter told nothing. The CONTROL block below drives + * that shape on a real engine with no admission registered — it is unchanged + * by this card, because the rule had nowhere else to live. + * + * ## What is pinned + * + * 1. A refusal answers `FORBIDDEN` (status 403, the prefix the approvals + * doors map) with the check's `userMessage`, and records NOTHING: every + * stored row is byte-equal before and after, the request is still + * pending on its slate, the run is still parked, and no one is notified + * — for an override approve, a slot holder's reject and a send-back. + * 2. An admitted decision behaves exactly as without the check: recorded, + * resumed, the owning node runs, the submitter is told. + * 3. A check that throws fails closed: its throw reaches the caller as + * thrown, and nothing is recorded. + * 4. The check is asked with the request's facts and the decider's, and + * only for the flow it was registered under; one owner per flow. + * 5. A send-back is asked as what it records: `revise`, or `reject` once + * the step's revision budget is spent (that arm records a reject and + * resumes the reject edge). The SLA sweep's auto-decision is asked too. + */ + +import { describe, it, expect } from 'vitest'; +import { AutomationEngine, InMemorySuspendedRunStore, installBuiltinNodes } from '@objectstack/service-automation'; +import { assertEngineDeleteDispatch, assertEngineUpdateDispatch } from '@objectstack/objectql'; +import { APPROVAL_REVISE_NODE_TYPE } from '@objectstack/spec/automation'; +import type { ApprovalDecisionAdmissionInput, ApprovalDecisionRefusal } from '@objectstack/spec/contracts'; +import { ApprovalService } from './approval-service.js'; +import { registerApprovalNode } from './approval-node.js'; + +const noopLogger: any = { info() {}, warn() {}, error() {}, debug() {} }; +noopLogger.child = () => noopLogger; + +/** The one person the owning flow's rule accepts. */ +const PLATFORM_ADMIN = 'u_platform'; +/** A slot holder on the review step. */ +const REVIEWER = 'u_reviewer'; +/** An organization administrator of the request's organization, holding no slot. */ +const ORG_ADMIN = { userId: 'u_org_admin', tenantId: 'org1', positions: [], permissions: ['organization_admin'] } as any; +const asUser = (userId: string) => ({ userId, tenantId: 'org1', positions: [], permissions: [] }) as any; + +const RULE = 'Only a platform administrator decides a listing review.'; +const USER_TEXT = '只有平台管理员可以审核上架申请,请到「上架审核」列表处理。'; + +/** In-memory ObjectQL stand-in holding every table the approvals service writes. */ +function makeFakeEngine() { + // A `user` approver holds a slot only when an account carries it. + const tables = new Map([['sys_user', [REVIEWER, PLATFORM_ADMIN, 'u_submitter', ORG_ADMIN.userId].map(id => ({ id }))]]); + const rows = (o: string) => (tables.get(o) ?? (tables.set(o, []), tables.get(o)!)); + const matches = (row: any, where: any): boolean => Object.entries(where ?? {}).every(([k, v]) => { + // The read door's participant probe asks one `$or`, as the real engine composes it. + if (k === '$or') return (v as any[]).some((sub) => matches(row, sub)); + if (k.startsWith('$')) throw new Error(`fake engine: unsupported filter operator ${k}`); + if (v && typeof v === 'object' && '$in' in (v as any)) return (v as any).$in.includes(row[k]); + if (v && typeof v === 'object' && '$ne' in (v as any)) return row[k] !== (v as any).$ne; + return row[k] === v; + }); + return { + tables, + async find(object: string, opts: any = {}) { + const where = opts.where ?? opts.filter ?? {}; + const out = rows(object).filter(r => matches(r, where)); + const start = opts.offset ?? 0; + const page = typeof opts.limit === 'number' ? out.slice(start, start + opts.limit) : out.slice(start); + return page.map(r => ({ ...r })); + }, + async insert(object: string, data: any) { rows(object).push({ ...data }); return { ...data }; }, + async update(object: string, data: any, options?: any) { + const dispatch = assertEngineUpdateDispatch(data, options); + const table = rows(object); + if (dispatch.kind === 'multi') { + let n = 0; + for (let i = 0; i < table.length; i++) { + if (matches(table[i], options?.where)) { table[i] = { ...table[i], ...data }; n++; } + } + return { updated: n }; + } + const i = table.findIndex(r => r.id === dispatch.id); + if (i >= 0) table[i] = { ...table[i], ...data }; + return i >= 0 ? { ...table[i] } : null; + }, + async delete(object: string, options?: any) { + const dispatch = assertEngineDeleteDispatch(options); + const table = rows(object); + if (dispatch.kind === 'multi') { + const keep = table.filter(r => !matches(r, options?.where)); + const n = table.length - keep.length; + tables.set(object, keep); + return { deleted: n }; + } + const i = table.findIndex(r => r.id === (dispatch as any).id); + if (i >= 0) table.splice(i, 1); + return { id: (dispatch as any).id }; + }, + }; +} + +/** The owning service's node: it applies the decision only when its decider is the platform administrator. */ +const OWNER_FINALIZE = 'owner.finalize'; + +/** + * start → review (approval) → approve/reject: owner.finalize → end, and a + * revise edge to the revise window. + */ +const REVIEW_FLOW = { + name: 'listing_review', + label: 'Listing Review', + type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + { + id: 'review', type: 'approval', label: 'Review', + config: { + approvers: [{ type: 'user', value: REVIEWER }, { type: 'user', value: PLATFORM_ADMIN }], + behavior: 'first_response', lockRecord: false }, + }, + { id: 'finalize_approved', type: OWNER_FINALIZE, label: 'Approve', config: { decision: 'approve' } }, + { id: 'finalize_rejected', type: OWNER_FINALIZE, label: 'Reject', config: { decision: 'reject' } }, + { id: 'wait_revision', type: APPROVAL_REVISE_NODE_TYPE, label: 'Awaiting Revision' }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'e_start', source: 'start', target: 'review' }, + { id: 'e_approve', source: 'review', target: 'finalize_approved', label: 'approve' }, + { id: 'e_reject', source: 'review', target: 'finalize_rejected', label: 'reject' }, + { id: 'e_revise', source: 'review', target: 'wait_revision', label: 'revise' }, + { id: 'e_back', source: 'wait_revision', target: 'review', label: 'resubmit', type: 'back' }, + { id: 'e_fa', source: 'finalize_approved', target: 'end' }, + { id: 'e_fr', source: 'finalize_rejected', target: 'end' }, + ], +}; + +/** The same steps under another name: no admission is registered for it. */ +const OTHER_FLOW = { ...REVIEW_FLOW, name: 'other_review', label: 'Other Review' }; + +/** + * @param reviewConfig extra keys for the review step's config (`maxRevisions`, + * `escalation`), on {@link REVIEW_FLOW} only. + */ +function boot(reviewConfig: Record = {}) { + const data = makeFakeEngine(); + data.tables.set('listing', [{ id: 'l1', status: 'pending_review' }]); + let t = Date.parse('2026-12-02T00:00:00Z'); + const service = new ApprovalService({ engine: data as any, logger: noopLogger, clock: { now: () => new Date((t += 1000)) } }); + /** Move the service's clock forward, for the SLA sweep. */ + const advance = (ms: number) => { t += ms; }; + const automation = new AutomationEngine(noopLogger, new InMemorySuspendedRunStore()); + installBuiltinNodes(automation, { logger: noopLogger, getService: (n: string) => (n === 'data' ? data : undefined) } as any); + registerApprovalNode(automation, service, noopLogger); + const finalized: string[] = []; + automation.registerNodeExecutor({ + type: OWNER_FINALIZE, + async execute(node: any, _vars: unknown, context: any) { + if (context?.userId !== PLATFORM_ADMIN) { + return { success: false, error: `owner.finalize: ${RULE}`, innerRefusal: { code: 'PERMISSION_DENIED', message: RULE }, userMessage: USER_TEXT }; + } + finalized.push(String(node.config?.decision)); + return { success: true }; + }, + } as never); + const review = { + ...REVIEW_FLOW, + nodes: REVIEW_FLOW.nodes.map(n => (n.id === 'review' ? { ...n, config: { ...n.config, ...reviewConfig } } : n)), + }; + for (const flow of [review, OTHER_FLOW]) automation.registerFlow(flow.name, flow as never); + service.attachAutomation(automation); + const emits: Array<{ topic: string }> = []; + service.attachMessaging({ async emit(input: any) { emits.push(input); } } as never); + return { data, service, automation, finalized, emits, advance }; +} + +type Env = ReturnType; + +/** Start `flow` for the listing, and hand back the pending request. */ +async function park(env: Env, flow = REVIEW_FLOW.name) { + const started = await env.automation.execute(flow, { + object: 'listing', record: { id: 'l1', status: 'pending_review' }, userId: 'u_submitter', organizationId: 'org1', + } as never); + expect((started as any).status, 'the run parks').toBe('paused'); + const req = (await env.data.find('sys_approval_request', { where: { status: 'pending' } }))[0]; + expect(req?.flow_run_id, 'the request names the run it gates').toBeTruthy(); + // The organization the request is filed under, for the override arm. + await env.data.update('sys_approval_request', { id: req.id, organization_id: 'org1' }, { context: {} }); + env.emits.length = 0; + return { ...req, organization_id: 'org1' }; +} + +/** Every stored row, for "nothing was recorded" (the double opens an empty table on a read; that stores nothing). */ +const snapshot = (env: Env) => JSON.stringify( + [...env.data.tables.entries()].filter(([, rows]) => rows.length > 0).sort(([a], [b]) => a.localeCompare(b)), +); + +/** The check the owning service registers: the platform administrator alone decides. */ +const platformAdminOnly = (seen: ApprovalDecisionAdmissionInput[] = []) => ({ + flow: REVIEW_FLOW.name, + check(input: ApprovalDecisionAdmissionInput): ApprovalDecisionRefusal | undefined { + seen.push(input); + return input.actorId === PLATFORM_ADMIN ? undefined : { userMessage: USER_TEXT, message: RULE }; + }, +}); + +/** The thrown refusal's envelope: code, status, the user's text and the English rule. */ +async function refusalOf(p: Promise) { + const err: any = await p.then(() => { throw new Error('expected the decision to be refused'); }, (e) => e); + return err; +} + +async function expectNothingRecorded(env: Env, req: any, before: string) { + expect(JSON.parse(snapshot(env)), 'every stored row is unchanged').toEqual(JSON.parse(before)); + const now = (await env.data.find('sys_approval_request', { where: { id: req.id } }))[0]; + expect(now.status, 'the request is still pending').toBe('pending'); + expect(now.pending_approvers, 'on the slate it had').toBe(req.pending_approvers); + expect(env.automation.listSuspendedRuns().map((r: any) => r.runId), 'the run is still parked').toContain(req.flow_run_id); + expect(env.emits, 'no one is notified').toEqual([]); + expect(env.finalized, 'the owning node never ran').toEqual([]); +} + +describe('decision admission — the owning service refuses before the decision is recorded', () => { + describe('CONTROL — with no admission, the owning node can only refuse after the record (the measured defect)', () => { + it('an override approval answers RESUME_FAILED and leaves the request reading approved, the submitter untold', async () => { + const env = boot(); + const req = await park(env); + const err = await refusalOf(env.service.decide(req.id, { decision: 'approve', actorId: ORG_ADMIN.userId }, ORG_ADMIN)); + expect(String(err.message)).toMatch(/^RESUME_FAILED/); + const now = (await env.data.find('sys_approval_request', { where: { id: req.id } }))[0]; + expect(now.status, 'decided, though the owning flow refused it').toBe('approved'); + expect(env.emits.map(e => e.topic)).not.toContain('approval.approved'); + expect(env.finalized).toEqual([]); + }); + }); + + it('an override approval the check refuses: 403 FORBIDDEN with the userMessage, nothing recorded, still pending', async () => { + const env = boot(); + const seen: ApprovalDecisionAdmissionInput[] = []; + env.service.registerDecisionAdmission(platformAdminOnly(seen)); + const req = await park(env); + const before = snapshot(env); + + const err = await refusalOf(env.service.decide(req.id, { decision: 'approve', actorId: ORG_ADMIN.userId }, ORG_ADMIN)); + expect(err.code).toBe('FORBIDDEN'); + expect(err.status).toBe(403); + expect(String(err.message)).toMatch(/^FORBIDDEN: /); + expect(err.userMessage).toBe(USER_TEXT); + expect(String(err.message)).toContain(RULE); + await expectNothingRecorded(env, req, before); + + expect(seen).toHaveLength(1); + expect(seen[0]).toMatchObject({ + requestId: req.id, flow: REVIEW_FLOW.name, packageId: null, nodeId: 'review', runId: req.flow_run_id, + object: 'listing', recordId: 'l1', organizationId: 'org1', submitterId: 'u_submitter', + decision: 'approve', actorId: ORG_ADMIN.userId, viaOverride: true, + }); + expect(seen[0]!.context).toBe(ORG_ADMIN); + }); + + it('a slot holder\'s rejection the check refuses: the same refusal, nothing recorded', async () => { + const env = boot(); + const seen: ApprovalDecisionAdmissionInput[] = []; + env.service.registerDecisionAdmission(platformAdminOnly(seen)); + const req = await park(env); + const before = snapshot(env); + + const err = await refusalOf(env.service.decide( + req.id, { decision: 'reject', actorId: REVIEWER, comment: 'not ready for listing' }, asUser(REVIEWER), + )); + expect(err.code).toBe('FORBIDDEN'); + expect(err.status).toBe(403); + expect(err.userMessage).toBe(USER_TEXT); + await expectNothingRecorded(env, req, before); + expect(seen[0]).toMatchObject({ decision: 'reject', actorId: REVIEWER, viaOverride: false, comment: 'not ready for listing' }); + }); + + it('a send-back the check refuses: the same refusal, asked as `revise`, nothing recorded', async () => { + const env = boot(); + const seen: ApprovalDecisionAdmissionInput[] = []; + env.service.registerDecisionAdmission(platformAdminOnly(seen)); + const req = await park(env); + const before = snapshot(env); + + const err = await refusalOf(env.service.sendBack(req.id, { actorId: REVIEWER, comment: 'fix the icon' }, asUser(REVIEWER))); + expect(err.code).toBe('FORBIDDEN'); + expect(err.status).toBe(403); + expect(err.userMessage).toBe(USER_TEXT); + await expectNothingRecorded(env, req, before); + expect(seen[0]).toMatchObject({ decision: 'revise', actorId: REVIEWER, viaOverride: false }); + }); + + describe('a send-back past its revision budget records a reject, so it is asked as `reject`', () => { + /** "Anyone on the slate may send back; only the platform administrator rejects." */ + const sendBackOnly = (seen: ApprovalDecisionAdmissionInput[]) => ({ + flow: REVIEW_FLOW.name, + check(input: ApprovalDecisionAdmissionInput): ApprovalDecisionRefusal | undefined { + seen.push(input); + return input.decision === 'reject' && input.actorId !== PLATFORM_ADMIN ? { userMessage: USER_TEXT, message: RULE } : undefined; + }, + }); + + it('the budget spent: the check that refuses a reject refuses the send-back, nothing recorded', async () => { + const env = boot({ maxRevisions: 0 }); + const seen: ApprovalDecisionAdmissionInput[] = []; + env.service.registerDecisionAdmission(sendBackOnly(seen)); + const req = await park(env); + const before = snapshot(env); + + const err = await refusalOf(env.service.sendBack(req.id, { actorId: REVIEWER, comment: 'fix the icon' }, asUser(REVIEWER))); + expect(err).toMatchObject({ code: 'FORBIDDEN', status: 403, userMessage: USER_TEXT }); + await expectNothingRecorded(env, req, before); + expect(seen.map(i => i.decision)).toEqual(['reject']); + }); + + it('CONTROL — budget left: the same check admits the send-back, asked as `revise`, and the request is returned', async () => { + const env = boot({ maxRevisions: 3 }); + const seen: ApprovalDecisionAdmissionInput[] = []; + env.service.registerDecisionAdmission(sendBackOnly(seen)); + const req = await park(env); + + const sent = await env.service.sendBack(req.id, { actorId: REVIEWER, comment: 'fix the icon' }, asUser(REVIEWER)); + expect(sent.request.status).toBe('returned'); + expect(sent.autoRejected).toBeUndefined(); + expect(seen.map(i => i.decision)).toEqual(['revise']); + }); + }); + + it("the SLA sweep's auto-decision is asked too: refused, no decision recorded, the request still pending", async () => { + const env = boot({ escalation: { enabled: true, timeoutHours: 1, action: 'auto_approve', notifySubmitter: true } }); + const seen: ApprovalDecisionAdmissionInput[] = []; + env.service.registerDecisionAdmission(platformAdminOnly(seen)); + const req = await park(env); + env.advance(2 * 3600_000); + + // The sweep isolates a throwing request (it logs and moves on), so it answers normally. + await env.service.runEscalations(); + expect(seen).toHaveLength(1); + // The sweep decides under a system context, which holds no slot and is admitted by the + // override arm: `viaOverride` is the arm taken, exactly what the action row would record. + expect(seen[0]).toMatchObject({ decision: 'approve', actorId: null, viaOverride: true }); + expect(seen[0]!.context.isSystem).toBe(true); + + const now = (await env.data.find('sys_approval_request', { where: { id: req.id } }))[0]; + expect(now.status, 'the request is still pending').toBe('pending'); + expect(now.pending_approvers, 'on the slate it had').toBe(req.pending_approvers); + const actions = (await env.data.find('sys_approval_action', { where: { request_id: req.id } })).map((a: any) => a.action); + expect(actions, 'no decision is recorded').not.toContain('approve'); + // What the sweep itself writes BEFORE it decides stays: its single-shot `escalate` + // marker (ADR-0042), so a refused auto-decision is not asked again on the next sweep. + expect(actions.filter((a: string) => a === 'escalate')).toHaveLength(1); + expect(env.automation.listSuspendedRuns().map((r: any) => r.runId), 'the run is still parked').toContain(req.flow_run_id); + expect(env.emits.map(e => e.topic), 'no decision outcome is told').not.toContain('approval.approved'); + expect(env.finalized).toEqual([]); + + await env.service.runEscalations(); + expect(seen, 'single-shot: the next sweep does not ask again').toHaveLength(1); + }); + + it('an admitted decision is unchanged: recorded, resumed, the owning node runs, the submitter is told', async () => { + const env = boot(); + env.service.registerDecisionAdmission(platformAdminOnly()); + const req = await park(env); + + const out = await env.service.decide(req.id, { decision: 'approve', actorId: PLATFORM_ADMIN }, asUser(PLATFORM_ADMIN)); + expect(out).toMatchObject({ finalized: true, resumed: true, decision: 'approve' }); + expect(out.request.status).toBe('approved'); + expect(env.finalized).toEqual(['approve']); + expect(env.emits.map(e => e.topic)).toContain('approval.approved'); + }); + + it('an async check is awaited: a promised refusal refuses, a promised admission admits', async () => { + const env = boot(); + env.service.registerDecisionAdmission({ + flow: REVIEW_FLOW.name, + check: async (input) => (input.decision === 'reject' ? { userMessage: USER_TEXT } : undefined), + }); + const req = await park(env); + const before = snapshot(env); + const err = await refusalOf(env.service.decide(req.id, { decision: 'reject', actorId: REVIEWER, comment: 'no' }, asUser(REVIEWER))); + expect(err).toMatchObject({ code: 'FORBIDDEN', status: 403, userMessage: USER_TEXT }); + await expectNothingRecorded(env, req, before); + }); + + it('a check that throws fails closed: the throw reaches the caller as thrown, nothing recorded', async () => { + const env = boot(); + const fault = Object.assign(new Error('directory unreachable'), { name: 'DirectoryError' }); + env.service.registerDecisionAdmission({ flow: REVIEW_FLOW.name, check() { throw fault; } }); + const req = await park(env); + const before = snapshot(env); + + const err = await refusalOf(env.service.decide(req.id, { decision: 'approve', actorId: REVIEWER }, asUser(REVIEWER))); + expect(err).toBe(fault); + await expectNothingRecorded(env, req, before); + }); + + it('a non-nullish answer that is not a refusal object refuses — fail closed, no userMessage', async () => { + for (const answer of [false, 'no', 0] as const) { + const env = boot(); + env.service.registerDecisionAdmission({ flow: REVIEW_FLOW.name, check: () => answer as never }); + const req = await park(env); + const before = snapshot(env); + const err = await refusalOf(env.service.decide(req.id, { decision: 'approve', actorId: REVIEWER }, asUser(REVIEWER))); + expect(err, `answer ${JSON.stringify(answer)}`).toMatchObject({ code: 'FORBIDDEN', status: 403 }); + expect('userMessage' in err).toBe(false); + await expectNothingRecorded(env, req, before); + } + }); + + it('a refusal with no usable userMessage still refuses, carrying none', async () => { + const env = boot(); + env.service.registerDecisionAdmission({ flow: REVIEW_FLOW.name, check: () => ({ userMessage: ' ' }) }); + const req = await park(env); + const before = snapshot(env); + const err = await refusalOf(env.service.decide(req.id, { decision: 'approve', actorId: REVIEWER }, asUser(REVIEWER))); + expect(err).toMatchObject({ code: 'FORBIDDEN', status: 403 }); + expect('userMessage' in err).toBe(false); + await expectNothingRecorded(env, req, before); + }); + + it('only the flow it was registered under is asked', async () => { + const env = boot(); + const seen: ApprovalDecisionAdmissionInput[] = []; + env.service.registerDecisionAdmission(platformAdminOnly(seen)); + const req = await park(env, OTHER_FLOW.name); + const out = await env.service.decide(req.id, { decision: 'approve', actorId: PLATFORM_ADMIN }, asUser(PLATFORM_ADMIN)); + expect(out.request.status).toBe('approved'); + expect(seen).toEqual([]); + }); + + it('one owner per flow: a second registration throws and the first stands; the disposer removes only its own', async () => { + const env = boot(); + const first = platformAdminOnly(); + const dispose = env.service.registerDecisionAdmission(first); + expect(() => env.service.registerDecisionAdmission({ flow: REVIEW_FLOW.name, check: () => undefined })) + .toThrow(/already has a decision admission/); + expect(() => env.service.registerDecisionAdmission({ flow: ' ', check: () => undefined } as never)).toThrow(TypeError); + expect(() => env.service.registerDecisionAdmission({ flow: 'x' } as never)).toThrow(TypeError); + + const req = await park(env); + await expect(env.service.decide(req.id, { decision: 'approve', actorId: REVIEWER }, asUser(REVIEWER))) + .rejects.toMatchObject({ code: 'FORBIDDEN' }); + dispose(); + // Removed: the decision is recorded, and the owning node refuses AFTER it — the CONTROL shape again. + await expect(env.service.decide(req.id, { decision: 'approve', actorId: REVIEWER }, asUser(REVIEWER))) + .rejects.toThrow(/^RESUME_FAILED/); + }); +}); diff --git a/packages/plugins/plugin-approvals/src/decision-admission.ts b/packages/plugins/plugin-approvals/src/decision-admission.ts new file mode 100644 index 00000000000..5889de8bad8 --- /dev/null +++ b/packages/plugins/plugin-approvals/src/decision-admission.ts @@ -0,0 +1,152 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Decision admissions — the check the service that owns an approval step + * runs BEFORE a decision on it is recorded (ruling record 7344644972, option + * A; the contract is `ApprovalDecisionAdmission` in + * `@objectstack/spec/contracts`). + * + * The approvals service records a decision and only then resumes the owning + * flow, so a rule the flow enforces in a node after the approval met a + * decision already written: it could only fail the resume (`500 + * RESUME_FAILED`), leaving the request reading decided and the submitter + * told nothing. An admission moves that rule in front of the record. + * + * Kept out of `approval-service.ts` (a new concern beside a file far past the + * size where new concerns get their own module); the service holds one + * {@link DecisionAdmissions} and asks it from `decideNode` and `sendBack`, + * after their own refusals and before their first write. + */ + +import type { + ApprovalDecisionAdmission, + ApprovalDecisionAdmissionInput, + ApprovalDecisionVerb, +} from '@objectstack/spec/contracts'; +import type { ExecutionContext } from '@objectstack/spec/kernel'; + +/** The facts of a pending request an admission is asked about, as the row stores them. */ +interface PendingRequestFacts { + id?: unknown; + process_name?: unknown; + process_package?: unknown; + flow_node_id?: unknown; + current_step?: unknown; + flow_run_id?: unknown; + object_name?: unknown; + record_id?: unknown; + organization_id?: unknown; + submitter_id?: unknown; +} + +/** The decision being asked about, beside the request. */ +export interface DecisionUnderAdmission { + decision: ApprovalDecisionVerb; + actorId: string | null; + viaOverride: boolean; + comment?: string; +} + +const FLOW_PREFIX = 'flow:'; + +/** The flow name a request row's `process_name` (`flow:`) carries, or `undefined`. */ +function flowNameOf(raw: PendingRequestFacts): string | undefined { + const process = raw.process_name; + if (typeof process !== 'string' || !process.startsWith(FLOW_PREFIX)) return undefined; + const name = process.slice(FLOW_PREFIX.length); + return name === '' ? undefined : name; +} + +const textOrNull = (v: unknown): string | null => (v == null || v === '' ? null : String(v)); + +/** A non-blank string, trimmed of nothing, or `undefined` — the marking rule `userMessage` is read by. */ +const marked = (v: unknown): string | undefined => (typeof v === 'string' && v.trim() !== '' ? v : undefined); + +/** + * The refusal a decision admission answers: `403 FORBIDDEN` (the approvals + * doors map the `FORBIDDEN:` prefix, and `status` / `code` ride the error for + * every door that reads them), its English rule as the message and the + * check's `userMessage` as the end user's text. + */ +export function decisionAdmissionRefusal( + flow: string, + decision: ApprovalDecisionVerb, + refusal: unknown, +): Error & { status: number; code: string; userMessage?: string } { + const r = (refusal ?? {}) as { userMessage?: unknown; message?: unknown }; + const userMessage = marked(r.userMessage); + const rule = marked(r.message) ?? userMessage; + const verb = decision === 'revise' ? 'send-back' : decision; + const err = new Error( + `FORBIDDEN: the service that owns flow '${flow}' refused this ${verb} decision before it was recorded` + + `${rule !== undefined ? `: ${rule}` : ''}${rule !== undefined && /[.!?。!?]$/.test(rule) ? '' : '.'}` + + ' Nothing was recorded and the request is still pending.', + ) as Error & { status: number; code: string; userMessage?: string }; + err.status = 403; + err.code = 'FORBIDDEN'; + if (userMessage !== undefined) err.userMessage = userMessage; + return err; +} + +/** The admissions one approvals service holds, keyed by the name of the flow each guards. */ +export class DecisionAdmissions { + private readonly byFlow = new Map(); + + /** + * Register `admission`. One owner per flow: a second registration for a + * flow name already held throws and replaces nothing. Returns the function + * that removes this registration (and only this one). + */ + register(admission: ApprovalDecisionAdmission): () => void { + const flow = admission?.flow; + if (typeof flow !== 'string' || flow.trim() === '') { + throw new TypeError('registerDecisionAdmission: `flow` must name the flow whose approval steps the check guards'); + } + if (typeof admission.check !== 'function') { + throw new TypeError(`registerDecisionAdmission: the admission for flow '${flow}' declares no \`check\` function`); + } + if (this.byFlow.has(flow)) { + throw new Error( + `registerDecisionAdmission: flow '${flow}' already has a decision admission; one service owns a flow's ` + + 'approval steps, so the second registration is refused and the first one stands', + ); + } + this.byFlow.set(flow, admission); + return () => { + if (this.byFlow.get(flow) === admission) this.byFlow.delete(flow); + }; + } + + /** + * Ask the admission registered for the request's flow about one decision. + * Resolves when it is admitted (or no admission guards the flow); throws + * {@link decisionAdmissionRefusal} when it refuses. A check that throws + * fails closed: its throw propagates as thrown. Asked BEFORE any write — + * the caller's contract, not this function's. + */ + async admit(raw: PendingRequestFacts, under: DecisionUnderAdmission, context: ExecutionContext): Promise { + const flow = flowNameOf(raw); + if (flow === undefined) return; + const admission = this.byFlow.get(flow); + if (!admission) return; + const input: ApprovalDecisionAdmissionInput = { + requestId: String(raw.id ?? ''), + flow, + packageId: textOrNull(raw.process_package), + nodeId: textOrNull(raw.flow_node_id ?? raw.current_step), + runId: textOrNull(raw.flow_run_id), + object: String(raw.object_name ?? ''), + recordId: String(raw.record_id ?? ''), + organizationId: textOrNull(raw.organization_id), + submitterId: textOrNull(raw.submitter_id), + decision: under.decision, + actorId: under.actorId, + viaOverride: under.viaOverride, + ...(typeof under.comment === 'string' ? { comment: under.comment } : {}), + context, + }; + const refusal = await admission.check(input); + if (refusal == null) return; + throw decisionAdmissionRefusal(flow, under.decision, refusal); + } +} diff --git a/packages/spec/api-surface/contracts.json b/packages/spec/api-surface/contracts.json index ef89a9527d6..116d70040f1 100644 --- a/packages/spec/api-surface/contracts.json +++ b/packages/spec/api-surface/contracts.json @@ -57,8 +57,12 @@ "ApprovalActionKind (type)", "ApprovalActionRow (interface)", "ApprovalCancelReason (type)", + "ApprovalDecisionAdmission (interface)", + "ApprovalDecisionAdmissionInput (interface)", "ApprovalDecisionInput (interface)", + "ApprovalDecisionRefusal (interface)", "ApprovalDecisionResult (interface)", + "ApprovalDecisionVerb (type)", "ApprovalRecallInput (interface)", "ApprovalRecallResult (interface)", "ApprovalRequestRow (interface)", diff --git a/packages/spec/export-origins/contracts.json b/packages/spec/export-origins/contracts.json index ebb7b8911ea..391dd65e684 100644 --- a/packages/spec/export-origins/contracts.json +++ b/packages/spec/export-origins/contracts.json @@ -57,8 +57,12 @@ "ApprovalActionKind": "src/contracts/approval-service.ts#ApprovalActionKind (type)", "ApprovalActionRow": "src/contracts/approval-service.ts#ApprovalActionRow (interface)", "ApprovalCancelReason": "src/contracts/approval-service.ts#ApprovalCancelReason (type)", + "ApprovalDecisionAdmission": "src/contracts/approval-service.ts#ApprovalDecisionAdmission (interface)", + "ApprovalDecisionAdmissionInput": "src/contracts/approval-service.ts#ApprovalDecisionAdmissionInput (interface)", "ApprovalDecisionInput": "src/contracts/approval-service.ts#ApprovalDecisionInput (interface)", + "ApprovalDecisionRefusal": "src/contracts/approval-service.ts#ApprovalDecisionRefusal (interface)", "ApprovalDecisionResult": "src/contracts/approval-service.ts#ApprovalDecisionResult (interface)", + "ApprovalDecisionVerb": "src/contracts/approval-service.ts#ApprovalDecisionVerb (type)", "ApprovalRecallInput": "src/contracts/approval-service.ts#ApprovalRecallInput (interface)", "ApprovalRecallResult": "src/contracts/approval-service.ts#ApprovalRecallResult (interface)", "ApprovalRequestRow": "src/contracts/approval-service.ts#ApprovalRequestRow (interface)", diff --git a/packages/spec/src/contracts/approval-service.ts b/packages/spec/src/contracts/approval-service.ts index 8245c84036c..ef65c229cb9 100644 --- a/packages/spec/src/contracts/approval-service.ts +++ b/packages/spec/src/contracts/approval-service.ts @@ -773,6 +773,133 @@ export interface ApprovalDecisionInput { outputs?: Record; } +/** + * The verbs a decision admission is asked about + * ({@link ApprovalDecisionAdmission}): the approver's verdicts that finalise a + * request (or, for `approve` under a co-sign behaviour, count toward it) and + * move the owning flow — an `approve`, a `reject`, and an ADR-0044 send-back + * (`revise`). Spelled as the {@link ApprovalActionKind} each one records: a + * send-back past the step's revision budget records a `reject` (and resumes + * the reject edge), so it is asked as `reject`, never as `revise`. + */ +export type ApprovalDecisionVerb = Extract; + +/** + * What a decision admission check is asked + * ({@link ApprovalDecisionAdmission.check}): one decision, before the approvals + * service records any of it. Every fact is read off the pending request as + * stored and off the decider's context — nothing here is the caller's claim. + */ +export interface ApprovalDecisionAdmissionInput { + /** The pending request the decision is about. */ + requestId: string; + /** The name of the flow the request's approval step belongs to — the name the admission was registered under. */ + flow: string; + /** The package the request's flow is filed under, or `null` for a flow no package holds. */ + packageId: string | null; + /** The approval step (flow node id) the request was opened on. */ + nodeId: string | null; + /** The suspended flow run the decision would resume. */ + runId: string | null; + /** The object and record the request is about. */ + object: string; + recordId: string; + /** The request's organization, or `null` for none. */ + organizationId: string | null; + /** Who submitted the request, or `null` when its run named no user. */ + submitterId: string | null; + /** The decision about to be recorded. */ + decision: ApprovalDecisionVerb; + /** + * The person the decision would be recorded against — the user the + * context vouches for, the value written to `sys_approval_action.actor_id` + * — or `null` for a machine decider (the SLA sweep's auto-decision). + */ + actorId: string | null; + /** + * `true` when the decider holds no slot on the request and is admitted only + * by the administrator override — the fact `sys_approval_action.via_override` + * records. Always `false` for a send-back, which the override does not reach. + * It is an audit fact about the arm this decision took, ⛔ not the decider's + * standing: an override actor who reassigned the request to themselves + * decides as a slot holder, `false` here. Judge a rule about WHO decides on + * {@link actorId} and {@link context}. + */ + viaOverride: boolean; + /** The decision's comment, when the decider wrote one. */ + comment?: string; + /** The decider's resolved execution context. */ + context: ExecutionContext; +} + +/** + * A decision admission check's refusal ({@link ApprovalDecisionAdmission.check}). + * The decision is answered `403 FORBIDDEN`, nothing is recorded and the + * request stays pending. + */ +export interface ApprovalDecisionRefusal { + /** + * What the decider is told, in their language: carried on the refusal as + * its `userMessage` (`ApiErrorSchema.userMessage`). A blank or non-string + * value is no marking — the decision is still refused, without one. + */ + userMessage: string; + /** + * The rule that refused, in English, for the refusal's `error` text and the + * operator's log. Defaults to {@link userMessage}. + */ + message?: string; +} + +/** + * **A declared check the service that owns an approval step runs before a + * decision on it is recorded** (ruling record 7344644972, option A). + * + * The approvals service records a decision — the audit row, the request's + * terminal status, the approver index, the status mirror — and only then + * resumes the owning flow. A rule the owning flow enforces in a node after + * the approval therefore met a decision already recorded: it could only fail + * the resume, which answered `500 RESUME_FAILED`, left the request reading + * decided and told the submitter nothing. A service that owns such a rule + * registers it here instead, keyed by the flow's name, and every decision on + * an approval step of that flow is asked of it first. + * + * - **When it runs:** on every decision verb ({@link ApprovalDecisionVerb}), + * through every door that decides (the REST routes, the action door, the + * action link, the SLA sweep's auto-decision), for a slot holder and for + * the administrator override alike — after the service's own refusals and + * before the first write. A send-back is asked as what it records: `revise`, + * or `reject` past the step's revision budget. ⛔ {@link IApprovalService.recall} + * is not asked — a recall is a withdrawal, not a decision, and it reaches a + * pending request through the submitter, a system context and the + * administrator override alike. + * - **Refusal:** {@link check} answers an {@link ApprovalDecisionRefusal}. The + * decision answers `403 FORBIDDEN` with its `userMessage`; nothing is + * recorded, the request stays pending, its approvers and the approver index + * are unchanged, the run stays parked and no one is notified. + * - **Admission:** {@link check} answers `undefined` (or `null`). Any other + * answer refuses — fail closed: a value that is not a refusal object + * (`false`, a string) refuses with no `userMessage`. + * - **Failure:** a check that throws fails closed. Its throw reaches the + * caller as thrown — a throw declaring its own `status` and `code` answers + * them, any other a 5xx — and nothing is recorded. + * - **Sync or async:** {@link check} may return its answer or a promise of it. + */ +export interface ApprovalDecisionAdmission { + /** + * The flow whose approval steps this check guards — its `name`, as the + * owning service registered it. Every request opened by an approval node + * of a flow so named is asked; the check reads + * {@link ApprovalDecisionAdmissionInput.packageId} and + * {@link ApprovalDecisionAdmissionInput.nodeId} to narrow further. + */ + flow: string; + /** Judge one decision: a refusal, or `undefined` to admit it. */ + check( + input: ApprovalDecisionAdmissionInput, + ): ApprovalDecisionRefusal | undefined | null | Promise; +} + /** Input for recalling (withdrawing) an undecided request. */ export interface ApprovalRecallInput { /** @@ -1263,6 +1390,22 @@ export interface IApprovalService { */ decide(requestId: string, input: ApprovalDecisionInput, context: ExecutionContext): Promise; + /** + * Attach a decision admission ({@link ApprovalDecisionAdmission}): the check + * the service that owns an approval step's flow runs before any decision on + * that step is recorded — {@link decide} and {@link sendBack} alike. + * + * One owner per flow: registering a second admission for a flow name that + * already holds one throws, and nothing is replaced. Returns the function + * that removes this registration. + * + * **Optional, and its absence is loud:** an implementation without it still + * satisfies this contract, so a service whose rule must hold probes for + * presence and refuses to start its flow without it — never assumes the + * check ran. + */ + registerDecisionAdmission?(admission: ApprovalDecisionAdmission): () => void; + /** * Withdraw a request that has not been decided. Finalises it as `recalled` * and resumes the owning flow run down the `reject` branch with diff --git a/scripts/engine-double-contract.pinned.json b/scripts/engine-double-contract.pinned.json index 10fe42fff02..95965c74f93 100644 --- a/scripts/engine-double-contract.pinned.json +++ b/scripts/engine-double-contract.pinned.json @@ -3776,6 +3776,16 @@ "verb": "update", "pinned": 1 }, + { + "file": "packages/plugins/plugin-approvals/src/decision-admission.test.ts", + "verb": "delete", + "pinned": 1 + }, + { + "file": "packages/plugins/plugin-approvals/src/decision-admission.test.ts", + "verb": "update", + "pinned": 1 + }, { "file": "packages/plugins/plugin-approvals/src/decision-strand-envelope.test.ts", "verb": "delete",