From cc6d5f6ace49a8964ad467ed17edb1e80efd363c Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 04:56:18 +0000 Subject: [PATCH 1/4] wip(approvals): an abandoned request never writes a closed value on its status mirror Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5phEgfPTCgvPqh4ER2 --- .../plugin-approvals/src/approval-service.ts | 209 +++++++++++++++++- 1 file changed, 208 insertions(+), 1 deletion(-) diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index 610a641fdda..5aaa0294034 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -1783,6 +1783,12 @@ function parseJson(raw: unknown, fallback: T): T { /** [#24577] What {@link ApprovalService.mirroredStatusValue} answers when a transition writes nothing. */ const STATUS_NOT_MIRRORED = Symbol('status-not-mirrored'); +/** + * [ADR-0162 D5] The statuses the mirror writes for a request of an approval: + * a closed value outside these was not written by the approval. + */ +const MIRRORED_REQUEST_STATUSES: ReadonlySet = new Set(['pending', 'returned', 'approved', 'rejected']); + /** * [ADR-0162 Execution item 8] The request a write of the status mirror is * about, so that a refusal on a field the object closes on can be told on that @@ -5017,6 +5023,13 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * is {@link mirroredStatusValue}'s answer, and `abandoned` (the request's * row, on a transition that abandons it) is what that answer may restore. * + * **An abandoned request never writes a closed value (ADR-0162 D5, ruling + * record 7201405662).** On a transition that abandons a request, where the + * object's `closedStates` lists any value for `field`, the value is + * {@link abandonedValueOnClosingField}'s answer instead, and that answer may + * be to write nothing. Every other write, and every write on an object that + * closes on no value of `field`, is chosen as above. + * * **A refused write on a field the object closes on is not swallowed * (ADR-0162 D5, Execution item 8).** A validation rule, an option's * `visibleWhen` or a hook of the app can refuse this write, and no reading of @@ -5038,7 +5051,18 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega about?: MirrorRequestRef, ): Promise { try { - const value = this.mirroredStatusValue(object, field, status, abandoned); + // [ADR-0162 D5, Execution item 7] An abandoned request on a field the + // object closes on, on any value of it: no closed value is written, and + // a closed value the approval did not write is left alone. + const closed = abandoned ? this.closedValuesOf(object, field) : []; + let value: unknown; + if (abandoned && closed.length > 0) { + const choice = await this.abandonedValueOnClosingField(object, recordId, field, closed, abandoned, about); + if ('leave' in choice) return undefined; + value = choice.write; + } else { + value = this.mirroredStatusValue(object, field, status, abandoned); + } if (value === STATUS_NOT_MIRRORED) { this.logger?.warn?.( `[approvals] approval status '${status}' was not written to ${object}.${field}: the field's options do not ` @@ -5264,6 +5288,189 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega return holdsDeclaredValues(def?.defaultValue, declared) ? def!.defaultValue : null; } + /** + * [ADR-0162 D1] The values `object` declares closed on `field` + * (`closedStates[field]`), read from the registry the engine validates the + * mirror's write against, as {@link closesOnApprovalOutcome} reads them. + * Empty where the object declares none for the field, or where the schema + * cannot be read: the mirror then chooses as it did before the key. + */ + private closedValuesOf(object: string, field: string): string[] { + let closedStates: unknown; + try { + closedStates = (this.engine.getSchema?.(object) as { closedStates?: unknown } | undefined)?.closedStates; + } catch { /* schema unavailable — no closed value can be read */ } + if (!closedStates || typeof closedStates !== 'object') return []; + const closed = (closedStates as Record)[field]; + return Array.isArray(closed) ? closed.map((v) => String(v)) : []; + } + + /** + * [ADR-0162 D5, Execution item 7] What the mirror writes for a request that + * is abandoned (a recall, its override arm, the dead-run sweep) where the + * object closes on `field` on any value (`closed`). Ruling record + * 7201405662: 「平台堵住:撤回不恢复关闭值」. + * + * 1. **A closed value the approval did not write is left alone.** The field + * is read as it stands. Where it holds a closed value, the request is + * placed by its root run and the request table is asked, in one probe + * ({@link approvalWroteHeldValue}), whether a request of the same + * approval on the same record had that value as its status. Where none + * did, nothing is written. Where one did, or where it cannot tell, the + * mirror goes on to 2. + * 2. **`recalled`**, where the field declares it (or declares no value set) + * and the object does not close on it. A declared `recalled` the object + * closes on is withheld, and said so. + * 3. **The order**: the value held at submit, the field's declared + * default, empty. A closed value is passed over at each step, and so is a + * value the field does not declare (#24577). On a required field an + * empty value at submit is passed over for the default; on a field that + * is not required it is put back. + * + * Each departure from what the mirror wrote before the key is logged + * (N21): a withheld `recalled` at `warn`, since the author's closed value + * on it closes nothing through the mirror; a passed-over closed value and a + * value left alone at `info`. + */ + private async abandonedValueOnClosingField( + object: string, + recordId: string, + field: string, + closed: readonly string[], + abandoned: { payloadJson: unknown }, + about: MirrorRequestRef | undefined, + ): Promise<{ write: unknown } | { leave: true }> { + const isClosed = (v: unknown) => (Array.isArray(v) ? v : [v]).some((x) => x != null && closed.includes(String(x))); + const isEmpty = (v: unknown) => v == null || v === '' || (Array.isArray(v) && v.length === 0); + const request = about?.request; + const where = { object, record: recordId, field, request: request?.id ?? null }; + + // 1. A closed value the approval did not write is left alone. + let held: unknown; + let heldRead = false; + try { + const rows = await this.engine.find(object, { + where: { id: recordId }, fields: ['id', field], limit: 1, context: SYSTEM_CTX, + }); + const row = Array.isArray(rows) ? rows[0] : undefined; + if (row) { held = row[field]; heldRead = true; } + } catch (err: any) { + this.logger?.warn?.('[approvals] could not read the status field of an abandoned request\'s record; the mirror goes down its order', { + ...where, error: err?.message ?? String(err), + }); + } + if (heldRead && isClosed(held)) { + const wrote = await this.approvalWroteHeldValue(request, held); + if (wrote === 'not') { + this.logger?.info?.( + `[approvals] the abandoned approval left ${object}.${field} at '${String(held)}': the object closes on that value ` + + `and no request of this approval on the record held it, so another writer put it there and the mirror writes nothing.`, + { ...where, value: held }, + ); + return { leave: true }; + } + } + + let def: { defaultValue?: unknown; required?: unknown } | undefined; + try { + const schema = this.engine.getSchema?.(object) as { fields?: Record } | undefined; + def = schema?.fields?.[field] as typeof def; + } catch { /* schema unavailable — no declared value set */ } + const declared = declaredOptionValues(def); + const usable = (v: unknown) => !declared || holdsDeclaredValues(v, declared); + const passedOver: Array<{ from: 'submit' | 'default'; value: unknown }> = []; + const passed = () => { + if (passedOver.length === 0) return; + this.logger?.info?.( + `[approvals] the abandoned approval passed over ${passedOver.map((p) => `'${String(p.value)}' (${p.from === 'submit' ? 'the value at submit' : 'the default'})`).join(' and ')} ` + + `for ${object}.${field}: the object closes on it, and an abandoned approval never writes a closed value.`, + { ...where, passedOver }, + ); + }; + + // 2. `recalled`, where the field may hold it and the object does not close on it. + const declaresRecalled = !declared || declared.includes('recalled'); + if (declaresRecalled && !closed.includes('recalled')) return { write: 'recalled' }; + if (declaresRecalled) { + this.logger?.warn?.( + `[approvals] the abandoned approval did not write 'recalled' to ${object}.${field}: the object closes on 'recalled', ` + + `and an abandoned approval never writes a closed value, so the field takes the value at submit, the default or empty. ` + + `To show a withdrawn approval on the record, remove 'recalled' from the field's closed values.`, + { ...where, value: 'recalled' }, + ); + } + + // 3. The order: the value held at submit, the declared default, empty. + const snapshot = parseJson(abandoned.payloadJson, undefined); + if (snapshot && typeof snapshot === 'object' && Object.prototype.hasOwnProperty.call(snapshot, field)) { + const atSubmit = (snapshot as Record)[field]; + if (isEmpty(atSubmit)) { + if (def?.required !== true) { passed(); return { write: null }; } + } else if (isClosed(atSubmit)) { + passedOver.push({ from: 'submit', value: atSubmit }); + } else if (usable(atSubmit)) { + passed(); + return { write: atSubmit }; + } + } + const fallback = def?.defaultValue; + if (!isEmpty(fallback)) { + if (isClosed(fallback)) passedOver.push({ from: 'default', value: fallback }); + else if (usable(fallback)) { passed(); return { write: fallback }; } + } + passed(); + return { write: null }; + } + + /** + * [ADR-0162 D5, Execution item 7] Whether the approval `request` belongs to + * wrote `held`, the closed value its record's status field holds: whether a + * request of the same approval on the same record had it as its status. + * + * - `'not'`: no such request — `held` is not a status the mirror writes + * (`pending`, `returned`, `approved`, `rejected`), or the probe found none; + * - `'wrote'`: the request itself held it (every request opens on + * `pending`, and a recall in the revise window abandons a `returned` + * one), or the probe found a request of the approval that did; + * - `'unknown'`: the request records no root run (seat ruling 7210700837: + * it goes down the order), the probe found a request that records none + * and was opened since the approval's run started, or the probe failed. + * + * The approval is the request's root run (`root_run_id`), and the record is + * its `object_name` and `record_id`: a `map` item's request on another + * record does not count. One probe of the request table, on the index + * slice A declared for it. + */ + private async approvalWroteHeldValue(request: any, held: unknown): Promise<'wrote' | 'not' | 'unknown'> { + if (typeof held !== 'string' || !MIRRORED_REQUEST_STATUSES.has(held)) return 'not'; + if (held === 'pending' || held === String(request?.status ?? '')) return 'wrote'; + const rootRunId = request?.root_run_id ? String(request.root_run_id) : ''; + if (!rootRunId) return 'unknown'; + const startedAt = request?.root_run_started_at ?? null; + try { + const rows = await this.engine.find('sys_approval_request', { + where: { + object_name: request.object_name, + record_id: request.record_id, + status: held, + $or: [ + { root_run_id: rootRunId }, + startedAt != null ? { root_run_id: null, created_at: { $gte: startedAt } } : { root_run_id: null }, + ], + }, + fields: ['id', 'root_run_id'], limit: 1, context: SYSTEM_CTX, + }); + const found = Array.isArray(rows) ? rows[0] : undefined; + if (!found) return 'not'; + return String(found.root_run_id ?? '') === rootRunId ? 'wrote' : 'unknown'; + } catch (err: any) { + this.logger?.warn?.('[approvals] could not read whether an abandoned request\'s approval wrote the closed value its record holds; the mirror goes down its order', { + request: request?.id ?? null, value: held, error: err?.message ?? String(err), + }); + return 'unknown'; + } + } + /** * The context a named actor's status mirror writes under (see * {@link mirrorStatusField}): `{ isSystem: true, userId, tenantId }` and From 6e9bed526b1424490df40bb7339ec37f9501bfe0 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 05:05:13 +0000 Subject: [PATCH 2/4] test(approvals): the status mirror on an abandoned request, across its writers Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5phEgfPTCgvPqh4ER2 --- ...abandoned-closed-value.integration.test.ts | 538 ++++++++++++++++++ 1 file changed, 538 insertions(+) create mode 100644 packages/plugins/plugin-approvals/src/status-mirror-abandoned-closed-value.integration.test.ts diff --git a/packages/plugins/plugin-approvals/src/status-mirror-abandoned-closed-value.integration.test.ts b/packages/plugins/plugin-approvals/src/status-mirror-abandoned-closed-value.integration.test.ts new file mode 100644 index 00000000000..ceec81266e9 --- /dev/null +++ b/packages/plugins/plugin-approvals/src/status-mirror-abandoned-closed-value.integration.test.ts @@ -0,0 +1,538 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 D5, Execution item 7, "The mirror"] An abandoned approval never + * writes a closed value — ruling record 7201405662, 「平台堵住:撤回不恢复关闭值」. + * + * On every transition that abandons a request, where the object's + * `closedStates` lists any value for the mirror field, the mirror: + * - writes `recalled` where the field declares it and the object does not + * close on it; + * - otherwise goes down the order: the value held at submit, the field's + * declared default, empty — passing over a closed value at each step, and + * on a required field an empty value at submit for the default; + * - leaves alone a closed value the approval did not write, judged by one + * probe of the request table on the request's root run and record; where + * it cannot tell (no root run, or a request with none opened since the + * approval's run started), it goes down the order. + * + * The writers that abandon a request are counted by transition (N20): the + * submitter's recall of a pending request, the submitter's recall in the + * revise window, the override arm of `recall` taken by an administrator and + * by a system context, and the dead-run sweep. Each test records the value + * the field keeps. + * + * Driven on the real data engine (ObjectQL, its validator, SQLite through + * `SqlDriver`, the plugin's own objects synced) and the real automation + * engine with the approval node, the `request-root-run` harness. "Another + * writer" is a system write of the record while the request is pending. + */ + +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { AutomationEngine, InMemorySuspendedRunStore, installBuiltinNodes } from '@objectstack/service-automation'; +import { APPROVAL_REVISE_NODE_TYPE } from '@objectstack/spec/automation'; +import type { EngineQueryOptions } from '@objectstack/spec/data'; +import { ApprovalService } from './approval-service.js'; +import { ApprovalsServicePlugin } from './approvals-plugin.js'; +import { registerApprovalNode } from './approval-node.js'; +import { installDefaultOrganization } from './default-organization.testkit.js'; + +const SYSTEM = { isSystem: true, positions: [], permissions: [] } as any; +const asUser = (userId: string) => ({ userId, positions: [], permissions: [] }) as any; +const ADMIN = { userId: 'u_root', posture: 'PLATFORM_ADMIN', positions: [], permissions: [] } as any; +const SUBMITTER = 'u_sub'; +const ORG = 'org_default'; +const silentBase = { info: () => {}, warn: () => {}, error: () => {}, debug: () => {} }; +const silent: any = { ...silentBase, child() { return silent; } }; + +/** Records every level, so a line the mirror owes (N21) is measurable. */ +function recordingLogger() { + const lines: Array<{ level: string; msg: string; meta?: any }> = []; + const mk = (level: string) => (msg: unknown, ...rest: unknown[]) => { + lines.push({ level, msg: String(msg), meta: rest.find((r) => r && typeof r === 'object') }); + }; + const self: any = { lines, info: mk('info'), warn: mk('warn'), error: mk('error'), debug: mk('debug'), child() { return self; } }; + return self; +} + +const STATUSES = ['draft', 'pending', 'approved', 'rejected', 'returned']; +const option = (value: string) => ({ label: value, value }); +const text = (name: string) => ({ name, label: name, type: 'text' as const }); + +/** An object whose `approval_status` select is shaped by `field`, closing on `closed` (none: no `closedStates`). */ +function doc(name: string, field: Record, closed?: string[], values: string[] = STATUSES) { + return { + name, label: name, + fields: { + id: { name: 'id', label: 'Id', type: 'text' as const, primaryKey: true }, + name: text('name'), + approval_status: { name: 'approval_status', label: 'Status', type: 'select' as const, options: values.map(option), ...field }, + }, + ...(closed ? { closedStates: { approval_status: closed } } : {}), + }; +} + +const OBJECTS = [ + doc('doc_main', { defaultValue: 'draft' }, ['approved']), + doc('doc_open_recalled', { defaultValue: 'draft' }, ['approved'], [...STATUSES, 'recalled']), + doc('doc_closed_recalled', { defaultValue: 'draft' }, ['approved', 'recalled'], [...STATUSES, 'recalled']), + doc('doc_default_closed', { defaultValue: 'approved' }, ['approved']), + doc('doc_no_default', {}, ['approved']), + doc('doc_required', { defaultValue: 'draft', required: true }, ['approved']), + doc('doc_own_values', { defaultValue: 'draft' }, ['paid'], [...STATUSES, 'paid']), + doc('doc_paid', { defaultValue: 'draft' }, ['approved', 'paid'], [...STATUSES, 'paid']), + doc('doc_control', { defaultValue: 'draft' }), + // A field that cannot show `pending`: an approval not judged at its opening, + // where an earlier step's outcome stays on the field while a later step waits. + doc('doc_no_pending', { defaultValue: 'draft' }, ['approved'], STATUSES.filter((v) => v !== 'pending')), + // N17: an empty put-back on each kind of required field, no default. + doc('doc_req_editable', { required: true }, ['approved']), + doc('doc_req_readonly', { required: true, readonly: true }, ['approved']), + doc('doc_req_system', { required: true, system: true }, ['approved']), + doc('doc_req_when_shown', { required: true, visibleWhen: 'has(record.name) && record.name != null' }, ['approved']), +]; + +const step = (id: string, approver: string) => ({ + id, type: 'approval', label: id, + config: { approvers: [{ type: 'user', value: approver }], approvalStatusField: 'approval_status' }, +}); +/** One step with a revise window (ADR-0044). */ +const ONE = { + name: 'one', label: 'One step', type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + step('review', 'u_mgr'), + { id: 'wait_revision', type: APPROVAL_REVISE_NODE_TYPE, label: 'Awaiting revision' }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'review' }, + { id: 'e2', source: 'review', target: 'end', label: 'approve' }, + { id: 'e3', source: 'review', target: 'end', label: 'reject' }, + { id: 'e4', source: 'review', target: 'wait_revision', label: 'revise' }, + { id: 'e5', source: 'wait_revision', target: 'review', label: 'resubmit', type: 'back' }, + ], +}; +const chain = (name: string, nodes: any[]) => ({ + name, label: name, type: 'autolaunched', + nodes: [{ id: 'start', type: 'start', label: 'Start' }, ...nodes, { id: 'end', type: 'end', label: 'End' }], + edges: [ + { id: 'cstart', source: 'start', target: nodes[0].id }, + ...nodes.flatMap((n, i) => { + const next = nodes[i + 1]?.id ?? 'end'; + return n.type === 'approval' + ? [{ id: `c${i}a`, source: n.id, target: next, label: 'approve' }, { id: `c${i}r`, source: n.id, target: 'end', label: 'reject' }] + : [{ id: `c${i}`, source: n.id, target: next }]; + }), + ], +}); +/** Two steps in one run. */ +const TWO = chain('two', [step('first', 'u_mgr'), step('second', 'u_exec')]); +/** The earlier step in a `subflow` child, the abandoned one in the parent. */ +const CHILD_FIRST_BODY = chain('child_first_body', [step('first', 'u_mgr')]); +const CHILD_FIRST = chain('child_first', [{ id: 'sub', type: 'subflow', label: 'First, in a child', config: { flowName: 'child_first_body' } }, step('second', 'u_exec')]); +/** The earlier step in the parent, the abandoned one in a `subflow` child. */ +const PARENT_FIRST_BODY = chain('parent_first_body', [step('second', 'u_exec')]); +const PARENT_FIRST = chain('parent_first', [step('first', 'u_mgr'), { id: 'sub', type: 'subflow', label: 'Second, in a child', config: { flowName: 'parent_first_body' } }]); +/** A batch with no record of its own: each item is a `doc_main` record, approved in its own `one` run. */ +const BATCH = { + name: 'batch', label: 'Batch', type: 'autolaunched', + variables: [{ name: 'items', type: 'list', isInput: true }], + nodes: [ + { id: 'bstart', type: 'start', label: 'Start' }, + { id: 'each', type: 'map', label: 'Each document', config: { collection: { dialect: 'cel', source: 'items' }, flowName: 'one', itemObject: 'doc_main' } }, + { id: 'bend', type: 'end', label: 'End' }, + ], + edges: [{ id: 'b1', source: 'bstart', target: 'each' }, { id: 'b2', source: 'each', target: 'bend' }], +}; + +async function packageObjects(): Promise { + let manifest: any; + const ctx: any = { + getService: (name: string) => { + if (name === 'manifest') return { register: (m: any) => { manifest = m; } }; + throw new Error(`no service '${name}'`); + }, + logger: silent, + }; + await new ApprovalsServicePlugin().init(ctx); + return manifest.objects; +} + +describe('ADR-0162 D5 — an abandoned approval never writes a closed value on its status mirror', () => { + let engine: ObjectQL; + let automation: AutomationEngine; + let svc: ApprovalService; + let logger: ReturnType; + let seq = 0; + + beforeEach(async () => { + engine = new ObjectQL(); + engine.registerDriver(new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }), true); + await engine.init(); + const users = { name: 'sys_user', label: 'User', fields: { id: { name: 'id', label: 'Id', type: 'text' as const, primaryKey: true }, name: text('name'), email: text('email') } }; + for (const def of [users, ...OBJECTS, ...(await packageObjects())]) { + engine.registry.registerObject(def as any, 'approvals-test', 'approvals-test'); + } + await engine.syncSchemas(); + await installDefaultOrganization(engine); + for (const id of [SUBMITTER, 'u_mgr', 'u_exec', 'u_root']) { + await engine.insert('sys_user', { id, name: id, email: `${id}@example.test` }, { context: SYSTEM } as any); + } + logger = recordingLogger(); + svc = new ApprovalService({ engine: engine as any, logger }); + automation = new AutomationEngine(silent, new InMemorySuspendedRunStore()); + installBuiltinNodes(automation, { logger: silent, getService() { throw new Error('none'); } } as any); + registerApprovalNode(automation as any, svc, silent); + for (const f of [ONE, TWO, CHILD_FIRST_BODY, CHILD_FIRST, PARENT_FIRST_BODY, PARENT_FIRST, BATCH]) automation.registerFlow(f.name, f as any); + svc.attachAutomation(automation as any); + }); + + afterEach(async () => { + try { await engine?.destroy(); } catch { /* noop */ } + }); + + const read = async (object: string, id: string) => + ((await engine.find(object, { where: { id }, context: SYSTEM } satisfies EngineQueryOptions)) as any[])[0]; + const statusOf = async (object: string, id: string) => (await read(object, id))?.approval_status ?? null; + const requestsOn = async (id: string): Promise => + engine.find('sys_approval_request', { where: { record_id: id }, context: SYSTEM } satisfies EngineQueryOptions) as any; + const pendingOn = async (id: string): Promise => { + const rows = (await requestsOn(id)).filter((r) => r.status === 'pending'); + expect(rows, `one pending request on ${id}`).toHaveLength(1); + return rows[0]; + }; + /** Another writer: a system write of the record's status while its request is pending. */ + const writeAsSystem = (object: string, id: string, value: unknown) => + engine.update(object, { id, approval_status: value }, { context: SYSTEM } as any); + /** + * Seed a record holding `atSubmit` and start `flow` on it. `snapshot` is the + * trigger record the flow starts from (the request's value at submit); + * by default the record as seeded. + */ + async function submit(object: string, opts: { atSubmit?: unknown; flow?: string; snapshot?: Record } = {}) { + const id = `${object}_${++seq}`; + const seedRow: Record = { id, name: id, organization_id: ORG }; + if (opts.atSubmit !== undefined) seedRow.approval_status = opts.atSubmit; + await engine.insert(object, seedRow, { context: SYSTEM } as any); + const record = opts.snapshot ? { id, name: id, organization_id: ORG, ...opts.snapshot } : await read(object, id); + const run = await automation.execute(opts.flow ?? 'one', { object, record, userId: SUBMITTER } as any); + expect(run.status, JSON.stringify(run)).toBe('paused'); + return { id, request: await pendingOn(id) }; + } + const approve = async (request: any, decider: string) => svc.decide(request.id, { decision: 'approve', actorId: decider } as any, asUser(decider)); + + type Writer = 'submitter recall' | 'recall in the revise window' | 'administrator override' | 'system override' | 'dead-run sweep'; + const WRITERS: Writer[] = ['submitter recall', 'recall in the revise window', 'administrator override', 'system override', 'dead-run sweep']; + /** + * Abandon `request` by `writer`; the revise-window arm sends it back first. + * `before` runs just ahead of the abandoning call (after the send-back). + */ + async function abandon(request: any, writer: Writer = 'submitter recall', before?: () => Promise): Promise { + if (writer === 'recall in the revise window') { + await svc.sendBack(request.id, { actorId: 'u_mgr' } as any, asUser('u_mgr')); + } + await before?.(); + switch (writer) { + case 'submitter recall': + await svc.recall(request.id, { actorId: SUBMITTER } as any, asUser(SUBMITTER)); + break; + case 'recall in the revise window': + await svc.recall(request.id, { actorId: SUBMITTER } as any, asUser(SUBMITTER)); + break; + case 'administrator override': + await svc.recall(request.id, { actorId: 'u_root' } as any, ADMIN); + break; + case 'system override': + await svc.recall(request.id, { actorId: 'ops_bot' } as any, SYSTEM); + break; + case 'dead-run sweep': { + const dead = String(request.flow_run_id); + svc.attachAutomation({ getRun: async (runId: string) => ({ status: runId === dead ? 'failed' : 'paused' }) } as any); + try { await svc.releaseDeadRunRequests(); } finally { svc.attachAutomation(automation as any); } + break; + } + } + const after = (await requestsOn(request.record_id)).find((r) => r.id === request.id); + expect(after?.status, `${writer} abandoned the request`).toBe('recalled'); + } + const lines = (level: string, text: string) => logger.lines.filter((l: any) => l.level === level && l.msg.includes(text)); + + describe('across the writers that abandon a request (N20)', () => { + it.each(WRITERS)('%s: a closed value at submit is passed over for the default, and the pass is logged', async (writer) => { + const { id, request } = await submit('doc_main', { atSubmit: 'approved' }); + expect(await statusOf('doc_main', id)).toBe('pending'); + await abandon(request, writer); + expect(await statusOf('doc_main', id)).toBe('draft'); + expect(lines('info', 'passed over')).toHaveLength(1); + }); + + it.each(WRITERS)('%s: a declared `recalled` the object closes on is withheld and logged; the field takes its value at submit', async (writer) => { + const { id, request } = await submit('doc_closed_recalled', { atSubmit: 'rejected' }); + await abandon(request, writer); + expect(await statusOf('doc_closed_recalled', id)).toBe('rejected'); + expect(lines('warn', "did not write 'recalled'")).toHaveLength(1); + }); + + it.each(WRITERS)('%s: a closed value the approval did not write is left alone, and that is logged', async (writer) => { + const { id, request } = await submit('doc_paid', { atSubmit: 'draft' }); + await abandon(request, writer, () => writeAsSystem('doc_paid', id, 'paid')); + expect(await statusOf('doc_paid', id)).toBe('paid'); + expect(lines('info', 'mirror writes nothing')).toHaveLength(1); + }); + + it.each(WRITERS)('%s CONTROL: on an object that closes on no value of the field, the value at submit is put back as before', async (writer) => { + const { id, request } = await submit('doc_control', { atSubmit: 'approved' }); + await abandon(request, writer); + expect(await statusOf('doc_control', id)).toBe('approved'); + expect(lines('info', 'passed over')).toEqual([]); + }); + }); + + describe('`recalled`', () => { + it('declared as an open value: written', async () => { + const { id, request } = await submit('doc_open_recalled', { atSubmit: 'approved' }); + await abandon(request); + expect(await statusOf('doc_open_recalled', id)).toBe('recalled'); + expect(lines('warn', "did not write 'recalled'")).toEqual([]); + }); + + it('declared as a closed value: withheld, and a closed value at submit passed over for the default', async () => { + const { id, request } = await submit('doc_closed_recalled', { atSubmit: 'approved' }); + await abandon(request); + expect(await statusOf('doc_closed_recalled', id)).toBe('draft'); + }); + + it('not declared: the field goes down the order (the value at submit)', async () => { + const { id, request } = await submit('doc_main', { atSubmit: 'rejected' }); + await abandon(request); + expect(await statusOf('doc_main', id)).toBe('rejected'); + }); + }); + + describe('the value at submit', () => { + it('open: put back', async () => { + const { id, request } = await submit('doc_main', { atSubmit: 'draft' }); + await abandon(request); + expect(await statusOf('doc_main', id)).toBe('draft'); + }); + + it('closed: passed over for the default', async () => { + const { id, request } = await submit('doc_main', { atSubmit: 'approved' }); + await abandon(request); + expect(await statusOf('doc_main', id)).toBe('draft'); + }); + + it('empty on a required field: passed over for the default', async () => { + const { id, request } = await submit('doc_required', { snapshot: { approval_status: null } }); + await abandon(request); + expect(await statusOf('doc_required', id)).toBe('draft'); + }); + + it('empty on a field that is not required: still put back', async () => { + const { id, request } = await submit('doc_main', { snapshot: { approval_status: null } }); + await abandon(request); + expect(await statusOf('doc_main', id)).toBeNull(); + }); + + it('not carried by the request: the default', async () => { + const { id, request } = await submit('doc_main', { atSubmit: 'rejected', snapshot: {} }); + await abandon(request); + expect(await statusOf('doc_main', id)).toBe('draft'); + }); + }); + + describe('the default', () => { + it('usable: written', async () => { + const { id, request } = await submit('doc_main', { atSubmit: 'approved' }); + await abandon(request); + expect(await statusOf('doc_main', id)).toBe('draft'); + }); + + it('closed: passed over for empty, both passes logged', async () => { + const { id, request } = await submit('doc_default_closed', { atSubmit: 'approved' }); + await abandon(request); + expect(await statusOf('doc_default_closed', id)).toBeNull(); + const [pass] = lines('info', 'passed over'); + expect(pass?.meta?.passedOver).toEqual([{ from: 'submit', value: 'approved' }, { from: 'default', value: 'approved' }]); + }); + + it('absent: empty', async () => { + const { id, request } = await submit('doc_no_default', { atSubmit: 'approved' }); + await abandon(request); + expect(await statusOf('doc_no_default', id)).toBeNull(); + }); + }); + + describe('what the field holds when the request is abandoned', () => { + it("an open value, the request's own status, with a value at submit: the order", async () => { + const { id, request } = await submit('doc_main', { atSubmit: 'rejected' }); + expect(await statusOf('doc_main', id)).toBe('pending'); + await abandon(request); + expect(await statusOf('doc_main', id)).toBe('rejected'); + }); + + it('an open value another writer put there, without a value at submit: the order', async () => { + const { id, request } = await submit('doc_main', { atSubmit: 'rejected', snapshot: {} }); + await writeAsSystem('doc_main', id, 'returned'); + await abandon(request); + expect(await statusOf('doc_main', id)).toBe('draft'); + }); + + it('a closed status no request of the approval had: left alone', async () => { + const { id, request } = await submit('doc_main', { atSubmit: 'draft' }); + await writeAsSystem('doc_main', id, 'approved'); + await abandon(request); + expect(await statusOf('doc_main', id)).toBe('approved'); + }); + + it('a closed status a request of another approval on the record had: left alone', async () => { + const first = await submit('doc_main', { atSubmit: 'draft' }); + await approve(first.request, 'u_mgr'); + expect(await statusOf('doc_main', first.id)).toBe('approved'); + const run = await automation.execute('one', { object: 'doc_main', record: await read('doc_main', first.id), userId: SUBMITTER } as any); + expect(run.status).toBe('paused'); + const second = await pendingOn(first.id); + await writeAsSystem('doc_main', first.id, 'approved'); + await abandon(second); + expect(await statusOf('doc_main', first.id)).toBe('approved'); + }); + }); + + describe('an object that closes on the field only on values of its own', () => { + it('such a value at submit is not put back: the default', async () => { + const { id, request } = await submit('doc_own_values', { atSubmit: 'paid' }); + await abandon(request); + expect(await statusOf('doc_own_values', id)).toBe('draft'); + }); + + it('such a value the approval did not write is left alone', async () => { + const { id, request } = await submit('doc_own_values', { atSubmit: 'draft' }); + await writeAsSystem('doc_own_values', id, 'paid'); + await abandon(request); + expect(await statusOf('doc_own_values', id)).toBe('paid'); + }); + + it('an approval status, open there, goes down the order as before: the value at submit', async () => { + const { id, request } = await submit('doc_own_values', { atSubmit: 'approved' }); + await abandon(request); + expect(await statusOf('doc_own_values', id)).toBe('approved'); + }); + }); + + // The field declares no `pending`, so a later step's opening writes nothing + // and the earlier step's `approved` stays on the field: the shape of an + // approval its opening check did not judge (ADR-0162 Execution item 7). + describe("an earlier step's outcome on the field: the approval wrote it, so the field goes down the order", () => { + it('that step in the same run', async () => { + const { id, request } = await submit('doc_no_pending', { atSubmit: 'approved', flow: 'two' }); + await approve(request, 'u_mgr'); + expect(await statusOf('doc_no_pending', id)).toBe('approved'); + const second = await pendingOn(id); + await abandon(second); + expect(await statusOf('doc_no_pending', id)).toBe('draft'); + }); + + it('that step in a child run', async () => { + const { id, request } = await submit('doc_no_pending', { atSubmit: 'draft', flow: 'child_first' }); + await approve(request, 'u_mgr'); + expect(await statusOf('doc_no_pending', id)).toBe('approved'); + const second = await pendingOn(id); + expect(second.root_run_id).toBe(request.root_run_id); + await abandon(second); + expect(await statusOf('doc_no_pending', id)).toBe('draft'); + }); + + it('that step in the parent of the run whose request is abandoned', async () => { + const { id, request } = await submit('doc_no_pending', { atSubmit: 'draft', flow: 'parent_first' }); + await approve(request, 'u_mgr'); + expect(await statusOf('doc_no_pending', id)).toBe('approved'); + const second = await pendingOn(id); + expect(second.flow_run_id).not.toBe(request.flow_run_id); + expect(second.root_run_id).toBe(request.root_run_id); + await abandon(second); + expect(await statusOf('doc_no_pending', id)).toBe('draft'); + }); + }); + + it("a `map` in which only another item's request had the value the field holds: left alone", async () => { + const items = ['map_a', 'map_b'].map((id) => ({ id, name: id, organization_id: ORG, approval_status: 'draft' })); + for (const item of items) await engine.insert('doc_main', item, { context: SYSTEM } as any); + const run = await automation.execute('batch', { params: { items }, userId: SUBMITTER } as any); + expect(run.status).toBe('paused'); + await approve(await pendingOn('map_a'), 'u_mgr'); + expect(await statusOf('doc_main', 'map_a')).toBe('approved'); + const b = await pendingOn('map_b'); + expect(b.root_run_id).toBe((await requestsOn('map_a'))[0].root_run_id); + await writeAsSystem('doc_main', 'map_b', 'approved'); + await abandon(b); + expect(await statusOf('doc_main', 'map_b')).toBe('approved'); + }); + + describe('where the mirror cannot tell, it goes down the order', () => { + it('the abandoned request records no root run (seat ruling 7210700837)', async () => { + const { id, request } = await submit('doc_main', { atSubmit: 'draft' }); + await engine.update('sys_approval_request', { id: request.id, root_run_id: null, root_run_started_at: null }, { context: SYSTEM } as any); + await writeAsSystem('doc_main', id, 'approved'); + await abandon({ ...request, root_run_id: null }); + expect(await statusOf('doc_main', id)).toBe('draft'); + }); + + it('a request on the record that records no root run, opened since the approval started, had the value', async () => { + const { id, request } = await submit('doc_main', { atSubmit: 'draft' }); + await engine.insert('sys_approval_request', { + id: 'legacy_after', process_name: 'one', object_name: 'doc_main', record_id: id, status: 'approved', + organization_id: ORG, created_at: new Date(Date.now() + 1000).toISOString(), + }, { context: SYSTEM } as any); + await writeAsSystem('doc_main', id, 'approved'); + await abandon(request); + expect(await statusOf('doc_main', id)).toBe('draft'); + }); + + it('CONTROL — the same request opened before the approval started does not count: left alone', async () => { + const { id, request } = await submit('doc_main', { atSubmit: 'draft' }); + await engine.insert('sys_approval_request', { + id: 'legacy_before', process_name: 'one', object_name: 'doc_main', record_id: id, status: 'approved', + organization_id: ORG, created_at: '2020-01-01T00:00:00.000Z', + }, { context: SYSTEM } as any); + await writeAsSystem('doc_main', id, 'approved'); + await abandon(request); + expect(await statusOf('doc_main', id)).toBe('approved'); + }); + }); + + describe('N17 — an empty put-back on each kind of required field, with no default: the value the field keeps', () => { + it('a required field that callers may edit: the validator refuses the empty write, which is reported, and the field keeps `pending`', async () => { + const { id, request } = await submit('doc_req_editable', { atSubmit: 'approved' }); + await abandon(request); + expect(await statusOf('doc_req_editable', id)).toBe('pending'); + expect(lines('error', 'was NOT written')).toHaveLength(1); + }); + + it('a `readonly` required field: the empty write lands', async () => { + const { id, request } = await submit('doc_req_readonly', { atSubmit: 'approved' }); + await abandon(request); + expect(await statusOf('doc_req_readonly', id)).toBeNull(); + }); + + it('a `system` required column: the empty write lands', async () => { + const { id, request } = await submit('doc_req_system', { atSubmit: 'approved' }); + await abandon(request); + expect(await statusOf('doc_req_system', id)).toBeNull(); + }); + + it('a field required only when shown, and shown: the empty write is refused, and the field keeps `pending`', async () => { + const { id, request } = await submit('doc_req_when_shown', { atSubmit: 'approved' }); + await abandon(request); + expect(await statusOf('doc_req_when_shown', id)).toBe('pending'); + }); + + it('empty at submit on a required field with no default: empty is all that is left, and the refusal is the same', async () => { + const { id, request } = await submit('doc_req_editable', { snapshot: { approval_status: null }, atSubmit: 'draft' }); + await abandon(request); + expect(await statusOf('doc_req_editable', id)).toBe('pending'); + }); + }); +}); From 3e7932cac52d665c9980adc817d83315afc29db3 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 05:09:56 +0000 Subject: [PATCH 3/4] chore(changeset): an abandoned approval never writes a closed value on its status mirror Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5phEgfPTCgvPqh4ER2 --- .changeset/37766-abandoned-mirror.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 .changeset/37766-abandoned-mirror.md diff --git a/.changeset/37766-abandoned-mirror.md b/.changeset/37766-abandoned-mirror.md new file mode 100644 index 00000000000..5836107f822 --- /dev/null +++ b/.changeset/37766-abandoned-mirror.md @@ -0,0 +1,16 @@ +--- +'@objectstack/plugin-approvals': patch +--- + +fix(approvals): an abandoned approval never writes a closed value on its status mirror (ADR-0162 D5, Execution item 7) + +Clause-②: no +Metadata-protocol: none + +A request is abandoned by its submitter's recall (while it is pending, or in the revise window after a send-back), by the override arm of a recall (an administrator, or a system context), and by the sweep that releases a record held by a dead run. Each puts a value back on the field the approval mirrors its status onto. Where the object's `closedStates` lists any value for that field (ADR-0162 D1), the mirror now chooses that value so that it never closes the document again: + +- **`recalled`** is written where the field declares it and the object does not close on it, as before. A declared `recalled` the object closes on is withheld, and a `warn` line says so: listing `recalled` among the closed values closes nothing through the mirror. +- **Otherwise the order**: the value held at submit, the field's declared default, empty. A closed value is passed over at each step, and on a required field an empty value at submit is passed over for the default. A pass is logged at `info`. +- **A closed value the approval did not write is left alone.** Where the field holds a closed value, the mirror asks the request table once, by the request's root run and record, whether a request of the same approval on the same record had that value as its status. Where none did, it writes nothing and logs it at `info`. A request of the approval on another record (another item of a `map`) does not count. Where it cannot tell (the request records no root run, or a request on the record that records none was opened since the approval's run started), it goes down the order. + +Every other write of the mirror is unchanged, and so is every write on an object that closes on no value of the mirror field. From a0ddf0cbedff9632b9c0ff07a9282a347b3e69e6 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 05:13:38 +0000 Subject: [PATCH 4/4] test(approvals): pin the hidden required-when-shown arm and a value no request can hold Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5phEgfPTCgvPqh4ER2 --- ...abandoned-closed-value.integration.test.ts | 20 ++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/packages/plugins/plugin-approvals/src/status-mirror-abandoned-closed-value.integration.test.ts b/packages/plugins/plugin-approvals/src/status-mirror-abandoned-closed-value.integration.test.ts index ceec81266e9..8179524343b 100644 --- a/packages/plugins/plugin-approvals/src/status-mirror-abandoned-closed-value.integration.test.ts +++ b/packages/plugins/plugin-approvals/src/status-mirror-abandoned-closed-value.integration.test.ts @@ -212,12 +212,12 @@ describe('ADR-0162 D5 — an abandoned approval never writes a closed value on i * trigger record the flow starts from (the request's value at submit); * by default the record as seeded. */ - async function submit(object: string, opts: { atSubmit?: unknown; flow?: string; snapshot?: Record } = {}) { + async function submit(object: string, opts: { atSubmit?: unknown; flow?: string; snapshot?: Record; name?: string | null } = {}) { const id = `${object}_${++seq}`; - const seedRow: Record = { id, name: id, organization_id: ORG }; + const seedRow: Record = { id, name: opts.name === undefined ? id : opts.name, organization_id: ORG }; if (opts.atSubmit !== undefined) seedRow.approval_status = opts.atSubmit; await engine.insert(object, seedRow, { context: SYSTEM } as any); - const record = opts.snapshot ? { id, name: id, organization_id: ORG, ...opts.snapshot } : await read(object, id); + const record = opts.snapshot ? { id, name: seedRow.name, organization_id: ORG, ...opts.snapshot } : await read(object, id); const run = await automation.execute(opts.flow ?? 'one', { object, record, userId: SUBMITTER } as any); expect(run.status, JSON.stringify(run)).toBe('paused'); return { id, request: await pendingOn(id) }; @@ -491,6 +491,14 @@ describe('ADR-0162 D5 — an abandoned approval never writes a closed value on i expect(await statusOf('doc_main', id)).toBe('draft'); }); + it('a closed value that is no status of a request, on a request with no root run: left alone, since no request can have held it', async () => { + const { id, request } = await submit('doc_paid', { atSubmit: 'draft' }); + await engine.update('sys_approval_request', { id: request.id, root_run_id: null, root_run_started_at: null }, { context: SYSTEM } as any); + await writeAsSystem('doc_paid', id, 'paid'); + await abandon({ ...request, root_run_id: null }); + expect(await statusOf('doc_paid', id)).toBe('paid'); + }); + it('CONTROL — the same request opened before the approval started does not count: left alone', async () => { const { id, request } = await submit('doc_main', { atSubmit: 'draft' }); await engine.insert('sys_approval_request', { @@ -529,6 +537,12 @@ describe('ADR-0162 D5 — an abandoned approval never writes a closed value on i expect(await statusOf('doc_req_when_shown', id)).toBe('pending'); }); + it('a field required only when shown, and hidden: the requirement is waived and the empty write lands', async () => { + const { id, request } = await submit('doc_req_when_shown', { atSubmit: 'approved', name: null }); + await abandon(request); + expect(await statusOf('doc_req_when_shown', id)).toBeNull(); + }); + it('empty at submit on a required field with no default: empty is all that is left, and the refusal is the same', async () => { const { id, request } = await submit('doc_req_editable', { snapshot: { approval_status: null }, atSubmit: 'draft' }); await abandon(request);