From 11ee69ac1a62eea5c33ef67a1d2ebe2bd9ece9c5 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 23:55:32 +0000 Subject: [PATCH 01/32] feat(spec): closedStates key on the object with its authoring refusals (ADR-0162 D1) Claude-Session: https://claude.ai/code/session_01L6bhgTCFhayR5cBZXM7XPP Co-authored-by: Claude --- packages/spec/src/data/closed-states.test.ts | 234 +++++++++++++++++++ packages/spec/src/data/closed-states.ts | 145 ++++++++++++ packages/spec/src/data/object.zod.ts | 44 ++++ 3 files changed, 423 insertions(+) create mode 100644 packages/spec/src/data/closed-states.test.ts create mode 100644 packages/spec/src/data/closed-states.ts diff --git a/packages/spec/src/data/closed-states.test.ts b/packages/spec/src/data/closed-states.test.ts new file mode 100644 index 00000000000..b72ff7d2f5c --- /dev/null +++ b/packages/spec/src/data/closed-states.test.ts @@ -0,0 +1,234 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { describe, it, expect } from 'vitest'; +import { ObjectSchema } from './object.zod'; +import { getMetadataTypeSchema } from '../kernel/metadata-type-schemas'; +import { ObjectStackDefinitionSchema } from '../stack.zod'; + +// --------------------------------------------------------------------------- +// [ADR-0162 D1] `closedStates` — the key and its authoring refusals. +// +// The key maps a stored, single-value `select` field of the object to a +// non-empty list of that field's own option values, each listed once. Every +// declaration that breaks one of those rules is ONE located `custom` issue at +// parse, at the save door (the `object` metadata schema) and at the stack +// door; so is the declaration a removed or retyped field, or a removed option, +// leaves behind. The pins bear weight both ways: the ADR's own two-field +// example parses clean and keeps its value. +// --------------------------------------------------------------------------- + +const STATUS_OPTIONS = [ + { label: 'Draft', value: 'draft' }, + { label: 'Paid', value: 'paid' }, + { label: 'Void', value: 'void' }, +]; +const APPROVAL_OPTIONS = [ + { label: 'Pending', value: 'pending' }, + { label: 'Approved', value: 'approved' }, + { label: 'Rejected', value: 'rejected' }, +]; + +const invoice = (closedStates: unknown, fields: Record = {}) => ({ + name: 'invoice', + fields: { + name: { type: 'text', label: 'Number' }, + status: { type: 'select', label: 'Status', options: STATUS_OPTIONS }, + approval_status: { type: 'select', label: 'Approval', options: APPROVAL_OPTIONS }, + ...fields, + }, + ...(closedStates === undefined ? {} : { closedStates }), +}); + +const ADR_EXAMPLE = { status: ['paid', 'void'], approval_status: ['approved'] }; + +/** The one issue a refused declaration carries: its code and path, and the message. */ +function refusedAt(input: unknown, path: (string | number)[]): string { + const parsed = ObjectSchema.safeParse(input); + expect(parsed.success, 'the declaration must NOT parse clean').toBe(false); + if (parsed.success) throw new Error('unreachable'); + expect(parsed.error.issues.map((i) => [i.code, i.path])).toEqual([['custom', path]]); + return parsed.error.issues[0]!.message; +} + +describe('[ADR-0162 D1] `closedStates` — accepted shapes', () => { + it('accepts the ADR example: two fields, each with its own closing values, and keeps it as written', () => { + const parsed = ObjectSchema.safeParse(invoice(ADR_EXAMPLE)); + expect(parsed.success, parsed.success ? '' : JSON.stringify(parsed.error.issues)).toBe(true); + if (!parsed.success) return; + expect(parsed.data.closedStates).toEqual(ADR_EXAMPLE); + }); + + it('is optional: an object without the key parses, and no parsed object grows one (control)', () => { + const parsed = ObjectSchema.safeParse(invoice(undefined)); + expect(parsed.success).toBe(true); + if (!parsed.success) return; + expect('closedStates' in parsed.data).toBe(false); + }); + + it('needs no `state_machine` rule on the field, and a `state_machine` rule does not need the key', () => { + expect(ObjectSchema.safeParse(invoice({ status: ['paid'] })).success).toBe(true); + const machine = { + ...invoice(undefined), + validations: [{ + type: 'state_machine', + name: 'status_flow', + message: 'Illegal status move', + field: 'status', + transitions: { draft: ['paid', 'void'], paid: [], void: [] }, + }], + }; + const parsed = ObjectSchema.safeParse(machine); + expect(parsed.success, parsed.success ? '' : JSON.stringify(parsed.error.issues)).toBe(true); + if (!parsed.success) return; + expect('closedStates' in parsed.data).toBe(false); + }); + + it('`create()` keeps the declaration', () => { + const created = ObjectSchema.create(invoice(ADR_EXAMPLE) as never) as { closedStates?: unknown }; + expect(created.closedStates).toEqual(ADR_EXAMPLE); + }); +}); + +describe('[ADR-0162 D1] `closedStates` — refused where the object is authored', () => { + it('refuses a key that names no field of the object', () => { + const message = refusedAt(invoice({ state: ['paid'] }), ['closedStates', 'state']); + expect(message).toContain('declares no field `state`'); + }); + + it('refuses a field that is not a `select`', () => { + const message = refusedAt(invoice({ name: ['x'] }), ['closedStates', 'name']); + expect(message).toContain('is a `text` field, not a single-value `select`'); + }); + + it('refuses a `multiple: true` select', () => { + const tags = { type: 'select', label: 'Tags', multiple: true, options: STATUS_OPTIONS }; + const message = refusedAt(invoice({ tags: ['paid'] }, { tags }), ['closedStates', 'tags']); + expect(message).toContain('a `multiple: true` `select`'); + }); + + it('refuses a `radio`, an option type that is not a `select` (the key names a select)', () => { + const stage = { type: 'radio', label: 'Stage', options: STATUS_OPTIONS }; + refusedAt(invoice({ stage: ['paid'] }, { stage }), ['closedStates', 'stage']); + }); + + it('refuses a `picklist`-backed select: its options are not declared on this object', () => { + const kind = { type: 'select', label: 'Kind', picklist: 'invoice_kind' }; + const message = refusedAt(invoice({ kind: ['credit'] }, { kind }), ['closedStates', 'kind']); + expect(message).toContain("picklist: 'invoice_kind'"); + }); + + it('refuses an empty list', () => { + const message = refusedAt(invoice({ status: [] }), ['closedStates', 'status']); + expect(message).toContain('empty list'); + }); + + it('refuses a value that is not one of the field\'s options, located at the value', () => { + const message = refusedAt(invoice({ status: ['paid', 'closed'] }), ['closedStates', 'status', 1]); + expect(message).toContain("'closed', which is not an option of `status`"); + }); + + it('refuses a value the list repeats, located at the repeat', () => { + const message = refusedAt(invoice({ status: ['paid', 'void', 'paid'] }), ['closedStates', 'status', 2]); + expect(message).toContain("lists the value 'paid' twice"); + }); + + it('refuses a key that is not a field name, and a list of non-strings, by the key\'s own shape', () => { + expect(ObjectSchema.safeParse(invoice({ Status: ['paid'] })).success).toBe(false); + expect(ObjectSchema.safeParse(invoice({ status: [1] })).success).toBe(false); + expect(ObjectSchema.safeParse(invoice({ status: 'paid' })).success).toBe(false); + }); + + it('judges each field on its own: one issue per offending entry, the sound entry untouched', () => { + const parsed = ObjectSchema.safeParse(invoice({ status: ['paid'], approval_status: ['done'], state: ['x'] })); + expect(parsed.success).toBe(false); + if (parsed.success) return; + expect(parsed.error.issues.map((i) => i.path)).toEqual([ + ['closedStates', 'approval_status', 0], + ['closedStates', 'state'], + ]); + }); +}); + +describe('[ADR-0162 D1] `closedStates` — a field or option a declaration still names is not removed or retyped', () => { + // The object's next version is judged whole, so each edit below leaves a + // declaration that names what the edit took away, and the edit is refused. + it('refuses removing the field', () => { + const before = invoice(ADR_EXAMPLE); + expect(ObjectSchema.safeParse(before).success).toBe(true); + const { approval_status: _removed, ...rest } = before.fields; + const message = refusedAt({ ...before, fields: rest }, ['closedStates', 'approval_status']); + expect(message).toContain('cannot be removed or renamed while the declaration names it'); + }); + + it('refuses retyping the field', () => { + const message = refusedAt( + invoice(ADR_EXAMPLE, { approval_status: { type: 'text', label: 'Approval' } }), + ['closedStates', 'approval_status'], + ); + expect(message).toContain('cannot be retyped while the declaration names it'); + }); + + it('refuses making the field multi-value', () => { + refusedAt( + invoice(ADR_EXAMPLE, { status: { type: 'select', label: 'Status', multiple: true, options: STATUS_OPTIONS } }), + ['closedStates', 'status'], + ); + }); + + it('refuses removing an option the declaration lists', () => { + const message = refusedAt( + invoice(ADR_EXAMPLE, { status: { type: 'select', label: 'Status', options: STATUS_OPTIONS.slice(0, 2) } }), + ['closedStates', 'status', 1], + ); + expect(message).toContain('cannot be removed while the declaration lists it'); + }); + + it('CONTROL: removing an option the declaration does not list lands', () => { + const parsed = ObjectSchema.safeParse( + invoice(ADR_EXAMPLE, { status: { type: 'select', label: 'Status', options: STATUS_OPTIONS.slice(1) } }), + ); + expect(parsed.success, parsed.success ? '' : JSON.stringify(parsed.error.issues)).toBe(true); + }); +}); + +describe('[ADR-0162 D1] `closedStates` — every door refuses at the same path', () => { + it('the save and publish door (the `object` metadata schema)', () => { + const schema = getMetadataTypeSchema('object'); + expect(schema).toBeDefined(); + const bad = schema!.safeParse(invoice({ status: ['closed'] })); + expect(bad.success).toBe(false); + if (bad.success) return; + expect(bad.error.issues.map((i) => [i.code, i.path])).toEqual([['custom', ['closedStates', 'status', 0]]]); + expect(schema!.safeParse(invoice(ADR_EXAMPLE)).success).toBe(true); + }); + + it('the stack door, inside `objects`', () => { + const manifest = { + id: 'com.example.closedstates', + name: 'closed-states-test', + version: '1.0.0', + type: 'app' as const, + namespace: 'crm', + }; + const bad = ObjectStackDefinitionSchema.safeParse({ manifest, objects: [invoice({ state: ['paid'] })] }); + expect(bad.success).toBe(false); + if (bad.success) return; + expect(bad.error.issues.map((i) => [i.code, i.path])).toEqual([['custom', ['objects', 0, 'closedStates', 'state']]]); + expect(ObjectStackDefinitionSchema.safeParse({ manifest, objects: [invoice(ADR_EXAMPLE)] }).success).toBe(true); + }); +}); + +describe('[ADR-0162 D1] `closedStates` — a line object', () => { + it('a `master_detail` line needs no declaration, and may declare its own', () => { + const line = (closedStates?: unknown) => ({ + name: 'invoice_line', + fields: { + invoice: { type: 'master_detail', label: 'Invoice', reference: 'invoice' }, + line_status: { type: 'select', label: 'Line status', options: [{ label: 'Open', value: 'open' }, { label: 'Shipped', value: 'shipped' }] }, + }, + ...(closedStates === undefined ? {} : { closedStates }), + }); + expect(ObjectSchema.safeParse(line()).success).toBe(true); + expect(ObjectSchema.safeParse(line({ line_status: ['shipped'] })).success).toBe(true); + }); +}); diff --git a/packages/spec/src/data/closed-states.ts b/packages/spec/src/data/closed-states.ts new file mode 100644 index 00000000000..2cb1f6a8cdb --- /dev/null +++ b/packages/spec/src/data/closed-states.ts @@ -0,0 +1,145 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { z } from 'zod'; + +// [ADR-0162 D1] The authoring half of `ObjectSchema.closedStates`: the +// declaration is judged against the object's own field map, at parse, so every +// door — `defineStack`, a raw `.parse()`, the metadata save and publish door — +// refuses a declaration that cannot be evaluated. Declared in its own module, +// outside the `data` barrel, so the function does not join the package's +// published exports (the `stage-field-kinds.ts` precedent). + +/** One closing field's declaration as the author wrote it: field name → its closing values. */ +type ClosedStatesInput = Record; + +/** The example every refusal ends on: the shape ADR-0162 D1 gives. */ +const CLOSED_STATES_EXAMPLE = + "e.g. `closedStates: { status: ['paid', 'void'], approval_status: ['approved'] }`"; + +/** + * [ADR-0162 D1] `closedStates` names, for each field of THIS object, the list + * of that field's values that close a record. A record is closed when any + * listed field holds one of its listed values; the engine reads it off the + * stored row, so a declaration it cannot evaluate would parse and close + * nothing (ADR-0049: declared = enforced). Refused, one located issue each, + * judged against the AUTHORED field map: + * + * - at `['closedStates', ]`: a key that names no field of the object — + * also the shape a field REMOVED under a standing declaration leaves; + * - at `['closedStates', ]`: a field that is not a single-value + * `select` — another type, a `multiple: true` select (its row value is a + * list, so "holds one of the values" has no single reading), or a select + * RETYPED under a standing declaration; + * - at `['closedStates', ]`: a select that declares no inline + * `options` (a `picklist`-backed select's values are not declared on this + * object, so the listed values cannot be checked here — this is the one + * door every save passes, so it is refused rather than let through + * unjudged, as `stageField` is); + * - at `['closedStates', ]`: an empty list — it closes nothing; + * - at `['closedStates', , ]`: a value that is not one of the + * field's option values — also the shape an option REMOVED under a standing + * declaration leaves — and a value the list repeats. + * + * Not judged here, on purpose: the key's own shape (a map of string lists), + * which the schema refuses before this runs; a `state_machine` rule on the + * field, in either direction (D1: the rule says which moves are legal, the key + * says when the record stops accepting a caller's writes); a line object, + * which declares nothing to be closed with its master and may declare its own. + */ +export function refuseDishonestClosedStates( + ownName: unknown, + closedStates: unknown, + fields: unknown, + ctx: z.RefinementCtx, +): void { + if (closedStates === null || typeof closedStates !== 'object' || Array.isArray(closedStates)) return; + const objectName = typeof ownName === 'string' ? ownName : ''; + const fieldMap = fields !== null && typeof fields === 'object' ? (fields as Record) : {}; + const prescription = + '`closedStates` maps a stored, single-value `select` field of this object to a non-empty list of ' + + `that field's own option values, each listed once (${CLOSED_STATES_EXAMPLE}).`; + + for (const [fieldName, values] of Object.entries(closedStates as ClosedStatesInput)) { + if (!Array.isArray(values)) continue; + const at = ['closedStates', fieldName]; + const head = `Object \`${objectName}\` declares \`closedStates.${fieldName}\``; + if (!Object.prototype.hasOwnProperty.call(fieldMap, fieldName)) { + ctx.addIssue({ + code: 'custom', + path: at, + message: + `${head}, but the object declares no field \`${fieldName}\`. A field a closed-state declaration names ` + + 'cannot be removed or renamed while the declaration names it: remove the entry from `closedStates` ' + + `first, or name a field the object declares. ${prescription}`, + }); + continue; + } + const def = fieldMap[fieldName] as + | { type?: unknown; multiple?: unknown; options?: unknown; picklist?: unknown } + | null + | undefined; + const type = def !== null && typeof def === 'object' ? def.type : undefined; + if (type !== 'select' || def?.multiple === true) { + const what = type === 'select' ? 'a `multiple: true` `select`' : `a \`${String(type)}\` field`; + ctx.addIssue({ + code: 'custom', + path: at, + message: + `${head}, but \`${fieldName}\` is ${what}, not a single-value \`select\`: a record is closed when the ` + + 'field holds one of the listed values, so the field must hold exactly one stored value. A field a ' + + 'closed-state declaration names cannot be retyped while the declaration names it. ' + + prescription, + }); + continue; + } + if (!Array.isArray(def?.options)) { + const source = typeof def?.picklist === 'string' ? `takes its options from \`picklist: '${def.picklist}'\`` : 'declares no inline `options`'; + ctx.addIssue({ + code: 'custom', + path: at, + message: + `${head}, but \`${fieldName}\` ${source}, so whether each listed value is one of its options cannot ` + + `be checked here. Declare the field's options inline on \`${fieldName}\`. ${prescription}`, + }); + continue; + } + if (values.length === 0) { + ctx.addIssue({ + code: 'custom', + path: at, + message: + `${head} with an empty list, which closes no record. List at least one value of \`${fieldName}\`, ` + + `or remove the entry. ${prescription}`, + }); + continue; + } + const declared = new Set( + (def.options as Array<{ value?: unknown } | null>) + .map((o) => (o !== null && typeof o === 'object' ? o.value : undefined)) + .filter((v): v is string => typeof v === 'string'), + ); + const seen = new Set(); + values.forEach((value: unknown, index: number) => { + if (typeof value !== 'string') return; + const path = [...at, index]; + if (seen.has(value)) { + ctx.addIssue({ + code: 'custom', + path, + message: `${head} lists the value '${value}' twice. List each closing value once.`, + }); + return; + } + seen.add(value); + if (declared.has(value)) return; + ctx.addIssue({ + code: 'custom', + path, + message: + `${head} lists '${value}', which is not an option of \`${fieldName}\` (its options: ` + + `${[...declared].map((v) => `'${v}'`).join(', ') || 'none'}). An option a closed-state declaration ` + + `lists cannot be removed while the declaration lists it. ${prescription}`, + }); + }); + } +} diff --git a/packages/spec/src/data/object.zod.ts b/packages/spec/src/data/object.zod.ts index 2b2ab939660..c87c4515c72 100644 --- a/packages/spec/src/data/object.zod.ts +++ b/packages/spec/src/data/object.zod.ts @@ -31,6 +31,7 @@ import { RECORD_PAGE_BUILTIN_TABS, relatedListEntryHidden, relatedListEntryName, // [#23809] The stage-field option-kind rule, in its own module so the AI // blueprint object (`ai/solution-blueprint.zod.ts`) runs this same refinement. import { refuseStageFieldWithoutKinds } from './stage-field-kinds'; +import { refuseDishonestClosedStates } from './closed-states'; // [#32763] The `icon` leaf, shared with the AI blueprint object. import { OBJECT_COLOR_SCHEMA, OBJECT_ICON_SCHEMA } from './object-icon'; // [#36366] The action arrangement per scope (pinned, more), shared with the object extension. @@ -4792,6 +4793,45 @@ const ObjectSchemaBase = strictObject( */ uiReadonlyWhen: EvaluatedExpressionInputSchema.optional().describe("Predicate (CEL) — every field of an existing record is read-only BY HAND while TRUE: the console surfaces a field's own `uiReadonlyWhen` locks (the edit dialog, record-page inline edit and the stage path, the highlight-strip chip, grid inline edit and multi-row save, kanban column drag, calendar drag, the Gantt, the timesheet cell, the line-item grid) do not let a person edit the record, while REST, import, action and flow writes keep every field, judged by the object's validations. e.g. P`record.status in ['confirmed', 'done']` on an order moved by Confirm / Cancel actions. A default for every field: a field that declares `uiReadonly: true` or its own `uiReadonlyWhen` is judged by that instead, so a field whose own `uiReadonlyWhen` is P`false` stays editable inside a locked record; `uiReadonly: false` is not such a declaration and the field follows the object lock. A create is not judged. A predicate the console cannot evaluate locks every field that inherits it. Same scope as a field's `readonlyWhen`: the record's OWN columns. The engine never reads this key."), + /** + * [ADR-0162 D1] The states in which a record of this object is CLOSED: a map + * from a field of this object to the list of that field's values that close + * the record. A record is closed when ANY listed field holds one of its + * listed values, read off the stored row (D2): nothing is stored for it. + * Two fields are the ordinary case — an approval mirrors its outcome into + * one field, the business status lives in another: + * `{ status: ['paid', 'void'], approval_status: ['approved'] }`. + * + * In a closed state the record and its direct `master_detail` lines are + * closed to change for every caller that is not a system context (D3–D5): + * no update or delete of the record, no line created, updated, deleted or + * moved. The line object declares nothing to be closed with its master, and + * may declare its own `closedStates` for a line that closes on its own. + * + * Each key names a stored, single-value `select` field of this object with + * inline `options`; each listed value is one of them; a list is not empty + * and repeats nothing. A declaration that breaks one of those rules is + * refused at parse and publish, and so is removing or retyping a field, or + * removing an option, that a declaration still names + * (`refuseDishonestClosedStates`, `./closed-states.ts`). Optional: an object + * without the key behaves exactly as before. No tie to a `state_machine` + * rule in either direction. + */ + closedStates: refuseRecordProtoKey( + z.record(FieldNameKeySchema, z.array(z.string())), + 'closedStates', + ).optional().describe( + 'States in which a record is CLOSED: a map from a stored, single-value `select` field of this object to ' + + 'the list of that field\'s option values that close the record, e.g. { status: [\'paid\', \'void\'], ' + + 'approval_status: [\'approved\'] }. A record is closed when ANY listed field holds one of its listed ' + + 'values, read off the stored row. While closed, the record and its direct master_detail lines are ' + + 'closed to change for every caller that is not a system context: the record is not updated or ' + + 'deleted, and no line is created, updated, deleted or moved. The field must declare inline options; ' + + 'each listed value is one of them; a list is not empty and repeats nothing. A field or option a ' + + 'declaration names cannot be removed or retyped while it names it. A line object declares nothing to ' + + 'be closed with its master, and may declare its own. Independent of any state_machine rule on the field.', + ), + /** * Display & UI Hints (Data-Layer) */ @@ -5405,6 +5445,10 @@ const ObjectSchemaBase = strictObject( // lifecycle `kind` — the same door: only the object knows which field is // its stage. refuseStageFieldWithoutKinds(object.name, object.stageField, object.fields, ctx); + // [ADR-0162 D1] Each `closedStates` key names a single-value `select` of + // THIS object with inline options, and each listed value one of them — the + // same door: only the object holds the field map. See the helper's docblock. + refuseDishonestClosedStates(object.name, object.closedStates, object.fields, ctx); // [cloud#3652 ruling D3] Each `renamedFrom` entry names one earlier key of // its field — not its own, not a live sibling's, not one another field // claims, once — the same door: only the object holds the field map. From 1e9782f5b6e02ff0dad1c2912b3a40bcec2b3323 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 23:58:23 +0000 Subject: [PATCH 02/32] feat(spec): closedStates form row, liveness row, FLS classification and generated docs (ADR-0162 D1) Claude-Session: https://claude.ai/code/session_01L6bhgTCFhayR5cBZXM7XPP Co-authored-by: Claude --- content/docs/references/data/object.mdx | 1 + .../src/object-schema-fls-references.test.ts | 16 ++++++++++++++++ .../src/object-schema-fls-references.ts | 7 +++++++ packages/spec/authorable-surface/data.json | 1 + packages/spec/docs/references/api/metadata.md | 1 + .../spec/docs/references/system/migration.md | 1 + .../docs/references/system/migration.part-2.md | 1 + packages/spec/liveness/object.json | 6 ++++++ packages/spec/liveness/state-counts/object.md | 2 +- packages/spec/src/data/object.metadata-form.ts | 4 ++++ 10 files changed, 39 insertions(+), 1 deletion(-) diff --git a/content/docs/references/data/object.mdx b/content/docs/references/data/object.mdx index 13c27fe5b97..2601fba4688 100644 --- a/content/docs/references/data/object.mdx +++ b/content/docs/references/data/object.mdx @@ -172,6 +172,7 @@ const result = ApiMethod.parse(data); | **validations** | `any[]` | optional | Object-level validation rules | | **activityMilestones** | `{ field: string; value: string; summary: string; type?: string }[]` | optional | Declarative semantic activity milestones — emit a templated timeline row when a field transitions into a value, no hook code (ADR-0052 §5b.2). | | **uiReadonlyWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — every field of an existing record is read-only BY HAND while TRUE: the console surfaces a field's own `uiReadonlyWhen` locks (the edit dialog, record-page inline edit and the stage path, the highlight-strip chip, grid inline edit and multi-row save, kanban column drag, calendar drag, the Gantt, the timesheet cell, the line-item grid) do not let a person edit the record, while REST, import, action and flow writes keep every field, judged by the object's validations. e.g. P`record.status in ['confirmed', 'done']` on an order moved by Confirm / Cancel actions. A default for every field: a field that declares `uiReadonly: true` or its own `uiReadonlyWhen` is judged by that instead, so a field whose own `uiReadonlyWhen` is P`false` stays editable inside a locked record; `uiReadonly: false` is not such a declaration and the field follows the object lock. A create is not judged. A predicate the console cannot evaluate locks every field that inherits it. Same scope as a field's `readonlyWhen`: the record's OWN columns. The engine never reads this key. | +| **closedStates** | `Record` | optional | States in which a record is CLOSED: a map from a stored, single-value `select` field of this object to the list of that field's option values that close the record, e.g. `{ status: ['paid', 'void'], approval_status: ['approved'] }`. A record is closed when ANY listed field holds one of its listed values, read off the stored row. While closed, the record and its direct master_detail lines are closed to change for every caller that is not a system context: the record is not updated or deleted, and no line is created, updated, deleted or moved. The field must declare inline options; each listed value is one of them; a list is not empty and repeats nothing. A field or option a declaration names cannot be removed or retyped while it names it. A line object declares nothing to be closed with its master, and may declare its own. Independent of any state_machine rule on the field. | | **nameField** | `string` | optional | [ADR-0079] Canonical primary title field — the stored field used as the record display name (e.g. "name", "title"). | | **displayNameField** | `string` | optional | [DEPRECATED → nameField] Field to use as the record display name (e.g., "name", "title"). Accepted as an alias for nameField. | | **titleFormat** | `string \| { dialect: 'template'; source?: string; ast?: any; meta?: object }` | optional | [DEPRECATED → nameField (ADR-0079)] Render-only title template; the server cannot return or query it, and an explicit nameField now takes precedence. An object definition that declares it is refused at the metadata save gate and by os validate; a stored object that carries it still parses and reads. Migrate a single-field title to nameField; a composite title that import, sort or search must match to a stored computed field (a non-formula field with an expression, computed and stored on every write) designated as nameField — a text formula designated as nameField stays legal for a title shown for display only. Placeholders may be written `{{field}}` or `{field}` — the title renderers treat the two as equivalent, normalizing `{{field}}` to `{field}` before substituting; neither spelling is judged at parse time. | diff --git a/packages/metadata-core/src/object-schema-fls-references.test.ts b/packages/metadata-core/src/object-schema-fls-references.test.ts index 6ffb26988fe..de4d9418da1 100644 --- a/packages/metadata-core/src/object-schema-fls-references.test.ts +++ b/packages/metadata-core/src/object-schema-fls-references.test.ts @@ -485,6 +485,22 @@ describe('[ADR-0106 D1] references to a denied field — inside a READABLE field expect(served.uiReadonlyWhen).toBe("record.title != ''"); }); + // [ADR-0162 D1] The closed states are keyed by this object's fields. + it('[ADR-0162] drops a `closedStates` entry keyed by the denied field, and keeps the readable one', () => { + const served = mask({ name: 'thing', fields: fieldsWith(), closedStates: { secret_score: ['high'], title: ['done'] } }); + expect(served.closedStates).toEqual({ title: ['done'] }); + }); + + it('[ADR-0162] deletes `closedStates` when its only entry is keyed by the denied field', () => { + const served = mask({ name: 'thing', fields: fieldsWith(), closedStates: { secret_score: ['high'] } }); + expect('closedStates' in served).toBe(false); + }); + + it('[ADR-0162] CONTROL: a closing VALUE spelled like the denied field is a literal, served as written', () => { + const served = mask({ name: 'thing', fields: fieldsWith(), closedStates: { title: ['secret_score'] } }); + expect(served.closedStates).toEqual({ title: ['secret_score'] }); + }); + it('drops a `lookupAutofill` pair whose target is denied, and keeps a source named on the referenced object', () => { // #27945 — `target` is a field of THIS object; `source` names a field of // the lookup's `reference` object, which this projection cannot judge. diff --git a/packages/metadata-core/src/object-schema-fls-references.ts b/packages/metadata-core/src/object-schema-fls-references.ts index fdfa8efdf43..f84b649b58c 100644 --- a/packages/metadata-core/src/object-schema-fls-references.ts +++ b/packages/metadata-core/src/object-schema-fls-references.ts @@ -850,6 +850,13 @@ export const OBJECT_REFERENCE_POSITIONS: Readonly> = { // Expressions. titleFormat: expression, uiReadonlyWhen: objectHandLock, + // [ADR-0162 D1] The closed states: KEYED by a field of this object, each + // value a list of that field's option codes (literals, never a field + // reference). An entry whose key is a denied field goes — the field does + // not exist for that caller, nor do the states it closes on — and an + // emptied map is deleted. The engine judges the stored declaration + // whoever is served what; this is the served document only. + closedStates: recordOf(keep, true), // Rule entries — dropped whole when they mention a denied field. validations: ruleEntries, indexes: ruleEntries, diff --git a/packages/spec/authorable-surface/data.json b/packages/spec/authorable-surface/data.json index 07c0cb93ecb..84a4cdccd9d 100644 --- a/packages/spec/authorable-surface/data.json +++ b/packages/spec/authorable-surface/data.json @@ -684,6 +684,7 @@ "data/Object:actions", "data/Object:activityMilestones", "data/Object:attachedOnRead", + "data/Object:closedStates", "data/Object:color", "data/Object:datasource", "data/Object:defaultRowScope", diff --git a/packages/spec/docs/references/api/metadata.md b/packages/spec/docs/references/api/metadata.md index 56b8224d1d0..c4933641dee 100644 --- a/packages/spec/docs/references/api/metadata.md +++ b/packages/spec/docs/references/api/metadata.md @@ -957,6 +957,7 @@ Metadata query with filtering, sorting, and pagination | **validations** | `any[]` | optional | Object-level validation rules | | **activityMilestones** | `{ field: string; value: string; summary: string; type?: string }[]` | optional | Declarative semantic activity milestones — emit a templated timeline row when a field transitions into a value, no hook code (ADR-0052 §5b.2). | | **uiReadonlyWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — every field of an existing record is read-only BY HAND while TRUE: the console surfaces a field's own `uiReadonlyWhen` locks (the edit dialog, record-page inline edit and the stage path, the highlight-strip chip, grid inline edit and multi-row save, kanban column drag, calendar drag, the Gantt, the timesheet cell, the line-item grid) do not let a person edit the record, while REST, import, action and flow writes keep every field, judged by the object's validations. e.g. P`record.status in ['confirmed', 'done']` on an order moved by Confirm / Cancel actions. A default for every field: a field that declares `uiReadonly: true` or its own `uiReadonlyWhen` is judged by that instead, so a field whose own `uiReadonlyWhen` is P`false` stays editable inside a locked record; `uiReadonly: false` is not such a declaration and the field follows the object lock. A create is not judged. A predicate the console cannot evaluate locks every field that inherits it. Same scope as a field's `readonlyWhen`: the record's OWN columns. The engine never reads this key. | +| **closedStates** | `Record` | optional | States in which a record is CLOSED: a map from a stored, single-value `select` field of this object to the list of that field's option values that close the record, e.g. `{ status: ['paid', 'void'], approval_status: ['approved'] }`. A record is closed when ANY listed field holds one of its listed values, read off the stored row. While closed, the record and its direct master_detail lines are closed to change for every caller that is not a system context: the record is not updated or deleted, and no line is created, updated, deleted or moved. The field must declare inline options; each listed value is one of them; a list is not empty and repeats nothing. A field or option a declaration names cannot be removed or retyped while it names it. A line object declares nothing to be closed with its master, and may declare its own. Independent of any state_machine rule on the field. | | **nameField** | `string` | optional | [ADR-0079] Canonical primary title field — the stored field used as the record display name (e.g. "name", "title"). | | **displayNameField** | `string` | optional | [DEPRECATED → nameField] Field to use as the record display name (e.g., "name", "title"). Accepted as an alias for nameField. | | **titleFormat** | `string \| { dialect: 'template'; source?: string; ast?: any; meta?: object }` | optional | [DEPRECATED → nameField (ADR-0079)] Render-only title template; the server cannot return or query it, and an explicit nameField now takes precedence. An object definition that declares it is refused at the metadata save gate and by os validate; a stored object that carries it still parses and reads. Migrate a single-field title to nameField; a composite title that import, sort or search must match to a stored computed field (a non-formula field with an expression, computed and stored on every write) designated as nameField — a text formula designated as nameField stays legal for a title shown for display only. Placeholders may be written `{{field}}` or `{field}` — the title renderers treat the two as equivalent, normalizing `{{field}}` to `{field}` before substituting; neither spelling is judged at parse time. | diff --git a/packages/spec/docs/references/system/migration.md b/packages/spec/docs/references/system/migration.md index 56298b61be3..2df45c0da40 100644 --- a/packages/spec/docs/references/system/migration.md +++ b/packages/spec/docs/references/system/migration.md @@ -356,6 +356,7 @@ Create a new object | **validations** | `any[]` | optional | Object-level validation rules | | **activityMilestones** | `{ field: string; value: string; summary: string; type?: string }[]` | optional | Declarative semantic activity milestones — emit a templated timeline row when a field transitions into a value, no hook code (ADR-0052 §5b.2). | | **uiReadonlyWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — every field of an existing record is read-only BY HAND while TRUE: the console surfaces a field's own `uiReadonlyWhen` locks (the edit dialog, record-page inline edit and the stage path, the highlight-strip chip, grid inline edit and multi-row save, kanban column drag, calendar drag, the Gantt, the timesheet cell, the line-item grid) do not let a person edit the record, while REST, import, action and flow writes keep every field, judged by the object's validations. e.g. P`record.status in ['confirmed', 'done']` on an order moved by Confirm / Cancel actions. A default for every field: a field that declares `uiReadonly: true` or its own `uiReadonlyWhen` is judged by that instead, so a field whose own `uiReadonlyWhen` is P`false` stays editable inside a locked record; `uiReadonly: false` is not such a declaration and the field follows the object lock. A create is not judged. A predicate the console cannot evaluate locks every field that inherits it. Same scope as a field's `readonlyWhen`: the record's OWN columns. The engine never reads this key. | +| **closedStates** | `Record` | optional | States in which a record is CLOSED: a map from a stored, single-value `select` field of this object to the list of that field's option values that close the record, e.g. `{ status: ['paid', 'void'], approval_status: ['approved'] }`. A record is closed when ANY listed field holds one of its listed values, read off the stored row. While closed, the record and its direct master_detail lines are closed to change for every caller that is not a system context: the record is not updated or deleted, and no line is created, updated, deleted or moved. The field must declare inline options; each listed value is one of them; a list is not empty and repeats nothing. A field or option a declaration names cannot be removed or retyped while it names it. A line object declares nothing to be closed with its master, and may declare its own. Independent of any state_machine rule on the field. | | **nameField** | `string` | optional | [ADR-0079] Canonical primary title field — the stored field used as the record display name (e.g. "name", "title"). | | **displayNameField** | `string` | optional | [DEPRECATED → nameField] Field to use as the record display name (e.g., "name", "title"). Accepted as an alias for nameField. | | **titleFormat** | `string \| { dialect: 'template'; source?: string; ast?: any; meta?: object }` | optional | [DEPRECATED → nameField (ADR-0079)] Render-only title template; the server cannot return or query it, and an explicit nameField now takes precedence. An object definition that declares it is refused at the metadata save gate and by os validate; a stored object that carries it still parses and reads. Migrate a single-field title to nameField; a composite title that import, sort or search must match to a stored computed field (a non-formula field with an expression, computed and stored on every write) designated as nameField — a text formula designated as nameField stays legal for a title shown for display only. Placeholders may be written `{{field}}` or `{field}` — the title renderers treat the two as equivalent, normalizing `{{field}}` to `{field}` before substituting; neither spelling is judged at parse time. | diff --git a/packages/spec/docs/references/system/migration.part-2.md b/packages/spec/docs/references/system/migration.part-2.md index 04f2782ebe9..1196b9a9d3e 100644 --- a/packages/spec/docs/references/system/migration.part-2.md +++ b/packages/spec/docs/references/system/migration.part-2.md @@ -200,6 +200,7 @@ Create a new object | **validations** | `any[]` | optional | Object-level validation rules | | **activityMilestones** | `{ field: string; value: string; summary: string; type?: string }[]` | optional | Declarative semantic activity milestones — emit a templated timeline row when a field transitions into a value, no hook code (ADR-0052 §5b.2). | | **uiReadonlyWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — every field of an existing record is read-only BY HAND while TRUE: the console surfaces a field's own `uiReadonlyWhen` locks (the edit dialog, record-page inline edit and the stage path, the highlight-strip chip, grid inline edit and multi-row save, kanban column drag, calendar drag, the Gantt, the timesheet cell, the line-item grid) do not let a person edit the record, while REST, import, action and flow writes keep every field, judged by the object's validations. e.g. P`record.status in ['confirmed', 'done']` on an order moved by Confirm / Cancel actions. A default for every field: a field that declares `uiReadonly: true` or its own `uiReadonlyWhen` is judged by that instead, so a field whose own `uiReadonlyWhen` is P`false` stays editable inside a locked record; `uiReadonly: false` is not such a declaration and the field follows the object lock. A create is not judged. A predicate the console cannot evaluate locks every field that inherits it. Same scope as a field's `readonlyWhen`: the record's OWN columns. The engine never reads this key. | +| **closedStates** | `Record` | optional | States in which a record is CLOSED: a map from a stored, single-value `select` field of this object to the list of that field's option values that close the record, e.g. `{ status: ['paid', 'void'], approval_status: ['approved'] }`. A record is closed when ANY listed field holds one of its listed values, read off the stored row. While closed, the record and its direct master_detail lines are closed to change for every caller that is not a system context: the record is not updated or deleted, and no line is created, updated, deleted or moved. The field must declare inline options; each listed value is one of them; a list is not empty and repeats nothing. A field or option a declaration names cannot be removed or retyped while it names it. A line object declares nothing to be closed with its master, and may declare its own. Independent of any state_machine rule on the field. | | **nameField** | `string` | optional | [ADR-0079] Canonical primary title field — the stored field used as the record display name (e.g. "name", "title"). | | **displayNameField** | `string` | optional | [DEPRECATED → nameField] Field to use as the record display name (e.g., "name", "title"). Accepted as an alias for nameField. | | **titleFormat** | `string \| { dialect: 'template'; source?: string; ast?: any; meta?: object }` | optional | [DEPRECATED → nameField (ADR-0079)] Render-only title template; the server cannot return or query it, and an explicit nameField now takes precedence. An object definition that declares it is refused at the metadata save gate and by os validate; a stored object that carries it still parses and reads. Migrate a single-field title to nameField; a composite title that import, sort or search must match to a stored computed field (a non-formula field with an expression, computed and stored on every write) designated as nameField — a text formula designated as nameField stays legal for a title shown for display only. Placeholders may be written `{{field}}` or `{field}` — the title renderers treat the two as equivalent, normalizing `{{field}}` to `{field}` before substituting; neither spelling is judged at parse time. | diff --git a/packages/spec/liveness/object.json b/packages/spec/liveness/object.json index efe379ab252..58455f0b4cd 100644 --- a/packages/spec/liveness/object.json +++ b/packages/spec/liveness/object.json @@ -286,6 +286,12 @@ "evidence": "ui/packages/core/src/evaluator/handLock.ts#effectiveUiReadonlyWhen (a field's own `uiReadonly: true` / `uiReadonlyWhen` wins, else the object's predicate; `uiReadonly: false` reads as absent) read by #fieldReadOnlyByHand, #fieldHasConditionalHandLock and #fieldLockPredicates, which every hand surface reads with the object definition beside the field: the record page (ui/packages/plugin-detail/src/DetailSection.tsx, HeaderHighlight.tsx, InlineEditSaveBar.tsx, renderers/recordPathStageChange.tsx), the grid cell (ui/packages/plugin-grid/src/objectGridCellFacts.ts#cellReadOnlyKind) and its operand fetch (objectGridRowLoad.ts, ui/packages/plugin-list/src/ListView.tsx), kanban and calendar drops, the Gantt (ui/packages/plugin-gantt/src/ganttHandLock.ts), the timesheet cell, and the edit dialog's form fields (ui/packages/plugin-form/src/sectionFields.ts#fromObjectSchema, ObjectForm.tsx, ui/packages/app-shell/src/utils/editFormLockedByState.ts); packages/runtime/src/domains/mcp.ts#describeServedObject and packages/mcp/src/mcp-server-runtime.ts#describeServedObject (describe_object); packages/lint/src/validate-expressions.ts (objectstack validate)", "note": "renderer only, by ruling (the two-tier field-lock model, its object level): while TRUE no person edits any field of an existing record at the console surfaces a field's own `uiReadonlyWhen` locks; a field that declares `uiReadonly: true` or its own `uiReadonlyWhen` is judged by that instead (`uiReadonly: false` is not a declaration: the field follows the object lock; the opt-out spelling is a field `uiReadonlyWhen` of P`false`). The engine never reads it, so REST, import, action and flow writes keep every field, judged by validations. Fail-closed on a fault, as the field key. The console has no person-triggered record duplicate, so no clone surface reads it; the REST clone door is an API write and keeps every value." }, + "closedStates": { + "status": "planned", + "verifiedAt": "2026-11-28", + "evidence": "packages/spec/src/data/closed-states.ts#refuseDishonestClosedStates (the authoring refusals, live at parse and at the save door: a key naming no field, a field that is not a single-value select with inline options, an empty list, a value that is not an option or is repeated; so a removed or retyped field or a removed option under a standing declaration is refused)", + "note": "PLANNED RECORD (ADR-0162 D1, card #37768 slice A): the object's closed states. Its REFUSALS are live at parse (evidence). No runtime reads the key yet: the engine's judgement (ADR-0162 D2-D7, D10) is slice B of the same card and the refusal's code and sentences (D8) are slice C, built on the same trunk branch, which does not merge before both land, so the key is never published without its enforcement (ADR-0078, ADR-0162 D10). It turns live in slice B, with its runtime proof." + }, "validations": { "status": "live", "verifiedAt": "2026-08-28", diff --git a/packages/spec/liveness/state-counts/object.md b/packages/spec/liveness/state-counts/object.md index a51975c0ba9..622d97af478 100644 --- a/packages/spec/liveness/state-counts/object.md +++ b/packages/spec/liveness/state-counts/object.md @@ -12,4 +12,4 @@ committed anywhere: `check:liveness` sums the shards when it reads them. | Type | live | exp | elsewhere | dead | planned | classified | |---|---|---|---|---|---|---| -| `object` | 95 | 0 | 0 | 1 | 1 | 97 | +| `object` | 95 | 0 | 0 | 1 | 2 | 98 | diff --git a/packages/spec/src/data/object.metadata-form.ts b/packages/spec/src/data/object.metadata-form.ts index 950350f6892..c6c524e53f2 100644 --- a/packages/spec/src/data/object.metadata-form.ts +++ b/packages/spec/src/data/object.metadata-form.ts @@ -537,6 +537,10 @@ export const objectForm = defineMetadataForm({ // machine it usually follows: the same CEL code row the field form // gives the field key. { field: 'uiReadonlyWhen', type: 'code', language: 'expression', colSpan: 2, helpText: "CEL predicate over the record (e.g. record.status in ['confirmed', 'done']) — while it is TRUE, people cannot edit any field of an existing record anywhere in the console (the edit dialog, the record page, grids, kanban, calendar and Gantt drag, the timesheet); a new record's create dialog is not judged. A field that sets its own hand lock (uiReadonly turned on, or uiReadonlyWhen) is judged by that instead, so uiReadonlyWhen: false on a field keeps it editable; uiReadonly turned off does not, and the field follows this lock. Actions, imports, the API and flows still write every field, judged by the object's validations. Reads the record's own columns. The in-app assistant acting for a person does not honour it yet." }, + // [ADR-0162 D1] The states that close a record, beside the state + // machine and the hand lock: a map from a select field to its closing + // values, the same JSON row `validations` is edited in. + { field: 'closedStates', widget: 'json', colSpan: 2, helpText: 'States in which a record is closed, as a map from a single-value select field of this object to the list of its option values that close the record, e.g. { "status": ["paid", "void"], "approval_status": ["approved"] }. While a record is closed, no one but the system edits or deletes it, or adds, edits, moves or removes its lines. Each field needs its options declared on it; each value must be one of them, listed once. A field or option named here cannot be removed or retyped until it is taken out of this map.' }, // #19332 (flight G2b of ruling record 5861442317) — the object's // declarative timeline milestones (ADR-0052 §5b.2), beside `validations`: // a milestone fires on a field reaching a value, the same transition a From b7893db92b3d32b5dc58f7d7bb2df584a1c0dfa7 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 23:59:42 +0000 Subject: [PATCH 03/32] feat(platform-objects): closedStates form row translated in every locale, changesets (ADR-0162 D1) Claude-Session: https://claude.ai/code/session_01L6bhgTCFhayR5cBZXM7XPP Co-authored-by: Claude --- .changeset/37768-closed-states-metadata-core.md | 10 ++++++++++ .changeset/37768-closed-states-platform-objects.md | 10 ++++++++++ .changeset/37768-closed-states-spec.md | 14 ++++++++++++++ .../translations/ar.metadata-forms.generated.ts | 4 ++++ .../translations/de.metadata-forms.generated.ts | 4 ++++ .../translations/es-ES.metadata-forms.generated.ts | 4 ++++ .../translations/fr.metadata-forms.generated.ts | 4 ++++ .../translations/ja-JP.metadata-forms.generated.ts | 4 ++++ .../translations/ko.metadata-forms.generated.ts | 4 ++++ ...bject-collapsed-sections-echo-decisions.test.ts | 7 +++++-- .../object-lifecycle-panel-echo-decisions.test.ts | 4 +++- .../translations/pt-BR.metadata-forms.generated.ts | 4 ++++ .../translations/ru.metadata-forms.generated.ts | 4 ++++ .../translations/zh-CN.metadata-forms.generated.ts | 4 ++++ .../zh-Hant.metadata-forms.generated.ts | 4 ++++ 15 files changed, 82 insertions(+), 3 deletions(-) create mode 100644 .changeset/37768-closed-states-metadata-core.md create mode 100644 .changeset/37768-closed-states-platform-objects.md create mode 100644 .changeset/37768-closed-states-spec.md diff --git a/.changeset/37768-closed-states-metadata-core.md b/.changeset/37768-closed-states-metadata-core.md new file mode 100644 index 00000000000..708da5d7204 --- /dev/null +++ b/.changeset/37768-closed-states-metadata-core.md @@ -0,0 +1,10 @@ +--- +'@objectstack/metadata-core': patch +--- + +feat(metadata-core): the field-level-security scrub serves an object's closed states without the fields a caller cannot read + +Clause-②: yes (widening: one new optional authorable key, `ObjectSchema.closedStates`) +Metadata-protocol: added + +`closedStates` (ADR-0162 D1) is classified in the object-schema FLS reference table as a map keyed by this object's fields: an entry whose field is denied to the caller is left out of the served definition, and a map left empty is deleted. The listed values are option codes, never field references, so a value spelled like a denied field is served as written. The stored declaration is untouched. diff --git a/.changeset/37768-closed-states-platform-objects.md b/.changeset/37768-closed-states-platform-objects.md new file mode 100644 index 00000000000..b57babeb0eb --- /dev/null +++ b/.changeset/37768-closed-states-platform-objects.md @@ -0,0 +1,10 @@ +--- +'@objectstack/platform-objects': patch +--- + +feat(platform-objects): the Studio object form's closed-states row is translated in every metadata-forms locale pack + +Clause-②: yes (widening: one new optional authorable key, `ObjectSchema.closedStates`) +Metadata-protocol: added + +The object form's Advanced section offers `closedStates` (ADR-0162 D1); its label and help text are authored in all eleven metadata-forms locale packs. diff --git a/.changeset/37768-closed-states-spec.md b/.changeset/37768-closed-states-spec.md new file mode 100644 index 00000000000..5904b291d91 --- /dev/null +++ b/.changeset/37768-closed-states-spec.md @@ -0,0 +1,14 @@ +--- +'@objectstack/spec': minor +--- + +feat(spec): an object declares its closed states (`closedStates`, ADR-0162 D1) + +Clause-②: yes (widening: one new optional authorable key, `ObjectSchema.closedStates`) +Metadata-protocol: added + +An object may now declare the states in which its records are closed: a map from a stored, single-value `select` field of the object to the list of that field's option values that close a record, e.g. `closedStates: { status: ['paid', 'void'], approval_status: ['approved'] }`. A record is closed when any listed field holds one of its listed values. In a closed state the record and its direct `master_detail` lines are closed to change for every caller that is not a system context. + +- **Refused where the object is authored**, at parse and at the metadata save and publish door, one located issue each: a key that names no field of the object; a field that is not a single-value `select` (another type, `radio` included, or `multiple: true`); a select whose options are not declared inline on it (a `picklist`-backed select); an empty list; a value that is not one of the field's options; a value listed twice. So is the edit that would leave such a declaration behind: removing or retyping a field, or removing an option, that a declaration still names. Take the entry out of `closedStates` first. +- **Optional**: an object without the key behaves exactly as before. A line object declares nothing to be closed with its master, and may declare its own `closedStates`. The key has no tie to a `state_machine` rule in either direction. +- Liveness row `object.closedStates`, the Studio object form's Advanced section offers it as a JSON row, and the reference docs, authorable-surface record and state counts are regenerated. diff --git a/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts index 7f75b36eefb..10d12a84152 100644 --- a/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts @@ -429,6 +429,10 @@ export const arMetadataForms: NonNullable = { label: "السجل كله للقراءة فقط في الواجهة عندما", helpText: "شرط CEL على السجل (مثل record.status in ['confirmed', 'done']) — ما دام TRUE لا يستطيع أحد تعديل أي حقل من سجل موجود في وحدة التحكم (مربع حوار التعديل، صفحة السجل، الجداول، كانبان، السحب في التقويم ومخطط جانت، جدول الدوام)؛ ولا يُقيَّم مربع حوار إنشاء سجل جديد. الحقل الذي يعلن قفله اليدوي الخاص (تفعيل uiReadonly، أو uiReadonlyWhen) يُحكم عليه بإعلانه، لذا فإن uiReadonlyWhen: false على حقل يبقيه قابلاً للتعديل؛ أما إيقاف uiReadonly فلا يُحتسب، ويتبع الحقل هذا القفل. تستمر الإجراءات والاستيراد وواجهة API والتدفقات في كتابة كل حقل، وتحكم عليها قواعد التحقق للكائن. يقرأ أعمدة السجل نفسه. المساعد داخل التطبيق الذي يعمل نيابة عن شخص لا يلتزم بهذا بعد." }, + closedStates: { + label: "الحالات المغلقة", + helpText: "الحالات التي يكون فيها السجل مغلقًا، في صورة خريطة من حقل اختيار أحادي القيمة في هذا الكائن إلى قائمة قيم خياراته التي تغلق السجل، مثل { \"status\": [\"paid\", \"void\"], \"approval_status\": [\"approved\"] }. ما دام السجل مغلقًا فلا يستطيع أحد غير النظام تعديله أو حذفه، ولا إضافة بنوده أو تعديلها أو نقلها أو إزالتها. يجب أن يعلن كل حقل خياراته بنفسه، وأن تكون كل قيمة واحدة منها مذكورة مرة واحدة. لا يمكن حذف حقل أو خيار مذكور هنا أو تغيير نوعه حتى يُزال من هذه الخريطة." + }, activityMilestones: { label: "معالم النشاط", helpText: "إدخالات في الخط الزمني يُطلقها وصول حقل إلى قيمة (ADR-0052 §5b.2): عندما ينقل تحديثٌ الحقلَ المراقَب إلى القيمة، يكتب مكوّن التدقيق الإضافي ملخّص المَعلم في الخط الزمني لنشاط السجل بدلًا من إدخال تغيير الحقل. يفوز أول مَعلم يطابق." diff --git a/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts index c9182fceb96..5eb4db7ae99 100644 --- a/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts @@ -429,6 +429,10 @@ export const deMetadataForms: NonNullable = { label: "Ganzer Datensatz in der Oberfläche schreibgeschützt wenn", helpText: "CEL-Prädikat über den Datensatz (z. B. record.status in ['confirmed', 'done']) – solange es TRUE ist, kann niemand in der Konsole ein Feld eines bestehenden Datensatzes bearbeiten (Bearbeitungsdialog, Datensatzseite, Tabellen, Kanban, Kalender- und Gantt-Ziehen, Zeiterfassung); der Erstellungsdialog eines neuen Datensatzes wird nicht geprüft. Ein Feld, das eine eigene manuelle Sperre (uiReadonly eingeschaltet oder uiReadonlyWhen) festlegt, wird stattdessen danach beurteilt, sodass uiReadonlyWhen: false an einem Feld es bearbeitbar hält; ein ausgeschaltetes uiReadonly zählt nicht, und das Feld folgt dieser Sperre. Aktionen, Importe, die API und Flows schreiben weiterhin jedes Feld, beurteilt durch die Validierungen des Objekts. Liest die eigenen Spalten des Datensatzes. Der In-App-Assistent, der für eine Person handelt, beachtet dies noch nicht." }, + closedStates: { + label: "Abgeschlossene Zustände", + helpText: "Zustände, in denen ein Datensatz abgeschlossen ist, als Zuordnung von einem einwertigen Auswahlfeld dieses Objekts zur Liste seiner Optionswerte, die den Datensatz abschließen, z. B. { \"status\": [\"paid\", \"void\"], \"approval_status\": [\"approved\"] }. Solange ein Datensatz abgeschlossen ist, kann ihn niemand außer dem System bearbeiten oder löschen, und niemand kann seine Positionen hinzufügen, bearbeiten, verschieben oder entfernen. Jedes Feld muss seine Optionen selbst deklarieren; jeder Wert muss eine davon sein und darf nur einmal aufgeführt werden. Ein hier genanntes Feld oder eine hier genannte Option kann erst entfernt oder umtypisiert werden, wenn es aus dieser Zuordnung herausgenommen wurde." + }, activityMilestones: { label: "Aktivitätsmeilensteine", helpText: "Zeitleisteneinträge, die ausgelöst werden, wenn ein Feld einen Wert erreicht (ADR-0052 §5b.2): Wenn eine Aktualisierung das beobachtete Feld auf den Wert setzt, schreibt das Audit-Plugin die Zusammenfassung des Meilensteins statt des Feldänderungseintrags in die Aktivitätszeitleiste des Datensatzes. Der erste passende Meilenstein gewinnt." diff --git a/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts index b7e23abe90e..39220da37d1 100644 --- a/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts @@ -429,6 +429,10 @@ export const esESMetadataForms: NonNullable = label: "Condición de solo lectura en la interfaz para todo el registro", helpText: "Predicado CEL sobre el registro (p. ej. record.status in ['confirmed', 'done']): mientras sea TRUE, nadie puede editar ningún campo de un registro existente en la consola (el diálogo de edición, la página del registro, las cuadrículas, el kanban, el arrastre del calendario y del Gantt, la hoja de horas); el diálogo de creación de un registro nuevo no se evalúa. Un campo que declara su propio bloqueo manual (uiReadonly activado, o uiReadonlyWhen) se juzga por él, así que uiReadonlyWhen: false en un campo lo mantiene editable; uiReadonly desactivado no cuenta y el campo sigue este bloqueo. Las acciones, las importaciones, la API y los flujos siguen escribiendo todos los campos, juzgados por las validaciones del objeto. Lee las columnas propias del registro. El asistente integrado que actúa por una persona aún no lo respeta." }, + closedStates: { + label: "Estados cerrados", + helpText: "Estados en los que un registro está cerrado, como un mapa de un campo de selección de valor único de este objeto a la lista de sus valores de opción que cierran el registro, p. ej. { \"status\": [\"paid\", \"void\"], \"approval_status\": [\"approved\"] }. Mientras un registro está cerrado, nadie salvo el sistema puede editarlo ni eliminarlo, ni añadir, editar, mover o quitar sus líneas. Cada campo debe declarar sus propias opciones; cada valor debe ser una de ellas y figurar una sola vez. Un campo u opción indicado aquí no se puede eliminar ni cambiar de tipo hasta que se quite de este mapa." + }, activityMilestones: { label: "Hitos de actividad", helpText: "Entradas de la cronología que se disparan cuando un campo alcanza un valor (ADR-0052 §5b.2): cuando una actualización cambia el campo vigilado a ese valor, el plugin de auditoría escribe el resumen del hito en la cronología de actividad del registro en lugar de la entrada de cambio de campo. Gana el primer hito que coincide." diff --git a/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts index bd5845ad4af..4d0579e7e60 100644 --- a/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts @@ -429,6 +429,10 @@ export const frMetadataForms: NonNullable = { label: "Enregistrement entier en lecture seule dans l'interface si", helpText: "Prédicat CEL sur l'enregistrement (par ex. record.status in ['confirmed', 'done']) — tant qu'il est TRUE, personne ne peut modifier un champ d'un enregistrement existant dans la console (boîte de dialogue de modification, page de l'enregistrement, grilles, kanban, glisser-déposer du calendrier et du Gantt, feuille de temps) ; la boîte de dialogue de création d'un nouvel enregistrement n'est pas évaluée. Un champ qui déclare son propre verrou manuel (uiReadonly activé, ou uiReadonlyWhen) est jugé par celui-ci, donc uiReadonlyWhen: false sur un champ le garde modifiable ; uiReadonly désactivé ne compte pas, et le champ suit ce verrou. Les actions, les imports, l'API et les flux écrivent toujours chaque champ, jugés par les validations de l'objet. Lit les colonnes propres de l'enregistrement. L'assistant intégré agissant pour une personne ne le respecte pas encore." }, + closedStates: { + label: "États clôturés", + helpText: "États dans lesquels un enregistrement est clôturé, sous forme d’une correspondance entre un champ de sélection à valeur unique de cet objet et la liste de ses valeurs d’option qui clôturent l’enregistrement, par ex. { \"status\": [\"paid\", \"void\"], \"approval_status\": [\"approved\"] }. Tant qu’un enregistrement est clôturé, personne d’autre que le système ne peut le modifier ou le supprimer, ni ajouter, modifier, déplacer ou supprimer ses lignes. Chaque champ doit déclarer ses propres options ; chaque valeur doit être l’une d’elles, citée une seule fois. Un champ ou une option cité ici ne peut être supprimé ni changer de type tant qu’il n’est pas retiré de cette correspondance." + }, activityMilestones: { label: "Jalons d’activité", helpText: "Entrées de chronologie déclenchées lorsqu’un champ atteint une valeur (ADR-0052 §5b.2) : lorsqu’une mise à jour fait passer le champ surveillé à cette valeur, le plugin d’audit écrit le résumé du jalon dans la chronologie d’activité de l’enregistrement au lieu de l’entrée de modification de champ. Le premier jalon qui correspond l’emporte." diff --git a/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts index 7986b5e7d8f..cffc9905ea0 100644 --- a/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts @@ -429,6 +429,10 @@ export const jaJPMetadataForms: NonNullable = label: "レコード全体を画面上で読み取り専用にする条件", helpText: "レコードに対する CEL 述語(例: record.status in ['confirmed', 'done'])。TRUE の間、コンソールのどこでも既存レコードのどのフィールドも人が編集できません(編集ダイアログ、レコードページ、グリッド、カンバン、カレンダーとガントのドラッグ、タイムシート)。新規レコードの作成ダイアログは判定されません。独自の手動ロック(uiReadonly をオン、または uiReadonlyWhen)を宣言したフィールドはその宣言で判定されるため、フィールドに uiReadonlyWhen: false を設定すると編集可能なままになります。uiReadonly をオフにしてもそうはならず、フィールドはこのロックに従います。アクション、インポート、API、フローは引き続きすべてのフィールドに書き込み、オブジェクトの検証ルールで判定されます。レコード自身の列を読み取ります。ユーザーの代わりに操作するアプリ内アシスタントはまだこの設定に従いません。" }, + closedStates: { + label: "クローズ状態", + helpText: "レコードがクローズされる状態。このオブジェクトの単一値の選択フィールドから、レコードをクローズさせるそのオプション値のリストへのマップです。例: { \"status\": [\"paid\", \"void\"], \"approval_status\": [\"approved\"] }。レコードがクローズされている間は、システム以外の誰もそのレコードを編集・削除できず、明細行の追加・編集・移動・削除もできません。各フィールドは自身にオプションを宣言している必要があり、各値はそのいずれかで、一度だけ記載します。ここで指定したフィールドやオプションは、このマップから外すまで削除や型の変更ができません。" + }, activityMilestones: { label: "アクティビティのマイルストーン", helpText: "フィールドが特定の値に達したときに書き込まれるタイムラインのエントリ(ADR-0052 §5b.2)。更新で監視対象のフィールドがその値に変わると、監査プラグインはフィールド変更のエントリの代わりに、マイルストーンの概要をレコードのアクティビティタイムラインに書き込みます。最初に一致したマイルストーンが使われます。" diff --git a/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts index 69e0936fcc0..97aeefbc433 100644 --- a/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts @@ -429,6 +429,10 @@ export const koMetadataForms: NonNullable = { label: "레코드 전체를 화면에서 읽기 전용으로 하는 조건", helpText: "레코드에 대한 CEL 조건식(예: record.status in ['confirmed', 'done']) — TRUE인 동안 콘솔 어디에서도 기존 레코드의 어떤 필드도 사람이 편집할 수 없습니다(편집 대화상자, 레코드 페이지, 그리드, 칸반, 캘린더와 간트 드래그, 타임시트). 새 레코드의 생성 대화상자는 판정하지 않습니다. 자체 수동 잠금(uiReadonly 켜기 또는 uiReadonlyWhen)을 선언한 필드는 그 선언으로 판정되므로, 필드에 uiReadonlyWhen: false를 두면 편집 가능한 상태로 유지됩니다. uiReadonly를 끈 것은 해당하지 않으며 필드는 이 잠금을 따릅니다. 작업, 가져오기, API, 플로는 여전히 모든 필드에 쓰며 객체의 검증 규칙이 판정합니다. 레코드 자체의 열을 읽습니다. 사용자를 대신해 작업하는 앱 내 어시스턴트는 아직 이 설정을 따르지 않습니다." }, + closedStates: { + label: "마감 상태", + helpText: "레코드가 마감되는 상태입니다. 이 객체의 단일 값 선택 필드를 레코드를 마감시키는 해당 옵션 값 목록에 매핑합니다. 예: { \"status\": [\"paid\", \"void\"], \"approval_status\": [\"approved\"] }. 레코드가 마감된 동안에는 시스템 외에는 누구도 레코드를 편집하거나 삭제할 수 없고, 상세 행을 추가, 편집, 이동, 삭제할 수도 없습니다. 각 필드는 자체에 옵션을 선언해야 하며, 각 값은 그중 하나여야 하고 한 번만 나열합니다. 여기에 지정된 필드나 옵션은 이 매핑에서 빼기 전까지 삭제하거나 유형을 바꿀 수 없습니다." + }, activityMilestones: { label: "활동 마일스톤", helpText: "필드가 특정 값에 도달하면 발생하는 타임라인 항목입니다(ADR-0052 §5b.2). 업데이트로 감시 대상 필드가 그 값으로 바뀌면, 감사 플러그인이 필드 변경 항목 대신 마일스톤의 요약을 레코드 활동 타임라인에 기록합니다. 처음 일치하는 마일스톤이 우선합니다." diff --git a/packages/platform-objects/src/apps/translations/object-collapsed-sections-echo-decisions.test.ts b/packages/platform-objects/src/apps/translations/object-collapsed-sections-echo-decisions.test.ts index 234b7bd2f8e..443171ddae1 100644 --- a/packages/platform-objects/src/apps/translations/object-collapsed-sections-echo-decisions.test.ts +++ b/packages/platform-objects/src/apps/translations/object-collapsed-sections-echo-decisions.test.ts @@ -970,10 +970,13 @@ describe('#19403 round 8 — the population, DERIVED from the form and a shape', // 127 since #37402 gave `advanced` the object's whole-record hand lock // (`uiReadonlyWhen`) — a label and a help text, two leaves, all translated // leaves authored in every locale by that card. `advanced` reads 112 → 114. - expect(PANEL_LEAVES.length).toBe(127); + // 129 since ADR-0162 D1 gave `advanced` the object's closed states + // (`closedStates`) — a label and a help text, two leaves, all translated + // leaves authored in every locale by that card. `advanced` reads 114 → 116. + expect(PANEL_LEAVES.length).toBe(129); expect(PANEL_LEAVES.every((l) => l.prop === 'label' || l.prop === 'helpText')).toBe(true); expect(PANEL_LEAVES.filter((l) => l.section === 'capabilities').length).toBe(13); - expect(PANEL_LEAVES.filter((l) => l.section === 'advanced').length).toBe(114); + expect(PANEL_LEAVES.filter((l) => l.section === 'advanced').length).toBe(116); }); it('⭐ DARK, OUTWARD — the open sections are excluded, and `fields.placeholder` is the one that proves it', () => { diff --git a/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts b/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts index 4be5a90cb63..eda16b2491d 100644 --- a/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts +++ b/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts @@ -1355,7 +1355,9 @@ describe('#19403 round 10 — the verdicts, on the live bundles', () => { // 866 since #37309: the `knowledge_source` form (ADR-0161 K4 clause 2) // — twenty of its section and row labels, authored in all three // locales. - expect(translated.length, `${locale} positive control`).toBe(866); + // 867 since ADR-0162 D1: the object form's `closedStates` row (the + // states that close a record), authored in every locale. + expect(translated.length, `${locale} positive control`).toBe(867); } // ⭐ DARK — the blindness, executable. On a synthetic two-locale catalog the // all-three predicate returns 0 while the per-locale one returns 1, so the diff --git a/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts index dfca7b34b03..0e4691d4b71 100644 --- a/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts @@ -429,6 +429,10 @@ export const ptBRMetadataForms: NonNullable = label: "Registro inteiro somente leitura na interface quando", helpText: "Predicado CEL sobre o registro (por exemplo, record.status in ['confirmed', 'done']) — enquanto for TRUE, ninguém pode editar nenhum campo de um registro existente no console (o diálogo de edição, a página do registro, grades, kanban, arrastar no calendário e no Gantt, a planilha de horas); o diálogo de criação de um novo registro não é avaliado. Um campo que declara seu próprio bloqueio manual (uiReadonly ativado, ou uiReadonlyWhen) é julgado por ele, então uiReadonlyWhen: false em um campo o mantém editável; uiReadonly desativado não conta, e o campo segue este bloqueio. Ações, importações, a API e fluxos continuam gravando todos os campos, julgados pelas validações do objeto. Lê as colunas do próprio registro. O assistente no aplicativo que age por uma pessoa ainda não respeita isso." }, + closedStates: { + label: "Estados fechados", + helpText: "Estados em que um registro está fechado, como um mapa de um campo de seleção de valor único deste objeto para a lista dos seus valores de opção que fecham o registro, por exemplo { \"status\": [\"paid\", \"void\"], \"approval_status\": [\"approved\"] }. Enquanto um registro está fechado, ninguém além do sistema pode editá-lo ou excluí-lo, nem adicionar, editar, mover ou remover suas linhas. Cada campo precisa declarar as próprias opções; cada valor deve ser uma delas, listado uma única vez. Um campo ou opção citado aqui não pode ser removido nem ter o tipo alterado até ser retirado deste mapa." + }, activityMilestones: { label: "Marcos de atividade", helpText: "Entradas da linha do tempo disparadas quando um campo atinge um valor (ADR-0052 §5b.2): quando uma atualização leva o campo observado para o valor, o plugin de auditoria grava o resumo do marco na linha do tempo de atividades do registro em vez da entrada de alteração de campo. O primeiro marco correspondente vence." diff --git a/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts index 545c5158f16..9ea714ad63e 100644 --- a/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts @@ -429,6 +429,10 @@ export const ruMetadataForms: NonNullable = { label: "Вся запись только для чтения в интерфейсе, когда", helpText: "Предикат CEL над записью (например, record.status in ['confirmed', 'done']) — пока он TRUE, никто не может изменить ни одно поле существующей записи в консоли (диалог редактирования, страница записи, таблицы, канбан, перетаскивание в календаре и диаграмме Ганта, табель); диалог создания новой записи не проверяется. Поле, объявившее собственную ручную блокировку (включённый uiReadonly или uiReadonlyWhen), оценивается по ней, поэтому uiReadonlyWhen: false у поля оставляет его редактируемым; выключенный uiReadonly не считается, и поле следует этой блокировке. Действия, импорт, API и потоки по-прежнему записывают каждое поле, и их оценивают проверки объекта. Читает собственные столбцы записи. Встроенный помощник, действующий от имени человека, пока это не учитывает." }, + closedStates: { + label: "Закрытые состояния", + helpText: "Состояния, в которых запись закрыта: сопоставление однозначного поля выбора этого объекта со списком его значений вариантов, которые закрывают запись, например { \"status\": [\"paid\", \"void\"], \"approval_status\": [\"approved\"] }. Пока запись закрыта, никто, кроме системы, не может её изменить или удалить, а также добавить, изменить, переместить или удалить её строки. Каждое поле должно само объявлять свои варианты; каждое значение должно быть одним из них и указываться один раз. Поле или вариант, указанные здесь, нельзя удалить или сменить им тип, пока они не убраны из этого сопоставления." + }, activityMilestones: { label: "Вехи активности", helpText: "Записи ленты, создаваемые, когда поле достигает значения (ADR-0052 §5b.2): когда обновление переводит отслеживаемое поле в это значение, плагин аудита записывает в ленту активности записи сводку вехи вместо записи об изменении поля. Побеждает первая подходящая веха." diff --git a/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts index ab8bcd54dcf..509d6cb0903 100644 --- a/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts @@ -429,6 +429,10 @@ export const zhCNMetadataForms: NonNullable = label: "记录界面只读条件", helpText: "基于记录的 CEL 谓词(例如 record.status in ['confirmed', 'done'])——为 TRUE 时,用户无法在控制台中编辑已有记录的任何字段(编辑对话框、记录页、表格、看板、日历和甘特图拖动、工时表);新建记录的创建对话框不做判断。自行声明了手动锁定(开启 uiReadonly,或 uiReadonlyWhen)的字段按其自身声明裁决,因此字段上的 uiReadonlyWhen: false 可让它保持可编辑;关闭 uiReadonly 不算,字段仍随此锁定。动作、导入、API 和流程仍可写入每个字段,并由对象的校验规则裁决。读取记录自身的列。代表用户操作的应用内助手暂不遵循此设置。" }, + closedStates: { + label: "已关闭状态", + helpText: "记录处于已关闭状态的条件:一个映射,键为本对象的单值选择字段,值为使记录关闭的选项值列表,例如 { \"status\": [\"paid\", \"void\"], \"approval_status\": [\"approved\"] }。记录关闭后,除系统外任何人都不能编辑或删除它,也不能新增、编辑、移动或删除它的明细行。每个字段都必须在自身上声明选项;每个值必须是其中之一,且只列一次。这里列出的字段或选项,在从此映射中移除之前不能删除或更改类型。" + }, activityMilestones: { label: "活动里程碑", helpText: "由字段到达某个值触发的时间线条目(ADR-0052 §5b.2):当一次更新把被监视的字段变为该值时,审计插件会把该里程碑的摘要写入记录的活动时间线,代替字段变更条目。第一个匹配的里程碑生效。" diff --git a/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts index 0e56ba2a608..eb794dbb603 100644 --- a/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts @@ -429,6 +429,10 @@ export const zhHantMetadataForms: NonNullable label: "記錄介面唯讀條件", helpText: "基於記錄的 CEL 述詞(例如 record.status in ['confirmed', 'done'])——為 TRUE 時,使用者無法在主控台中編輯既有記錄的任何欄位(編輯對話框、記錄頁、表格、看板、行事曆與甘特圖拖曳、工時表);新記錄的建立對話框不做判斷。自行宣告了手動鎖定(開啟 uiReadonly,或 uiReadonlyWhen)的欄位依其自身宣告裁決,因此欄位上的 uiReadonlyWhen: false 可讓它保持可編輯;關閉 uiReadonly 不算,欄位仍隨此鎖定。動作、匯入、API 與流程仍可寫入每個欄位,並由物件的驗證規則裁決。讀取記錄自身的欄。代表使用者操作的應用程式內助理暫不遵循此設定。" }, + closedStates: { + label: "已關閉狀態", + helpText: "記錄處於已關閉狀態的條件:一個對應表,鍵為本物件的單值選擇欄位,值為使記錄關閉的選項值清單,例如 { \"status\": [\"paid\", \"void\"], \"approval_status\": [\"approved\"] }。記錄關閉後,除系統外任何人都不能編輯或刪除它,也不能新增、編輯、移動或刪除它的明細列。每個欄位都必須在自身上宣告選項;每個值必須是其中之一,且只列一次。這裡列出的欄位或選項,在從此對應表中移除之前不能刪除或變更類型。" + }, activityMilestones: { label: "活動里程碑", helpText: "由欄位到達某個值觸發的時間軸條目(ADR-0052 §5b.2):當一次更新把被監視的欄位變為該值時,稽核外掛會把該里程碑的摘要寫入記錄的活動時間軸,代替欄位變更條目。第一個比對的里程碑生效。" From 649f344cf916084bdebf51c18a94f5c20d678fda Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 00:05:25 +0000 Subject: [PATCH 04/32] chore(platform-objects): regenerate the en metadata-forms bundle for the closedStates row Claude-Session: https://claude.ai/code/session_01L6bhgTCFhayR5cBZXM7XPP Co-authored-by: Claude --- .../src/apps/translations/en.metadata-forms.generated.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts index 3952dcfe568..7b300e57d48 100644 --- a/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts @@ -429,6 +429,10 @@ export const enMetadataForms: NonNullable = { label: "Ui Readonly When", helpText: "CEL predicate over the record (e.g. record.status in ['confirmed', 'done']) — while it is TRUE, people cannot edit any field of an existing record anywhere in the console (the edit dialog, the record page, grids, kanban, calendar and Gantt drag, the timesheet); a new record's create dialog is not judged. A field that sets its own hand lock (uiReadonly turned on, or uiReadonlyWhen) is judged by that instead, so uiReadonlyWhen: false on a field keeps it editable; uiReadonly turned off does not, and the field follows this lock. Actions, imports, the API and flows still write every field, judged by the object's validations. Reads the record's own columns. The in-app assistant acting for a person does not honour it yet." }, + closedStates: { + label: "Closed States", + helpText: "States in which a record is closed, as a map from a single-value select field of this object to the list of its option values that close the record, e.g. { \"status\": [\"paid\", \"void\"], \"approval_status\": [\"approved\"] }. While a record is closed, no one but the system edits or deletes it, or adds, edits, moves or removes its lines. Each field needs its options declared on it; each value must be one of them, listed once. A field or option named here cannot be removed or retyped until it is taken out of this map." + }, activityMilestones: { label: "Activity Milestones", helpText: "Timeline entries fired by a field reaching a value (ADR-0052 §5b.2): when an update moves the watched field into the value, the audit plugin writes the milestone's summary to the record's activity timeline instead of the field-change entry. The first milestone that matches wins." From 31da54b71dc296b209e46faf4228734b0545c484 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 00:11:06 +0000 Subject: [PATCH 05/32] test(spec): the composeStacks collection-refusal pins carry closedStates (ADR-0162 D1) Claude-Session: https://claude.ai/code/session_01L6bhgTCFhayR5cBZXM7XPP Co-authored-by: Claude --- .../compose-stacks-collection-pipe-arm.test.ts | 18 +++++++++++++----- ...ose-stacks-merge-collection-refusal.test.ts | 4 ++++ 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/packages/spec/src/compose-stacks-collection-pipe-arm.test.ts b/packages/spec/src/compose-stacks-collection-pipe-arm.test.ts index dff46d04225..a43c90ed324 100644 --- a/packages/spec/src/compose-stacks-collection-pipe-arm.test.ts +++ b/packages/spec/src/compose-stacks-collection-pipe-arm.test.ts @@ -253,6 +253,8 @@ describe('MAIN — the preprocess-wrapped collection key is IN the refusal set', 'requiredPermissions', 'validations', 'activityMilestones', + // [ADR-0162 D1] `closedStates` — the object's closed states, a map keyed by its fields. + 'closedStates', 'highlightFields', 'relatedLists', 'listViews', @@ -299,18 +301,24 @@ describe("TODAY-INVARIANCE — the fix moves no key on today's ObjectSchema", () const setUnder = (shape: Record, walk: Walk) => Object.keys(shape).filter((key) => key !== 'fields' && walk(shape[key])); - it('all three candidate readings derive the SAME refusal set', async () => { + // [ADR-0162 D1] `closedStates` is the first collection key on the real shape + // whose record sits behind a preprocess stage (the `__proto__` guard): it is + // exactly the key this rule exists for. The landed reading and `in || out` + // carry it; the in-only reading misses it, and misses nothing else. + it('the landed rule and `in || out` derive the same refusal set; the in-only reading misses only the preprocess-wrapped `closedStates`', async () => { const shape = await realShape(); - const inOnly = setUnder(shape, inOnlyWalk); - expect(setUnder(shape, authorableWalk), 'the landed rule moved a key on the real shape').toEqual(inOnly); - expect(setUnder(shape, eitherSideWalk), '`in || out` would move a key on the real shape').toEqual(inOnly); - expect(inOnly).toEqual([ + const landed = setUnder(shape, authorableWalk); + expect(setUnder(shape, eitherSideWalk), '`in || out` would move a key on the real shape').toEqual(landed); + expect(setUnder(shape, inOnlyWalk)).toEqual(landed.filter((key) => key !== 'closedStates')); + expect(landed).toEqual([ 'attachedOnRead', 'indexes', 'fieldGroups', 'requiredPermissions', 'validations', 'activityMilestones', + // [ADR-0162 D1] `closedStates` — the object's closed states, a map keyed by its fields. + 'closedStates', 'highlightFields', 'relatedLists', 'listViews', diff --git a/packages/spec/src/compose-stacks-merge-collection-refusal.test.ts b/packages/spec/src/compose-stacks-merge-collection-refusal.test.ts index 0c01604f479..bce81d2b0bb 100644 --- a/packages/spec/src/compose-stacks-merge-collection-refusal.test.ts +++ b/packages/spec/src/compose-stacks-merge-collection-refusal.test.ts @@ -66,6 +66,8 @@ const COLLECTION_KEYS_IN_SHAPE_ORDER = [ 'requiredPermissions', 'validations', 'activityMilestones', + // [ADR-0162 D1] `closedStates` — the object's closed states, a map keyed by its fields. + 'closedStates', 'highlightFields', 'relatedLists', 'listViews', @@ -146,6 +148,8 @@ describe("composeStacks objectConflict: 'merge' — a collection both objects de ['requiredPermissions', ['crm.read'], ['billing.read']], ['attachedOnRead', { viewer: { can_act: 'boolean' } }, { viewer: { can_act: 'boolean', is_submitter: 'boolean' } }], ['membershipKeys', { mine_ids: { userField: 'owner', valueField: 'title' } }, { mine_ids: { userField: 'owner', valueField: 'body' } }], + // [ADR-0162 D1] Two packages that close one object on different states: neither may silently win. + ['closedStates', { status: ['paid'] }, { status: ['paid', 'void'] }], ] as const)("refuses two objects declaring different '%s'", (key, left, right) => { const a = defineStack({ manifest: mf('com.example.a'), objects: [obj('shared', { [key]: left })] }, { strict: false }); const b = defineStack({ manifest: mf('com.example.b'), objects: [obj('shared', { [key]: right })] }, { strict: false }); From 5d8b45b76ff45cb99da820aa2efde691bc06d3e0 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 00:13:27 +0000 Subject: [PATCH 06/32] test(metadata-protocol): the object type serves one more top-level property, closedStates (ADR-0162 D1) Claude-Session: https://claude.ai/code/session_01L6bhgTCFhayR5cBZXM7XPP Co-authored-by: Claude --- .../src/protocol.meta-types-degenerate-derivation.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/metadata-protocol/src/protocol.meta-types-degenerate-derivation.test.ts b/packages/metadata-protocol/src/protocol.meta-types-degenerate-derivation.test.ts index 8eb62f9025d..3755e79835b 100644 --- a/packages/metadata-protocol/src/protocol.meta-types-degenerate-derivation.test.ts +++ b/packages/metadata-protocol/src/protocol.meta-types-degenerate-derivation.test.ts @@ -416,9 +416,11 @@ describe('#17501 — /meta/types serves a real schema for `action`, and moves no // from (ADR-0160 D8), which gives its MCP prompt a record argument. // [#37402] `object` 52 → 53: `uiReadonlyWhen`, the whole-record hand lock // (no person edits a field of the record at the console; writes keep it). + // [ADR-0162 D1] `object` 53 → 54: `closedStates`, the states in which a + // record and its master-detail lines are closed to change. const CARD_PROPERTY_COUNTS: Record = { agent: 24, app: 24, dashboard: 21, dataset: 17, field: 89, flow: 24, - hook: 24, object: 53, page: 28, position: 14, report: 24, skill: 18, tool: 14, + hook: 24, object: 54, page: 28, position: 14, report: 24, skill: 18, tool: 14, }; it.each(Object.entries(CARD_PROPERTY_COUNTS))( From cfde5477d61f44c7d2686b3541c42b9a1e39afd2 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 01:18:03 +0000 Subject: [PATCH 07/32] test(approvals): pin what a multi-step approval that does not finish leaves on its status mirror (ADR-0162 item 8, readings 3-6) A node failing after a decision strands the run and the field keeps the first step's outcome; a later step that cannot open (empty slate under `fail`, another approval pending) strands it, or completes the run down a `fault` edge with the step never asked; a parent cancelled above a pending child leaves the decision admitted, the door reporting a clean resume and the parent's next step never asked. The dead-run sweep changes nothing after any of them. Claude-Session: https://claude.ai/code/session_01L6bhgX7z5dcSkTqEAWNMsP Co-authored-by: Claude --- ...pproval-mirror-unfinished-readings.test.ts | 364 ++++++++++++++++++ 1 file changed, 364 insertions(+) create mode 100644 packages/plugins/plugin-approvals/src/approval-mirror-unfinished-readings.test.ts diff --git a/packages/plugins/plugin-approvals/src/approval-mirror-unfinished-readings.test.ts b/packages/plugins/plugin-approvals/src/approval-mirror-unfinished-readings.test.ts new file mode 100644 index 00000000000..a2b8a98a31b --- /dev/null +++ b/packages/plugins/plugin-approvals/src/approval-mirror-unfinished-readings.test.ts @@ -0,0 +1,364 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 Execution item 8] What a multi-step approval leaves on its status + * mirror when it does not finish — measured as the code stands, before the + * outcome is held back on a field the object closes on. + * + * The item's design note (ruling record 7210179412 on its card) was read, not + * run, and its first build step is to pin four of its readings with tests. + * This file is that step. Each test records the value the mirror field keeps, + * which is what the later pieces of the item change on an object that declares + * `closedStates`; the object here declares none, so every assertion below is + * also the control those pieces keep: an object with no closed state behaves + * as it does today. + * + * - Reading 3: the door that records a decision is told about a parent run + * only where that parent STRANDED. A parent that was cancelled answers + * `RUN_NOT_FOUND` to the up-bubble, which is a `warn` line, and the door + * reports a clean resume with nothing behind it. + * - Reading 4: a node that fails after a decision ends the run `failed`; the + * engine answers `stranded`, and the door throws `RESUME_FAILED` with + * `repairable`. The decision stands, and no request is open. + * - Reading 5: a step that cannot open fails its node — `NO_APPROVERS` under + * `onEmptyApprovers: 'fail'`, `DUPLICATE_REQUEST` while another request is + * pending on the record. Unrouted, that is reading 4's strand; down a + * `fault` edge the run goes on and completes, with the step never asked. + * - Reading 6: `cancelRun` cancels one suspended run and touches no child. A + * parent parked at a `subflow` node is cancelled while its child's request + * is pending; the decision on the child is still admitted, the child + * completes, and the parent's next step is never asked. + * + * And reading 8 where it meets these: the dead-run sweep reads pending + * requests only, so after each of these ends it changes nothing. + */ + +import { describe, it, expect, beforeEach } from 'vitest'; +import { AutomationEngine, InMemorySuspendedRunStore, installBuiltinNodes } from '@objectstack/service-automation'; +import { assertEngineDeleteDispatch, assertEngineUpdateDispatch } from '@objectstack/objectql'; +import { strandedDecisionDetails } from '@objectstack/types'; +import { ApprovalService } from './approval-service.js'; +import { registerApprovalNode } from './approval-node.js'; + +const SYSTEM_CTX = { isSystem: true, positions: [], permissions: [] } as any; + +/** Records every level, so "only a warn line says so" is measurable. */ +function recordingLogger() { + const lines: Array<{ level: string; msg: string; meta?: unknown }> = []; + const mk = (level: string) => (msg: string, meta?: unknown) => { lines.push({ level, msg, meta }); }; + const self: any = { + lines, + info: mk('info'), warn: mk('warn'), error: mk('error'), debug: mk('debug'), + child() { return self; }, + }; + return self; +} + +function makeFakeEngine() { + const tables = new Map(); + const rows = (o: string) => (tables.get(o) ?? (tables.set(o, []), tables.get(o)!)); + const matches = (row: any, where: any) => Object.entries(where ?? {}).every(([k, v]) => { + 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 survivors = table.filter(r => !matches(r, options?.where)); + const deleted = table.length - survivors.length; + table.splice(0, table.length, ...survivors); + return { deleted }; + } + const i = table.findIndex(r => r.id === dispatch.id); + if (i >= 0) table.splice(i, 1); + return { id: dispatch.id }; + }, + }; +} + +const MIRROR = 'approval_status'; +const approvalStep = (id: string, approvers: unknown[], extra: Record = {}) => ({ + id, type: 'approval', label: id, config: { approvers, approvalStatusField: MIRROR, ...extra }, +}); + +/** + * Two approval steps with a `mark` node between them. `step2` is the caller's, + * and `fault` adds a `fault` edge from it to the end. + */ +function twoStepFlow(step2: Record, opts: { fault?: boolean } = {}) { + return { + name: 'two_step', label: 'Two steps', type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + approvalStep('step1', [{ type: 'user', value: 'u1' }]), + { id: 'between', type: 'mark', label: 'Between the steps' }, + step2, + { id: 'done', type: 'mark', label: 'Done' }, + { id: 'rejected', type: 'mark', label: 'Rejected' }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'step1' }, + { id: 'e2', source: 'step1', target: 'between', label: 'approve' }, + { id: 'e3', source: 'step1', target: 'rejected', label: 'reject' }, + { id: 'e4', source: 'between', target: 'step2' }, + { id: 'e5', source: 'step2', target: 'done', label: 'approve' }, + { id: 'e6', source: 'step2', target: 'rejected', label: 'reject' }, + { id: 'e7', source: 'done', target: 'end' }, + { id: 'e8', source: 'rejected', target: 'end' }, + ...(opts.fault ? [{ id: 'f1', source: 'step2', target: 'end', type: 'fault' }] : []), + ], + }; +} + +/** Another approval of the same record: one step. */ +const OTHER_APPROVAL = { + name: 'other_approval', label: 'Other approval', type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + approvalStep('other_step', [{ type: 'user', value: 'u9' }]), + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'x1', source: 'start', target: 'other_step' }, + { id: 'x2', source: 'other_step', target: 'end' }, + ], +}; + +/** A one-step approval, hosted by {@link PARENT}'s `subflow` node. */ +const CHILD = { + name: 'child_approval', label: 'Child approval', type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + approvalStep('child_step', [{ type: 'user', value: 'u1' }]), + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'c1', source: 'start', target: 'child_step' }, + { id: 'c2', source: 'child_step', target: 'end', label: 'approve' }, + { id: 'c3', source: 'child_step', target: 'end', label: 'reject' }, + ], +}; + +/** The parent: its first step is the child's, its second its own. */ +const PARENT = { + name: 'parent_approval', label: 'Parent approval', type: 'autolaunched', + nodes: [ + { id: 'pstart', type: 'start', label: 'Start' }, + { id: 'sub', type: 'subflow', label: 'First step, in a child', config: { flowName: 'child_approval', outputVariable: 'subOut' } }, + approvalStep('parent_step', [{ type: 'user', value: 'u2' }]), + { id: 'pend', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'p1', source: 'pstart', target: 'sub' }, + { id: 'p2', source: 'sub', target: 'parent_step' }, + { id: 'p3', source: 'parent_step', target: 'pend' }, + ], +}; + +describe('[ADR-0162 item 8] an approval that does not finish, as the mirror stands today (readings 3–6)', () => { + let data: ReturnType; + let service: ApprovalService; + let logger: ReturnType; + let marks: string[]; + let throwOn: Record; + let onMark: Record Promise) | undefined>; + + beforeEach(() => { + marks = []; + throwOn = {}; + onMark = {}; + logger = recordingLogger(); + data = makeFakeEngine(); + data.tables.set('crm_deal', [{ id: 'd1', amount: 100, [MIRROR]: 'draft' }]); + data.tables.set('sys_user', ['submitter', 'u1', 'u2', 'u9'].map((id) => ({ id, email: `${id}@example.test` }))); + service = new ApprovalService({ engine: data as any, logger }); + }); + + function boot(...flows: Array>) { + const automation = new AutomationEngine(logger, new InMemorySuspendedRunStore()); + installBuiltinNodes(automation, { logger, getService() { throw new Error('none'); } } as any); + registerApprovalNode(automation, service, logger); + automation.registerNodeExecutor({ + type: 'mark', + async execute(node: any) { + const boom = throwOn[node.id]; + if (boom) throw new Error(boom); + await onMark[node.id]?.(); + marks.push(node.id); + return { success: true }; + }, + } as never); + for (const flow of flows) automation.registerFlow(flow.name, flow as never); + service.attachAutomation(automation); + return automation; + } + + const submit = async (automation: AutomationEngine, flow: string) => + (await automation.execute(flow, { object: 'crm_deal', record: { id: 'd1', amount: 100 }, userId: 'submitter' } as never)) as any; + const mirrorField = () => data.tables.get('crm_deal')![0][MIRROR]; + const requests = async () => + (await data.find('sys_approval_request', {})).map((r: any) => ({ step: r.flow_node_id, status: r.status })); + const firstPending = async () => (await data.find('sys_approval_request', { where: { status: 'pending' } }))[0]; + const stepLog = async (automation: AutomationEngine, runId: string) => + ((await automation.getRun(runId)) as any)?.steps?.map((s: any) => [s.nodeId, s.status]) ?? []; + const approveFirst = async () => { + const req = await firstPending(); + return service + .decide(req.id, { decision: 'approve', actorId: 'u1' }, SYSTEM_CTX) + .then((r) => ({ ok: true as const, r }), (e: Error) => ({ ok: false as const, e })); + }; + /** Reading 8: the dead-run sweep reads pending requests only, so here it changes nothing. */ + const sweepChangesNothing = async () => { + const before = { field: mirrorField(), requests: await requests() }; + await service.releaseDeadRunRequests(); + expect({ field: mirrorField(), requests: await requests() }, 'the sweep reads pending requests only').toEqual(before); + }; + + it('reading 4: a node that fails after a decision strands the run; the decision stands and the field keeps `approved`', async () => { + throwOn.between = 'the node between the steps failed'; + const automation = boot(twoStepFlow(approvalStep('step2', [{ type: 'user', value: 'u2' }]))); + const run = await submit(automation, 'two_step'); + expect(mirrorField()).toBe('pending'); + + const outcome = await approveFirst(); + + expect(outcome.ok, 'the decision door throws').toBe(false); + const err = outcome.ok ? (undefined as never) : outcome.e; + expect(err.message).toMatch(/^RESUME_FAILED/); + expect(strandedDecisionDetails(err)).toEqual({ finalized: true, decision: 'approve', runId: run.runId, repairable: true }); + expect((await automation.getRun(run.runId))?.status).toBe('failed'); + expect(await stepLog(automation, run.runId)).toEqual([['start', 'success'], ['step1', 'success'], ['between', 'failure']]); + expect(await requests(), 'the second step was never asked').toEqual([{ step: 'step1', status: 'approved' }]); + expect(mirrorField(), 'the value the field keeps').toBe('approved'); + await sweepChangesNothing(); + expect((await automation.restoreConsumedSuspension(run.runId, { requestedBy: 'ops' })).restored, 'an operator can put the pause back').toBe(true); + }); + + describe('reading 5: a later step that cannot open fails its node', () => { + const emptySlate = () => approvalStep('step2', [{ type: 'field', value: 'reviewer_id' }], { onEmptyApprovers: 'fail' }); + + it('on an empty slate under `fail`, unrouted: the run strands at the step, and the field keeps `approved`', async () => { + const automation = boot(twoStepFlow(emptySlate())); + const run = await submit(automation, 'two_step'); + + const outcome = await approveFirst(); + + expect(outcome.ok).toBe(false); + const err = outcome.ok ? (undefined as never) : outcome.e; + expect(strandedDecisionDetails(err)).toEqual({ finalized: true, decision: 'approve', runId: run.runId, repairable: true }); + expect((await automation.getRun(run.runId))?.status).toBe('failed'); + const steps = ((await automation.getRun(run.runId)) as any).steps; + expect(steps.at(-1)).toMatchObject({ nodeId: 'step2', status: 'failure' }); + expect(steps.at(-1).error.message).toContain('NO_APPROVERS'); + expect(await requests()).toEqual([{ step: 'step1', status: 'approved' }]); + expect(mirrorField(), 'the value the field keeps').toBe('approved'); + await sweepChangesNothing(); + }); + + it('on an empty slate, down a `fault` edge to the end: the run completes with the step never asked, and the field keeps `approved`', async () => { + const automation = boot(twoStepFlow(emptySlate(), { fault: true })); + const run = await submit(automation, 'two_step'); + + const outcome = await approveFirst(); + + expect(outcome.ok, 'the door answers a clean resume').toBe(true); + const answer = outcome.ok ? outcome.r : (undefined as never); + expect(answer.resumed).toBe(true); + expect(answer.resumeError).toBeUndefined(); + expect(answer.resumeFailure).toBeUndefined(); + expect((await automation.getRun(run.runId))?.status).toBe('completed'); + expect(await stepLog(automation, run.runId), 'the failure is in the step log, which is all that says so') + .toEqual([['start', 'success'], ['step1', 'success'], ['between', 'success'], ['step2', 'failure']]); + expect(marks, 'neither the approved nor the rejected branch ran').toEqual(['between']); + expect(await requests()).toEqual([{ step: 'step1', status: 'approved' }]); + expect(mirrorField(), 'the value the field keeps').toBe('approved'); + await sweepChangesNothing(); + }); + + for (const fault of [false, true]) { + it(`while another approval's request is pending on the record${fault ? ', down a `fault` edge' : ', unrouted'}: the field keeps that approval's \`pending\``, async () => { + const automation = boot(twoStepFlow(approvalStep('step2', [{ type: 'user', value: 'u2' }]), { fault }), OTHER_APPROVAL); + // Between the two steps, another approval of the same record opens: + // the first step's request is no longer pending, so nothing stops it. + onMark.between = async () => { + expect((await submit(automation, 'other_approval')).status).toBe('paused'); + }; + const run = await submit(automation, 'two_step'); + + const outcome = await approveFirst(); + + expect(outcome.ok).toBe(fault); + expect((await automation.getRun(run.runId))?.status).toBe(fault ? 'completed' : 'failed'); + const steps = ((await automation.getRun(run.runId)) as any).steps; + expect(steps.at(-1)).toMatchObject({ nodeId: 'step2', status: 'failure' }); + expect(steps.at(-1).error.message).toContain('DUPLICATE_REQUEST'); + expect(await requests()).toEqual([{ step: 'step1', status: 'approved' }, { step: 'other_step', status: 'pending' }]); + expect(mirrorField(), "the value the field keeps: the other approval's").toBe('pending'); + }); + } + }); + + it('readings 3 and 6: a parent cancelled above a pending child; the decision is admitted, the door reports a clean resume, and the field keeps `approved`', async () => { + const automation = boot(CHILD, PARENT); + const parent = await submit(automation, 'parent_approval'); + expect(parent.status, 'the parent parks at its subflow node').toBe('paused'); + const req = await firstPending(); + const childRunId = String(req.flow_run_id); + expect(childRunId, 'the request names the child run').not.toBe(parent.runId); + expect(req.root_run_id, "the request's approval is the parent's run").toBe(parent.runId); + expect(mirrorField()).toBe('pending'); + + // Reading 6: the cancel reaches the parent and touches no child. + expect(await automation.cancelRun(parent.runId, 'operator')).toBe(true); + expect((await automation.getRun(parent.runId))?.status).toBe('cancelled'); + expect(await automation.hasSuspendedRun(childRunId), 'the child is still parked').toBe(true); + expect((await firstPending())?.id, "the child's request is still pending").toBe(req.id); + + const outcome = await approveFirst(); + + // Reading 3: the decision is admitted, because the liveness check asks + // about the request's own run, and the door is told nothing of the parent. + expect(outcome.ok).toBe(true); + const answer = outcome.ok ? outcome.r : (undefined as never); + expect(answer.finalized).toBe(true); + expect(answer.resumed).toBe(true); + expect(answer.resumeError).toBeUndefined(); + expect(answer.resumeFailure, 'only a stranded parent is told to the door').toBeUndefined(); + expect((await automation.getRun(childRunId))?.status).toBe('completed'); + expect((await automation.getRun(parent.runId))?.status).toBe('cancelled'); + const bubble = logger.lines.filter((l: any) => String(l.msg).includes(`resuming parent '${parent.runId}' failed`)); + expect(bubble.map((l: any) => l.level), 'one warn line is all that says so').toEqual(['warn']); + expect(logger.lines.filter((l: any) => l.level === 'error')).toEqual([]); + expect(await requests(), "the parent's step was never asked").toEqual([{ step: 'child_step', status: 'approved' }]); + expect(mirrorField(), 'the value the field keeps').toBe('approved'); + await sweepChangesNothing(); + }); +}); From 2953b1ba671c337e8422f2adf3879bce3993f7fd Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 01:18:04 +0000 Subject: [PATCH 08/32] fix(approvals): a refused status-mirror write on a field the object closes on is reported, and refuses an approval's first opening (ADR-0162 item 8) On a field the object closes on at `approved` or `rejected`, the mirror's write that a validation rule, an option's `visibleWhen` or a hook refuses is no longer swallowed at `warn`. At an approval's first request the `pending` is written right after the row; a refusal voids the row as `cancelled`, empties the approver index, notes the timeline and fails the run at that step with the refusal's own message. Every other refused write is reported: an `error` line, a line with no actor on the request's timeline, and a notice to the organization's administrators (`approval.status_mirror_refused`). Objects with no closed state keep the `warn`. Claude-Session: https://claude.ai/code/session_01L6bhgX7z5dcSkTqEAWNMsP Co-authored-by: Claude --- ...767-status-mirror-closing-field-refusal.md | 16 + .../plugin-approvals/src/approval-service.ts | 241 +++++++++++- ...-closing-field-refusal.integration.test.ts | 344 ++++++++++++++++++ .../src/translations/messages.ts | 22 ++ .../src/preference-options.ts | 1 + 5 files changed, 616 insertions(+), 8 deletions(-) create mode 100644 .changeset/37767-status-mirror-closing-field-refusal.md create mode 100644 packages/plugins/plugin-approvals/src/status-mirror-closing-field-refusal.integration.test.ts diff --git a/.changeset/37767-status-mirror-closing-field-refusal.md b/.changeset/37767-status-mirror-closing-field-refusal.md new file mode 100644 index 00000000000..b74af8a9633 --- /dev/null +++ b/.changeset/37767-status-mirror-closing-field-refusal.md @@ -0,0 +1,16 @@ +--- +'@objectstack/plugin-approvals': patch +'@objectstack/service-messaging': patch +--- + +fix(approvals): on a field the object closes on, a refused write of the approval status mirror is no longer swallowed (ADR-0162 Execution item 8) + +Clause-②: no +Metadata-protocol: none + +A validation rule, an option's `visibleWhen` or a hook of the app can refuse the write that mirrors an approval's status onto the record. The mirror used to log every such refusal at `warn` and go on. On a field the object closes on at `approved` or `rejected` (`closedStates`, ADR-0162 D1): + +- **The `pending` of an approval's first request.** The approval does not open. The request's row is voided as `cancelled`, nobody's inbox lists it, no lock is taken, and the run fails at that step with the refusal's own message. The record keeps the value it held, a closed one included. +- **Every other write** (a decision, a send-back, a recall's put-back, a later request's `pending`, the dead-run sweep's put-back). The field keeps the value it held, and the refusal is reported three ways: an `error` line naming the write and the fix, a line with no actor on the request's timeline carrying the refusal's message, and a notice to the organization's administrators under the new topic `approval.status_mirror_refused`, which the notification preference options now list. + +An object that declares no closed state is unchanged: its mirror still logs a refused write at `warn`, and its approval still opens. diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index eb9b812c2de..610a641fdda 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -1783,6 +1783,37 @@ 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 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 + * request (`ApprovalService.reportRefusedMirror`). `opening` is set by the one + * caller that answers the refusal itself: the `pending` of an approval's first + * request, whose refusal refuses the opening. + */ +interface MirrorRequestRef { + readonly request: any; + readonly step?: string | null; + readonly opening?: boolean; +} + +/** A write of the status mirror refused on a field the object closes on. */ +interface MirrorRefusal { + readonly refused: unknown; + readonly message: string; +} + +/** + * [ADR-0162 Execution item 8] The topic of the notice the organization's + * administrators get when a rule or a hook of the app refuses a write of the + * status mirror on a field the object closes on. + */ +const REFUSED_MIRROR_TOPIC = 'approval.status_mirror_refused'; + +/** The timeline line a refused write of the status mirror leaves on its request. */ +function refusedMirrorNoteText(status: string, reason: string): string { + return `The approval status '${status}' could not be written to the record: ${reason}`; +} + /** * [#24577] The values a status field declares, read as the engine's record * validator reads a select's options (objectql `record-validator.ts`, @@ -4985,6 +5016,16 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * **The value written is one the field declares (#24577).** What is written * is {@link mirroredStatusValue}'s answer, and `abandoned` (the request's * row, on a transition that abandons it) is what that answer may restore. + * + * **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 + * a definition shows when. Where the object closes on `field` at `approved` or + * `rejected` ({@link closesOnApprovalOutcome}) and `about` names the request, + * the refusal is answered as `{ refused }` and, unless `about.opening` says the + * caller refuses the opening itself, reported by + * {@link reportRefusedMirror}. On every other field the write keeps its + * best-effort `warn`, as before. */ private async mirrorStatusField( object: string, @@ -4994,7 +5035,8 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega actorId: string | null, requestOrg: string | null | undefined, abandoned?: { payloadJson: unknown }, - ): Promise { + about?: MirrorRequestRef, + ): Promise { try { const value = this.mirroredStatusValue(object, field, status, abandoned); if (value === STATUS_NOT_MIRRORED) { @@ -5003,14 +5045,171 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega + `declare it, so the field keeps its value. Declare '${status}' among the field's options to mirror this transition.`, { object, record: recordId, field, value: status }, ); - return; + return undefined; } const context = actorId ? await this.attributedMirrorContext(object, recordId, actorId, requestOrg) : SYSTEM_CTX; await this.engine.update(object, { id: recordId, [field]: value }, { context }); + return undefined; } catch (err: any) { + if (about && this.closesOnApprovalOutcome(object, field)) { + const refusal: MirrorRefusal = { refused: err, message: String(err?.message ?? err) }; + if (!about.opening) { + await this.reportRefusedMirror(object, recordId, field, status, refusal.message, about, requestOrg); + } + return refusal; + } this.logger?.warn?.(`[approvals] mirrorStatusField failed: ${err?.message ?? err}`); + return undefined; + } + } + + /** + * [ADR-0162 D5] Whether `object` closes on `field` at an approval's outcome: + * its `closedStates` lists `approved` or `rejected` for that field. Read from + * the registry the engine validates the mirror's write against, as + * {@link mirroredStatusValue} reads the field's options. An object that + * declares no closed state answers `false`, and its mirror behaves as it did + * before the key. + */ + private closesOnApprovalOutcome(object: string, field: string): boolean { + let closedStates: unknown; + try { + closedStates = (this.engine.getSchema?.(object) as { closedStates?: unknown } | undefined)?.closedStates; + } catch { /* schema unavailable — no closed state can be read, as for the value set above */ } + if (!closedStates || typeof closedStates !== 'object') return false; + const closed = (closedStates as Record)[field]; + return Array.isArray(closed) && (closed.includes('approved') || closed.includes('rejected')); + } + + /** + * [ADR-0162 Execution item 8] Whether `row` is its approval's first request on + * its record: no other request on the record names the same approval. The + * approval is the request's root run (`root_run_id`, ADR-0162 Execution item + * 7), or its own run where no root run was recorded. A later step, a later + * round of a resubmitted step and a step of a `subflow` child all share it. + * + * A read that fails answers "not the first": the refusal is then reported and + * the request stays open on an open value, where the other answer would fail + * the run between two steps on a guess. + */ + private async isFirstRequestOfApproval(row: any): Promise { + const approval = row?.root_run_id ? { root_run_id: row.root_run_id } : { flow_run_id: row?.flow_run_id }; + try { + const rows = await this.engine.find('sys_approval_request', { + where: { object_name: row.object_name, record_id: row.record_id, ...approval }, + fields: ['id'], limit: 2, context: SYSTEM_CTX, + }); + return !(Array.isArray(rows) ? rows : []).some((r: any) => String(r?.id) !== String(row.id)); + } catch (err: any) { + this.logger?.warn?.('[approvals] could not read whether a request is its approval\'s first; a refused status write is reported, not refused', { + request: row?.id, error: err?.message ?? String(err), + }); + return false; + } + } + + /** + * [ADR-0162 D5] An approval's first request whose `pending` a rule or a hook + * of the app refused, on a field the object closes on: the row is voided + * with the status the platform already has for that, `cancelled`, the + * approvers' index is emptied so that nobody's inbox lists it, and its + * timeline carries the refusal. The caller then fails the run at this step + * with the refusal's own message, which is what the submitter reads; the + * record keeps the value it held. + */ + private async voidRefusedOpening(row: any, refusal: MirrorRefusal, requestOrg: string | null | undefined): Promise { + const now = this.clock.now().toISOString(); + await this.engine.update('sys_approval_request', { + id: row.id, status: 'cancelled', pending_approvers: null, pending_approver_labels: null, + completed_at: now, updated_at: now, + }, { context: SYSTEM_CTX }); + await this.syncApproverIndex(row.id, [], requestOrg ?? null, now); + await this.engine.insert('sys_approval_action', await this.actionRow(row, { + id: uid('aact'), request_id: row.id, organization_id: requestOrg ?? null, + step_name: row.current_step ?? null, step_index: 0, action: 'comment', + actor_id: null, + comment: refusedMirrorNoteText('pending', refusal.message), + created_at: now, + }), { context: SYSTEM_CTX }); + this.logger?.warn?.( + `[approvals] the approval of ${row.object_name}/${row.record_id} did not open: a rule or a hook of the app ` + + `refused its status 'pending' (${refusal.message}), so the request was voided and the run fails at this step.`, + { request: row.id, object: row.object_name, record: row.record_id, error: refusal.message }, + ); + } + + /** + * [ADR-0162 D5, Execution item 8] Report a write of the status mirror that a + * rule or a hook of the app refused, on a field the object closes on. Three + * things, each best-effort so that one failing does not hide the others: + * + * - an `error` line: the record now reads a status its approval does not + * hold, nothing else looks broken, and the fix is the app's rule or hook; + * - a line with no actor on the request's timeline, carrying the refusal's + * own message, which everyone who can read the request sees; + * - a notice to the organization's administrators, who can change the rule + * ({@link organizationAdministrators}). + */ + private async reportRefusedMirror( + object: string, + recordId: string, + field: string, + status: string, + reason: string, + about: MirrorRequestRef, + requestOrg: string | null | undefined, + ): Promise { + const request = about.request; + const requestId = String(request?.id ?? ''); + this.logger?.error?.( + `[approvals] the approval status '${status}' was NOT written to ${object}.${field} on record '${recordId}': ` + + `a validation rule, an option's visibleWhen or a hook of the app refused the write (${reason}). The object ` + + `closes on this field, so the record now reads a status its approval does not hold, and nothing else looks ` + + `broken. Change the rule or hook so that it admits the approval's status; request '${requestId}' holds the ` + + `decision, and its timeline and the organization's administrators were told.`, + undefined, + { object, record: recordId, field, value: status, request: requestId, error: reason }, + ); + const now = this.clock.now().toISOString(); + try { + await this.engine.insert('sys_approval_action', await this.actionRow(request, { + id: uid('aact'), request_id: requestId, organization_id: requestOrg ?? null, + step_name: about.step ?? request?.current_step ?? null, step_index: 0, action: 'comment', + actor_id: null, + comment: refusedMirrorNoteText(status, reason), + created_at: now, + }), { context: SYSTEM_CTX }); + } catch (err: any) { + this.logger?.warn?.('[approvals] could not note a refused status write on the request timeline', { + request: requestId, error: err?.message ?? String(err), + }); + } + try { + const admins = await this.organizationAdministrators(requestOrg); + if ('ids' in admins && admins.ids.length) { + await this.notify({ + topic: REFUSED_MIRROR_TOPIC, + organizationId: requestOrg, + audience: admins.ids, + source: { object: 'sys_approval_request', id: requestId }, + dedupKey: `approval-mirror-refused-${requestId}-${status}`, + about: { object, recordId }, + text: (subject) => approvalNotificationText({ + title: 'approvalStatusMirrorRefusedTitle', body: 'approvalStatusMirrorRefusedBody', + params: { ...subject, reason }, + }), + }); + } else if ('failure' in admins) { + this.logger?.warn?.('[approvals] could not read the organization\'s administrators to tell them of a refused status write', { + request: requestId, organizationId: requestOrg ?? null, error: admins.failure, + }); + } + } catch (err: any) { + this.logger?.warn?.('[approvals] could not tell the organization\'s administrators of a refused status write', { + request: requestId, error: err?.message ?? String(err), + }); } } @@ -5693,6 +5892,32 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega }), { context: SYSTEM_CTX }); } + // [ADR-0162 D5, Execution item 8] On a field the object closes on at + // `approved` or `rejected`, the `pending` is written here: after the row, + // which is written first, and before anyone is told of the request. At an + // approval's first request this is the one write of the mirror that takes a + // record off a closed value, and a rule or a hook of the app that refuses + // it holds: the approval does not open, the row is voided as `cancelled`, + // no lock is taken (the pending lock keys on `status: 'pending'`) and the + // run fails at this step with the refusal's own message. The other order + // could leave a decided document on `pending` with no request. At any + // later request a refusal leaves an open value on the field, and it is + // reported (`reportRefusedMirror`). Every other field is mirrored below, + // as before. + const mirrorField = input.config.approvalStatusField; + const closingMirror = !!mirrorField && this.closesOnApprovalOutcome(input.object, mirrorField); + if (closingMirror) { + const opening = await this.isFirstRequestOfApproval(row); + const refusal = await this.mirrorStatusField( + input.object, input.recordId, mirrorField!, 'pending', + row.submitter_id ?? null, requestOrg, undefined, { request: row, step: input.nodeId, opening }, + ); + if (refusal && opening) { + await this.voidRefusedOpening(row, refusal, requestOrg); + throw refusal.refused instanceof Error ? refusal.refused : new Error(refusal.message); + } + } + // OOO substitution audit + notification (#1322 M4). Each hop that rerouted // an approver away from an out-of-office user is recorded on the request's // audit trail (a system action, no human actor) and notified to both the @@ -5752,7 +5977,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega // Record lock (when `lockRecord !== false`) is enforced by the beforeUpdate // hook keyed on the now-pending request; no extra write needed here. - if (input.config.approvalStatusField) { + if (input.config.approvalStatusField && !closingMirror) { // Attributed to whoever the row itself calls the submitter (#3783), so // there is exactly one answer to "who submitted this". Not the // {@link actingUserId} route: `submitterId` is server-supplied here (the @@ -6311,7 +6536,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega if (config.approvalStatusField) { await this.mirrorStatusField( raw.object_name, raw.record_id, config.approvalStatusField, finalStatus, - actingUserId(context), org, + actingUserId(context), org, undefined, { request: raw, step: nodeId }, ); } const fresh = await this.readBackRequest(requestId, context); @@ -7109,7 +7334,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega // declare `recalled` goes back to its value at submit. await this.mirrorStatusField( raw.object_name, raw.record_id, config.approvalStatusField, 'recalled', - actingUserId(context), org, { payloadJson: raw.payload_json }, + actingUserId(context), org, { payloadJson: raw.payload_json }, { request: raw, step: nodeId }, ); } @@ -7725,7 +7950,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega if (config.approvalStatusField) { await this.mirrorStatusField( raw.object_name, raw.record_id, config.approvalStatusField, 'rejected', - actingUserId(context), org, + actingUserId(context), org, undefined, { request: raw, step: nodeId }, ); } let resumed = false; @@ -7767,7 +7992,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega if (config.approvalStatusField) { await this.mirrorStatusField( raw.object_name, raw.record_id, config.approvalStatusField, 'returned', - actingUserId(context), org, + actingUserId(context), org, undefined, { request: raw, step: nodeId }, ); } @@ -9809,7 +10034,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega // options do not declare `recalled` goes back to its value at submit. await this.mirrorStatusField( raw.object_name, raw.record_id, config.approvalStatusField, 'recalled', null, org, - { payloadJson: raw.payload_json }, + { payloadJson: raw.payload_json }, { request: raw, step: raw.current_step ?? null }, ); } diff --git a/packages/plugins/plugin-approvals/src/status-mirror-closing-field-refusal.integration.test.ts b/packages/plugins/plugin-approvals/src/status-mirror-closing-field-refusal.integration.test.ts new file mode 100644 index 00000000000..1e3e7fe96ba --- /dev/null +++ b/packages/plugins/plugin-approvals/src/status-mirror-closing-field-refusal.integration.test.ts @@ -0,0 +1,344 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 D5, Execution item 8] A write of the status mirror that a rule or a + * hook of the app refuses, on a field the object closes on, is not swallowed. + * + * The mirror writes as the system, and every control of the object still meets + * that write: a validation rule, an option's `visibleWhen` and a hook can each + * refuse it, and no reading of a definition shows when. On every field the + * mirror used to log such a refusal at `warn` and go on. On a field the object + * closes on at `approved` or `rejected` (`closedStates`), ADR-0162 D5 states + * what follows, by the write: + * + * - the `pending` of an approval's FIRST request: the approval does not open. + * The request's row, written first, is voided as `cancelled`; no lock is + * taken; the run fails at that step with the refusal's own message; the + * record keeps the value it held, a closed one included; + * - every other write: the field keeps the value it held, and the refusal is + * reported — an `error` line, a line with no actor on the request's + * timeline carrying the refusal's message, and a notice to the + * organization's administrators. + * + * Each test records the value the field keeps. The last one is the control: + * the same refusal on an object that declares no closed state is still the + * `warn` it was, and its approval opens. + * + * Real kernel, real ObjectQL engine with its validator and hooks, real + * automation engine, real approval node and record-lock hook, driver-sql on + * better-sqlite3 `:memory:`. The organization's administrators are stubbed at + * the one resolver the notice reads (`organizationAdministrators`): who holds + * that rung is pinned elsewhere (`admin-rescue-named-slate.integration.test.ts`). + */ + +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { ObjectKernel } from '@objectstack/core'; +import { ObjectQLPlugin, type ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { AutomationServicePlugin, type AutomationEngine } from '@objectstack/service-automation'; +import { APPROVAL_REVISE_NODE_TYPE } from '@objectstack/spec/automation'; +import { ApprovalService } from './approval-service.js'; +import { registerApprovalNode } from './approval-node.js'; +import { bindApprovalLockHook } from './lifecycle-hooks.js'; +import { SysApprovalRequest } from './sys-approval-request.object.js'; +import { SysApprovalAction } from './sys-approval-action.object.js'; +import { SysApprovalApprover } from './sys-approval-approver.object.js'; +import { SysApprovalDelegation } from './sys-approval-delegation.object.js'; +import { SysApprovalToken } from './sys-approval-token.object.js'; + +const ORG = 'org_default'; +const SYS = { isSystem: true } as const; +const asPerson = (userId: string) => ({ userId, positions: [], permissions: [] }) as any; + +const text = (name: string) => ({ name, type: 'text' as const }); +const PLATFORM_GLOBAL = { enabled: false }; +const authzObjects = [ + { owner: '@objectstack/plugin-auth', def: { name: 'sys_user', label: 'User', tenancy: PLATFORM_GLOBAL, fields: { id: { ...text('id'), primaryKey: true }, email: text('email') } } }, + { owner: '@objectstack/plugin-auth', def: { name: 'sys_member', label: 'Member', tenancy: PLATFORM_GLOBAL, fields: { id: { ...text('id'), primaryKey: true }, user_id: text('user_id'), organization_id: text('organization_id'), role: text('role') } } }, + { owner: '@objectstack/plugin-security', def: { name: 'sys_user_position', label: 'User Position', tenancy: PLATFORM_GLOBAL, fields: { id: { ...text('id'), primaryKey: true }, user_id: text('user_id'), position: text('position'), organization_id: text('organization_id') } } }, + { owner: '@objectstack/plugin-security', def: { name: 'sys_user_permission_set', label: 'User Permission Set', tenancy: PLATFORM_GLOBAL, fields: { id: { ...text('id'), primaryKey: true }, user_id: text('user_id'), permission_set: text('permission_set'), organization_id: text('organization_id') } } }, +] as const; + +/** + * The status field, with the three controls of the app that can refuse the + * mirror's write, each armed by the record's own `block` field: + * - a `script` validation rule refuses the status `block` names; + * - the `draft` option's `visibleWhen` hides it while `block` is `draft`; + * - a hook (bound in `beforeEach`) refuses a status in {@link hookRefuses}. + * `recalled` is not declared, so an abandoned request puts the value at submit + * back. + */ +const statusField = { + name: 'approval_status', type: 'select' as const, defaultValue: 'draft', + options: [ + { label: 'Draft', value: 'draft', visibleWhen: '!has(record.block) || record.block == null || record.block != "draft"' }, + ...['pending', 'approved', 'rejected', 'returned'].map((value) => ({ label: value, value })), + ], +}; +const blockRule = { + type: 'script' as const, name: 'blocked_status', message: 'This status is blocked by a rule of the app.', + condition: 'has(record.block) && record.block != null && record.approval_status == record.block', +}; +const invoiceFields = { name: text('name'), note: text('note'), block: text('block'), approval_status: statusField }; +/** Closes on its approval's outcome (ADR-0162 D1). */ +const invoice = { name: 'crm_invoice', label: 'Invoice', fields: invoiceFields, validations: [blockRule], closedStates: { approval_status: ['approved'] } }; +/** The same object, declaring no closed state: the control. */ +const memo = { name: 'crm_memo', label: 'Memo', fields: invoiceFields, validations: [blockRule] }; + +const step = (id: string, approver: string) => ({ + id, type: 'approval', label: id, + config: { approvers: [{ type: 'user', value: approver }], lockRecord: true, approvalStatusField: 'approval_status' }, +}); +/** One step, with a revise window so a send-back can be resubmitted (ADR-0044). */ +const oneStep = { + name: 'one_step', label: 'One step', type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + step('review', 'approver'), + { 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 twoStep = { + name: 'two_step', label: 'Two steps', type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + step('first', 'approver'), + step('second', 'approver2'), + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'first' }, + { id: 'e2', source: 'first', target: 'second', label: 'approve' }, + { id: 'e3', source: 'first', target: 'end', label: 'reject' }, + { id: 'e4', source: 'second', target: 'end', label: 'approve' }, + { id: 'e5', source: 'second', target: 'end', label: 'reject' }, + ], +}; + +const HOOK_REFUSAL = 'The hook refuses this status.'; + +describe('[ADR-0162 item 8] a refused write of the status mirror on a field the object closes on', () => { + let kernel: ObjectKernel; + let ql: ObjectQL; + let automation: AutomationEngine; + let svc: ApprovalService; + let hookRefuses: Set; + let logs: Array<{ level: string; message: string; meta: any }>; + let emits: Array<{ topic: string; audience: string[]; source?: { object: string; id: string }; payload?: any }>; + + afterEach(async () => { + try { await kernel?.shutdown(); } catch { /* noop */ } + }); + + beforeEach(async () => { + kernel = new ObjectKernel({ logger: { level: 'silent' } } as any); + await kernel.use(new ObjectQLPlugin()); + await kernel.use(new AutomationServicePlugin()); + await kernel.bootstrap(); + ql = kernel.getService('objectql'); + automation = kernel.getService('automation'); + + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); + await driver.connect(); + ql.registerDriver(driver, true); + for (const def of [invoice, memo, SysApprovalRequest, SysApprovalAction, SysApprovalApprover, SysApprovalDelegation, SysApprovalToken]) { + ql.registry.registerObject(def as any, 'approvals-test', 'approvals-test'); + } + for (const o of authzObjects) ql.registry.registerObject(o.def as any, o.owner); + ql.registry.registerObject( + { name: 'sys_organization', label: 'Organization', managedBy: 'better-auth', fields: { name: text('name'), slug: text('slug') } } as any, + '@objectstack/plugin-auth', + ); + await ql.syncSchemas(); + await ql.insert('sys_organization', { id: ORG, name: 'Default Organization', slug: 'default' }, { context: SYS }); + for (const id of ['owner', 'approver', 'approver2']) { + await ql.insert('sys_user', { id, email: `${id}@example.test` }, { context: SYS }); + await ql.insert('sys_member', { id: `mem_${id}`, user_id: id, organization_id: ORG, role: 'member' }, { context: SYS }); + } + + hookRefuses = new Set(); + for (const object of ['crm_invoice', 'crm_memo']) { + ql.registerHook('beforeUpdate', async (ctx: any) => { + const status = (ctx.input?.data ?? {}).approval_status; + if (typeof status === 'string' && hookRefuses.has(status)) throw new Error(HOOK_REFUSAL); + }, { object }); + } + + logs = []; + const record = (level: string) => (message: unknown, a?: unknown, b?: unknown) => { + logs.push({ level, message: String(message), meta: level === 'error' ? b : a }); + }; + const logger = { debug: () => {}, info: () => {}, warn: record('warn'), error: record('error') }; + emits = []; + svc = new ApprovalService({ + engine: ql, logger: logger as any, + messaging: { emit: async (e: any) => { emits.push(e); } } as any, + }); + (svc as any).organizationAdministrators = async (org: unknown) => ({ ids: org === ORG ? ['org_admin'] : [] }); + svc.attachAutomation(automation as any); + registerApprovalNode(automation as any, svc, logger as any); + bindApprovalLockHook(ql as any, logger as any); + automation.registerFlow(oneStep.name, oneStep as any); + automation.registerFlow(twoStep.name, twoStep as any); + }); + + const read = async (object: string, id: string) => (await ql.find(object, { where: { id }, context: SYS }))[0]; + const field = async (object: string, id: string) => (await read(object, id))?.approval_status; + const requestsOn = async (id: string) => + (await ql.find('sys_approval_request', { where: { record_id: id }, orderBy: [{ field: 'created_at', order: 'asc' }], context: SYS })) + .map((r: any) => ({ id: String(r.id), step: String(r.flow_node_id), status: String(r.status) })); + const timelineNotes = async (requestId: string) => + (await ql.find('sys_approval_action', { where: { request_id: requestId, action: 'comment' }, context: SYS })) + .map((r: any) => ({ actor: r.actor_id ?? null, comment: String(r.comment) })); + const inboxRows = async (requestId: string) => ql.find('sys_approval_approver', { where: { request_id: requestId }, context: SYS }); + const seed = (object: string, id: string, extra: Record = {}) => + ql.insert(object, { id, name: id, organization_id: ORG, ...extra }, { context: { isSystem: true, tenantId: ORG } }); + const start = async (flow: string, object: string, id: string) => + automation.execute(flow, { object, record: await read(object, id), userId: 'owner' } as any) as Promise; + const open = async (flow: string, object: string, id: string) => { + const out = await start(flow, object, id); + expect(out.status, JSON.stringify(out)).toBe('paused'); + const pending = (await requestsOn(id)).filter((r) => r.status === 'pending'); + expect(pending).toHaveLength(1); + return pending[0].id; + }; + const errors = () => logs.filter((l) => l.level === 'error'); + const notices = () => emits.filter((e) => e.topic === 'approval.status_mirror_refused'); + /** The three parts of a report, for one refused write. */ + async function expectReported(object: string, id: string, requestId: string, status: string, reason: string) { + expect(errors().map((l) => l.meta), 'one error line, naming the write').toEqual([ + expect.objectContaining({ object, record: id, field: 'approval_status', value: status, request: requestId }), + ]); + expect(errors()[0].message).toContain('NOT written'); + expect(errors()[0].message, 'it names the fix').toContain('Change the rule or hook'); + expect(await timelineNotes(requestId), "a line with no actor, carrying the refusal's own message").toContainEqual({ + actor: null, comment: expect.stringContaining(reason), + }); + expect(notices().map((e) => ({ audience: e.audience, source: e.source })), "a notice to the organization's administrators") + .toEqual([{ audience: ['org_admin'], source: { object: 'sys_approval_request', id: requestId } }]); + } + + describe("the `pending` of an approval's first request", () => { + it('a validation rule refuses it: the approval does not open, the row is voided, the run fails with the rule\'s message, and the field keeps `draft`', async () => { + await seed('crm_invoice', 'i_rule', { block: 'pending' }); + + const out = await start('one_step', 'crm_invoice', 'i_rule'); + + expect(out.status).toBe('failed'); + expect(JSON.stringify(out), "the run fails with the refusal's own message").toContain(blockRule.message); + const [voided] = await requestsOn('i_rule'); + expect(await requestsOn('i_rule')).toEqual([{ id: voided.id, step: 'review', status: 'cancelled' }]); + expect(await field('crm_invoice', 'i_rule'), 'the value the field keeps').toBe('draft'); + expect(await inboxRows(voided.id), "nobody's inbox lists it").toEqual([]); + expect(await timelineNotes(voided.id)).toContainEqual({ actor: null, comment: expect.stringContaining(blockRule.message) }); + // No lock was taken: the owner edits the record at once. + await expect(ql.update('crm_invoice', { id: 'i_rule', note: 'edited' }, { context: asPerson('owner') })).resolves.toBeTruthy(); + // The submitter was told by the run's failure; nothing was lost, so this is no durability error. + expect(errors()).toEqual([]); + expect(notices()).toEqual([]); + }); + + it('a hook refuses it on a record closed on its last approval: the record stays closed on `approved`', async () => { + await seed('crm_invoice', 'i_closed', { approval_status: 'approved' }); + hookRefuses.add('pending'); + + const out = await start('one_step', 'crm_invoice', 'i_closed'); + + expect(out.status).toBe('failed'); + expect(JSON.stringify(out)).toContain(HOOK_REFUSAL); + expect((await requestsOn('i_closed')).map((r) => r.status)).toEqual(['cancelled']); + expect(await field('crm_invoice', 'i_closed'), 'the value the field keeps').toBe('approved'); + }); + + it('a later submission of the same record, once the rule admits it, opens a new approval', async () => { + await seed('crm_invoice', 'i_again', { block: 'pending' }); + expect((await start('one_step', 'crm_invoice', 'i_again')).status).toBe('failed'); + await ql.update('crm_invoice', { id: 'i_again', block: null }, { context: SYS }); + + await open('one_step', 'crm_invoice', 'i_again'); + + expect((await requestsOn('i_again')).map((r) => r.status)).toEqual(['cancelled', 'pending']); + expect(await field('crm_invoice', 'i_again')).toBe('pending'); + }); + }); + + it("a later request's `pending` refused: the request stays open, the refusal is reported, and the field keeps `approved`", async () => { + await seed('crm_invoice', 'i_later'); + const first = await open('two_step', 'crm_invoice', 'i_later'); + hookRefuses.add('pending'); + + await svc.decide(first, { decision: 'approve', actorId: 'approver' } as any, asPerson('approver')); + + const [, second] = await requestsOn('i_later'); + expect(await requestsOn('i_later')).toEqual([ + { id: first, step: 'first', status: 'approved' }, + { id: second.id, step: 'second', status: 'pending' }, + ]); + // The outcome is still written at each decision on this branch; holding it + // back until the approval is over is the next piece of the item. + expect(await field('crm_invoice', 'i_later'), 'the value the field keeps').toBe('approved'); + await expectReported('crm_invoice', 'i_later', second.id, 'pending', HOOK_REFUSAL); + }); + + it('the decision refused by a hook: the request is approved, the refusal is reported, and the field keeps `pending`', async () => { + await seed('crm_invoice', 'i_decide'); + const request = await open('one_step', 'crm_invoice', 'i_decide'); + hookRefuses.add('approved'); + + await svc.decide(request, { decision: 'approve', actorId: 'approver' } as any, asPerson('approver')); + + expect((await requestsOn('i_decide')).map((r) => r.status)).toEqual(['approved']); + expect(await field('crm_invoice', 'i_decide'), 'the value the field keeps').toBe('pending'); + await expectReported('crm_invoice', 'i_decide', request, 'approved', HOOK_REFUSAL); + expect(notices()[0].payload, 'the notice is about the record').toBeTruthy(); + }); + + it('the put-back of a recall refused by the `visibleWhen` of the value it puts back: the field keeps `pending`', async () => { + await seed('crm_invoice', 'i_recall'); + const request = await open('one_step', 'crm_invoice', 'i_recall'); + await ql.update('crm_invoice', { id: 'i_recall', block: 'draft' }, { context: SYS }); + + await svc.recall(request, { actorId: 'owner' } as any, asPerson('owner')); + + expect((await requestsOn('i_recall')).map((r) => r.status)).toEqual(['recalled']); + expect(await field('crm_invoice', 'i_recall'), 'the value the field keeps').toBe('pending'); + expect(errors()).toHaveLength(1); + expect(errors()[0].meta).toMatchObject({ object: 'crm_invoice', record: 'i_recall', value: 'recalled', request }); + expect(await timelineNotes(request)).toHaveLength(1); + expect(notices()).toHaveLength(1); + }); + + it('a send-back refused by a validation rule: the field keeps `pending`, and the refusal is reported', async () => { + await seed('crm_invoice', 'i_back'); + const request = await open('one_step', 'crm_invoice', 'i_back'); + await ql.update('crm_invoice', { id: 'i_back', block: 'returned' }, { context: SYS }); + + await svc.sendBack(request, { actorId: 'approver' } as any, asPerson('approver')); + + expect((await requestsOn('i_back')).map((r) => r.status)).toEqual(['returned']); + expect(await field('crm_invoice', 'i_back'), 'the value the field keeps').toBe('pending'); + await expectReported('crm_invoice', 'i_back', request, 'returned', blockRule.message); + }); + + it('CONTROL — the same refusal on an object that declares no closed state is the `warn` it was, and the approval opens', async () => { + await seed('crm_memo', 'm_rule', { block: 'pending' }); + + await open('one_step', 'crm_memo', 'm_rule'); + + expect((await requestsOn('m_rule')).map((r) => r.status)).toEqual(['pending']); + expect(await field('crm_memo', 'm_rule'), 'the value the field keeps').toBe('draft'); + expect(logs.filter((l) => l.level === 'warn' && l.message.includes('mirrorStatusField failed'))).toHaveLength(1); + expect(errors()).toEqual([]); + const [request] = await requestsOn('m_rule'); + expect(await timelineNotes(request.id)).toEqual([]); + expect(notices()).toEqual([]); + }); +}); diff --git a/packages/plugins/plugin-approvals/src/translations/messages.ts b/packages/plugins/plugin-approvals/src/translations/messages.ts index 7f8b399c79d..a95b39cd32a 100644 --- a/packages/plugins/plugin-approvals/src/translations/messages.ts +++ b/packages/plugins/plugin-approvals/src/translations/messages.ts @@ -120,6 +120,8 @@ const enSentences = { approvalReminderBody: 'A decision on {{object}} {{record}} is still waiting on you.', approvalSlaBreachedTitle: 'Approval SLA breached', approvalSlaBreachedBody: 'A decision on {{object}} {{record}} is overdue.', + approvalStatusMirrorRefusedTitle: 'Approval status not written', + approvalStatusMirrorRefusedBody: 'The approval status of {{object}} {{record}} was refused by a rule or hook of the app: {{reason}} Change that rule or hook so the status can be written.', approvalSlaBreachedSubmitterTitle: 'Your approval request breached its SLA', approvalSlaBreachedSubmitterBody: "{{object}} {{record}}: escalation action '{{action}}' was taken.", approvalApprovedTitle: 'Request approved', @@ -253,6 +255,8 @@ export const zhCNMessages: ApprovalMessages = { approvalReminderBody: '{{object}} {{record}} 仍在等待您的审批决定。', approvalSlaBreachedTitle: '审批已超出时限', approvalSlaBreachedBody: '{{object}} {{record}} 的审批决定已逾期。', + approvalStatusMirrorRefusedTitle: '审批状态未能写入', + approvalStatusMirrorRefusedBody: '{{object}} {{record}} 的审批状态被应用自己的规则或钩子拒绝:{{reason}} 请修改该规则或钩子,使状态可以写入。', approvalSlaBreachedSubmitterTitle: '您的审批请求已超出时限', approvalSlaBreachedSubmitterBody: '{{object}} {{record}}:已执行升级操作「{{action}}」。', approvalApprovedTitle: '请求已批准', @@ -323,6 +327,8 @@ export const jaJPMessages: ApprovalMessages = { approvalReminderBody: '{{object}} {{record}} について、引き続きあなたの承認判断をお待ちしています。', approvalSlaBreachedTitle: '承認の期限超過', approvalSlaBreachedBody: '{{object}} {{record}} の承認判断が期限を過ぎています。', + approvalStatusMirrorRefusedTitle: '承認ステータスを書き込めませんでした', + approvalStatusMirrorRefusedBody: '{{object}} {{record}} の承認ステータスは、アプリのルールまたはフックに拒否されました:{{reason}} ステータスを書き込めるよう、そのルールまたはフックを変更してください。', approvalSlaBreachedSubmitterTitle: 'あなたの承認申請が期限を超過しました', approvalSlaBreachedSubmitterBody: '{{object}} {{record}}:エスカレーション操作「{{action}}」が実行されました。', approvalApprovedTitle: '申請が承認されました', @@ -393,6 +399,8 @@ export const esESMessages: ApprovalMessages = { approvalReminderBody: 'Una decisión sobre {{object}} {{record}} sigue pendiente de usted.', approvalSlaBreachedTitle: 'Plazo de aprobación incumplido', approvalSlaBreachedBody: 'La decisión sobre {{object}} {{record}} está vencida.', + approvalStatusMirrorRefusedTitle: 'No se escribió el estado de aprobación', + approvalStatusMirrorRefusedBody: 'Una regla o un hook de la aplicación rechazó el estado de aprobación de {{object}} {{record}}: {{reason}} Cambie esa regla o ese hook para que el estado pueda escribirse.', approvalSlaBreachedSubmitterTitle: 'Su solicitud de aprobación ha superado su plazo', approvalSlaBreachedSubmitterBody: "{{object}} {{record}}: se ha ejecutado la acción de escalado '{{action}}'.", approvalApprovedTitle: 'Solicitud aprobada', @@ -463,6 +471,8 @@ export const zhHantMessages: ApprovalMessages = { approvalReminderBody: '{{object}} {{record}} 仍在等待你的核准決定。', approvalSlaBreachedTitle: '核准已逾時', approvalSlaBreachedBody: '{{object}} {{record}} 的核准決定已逾期。', + approvalStatusMirrorRefusedTitle: '核准狀態未能寫入', + approvalStatusMirrorRefusedBody: '{{object}} {{record}} 的核准狀態被應用程式自己的規則或掛鉤拒絕:{{reason}} 請修改該規則或掛鉤,讓狀態可以寫入。', approvalSlaBreachedSubmitterTitle: '你的核准請求已逾時', approvalSlaBreachedSubmitterBody: '{{object}} {{record}}:已執行升級動作「{{action}}」。', approvalApprovedTitle: '請求已核准', @@ -533,6 +543,8 @@ export const arMessages: ApprovalMessages = { approvalReminderBody: 'قرار بشأن {{object}} {{record}} لا يزال بانتظارك.', approvalSlaBreachedTitle: 'تجاوزت الموافقة مهلتها', approvalSlaBreachedBody: 'القرار بشأن {{object}} {{record}} متأخر.', + approvalStatusMirrorRefusedTitle: 'لم تُكتب حالة الموافقة', + approvalStatusMirrorRefusedBody: 'رفضت قاعدة أو خطّاف في التطبيق حالة الموافقة على {{object}} {{record}}: {{reason}} غيّر تلك القاعدة أو ذلك الخطّاف لكي تُكتب الحالة.', approvalSlaBreachedSubmitterTitle: 'تجاوز طلب الموافقة الخاص بك مهلته', approvalSlaBreachedSubmitterBody: '{{object}} {{record}}: نُفِّذ إجراء التصعيد «{{action}}».', approvalApprovedTitle: 'تمت الموافقة على الطلب', @@ -603,6 +615,8 @@ export const frMessages: ApprovalMessages = { approvalReminderBody: 'Une décision sur {{object}} {{record}} vous attend toujours.', approvalSlaBreachedTitle: 'Délai d’approbation dépassé', approvalSlaBreachedBody: 'La décision sur {{object}} {{record}} est en retard.', + approvalStatusMirrorRefusedTitle: 'Statut d’approbation non écrit', + approvalStatusMirrorRefusedBody: 'Une règle ou un hook de l’application a refusé le statut d’approbation de {{object}} {{record}} : {{reason}} Modifiez cette règle ou ce hook pour que le statut puisse être écrit.', approvalSlaBreachedSubmitterTitle: 'Votre demande d’approbation a dépassé son délai', approvalSlaBreachedSubmitterBody: '{{object}} {{record}} : l’action d’escalade « {{action}} » a été exécutée.', approvalApprovedTitle: 'Demande approuvée', @@ -673,6 +687,8 @@ export const ptBRMessages: ApprovalMessages = { approvalReminderBody: 'Uma decisão sobre {{object}} {{record}} ainda está aguardando você.', approvalSlaBreachedTitle: 'Prazo de aprovação estourado', approvalSlaBreachedBody: 'A decisão sobre {{object}} {{record}} está atrasada.', + approvalStatusMirrorRefusedTitle: 'Status de aprovação não gravado', + approvalStatusMirrorRefusedBody: 'Uma regra ou um hook do aplicativo recusou o status de aprovação de {{object}} {{record}}: {{reason}} Altere essa regra ou esse hook para que o status possa ser gravado.', approvalSlaBreachedSubmitterTitle: 'Sua solicitação de aprovação estourou o prazo', approvalSlaBreachedSubmitterBody: '{{object}} {{record}}: a ação de escalonamento "{{action}}" foi executada.', approvalApprovedTitle: 'Solicitação aprovada', @@ -743,6 +759,8 @@ export const ruMessages: ApprovalMessages = { approvalReminderBody: 'Решение по {{object}} {{record}} всё ещё ждёт вас.', approvalSlaBreachedTitle: 'Срок согласования нарушен', approvalSlaBreachedBody: 'Решение по {{object}} {{record}} просрочено.', + approvalStatusMirrorRefusedTitle: 'Статус согласования не записан', + approvalStatusMirrorRefusedBody: 'Правило или хук приложения отклонили статус согласования для {{object}} {{record}}: {{reason}} Измените это правило или хук, чтобы статус можно было записать.', approvalSlaBreachedSubmitterTitle: 'Ваш запрос на согласование нарушил срок', approvalSlaBreachedSubmitterBody: '{{object}} {{record}}: выполнено действие эскалации «{{action}}».', approvalApprovedTitle: 'Запрос одобрен', @@ -813,6 +831,8 @@ export const deMessages: ApprovalMessages = { approvalReminderBody: 'Eine Entscheidung zu {{object}} {{record}} wartet noch auf Sie.', approvalSlaBreachedTitle: 'Genehmigungsfrist überschritten', approvalSlaBreachedBody: 'Die Entscheidung zu {{object}} {{record}} ist überfällig.', + approvalStatusMirrorRefusedTitle: 'Genehmigungsstatus nicht geschrieben', + approvalStatusMirrorRefusedBody: 'Eine Regel oder ein Hook der App hat den Genehmigungsstatus von {{object}} {{record}} abgelehnt: {{reason}} Ändern Sie diese Regel oder diesen Hook, damit der Status geschrieben werden kann.', approvalSlaBreachedSubmitterTitle: 'Ihre Genehmigungsanfrage hat ihre Frist überschritten', approvalSlaBreachedSubmitterBody: '{{object}} {{record}}: Die Eskalationsaktion „{{action}}“ wurde ausgeführt.', approvalApprovedTitle: 'Anfrage genehmigt', @@ -883,6 +903,8 @@ export const koMessages: ApprovalMessages = { approvalReminderBody: '{{object}} {{record}}에 대한 결정이 아직 회원님을 기다리고 있습니다.', approvalSlaBreachedTitle: '승인 기한 초과', approvalSlaBreachedBody: '{{object}} {{record}}에 대한 결정이 기한을 넘겼습니다.', + approvalStatusMirrorRefusedTitle: '승인 상태를 기록하지 못했습니다', + approvalStatusMirrorRefusedBody: '앱의 규칙 또는 훅이 {{object}} {{record}}의 승인 상태를 거부했습니다: {{reason}} 상태를 기록할 수 있도록 해당 규칙 또는 훅을 변경하세요.', approvalSlaBreachedSubmitterTitle: '승인 요청이 기한을 넘겼습니다', approvalSlaBreachedSubmitterBody: "{{object}} {{record}}: 에스컬레이션 작업 '{{action}}'이(가) 실행되었습니다.", approvalApprovedTitle: '요청 승인됨', diff --git a/packages/services/service-messaging/src/preference-options.ts b/packages/services/service-messaging/src/preference-options.ts index 01e45087c3e..f5d9b3fde07 100644 --- a/packages/services/service-messaging/src/preference-options.ts +++ b/packages/services/service-messaging/src/preference-options.ts @@ -63,6 +63,7 @@ export const PLATFORM_NOTIFICATION_TOPICS: readonly string[] = [ 'approval.requested', 'approval.returned', 'approval.sla_breached', + 'approval.status_mirror_refused', 'auth.phone_invite', 'auth.phone_otp', 'collab.mention', From bda8482bfe37573f720a0ad109da95112138610a Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 01:48:54 +0000 Subject: [PATCH 09/32] chore(approvals): regenerate the tenant-audit census and the engine-double ledger for the refused-mirror writes and the readings pins Claude-Session: https://claude.ai/code/session_01L6bhgX7z5dcSkTqEAWNMsP Co-authored-by: Claude --- .../plugins/plugin-approvals.md | 18 +++++++++--------- scripts/engine-double-contract.pinned.json | 10 ++++++++++ 2 files changed, 19 insertions(+), 9 deletions(-) diff --git a/docs/audits/2026-08-tenant-audit-write-call-sites.counts/plugins/plugin-approvals.md b/docs/audits/2026-08-tenant-audit-write-call-sites.counts/plugins/plugin-approvals.md index 9944d4a929d..b3808a404c1 100644 --- a/docs/audits/2026-08-tenant-audit-write-call-sites.counts/plugins/plugin-approvals.md +++ b/docs/audits/2026-08-tenant-audit-write-call-sites.counts/plugins/plugin-approvals.md @@ -14,24 +14,24 @@ a row or a number here — fix the code, or the census, and regenerate. | Measure | Value | |---|---:| -| Write call sites | 42 | -| Object name statically decidable | 40 | +| Write call sites | 45 | +| Object name statically decidable | 43 | | Object name chosen at run time | 2 | -| Object name spelled inline | 38 | +| Object name spelled inline | 41 | | Object name spelled through a `const` | 2 | | Object name is an `object: string` parameter | 1 | | Object name is some other run-time expression | 1 | -| Against a tenancy-enabled object | 40 | +| Against a tenancy-enabled object | 43 | | Against an object declaring tenancy off | 0 | -| Threading a tenant context | 42 | +| Threading a tenant context | 45 | | Provably carrying none (options read, no context key) | 0 | | …and decidably tenancy-enabled | 0 | | Options argument unreadable | 0 | | …and decidably tenancy-enabled | 0 | -| Threading a decidably elevated (`isSystem`) context | 40 | +| Threading a decidably elevated (`isSystem`) context | 43 | | Threading a decidably non-elevated context | 0 | | Threading a context of undecidable elevation | 2 | -| Receiver carried a readable engine type | 42 | +| Receiver carried a readable engine type | 45 | | Receiver erased, placed by the object NAME | 0 | | Receiver erased, placed by an `object: string` PARAMETER | 0 | | Receiver erased, placed by an `UNTYPED_RECEIVERS` row | 0 | @@ -50,11 +50,11 @@ a row or a number here — fix the code, or the census, and regenerate. | `packages/plugins/plugin-approvals/src/action-slot-backfill.ts` | `update` | `sys_approval_action` | enabled | elevated | 2 | | `packages/plugins/plugin-approvals/src/approval-activity-feed.ts` | `insert` | `sys_activity` | enabled | elevated | 1 | | `packages/plugins/plugin-approvals/src/approval-service.ts` | `update` | `object` | undecidable | context, elevation undecidable | 1 | -| `packages/plugins/plugin-approvals/src/approval-service.ts` | `insert` | `sys_approval_action` | enabled | elevated | 17 | +| `packages/plugins/plugin-approvals/src/approval-service.ts` | `insert` | `sys_approval_action` | enabled | elevated | 19 | | `packages/plugins/plugin-approvals/src/approval-service.ts` | `delete` | `sys_approval_approver` | enabled | elevated | 2 | | `packages/plugins/plugin-approvals/src/approval-service.ts` | `insert` | `sys_approval_approver` | enabled | elevated | 2 | | `packages/plugins/plugin-approvals/src/approval-service.ts` | `insert` | `sys_approval_request` | enabled | elevated | 1 | -| `packages/plugins/plugin-approvals/src/approval-service.ts` | `update` | `sys_approval_request` | enabled | elevated | 10 | +| `packages/plugins/plugin-approvals/src/approval-service.ts` | `update` | `sys_approval_request` | enabled | elevated | 11 | | `packages/plugins/plugin-approvals/src/approval-service.ts` | `insert` | `sys_approval_token` | enabled | elevated | 1 | | `packages/plugins/plugin-approvals/src/approval-service.ts` | `update` | `sys_approval_token` | enabled | elevated | 1 | | `packages/plugins/plugin-approvals/src/backfill-platform-row-organizations.ts` | `update` | `objectPlan.object` | undecidable | context, elevation undecidable | 1 | diff --git a/scripts/engine-double-contract.pinned.json b/scripts/engine-double-contract.pinned.json index 41792ad5941..37a689920f6 100644 --- a/scripts/engine-double-contract.pinned.json +++ b/scripts/engine-double-contract.pinned.json @@ -3651,6 +3651,16 @@ "verb": "delete", "pinned": 1 }, + { + "file": "packages/plugins/plugin-approvals/src/approval-mirror-unfinished-readings.test.ts", + "verb": "delete", + "pinned": 1 + }, + { + "file": "packages/plugins/plugin-approvals/src/approval-mirror-unfinished-readings.test.ts", + "verb": "update", + "pinned": 1 + }, { "file": "packages/plugins/plugin-approvals/src/approval-positions-name-authority.test.ts", "verb": "delete", From 0c234abfe5fd5f1a187ef1adb817f40a5209160f Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 02:08:59 +0000 Subject: [PATCH 10/32] feat(objectql): a record in a closed state, and its lines, are closed to change (ADR-0162 D2-D7, D10) Every write a system context does not make is judged against the stored row: an update or delete of a closed record, and a line create, update, delete or move under a closed master, are refused 409 RECORD_LOCKED. A many-row write is refused whole before any row is written, by one existence probe or the write's one read of its matched rows under the per-row ceiling. A cascade that reaches a closed record removes no row; a restore under a live closed master is refused. The lock runs after the middleware gates and before the before-hooks. Claude-Session: https://claude.ai/code/session_01L6bhgTCFhayR5cBZXM7XPP Co-authored-by: Claude --- packages/objectql/src/closed-state-lock.ts | 578 +++++++++++++++++ packages/objectql/src/closed-state-values.ts | 23 + .../objectql/src/engine-cascade-planning.ts | 10 +- .../src/engine-delete-and-aggregate.ts | 41 +- packages/objectql/src/engine-insert.ts | 16 +- packages/objectql/src/engine-update.ts | 57 +- packages/objectql/src/engine.ts | 8 +- .../federated-injected-column-readers.test.ts | 7 + packages/objectql/src/recycle-bin/restore.ts | 13 +- .../qa/dogfood/test/closed-state-lock.test.ts | 587 ++++++++++++++++++ 10 files changed, 1311 insertions(+), 29 deletions(-) create mode 100644 packages/objectql/src/closed-state-lock.ts create mode 100644 packages/objectql/src/closed-state-values.ts create mode 100644 packages/qa/dogfood/test/closed-state-lock.test.ts diff --git a/packages/objectql/src/closed-state-lock.ts b/packages/objectql/src/closed-state-lock.ts new file mode 100644 index 00000000000..9f5957017b5 --- /dev/null +++ b/packages/objectql/src/closed-state-lock.ts @@ -0,0 +1,578 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 D2 to D7, D10] The closed-state lock: the engine's judgement of a + * write that reaches a CLOSED record, or a line of one. + * + * ## What is closed (D2) + * + * An object declares `closedStates` (`packages/spec/src/data/object.zod.ts`): + * a map from one of its single-value `select` fields to the values of it that + * close a record. A record is closed when, for at least one named field, the + * STORED value is one of the listed ones. Nothing is stored for it: every + * judgement below reads the row as the store holds it when the write reaches + * it, inside the write's own unit of work (the driver options each read is + * given carry the open transaction). + * + * ## The unit (D3) + * + * The record and every row that points at it through a `master_detail` field, + * one level deep. A line under two masters is a line of both. Lookups and + * satellite objects are not in the unit. {@link closedStateUnitOf} reads it off + * the registry; an object that neither declares the key nor is a line of one + * that does answers `undefined`, and its writes read nothing extra (D10). + * + * ## Who is bound (D5) + * + * Every write not made in a system context, a write with no context at all + * included ({@link boundByClosedStates}). No grant opens a closed record, and + * the state field is frozen with the rest. + * + * ## What is refused (D4) + * + * | Write | closed record | line of a closed record | + * |---|---|---| + * | create | not judged | refused | + * | update | refused | refused | + * | delete | refused | refused | + * | move a line | — | refused when either end is closed | + * + * An update is judged by the keys it carries: one with no key writes nothing + * and is not refused. A many-row write is refused whole before any row is + * written. Three cases cannot be judged and are refused: + * - a predicate write on a store that cannot run the line probe, whose + * matched rows pass the engine's per-row ceiling; + * - a line write that names its master by something that is not one id; + * - a read of the state that fails. + * + * ## Where it runs (D10) + * + * In the engine's write path, inside the executor the middleware chain calls, + * so after the object-permission and row-access gates have answered, and + * before the before-phase hooks. A master the write NAMES is consulted only + * when the caller's own read door returns it (otherwise the reference gate + * refuses the write in its own words, later). A master the stored row already + * hangs under is judged on its stored state, whoever the writer is: that read + * is the engine's, above the writer's grants and inside its organization scope. + * + * ## The refusal + * + * `409 RECORD_LOCKED`, the code the pending-approval lock already answers + * with. The sentence family a person reads (ADR-0162 D8) is the message + * catalog's; the `message` here is the developer's and carries no record id + * and no state value. + */ + +import { MAX_BULK_PER_ROW_HOOK_ROWS, ReadableIds, type FilterCondition } from '@objectstack/spec/data'; +import { postureEnforcesWall, type TenancyPosture } from '@objectstack/spec/security'; +import type { ExecutionContext } from '@objectstack/spec/kernel'; +import { isDriverTenantScopedSchema } from './engine-driver-options.js'; +import { isFederatedObject } from './federated-object.js'; +import { driverCompilesReadableIdsLeaf } from './relation-semi-join.js'; +import { closedValuesOf, type ClosedValues } from './closed-state-values.js'; + +export { closedValuesOf, type ClosedValues }; + +/** The code every closed-state refusal carries. */ +export const CLOSED_STATE_LOCK_CODE = 'RECORD_LOCKED'; + +/** A `master_detail` edge from a line object to a master that declares closed states. */ +export interface ClosedMasterEdge { + /** The line's foreign-key column. */ + readonly fk: string; + /** The master object's resolved name. */ + readonly master: string; + /** The master's closed values. */ + readonly closed: ClosedValues; +} + +/** What the lock reads off the registry for one object. */ +export interface ClosedStateUnit { + /** The object's own closed values, when it declares the key. */ + readonly own: ClosedValues | undefined; + /** Every `master_detail` edge to a master that declares the key. */ + readonly masters: readonly ClosedMasterEdge[]; +} + +/** The engine members the lock reads. */ +export interface ClosedStateLockHost { + readonly _registry: { getObject(name: string): unknown }; + resolveObjectName(name: string): string; + getDriver(object: string): any; + buildDriverOptions(object: string, context: ExecutionContext | undefined, base?: any, extra?: any): any; + masterDetailHeadersCallerReads(master: string, ids: ReadonlyArray, context: ExecutionContext | undefined): Promise>; + resolveEnginePosture(): TenancyPosture; +} + +/** The verbs a refusal names. */ +export type ClosedStateWriteVerb = 'update' | 'delete' | 'create' | 'restore'; + +/** Why a write was refused. */ +export type ClosedStateRefusalReason = + /** The record itself is closed. */ + | 'record_closed' + /** The row is a line of a closed record (or moves into or out of one). */ + | 'master_closed' + /** A delete's cascade reaches a closed record or a line of one. */ + | 'cascade_reaches_closed' + /** The write could not be judged (D4's three cases). */ + | 'cannot_judge'; + +/** The refusal every closed-state judgement throws. */ +export interface ClosedStateLockError extends Error { + readonly code: typeof CLOSED_STATE_LOCK_CODE; + readonly status: 409; + readonly statusCode: 409; + /** The object the write was made on. */ + readonly object: string; + readonly reason: ClosedStateRefusalReason; + /** For `master_closed` and `cascade_reaches_closed`: the object whose closed record stands in the way. */ + readonly blockingObject?: string; + /** What the lock read: `closed_state`, the one lock read's reason (ADR-0162 D9). */ + readonly lockReason: 'closed_state'; +} + +/** + * Build the refusal. `message` is the developer's: it names objects by their + * API names and never a record id or a state value. + */ +export function closedStateLockError( + object: string, + verb: ClosedStateWriteVerb, + reason: ClosedStateRefusalReason, + blockingObject?: string, + detail?: string, +): ClosedStateLockError { + const what = reason === 'record_closed' + ? `the '${object}' record is closed (its object declares closedStates and the record is in one of them), so it cannot be ${verbPast(verb)}` + : reason === 'master_closed' + ? `the '${object}' row is a line of a closed '${blockingObject}' record, so it cannot be ${verbPast(verb)}` + : reason === 'cascade_reaches_closed' + ? `deleting this '${object}' record would also remove a closed '${blockingObject}' record or a line of one; nothing was deleted` + : `the closed-state lock could not judge this ${verb} on '${object}'${detail ? `: ${detail}` : ''}; it is refused rather than taken for open`; + const err = new Error(`${CLOSED_STATE_LOCK_CODE}: ${what}.`) as Error & Record; + err.name = 'ClosedStateLockError'; + err.code = CLOSED_STATE_LOCK_CODE; + err.status = 409; + err.statusCode = 409; + err.object = object; + err.reason = reason; + if (blockingObject !== undefined) err.blockingObject = blockingObject; + err.lockReason = 'closed_state'; + return err as unknown as ClosedStateLockError; +} + +function verbPast(verb: ClosedStateWriteVerb): string { + switch (verb) { + case 'update': return 'changed'; + case 'delete': return 'deleted'; + case 'create': return 'added'; + case 'restore': return 'restored under it'; + } +} + +/** + * [D5] Is a write in `context` bound by the lock? Every write is, except one + * made in a system context. A write with no context is bound: no identity is + * not an elevated identity. + */ +export function boundByClosedStates(context: ExecutionContext | undefined): boolean { + return context?.isSystem !== true; +} + +/** + * [D3, D10] What the lock reads for `object`: its own closed values and its + * `master_detail` edges to masters that declare them. `undefined` when there + * is neither, which is the "free when not declared" answer: the write reads + * nothing extra. + */ +export function closedStateUnitOf(this: Pick, object: string): ClosedStateUnit | undefined { + const schema = this._registry.getObject(object) as { fields?: Record } | undefined; + if (!schema) return undefined; + const own = closedValuesOf(schema); + const masters: ClosedMasterEdge[] = []; + for (const [name, def] of Object.entries(schema.fields ?? {})) { + if (!def || def.type !== 'master_detail') continue; + const ref = typeof def.reference === 'string' && def.reference ? def.reference : undefined; + if (!ref) continue; + let master: string; + try { master = this.resolveObjectName(ref); } catch { master = ref; } + const closed = closedValuesOf(this._registry.getObject(master)); + if (!closed) continue; + masters.push({ fk: typeof def.name === 'string' && def.name ? def.name : name, master, closed }); + } + if (!own && masters.length === 0) return undefined; + return { own, masters }; +} + +/** Is `row` closed under `closed`? An empty state value closes nothing. */ +export function rowIsClosed(row: Record | null | undefined, closed: ClosedValues): boolean { + if (!row) return false; + for (const [field, values] of closed) { + const v = row[field]; + if (typeof v === 'string' && v !== '' && values.has(v)) return true; + } + return false; +} + +/** The closed predicate over an object's own stored columns. */ +export function closedPredicate(closed: ClosedValues): FilterCondition { + const legs = [...closed].map(([field, values]) => ({ [field]: { $in: [...values] } }) as FilterCondition); + return legs.length === 1 ? legs[0]! : ({ $or: legs } as FilterCondition); +} + +/** A scalar id, or `null` for an empty value; `undefined` for a value that names something but not as one id. */ +function scalarIdOf(value: unknown): string | null | undefined { + if (value === undefined || value === null || value === '') return null; + if (typeof value === 'string') return value; + if (typeof value === 'number' && Number.isFinite(value)) return String(value); + return undefined; +} + +const IN_CHUNK = 500; + +function chunks(list: readonly T[], size = IN_CHUNK): T[][] { + const out: T[][] = []; + for (let i = 0; i < list.length; i += size) out.push(list.slice(i, i + size)); + return out; +} + +/** + * The ids among `ids` of `master` that are closed, read by the engine itself: + * straight from the store, above the writer's grants, inside the writer's + * organization scope and unit of work (the driver options of `context`). A + * read that fails is refused as "cannot be judged". + */ +async function closedIdsOf( + this: Pick, + master: string, + ids: ReadonlyArray, + closed: ClosedValues, + context: ExecutionContext | undefined, + refuse: (detail: string) => Error, +): Promise> { + const out = new Set(); + const unique = [...new Set(ids)]; + if (unique.length === 0) return out; + const fields = ['id', ...closed.keys()]; + try { + const driver = this.getDriver(master); + const opts = this.buildDriverOptions(master, context); + for (const part of chunks(unique)) { + const rows = (await driver.find( + master, + { object: master, where: { id: part.length === 1 ? part[0] : { $in: part } }, fields, limit: part.length }, + opts, + )) as Array> | null; + for (const row of rows ?? []) if (row && rowIsClosed(row, closed)) out.add(String(row.id)); + } + } catch (error) { + throw Object.assign(refuse(`the state of a '${master}' record could not be read`), { cause: error }); + } + return out; +} + +/** + * The named-master judgement (D10): for each id the write names as the master + * of a line, the caller's read door first; the state only of a master the door + * returns. A master it does not return is not this lock's to answer. + */ +async function namedMastersClosed( + this: ClosedStateLockHost, + edge: ClosedMasterEdge, + named: ReadonlyArray, + context: ExecutionContext | undefined, + refuse: (detail: string) => Error, +): Promise { + if (named.length === 0) return false; + const readable = await this.masterDetailHeadersCallerReads(edge.master, named, context); + const asked = named.filter((id) => readable.has(id)); + if (asked.length === 0) return false; + return (await closedIdsOf.call(this, edge.master, asked, edge.closed, context, refuse)).size > 0; +} + +/** The keys an update carries, addressing excluded. */ +function carriedKeys(payload: Record | null | undefined): string[] { + if (!payload || typeof payload !== 'object') return []; + return Object.keys(payload).filter((k) => k !== 'id'); +} + +/** [D7] The referential clear the engine wrote, and nothing else beside it. */ +export interface ClosedStateReferentialClear { + readonly field: string; + readonly value: unknown; +} + +function isBareReferentialClear(payload: Record | null | undefined, clear: ClosedStateReferentialClear | undefined): boolean { + if (!clear || !payload) return false; + const keys = carriedKeys(payload); + return keys.length === 1 && keys[0] === clear.field && Object.is(payload[clear.field], clear.value); +} + +/** Input of {@link judgeClosedStateByIdWrite}. */ +export interface ClosedStateByIdWrite { + readonly object: string; + readonly verb: 'update' | 'delete'; + /** The stored row, as the write's own prior read returned it. */ + readonly prior: Record; + /** An update's payload as the caller (and the middleware chain) left it, before the before-phase hooks. */ + readonly payload?: Record | null; + readonly context: ExecutionContext | undefined; + /** An update that is the engine's referential clear or the recycle bin's re-link (D7). */ + readonly referentialClear?: ClosedStateReferentialClear; +} + +/** + * [D4, D6, D7, D10] Judge a by-id update or delete. Called after the write's + * prior read (the row as stored, inside the write's unit of work) and before + * the before-phase hooks. + */ +export async function judgeClosedStateByIdWrite(this: ClosedStateLockHost, write: ClosedStateByIdWrite): Promise { + const { object, verb, prior, payload, context } = write; + if (!boundByClosedStates(context)) return; + const unit = closedStateUnitOf.call(this, object); + if (!unit) return; + if (verb === 'update') { + if (carriedKeys(payload).length === 0) return; + if (isBareReferentialClear(payload, write.referentialClear)) return; + } + if (unit.own && rowIsClosed(prior, unit.own)) throw closedStateLockError(object, verb, 'record_closed'); + const refuse = (detail: string) => closedStateLockError(object, verb, 'cannot_judge', undefined, detail); + for (const edge of unit.masters) { + // The master the stored row hangs under: its stored state, whoever writes. + const stored = scalarIdOf(prior[edge.fk]); + if (stored === undefined) throw refuse(`its '${edge.fk}' does not hold one id`); + if (stored !== null && (await closedIdsOf.call(this, edge.master, [stored], edge.closed, context, refuse)).size > 0) { + throw closedStateLockError(object, verb, 'master_closed', edge.master); + } + // A move names the master it moves to: the caller's read door first. + if (verb === 'update' && payload && Object.prototype.hasOwnProperty.call(payload, edge.fk)) { + const named = scalarIdOf(payload[edge.fk]); + if (named === undefined) throw refuse(`the master named by '${edge.fk}' is not one id`); + if (named !== null && named !== stored && await namedMastersClosed.call(this, edge, [named], context, refuse)) { + throw closedStateLockError(object, verb, 'master_closed', edge.master); + } + } + } +} + +/** + * [D4] Judge a create (one row or many) of lines of a master that declares + * closed states. A create of a record is not judged: there is no stored state + * yet. Refused whole when one row names a closed master the caller may read. + */ +export async function judgeClosedStateCreate( + this: ClosedStateLockHost, + object: string, + rows: ReadonlyArray | null | undefined>, + context: ExecutionContext | undefined, +): Promise { + if (!boundByClosedStates(context)) return; + const unit = closedStateUnitOf.call(this, object); + if (!unit || unit.masters.length === 0) return; + const refuse = (detail: string) => closedStateLockError(object, 'create', 'cannot_judge', undefined, detail); + for (const edge of unit.masters) { + const named: string[] = []; + for (const row of rows) { + if (!row || typeof row !== 'object') continue; + const id = scalarIdOf(row[edge.fk]); + if (id === undefined) throw refuse(`the master named by '${edge.fk}' is not one id`); + if (id !== null) named.push(id); + } + if (await namedMastersClosed.call(this, edge, [...new Set(named)], context, refuse)) { + throw closedStateLockError(object, 'create', 'master_closed', edge.master); + } + } +} + +/** Input of {@link judgeClosedStatePredicateWrite}. */ +export interface ClosedStatePredicateWrite { + readonly object: string; + readonly verb: 'update' | 'delete'; + /** The write's AST as the middleware chain composed it: the caller's row scope is in its `where`. */ + readonly ast: { where?: unknown }; + /** The driver options the write's own matched-row read is given. */ + readonly driverOptions: unknown; + readonly payload?: Record | null; + readonly context: ExecutionContext | undefined; + /** The write's one read of its matched rows (a memo), for a store that cannot run the line probe. */ + readonly readMatchedRows: () => Promise> | null>; +} + +/** + * Can one statement on `object`'s store answer "does a matched row hang under + * a closed `master`"? The line and the master share a driver that compiles the + * composed `ReadableIds` semi-join leaf, the master is not federated, and under + * a walled posture both are of the same tenancy class (so one read's driver + * options scope both tables). + */ +function lineProbeServes(this: ClosedStateLockHost, object: string, master: string): boolean { + const driver = this.getDriver(object); + if (!driverCompilesReadableIdsLeaf(driver)) return false; + if (this.getDriver(master) !== driver) return false; + const masterSchema = this._registry.getObject(master); + if (isFederatedObject(masterSchema)) return false; + if (postureEnforcesWall(this.resolveEnginePosture()) && + isDriverTenantScopedSchema(this._registry.getObject(object) as never) !== isDriverTenantScopedSchema(masterSchema as never)) return false; + return true; +} + +function andWhere(where: unknown, extra: FilterCondition): FilterCondition { + if (where === undefined || where === null) return extra; + if (typeof where === 'object' && !Array.isArray(where) && Object.keys(where as object).length === 0) return extra; + return { $and: [where as FilterCondition, extra] } as FilterCondition; +} + +/** + * [D4] Judge a predicate update or delete, whole, before any row is written. + * + * - The record's own state: one existence probe, the write's own composed + * predicate joined to the closed predicate. + * - A line's masters: one probe through a semi-join to the master where the + * store can run it ({@link lineProbeServes}); otherwise the write's one read + * of its matched rows, under the engine's per-row ceiling, and one read of + * the masters those rows hang under. A set over the ceiling cannot be + * judged and is refused. + * - An update that moves every matched line to a named master: that master, + * through the caller's read door first. + */ +export async function judgeClosedStatePredicateWrite(this: ClosedStateLockHost, write: ClosedStatePredicateWrite): Promise { + const { object, verb, ast, payload, context } = write; + if (!boundByClosedStates(context)) return; + const unit = closedStateUnitOf.call(this, object); + if (!unit) return; + if (verb === 'update' && carriedKeys(payload).length === 0) return; + const refuse = (detail: string) => closedStateLockError(object, verb, 'cannot_judge', undefined, detail); + const driver = this.getDriver(object); + const probe = async (where: FilterCondition): Promise => { + try { + const rows = (await driver.find(object, { object, where, fields: ['id'], limit: 1 }, write.driverOptions)) as unknown[] | null; + return Array.isArray(rows) && rows.length > 0; + } catch (error) { + throw Object.assign(refuse('the probe for a closed record failed'), { cause: error }); + } + }; + if (unit.own && await probe(andWhere(ast.where, closedPredicate(unit.own)))) { + throw closedStateLockError(object, verb, 'record_closed'); + } + let matched: ReadonlyArray> | undefined; + const matchedRows = async (): Promise>> => { + if (matched) return matched; + let rows: ReadonlyArray> | null; + try { + rows = await write.readMatchedRows(); + } catch (error) { + throw Object.assign(refuse('the read of the rows it matches failed'), { cause: error }); + } + matched = (rows ?? []).filter((r): r is Record => r != null && typeof r === 'object'); + if (matched.length > MAX_BULK_PER_ROW_HOOK_ROWS) { + throw refuse(`its store cannot run the line probe and it matches ${matched.length} rows, over the engine's per-row ceiling of ${MAX_BULK_PER_ROW_HOOK_ROWS}`); + } + return matched; + }; + for (const edge of unit.masters) { + if (lineProbeServes.call(this, object, edge.master)) { + const semiJoin = { [edge.fk]: { $in: ReadableIds.compose(ReadableIds.of(edge.master), closedPredicate(edge.closed)) } } as FilterCondition; + if (await probe(andWhere(ast.where, semiJoin))) throw closedStateLockError(object, verb, 'master_closed', edge.master); + } else { + const ids: string[] = []; + for (const row of await matchedRows()) { + const id = scalarIdOf(row[edge.fk]); + if (id === undefined) throw refuse(`a matched row's '${edge.fk}' does not hold one id`); + if (id !== null) ids.push(id); + } + if ((await closedIdsOf.call(this, edge.master, ids, edge.closed, context, refuse)).size > 0) { + throw closedStateLockError(object, verb, 'master_closed', edge.master); + } + } + if (verb === 'update' && payload && Object.prototype.hasOwnProperty.call(payload, edge.fk)) { + const named = scalarIdOf(payload[edge.fk]); + if (named === undefined) throw refuse(`the master named by '${edge.fk}' is not one id`); + if (named !== null && await namedMastersClosed.call(this, edge, [named], context, refuse)) { + throw closedStateLockError(object, verb, 'master_closed', edge.master); + } + } + } +} + +/** + * [D6] Judge the set a delete's cascade will remove, collected whole before + * any row is removed (`engine-cascade-planning.ts#cascadeDeleteRelations`). + * Refused whole when a member is closed, or is a line of a closed record. The + * refusal names the record the caller asked to delete (its object) and the + * object whose closed record stands in the way, and nothing else. + */ +export async function judgeClosedStateCascadeSet( + this: Pick, + root: string, + members: ReadonlyMap>, + context: ExecutionContext | undefined, +): Promise { + if (!boundByClosedStates(context)) return; + const refuse = (detail: string) => closedStateLockError(root, 'delete', 'cannot_judge', undefined, detail); + for (const [object, idSet] of members) { + const unit = closedStateUnitOf.call(this, object); + if (!unit || idSet.size === 0) continue; + const ids = [...idSet]; + const fields = ['id', ...(unit.own ? unit.own.keys() : []), ...unit.masters.map((e) => e.fk)]; + let rows: Array> = []; + try { + const driver = this.getDriver(object); + const opts = this.buildDriverOptions(object, context); + for (const part of chunks(ids)) { + const found = (await driver.find( + object, + { object, where: { id: part.length === 1 ? part[0] : { $in: part } }, fields, limit: part.length }, + opts, + )) as Array> | null; + rows = rows.concat((found ?? []).filter((r) => r && typeof r === 'object')); + } + } catch (error) { + throw Object.assign(refuse(`the rows of '${object}' its cascade reaches could not be read`), { cause: error }); + } + if (unit.own && rows.some((row) => rowIsClosed(row, unit.own!))) { + throw closedStateLockError(root, 'delete', 'cascade_reaches_closed', object); + } + for (const edge of unit.masters) { + const masterIds: string[] = []; + for (const row of rows) { + const id = scalarIdOf(row[edge.fk]); + if (id === undefined) throw refuse(`a '${object}' row its cascade reaches does not hold one id in '${edge.fk}'`); + if (id !== null) masterIds.push(id); + } + if ((await closedIdsOf.call(this, edge.master, masterIds, edge.closed, context, refuse)).size > 0) { + throw closedStateLockError(root, 'delete', 'cascade_reaches_closed', edge.master); + } + } + } +} + +/** + * [D7] Restore: an entry that would put a row back under a LIVE, closed master + * that is not itself part of the entry is refused before anything is written. + * `parents` lists, for each such reference, the line's object and field and + * the live master's id. + */ +export async function judgeClosedStateRestore( + this: Pick, + parents: ReadonlyArray<{ object: string; field: string; master: string; id: string }>, + context: ExecutionContext | undefined, +): Promise { + if (!boundByClosedStates(context)) return; + const byMaster = new Map(); + for (const p of parents) { + // Named as the restore's own judgement names it: the reference as declared. + const master = p.master; + const closed = closedValuesOf(this._registry.getObject(master)); + if (!closed) continue; + const slot = byMaster.get(master) ?? { closed, ids: [], object: p.object }; + slot.ids.push(p.id); + byMaster.set(master, slot); + } + for (const [master, { closed, ids, object }] of byMaster) { + const refuse = (detail: string) => closedStateLockError(object, 'restore', 'cannot_judge', undefined, detail); + if ((await closedIdsOf.call(this, master, ids, closed, context, refuse)).size > 0) { + throw closedStateLockError(object, 'restore', 'master_closed', master); + } + } +} diff --git a/packages/objectql/src/closed-state-values.ts b/packages/objectql/src/closed-state-values.ts new file mode 100644 index 00000000000..3c11d608f77 --- /dev/null +++ b/packages/objectql/src/closed-state-values.ts @@ -0,0 +1,23 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 D1, D2] An object's declared `closedStates`, read as the lock and + * the registry fold read it. Kept apart from the lock (`closed-state-lock.ts`) + * so the registry imports nothing of the engine's write path. + */ + +/** One object's closed values, field → the values of it that close a record. */ +export type ClosedValues = ReadonlyMap>; + +/** An object's declared closed values, or `undefined` when it declares none. */ +export function closedValuesOf(schema: unknown): ClosedValues | undefined { + const declared = (schema as { closedStates?: unknown } | null | undefined)?.closedStates; + if (!declared || typeof declared !== 'object' || Array.isArray(declared)) return undefined; + const out = new Map>(); + for (const [field, values] of Object.entries(declared as Record)) { + if (!Array.isArray(values)) continue; + const set = new Set(values.filter((v): v is string => typeof v === 'string')); + if (set.size > 0) out.set(field, set); + } + return out.size > 0 ? out : undefined; +} diff --git a/packages/objectql/src/engine-cascade-planning.ts b/packages/objectql/src/engine-cascade-planning.ts index 327c435f887..89b15e6c295 100644 --- a/packages/objectql/src/engine-cascade-planning.ts +++ b/packages/objectql/src/engine-cascade-planning.ts @@ -43,6 +43,7 @@ * this module. */ +import { judgeClosedStateCascadeSet } from './closed-state-lock.js'; import type { ServiceObject } from '@objectstack/spec/data'; import { SystemFieldName } from '@objectstack/spec/system'; import type { ExecutionContext } from '@objectstack/spec/kernel'; @@ -84,6 +85,8 @@ export interface CascadePlanningHost { readonly drivers: ObjectQLClass['drivers']; fileReferenceCheckElevation: ObjectQLClass['fileReferenceCheckElevation']; find: ObjectQLClass['find']; + /** [ADR-0162 D6] The driver options the closed-state lock reads the cascade set with. */ + buildDriverOptions: ObjectQLClass['buildDriverOptions']; getDriver: ObjectQLClass['getDriver']; isTenantColumnSetNull: ObjectQLClass['isTenantColumnSetNull']; readonly logger: ObjectQLClass['logger']; @@ -532,7 +535,7 @@ export class CascadePlanningFacet { * (formula values, file references, hooks), so they are not the values a * restore must write back. */ - static async cascadeDeleteRelations(this: Pick, object: string, ids: ReadonlyArray, context?: ExecutionContext, depth = 0, onCollected?: (set: CascadeDeleteSet) => Promise): Promise { + static async cascadeDeleteRelations(this: Pick, object: string, ids: ReadonlyArray, context?: ExecutionContext, depth = 0, onCollected?: (set: CascadeDeleteSet) => Promise): Promise { const roots: Array = []; const seen = new Set(); for (const id of ids) { @@ -575,6 +578,11 @@ export class CascadePlanningFacet { // [#26718] Every restrict a member's own cascade would override is judged // here, before the first write. await this.refuseRestrictsInsideOwnCascade(cascadeSet, fresh.map((id) => ({ object, id })), context, objects); + // [ADR-0162 D6] The closed-state lock over the whole set, at the same + // point: after the caller's gates on the record it asked to delete and + // before the first row is removed, never leg by leg. A member that is + // closed, or is a line of a closed record, refuses the delete whole. + await judgeClosedStateCascadeSet.call(this, object, cascadeSet.members, context); if (onCollected) await onCollected(cascadeSet); await this.cascadeDeleteSets.run(cascadeSet, () => this.walkReferencingRelations(object, fresh, context, objects, cascadeSet), diff --git a/packages/objectql/src/engine-delete-and-aggregate.ts b/packages/objectql/src/engine-delete-and-aggregate.ts index 76bc9d881b6..072787d6e74 100644 --- a/packages/objectql/src/engine-delete-and-aggregate.ts +++ b/packages/objectql/src/engine-delete-and-aggregate.ts @@ -35,6 +35,7 @@ * this module. */ +import { judgeClosedStateByIdWrite, judgeClosedStatePredicateWrite } from './closed-state-lock.js'; import { normalizeFilterComparandTypes } from '@objectstack/spec/data'; import type { EngineAggregateOptions, EngineDeleteOptions, FilterCondition, HookContext, QueryAST } from '@objectstack/spec/data'; import type { InternalFieldEvaluationOptions, InternalFieldEvaluationQuery } from '@objectstack/spec/contracts'; @@ -136,6 +137,10 @@ export interface DeleteAndAggregateHost { inAfterAbortUnit: ObjectQLClass['inAfterAbortUnit']; invalidateOrganizationProbe: ObjectQLClass['invalidateOrganizationProbe']; readonly logger: ObjectQLClass['logger']; + /** [ADR-0162 D10] The caller's read door on a named master (the closed-state lock). */ + masterDetailHeadersCallerReads: ObjectQLClass['masterDetailHeadersCallerReads']; + /** [ADR-0162 D4] The tenancy posture, read by the closed-state lock's line probe. */ + resolveEnginePosture: ObjectQLClass['resolveEnginePosture']; openRecycleBinCapture: ObjectQLClass['openRecycleBinCapture']; opensAfterAbortUnit: ObjectQLClass['opensAfterAbortUnit']; planCascadeAtomicity: ObjectQLClass['planCascadeAtomicity']; @@ -159,7 +164,7 @@ export interface DeleteAndAggregateHost { /** The bodies of the "Delete, count, aggregate and execute" section of `ObjectQL`: a stateless facet, called by the class's stubs. */ export class DeleteAndAggregateFacet { /** The body of `ObjectQL#delete`; the method's docblock there is its contract. */ - static async delete(this: Pick, object: string, options?: EngineDeleteOptions & RecycleBinDeleteObservability): Promise { + static async delete(this: Pick, object: string, options?: EngineDeleteOptions & RecycleBinDeleteObservability): Promise { object = this.resolveObjectName(object); // [#22782, #34412] An aborting `afterDelete`, or a refusal after a `beforeDelete` hook's // `ctx.api` write, rolls this write back with it — see `opensAfterAbortUnit`. @@ -503,6 +508,13 @@ export class DeleteAndAggregateFacet { // `bindPreImage`'s never-fabricate rule (#4649/#4775) is unchanged and // still the reason the binding goes through it rather than around it. bindPreImage(priorRecord); + // [ADR-0162 D4, D6, D10] The closed-state lock, on the row as stored, + // after the gates and before the before-phase hooks. A cascade leg + // (`referentialCascadeDelete`) is not judged again: its root judged + // the whole set the cascade removes, where the set was planned. + if (referentialCascadeDelete !== true) { + await judgeClosedStateByIdWrite.call(this, { object, verb: 'delete', prior: priorRecord, context: opCtx.context }); + } await this.triggerHooks('beforeDelete', hookContext); // [#6752] The retired lever, refused — the `update()` twin's check, // verbatim, because the rule is now ONE rule: a by-id target is @@ -565,6 +577,26 @@ export class DeleteAndAggregateFacet { // `where: {}` is a REAL (match-all) query and stays on the per-row // authorize path; only an absent or `null` predicate is unscoped. // `update()`'s predicate branch carries the identical check (#9974). + // [ADR-0162 D4, D10] The closed-state lock over every row the composed + // predicate reaches, whole, before any hook runs (the unscoped-multi + // dispatch below included) and before any row is removed. Where the + // store cannot run the line probe it is answered from the one read of + // the doomed rows the hooks below are served from (`readDoomed`). + const preOpts = this.buildDriverOptions(object, opCtx.context, hookContext.input.options as any, { recordedVerdict: opCtx.tenantLayer0Verdict }); + let doomedRead: Record[] | undefined; + const readDoomed = async (): Promise[]> => { + // [#21613] Each doomed row is its per-row `previous`: declared set. + doomedRead ??= rowsWithDeclaredColumnsOnly( + (await driver.find(object, ast, preOpts) as Record[]) ?? [], + declaredDeleteColumns, + ); + return doomedRead; + }; + if (referentialCascadeDelete !== true) { + await judgeClosedStatePredicateWrite.call(this, { + object, verb: 'delete', ast, driverOptions: preOpts, context: opCtx.context, readMatchedRows: readDoomed, + }); + } const rawWhere = (hookContext.input.options as { where?: unknown } | undefined)?.where; if (rawWhere === undefined || rawWhere === null) { await this.dispatchUnscopedMultiWriteHooks('beforeDelete', object, hookContext); @@ -580,12 +612,7 @@ export class DeleteAndAggregateFacet { // rows: they are its scope check and its per-row realtime events. const cascadeBatch = referentialCascadeDelete === true; if (perRowBeforeHooks || perRowAfterHooks || cascadeBatch) { - const preOpts = this.buildDriverOptions(object, opCtx.context, hookContext.input.options as any, { recordedVerdict: opCtx.tenantLayer0Verdict }); - // [#21613] Each doomed row is its per-row `previous`: declared set. - const doomed = rowsWithDeclaredColumnsOnly( - (await driver.find(object, ast, preOpts) as Record[]) ?? [], - declaredDeleteColumns, - ); + const doomed = await readDoomed(); predicateMatchedRows = doomed; // [ruling 6893104201 point (2)] The read ran through the AST the // middleware chain composed for this delete, so it is the caller's diff --git a/packages/objectql/src/engine-insert.ts b/packages/objectql/src/engine-insert.ts index 2bf18247089..0a9ece50b8f 100644 --- a/packages/objectql/src/engine-insert.ts +++ b/packages/objectql/src/engine-insert.ts @@ -35,6 +35,7 @@ * this module. */ +import { judgeClosedStateCreate } from './closed-state-lock.js'; import { formulaWorkCalendarsFor } from './formula-work-calendars.js'; import type { DataEngineInsertOptions, EngineCountOptions, EngineQueryOptions, HookContext, QueryAST } from '@objectstack/spec/data'; import type { WriteObservabilityOptions } from '@objectstack/spec/contracts'; @@ -126,6 +127,10 @@ export interface InsertHost { invalidateOrganizationProbe: ObjectQLClass['invalidateOrganizationProbe']; isIssuedAutonumberCollision: ObjectQLClass['isIssuedAutonumberCollision']; readonly logger: ObjectQLClass['logger']; + /** [ADR-0162 D10] The caller's read door on a named master (the closed-state lock). */ + masterDetailHeadersCallerReads: ObjectQLClass['masterDetailHeadersCallerReads']; + /** [ADR-0162 D4] The tenancy posture, read by the closed-state lock's line probe. */ + resolveEnginePosture: ObjectQLClass['resolveEnginePosture']; mediaValueShapeStrictFor: ObjectQLClass['mediaValueShapeStrictFor']; opensAfterAbortUnit: ObjectQLClass['opensAfterAbortUnit']; ownershipQueueService: ObjectQLClass['ownershipQueueService']; @@ -328,7 +333,7 @@ export class InsertFacet { } /** The body of `ObjectQL#insert`; the method's docblock there is its contract. */ - static async insert(this: Pick, object: string, data: any | any[], options?: DataEngineInsertOptions & WriteObservabilityOptions): Promise { + static async insert(this: Pick, object: string, data: any | any[], options?: DataEngineInsertOptions & WriteObservabilityOptions): Promise { object = this.resolveObjectName(object); // [#22782, #34412] An aborting `afterInsert`, or a refusal after a `beforeInsert` hook's // `ctx.api` write, rolls this write back with it — see `opensAfterAbortUnit`. @@ -612,6 +617,15 @@ export class InsertFacet { // context tells a handler whether it is one row of a batch. The scratch // is created once per CALL and shared by every row's context, before and // after — see `HookContext.dispatch`. + // [ADR-0162 D4, D10] The closed-state lock on a create of lines: each + // master the rows name, through the caller's read door first, then its + // stored state. After the gates and the engine's defaults, before the + // before-phase hooks; a many-row create is refused whole. A master a + // `beforeInsert` hook supplies afterwards is not judged here. + await judgeClosedStateCreate.call(this, object, + ((isBatch ? defaultedData : [defaultedData]) as Array | null | undefined>) + .filter((_row, i) => undeclaredPerRow[i] === undefined), + opCtx.context); const insertScope: Record = {}; // ── [#14259] ARM the hook-write recording, one PER ROW ─────────────── // diff --git a/packages/objectql/src/engine-update.ts b/packages/objectql/src/engine-update.ts index 378b4f0d01f..bf42dd5797a 100644 --- a/packages/objectql/src/engine-update.ts +++ b/packages/objectql/src/engine-update.ts @@ -87,6 +87,7 @@ import { } from './engine-top-level.js'; import type { OperationContext, ReferentialClearOption, StoredExpressionServing } from './engine-top-level.js'; import { REFERENTIAL_CLEAR_OPTION } from './engine-top-level.js'; +import { judgeClosedStateByIdWrite, judgeClosedStatePredicateWrite } from './closed-state-lock.js'; import { ObjectQLStatics as ObjectQL } from './engine.js'; import type { ObjectQL as ObjectQLClass } from './engine.js'; @@ -135,6 +136,10 @@ export interface UpdateHost { inAfterAbortUnit: ObjectQLClass['inAfterAbortUnit']; invalidateOrganizationProbe: ObjectQLClass['invalidateOrganizationProbe']; readonly logger: ObjectQLClass['logger']; + /** [ADR-0162 D10] The caller's read door on a named master (the closed-state lock). */ + masterDetailHeadersCallerReads: ObjectQLClass['masterDetailHeadersCallerReads']; + /** [ADR-0162 D4] The tenancy posture, read by the closed-state lock's line probe. */ + resolveEnginePosture: ObjectQLClass['resolveEnginePosture']; mediaValueShapeStrictFor: ObjectQLClass['mediaValueShapeStrictFor']; opensAfterAbortUnit: ObjectQLClass['opensAfterAbortUnit']; permissionResolution: ObjectQLClass['permissionResolution']; @@ -170,7 +175,7 @@ export interface UpdateHost { /** The bodies of the "Update" section of `ObjectQL`: a stateless facet, called by the class's stubs. */ export class UpdateFacet { /** The body of `ObjectQL#update`; the method's docblock there is its contract. */ - static async update(this: Pick, object: string, data: any, options?: EngineUpdateOptions & WriteObservabilityOptions): Promise | number | null> { + static async update(this: Pick, object: string, data: any, options?: EngineUpdateOptions & WriteObservabilityOptions): Promise | number | null> { object = this.resolveObjectName(object); // [#22782, #34412] An aborting `afterUpdate`, or a refusal after a `beforeUpdate` hook's // `ctx.api` write, rolls this write back with it — see `opensAfterAbortUnit`. @@ -938,6 +943,16 @@ export class UpdateFacet { // permanently true here: it states the invariant, and the invariant // outlives this call site. if (priorRecord) hookContext.previous = coerceBooleanFields(updateSchema as any, priorRecord as any) as any; + // [ADR-0162 D4, D10] The closed-state lock, on the row as stored: + // after the permission and row-access gates (the middleware chain + // has answered) and before the before-phase hooks, so a write + // refused for its own record or its own master runs no app hook. + // Judged by the keys the write carries — the payload as the chain + // left it, the keys the hide pass withheld from the hooks included. + await judgeClosedStateByIdWrite.call(this, { + object, verb: 'update', prior: priorRecord, context: opCtx.context, referentialClear, + payload: { ...(readonlyHiddenFromHooks ?? {}), ...((opCtx.data as Record | null | undefined) ?? {}) }, + }); // [#24619] The stored computed fields over the stored row merged // with the caller's patch, BEFORE the beforeUpdate hooks, so a hook // sees the expression's value over the PRE-strip row. That is not @@ -1008,6 +1023,32 @@ export class UpdateFacet { `write reaches only the rows this caller may edit).`, ); } + const preOpts = this.buildDriverOptions(object, opCtx.context, hookContext.input.options as any, { recordedVerdict: opCtx.tenantLayer0Verdict }); + readPriorRows = async () => { + if (!priorRowsRead) { + priorRowsRead = true; + // [#21613] The matched rows' pre-images, shaped like the + // by-id prior read: each per-row `afterUpdate` composes its + // `result` from one of them, so both sides stay declared. + priorRows = rowsWithDeclaredColumnsOnly( + (await driver.find(object, ast, preOpts) as Record[]) ?? [], + declaredColumnSet(updateSchema), + ); + } + return priorRows; + }; + + // [ADR-0162 D4, D10] The closed-state lock over every row the + // composed predicate reaches, whole, before any hook runs (the + // unscoped-multi dispatch below included) and any row is written: + // one existence probe on the store, or the one read of the matched + // rows (`readPriorRows`, the memo) where the store cannot run the + // line probe. + await judgeClosedStatePredicateWrite.call(this, { + object, verb: 'update', ast, driverOptions: preOpts, context: opCtx.context, + payload: { ...(readonlyHiddenFromHooks ?? {}), ...((opCtx.data as Record | null | undefined) ?? {}) }, + readMatchedRows: readPriorRows, + }); // [#9974] The unscoped-multi shape check, BEFORE the matched-row // read — `delete()`'s twin (#9719), verbatim in condition, slot and // placement, because the two branches answer the same question about @@ -1040,20 +1081,6 @@ export class UpdateFacet { await dispatchHooksExplainingWithheldReadonly(readonlyHiddenFromHooks, 'beforeUpdate', () => this.dispatchUnscopedMultiWriteHooks('beforeUpdate', object, hookContext)); } - const preOpts = this.buildDriverOptions(object, opCtx.context, hookContext.input.options as any, { recordedVerdict: opCtx.tenantLayer0Verdict }); - readPriorRows = async () => { - if (!priorRowsRead) { - priorRowsRead = true; - // [#21613] The matched rows' pre-images, shaped like the - // by-id prior read: each per-row `afterUpdate` composes its - // `result` from one of them, so both sides stay declared. - priorRows = rowsWithDeclaredColumnsOnly( - (await driver.find(object, ast, preOpts) as Record[]) ?? [], - declaredColumnSet(updateSchema), - ); - } - return priorRows; - }; // The demand is uniform across hooks and asked PER OBJECT: it is // NOT keyed on whether any condition mentions `previous`, which the diff --git a/packages/objectql/src/engine.ts b/packages/objectql/src/engine.ts index 8b26cf65a68..e7f41ee1aa6 100644 --- a/packages/objectql/src/engine.ts +++ b/packages/objectql/src/engine.ts @@ -5826,7 +5826,7 @@ export class ObjectQL implements IObjectQLEngine { refuseRestrictsInsideOwnCascade: (...a) => engine.refuseRestrictsInsideOwnCascade(...a), resolveObjectName: (...a) => engine.resolveObjectName(...a), update: (...a) => engine.update(...a), - walkReferencingRelations: (...a) => engine.walkReferencingRelations(...a), + walkReferencingRelations: (...a) => engine.walkReferencingRelations(...a), buildDriverOptions: (...a) => engine.buildDriverOptions(...a), // [ADR-0162 D6] })); compatibilitySectionHost.install((engine) => ({ get _registry() { return engine._registry; }, @@ -5899,7 +5899,7 @@ export class ObjectQL implements IObjectQLEngine { transaction: (...a) => engine.transaction(...a), triggerHooks: (...a) => engine.triggerHooks(...a), warnCascadeNotAtomic: (...a) => engine.warnCascadeNotAtomic(...a), - withResolvedWhere: (...a) => engine.withResolvedWhere(...a), + withResolvedWhere: (...a) => engine.withResolvedWhere(...a), masterDetailHeadersCallerReads: (...a) => engine.masterDetailHeadersCallerReads(...a), resolveEnginePosture: () => engine.resolveEnginePosture(), // [ADR-0162 D10] })); findHost.install((engine) => ({ get _registry() { return engine._registry; }, @@ -6018,7 +6018,7 @@ export class ObjectQL implements IObjectQLEngine { update: (...a) => engine.update(...a), validationMessageContext: (...a) => engine.validationMessageContext(...a), valueShapeStrictFor: (...a) => engine.valueShapeStrictFor(...a), - warnAutonumberReadersUnserved: (...a) => engine.warnAutonumberReadersUnserved(...a), + warnAutonumberReadersUnserved: (...a) => engine.warnAutonumberReadersUnserved(...a), masterDetailHeadersCallerReads: (...a) => engine.masterDetailHeadersCallerReads(...a), resolveEnginePosture: () => engine.resolveEnginePosture(), // [ADR-0162 D10] })); middlewareAndContextHost.install((engine) => ({ get _registry() { return engine._registry; }, @@ -6256,7 +6256,7 @@ export class ObjectQL implements IObjectQLEngine { updateByIdExpecting: (...a) => engine.updateByIdExpecting(...a), validationMessageContext: (...a) => engine.validationMessageContext(...a), valueShapeStrictFor: (...a) => engine.valueShapeStrictFor(...a), - withResolvedWhere: (...a) => engine.withResolvedWhere(...a), + withResolvedWhere: (...a) => engine.withResolvedWhere(...a), masterDetailHeadersCallerReads: (...a) => engine.masterDetailHeadersCallerReads(...a), resolveEnginePosture: () => engine.resolveEnginePosture(), // [ADR-0162 D10] })); } } diff --git a/packages/objectql/src/federated-injected-column-readers.test.ts b/packages/objectql/src/federated-injected-column-readers.test.ts index 14655b2c3ba..4989d6a5974 100644 --- a/packages/objectql/src/federated-injected-column-readers.test.ts +++ b/packages/objectql/src/federated-injected-column-readers.test.ts @@ -248,6 +248,13 @@ const READERS: Record = { disposition: 'exempt', why: 'names the related object only to judge the join beside the federated test; it reads no row', }, + // [ADR-0162 D4] The closed-state lock's line probe: a federated master + // declines the composed semi-join, and the lock reads the matched lines + // and their masters by id instead, so no subquery runs against it. + 'closed-state-lock.ts#lineProbeServes :: isFederatedObject()': { + disposition: 'exempt', + why: 'a federated master declines the line probe, so no subquery is compiled against it; it reads no row', + }, // [latest per group] A federated object refuses the one-row-per-group read // before anything is read, so no window is compiled against its remote table. 'latest-per.ts#latestPerRegistryRefusal :: isFederatedObject()': { diff --git a/packages/objectql/src/recycle-bin/restore.ts b/packages/objectql/src/recycle-bin/restore.ts index 1575a182347..b5b765d03c9 100644 --- a/packages/objectql/src/recycle-bin/restore.ts +++ b/packages/objectql/src/recycle-bin/restore.ts @@ -67,6 +67,7 @@ * context, as the delete's `set_null` clear went (`engine-cascade-planning.ts`). */ +import { judgeClosedStateRestore } from '../closed-state-lock.js'; import { RECYCLE_BIN_GRANT_KEYS, RECYCLE_BIN_OBJECT, @@ -520,6 +521,8 @@ async function judgeRestore( /** Each master-detail reference whose parent is not live, in row order, and each such parent once. */ const missing: Array<{ row: RecycleBinSnapshotRow; field: string; parent: { object: string; id: string } }> = []; const missingParents = new Map(); + /** [ADR-0162 D7] Each live master a row of the entry comes back under, for the closed-state lock. */ + const liveParents: Array<{ object: string; field: string; master: string; id: string }> = []; for (const row of rows) { const schema = this._registry.getObject(row.object); const fields = fieldsOf(schema); @@ -535,7 +538,10 @@ async function judgeRestore( // restored (its own entry would refuse RESTORE_PACKAGE_UNINSTALLED), so it // is gone for good, whatever the bin holds. if (!this._registry.getObject(parent.object)) throw parentPurgedRefusal(entryId, row, field, parent, true); - if (!missingParents.has(key) && await isLive(parent.object, { id: parent.id })) continue; + if (!missingParents.has(key) && await isLive(parent.object, { id: parent.id })) { + liveParents.push({ object: row.object, field, master: parent.object, id: parent.id }); + continue; + } missing.push({ row, field, parent }); missingParents.set(key, parent); } @@ -552,6 +558,11 @@ async function judgeRestore( if (await isLive(row.object, where)) throw uniqueValueTakenRefusal(entryId, row, field, fieldLabelOf.call(this, row.object, field, context)); } } + // [ADR-0162 D7] Then: no row comes back under a LIVE master that is closed + // and not part of the entry: that is adding a line to a closed document + // through another door. Judged before anything is written; a restore in + // a system context passes. + await judgeClosedStateRestore.call(this, liveParents, context); if (missing.length === 0) return; // 4. The bin, asked once about every missing parent: one not held is purged // (permanent); then, nothing permanent standing, one held is the reason. diff --git a/packages/qa/dogfood/test/closed-state-lock.test.ts b/packages/qa/dogfood/test/closed-state-lock.test.ts new file mode 100644 index 00000000000..07874aa9d07 --- /dev/null +++ b/packages/qa/dogfood/test/closed-state-lock.test.ts @@ -0,0 +1,587 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 D2 to D7, D10] The closed-state lock, on a real store. + * + * An object declares `closedStates`; a record whose stored state is one of + * the listed values is closed, and so are its direct `master_detail` lines. + * Every write a system context does not make is bound: an update, a delete, a + * line create, update, delete or move is refused `409 RECORD_LOCKED`, and a + * many-row write is refused whole before any row is written. + * + * Run on SQLite (`SqlDriver`, better-sqlite3 `:memory:`) in two store shapes, + * each pinned on its own: + * + * - **probe**: the store compiles the composed `ReadableIds` semi-join leaf, + * so a predicate write on lines is judged by one existence statement; + * - **no probe**: the same store declaring `readableIdsLeaf: false` (the + * MongoDB and OData shape), so a predicate write on lines is judged from + * the write's one read of its matched rows, under the engine's per-row + * ceiling. + * + * The cascade's "removes no row" is pinned on a store with transactions and + * on one that declares `transactionsUnsupported`. + * + * Ground truth is read through knex, past every engine layer. + */ + +import { afterEach, describe, expect, it } from 'vitest'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { MAX_BULK_PER_ROW_HOOK_ROWS } from '@objectstack/spec/data'; +import { SysRecycleBin } from '@objectstack/platform-objects/system'; +import { SysUser } from '@objectstack/platform-objects/identity'; +import { changeRecordsOwner, transferUserAssignedWork } from '@objectstack/core'; +import { DEFAULT_ORGANIZATION_ID, installDefaultOrganization } from './default-organization.testkit.js'; + +const SYS = { isSystem: true, userId: 'usr_system' } as const; +const CALLER = { userId: 'usr_caller', tenantId: DEFAULT_ORGANIZATION_ID, positions: [], permissions: [] } as const; + +const CUSTOMER = 'dg_cs_customer'; +const CONTACT = 'dg_cs_contact'; +const INVOICE = 'dg_cs_invoice'; +const LINE = 'dg_cs_line'; +const BUDGET = 'dg_cs_budget'; +const ALLOC = 'dg_cs_alloc'; +const PAYMENT = 'dg_cs_payment'; + +const STATUS_OPTIONS = ['draft', 'sent', 'paid', 'void'].map((v) => ({ label: v, value: v })); + +const OBJECTS = [ + { name: CUSTOMER, label: 'Customer', fields: { name: { type: 'text', label: 'Name' } } }, + { name: CONTACT, label: 'Contact', fields: { name: { type: 'text', label: 'Name' } } }, + { + name: INVOICE, + label: 'Invoice', + fields: { + name: { type: 'text', label: 'Number' }, + status: { type: 'select', label: 'Status', options: STATUS_OPTIONS }, + amount: { type: 'number', label: 'Amount' }, + customer: { type: 'lookup', label: 'Customer', reference: CUSTOMER, deleteBehavior: 'cascade' }, + contact: { type: 'lookup', label: 'Contact', reference: CONTACT }, + }, + closedStates: { status: ['paid', 'void'] }, + }, + { + name: LINE, + label: 'Invoice line', + fields: { + name: { type: 'text', label: 'Description' }, + qty: { type: 'number', label: 'Quantity' }, + invoice: { type: 'master_detail', label: 'Invoice', reference: INVOICE, required: true }, + }, + }, + { + name: BUDGET, + label: 'Budget', + fields: { + name: { type: 'text', label: 'Name' }, + state: { type: 'select', label: 'State', options: [{ label: 'Open', value: 'open' }, { label: 'Frozen', value: 'frozen' }] }, + }, + closedStates: { state: ['frozen'] }, + }, + { + // A junction under two masters: a line of both (D3). + name: ALLOC, + label: 'Allocation', + fields: { + name: { type: 'text', label: 'Name' }, + invoice: { type: 'master_detail', label: 'Invoice', reference: INVOICE, required: true }, + budget: { type: 'master_detail', label: 'Budget', reference: BUDGET, required: true }, + }, + }, +]; + +interface Shape { readonly probe: boolean; readonly transactions: boolean } + +let engine: ObjectQL; +let driver: SqlDriver; + +/** + * A payment is a LOOKUP child of the invoice, not a line: the lock does not + * bind it, and the invoice rolls its payments up into a summary field, so a + * payment write reaches the invoice through the engine's own recompute. + */ +const PAYMENT_OBJECT = { + name: PAYMENT, + label: 'Payment', + fields: { + name: { type: 'text', label: 'Reference' }, + paid: { type: 'number', label: 'Paid' }, + invoice: { type: 'lookup', label: 'Invoice', reference: INVOICE }, + }, +}; +const withPaymentSummary = (objects: typeof OBJECTS): unknown[] => [ + ...objects.map((o) => (o.name === INVOICE + ? { ...o, fields: { ...o.fields, paid_total: { type: 'summary', label: 'Paid total', summaryOperations: { object: PAYMENT, field: 'paid', function: 'sum' } } } } + : o)), + PAYMENT_OBJECT, +]; + +async function boot(shape: Shape, extra: { recycleBin?: boolean; users?: boolean; summary?: boolean } = {}): Promise { + driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); + const supports = (driver as unknown as { supports: Record }).supports; + Object.defineProperty(driver, 'supports', { + configurable: true, + value: { ...supports, readableIdsLeaf: shape.probe, ...(shape.transactions ? {} : { transactionsUnsupported: true }) }, + }); + engine = new ObjectQL(); + engine.registerDriver(driver, true); + await engine.init(); + engine.registerApp({ + id: 'com.objectstack.dogfood.closed-state-lock', + name: 'Closed-state lock', + version: '1.0.0', + type: 'plugin', + scope: 'system', + objects: [...(extra.summary ? withPaymentSummary(OBJECTS) : OBJECTS), ...(extra.recycleBin ? [SysRecycleBin] : []), ...(extra.users ? [SysUser] : [])], + } as never); + await engine.syncSchemas(); + await installDefaultOrganization(engine); + await engine.insert(CUSTOMER, { id: 'cu1', name: 'Acme' }, { context: SYS } as never); + await engine.insert(CONTACT, { id: 'ct1', name: 'Ada' }, { context: SYS } as never); + for (const [id, status] of [['inv_open', 'draft'], ['inv_open2', 'sent'], ['inv_paid', 'paid'], ['inv_void', 'void']] as const) { + await engine.insert(INVOICE, { id, name: id, status, amount: 10, customer: 'cu1', contact: 'ct1' }, { context: SYS } as never); + } + for (const [id, invoice] of [['l_open', 'inv_open'], ['l_open2', 'inv_open2'], ['l_paid', 'inv_paid'], ['l_paid2', 'inv_paid']] as const) { + await engine.insert(LINE, { id, name: id, qty: 1, invoice }, { context: SYS } as never); + } + await engine.insert(BUDGET, { id: 'b_open', name: 'Open', state: 'open' }, { context: SYS } as never); + await engine.insert(BUDGET, { id: 'b_frozen', name: 'Frozen', state: 'frozen' }, { context: SYS } as never); + await engine.insert(ALLOC, { id: 'a_open', name: 'a', invoice: 'inv_open', budget: 'b_open' }, { context: SYS } as never); + await engine.insert(ALLOC, { id: 'a_frozen', name: 'b', invoice: 'inv_open', budget: 'b_frozen' }, { context: SYS } as never); +} + +afterEach(async () => { + await engine?.destroy(); +}); + +type Knex = (table: string) => { select: (...c: string[]) => Promise>> }; +const knex = (): Knex => (driver as unknown as { knex: Knex }).knex; + +/** The table as stored: `id:col` for each row, sorted. */ +async function stored(table: string, col: string): Promise { + const rows = await knex()(table).select('id', col); + return rows.map((r) => `${r.id}:${r[col]}`).sort(); +} + +async function refusal(run: () => Promise): Promise<{ code?: unknown; status?: unknown; reason?: unknown; blockingObject?: unknown; message?: unknown }> { + try { + await run(); + } catch (e) { + return e as never; + } + throw new Error('expected the write to be refused, and it landed'); +} + +const by = (context: unknown) => ({ context }) as never; +const multi = (where: unknown, context: unknown = CALLER) => ({ where, multi: true, context }) as never; + +const SHAPES: ReadonlyArray = [ + ['a store that runs the probe', { probe: true, transactions: true }], + ['a store that cannot run the line probe', { probe: false, transactions: true }], +]; + +for (const [label, shape] of SHAPES) { + describe(`[ADR-0162 D4] the closed-state lock on ${label}`, () => { + // ── the record itself ────────────────────────────────────────────────── + it('a closed record refuses a by-id update, whichever field it carries; an open one takes it (control)', async () => { + await boot(shape); + const err = await refusal(() => engine.update(INVOICE, { id: 'inv_paid', amount: 99 }, by(CALLER))); + expect([err.code, err.status, err.reason]).toEqual(['RECORD_LOCKED', 409, 'record_closed']); + await engine.update(INVOICE, { id: 'inv_open', amount: 99 }, by(CALLER)); + expect(await stored(INVOICE, 'amount')).toEqual(['inv_open2:10', 'inv_open:99', 'inv_paid:10', 'inv_void:10']); + }); + + it('the state field is frozen with the rest: a caller cannot reopen a closed record', async () => { + await boot(shape); + const err = await refusal(() => engine.update(INVOICE, { id: 'inv_void', status: 'draft' }, by(CALLER))); + expect(err.code).toBe('RECORD_LOCKED'); + expect(await stored(INVOICE, 'status')).toContain('inv_void:void'); + }); + + it('an update that carries no field writes nothing and is not refused', async () => { + await boot(shape); + await engine.update(INVOICE, { id: 'inv_paid' }, by(CALLER)); + }); + + it('a closed record refuses a by-id delete, and stays', async () => { + await boot(shape); + const err = await refusal(() => engine.delete(INVOICE, { where: { id: 'inv_paid' }, context: CALLER } as never)); + expect([err.code, err.reason]).toEqual(['RECORD_LOCKED', 'record_closed']); + expect(await stored(INVOICE, 'status')).toContain('inv_paid:paid'); + }); + + it('a predicate update that reaches one closed record is refused whole; no row changes', async () => { + await boot(shape); + const err = await refusal(() => engine.update(INVOICE, { amount: 7 }, multi({ amount: 10 }))); + expect([err.code, err.reason]).toEqual(['RECORD_LOCKED', 'record_closed']); + expect(await stored(INVOICE, 'amount')).toEqual(['inv_open2:10', 'inv_open:10', 'inv_paid:10', 'inv_void:10']); + // control: a predicate that reaches only open records lands. + await engine.update(INVOICE, { amount: 7 }, multi({ status: { $in: ['draft', 'sent'] } })); + expect(await stored(INVOICE, 'amount')).toEqual(['inv_open2:7', 'inv_open:7', 'inv_paid:10', 'inv_void:10']); + }); + + it('a predicate delete that reaches one closed record is refused whole; no row is removed', async () => { + await boot(shape); + const err = await refusal(() => engine.delete(INVOICE, multi({ customer: 'cu1' }))); + expect(err.code).toBe('RECORD_LOCKED'); + expect(await stored(INVOICE, 'status')).toHaveLength(4); + }); + + it('a create of a record in a closed state is not judged (no stored state yet)', async () => { + await boot(shape); + await engine.insert(INVOICE, { id: 'inv_born_paid', name: 'x', status: 'paid', amount: 1 }, by(CALLER)); + expect(await stored(INVOICE, 'status')).toContain('inv_born_paid:paid'); + }); + + // ── a line of the record ────────────────────────────────────────────── + it('a line create under a closed master is refused; under an open one it lands (control)', async () => { + await boot(shape); + const err = await refusal(() => engine.insert(LINE, { name: 'n', qty: 1, invoice: 'inv_paid' }, by(CALLER))); + expect([err.code, err.reason, err.blockingObject]).toEqual(['RECORD_LOCKED', 'master_closed', INVOICE]); + await engine.insert(LINE, { id: 'l_new', name: 'n', qty: 1, invoice: 'inv_open' }, by(CALLER)); + expect(await stored(LINE, 'invoice')).toContain('l_new:inv_open'); + }); + + it('a many-row create of lines is refused whole when one row names a closed master', async () => { + await boot(shape); + const err = await refusal(() => engine.insert(LINE, [ + { id: 'l_a', name: 'a', qty: 1, invoice: 'inv_open' }, + { id: 'l_b', name: 'b', qty: 1, invoice: 'inv_void' }, + ], by(CALLER))); + expect(err.code).toBe('RECORD_LOCKED'); + expect(await stored(LINE, 'invoice')).toEqual(['l_open2:inv_open2', 'l_open:inv_open', 'l_paid2:inv_paid', 'l_paid:inv_paid']); + }); + + it('a line of a closed record refuses an update and a delete', async () => { + await boot(shape); + expect((await refusal(() => engine.update(LINE, { id: 'l_paid', qty: 5 }, by(CALLER)))).reason).toBe('master_closed'); + expect((await refusal(() => engine.delete(LINE, { where: { id: 'l_paid' }, context: CALLER } as never))).reason).toBe('master_closed'); + expect(await stored(LINE, 'qty')).toEqual(['l_open2:1', 'l_open:1', 'l_paid2:1', 'l_paid:1']); + }); + + it('a move is refused at either end: out of a closed master, and into one; open to open lands', async () => { + await boot(shape); + expect((await refusal(() => engine.update(LINE, { id: 'l_paid', invoice: 'inv_open' }, by(CALLER)))).reason).toBe('master_closed'); + expect((await refusal(() => engine.update(LINE, { id: 'l_open', invoice: 'inv_paid' }, by(CALLER)))).reason).toBe('master_closed'); + await engine.update(LINE, { id: 'l_open', invoice: 'inv_open2' }, by(CALLER)); + expect(await stored(LINE, 'invoice')).toContain('l_open:inv_open2'); + }); + + it('a predicate update of lines that reaches one line of a closed record is refused whole', async () => { + await boot(shape); + const err = await refusal(() => engine.update(LINE, { qty: 3 }, multi({ qty: 1 }))); + expect([err.code, err.reason]).toEqual(['RECORD_LOCKED', 'master_closed']); + expect(await stored(LINE, 'qty')).toEqual(['l_open2:1', 'l_open:1', 'l_paid2:1', 'l_paid:1']); + // control: lines of open records only. + await engine.update(LINE, { qty: 3 }, multi({ invoice: { $in: ['inv_open', 'inv_open2'] } })); + expect(await stored(LINE, 'qty')).toEqual(['l_open2:3', 'l_open:3', 'l_paid2:1', 'l_paid:1']); + }); + + it('a predicate delete of lines that reaches one line of a closed record is refused whole', async () => { + await boot(shape); + const err = await refusal(() => engine.delete(LINE, multi({ qty: 1 }))); + expect(err.reason).toBe('master_closed'); + expect(await stored(LINE, 'qty')).toHaveLength(4); + }); + + it('a predicate update that moves open lines into a closed master is refused', async () => { + await boot(shape); + const err = await refusal(() => engine.update(LINE, { invoice: 'inv_paid' }, multi({ invoice: 'inv_open' }))); + expect(err.reason).toBe('master_closed'); + expect(await stored(LINE, 'invoice')).toContain('l_open:inv_open'); + }); + + it('a junction row is a line of both masters: closed when either is', async () => { + await boot(shape); + // a_frozen hangs under an open invoice and a frozen budget. + expect((await refusal(() => engine.update(ALLOC, { id: 'a_frozen', name: 'z' }, by(CALLER)))).blockingObject).toBe(BUDGET); + await engine.update(ALLOC, { id: 'a_open', name: 'z' }, by(CALLER)); + expect((await refusal(() => engine.update(ALLOC, { name: 'y' }, multi({ invoice: 'inv_open' })))).blockingObject).toBe(BUDGET); + }); + + it('a predicate move out of a closed master is refused whole', async () => { + await boot(shape); + const err = await refusal(() => engine.update(LINE, { invoice: 'inv_open' }, multi({ invoice: 'inv_paid' }))); + expect(err.reason).toBe('master_closed'); + expect((await stored(LINE, 'invoice')).filter((r) => r.endsWith(':inv_paid'))).toHaveLength(2); + }); + + it('a many-row create of records in a closed state is not judged', async () => { + await boot(shape); + await engine.insert(INVOICE, [ + { id: 'inv_b1', name: 'b1', status: 'paid', amount: 1 }, + { id: 'inv_b2', name: 'b2', status: 'void', amount: 1 }, + ], by(CALLER)); + expect(await stored(INVOICE, 'status')).toEqual(expect.arrayContaining(['inv_b1:paid', 'inv_b2:void'])); + }); + + it('a refused write runs no before-phase hook (D10)', async () => { + await boot(shape); + const ran: string[] = []; + engine.registerHook('beforeUpdate', async (ctx: { object: string }) => { ran.push(ctx.object); }, { object: [INVOICE, LINE] } as never); + engine.registerHook('beforeDelete', async (ctx: { object: string }) => { ran.push(ctx.object); }, { object: [INVOICE, LINE] } as never); + await refusal(() => engine.update(INVOICE, { id: 'inv_paid', amount: 1 }, by(CALLER))); + await refusal(() => engine.update(LINE, { id: 'l_paid', qty: 1 }, by(CALLER))); + await refusal(() => engine.update(LINE, { qty: 2 }, multi({ qty: 1 }))); + await refusal(() => engine.delete(INVOICE, { where: { id: 'inv_paid' }, context: CALLER } as never)); + await refusal(() => engine.delete(LINE, multi({ qty: 1 }))); + expect(ran).toEqual([]); + await engine.update(INVOICE, { id: 'inv_open', amount: 1 }, by(CALLER)); + expect(ran).toEqual([INVOICE]); + }); + + it(`a predicate line write is judged ${shape.probe ? 'by one statement on the line table' : 'from the matched rows and one read of their masters'}`, async () => { + await boot(shape); + const seen: string[] = []; + const find = driver.find.bind(driver); + (driver as unknown as { find: typeof find }).find = (async (object: string, ast: unknown, opts: unknown) => { + seen.push(object); + return find(object as never, ast as never, opts as never); + }) as typeof find; + await engine.update(LINE, { qty: 8 }, multi({ invoice: 'inv_open' })); + if (shape.probe) { + expect(seen.filter((o) => o === INVOICE)).toEqual([]); + expect(seen.filter((o) => o === LINE)).toHaveLength(1); + } else { + expect(seen.filter((o) => o === LINE)).toHaveLength(1); + expect(seen.filter((o) => o === INVOICE)).toHaveLength(1); + } + }); + + // ── what cannot be judged (D4) ───────────────────────────────────────── + it('cannot judge: a line write that names its master by something that is not one id', async () => { + await boot(shape); + const err = await refusal(() => engine.insert(LINE, { name: 'n', qty: 1, invoice: { id: 'inv_open' } }, by(CALLER))); + expect([err.code, err.reason]).toEqual(['RECORD_LOCKED', 'cannot_judge']); + }); + + it('cannot judge: a read of the state that fails', async () => { + await boot(shape); + const find = driver.find.bind(driver); + (driver as unknown as { find: typeof find }).find = (async (object: string, ast: unknown, opts: unknown) => { + if (object === INVOICE && (ast as { fields?: string[] })?.fields?.includes('status')) throw new Error('store unavailable'); + return find(object as never, ast as never, opts as never); + }) as typeof find; + const err = await refusal(() => engine.update(LINE, { id: 'l_open', qty: 9 }, by(CALLER))); + expect([err.code, err.reason]).toEqual(['RECORD_LOCKED', 'cannot_judge']); + expect(await stored(LINE, 'qty')).toContain('l_open:1'); + }); + + // ── the write that closes, and who is bound (D4 ▲, D5) ───────────────── + it('a write that closes an open record lands whole with its other fields; the next write is refused', async () => { + await boot(shape); + await engine.update(INVOICE, { id: 'inv_open', status: 'paid', amount: 42 }, by(CALLER)); + expect(await stored(INVOICE, 'amount')).toContain('inv_open:42'); + expect(await stored(INVOICE, 'status')).toContain('inv_open:paid'); + expect((await refusal(() => engine.update(INVOICE, { id: 'inv_open', amount: 43 }, by(CALLER)))).code).toBe('RECORD_LOCKED'); + expect((await refusal(() => engine.insert(LINE, { name: 'late', qty: 1, invoice: 'inv_open' }, by(CALLER)))).code).toBe('RECORD_LOCKED'); + }); + + it('a write with no principal (no context at all) is refused', async () => { + await boot(shape); + expect((await refusal(() => engine.update(INVOICE, { id: 'inv_paid', amount: 1 }))).code).toBe('RECORD_LOCKED'); + expect((await refusal(() => engine.update(LINE, { id: 'l_paid', qty: 2 }))).code).toBe('RECORD_LOCKED'); + }); + + it('a system context writes and deletes a closed record and its lines', async () => { + await boot(shape); + await engine.update(INVOICE, { id: 'inv_paid', amount: 5 }, by(SYS)); + await engine.update(LINE, { id: 'l_paid', qty: 5 }, by(SYS)); + await engine.update(LINE, { qty: 6 }, multi({ invoice: 'inv_paid' }, SYS)); + await engine.insert(LINE, { id: 'l_sys', name: 's', qty: 1, invoice: 'inv_paid' }, by(SYS)); + await engine.delete(INVOICE, { where: { id: 'inv_paid' }, context: SYS } as never); + expect(await stored(INVOICE, 'status')).not.toContain('inv_paid:paid'); + expect((await stored(LINE, 'invoice')).filter((r) => r.endsWith(':inv_paid'))).toEqual([]); + }); + + // ── the delete's cascade (D6) and the referential clear (D7) ─────────── + it('a delete whose cascade reaches a closed record removes no row, and names the object in the way', async () => { + await boot(shape); + const err = await refusal(() => engine.delete(CUSTOMER, { where: { id: 'cu1' }, context: CALLER } as never)); + expect([err.code, err.reason, err.blockingObject]).toEqual(['RECORD_LOCKED', 'cascade_reaches_closed', INVOICE]); + expect(await stored(CUSTOMER, 'name')).toEqual(['cu1:Acme']); + expect(await stored(INVOICE, 'status')).toHaveLength(4); + expect(await stored(LINE, 'qty')).toHaveLength(4); + // a system context deletes, its cascade with it. + await engine.delete(CUSTOMER, { where: { id: 'cu1' }, context: SYS } as never); + expect(await stored(INVOICE, 'status')).toEqual([]); + }); + + it('a referential clear lands on a closed record: exactly the cleared field', async () => { + await boot(shape); + await engine.delete(CONTACT, { where: { id: 'ct1' }, context: CALLER } as never); + expect(await stored(INVOICE, 'contact')).toEqual(['inv_open2:null', 'inv_open:null', 'inv_paid:null', 'inv_void:null']); + expect(await stored(INVOICE, 'status')).toContain('inv_paid:paid'); + }); + }); +} + +describe('[ADR-0162 D4] the per-row ceiling on a store that cannot run the line probe', () => { + const seedLines = async (count: number) => { + const rows = Array.from({ length: count }, (_, i) => ({ + id: `bulk_${i}`, name: 'bulk', qty: 4, invoice: 'inv_open', organization_id: DEFAULT_ORGANIZATION_ID, + })); + const k = (driver as unknown as { knex: (t: string) => { insert: (r: unknown[]) => Promise } }).knex; + for (let i = 0; i < rows.length; i += 400) await k(LINE).insert(rows.slice(i, i + 400)); + }; + + it('a predicate line write whose matched rows pass the ceiling cannot be judged, and is refused', async () => { + await boot({ probe: false, transactions: true }); + await seedLines(MAX_BULK_PER_ROW_HOOK_ROWS + 1); + const err = await refusal(() => engine.update(LINE, { qty: 5 }, multi({ qty: 4 }))); + expect([err.code, err.reason]).toEqual(['RECORD_LOCKED', 'cannot_judge']); + expect(String(err.message)).toContain(String(MAX_BULK_PER_ROW_HOOK_ROWS)); + }, 60_000); + + it('CONTROL: the same write on a store that runs the probe is judged by one statement and lands', async () => { + await boot({ probe: true, transactions: true }); + await seedLines(MAX_BULK_PER_ROW_HOOK_ROWS + 1); + await engine.update(LINE, { qty: 5 }, multi({ qty: 4 })); + const rows = await knex()(LINE).select('id', 'qty'); + expect(rows.filter((r) => r.qty === 5)).toHaveLength(MAX_BULK_PER_ROW_HOOK_ROWS + 1); + }, 60_000); +}); + +describe('[ADR-0162 D6] a refused cascade removes no row, with and without transactions', () => { + for (const transactions of [true, false]) { + it(`on a store ${transactions ? 'with' : 'without'} transactions`, async () => { + await boot({ probe: true, transactions }); + const before = [await stored(CUSTOMER, 'name'), await stored(INVOICE, 'status'), await stored(LINE, 'qty')]; + expect((await refusal(() => engine.delete(CUSTOMER, { where: { id: 'cu1' }, context: CALLER } as never))).reason).toBe('cascade_reaches_closed'); + expect([await stored(CUSTOMER, 'name'), await stored(INVOICE, 'status'), await stored(LINE, 'qty')]).toEqual(before); + }); + } +}); + +describe('[ADR-0162 D7] restore', () => { + const entryFor = async (object: string, id: string): Promise => { + const rows = await knex()('sys_recycle_bin').select('id', 'object_name', 'record_id'); + const hit = rows.find((r) => r.object_name === object && r.record_id === id); + if (!hit) throw new Error(`no recycle-bin entry for ${object}/${id}`); + return String(hit.id); + }; + + it('refuses to put a line back under a live closed master that is not part of the entry; a system context restores', async () => { + await boot({ probe: true, transactions: true }, { recycleBin: true }); + await engine.delete(LINE, { where: { id: 'l_open' }, context: CALLER } as never); + await engine.update(INVOICE, { id: 'inv_open', status: 'paid' }, by(CALLER)); + const entry = await entryFor(LINE, 'l_open'); + const err = await refusal(() => engine.restore(entry, { context: CALLER } as never)); + expect([err.code, err.reason, err.blockingObject]).toEqual(['RECORD_LOCKED', 'master_closed', INVOICE]); + expect(await stored(LINE, 'invoice')).not.toContain('l_open:inv_open'); + await engine.restore(entry, { context: SYS } as never); + expect(await stored(LINE, 'invoice')).toContain('l_open:inv_open'); + }); + + it('an entry comes back as it stood, closed or not: a closed record restored with its lines', async () => { + await boot({ probe: true, transactions: true }, { recycleBin: true }); + await engine.delete(INVOICE, { where: { id: 'inv_paid' }, context: SYS } as never); + const entry = await entryFor(INVOICE, 'inv_paid'); + await engine.restore(entry, { context: SYS } as never); + expect(await stored(INVOICE, 'status')).toContain('inv_paid:paid'); + expect((await stored(LINE, 'invoice')).filter((r) => r.endsWith(':inv_paid'))).toHaveLength(2); + }); + + it('CONTROL: a line restored under an open master lands for the caller', async () => { + await boot({ probe: true, transactions: true }, { recycleBin: true }); + await engine.delete(LINE, { where: { id: 'l_open' }, context: CALLER } as never); + await engine.restore(await entryFor(LINE, 'l_open'), { context: CALLER } as never); + expect(await stored(LINE, 'invoice')).toContain('l_open:inv_open'); + }); +}); + +describe('[ADR-0162 D5] engine-derived writes that reach a closed record', () => { + it('the summary recompute writes the closed invoice in a system context, and lands', async () => { + await boot({ probe: true, transactions: true }, { summary: true }); + // The caller writes a payment (a lookup child, not a line): the write is + // free, and the roll-up onto inv_paid is the engine's own write. + await engine.insert(PAYMENT, { id: 'p1', name: 'p1', paid: 7, invoice: 'inv_paid' }, by(CALLER)); + expect(await stored(INVOICE, 'paid_total')).toContain('inv_paid:7'); + // The caller's own write of that field on the closed invoice is still refused. + expect((await refusal(() => engine.update(INVOICE, { id: 'inv_paid', amount: 11 }, by(CALLER)))).code).toBe('RECORD_LOCKED'); + }); + + it('the recycle-bin relink puts a cleared reference back on a closed record, for the caller', async () => { + await boot({ probe: true, transactions: true }, { recycleBin: true }); + await engine.delete(CONTACT, { where: { id: 'ct1' }, context: CALLER } as never); + expect(await stored(INVOICE, 'contact')).toContain('inv_paid:null'); + const rows = await knex()('sys_recycle_bin').select('id', 'object_name', 'record_id'); + const entry = rows.find((r) => r.object_name === CONTACT && r.record_id === 'ct1'); + await engine.restore(String(entry?.id), { context: CALLER } as never); + expect(await stored(INVOICE, 'contact')).toEqual(['inv_open2:ct1', 'inv_open:ct1', 'inv_paid:ct1', 'inv_void:ct1']); + expect(await stored(INVOICE, 'status')).toContain('inv_paid:paid'); + }); +}); + +describe('[ADR-0162 D10] free when not declared, and a master the write names', () => { + it('an object that neither declares the key nor is a line of one reads nothing extra', async () => { + await boot({ probe: true, transactions: true }); + const seen: string[] = []; + const find = driver.find.bind(driver); + (driver as unknown as { find: typeof find }).find = (async (object: string, ast: unknown, opts: unknown) => { + seen.push(object); + return find(object as never, ast as never, opts as never); + }) as typeof find; + await engine.update(CUSTOMER, { id: 'cu1', name: 'Acme 2' }, by(CALLER)); + await engine.update(CUSTOMER, { name: 'Acme 3' }, multi({ id: 'cu1' })); + expect(seen.filter((o) => o === INVOICE || o === BUDGET)).toEqual([]); + }); + + it('a master a beforeInsert hook supplies is not judged by the lock (the lock runs before the hooks)', async () => { + await boot({ probe: true, transactions: true }); + engine.registerHook('beforeInsert', (async (ctx: { input: { data: Record } }) => { + if (ctx.input.data.name === 'hooked') ctx.input.data.invoice = 'inv_paid'; + }) as never, { object: LINE } as never); + await engine.insert(LINE, { id: 'l_hooked', name: 'hooked', qty: 1, invoice: 'inv_open' }, by(CALLER)); + expect(await stored(LINE, 'invoice')).toContain('l_hooked:inv_paid'); + }); +}); + +describe('[ADR-0162 D7] Change Owner and the hand-over of a user\'s work are bound like any edit', () => { + const seedUsers = async () => { + for (const id of ['usr_a', 'usr_b']) { + await engine.insert('sys_user', { id, name: id, email: `${id}@example.com` }, { context: SYS } as never); + } + for (const id of ['inv_open', 'inv_paid', 'inv_void']) await engine.update(INVOICE, { id, owner_id: 'usr_a' }, by(SYS)); + for (const id of ['l_open', 'l_paid']) await engine.update(LINE, { id, owner_id: 'usr_a' }, by(SYS)); + }; + + it('the bulk form moves the open records and lists each closed one among its failures, with RECORD_LOCKED', async () => { + await boot({ probe: true, transactions: true }, { users: true }); + await seedUsers(); + const report = await changeRecordsOwner(engine as never, INVOICE, ['inv_open', 'inv_paid', 'inv_void'], { ownerId: 'usr_b' }, CALLER); + expect(report.updated).toBe(1); + expect(report.failed).toBe(2); + expect(report.failures.map((f: { id: unknown; code?: unknown }) => [f.id, f.code])).toEqual([ + ['inv_paid', 'RECORD_LOCKED'], + ['inv_void', 'RECORD_LOCKED'], + ]); + expect(await stored(INVOICE, 'owner_id')).toEqual(['inv_open2:null', 'inv_open:usr_b', 'inv_paid:usr_a', 'inv_void:usr_a']); + }); + + it('a line of a closed record keeps its owner the same way', async () => { + await boot({ probe: true, transactions: true }, { users: true }); + await seedUsers(); + const report = await changeRecordsOwner(engine as never, LINE, ['l_open', 'l_paid'], { ownerId: 'usr_b' }, CALLER); + expect(report.failures.map((f: { id: unknown; code?: unknown }) => [f.id, f.code])).toEqual([['l_paid', 'RECORD_LOCKED']]); + }); + + it('the hand-over of a user\'s work leaves the closed records with that user and counts them among the failures', async () => { + await boot({ probe: true, transactions: true }, { users: true }); + await seedUsers(); + const report = await transferUserAssignedWork(engine as never, 'usr_a', 'usr_b', CALLER, { objects: [INVOICE] }); + const invoice = report.objects.find((o: { object: string }) => o.object === INVOICE)!; + expect([invoice.updated, invoice.failed]).toEqual([1, 2]); + expect(invoice.failures.every((f: { code?: unknown }) => f.code === 'RECORD_LOCKED')).toBe(true); + expect(await stored(INVOICE, 'owner_id')).toEqual(['inv_open2:null', 'inv_open:usr_b', 'inv_paid:usr_a', 'inv_void:usr_a']); + }); + + it('CONTROL: a system context changes the owner of a closed record', async () => { + await boot({ probe: true, transactions: true }, { users: true }); + await seedUsers(); + const report = await changeRecordsOwner(engine as never, INVOICE, ['inv_paid'], { ownerId: 'usr_b' }, SYS); + expect([report.updated, report.failed]).toEqual([1, 0]); + }); +}); From 2cca4a6871244e2ee375c029865582bb428847c0 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 02:08:59 +0000 Subject: [PATCH 11/32] feat(objectql): the registry fold keeps a package's closedStates honest (ADR-0162 D1) An extension's redeclaration that removes, retypes, makes multi-value or narrows a field the served declaration names is refused at the fold (the field stands, the fold logs once, the rest of the extension lands). A tenant overlay may add closed values and may not shorten the package's list or break a field it names. Claude-Session: https://claude.ai/code/session_01L6bhgTCFhayR5cBZXM7XPP Co-authored-by: Claude --- .../src/registry-closed-state-fold.test.ts | 159 ++++++++++++++++++ .../src/registry-closed-state-fold.ts | 114 +++++++++++++ .../src/registry-object-registration.ts | 8 +- 3 files changed, 280 insertions(+), 1 deletion(-) create mode 100644 packages/objectql/src/registry-closed-state-fold.test.ts create mode 100644 packages/objectql/src/registry-closed-state-fold.ts diff --git a/packages/objectql/src/registry-closed-state-fold.test.ts b/packages/objectql/src/registry-closed-state-fold.test.ts new file mode 100644 index 00000000000..0254558d0b7 --- /dev/null +++ b/packages/objectql/src/registry-closed-state-fold.test.ts @@ -0,0 +1,159 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 D1] The registry fold keeps a package's `closedStates` honest + * (`registry-closed-state-fold.ts`). + * + * The object's own parse refuses a declaration whose field is gone, retyped, + * multi-value or short of a listed option. The served object is a fold of + * layers the parse never sees together, so the fold holds the same line: + * + * - an extension's redeclaration of a field the declaration names is refused + * where it removes, retypes, makes multi-value or narrows it (one test per + * case), and the rest of the extension still lands; + * - a tenant overlay may add closed values, and may not shorten the + * package's list or break a field it names. + */ + +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { ObjectQL } from './engine.js'; + +const OWNER_PKG = 'com.example.billing'; +const EXT_PKG = 'com.example.ext'; + +const STATUS = { + type: 'select', + label: 'Status', + options: [ + { label: 'Draft', value: 'draft' }, + { label: 'Paid', value: 'paid' }, + { label: 'Void', value: 'void' }, + ], +}; + +const owner = () => ({ + name: 'cs_invoice', + label: 'Invoice', + fields: { name: { type: 'text', label: 'Number' }, status: STATUS }, + closedStates: { status: ['paid', 'void'] }, +}); + +function makeDriver() { + return { + name: 'com.objectstack.driver.memory.cs-fold', + version: '1.0.0', + async connect() {}, async disconnect() {}, async initObjects() {}, + async find() { return []; }, async findOne() { return null; }, async count() { return 0; }, + async create(_o: string, d: unknown) { return d; }, async update(_o: string, d: unknown) { return d; }, async delete() { return false; }, + } as any; +} + +let engine: ObjectQL; +async function boot(): Promise { + engine = new ObjectQL(); + engine.registerDriver(makeDriver(), true); + await engine.init(); +} +afterEach(async () => { try { await engine?.destroy(); } catch { /* noop */ } vi.restoreAllMocks(); }); + +const served = () => engine.registry.getObject('cs_invoice') as any; + +describe('[ADR-0162 D1] an extension cannot break a field the served closedStates names', () => { + const cases: ReadonlyArray, string]> = [ + ['retypes it', { type: 'text', label: 'Status' }, 'retypes it as `text`'], + ['makes it multi-value', { ...STATUS, multiple: true }, 'makes it a multi-value select'], + ['narrows its options past a listed value', { ...STATUS, options: STATUS.options.slice(0, 2) }, "drops the listed option 'void'"], + ['leaves it with no inline options', { type: 'select', label: 'Status', picklist: 'other' }, 'leaves it with no inline options'], + ]; + for (const [label, redeclared, said] of cases) { + it(`refuses an extension that ${label}, and applies the rest of the extension`, async () => { + await boot(); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + engine.registry.registerObject(owner() as any, OWNER_PKG); + engine.registry.registerObject({ + name: 'cs_invoice', + fields: { status: redeclared, memo: { type: 'text', label: 'Memo' } }, + } as any, EXT_PKG, undefined, 'extend'); + const obj = served(); + expect(obj.fields.status).toEqual(STATUS); + expect(obj.fields.memo?.type).toBe('text'); + expect(obj.closedStates).toEqual({ status: ['paid', 'void'] }); + const lines = warn.mock.calls.map((c) => String(c[0])).filter((m) => m.includes('closedStates')); + expect(lines).toHaveLength(1); + expect(lines[0]).toContain(said); + expect(lines[0]).toContain(EXT_PKG); + }); + } + + it('CONTROL: an extension that adds an option to the named field lands', async () => { + await boot(); + vi.spyOn(console, 'warn').mockImplementation(() => {}); + engine.registry.registerObject(owner() as any, OWNER_PKG); + const wider = { ...STATUS, options: [...STATUS.options, { label: 'Refunded', value: 'refunded' }] }; + engine.registry.registerObject({ name: 'cs_invoice', fields: { status: wider } } as any, EXT_PKG, undefined, 'extend'); + expect(served().fields.status.options.map((o: { value: string }) => o.value)).toEqual(['draft', 'paid', 'void', 'refunded']); + }); + + it('CONTROL: an object no layer declares closedStates on folds as before', async () => { + await boot(); + vi.spyOn(console, 'warn').mockImplementation(() => {}); + const { closedStates: _none, ...plain } = owner(); + engine.registry.registerObject(plain as any, OWNER_PKG); + engine.registry.registerObject({ name: 'cs_invoice', fields: { status: { type: 'text', label: 'Status' } } } as any, EXT_PKG, undefined, 'extend'); + expect(served().fields.status.type).toBe('text'); + expect(served().closedStates).toBeUndefined(); + }); +}); + +describe('[ADR-0162 D1] a tenant overlay may add closed values, and may not shorten the package\'s list', () => { + const overlay = (body: Record) => + engine.registry.registerObject({ ...body, _provenance: 'org' } as any, OWNER_PKG, undefined, 'overlay'); + + it('may ADD: an overlay that declares closed values of its own is served with them', async () => { + await boot(); + engine.registry.registerObject(owner() as any, OWNER_PKG); + overlay({ ...owner(), closedStates: { status: ['paid', 'void', 'draft'] } }); + expect(served().closedStates).toEqual({ status: ['paid', 'void', 'draft'] }); + }); + + it('may add a declaration to a package object that has none', async () => { + await boot(); + const { closedStates: _none, ...plain } = owner(); + engine.registry.registerObject(plain as any, OWNER_PKG); + overlay({ ...plain, closedStates: { status: ['void'] } }); + expect(served().closedStates).toEqual({ status: ['void'] }); + }); + + it('may not shorten: an overlay that leaves the key out, or lists less, is served the package\'s list', async () => { + await boot(); + engine.registry.registerObject(owner() as any, OWNER_PKG); + const { closedStates: _dropped, ...withoutKey } = owner(); + overlay(withoutKey); + expect(served().closedStates).toEqual({ status: ['paid', 'void'] }); + }); + + it('may not shorten by listing fewer values', async () => { + await boot(); + engine.registry.registerObject(owner() as any, OWNER_PKG); + overlay({ ...owner(), closedStates: { status: ['paid'] } }); + expect(served().closedStates).toEqual({ status: ['paid', 'void'] }); + }); + + it('may not break the named field: an overlay that drops a listed option is served the package\'s field', async () => { + await boot(); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + engine.registry.registerObject(owner() as any, OWNER_PKG); + const { closedStates: _dropped, ...rest } = owner(); + overlay({ ...rest, fields: { ...rest.fields, status: { ...STATUS, options: STATUS.options.slice(0, 2) } } }); + expect(served().fields.status).toEqual(STATUS); + expect(warn.mock.calls.map((c) => String(c[0])).some((m) => m.includes("drops the listed option 'void'"))).toBe(true); + }); + + it('CONTROL: an overlay that only relabels keeps its label and the package\'s list', async () => { + await boot(); + engine.registry.registerObject(owner() as any, OWNER_PKG); + overlay({ ...owner(), label: 'Customer invoice' }); + expect(served().label).toBe('Customer invoice'); + expect(served().closedStates).toEqual({ status: ['paid', 'void'] }); + }); +}); diff --git a/packages/objectql/src/registry-closed-state-fold.ts b/packages/objectql/src/registry-closed-state-fold.ts new file mode 100644 index 00000000000..35337ea9b9e --- /dev/null +++ b/packages/objectql/src/registry-closed-state-fold.ts @@ -0,0 +1,114 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 D1] The registry fold keeps a `closedStates` declaration honest. + * + * The object's own parse refuses a declaration that names a field which is + * missing, not a single-value `select`, or lacks one of the listed options + * (`packages/spec/src/data/closed-states.ts#refuseDishonestClosedStates`). The + * served object is not one document, though: the fold lays a tenant overlay + * base and other packages' `extend` bodies over the owner's + * (`registry-object-registration.ts#foldExtendersOntoDefinition`), and the + * object's refinement is not run again over the result. Two layers could then + * take from a package's declaration what its own parse protects: + * + * - **An extension** that redeclares, in its `fields`, a field the served + * declaration names, as another type, as a multi-value select, or with + * options that leave out a listed value. Its redeclaration of THAT field is + * refused at the fold: the field the fold had stands, and the fold says so + * once in the log. The rest of the extension is applied as before. + * - **A tenant overlay** (the base the fold starts from, ADR-0029 D9.2). It + * may add closed values of its own, which an overlay body can always carry; + * it may not shorten a package's own list. The served declaration is the + * package's, with the overlay's added to it, and a field the package's list + * names keeps the package's definition where the overlay removed it, + * retyped it, made it multi-value or dropped a listed option. + * + * Neither changes an object no layer declares `closedStates` on. + */ + +import { closedValuesOf, type ClosedValues } from './closed-state-values.js'; + +type Body = { name?: unknown; fields?: Record; closedStates?: Record }; + +/** Why `field` cannot carry `listed`, or `undefined` when it can. */ +export function closedStateFieldBreach(field: unknown, listed: ReadonlySet): string | undefined { + if (!field || typeof field !== 'object') return 'removes it'; + const def = field as { type?: unknown; multiple?: unknown; options?: unknown }; + if (def.type !== 'select') return `retypes it as \`${String(def.type)}\``; + if (def.multiple === true) return 'makes it a multi-value select'; + if (!Array.isArray(def.options)) return 'leaves it with no inline options'; + const values = new Set(def.options.map((o) => (o && typeof o === 'object' ? (o as { value?: unknown }).value : o))); + const dropped = [...listed].filter((v) => !values.has(v)); + if (dropped.length > 0) return `drops the listed option${dropped.length > 1 ? 's' : ''} ${dropped.map((v) => `'${v}'`).join(', ')}`; + return undefined; +} + +/** + * The extension body with every redeclaration of a field the running + * declaration names removed where it would break that declaration. Answers the + * body itself when nothing is refused. + */ +export function withoutClosedStateFieldBreaches(running: Body, extension: T, packageId: string | undefined): T { + const closed = closedValuesOf(running); + const fields = extension.fields; + if (!closed || !fields || typeof fields !== 'object') return extension; + let kept: Record | undefined; + for (const [name, listed] of closed) { + if (!Object.prototype.hasOwnProperty.call(fields, name)) continue; + const breach = closedStateFieldBreach(fields[name], listed); + if (breach === undefined) continue; + kept ??= { ...fields }; + delete kept[name]; + console.warn( + `[Registry] An extension of object "${String(running.name ?? extension.name ?? '')}"` + + `${packageId ? ` from package "${packageId}"` : ''} redeclares field "${name}" in a way that ${breach}, ` + + 'and the object\'s `closedStates` names that field. The redeclaration is refused and the field stands as the ' + + 'fold had it: a closed-state declaration names a stored single-value `select` and its own options. ' + + 'Patch the field\'s display properties instead (`fieldPatches`), or add options without removing a listed one.', + ); + } + return kept ? { ...extension, fields: kept } : extension; +} + +/** `a` with every value of `b` added, per field. */ +function unionClosed(a: ClosedValues, b: ClosedValues | undefined): Record { + const out: Record = {}; + for (const [field, values] of a) out[field] = [...values]; + for (const [field, values] of b ?? []) { + const list = out[field] ?? (out[field] = []); + for (const v of values) if (!list.includes(v)) list.push(v); + } + return out; +} + +/** + * The fold's base where it is a tenant overlay over a package's object: the + * package's `closedStates` kept whole, the overlay's own values added, and the + * package's definition kept for each field its list names where the overlay + * broke it. Answers `base` itself when the owner declares nothing or the base + * is the owner's own body. + */ +export function withPackagedClosedStates(owner: Body | undefined, base: T): T { + if (!owner || owner === base) return base; + const packaged = closedValuesOf(owner); + if (!packaged) return base; + const out: T = { ...base, closedStates: unionClosed(packaged, closedValuesOf(base)) }; + const fields = base.fields && typeof base.fields === 'object' ? { ...base.fields } : {}; + let restored = false; + for (const [name, listed] of packaged) { + const breach = closedStateFieldBreach(fields[name], listed); + if (breach === undefined) continue; + const ownerField = owner.fields?.[name]; + if (ownerField === undefined) continue; + fields[name] = ownerField; + restored = true; + console.warn( + `[Registry] Field "${name}" of object "${String(base.name ?? owner.name ?? '')}": the tenant overlay ${breach}, ` + + 'and the package\'s `closedStates` names the field. The package\'s definition of the field stands: an overlay may add ' + + 'closed values of its own, and may not shorten or break the package\'s list.', + ); + } + if (restored) out.fields = fields; + return out; +} diff --git a/packages/objectql/src/registry-object-registration.ts b/packages/objectql/src/registry-object-registration.ts index a2ec45ab3cd..42865b32a73 100644 --- a/packages/objectql/src/registry-object-registration.ts +++ b/packages/objectql/src/registry-object-registration.ts @@ -45,6 +45,7 @@ * this module. */ +import { withPackagedClosedStates, withoutClosedStateFieldBreaches } from './registry-closed-state-fold.js'; import { BASE_FIELD_DISPLAY_WHITELIST, isInjectedColumnDefinition, materializeTreeSelfReferences, provisionPrimary, resolveInjectedSystemColumns } from '@objectstack/spec/data'; import type { ObjectOwnership, RelatedListsArrangement, ServiceObject } from '@objectstack/spec/data'; import { QUEUE_FIELD_DEF, applyAuditFieldGovernance, fieldPatchTargetMisses, installedManifestsOf, isCodeArtifactBody, isTenantAuthored, pairsOf } from '@objectstack/metadata-core'; @@ -927,6 +928,9 @@ export class ObjectRegistrationFacet { let merged = tenantRules ? this.withPackagedOwnerRules(contributors, baseDefinition, tenantRules) : { ...baseDefinition }; + // [ADR-0162 D1] A tenant overlay base may add closed values of its own + // and may not shorten the package's list, or break a field it names. + if (owner && owner !== baseDefinition) merged = withPackagedClosedStates(owner, merged); // [#28835] Each extension's `fields` as the merge took them, in fold order. const folded: FoldedExtensionFields[] = []; for (const contrib of contributors) { @@ -950,7 +954,9 @@ export class ObjectRegistrationFacet { const admitted = misses.length > 0 ? { ...extension, fieldPatches: admittedFieldPatches(patches!, misses) } as ObjectExtensionBody : extension; - merged = mergeObjectDefinitions(merged, admitted, tenantAuthored, tenantRules, tenantPatched, ownFields); + // [ADR-0162 D1] An extension's redeclaration of a field the served + // `closedStates` names is refused where it would break the declaration. + merged = mergeObjectDefinitions(merged, withoutClosedStateFieldBreaches(merged, admitted, contrib.packageId), tenantAuthored, tenantRules, tenantPatched, ownFields); // [#28809] …and the same judge once more, over the admitted patches // against the owner's fields as MERGED, which only names: an admitted // option an earlier layer left out (an extension's `fields` From 1f399d905b8e1388e1a28e879e43fbb829398d40 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 02:08:59 +0000 Subject: [PATCH 12/32] chore(spec): closedStates is live; RECORD_LOCKED is registered for objectql (ADR-0162) The liveness row flips to live with the engine's reads and the dogfood suite as evidence; state counts regenerated. The error-code ledger names objectql as an emitter of RECORD_LOCKED. Changeset for objectql (minor). Claude-Session: https://claude.ai/code/session_01L6bhgTCFhayR5cBZXM7XPP Co-authored-by: Claude --- .changeset/37768-closed-states-objectql.md | 17 +++++++++++++++++ .changeset/37768-closed-states-spec.md | 1 + packages/spec/liveness/object.json | 8 ++++---- packages/spec/liveness/state-counts/object.md | 2 +- packages/spec/src/api/error-code-ledger.zod.ts | 10 ++++++++++ 5 files changed, 33 insertions(+), 5 deletions(-) create mode 100644 .changeset/37768-closed-states-objectql.md diff --git a/.changeset/37768-closed-states-objectql.md b/.changeset/37768-closed-states-objectql.md new file mode 100644 index 00000000000..8042146d6ff --- /dev/null +++ b/.changeset/37768-closed-states-objectql.md @@ -0,0 +1,17 @@ +--- +'@objectstack/objectql': minor +--- + +feat(objectql): a record in a closed state, and its lines, are closed to change (`closedStates`, ADR-0162 D2 to D7, D10) + +Clause-②: yes (widening: the engine enforces the new optional key `ObjectSchema.closedStates`; an object without it behaves exactly as before) +Metadata-protocol: none + +A record whose stored state is one of the values its object lists in `closedStates` is closed, and so are its direct `master_detail` lines (a junction row is a line of both masters). Every write a system context does not make is refused `409 RECORD_LOCKED`, with `reason` (`record_closed`, `master_closed`, `cascade_reaches_closed`, `cannot_judge`), `object`, `blockingObject` and `lockReason: 'closed_state'`; the message names no record id and no state value. + +- **What is judged**: an update or delete of a closed record; a line create, update, delete or move under a closed master, or out of one. An update is judged by the stored row, not by its payload, so the write that closes a record lands whole, other fields included, and the next write is refused. A write with no context is bound. +- **Many-row writes are refused whole**, before any row is written: one existence probe where the store compiles the line semi-join (SQL, the memory driver), otherwise the write's one read of its matched rows, under the engine's per-row ceiling. +- **Refused when it cannot be judged**: a master named in a form the engine cannot read as one id, a master or state read that fails, a many-row line write over the ceiling on a store with no probe. +- **Cascades and restore**: a delete whose cascade reaches a closed record removes no row, with or without transactions; restoring a line under a live closed master that is not part of the entry is refused. The referential clear of a deleted record's references, the recycle-bin relink, and the roll-up summary recompute (a system context) land. Change Owner and the hand-over of a banned user's work are bound like any edit: each closed record is listed among the failures. +- **Placement**: after the permission and record-access gates, before the before-hooks; a master the write names is checked through the caller's own read first. A master a before-hook supplies is not judged. +- **The registry fold** keeps a package's declaration honest: an extension's redeclaration that removes, retypes, makes multi-value or narrows a field the declaration names is refused (the field stands, and the fold logs it once), and a tenant overlay may add closed values but may not shorten the package's list or break a field it names. diff --git a/.changeset/37768-closed-states-spec.md b/.changeset/37768-closed-states-spec.md index 5904b291d91..4a410432ed6 100644 --- a/.changeset/37768-closed-states-spec.md +++ b/.changeset/37768-closed-states-spec.md @@ -12,3 +12,4 @@ An object may now declare the states in which its records are closed: a map from - **Refused where the object is authored**, at parse and at the metadata save and publish door, one located issue each: a key that names no field of the object; a field that is not a single-value `select` (another type, `radio` included, or `multiple: true`); a select whose options are not declared inline on it (a `picklist`-backed select); an empty list; a value that is not one of the field's options; a value listed twice. So is the edit that would leave such a declaration behind: removing or retyping a field, or removing an option, that a declaration still names. Take the entry out of `closedStates` first. - **Optional**: an object without the key behaves exactly as before. A line object declares nothing to be closed with its master, and may declare its own `closedStates`. The key has no tie to a `state_machine` rule in either direction. - Liveness row `object.closedStates`, the Studio object form's Advanced section offers it as a JSON row, and the reference docs, authorable-surface record and state counts are regenerated. +- The error-code ledger registers `RECORD_LOCKED` for `@objectstack/objectql`, the engine's closed-state refusal, beside the approval lock that already emits it. diff --git a/packages/spec/liveness/object.json b/packages/spec/liveness/object.json index 58455f0b4cd..3c1ab5115f3 100644 --- a/packages/spec/liveness/object.json +++ b/packages/spec/liveness/object.json @@ -287,10 +287,10 @@ "note": "renderer only, by ruling (the two-tier field-lock model, its object level): while TRUE no person edits any field of an existing record at the console surfaces a field's own `uiReadonlyWhen` locks; a field that declares `uiReadonly: true` or its own `uiReadonlyWhen` is judged by that instead (`uiReadonly: false` is not a declaration: the field follows the object lock; the opt-out spelling is a field `uiReadonlyWhen` of P`false`). The engine never reads it, so REST, import, action and flow writes keep every field, judged by validations. Fail-closed on a fault, as the field key. The console has no person-triggered record duplicate, so no clone surface reads it; the REST clone door is an API write and keeps every value." }, "closedStates": { - "status": "planned", - "verifiedAt": "2026-11-28", - "evidence": "packages/spec/src/data/closed-states.ts#refuseDishonestClosedStates (the authoring refusals, live at parse and at the save door: a key naming no field, a field that is not a single-value select with inline options, an empty list, a value that is not an option or is repeated; so a removed or retyped field or a removed option under a standing declaration is refused)", - "note": "PLANNED RECORD (ADR-0162 D1, card #37768 slice A): the object's closed states. Its REFUSALS are live at parse (evidence). No runtime reads the key yet: the engine's judgement (ADR-0162 D2-D7, D10) is slice B of the same card and the refusal's code and sentences (D8) are slice C, built on the same trunk branch, which does not merge before both land, so the key is never published without its enforcement (ADR-0078, ADR-0162 D10). It turns live in slice B, with its runtime proof." + "status": "live", + "verifiedAt": "2026-11-29", + "evidence": "packages/objectql/src/closed-state-lock.ts#closedStateUnitOf (the engine's read of the key: the record's own closed values, and each master whose closed values bind a line); packages/objectql/src/closed-state-lock.ts#judgeClosedStateByIdWrite (the by-id update and delete door); packages/objectql/src/closed-state-lock.ts#judgeClosedStatePredicateWrite (the many-row door: one existence probe, or the matched-row read under the per-row ceiling); packages/objectql/src/registry-closed-state-fold.ts#withPackagedClosedStates (the fold keeps a package's list against a tenant overlay); packages/qa/dogfood/test/closed-state-lock.test.ts (runtime proof on SQLite, with and without the line probe and transactions); packages/spec/src/data/closed-states.ts#refuseDishonestClosedStates (the authoring refusals at parse and at the save door)", + "note": "LIVE (ADR-0162 D2-D7, D10; card #37768 slice B): a record whose stored state is a listed value is closed, and so are its direct master_detail lines; every write a system context does not make is refused 409 RECORD_LOCKED, a many-row write whole and before any row is written; a cascade that reaches a closed record removes no row; a restore under a live closed master is refused; a referential clear and the recycle-bin relink land. The lock runs after the middleware gates and before the before-hooks. The extension and overlay fold cannot shorten a package's list or break a field it names. The refusal's sentences (D8) are slice C of the same trunk branch, which does not merge before C lands." }, "validations": { "status": "live", diff --git a/packages/spec/liveness/state-counts/object.md b/packages/spec/liveness/state-counts/object.md index 622d97af478..e433accdd00 100644 --- a/packages/spec/liveness/state-counts/object.md +++ b/packages/spec/liveness/state-counts/object.md @@ -12,4 +12,4 @@ committed anywhere: `check:liveness` sums the shards when it reads them. | Type | live | exp | elsewhere | dead | planned | classified | |---|---|---|---|---|---|---| -| `object` | 95 | 0 | 0 | 1 | 2 | 98 | +| `object` | 96 | 0 | 0 | 1 | 1 | 98 | diff --git a/packages/spec/src/api/error-code-ledger.zod.ts b/packages/spec/src/api/error-code-ledger.zod.ts index 66ff4deb1ab..8aedf2dab8d 100644 --- a/packages/spec/src/api/error-code-ledger.zod.ts +++ b/packages/spec/src/api/error-code-ledger.zod.ts @@ -961,6 +961,16 @@ export const ERROR_CODE_LEDGER = { // assembled vocabulary rejects, both 422/INVALID_METADATA. Provenance, not // identity, per this file's header. 'INVALID_METADATA', + // [ADR-0162 D4, D8] 409 from the closed-state lock (`closed-state-lock.ts`): + // a write a system context does not make reaches a record whose stored + // state its object lists in `closedStates`, or a line of one, a cascade + // that reaches one, or a restore under one; a many-row write is refused + // whole before any row is written. `reason` tells the four apart, and + // `lockReason: 'closed_state'` tells it from the approval lock. Third + // EMITTER of the code `@objectstack/plugin-approvals` registers for the + // pending-approval lock and `@objectstack/rest` relays: one condition, + // the record is not open to change, one code. Provenance, not identity. + 'RECORD_LOCKED', 'ERR_READONLY_FIELD_REJECTED', // strictReadonlyWrites: the write would strip caller-supplied fields, so it was refused (#5126; since #6437 that covers the primary_key strip too — one code, `drops` carries the per-reason breakdown) 'ERR_SUMMARY_RECOMPUTE', // [#8844] A system-context insert on a tenant-scoped application object From a0d9493892f12e1d7b6cbaa5dfddfe4305d97ea7 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 02:15:56 +0000 Subject: [PATCH 13/32] docs(permissions): the closed-state lock is a system-context behaviour (row 29g, ADR-0162 D5) The census reads boundByClosedStates as an elevation read site; the row names it and the site register is regenerated. Claude-Session: https://claude.ai/code/session_01L6bhgTCFhayR5cBZXM7XPP Co-authored-by: Claude --- content/docs/permissions/system-context.mdx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/content/docs/permissions/system-context.mdx b/content/docs/permissions/system-context.mdx index 4fb987ecf85..ef6afe7769b 100644 --- a/content/docs/permissions/system-context.mdx +++ b/content/docs/permissions/system-context.mdx @@ -158,6 +158,7 @@ bugs — it is the protection or the side effect that silently does not happen. | 29d | The recycle bin's tenant wall does not apply: `restore`, `purge` and `empty` read and remove **every organization's** entries | objectql | Get: the bin's own doors reach any entry, as the system reaches every wall. Every caller that is not system is held to the Layer-0 verdict: one the wall denies (a signed-in caller with no active organization under a walled posture) sees no entry, so `restore` answers `null`, `purge` `false` and `empty` `0`, and the removal is scoped by the verdict the security layer recorded on the dispatch when it recorded one (#30237) | `recycleBinWallDenies` | | 29e | A restore of an entry someone else deleted asks **no recycle-bin grant** | objectql | Get: the system restores any entry. Every caller that is not system restores only the entries whose `deleted_by` is its own `userId` unless its effective permissions grant `manageRecycleBin` on the entry's object; otherwise `403 PERMISSION_DENIED`, and the same refusal when no permission resolver is registered or it throws (#30237, ADR-0148 D5) | `assertCallerMayRestoreEntry` | | 29f | Listing the recycle bin of an object asks **no recycle-bin grant** | objectql | Get: the system lists every entry of any object the bin takes. Every caller that is not system lists an object's entries only when its effective permissions grant `manageRecycleBin` on the object; otherwise `403 PERMISSION_DENIED`, and the same refusal when no permission resolver is registered or it throws (#30237, ADR-0148 D5) | `assertCallerManagesRecycleBin` | +| 29g | **The closed-state lock does not bind** — a write to a record in one of its object's `closedStates`, or to a line of one, is not judged | objectql | Get: a system context updates, deletes and restores a closed record and its `master_detail` lines, and a cascade that reaches one runs; the engine's own derived writes (the roll-up recompute, the approval status mirror) land on a closed record. Every caller that is not system, and a write with no context at all, is refused `409 RECORD_LOCKED` (ADR-0162 D5) | `boundByClosedStates` | | 30 | **Bulk data event `organizationId` OMITTED** — the batch is published "not asserted" | plugin-security | Get: nothing — the `data.records.*` event still publishes. Lose: the per-organization attribution: this exit is taken before the security middleware composes any tenant wall, so it records no Layer 0 verdict on the operation (`OperationContext.tenantLayer0Verdict`, #15813), and the engine's bulk producer — which reads that recorded verdict and nothing else — omits the key rather than filling it from the caller's `tenantId`; a tenant-scoped consumer then does not deliver the event inside an organization wall (#15225) | `registerAuthzMiddleware` | | 30b | **The import doors admit a control opt-out** — `runAutomations: false` and `treatAsHistorical: true` on `POST /data/:object/import` and `/import/jobs` | rest | Get: an import whose rows are written with `skipAutomations` (no metadata-bound hook, no record-change trigger: an app's approvals and record freezes among them) or with `skipStateMachine` and `preserveAudit`. Every other caller, every signed-in user and administrator included, is refused `403 PERMISSION_DENIED` before the body is parsed, so nothing is written and no job is created. Inbound HTTP never carries the flag, so this is an in-process caller's door. Note: the flag still suppresses none of those controls by itself (see below); it only admits the opt-outs that do | `importControlOptOutRefusal` | | 30c | **The import undo keeps the control skips** — `POST /data/import/jobs/:jobId/undo` | rest | Get: an undo whose deletes and restores are written with `skipAutomations` and `skipStateMachine`, so no metadata-bound hook, record-change trigger or `state_machine` rule refuses a reversal. Every other caller, every signed-in user and administrator included, undoes under those controls: a reversal one of them refuses is reported per row in the undo answer's `failures` and kept in the job's undo log, and the job is stamped reverted only once every row is. A historical job's `preserveAudit` belongs to the job, not the caller, and rides every undo. Inbound HTTP never carries the flag, so this is an in-process caller's door | `importUndoWriteContext` | @@ -549,6 +550,7 @@ and CI refuses one that differs from what the tree produces. | `packages/metadata-core/src/meta-write-capability.ts#metaWriteCapabilityVerdict` | 1 | 51 | | `packages/metadata-core/src/meta-write-capability.ts#walledCatalogWriteVerdict` | 1 | 55b | | `packages/metadata-core/src/object-schema-fls.ts#isObjectSchemaMaskExempt` | 1 | 8 | +| `packages/objectql/src/closed-state-lock.ts#boundByClosedStates` | 1 | 29g | | `packages/objectql/src/credential-evaluation-guard.ts#rejectCredentialEvaluation` | 1 | 18c | | `packages/objectql/src/engine-cascade-planning.ts#dependentCountIsDisclosable` | 1 | 28 | | `packages/objectql/src/engine-delete-cascade.ts#recordReferenceCheckElevation` | 1 | 29 | From 8e95b36e2ab410417d1ae2acdaf5fd959e0289a0 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 02:25:31 +0000 Subject: [PATCH 14/32] fix(objectql): the closed-state lock asks the store whether a record is closed (ADR-0162 D4) The master check is one existence probe per chunk of ids with the closed predicate in its where, never a read of state columns tested in process. The cascade set is judged the same way: one probe per chunk for its own state, and for its lines the predicate door's semi-join where the store runs it; only a store that cannot keeps the read of the lines' keys, then one probe of their masters. Where the fold restores a package's field over a tenant overlay, the overlay's closed values for that field are served only where the package's field declares them. Claude-Session: https://claude.ai/code/session_01L6bhgTCFhayR5cBZXM7XPP Co-authored-by: Claude --- packages/objectql/src/closed-state-lock.ts | 104 +++++++++++------- .../objectql/src/engine-cascade-planning.ts | 3 +- packages/objectql/src/engine.ts | 2 +- .../src/registry-closed-state-fold.test.ts | 11 ++ .../src/registry-closed-state-fold.ts | 12 +- .../qa/dogfood/test/closed-state-lock.test.ts | 29 ++++- 6 files changed, 115 insertions(+), 46 deletions(-) diff --git a/packages/objectql/src/closed-state-lock.ts b/packages/objectql/src/closed-state-lock.ts index 9f5957017b5..79422ac9956 100644 --- a/packages/objectql/src/closed-state-lock.ts +++ b/packages/objectql/src/closed-state-lock.ts @@ -238,38 +238,42 @@ function chunks(list: readonly T[], size = IN_CHUNK): T[][] { } /** - * The ids among `ids` of `master` that are closed, read by the engine itself: - * straight from the store, above the writer's grants, inside the writer's - * organization scope and unit of work (the driver options of `context`). A - * read that fails is refused as "cannot be judged". + * Does any of `ids` of `master` stand in a closed state? Asked of the store, + * not listed: one existence probe per chunk of ids, the closed predicate in + * its `where` (D4). Read by the engine itself: straight from the store, above + * the writer's grants, inside the writer's organization scope and unit of work + * (the driver options of `context`). A read that fails is refused as "cannot + * be judged". */ -async function closedIdsOf( +async function anyClosedAmong( this: Pick, master: string, ids: ReadonlyArray, closed: ClosedValues, context: ExecutionContext | undefined, refuse: (detail: string) => Error, -): Promise> { - const out = new Set(); +): Promise { const unique = [...new Set(ids)]; - if (unique.length === 0) return out; - const fields = ['id', ...closed.keys()]; + if (unique.length === 0) return false; try { const driver = this.getDriver(master); const opts = this.buildDriverOptions(master, context); for (const part of chunks(unique)) { const rows = (await driver.find( master, - { object: master, where: { id: part.length === 1 ? part[0] : { $in: part } }, fields, limit: part.length }, + { object: master, where: andWhere(idIn(part), closedPredicate(closed)), fields: ['id'], limit: 1 }, opts, - )) as Array> | null; - for (const row of rows ?? []) if (row && rowIsClosed(row, closed)) out.add(String(row.id)); + )) as unknown[] | null; + if (Array.isArray(rows) && rows.length > 0) return true; } } catch (error) { throw Object.assign(refuse(`the state of a '${master}' record could not be read`), { cause: error }); } - return out; + return false; +} + +function idIn(part: ReadonlyArray): FilterCondition { + return { id: part.length === 1 ? part[0] : { $in: [...part] } } as FilterCondition; } /** @@ -288,7 +292,7 @@ async function namedMastersClosed( const readable = await this.masterDetailHeadersCallerReads(edge.master, named, context); const asked = named.filter((id) => readable.has(id)); if (asked.length === 0) return false; - return (await closedIdsOf.call(this, edge.master, asked, edge.closed, context, refuse)).size > 0; + return anyClosedAmong.call(this, edge.master, asked, edge.closed, context, refuse); } /** The keys an update carries, addressing excluded. */ @@ -342,7 +346,7 @@ export async function judgeClosedStateByIdWrite(this: ClosedStateLockHost, write // The master the stored row hangs under: its stored state, whoever writes. const stored = scalarIdOf(prior[edge.fk]); if (stored === undefined) throw refuse(`its '${edge.fk}' does not hold one id`); - if (stored !== null && (await closedIdsOf.call(this, edge.master, [stored], edge.closed, context, refuse)).size > 0) { + if (stored !== null && await anyClosedAmong.call(this, edge.master, [stored], edge.closed, context, refuse)) { throw closedStateLockError(object, verb, 'master_closed', edge.master); } // A move names the master it moves to: the caller's read door first. @@ -406,7 +410,7 @@ export interface ClosedStatePredicateWrite { * a walled posture both are of the same tenancy class (so one read's driver * options scope both tables). */ -function lineProbeServes(this: ClosedStateLockHost, object: string, master: string): boolean { +function lineProbeServes(this: Pick, object: string, master: string): boolean { const driver = this.getDriver(object); if (!driverCompilesReadableIdsLeaf(driver)) return false; if (this.getDriver(master) !== driver) return false; @@ -481,7 +485,7 @@ export async function judgeClosedStatePredicateWrite(this: ClosedStateLockHost, if (id === undefined) throw refuse(`a matched row's '${edge.fk}' does not hold one id`); if (id !== null) ids.push(id); } - if ((await closedIdsOf.call(this, edge.master, ids, edge.closed, context, refuse)).size > 0) { + if (await anyClosedAmong.call(this, edge.master, ids, edge.closed, context, refuse)) { throw closedStateLockError(object, verb, 'master_closed', edge.master); } } @@ -503,7 +507,7 @@ export async function judgeClosedStatePredicateWrite(this: ClosedStateLockHost, * object whose closed record stands in the way, and nothing else. */ export async function judgeClosedStateCascadeSet( - this: Pick, + this: Pick, root: string, members: ReadonlyMap>, context: ExecutionContext | undefined, @@ -513,34 +517,50 @@ export async function judgeClosedStateCascadeSet( for (const [object, idSet] of members) { const unit = closedStateUnitOf.call(this, object); if (!unit || idSet.size === 0) continue; - const ids = [...idSet]; - const fields = ['id', ...(unit.own ? unit.own.keys() : []), ...unit.masters.map((e) => e.fk)]; - let rows: Array> = []; - try { - const driver = this.getDriver(object); - const opts = this.buildDriverOptions(object, context); - for (const part of chunks(ids)) { - const found = (await driver.find( - object, - { object, where: { id: part.length === 1 ? part[0] : { $in: part } }, fields, limit: part.length }, - opts, - )) as Array> | null; - rows = rows.concat((found ?? []).filter((r) => r && typeof r === 'object')); + const parts = chunks([...idSet].map(String)); + const driver = this.getDriver(object); + const opts = this.buildDriverOptions(object, context); + // Asked of the store, per chunk of the set's ids: one existence probe. + const probe = async (part: ReadonlyArray, extra: FilterCondition): Promise => { + try { + const rows = (await driver.find(object, { object, where: andWhere(idIn(part), extra), fields: ['id'], limit: 1 }, opts)) as unknown[] | null; + return Array.isArray(rows) && rows.length > 0; + } catch (error) { + throw Object.assign(refuse(`the rows of '${object}' its cascade reaches could not be read`), { cause: error }); + } + }; + if (unit.own) { + for (const part of parts) { + if (await probe(part, closedPredicate(unit.own))) throw closedStateLockError(root, 'delete', 'cascade_reaches_closed', object); } - } catch (error) { - throw Object.assign(refuse(`the rows of '${object}' its cascade reaches could not be read`), { cause: error }); - } - if (unit.own && rows.some((row) => rowIsClosed(row, unit.own!))) { - throw closedStateLockError(root, 'delete', 'cascade_reaches_closed', object); } for (const edge of unit.masters) { + if (lineProbeServes.call(this, object, edge.master)) { + // The predicate door's semi-join, scoped to the set's ids. + const semiJoin = { [edge.fk]: { $in: ReadableIds.compose(ReadableIds.of(edge.master), closedPredicate(edge.closed)) } } as FilterCondition; + for (const part of parts) { + if (await probe(part, semiJoin)) throw closedStateLockError(root, 'delete', 'cascade_reaches_closed', edge.master); + } + continue; + } + // A store that cannot run the semi-join: the set's foreign keys, then + // one probe of the masters they name (D4's stated fallback). const masterIds: string[] = []; - for (const row of rows) { - const id = scalarIdOf(row[edge.fk]); - if (id === undefined) throw refuse(`a '${object}' row its cascade reaches does not hold one id in '${edge.fk}'`); - if (id !== null) masterIds.push(id); + try { + for (const part of parts) { + const rows = (await driver.find(object, { object, where: idIn(part), fields: ['id', edge.fk], limit: part.length }, opts)) as Array> | null; + for (const row of rows ?? []) { + if (!row || typeof row !== 'object') continue; + const id = scalarIdOf(row[edge.fk]); + if (id === undefined) throw refuse(`a '${object}' row its cascade reaches does not hold one id in '${edge.fk}'`); + if (id !== null) masterIds.push(id); + } + } + } catch (error) { + if ((error as { reason?: unknown })?.reason === 'cannot_judge') throw error; + throw Object.assign(refuse(`the rows of '${object}' its cascade reaches could not be read`), { cause: error }); } - if ((await closedIdsOf.call(this, edge.master, masterIds, edge.closed, context, refuse)).size > 0) { + if (await anyClosedAmong.call(this, edge.master, masterIds, edge.closed, context, refuse)) { throw closedStateLockError(root, 'delete', 'cascade_reaches_closed', edge.master); } } @@ -571,7 +591,7 @@ export async function judgeClosedStateRestore( } for (const [master, { closed, ids, object }] of byMaster) { const refuse = (detail: string) => closedStateLockError(object, 'restore', 'cannot_judge', undefined, detail); - if ((await closedIdsOf.call(this, master, ids, closed, context, refuse)).size > 0) { + if (await anyClosedAmong.call(this, master, ids, closed, context, refuse)) { throw closedStateLockError(object, 'restore', 'master_closed', master); } } diff --git a/packages/objectql/src/engine-cascade-planning.ts b/packages/objectql/src/engine-cascade-planning.ts index 89b15e6c295..654cf66a52b 100644 --- a/packages/objectql/src/engine-cascade-planning.ts +++ b/packages/objectql/src/engine-cascade-planning.ts @@ -87,6 +87,7 @@ export interface CascadePlanningHost { find: ObjectQLClass['find']; /** [ADR-0162 D6] The driver options the closed-state lock reads the cascade set with. */ buildDriverOptions: ObjectQLClass['buildDriverOptions']; + resolveEnginePosture: ObjectQLClass['resolveEnginePosture']; getDriver: ObjectQLClass['getDriver']; isTenantColumnSetNull: ObjectQLClass['isTenantColumnSetNull']; readonly logger: ObjectQLClass['logger']; @@ -535,7 +536,7 @@ export class CascadePlanningFacet { * (formula values, file references, hooks), so they are not the values a * restore must write back. */ - static async cascadeDeleteRelations(this: Pick, object: string, ids: ReadonlyArray, context?: ExecutionContext, depth = 0, onCollected?: (set: CascadeDeleteSet) => Promise): Promise { + static async cascadeDeleteRelations(this: Pick, object: string, ids: ReadonlyArray, context?: ExecutionContext, depth = 0, onCollected?: (set: CascadeDeleteSet) => Promise): Promise { const roots: Array = []; const seen = new Set(); for (const id of ids) { diff --git a/packages/objectql/src/engine.ts b/packages/objectql/src/engine.ts index e7f41ee1aa6..de840274a13 100644 --- a/packages/objectql/src/engine.ts +++ b/packages/objectql/src/engine.ts @@ -5826,7 +5826,7 @@ export class ObjectQL implements IObjectQLEngine { refuseRestrictsInsideOwnCascade: (...a) => engine.refuseRestrictsInsideOwnCascade(...a), resolveObjectName: (...a) => engine.resolveObjectName(...a), update: (...a) => engine.update(...a), - walkReferencingRelations: (...a) => engine.walkReferencingRelations(...a), buildDriverOptions: (...a) => engine.buildDriverOptions(...a), // [ADR-0162 D6] + walkReferencingRelations: (...a) => engine.walkReferencingRelations(...a), buildDriverOptions: (...a) => engine.buildDriverOptions(...a), resolveEnginePosture: () => engine.resolveEnginePosture(), // [ADR-0162 D6] })); compatibilitySectionHost.install((engine) => ({ get _registry() { return engine._registry; }, diff --git a/packages/objectql/src/registry-closed-state-fold.test.ts b/packages/objectql/src/registry-closed-state-fold.test.ts index 0254558d0b7..6293b8765c9 100644 --- a/packages/objectql/src/registry-closed-state-fold.test.ts +++ b/packages/objectql/src/registry-closed-state-fold.test.ts @@ -149,6 +149,17 @@ describe('[ADR-0162 D1] a tenant overlay may add closed values, and may not shor expect(warn.mock.calls.map((c) => String(c[0])).some((m) => m.includes("drops the listed option 'void'"))).toBe(true); }); + it('a value the overlay added for its own version of a restored field is not served', async () => { + await boot(); + vi.spyOn(console, 'warn').mockImplementation(() => {}); + engine.registry.registerObject(owner() as any, OWNER_PKG); + // The overlay drops 'void' and adds 'refunded', and lists 'refunded' as closed. + const broken = { ...STATUS, options: [...STATUS.options.slice(0, 2), { label: 'Refunded', value: 'refunded' }] }; + overlay({ ...owner(), fields: { ...owner().fields, status: broken }, closedStates: { status: ['paid', 'void', 'refunded'] } }); + expect(served().fields.status).toEqual(STATUS); + expect(served().closedStates).toEqual({ status: ['paid', 'void'] }); + }); + it('CONTROL: an overlay that only relabels keeps its label and the package\'s list', async () => { await boot(); engine.registry.registerObject(owner() as any, OWNER_PKG); diff --git a/packages/objectql/src/registry-closed-state-fold.ts b/packages/objectql/src/registry-closed-state-fold.ts index 35337ea9b9e..5edf2ebab7a 100644 --- a/packages/objectql/src/registry-closed-state-fold.ts +++ b/packages/objectql/src/registry-closed-state-fold.ts @@ -38,7 +38,7 @@ export function closedStateFieldBreach(field: unknown, listed: ReadonlySet (o && typeof o === 'object' ? (o as { value?: unknown }).value : o))); + const values = optionValuesOf(def); const dropped = [...listed].filter((v) => !values.has(v)); if (dropped.length > 0) return `drops the listed option${dropped.length > 1 ? 's' : ''} ${dropped.map((v) => `'${v}'`).join(', ')}`; return undefined; @@ -71,6 +71,11 @@ export function withoutClosedStateFieldBreaches(running: Body, e return kept ? { ...extension, fields: kept } : extension; } +function optionValuesOf(field: unknown): Set { + const options = field && typeof field === 'object' ? (field as { options?: unknown }).options : undefined; + return new Set(Array.isArray(options) ? options.map((o) => (o && typeof o === 'object' ? (o as { value?: unknown }).value : o)) : []); +} + /** `a` with every value of `b` added, per field. */ function unionClosed(a: ClosedValues, b: ClosedValues | undefined): Record { const out: Record = {}; @@ -103,6 +108,11 @@ export function withPackagedClosedStates(owner: Body | undefined if (ownerField === undefined) continue; fields[name] = ownerField; restored = true; + // The package's field is served, so the overlay's values for it are kept + // only where that field declares them: a value only the overlay's own + // version of the field offered would be served in a list naming no option. + const declared = optionValuesOf(ownerField); + out.closedStates![name] = out.closedStates![name].filter((v) => listed.has(v) || declared.has(v)); console.warn( `[Registry] Field "${name}" of object "${String(base.name ?? owner.name ?? '')}": the tenant overlay ${breach}, ` + 'and the package\'s `closedStates` names the field. The package\'s definition of the field stands: an overlay may add ' + diff --git a/packages/qa/dogfood/test/closed-state-lock.test.ts b/packages/qa/dogfood/test/closed-state-lock.test.ts index 07874aa9d07..37469233b22 100644 --- a/packages/qa/dogfood/test/closed-state-lock.test.ts +++ b/packages/qa/dogfood/test/closed-state-lock.test.ts @@ -361,7 +361,8 @@ for (const [label, shape] of SHAPES) { await boot(shape); const find = driver.find.bind(driver); (driver as unknown as { find: typeof find }).find = (async (object: string, ast: unknown, opts: unknown) => { - if (object === INVOICE && (ast as { fields?: string[] })?.fields?.includes('status')) throw new Error('store unavailable'); + // The lock's probe of the master carries the closed predicate in its where. + if (object === INVOICE && JSON.stringify((ast as { where?: unknown })?.where ?? null).includes('"paid"')) throw new Error('store unavailable'); return find(object as never, ast as never, opts as never); }) as typeof find; const err = await refusal(() => engine.update(LINE, { id: 'l_open', qty: 9 }, by(CALLER))); @@ -409,6 +410,32 @@ for (const [label, shape] of SHAPES) { expect(await stored(INVOICE, 'status')).toEqual([]); }); + it(`a cascade that reaches a line of a closed record is refused, ${shape.probe ? 'by one probe on the line table' : 'from the lines\' keys and one probe of their masters'}`, async () => { + await boot(shape); + const seen: Array<{ object: string; where: string; fields: unknown }> = []; + const find = driver.find.bind(driver); + (driver as unknown as { find: typeof find }).find = (async (object: string, ast: unknown, opts: unknown) => { + const a = ast as { where?: unknown; fields?: unknown }; + seen.push({ object, where: JSON.stringify(a.where ?? null), fields: a.fields }); + return find(object as never, ast as never, opts as never); + }) as typeof find; + // inv_open is open; its cascade reaches a_frozen, a line of the frozen budget. + const err = await refusal(() => engine.delete(INVOICE, { where: { id: 'inv_open' }, context: CALLER } as never)); + expect([err.code, err.reason, err.blockingObject]).toEqual(['RECORD_LOCKED', 'cascade_reaches_closed', BUDGET]); + expect(await stored(INVOICE, 'status')).toContain('inv_open:draft'); + expect(await stored(ALLOC, 'budget')).toEqual(['a_frozen:b_frozen', 'a_open:b_open']); + const budgetReads = seen.filter((r) => r.object === BUDGET); + if (shape.probe) { + expect(budgetReads).toEqual([]); + } else { + // The masters are asked of the store: the closed predicate rides the + // probe's where, and only the id comes back. + expect(budgetReads).toHaveLength(1); + expect(budgetReads[0].where).toContain('frozen'); + expect(budgetReads[0].fields).toEqual(['id']); + } + }); + it('a referential clear lands on a closed record: exactly the cleared field', async () => { await boot(shape); await engine.delete(CONTACT, { where: { id: 'ct1' }, context: CALLER } as never); From cc6d5f6ace49a8964ad467ed17edb1e80efd363c Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 04:56:18 +0000 Subject: [PATCH 15/32] 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 16/32] 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 17/32] 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 18/32] 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); From 1a9fee5e1e487d7000b670c9fbb0e856fe37380d Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 05:27:57 +0000 Subject: [PATCH 19/32] feat(approvals): the check when an approval opens, and the between-two-steps stamp (slice B) ADR-0162 Execution item 7 "The check", as revised on 2026-11-27. At an approval's first request the plugin reads the approval whole (the root run's flow and every subflow/map body, to any depth) and: - stamps the between-two-steps set on the request (new engine-written column between_steps_json); later requests of the approval copy it; - refuses the opening, VALIDATION_FAILED with one sentence per gap in the run's locale, where a step mirrors onto a field its object closes on at a request status and a D5 condition fails, where a flow cannot be read, or where the host runs no job service. Not judged: no object declares closedStates; no root run; a later request; a request that cannot be placed. The writing-node condition is withdrawn and pinned as not refused. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5nzgcVrZ8Neqqd1AFi --- .changeset/37766-opening-check.md | 19 + .../plugin-approvals/src/approval-node.ts | 2 + ...al-opening-check-37766.integration.test.ts | 232 +++++++ .../src/approval-opening-check.test.ts | 337 +++++++++ .../src/approval-opening-check.ts | 644 ++++++++++++++++++ .../src/approval-opening-refusal.ts | 60 ++ .../plugin-approvals/src/approval-service.ts | 228 ++++++- .../plugin-approvals/src/approvals-plugin.ts | 3 + ...-closing-field-refusal.integration.test.ts | 4 + .../src/sys-approval-request.object.ts | 19 +- .../src/translations/ar.objects.generated.ts | 4 + .../src/translations/de.objects.generated.ts | 4 + .../src/translations/en.objects.generated.ts | 4 + .../translations/es-ES.objects.generated.ts | 4 + .../src/translations/fr.objects.generated.ts | 4 + .../translations/ja-JP.objects.generated.ts | 4 + .../src/translations/ko.objects.generated.ts | 4 + .../src/translations/messages.ts | 132 ++++ .../translations/pt-BR.objects.generated.ts | 4 + .../src/translations/ru.objects.generated.ts | 4 + .../translations/zh-CN.objects.generated.ts | 4 + .../translations/zh-Hant.objects.generated.ts | 4 + 22 files changed, 1722 insertions(+), 2 deletions(-) create mode 100644 .changeset/37766-opening-check.md create mode 100644 packages/plugins/plugin-approvals/src/approval-opening-check-37766.integration.test.ts create mode 100644 packages/plugins/plugin-approvals/src/approval-opening-check.test.ts create mode 100644 packages/plugins/plugin-approvals/src/approval-opening-check.ts create mode 100644 packages/plugins/plugin-approvals/src/approval-opening-refusal.ts diff --git a/.changeset/37766-opening-check.md b/.changeset/37766-opening-check.md new file mode 100644 index 00000000000..1a40086ab2c --- /dev/null +++ b/.changeset/37766-opening-check.md @@ -0,0 +1,19 @@ +--- +'@objectstack/plugin-approvals': minor +--- + +feat(approvals): an approval that cannot show itself in progress on a field its object closes on does not open (ADR-0162 Execution item 7, the check) + +Clause-②: yes (widening) +Metadata-protocol: none + +Widened: `sys_approval_request` gains the engine-written, read-only column `between_steps_json`; `ApprovalService` gains `noteSweepClockScheduled()`; the plugin's message catalog gains twelve `approvalOpening*` sentences in all 11 locale packs. + +At an approval's first request the plugin now reads the approval whole: the flow its root run was started on and every flow a `subflow` or a `map` in it names, to any depth. Where a step can act on an object that declares `closedStates`: + +- **The between-two-steps set is stamped** on the request, and every later request of the same approval carries the same set. It lists the nodes after which a step of the approval can still follow, so that a run that stops there can later be told from one that stopped after the last step. +- **The approval does not open** where a step mirrors onto a field the object closes on at `pending`, `returned`, `approved` or `rejected`, and one of these is missing: the field declares `pending` and the object closes on neither `pending` nor `returned`; a `state_machine` rule on the field that declares the moves out of a closed `approved` or `rejected` includes `pending` among them; the field has no `readonlyWhen` and no request-status option has a `visibleWhen`; every step that can act on the object mirrors onto the same field; no node that can pause the run (a `wait`, a `screen`, a node type with no descriptor) stands between two steps, and no `map` runs an approval step for items it does not show are not records. An approval one of whose flows cannot be read does not open either, and neither does one on a host that runs no `job` service. + +A refused approval fails its run at the step with `VALIDATION_FAILED` and one sentence per gap naming the flow, the step, the object, the field and what is missing, in the run's locale. No request row is written. + +Not judged, and unchanged: an application in which no object declares `closedStates`; an approval whose objects declare none; a request whose run hands no root run; a later request of an approval already open (also one opened before the object declared the key); a request that cannot be placed because an earlier request on the record since its root run started records no root run. A writing node between two steps of a flow that runs as the user is not refused. diff --git a/packages/plugins/plugin-approvals/src/approval-node.ts b/packages/plugins/plugin-approvals/src/approval-node.ts index bc93e658922..4a0ea9a5f43 100644 --- a/packages/plugins/plugin-approvals/src/approval-node.ts +++ b/packages/plugins/plugin-approvals/src/approval-node.ts @@ -243,6 +243,8 @@ export function registerApprovalNode( runRoot: !hasParentRun(context), rootRun, recordRun, + // [ADR-0162 Execution item 7] A refused opening is worded in the run's locale. + locale: typeof context?.locale === 'string' ? context.locale : undefined, }, { ...SYSTEM_CTX, userId: context?.userId, diff --git a/packages/plugins/plugin-approvals/src/approval-opening-check-37766.integration.test.ts b/packages/plugins/plugin-approvals/src/approval-opening-check-37766.integration.test.ts new file mode 100644 index 00000000000..33fe0a448a9 --- /dev/null +++ b/packages/plugins/plugin-approvals/src/approval-opening-check-37766.integration.test.ts @@ -0,0 +1,232 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 Execution item 7 "The check", #37766 slice B] The check when an + * approval opens, as the service runs it at a request's opening: placed by + * the request's root run, judged once at the approval's first request, its + * between-two-steps set stamped on every request of an approval that touches + * an object declaring `closedStates`, and a refusal that names what is + * missing, in the run's locale. The read of the definition itself, arm by + * arm, is pinned over fixtures in `approval-opening-check.test.ts`. + * + * Real kernel, real ObjectQL engine, real automation engine (which hands the + * root run, slice A), real approval node, driver-sql on better-sqlite3 + * `:memory:`. + */ + +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { ObjectKernel } from '@objectstack/core'; +import { ObjectQLPlugin, type ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { AutomationServicePlugin, type AutomationEngine } from '@objectstack/service-automation'; +import { ApprovalService } from './approval-service.js'; +import { registerApprovalNode } from './approval-node.js'; +import { SysApprovalRequest } from './sys-approval-request.object.js'; +import { SysApprovalAction } from './sys-approval-action.object.js'; +import { SysApprovalApprover } from './sys-approval-approver.object.js'; +import { SysApprovalDelegation } from './sys-approval-delegation.object.js'; +import { SysApprovalToken } from './sys-approval-token.object.js'; + +const ORG = 'org_default'; +const SYS = { isSystem: true } as const; +const asPerson = (userId: string) => ({ userId, positions: [], permissions: [] }) as any; + +const text = (name: string) => ({ name, type: 'text' as const }); +const PLATFORM_GLOBAL = { enabled: false }; +const authzObjects = [ + { owner: '@objectstack/plugin-auth', def: { name: 'sys_user', label: 'User', tenancy: PLATFORM_GLOBAL, fields: { id: { ...text('id'), primaryKey: true }, email: text('email') } } }, + { owner: '@objectstack/plugin-auth', def: { name: 'sys_member', label: 'Member', tenancy: PLATFORM_GLOBAL, fields: { id: { ...text('id'), primaryKey: true }, user_id: text('user_id'), organization_id: text('organization_id'), role: text('role') } } }, + { owner: '@objectstack/plugin-security', def: { name: 'sys_user_position', label: 'User Position', tenancy: PLATFORM_GLOBAL, fields: { id: { ...text('id'), primaryKey: true }, user_id: text('user_id'), position: text('position'), organization_id: text('organization_id') } } }, + { owner: '@objectstack/plugin-security', def: { name: 'sys_user_permission_set', label: 'User Permission Set', tenancy: PLATFORM_GLOBAL, fields: { id: { ...text('id'), primaryKey: true }, user_id: text('user_id'), permission_set: text('permission_set'), organization_id: text('organization_id') } } }, +] as const; + +const statusField = { + name: 'approval_status', type: 'select' as const, defaultValue: 'draft', + options: ['draft', 'pending', 'returned', 'approved', 'rejected', 'recalled'].map((value) => ({ label: value, value })), +}; +const fields = { name: text('name'), approval_status: statusField, other_status: { ...statusField, name: 'other_status' } }; +/** Closes on its approval's outcome, and meets every condition of D5. */ +const invoice = { name: 'crm_invoice', label: 'Invoice', fields, closedStates: { approval_status: ['approved', 'rejected'] } }; +/** The same object, declaring no closed state. */ +const memo = { name: 'crm_memo', label: 'Memo', fields }; + +const step = (id: string, approver: string, field = 'approval_status') => ({ + id, type: 'approval', label: id, + config: { approvers: [{ type: 'user', value: approver }], approvalStatusField: field }, +}); +const endEdges = (from: string, to: string, n: number) => [ + { id: `e${n}a`, source: from, target: to, label: 'approve' }, + { id: `e${n}r`, source: from, target: 'end', label: 'reject' }, +]; + +/** Two steps on the same field: opens. */ +const twoStep = { + name: 'two_step', label: 'Two steps', type: 'autolaunched', + nodes: [{ id: 'start', type: 'start', label: 'Start' }, step('first', 'approver'), step('second', 'approver2'), { id: 'end', type: 'end', label: 'End' }], + edges: [{ id: 'e1', source: 'start', target: 'first' }, ...endEdges('first', 'second', 2), ...endEdges('second', 'end', 3)], +}; +/** A timer between the two steps: D5 condition 5. */ +const waitBetween = { + name: 'wait_between', label: 'Wait between', type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, step('first', 'approver'), + { id: 'hold', type: 'wait', label: 'Hold', waitEventConfig: { eventType: 'timer', timerDuration: 'PT1H' } }, + step('second', 'approver2'), { id: 'end', type: 'end', label: 'End' }, + ], + edges: [{ id: 'e1', source: 'start', target: 'first' }, ...endEdges('first', 'hold', 2), { id: 'e3', source: 'hold', target: 'second' }, ...endEdges('second', 'end', 4)], +}; +/** The second step mirrors onto another field: D5 condition 4. */ +const otherField = { + name: 'other_field', label: 'Other field', type: 'autolaunched', + nodes: [{ id: 'start', type: 'start', label: 'Start' }, step('first', 'approver'), step('second', 'approver2', 'other_status'), { id: 'end', type: 'end', label: 'End' }], + edges: [{ id: 'e1', source: 'start', target: 'first' }, ...endEdges('first', 'second', 2), ...endEdges('second', 'end', 3)], +}; + +describe('[ADR-0162 item 7] the check when an approval opens', () => { + let kernel: ObjectKernel; + let ql: ObjectQL; + let automation: AutomationEngine; + let svc: ApprovalService; + + afterEach(async () => { + try { await kernel?.shutdown(); } catch { /* noop */ } + }); + + async function boot(opts: { sweeps?: boolean; invoiceDef?: Record } = {}) { + kernel = new ObjectKernel({ logger: { level: 'silent' } } as any); + await kernel.use(new ObjectQLPlugin()); + await kernel.use(new AutomationServicePlugin()); + await kernel.bootstrap(); + ql = kernel.getService('objectql'); + automation = kernel.getService('automation'); + + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); + await driver.connect(); + ql.registerDriver(driver, true); + for (const def of [opts.invoiceDef ?? invoice, memo, SysApprovalRequest, SysApprovalAction, SysApprovalApprover, SysApprovalDelegation, SysApprovalToken]) { + ql.registry.registerObject(def as any, 'approvals-test', 'approvals-test'); + } + for (const o of authzObjects) ql.registry.registerObject(o.def as any, o.owner); + ql.registry.registerObject( + { name: 'sys_organization', label: 'Organization', managedBy: 'better-auth', fields: { name: text('name'), slug: text('slug') } } as any, + '@objectstack/plugin-auth', + ); + await ql.syncSchemas(); + await ql.insert('sys_organization', { id: ORG, name: 'Default Organization', slug: 'default' }, { context: SYS }); + for (const id of ['owner', 'approver', 'approver2']) { + await ql.insert('sys_user', { id, email: `${id}@example.test` }, { context: SYS }); + await ql.insert('sys_member', { id: `mem_${id}`, user_id: id, organization_id: ORG, role: 'member' }, { context: SYS }); + } + const quiet = { debug: () => {}, info: () => {}, warn: () => {}, error: () => {} }; + svc = new ApprovalService({ engine: ql, logger: quiet as any }); + if (opts.sweeps !== false) svc.noteSweepClockScheduled(); + svc.attachAutomation(automation as any); + registerApprovalNode(automation as any, svc, quiet as any); + for (const flow of [twoStep, waitBetween, otherField]) automation.registerFlow(flow.name, flow as any); + } + + const read = async (object: string, id: string) => (await ql.find(object, { where: { id }, context: SYS }))[0]; + const requestsOn = async (id: string) => + (await ql.find('sys_approval_request', { where: { record_id: id }, orderBy: [{ field: 'created_at', order: 'asc' }], context: SYS })) as any[]; + const seed = (object: string, id: string) => + ql.insert(object, { id, name: id, organization_id: ORG }, { context: { isSystem: true, tenantId: ORG } }); + const start = async (flow: string, object: string, id: string, extra: Record = {}) => + automation.execute(flow, { object, record: await read(object, id), userId: 'owner', ...extra } as any) as Promise; + const approve = async (requestId: string, who: string) => + svc.decide(requestId, { decision: 'approve', actorId: who } as any, asPerson(who)); + + describe('an approval that meets every condition', () => { + beforeEach(() => boot()); + + it('opens, and each of its requests carries the set its first request was stamped with', async () => { + await seed('crm_invoice', 'i_ok'); + expect((await start('two_step', 'crm_invoice', 'i_ok')).status).toBe('paused'); + const [first] = await requestsOn('i_ok'); + expect(first.status).toBe('pending'); + const stamp = JSON.parse(first.between_steps_json); + expect(stamp).toEqual([{ flow: 'two_step', node: 'first' }]); + + await approve(String(first.id), 'approver'); + const rows = await requestsOn('i_ok'); + expect(rows.map((r) => [r.flow_node_id, r.status])).toEqual([['first', 'approved'], ['second', 'pending']]); + expect(rows[1].between_steps_json, 'a later request copies the first request\'s set').toBe(first.between_steps_json); + }); + + it('stamps nothing on an approval whose object declares no closed state', async () => { + await seed('crm_memo', 'm_ok'); + expect((await start('wait_between', 'crm_memo', 'm_ok')).status).toBe('paused'); + const [row] = await requestsOn('m_ok'); + expect(row.status).toBe('pending'); + expect(row.between_steps_json ?? null).toBeNull(); + }); + }); + + describe('an approval that misses a condition', () => { + beforeEach(() => boot()); + + it('does not open: the run fails with a sentence naming the flow, the step, the object and what is missing', async () => { + await seed('crm_invoice', 'i_wait'); + const out = await start('wait_between', 'crm_invoice', 'i_wait'); + expect(out.status).toBe('failed'); + const said = JSON.stringify(out); + expect(said).toContain('VALIDATION_FAILED'); + expect(said).toContain('Node hold (wait) of flow wait_between can pause the run between two approval steps of crm_invoice'); + expect(await requestsOn('i_wait'), 'no request opened').toEqual([]); + }); + + it('words the refusal in the run\'s locale', async () => { + await seed('crm_invoice', 'i_zh'); + const out = await start('other_field', 'crm_invoice', 'i_zh', { locale: 'zh-CN' }); + expect(out.status).toBe('failed'); + expect(JSON.stringify(out)).toContain('流程 other_field 的步骤 second 可以作用于 crm_invoice,却把状态写到字段 other_status'); + }); + + }); + + it('does not judge a later request whose approval\'s earlier requests record no root run', async () => { + const { closedStates: _declared, ...undeclared } = invoice; + await boot({ invoiceDef: undeclared }); + await seed('crm_invoice', 'i_unplaced'); + expect((await start('other_field', 'crm_invoice', 'i_unplaced')).status).toBe('paused'); + const [first] = await requestsOn('i_unplaced'); + // The shape of a request opened before requests recorded their root run. + await ql.update('sys_approval_request', { id: first.id, root_run_id: null, root_run_started_at: null, record_run_id: null }, { context: SYS }); + expect((await requestsOn('i_unplaced'))[0].root_run_id ?? null).toBeNull(); + + ql.registry.registerObject(invoice as any, 'approvals-test', 'approvals-test'); + await approve(String(first.id), 'approver'); + const rows = await requestsOn('i_unplaced'); + // Judged, the second step's other field would refuse it; it cannot be placed, so it opens. + expect(rows.map((r) => [r.flow_node_id, r.status])).toEqual([['first', 'approved'], ['second', 'pending']]); + expect(rows[1].between_steps_json ?? null).toBeNull(); + }); + + it('does not judge again a later request of an approval opened before the object declared closedStates', async () => { + const { closedStates: _declared, ...undeclared } = invoice; + await boot({ invoiceDef: undeclared }); + await seed('crm_invoice', 'i_before'); + expect((await start('other_field', 'crm_invoice', 'i_before')).status).toBe('paused'); + const [first] = await requestsOn('i_before'); + expect(first.between_steps_json ?? null).toBeNull(); + + // The object now declares the key, as after an upgrade. + ql.registry.registerObject(invoice as any, 'approvals-test', 'approvals-test'); + await approve(String(first.id), 'approver'); + const rows = await requestsOn('i_before'); + expect(rows.map((r) => [r.flow_node_id, r.status])).toEqual([['first', 'approved'], ['second', 'pending']]); + expect(rows[1].between_steps_json ?? null).toBeNull(); + }); + + it('refuses the first request on a host that runs no job service', async () => { + await boot({ sweeps: false }); + await seed('crm_invoice', 'i_host'); + const out = await start('two_step', 'crm_invoice', 'i_host'); + expect(out.status).toBe('failed'); + expect(JSON.stringify(out)).toContain('crm_invoice declares closedStates, and this host runs no job service'); + expect(await requestsOn('i_host')).toEqual([]); + + // An approval whose objects declare no closed state opens on that host. + await seed('crm_memo', 'm_host'); + expect((await start('two_step', 'crm_memo', 'm_host')).status).toBe('paused'); + }); +}); diff --git a/packages/plugins/plugin-approvals/src/approval-opening-check.test.ts b/packages/plugins/plugin-approvals/src/approval-opening-check.test.ts new file mode 100644 index 00000000000..0a5a830b5e0 --- /dev/null +++ b/packages/plugins/plugin-approvals/src/approval-opening-check.test.ts @@ -0,0 +1,337 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 Execution item 7 "The check", #37766 slice B] The read of an + * approval's whole definition at its first request, over fixtures: each D5 + * condition as revised on 2026-11-27, the between-two-steps set it stamps, the + * unread parts, and the host's `job` service. The service's wiring (root run, + * later requests, the refusal and its locale) is pinned in + * `approval-opening-check-37766.integration.test.ts`. + */ + +import { describe, expect, it } from 'vitest'; +import { + judgeApprovalOpening, + type OpeningCheckSource, + type OpeningFlowBody, + type OpeningFlowNode, + type OpeningGap, +} from './approval-opening-check.js'; + +const STATUSES = ['draft', 'pending', 'returned', 'approved', 'rejected', 'recalled']; + +function statusField(extra: Record = {}, options: unknown[] = STATUSES.map((v) => ({ value: v, label: v }))) { + return { type: 'select', options, ...extra }; +} + +/** An object that closes on `approved` and `rejected` of `status`, and meets every condition. */ +function invoice(over: Record = {}) { + return { name: 'invoice', closedStates: { status: ['approved', 'rejected'] }, fields: { status: statusField() }, ...over }; +} + +const memo = { name: 'memo', fields: { status: statusField() } }; + +const DESCRIPTORS: Record = { + wait: { supportsPause: true }, + screen: { supportsPause: true }, + approval: { supportsPause: true }, + decision: {}, + assignment: {}, + update_record: {}, + create_record: {}, + loop: {}, + parallel: {}, + try_catch: {}, +}; + +function source(spec: { + objects?: Record; + flows?: Record; + descriptors?: Record; + host?: boolean; +}): OpeningCheckSource & { read: string[] } { + const objects = spec.objects ?? { invoice: invoice(), memo }; + const descriptors = { ...DESCRIPTORS, ...spec.descriptors }; + const read: string[] = []; + return { + read, + objectSchema: (name) => { read.push(name); return objects[name]; }, + calleeFlow: async (name) => (spec.flows?.[name] ? { key: name, body: spec.flows[name]! } : null), + nodeDescriptor: (type) => descriptors[type], + hostRunsReconciler: spec.host ?? true, + }; +} + +const step = (id: string, field: string | null = 'status'): OpeningFlowNode => + ({ id, type: 'approval', config: field ? { approvalStatusField: field } : {} }); +const n = (id: string, type: string, config: Record = {}): OpeningFlowNode => ({ id, type, config }); + +/** A body whose nodes run one after another, wrapped in `start` and `end`. */ +function chain(...nodes: OpeningFlowNode[]): OpeningFlowBody { + const all = [n('start', 'start'), ...nodes, n('end', 'end')]; + return { nodes: all, edges: all.slice(1).map((b, i) => ({ source: all[i]!.id, target: b.id })) }; +} + +async function judge(root: OpeningFlowBody, opts: Parameters[0] & { rootObject?: string | null } = {}) { + const src = source(opts); + const rootObject = opts.rootObject === undefined ? 'invoice' : opts.rootObject; + const out = await judgeApprovalOpening({ rootFlow: { key: 'F', body: root }, rootFlowName: 'F', rootObject }, src); + return { ...out, read: src.read }; +} + +const kinds = (gaps: OpeningGap[]) => gaps.map((g) => g.kind); + +describe('the opening check: an approval that meets every condition', () => { + it('opens a two-step approval on a closing field, and stamps what stands between the steps', async () => { + const out = await judge(chain(step('a1'), n('d1', 'decision'), step('a2'))); + expect(out.gaps).toEqual([]); + expect(out.touchesClosedStates).toBe(true); + // a1 (a step can follow it) and d1 (after a1, before a2); not a2, after which no step follows. + expect(out.between).toEqual([{ flow: 'F', node: 'a1' }, { flow: 'F', node: 'd1' }]); + }); + + it('does not refuse a writing node in a run-as-user flow (the withdrawn writing-node condition)', async () => { + const root = { ...chain(step('a1'), n('w', 'update_record', { objectName: 'invoice', fields: { note: 'x' } }), step('a2')), runAs: 'user' }; + const out = await judge(root); + expect(out.gaps).toEqual([]); + expect(out.between).toContainEqual({ flow: 'F', node: 'w' }); + }); +}); + +describe('the opening check: D5 conditions 1 to 3, on the field', () => { + it('refuses a field that does not declare pending', async () => { + const objects = { invoice: invoice({ fields: { status: statusField({}, ['draft', 'approved', 'rejected']) } }) }; + const out = await judge(chain(step('a1')), { objects }); + expect(out.gaps).toEqual([{ kind: 'no_pending_option', flow: 'F', step: 'a1', object: 'invoice', field: 'status' }]); + }); + + it.each(['pending', 'returned'])('refuses an object that closes on %s', async (value) => { + const objects = { invoice: invoice({ closedStates: { status: ['approved', value] } }) }; + const out = await judge(chain(step('a1')), { objects }); + expect(out.gaps).toEqual([{ kind: 'closes_in_flight', flow: 'F', step: 'a1', object: 'invoice', field: 'status', value }]); + }); + + it('refuses a state_machine rule whose moves out of a closed approved leave out pending', async () => { + const validations = [{ name: 'flow_of_status', type: 'state_machine', field: 'status', transitions: { approved: ['draft'], rejected: ['pending', 'draft'] } }]; + const out = await judge(chain(step('a1')), { objects: { invoice: invoice({ validations }) } }); + expect(out.gaps).toEqual([{ kind: 'state_machine_no_pending', flow: 'F', step: 'a1', object: 'invoice', field: 'status', value: 'approved', rule: 'flow_of_status' }]); + }); + + it('reads a state_machine rule that keeps a closed value final as missing pending, and one that declares no move out of it as nothing', async () => { + const final = [{ name: 'r', type: 'state_machine', field: 'status', transitions: { rejected: [] } }]; + expect(kinds((await judge(chain(step('a1')), { objects: { invoice: invoice({ validations: final }) } })).gaps)).toEqual(['state_machine_no_pending']); + const silent = [{ name: 'r', type: 'state_machine', field: 'status', transitions: { draft: ['pending'] } }]; + expect((await judge(chain(step('a1')), { objects: { invoice: invoice({ validations: silent }) } })).gaps).toEqual([]); + }); + + it('refuses a field that carries a readonlyWhen', async () => { + const objects = { invoice: invoice({ fields: { status: statusField({ readonlyWhen: 'record.locked' }) } }) }; + expect((await judge(chain(step('a1')), { objects })).gaps) + .toEqual([{ kind: 'readonly_when', flow: 'F', step: 'a1', object: 'invoice', field: 'status' }]); + }); + + it.each(['pending', 'returned', 'approved', 'rejected', 'recalled'])('refuses a visibleWhen on the %s option', async (value) => { + const options = STATUSES.map((v) => (v === value ? { value: v, label: v, visibleWhen: 'false' } : { value: v, label: v })); + const objects = { invoice: invoice({ fields: { status: statusField({}, options) } }) }; + expect((await judge(chain(step('a1')), { objects })).gaps) + .toEqual([{ kind: 'option_visible_when', flow: 'F', step: 'a1', object: 'invoice', field: 'status', value }]); + }); + + it('does not refuse a visibleWhen on an option that is no request status', async () => { + const options = STATUSES.map((v) => (v === 'draft' ? { value: v, label: v, visibleWhen: 'false' } : { value: v, label: v })); + expect((await judge(chain(step('a1')), { objects: { invoice: invoice({ fields: { status: statusField({}, options) } }) } })).gaps).toEqual([]); + }); + + it('reads nothing of an object that closes only on values of its own, also with a state_machine that keeps one final', async () => { + const validations = [{ name: 'r', type: 'state_machine', field: 'status', transitions: { archived: [] } }]; + const objects = { invoice: invoice({ closedStates: { status: ['archived'] }, validations, fields: { status: statusField({ readonlyWhen: 'x' }) } }) }; + const out = await judge(chain(step('a1'), n('w', 'wait'), step('a2')), { objects }); + expect(out.gaps).toEqual([]); + expect(out.touchesClosedStates).toBe(true); + expect(out.between.length).toBeGreaterThan(0); + }); +}); + +describe('the opening check: D5 condition 4, every step mirrors onto the field', () => { + it.each([ + ['after', [step('a1'), step('a2', 'other_status')]], + ['ahead of', [step('a2', 'other_status'), step('a1')]], + ] as const)('refuses a step %s a concerned step that mirrors onto another field', async (_where, nodes) => { + const out = await judge(chain(...nodes)); + expect(out.gaps).toEqual([{ kind: 'other_field', flow: 'F', step: 'a2', object: 'invoice', field: 'status', other: 'other_status' }]); + }); + + it('refuses a step that names no field beside a concerned one', async () => { + const out = await judge(chain(step('a1'), step('a2', null))); + expect(out.gaps).toEqual([{ kind: 'no_field', flow: 'F', step: 'a2', object: 'invoice', field: 'status' }]); + }); + + it('does not refuse, but stamps, an approval none of whose steps names a closing field', async () => { + const out = await judge(chain(step('a1', null), n('w', 'wait'), step('a2', 'other_status'))); + expect(out.gaps).toEqual([]); + expect(out.touchesClosedStates).toBe(true); + expect(out.between).toEqual([{ flow: 'F', node: 'a1' }, { flow: 'F', node: 'w' }]); + }); + + it('refuses a step two levels down that mirrors onto another field', async () => { + const flows = { + S1: chain(n('s2', 'subflow', { flowName: 'S2' })), + S2: chain(step('deep', 'other_status')), + }; + const out = await judge(chain(step('a1'), n('s1', 'subflow', { flowName: 'S1' })), { flows }); + expect(out.gaps).toEqual([{ kind: 'other_field', flow: 'S2', step: 'deep', object: 'invoice', field: 'status', other: 'other_status' }]); + }); +}); + +describe('the opening check: D5 condition 5, no pause between two steps', () => { + it.each(['wait', 'screen'])('refuses a %s between two steps', async (type) => { + const out = await judge(chain(step('a1'), n('p', type), step('a2'))); + expect(out.gaps).toEqual([{ kind: 'pause_between_steps', flow: 'F', node: 'p', type, object: 'invoice' }]); + }); + + it.each(['wait', 'screen'])('refuses a %s between two steps in a screen flow too (a run with no record trigger)', async (type) => { + const root = { ...chain(step('a1'), n('p', type), step('a2')), type: 'screen' }; + expect(kinds((await judge(root)).gaps)).toEqual(['pause_between_steps']); + }); + + it('does not refuse a pause before the first step or after the last', async () => { + expect((await judge(chain(n('p0', 'wait'), step('a1'), step('a2'), n('p1', 'screen')))).gaps).toEqual([]); + }); + + it('refuses a node type that publishes no descriptor, and one the engine cannot be asked about', async () => { + expect(kinds((await judge(chain(step('a1'), n('x', 'custom_thing'), step('a2')))).gaps)).toEqual(['pause_between_steps']); + const unread = await judge(chain(step('a1'), n('x', 'decision'), step('a2')), { descriptors: { decision: 'unread' } }); + expect(kinds(unread.gaps)).toEqual(['pause_between_steps']); + }); + + it('follows aliasOf to the canonical descriptor', async () => { + const descriptors = { hold: { aliasOf: 'wait' }, branch: { aliasOf: 'decision' } }; + expect(kinds((await judge(chain(step('a1'), n('x', 'hold'), step('a2')), { descriptors })).gaps)).toEqual(['pause_between_steps']); + expect((await judge(chain(step('a1'), n('x', 'branch'), step('a2')), { descriptors })).gaps).toEqual([]); + }); + + it('does not refuse the revise window of a returned request', async () => { + expect((await judge(chain(step('a1'), n('rev', 'approval_revise'), step('a2')))).gaps).toEqual([]); + }); + + it('refuses a pause after the only step of a loop body, where the step opens again', async () => { + const root = chain(n('l', 'loop', { collection: '{{items}}', body: chain(step('a1'), n('p', 'wait')) })); + expect(kinds((await judge(root)).gaps)).toEqual(['pause_between_steps']); + }); + + it('refuses a pause in one of two child runs side by side, where the other branch\'s step can follow it', async () => { + const flows = { C1: chain(step('c1'), n('p', 'wait')), C2: chain(step('c2')) }; + const root = chain(n('par', 'parallel', { + branches: [ + { name: 'one', ...chain(n('s1', 'subflow', { flowName: 'C1' })) }, + { name: 'two', ...chain(n('s2', 'subflow', { flowName: 'C2' })) }, + ], + })); + const out = await judge(root, { flows }); + expect(out.gaps).toEqual([{ kind: 'pause_between_steps', flow: 'C1', node: 'p', type: 'wait', object: 'invoice' }]); + }); + + it('refuses a pause in a catch region, where a step that failed is followed by another', async () => { + const root = chain(n('t', 'try_catch', { try: chain(step('a1')), catch: chain(n('p', 'wait')) }), step('a2')); + expect(kinds((await judge(root)).gaps)).toEqual(['pause_between_steps']); + }); +}); + +describe('the opening check: D5 condition 5, a map with an approval body', () => { + const body = { B: chain(step('b1')) }; + const map = (collection: unknown, extra: Record = {}) => n('m', 'map', { flowName: 'B', collection, ...extra }); + + it.each([ + ['ahead of', [map('{{record.lines}}'), step('a1')]], + ['between', [step('a1'), map('{{record.lines}}'), step('a2')]], + ['after', [step('a1'), map('{{record.lines}}')]], + ] as const)('refuses a map whose items are read from an expression, %s the parent\'s steps', async (_where, nodes) => { + const out = await judge(chain(...nodes), { flows: body }); + expect(out.gaps).toContainEqual({ kind: 'map_with_approval', flow: 'F', node: 'm', object: 'invoice' }); + }); + + it('refuses it also where the node names an object for its items', async () => { + const objects = { invoice: invoice(), invoice_line: { name: 'invoice_line', fields: {} } }; + const out = await judge(chain(step('a1'), map('{{record.lines}}', { itemObject: 'invoice_line' })), { flows: body, objects }); + expect(out.gaps).toContainEqual({ kind: 'map_with_approval', flow: 'F', node: 'm', object: 'invoice' }); + }); + + it('reads items written out with none a record as steps of the parent, and refuses one that is a record', async () => { + const plain = await judge(chain(step('a1'), map([{ amount: 1 }, { amount: 2 }])), { flows: body }); + expect(plain.gaps).toEqual([]); + // As steps of the parent, the body's step is held to condition 4 on the parent's object. + const otherField = await judge(chain(step('a1'), map([{ amount: 1 }])), { flows: { B: chain(step('b1', 'other_status')) } }); + expect(otherField.gaps).toEqual([{ kind: 'other_field', flow: 'B', step: 'b1', object: 'invoice', field: 'status', other: 'other_status' }]); + const oneRecord = await judge(chain(step('a1'), map([{ amount: 1 }, { id: 'inv-2' }])), { flows: body }); + expect(oneRecord.gaps).toContainEqual({ kind: 'map_with_approval', flow: 'F', node: 'm', object: 'invoice' }); + }); + + it('does not refuse a map whose parent\'s object the conditions do not concern', async () => { + const out = await judge(chain(step('a1'), map('{{record.lines}}', { itemObject: 'invoice' })), { flows: body, rootObject: 'memo' }); + expect(kinds(out.gaps)).not.toContain('map_with_approval'); + expect(out.gaps).toEqual([]); + }); + + it('does not refuse the batch of a run with no record', async () => { + const out = await judge(chain(map('{{input.ids}}', { itemObject: 'invoice' })), { flows: body, rootObject: null }); + expect(out.gaps).toEqual([]); + expect(out.touchesClosedStates).toBe(true); + }); + + it('stamps a map body including its only step', async () => { + const flows = { B: chain(n('p', 'assignment'), step('b1'), n('q', 'assignment')) }; + const out = await judge(chain(map('{{input.ids}}', { itemObject: 'invoice' })), { flows, rootObject: 'memo' }); + expect(out.gaps).toEqual([]); + expect(out.between).toEqual([ + { flow: 'B', node: 'b1' }, { flow: 'B', node: 'end' }, { flow: 'B', node: 'p' }, { flow: 'B', node: 'q' }, { flow: 'B', node: 'start' }, + { flow: 'F', node: 'm' }, + ]); + }); +}); + +describe('the opening check: the stamp', () => { + it('leaves out a branch that passes over the remaining steps', async () => { + const root: OpeningFlowBody = { + nodes: [n('start', 'start'), step('a1'), n('d', 'decision'), step('a2'), n('end', 'end'), n('skip', 'assignment'), n('end2', 'end')], + edges: [ + { source: 'start', target: 'a1' }, { source: 'a1', target: 'd' }, { source: 'd', target: 'a2' }, + { source: 'a2', target: 'end' }, { source: 'd', target: 'skip' }, { source: 'skip', target: 'end2' }, + ], + }; + const out = await judge(root); + expect(out.between).toEqual([{ flow: 'F', node: 'a1' }, { flow: 'F', node: 'd' }]); + }); + + it('follows a subflow into its body', async () => { + const flows = { S: chain(n('x', 'assignment'), step('a2')) }; + const out = await judge(chain(step('a1'), n('sub', 'subflow', { flowName: 'S' })), { flows }); + expect(out.gaps).toEqual([]); + expect(out.between).toEqual([{ flow: 'F', node: 'a1' }, { flow: 'F', node: 'sub' }, { flow: 'S', node: 'start' }, { flow: 'S', node: 'x' }]); + }); + + it('does not count a subflow after the last step as between', async () => { + const flows = { S: chain(n('x', 'assignment')) }; + const out = await judge(chain(step('a1'), n('sub', 'subflow', { flowName: 'S' })), { flows }); + expect(out.between).toEqual([]); + }); +}); + +describe('the opening check: what it does not read, and what it cannot', () => { + it('reads nothing more of an approval whose objects declare no closedStates', async () => { + const out = await judge(chain(step('a1'), n('w', 'wait'), step('a2', null)), { rootObject: 'memo', host: false }); + expect(out).toMatchObject({ touchesClosedStates: false, between: [], gaps: [] }); + expect(new Set(out.read)).toEqual(new Set(['memo'])); + }); + + it('refuses an approval one of whose flows cannot be read', async () => { + const out = await judge(chain(step('a1'), n('sub', 'subflow', { flowName: 'missing' }))); + expect(out.gaps).toContainEqual({ kind: 'unreadable_flow', flow: 'missing' }); + const noRoot = await judgeApprovalOpening({ rootFlow: null, rootFlowName: 'gone', rootObject: 'invoice' }, source({})); + expect(noRoot.gaps).toEqual([{ kind: 'unreadable_flow', flow: 'gone' }]); + }); + + it('refuses on a host that runs no job service, for an approval touching a closing object', async () => { + const out = await judge(chain(step('a1', null)), { host: false }); + expect(out.gaps).toEqual([{ kind: 'no_job_service', object: 'invoice' }]); + }); +}); diff --git a/packages/plugins/plugin-approvals/src/approval-opening-check.ts b/packages/plugins/plugin-approvals/src/approval-opening-check.ts new file mode 100644 index 00000000000..7bf8bd0ec74 --- /dev/null +++ b/packages/plugins/plugin-approvals/src/approval-opening-check.ts @@ -0,0 +1,644 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 D5, Execution item 7 "The check"] The check when an approval + * opens, read off the approval's definition at its first request. + * + * An approval is one passage of a record through its approval flow, taken as + * a whole: the flow its root run was started on, and every flow a `subflow` + * or a `map` in it names, to any depth. This module reads that whole once and + * answers three things: + * + * 1. **Whether the approval touches an object that declares `closedStates`**: + * a step of it can act on such an object. Only then is anything stamped or + * refused. + * 2. **The set of nodes that stand between two steps** ({@link OpeningJudgement.between}), + * which each request of the approval carries from its opening, so that the + * plugin can later place a stop or a pause against it (ADR-0162 item 8, + * design note 7210179412 question 3, T2). It is stamped for every approval + * that touches such an object, also one the conditions do not concern. + * 3. **What is missing**, for every step whose mirror field the object closes + * on at a status the mirror writes for a request that is not abandoned + * (`pending`, `returned`, `approved`, `rejected`): the five conditions of + * ADR-0162 D5 as revised on 2026-11-27, the approval's unread parts, and + * the host's `job` service. + * + * Between two steps means after a step is decided, whichever way, and before + * the next step opens; the next step can be the same step opened again (a + * `map` body or a `loop` body that holds one). The read is a reachability + * over one graph of the whole approval: every node of every flow, a `subflow` + * or a `map` joined to the body it calls, every region (`loop`, `parallel`, + * `try_catch`) joined to its container. It is context-insensitive and errs one + * way only: a node that could stand between two steps on some path counts as + * standing there. A stop wrongly read as "between" costs a resubmission; the + * other error would close a document on an unfinished approval (ADR-0162 D5). + * + * Pure over a {@link OpeningCheckSource}: the service hands it the readers it + * has (the engine's object registry, the automation engine's flow lookup and + * node descriptors, whether the host runs a `job` service), and the tests hand + * it fixtures. + */ + +import { FLOW_REGION_SLOTS_BY_TYPE } from '@objectstack/spec/automation'; + +/** The statuses the mirror writes for a request that is not abandoned. */ +const IN_APPROVAL_STATUSES = ['pending', 'returned', 'approved', 'rejected'] as const; +/** The statuses of a request whose option may carry no `visibleWhen` (D5 condition 3). */ +const REQUEST_STATUSES = ['pending', 'returned', 'approved', 'rejected', 'recalled'] as const; +/** The node types that have no executor and cannot pause (N43). */ +const STRUCTURAL_TYPES: ReadonlySet = new Set(['start', 'end']); +/** The type of an approval step. */ +const APPROVAL_TYPE = 'approval'; +/** The revise window of a returned request: not a pause between two steps (D5, ADR-0044). */ +const REVISE_WINDOW_TYPE = 'approval_revise'; +/** The two node types that call another flow; they are read by their bodies. */ +const CALL_TYPES: ReadonlySet = new Set(['subflow', 'map']); +/** How many flows one approval may name before it is read as not readable whole. */ +const MAX_FLOWS = 64; +/** How many region levels the read descends. */ +const MAX_REGION_DEPTH = 16; +/** How many `aliasOf` hops a node type's descriptor is followed. */ +const MAX_ALIAS_HOPS = 8; + +/** A flow body as the engine holds it: the parts this check reads. */ +export interface OpeningFlowBody { + nodes?: ReadonlyArray; + edges?: ReadonlyArray; +} +export interface OpeningFlowNode { + id: string; + type?: string; + label?: string; + config?: Record | null; +} +export interface OpeningFlowEdge { + source: string; + target: string; +} + +/** A flow the check read, by the key the engine files it under. */ +export interface OpeningFlow { + key: string; + body: OpeningFlowBody; +} + +/** The readers the check needs. Every one answers, never throws: the service wraps its reads. */ +export interface OpeningCheckSource { + /** The object definition registered under `name`, or `undefined`. */ + objectSchema(name: string): unknown; + /** The flow a `subflow` or a `map` of the flow filed under `callerKey` names as `name`; `null` when it cannot be read. */ + calleeFlow(name: string, callerKey: string): Promise; + /** + * The published descriptor of a node type: `undefined` where the type + * publishes none, `'unread'` where the engine cannot be asked. + */ + nodeDescriptor(type: string): { supportsPause?: unknown; aliasOf?: unknown } | undefined | 'unread'; + /** Whether the host runs the plugin's sweeps, the reconciler of ADR-0162 item 8 (a `job` service). */ + hostRunsReconciler: boolean; +} + +/** One thing that keeps the approval from opening. */ +export type OpeningGap = + | { kind: 'no_pending_option'; flow: string; step: string; object: string; field: string } + | { kind: 'closes_in_flight'; flow: string; step: string; object: string; field: string; value: string } + | { kind: 'state_machine_no_pending'; flow: string; step: string; object: string; field: string; value: string; rule: string } + | { kind: 'readonly_when'; flow: string; step: string; object: string; field: string } + | { kind: 'option_visible_when'; flow: string; step: string; object: string; field: string; value: string } + | { kind: 'other_field'; flow: string; step: string; object: string; field: string; other: string } + | { kind: 'no_field'; flow: string; step: string; object: string; field: string } + | { kind: 'pause_between_steps'; flow: string; node: string; type: string; object: string } + | { kind: 'map_with_approval'; flow: string; node: string; object: string } + | { kind: 'unreadable_flow'; flow: string } + | { kind: 'no_job_service'; object: string }; + +/** One node of the between-two-steps set: the flow it is in, by the key the engine files it under, and its id. */ +export interface BetweenNode { + flow: string; + node: string; +} + +/** What the check answers for an approval's first request. */ +export interface OpeningJudgement { + /** Whether a step of the approval can act on an object that declares `closedStates`. */ + touchesClosedStates: boolean; + /** The nodes that stand between two steps, sorted; stamped only where {@link touchesClosedStates}. */ + between: BetweenNode[]; + /** What keeps the approval from opening; empty when it opens. */ + gaps: OpeningGap[]; +} + +/** What the check is handed about the run that opens the request. */ +export interface OpeningCheckInput { + /** The flow the approval's root run was started on, read by the caller; `null` when it could not be read. */ + rootFlow: OpeningFlow | null; + /** The flow name of the root run, for a refusal that names an unread root flow. */ + rootFlowName: string; + /** The object of the root run's record; `null` for a root run that carries none (a batch). */ + rootObject: string | null; +} + +/** An object's declared closed values, field → values, or `undefined` when it declares none. */ +export function closedValuesOf(schema: unknown): ReadonlyMap> | undefined { + const declared = (schema as { closedStates?: unknown } | null | undefined)?.closedStates; + if (!declared || typeof declared !== 'object' || Array.isArray(declared)) return undefined; + const out = new Map>(); + for (const [field, values] of Object.entries(declared as Record)) { + if (!Array.isArray(values)) continue; + const set = new Set(values.filter((v): v is string => typeof v === 'string')); + if (set.size > 0) out.set(field, set); + } + return out.size > 0 ? out : undefined; +} + +/** A vertex of the approval's graph. A node is one vertex; a container or a call is two (its entry and its exit). */ +type Vertex = string; + +interface StepInfo { + flow: string; + node: OpeningFlowNode; + field: string | undefined; +} + +interface MapInfo { + flow: string; + node: OpeningFlowNode; + callee: string | null; + /** Whether the node shows that none of its items is a record (items written out, none of them one). */ + noRecordItems: boolean; +} + +/** + * Read the approval whole and judge it. Never throws: a part that cannot be + * read is a gap ({@link OpeningGap} `unreadable_flow`), and an approval with + * one cannot be judged, so it does not open. + */ +export async function judgeApprovalOpening(input: OpeningCheckInput, source: OpeningCheckSource): Promise { + const gaps: OpeningGap[] = []; + if (!input.rootFlow) { + return { touchesClosedStates: true, between: [], gaps: [{ kind: 'unreadable_flow', flow: input.rootFlowName }] }; + } + + // ── 1. Read every flow of the approval, to any depth ────────────────────── + const flows = new Map(); + /** For each flow: the flows it calls, by call node, with how the call hands objects down. */ + const calls = new Map>(); + const queue: OpeningFlow[] = [input.rootFlow]; + flows.set(input.rootFlow.key, input.rootFlow.body); + while (queue.length > 0) { + const { key, body } = queue.shift()!; + const out: Array<{ node: OpeningFlowNode; callee: string | null; kind: 'subflow' | 'map' }> = []; + for (const node of allNodes(body)) { + if (!node.type || !CALL_TYPES.has(node.type)) continue; + const name = typeof node.config?.flowName === 'string' ? node.config.flowName : ''; + if (!name) { + gaps.push({ kind: 'unreadable_flow', flow: `${key} › ${node.id}` }); + out.push({ node, callee: null, kind: node.type as 'subflow' | 'map' }); + continue; + } + const callee = await source.calleeFlow(name, key); + if (!callee) { + gaps.push({ kind: 'unreadable_flow', flow: name }); + out.push({ node, callee: null, kind: node.type as 'subflow' | 'map' }); + continue; + } + out.push({ node, callee: callee.key, kind: node.type as 'subflow' | 'map' }); + if (!flows.has(callee.key)) { + if (flows.size >= MAX_FLOWS) { + gaps.push({ kind: 'unreadable_flow', flow: name }); + continue; + } + flows.set(callee.key, callee.body); + queue.push(callee); + } + } + calls.set(key, out); + } + + // ── 2. The objects each flow's steps can act on ─────────────────────────── + // The root flow acts on the root run's record. A `subflow` body acts on its + // caller's record. A `map` body acts on an item where the item is a record, + // on the object the node names for its items (else its caller's), and on its + // caller's record where the item is not one; the check cannot read ahead + // whether an item is a record unless the items are written out in the node. + const objects = new Map>(); + for (const key of flows.keys()) objects.set(key, new Set()); + if (input.rootObject) objects.get(input.rootFlow.key)!.add(input.rootObject); + const maps: MapInfo[] = []; + for (const [key, list] of calls) { + for (const call of list) { + if (call.kind === 'map') maps.push({ flow: key, node: call.node, callee: call.callee, noRecordItems: itemsShowNoRecord(call.node) }); + } + } + for (let changed = true, rounds = 0; changed && rounds <= flows.size + 1; rounds++) { + changed = false; + for (const [key, list] of calls) { + const mine = objects.get(key)!; + for (const call of list) { + if (!call.callee) continue; + const theirs = objects.get(call.callee)!; + const before = theirs.size; + if (call.kind === 'subflow') { + for (const o of mine) theirs.add(o); + } else { + const items = mapItems(call.node); + const anyRecord = items === undefined || items.some(isRecordItem); + const anyOther = items === undefined || items.some((i) => !isRecordItem(i)); + if (anyOther) for (const o of mine) theirs.add(o); + if (anyRecord) { + const itemObject = typeof call.node.config?.itemObject === 'string' && call.node.config.itemObject + ? call.node.config.itemObject : undefined; + if (itemObject) theirs.add(itemObject); + else for (const o of mine) theirs.add(o); + } + } + if (theirs.size !== before) changed = true; + } + } + } + + // ── 3. The steps, and whether the approval touches a closing object ─────── + const steps: StepInfo[] = []; + for (const [key, body] of flows) { + for (const node of allNodes(body)) { + if (node.type !== APPROVAL_TYPE) continue; + const field = typeof node.config?.approvalStatusField === 'string' && node.config.approvalStatusField + ? node.config.approvalStatusField : undefined; + steps.push({ flow: key, node, field }); + } + } + const declaring = (object: string) => closedValuesOf(source.objectSchema(object)) !== undefined; + const touchesClosedStates = gaps.length > 0 + || steps.some((s) => [...objects.get(s.flow)!].some(declaring)); + if (!touchesClosedStates) return { touchesClosedStates: false, between: [], gaps: [] }; + + // ── 4. The nodes between two steps ──────────────────────────────────────── + const graph = buildGraph(flows, calls); + const stepVertices = steps.map((s) => vertexOf(s.flow, s.node.id)); + const after = reach(graph.succ, stepVertices); + const before = reach(graph.pred, stepVertices); + const betweenKeys = new Set(); + const pausing: Array<{ flow: string; node: OpeningFlowNode }> = []; + // A node other than a step is between two steps where a step can come + // before it and a step can follow it. A step is in the set where a step can + // follow it: a run that stops on a step decided with no later step logged + // (design note question 3, T2) stopped between two steps exactly then. + for (const [vertex, owner] of graph.owner) { + if (!before.has(vertex)) continue; + const isStep = owner.node.type === APPROVAL_TYPE; + if (!isStep && !after.has(vertex)) continue; + const k = `${owner.flow}\u0000${owner.node.id}`; + if (betweenKeys.has(k)) continue; + betweenKeys.add(k); + if (!isStep && canPause(owner.node, source)) pausing.push(owner); + } + // A `map` or a `loop` whose body holds a step stands between two steps + // where it is entered before a step and left after one: between one item's + // (one pass's) step and the next, the run is parked at the node or back on + // it. A `subflow` is not: its body runs once. + for (const { flow, node } of graph.owner.values()) { + if (node.type !== 'map' && node.type !== 'loop') continue; + if (before.has(vertexOf(flow, node.id, 'in')) && after.has(vertexOf(flow, node.id, 'out'))) { + betweenKeys.add(`${flow}\u0000${node.id}`); + } + } + const between = [...betweenKeys] + .map((k) => { const [flow, node] = k.split('\u0000'); return { flow, node }; }) + .sort((a, b) => (a.flow === b.flow ? cmp(a.node, b.node) : cmp(a.flow, b.flow))); + + // ── 5. The conditions, for every step they concern ──────────────────────── + const concernedObjects = new Set(); + for (const step of steps) { + for (const object of objects.get(step.flow)!) { + const schema = source.objectSchema(object); + const closed = closedValuesOf(schema); + if (!closed || !step.field) continue; + const values = closed.get(step.field); + if (!values || !IN_APPROVAL_STATUSES.some((s) => values.has(s))) continue; + concernedObjects.add(object); + judgeField(step, object, step.field, schema, values, gaps); + // Condition 4: every step that can act on a record of the object names that field. + for (const other of steps) { + if (other === step || !objects.get(other.flow)!.has(object)) continue; + if (other.field === step.field) continue; + if (other.field) gaps.push({ kind: 'other_field', flow: other.flow, step: other.node.id, object, field: step.field, other: other.field }); + else gaps.push({ kind: 'no_field', flow: other.flow, step: other.node.id, object, field: step.field }); + } + } + } + if (concernedObjects.size > 0) { + const object = [...concernedObjects].sort(cmp)[0]; + // Condition 5: no node that can pause the run of itself stands between two steps. + for (const p of pausing) { + gaps.push({ kind: 'pause_between_steps', flow: p.flow, node: p.node.id, type: String(p.node.type ?? ''), object }); + } + // Condition 5, its second half: no `map` with an approval step in its body, + // at any depth, where the parent's object is one the conditions concern, + // unless the node shows that none of its items is a record. + const holdsStep = flowsHoldingSteps(flows, calls, steps); + for (const m of maps) { + if (!m.callee || !holdsStep.has(m.callee) || m.noRecordItems) continue; + const parentObjects = [...objects.get(m.flow)!].filter((o) => concernedObjects.has(o)).sort(cmp); + if (parentObjects.length > 0) gaps.push({ kind: 'map_with_approval', flow: m.flow, node: m.node.id, object: parentObjects[0] }); + } + } + + // ── 6. The host ─────────────────────────────────────────────────────────── + if (!source.hostRunsReconciler) { + const object = steps.flatMap((s) => [...objects.get(s.flow)!]).filter(declaring).sort(cmp)[0]; + if (object) gaps.push({ kind: 'no_job_service', object }); + } + + return { touchesClosedStates, between, gaps: dedupe(gaps) }; +} + +/** D5 conditions 1 to 3, on the field `field` of `object`, for `step`. */ +function judgeField( + step: StepInfo, object: string, field: string, schema: unknown, + closed: ReadonlySet, gaps: OpeningGap[], +): void { + const flow = step.flow; + const stepId = step.node.id; + const def = (schema as { fields?: Record } | undefined)?.fields?.[field] as + { options?: unknown; readonlyWhen?: unknown } | undefined; + const options = Array.isArray(def?.options) ? def!.options as unknown[] : []; + const optionOf = (value: string): Record | undefined => { + for (const o of options) { + if (o && typeof o === 'object' && String((o as { value?: unknown }).value) === value) return o as Record; + } + return undefined; + }; + const declares = (value: string) => options.some((o) => (o && typeof o === 'object' ? String((o as { value?: unknown }).value) : String(o)) === value); + + // 1. The field declares `pending`, and the object closes on neither `pending` nor `returned`. + if (!declares('pending')) gaps.push({ kind: 'no_pending_option', flow, step: stepId, object, field }); + for (const value of ['pending', 'returned']) { + if (closed.has(value)) gaps.push({ kind: 'closes_in_flight', flow, step: stepId, object, field, value }); + } + + // 2. A `state_machine` rule on the field that declares the moves out of a + // closed `approved` or `rejected` has `pending` among them. + const rules = (schema as { validations?: unknown } | undefined)?.validations; + if (Array.isArray(rules)) { + for (const rule of rules) { + const r = rule as { type?: unknown; field?: unknown; active?: unknown; transitions?: unknown; name?: unknown } | null; + if (!r || r.type !== 'state_machine' || r.field !== field || r.active === false) continue; + const transitions = r.transitions && typeof r.transitions === 'object' ? r.transitions as Record : {}; + for (const value of ['approved', 'rejected']) { + if (!closed.has(value) || !Object.prototype.hasOwnProperty.call(transitions, value)) continue; + const moves = transitions[value]; + if (!Array.isArray(moves) || !moves.includes('pending')) { + gaps.push({ kind: 'state_machine_no_pending', flow, step: stepId, object, field, value, rule: String(r.name ?? '') }); + } + } + } + } + + // 3. The field carries no `readonlyWhen`, and none of its options for a request's status carries a `visibleWhen`. + if (def?.readonlyWhen != null) gaps.push({ kind: 'readonly_when', flow, step: stepId, object, field }); + for (const value of REQUEST_STATUSES) { + const option = optionOf(value); + if (option && option.visibleWhen != null) gaps.push({ kind: 'option_visible_when', flow, step: stepId, object, field, value }); + } +} + +/** Whether a node can pause the run of itself, by what its type declares (D5 condition 5, N43). */ +function canPause(node: OpeningFlowNode, source: OpeningCheckSource): boolean { + const type = node.type; + if (!type) return true; // a node it cannot place counts as one that can + if (STRUCTURAL_TYPES.has(type) || type === APPROVAL_TYPE || type === REVISE_WINDOW_TYPE || CALL_TYPES.has(type)) return false; + let descriptor = source.nodeDescriptor(type); + for (let hop = 0; descriptor && descriptor !== 'unread' && typeof descriptor.aliasOf === 'string' && hop < MAX_ALIAS_HOPS; hop++) { + const canonical = source.nodeDescriptor(descriptor.aliasOf as string); + if (!canonical || canonical === 'unread' || canonical === descriptor) break; + descriptor = canonical; + } + if (descriptor === 'unread' || descriptor === undefined) return true; + return descriptor.supportsPause === true; +} + +/** Every node of a body, its regions' nodes included, to {@link MAX_REGION_DEPTH}. */ +function allNodes(body: OpeningFlowBody): OpeningFlowNode[] { + const out: OpeningFlowNode[] = []; + const visit = (nodes: ReadonlyArray | undefined, depth: number) => { + for (const node of nodes ?? []) { + if (!node || typeof node !== 'object' || typeof node.id !== 'string') continue; + out.push(node); + if (depth >= MAX_REGION_DEPTH) continue; + for (const region of regionsOf(node)) visit(region.nodes, depth + 1); + } + }; + visit(body.nodes, 0); + return out; +} + +/** The regions a container node holds, in slot order. */ +function regionsOf(node: OpeningFlowNode): Array<{ slot: string; region: OpeningFlowBody } & OpeningFlowBody> { + const slots = node.type ? FLOW_REGION_SLOTS_BY_TYPE.get(node.type) : undefined; + if (!slots) return []; + const out: Array<{ slot: string; region: OpeningFlowBody } & OpeningFlowBody> = []; + for (const slot of slots) { + const value = node.config?.[slot.key]; + const list = slot.arity === 'many' ? (Array.isArray(value) ? value : []) : (value ? [value] : []); + list.forEach((raw, i) => { + // A `parallel` branch carries its region beside its name; read either shape. + const region = raw && typeof raw === 'object' && 'region' in (raw as object) + ? (raw as { region?: OpeningFlowBody }).region : raw as OpeningFlowBody; + if (region && typeof region === 'object') { + out.push({ slot: `${slot.key}[${i}]`, region, nodes: region.nodes, edges: region.edges }); + } + }); + } + return out; +} + +/** The items a `map` node writes out in itself, or `undefined` where they are read from an expression. */ +function mapItems(node: OpeningFlowNode): unknown[] | undefined { + const collection = node.config?.collection; + return Array.isArray(collection) ? collection : undefined; +} + +/** Whether an item is a record, read as the `map` node reads it (an object with a string `id`). */ +function isRecordItem(item: unknown): boolean { + return item != null && typeof item === 'object' && typeof (item as { id?: unknown }).id === 'string'; +} + +/** Whether a `map` node shows that none of its items is a record: its items are written out, and none is one. */ +function itemsShowNoRecord(node: OpeningFlowNode): boolean { + const items = mapItems(node); + return items !== undefined && !items.some(isRecordItem); +} + +/** The flows whose body holds an approval step at any depth, through the flows it calls. */ +function flowsHoldingSteps( + flows: Map, + calls: Map>, + steps: StepInfo[], +): Set { + const holds = new Set(steps.map((s) => s.flow)); + for (let changed = true, rounds = 0; changed && rounds <= flows.size + 1; rounds++) { + changed = false; + for (const [key, list] of calls) { + if (holds.has(key)) continue; + if (list.some((c) => c.callee && holds.has(c.callee))) { holds.add(key); changed = true; } + } + } + return holds; +} + +function vertexOf(flow: string, node: string, part = ''): Vertex { + return `${flow}\u0000${node}\u0000${part}`; +} + +interface Graph { + succ: Map>; + pred: Map>; + /** Each vertex that stands for a node, with the node and its flow. Synthetic vertices are absent. */ + owner: Map; +} + +/** + * One graph of the whole approval. A plain node is one vertex. A container + * (`loop`, `parallel`, `try_catch`) and a call (`subflow`, `map`) are two, its + * entry and its exit, joined through the regions or the body it runs: + * - a region or a called body is entered from the entry and left to the exit; + * - a `loop` body and a `map` body may run again (exit → entry) or not at all + * (entry → exit); + * - the branches of a `parallel` may interleave, so each branch's exit leads + * into every other branch; + * - every node of a `try` region may fail into its `catch` region and to the + * container's exit; + * - an edge of the flow, a `fault` edge included, leads from its source's exit + * to its target's entry. + * A step is one vertex: its decision leaves it. + */ +function buildGraph( + flows: Map, + calls: Map>, +): Graph { + const succ = new Map>(); + const pred = new Map>(); + const owner = new Map(); + const link = (a: Vertex, b: Vertex) => { + if (!succ.has(a)) succ.set(a, new Set()); + if (!pred.has(b)) pred.set(b, new Set()); + succ.get(a)!.add(b); + pred.get(b)!.add(a); + }; + const entryOfFlow = (key: string) => vertexOf(key, '', 'flow-entry'); + const exitOfFlow = (key: string) => vertexOf(key, '', 'flow-exit'); + const calleeOf = new Map(); + for (const [key, list] of calls) for (const c of list) calleeOf.set(`${key}\u0000${c.node.id}`, c); + + const isCompound = (node: OpeningFlowNode) => !!node.type && (CALL_TYPES.has(node.type) || FLOW_REGION_SLOTS_BY_TYPE.has(node.type)); + const inOf = (flow: string, node: OpeningFlowNode) => vertexOf(flow, node.id, isCompound(node) ? 'in' : ''); + const outOf = (flow: string, node: OpeningFlowNode) => vertexOf(flow, node.id, isCompound(node) ? 'out' : ''); + + /** Wire one graph (a flow's top level or a region); answers its entry and exit vertices. */ + const wire = (flow: string, nodes: ReadonlyArray | undefined, edges: ReadonlyArray | undefined, depth: number): + { entries: Vertex[]; exits: Vertex[]; inner: Vertex[] } => { + const list = (nodes ?? []).filter((n) => n && typeof n === 'object' && typeof n.id === 'string'); + const byId = new Map(list.map((n) => [n.id, n])); + const inner: Vertex[] = []; + const hasIn = new Set(); + const hasOut = new Set(); + for (const e of edges ?? []) { + const a = byId.get(e?.source); + const b = byId.get(e?.target); + if (!a || !b) continue; + link(outOf(flow, a), inOf(flow, b)); + hasOut.add(a.id); + hasIn.add(b.id); + } + for (const node of list) { + const vin = inOf(flow, node); + const vout = outOf(flow, node); + owner.set(vin, { flow, node }); + owner.set(vout, { flow, node }); + inner.push(vin); + if (vout !== vin) inner.push(vout); + const call = calleeOf.get(`${flow}\u0000${node.id}`); + if (call) { + if (call.callee) { + link(vin, entryOfFlow(call.callee)); + link(exitOfFlow(call.callee), vout); + if (call.kind === 'map') link(exitOfFlow(call.callee), entryOfFlow(call.callee)); + } else { + link(vin, vout); + } + if (call.kind === 'map') link(vin, vout); + continue; + } + const regions = depth < MAX_REGION_DEPTH ? regionsOf(node) : []; + if (node.type && FLOW_REGION_SLOTS_BY_TYPE.has(node.type)) { + const wired = regions.map((r) => ({ slot: r.slot, ...wire(flow, r.nodes, r.edges, depth + 1) })); + if (wired.length === 0) link(vin, vout); + if (node.type === 'try_catch') { + const tryR = wired.filter((w) => w.slot.startsWith('try')); + const catchR = wired.filter((w) => w.slot.startsWith('catch')); + for (const t of tryR) { + for (const e of t.entries) link(vin, e); + for (const x of t.exits) link(x, vout); + for (const v of t.inner) { + link(v, vout); + for (const c of catchR) for (const e of c.entries) link(v, e); + } + } + for (const c of catchR) for (const x of c.exits) link(x, vout); + } else { + for (const w of wired) { + for (const e of w.entries) link(vin, e); + for (const x of w.exits) link(x, vout); + } + if (node.type === 'loop') { + link(vin, vout); + for (const w of wired) for (const x of w.exits) for (const e of w.entries) link(x, e); + } + if (node.type === 'parallel') { + for (const a of wired) for (const b of wired) { + if (a === b) continue; + for (const x of a.exits) for (const e of b.entries) link(x, e); + } + } + } + } + } + const entries = list.filter((n) => (depth === 0 ? n.type === 'start' || !hasIn.has(n.id) : !hasIn.has(n.id))).map((n) => inOf(flow, n)); + const exits = list.filter((n) => !hasOut.has(n.id)).map((n) => outOf(flow, n)); + return { entries, exits, inner }; + }; + + for (const [key, body] of flows) { + const { entries, exits } = wire(key, body.nodes, body.edges, 0); + for (const e of entries) link(entryOfFlow(key), e); + for (const x of exits) link(x, exitOfFlow(key)); + } + return { succ, pred, owner }; +} + +/** The vertices reachable from `starts` by one edge or more. */ +function reach(edges: Map>, starts: Vertex[]): Set { + const seen = new Set(); + const stack: Vertex[] = []; + for (const s of starts) for (const n of edges.get(s) ?? []) stack.push(n); + while (stack.length > 0) { + const v = stack.pop()!; + if (seen.has(v)) continue; + seen.add(v); + for (const n of edges.get(v) ?? []) if (!seen.has(n)) stack.push(n); + } + return seen; +} + +function cmp(a: string, b: string): number { + return a < b ? -1 : a > b ? 1 : 0; +} + +function dedupe(gaps: OpeningGap[]): OpeningGap[] { + const seen = new Set(); + return gaps.filter((g) => { + const k = JSON.stringify(g); + if (seen.has(k)) return false; + seen.add(k); + return true; + }); +} diff --git a/packages/plugins/plugin-approvals/src/approval-opening-refusal.ts b/packages/plugins/plugin-approvals/src/approval-opening-refusal.ts new file mode 100644 index 00000000000..3018bdec513 --- /dev/null +++ b/packages/plugins/plugin-approvals/src/approval-opening-refusal.ts @@ -0,0 +1,60 @@ +/** + * The sentence an approval's first request is refused with when the opening + * check (ADR-0162 Execution item 7, #37766 slice B) finds a gap: one lead + * naming the record, then one sentence per gap naming the flow, step, object, + * field and what is missing — in the run's locale, from the plugin's own + * catalog (`translations/messages.ts`), falling back to `en`. + */ + +import { interpolate } from './approval-notification-text.js'; +import type { OpeningGap } from './approval-opening-check.js'; +import { approvalMessages, type ApprovalMessageId } from './translations/messages.js'; + +type Pack = (typeof approvalMessages)[keyof typeof approvalMessages]; + +const GAP_SENTENCE: Readonly> = { + no_pending_option: 'approvalOpeningNoPendingOption', + closes_in_flight: 'approvalOpeningClosesInFlight', + state_machine_no_pending: 'approvalOpeningStateMachine', + readonly_when: 'approvalOpeningReadonlyWhen', + option_visible_when: 'approvalOpeningOptionVisibleWhen', + other_field: 'approvalOpeningOtherField', + no_field: 'approvalOpeningNoField', + pause_between_steps: 'approvalOpeningPause', + map_with_approval: 'approvalOpeningMapApproval', + unreadable_flow: 'approvalOpeningUnreadableFlow', + no_job_service: 'approvalOpeningNoJobService', +}; + +/** + * The catalog pack for `locale`: the exact tag; else `zh-Hant` for a + * Traditional Chinese tag (`zh-TW`, `zh-HK`, `zh-MO`); else the first pack of + * the same language; else `en`. + */ +export function openingRefusalPack(locale: string | undefined): Pack { + const packs = approvalMessages as Readonly>; + if (!locale) return approvalMessages.en; + const wanted = locale.replace(/_/g, '-').toLowerCase(); + const tags = Object.keys(packs); + const exact = tags.find((t) => t.toLowerCase() === wanted); + if (exact) return packs[exact]!; + if (/^zh-(hant|tw|hk|mo)\b/.test(wanted) && packs['zh-Hant']) return packs['zh-Hant']!; + const language = wanted.split('-')[0]; + const same = tags.find((t) => t.toLowerCase().split('-')[0] === language); + return same ? packs[same]! : approvalMessages.en; +} + +/** The refusal text for `gaps`, on the record `subject`, in `locale`. */ +export function openingRefusalText( + gaps: readonly OpeningGap[], + subject: { object: string; record: string }, + locale?: string, +): string { + const pack = openingRefusalPack(locale); + const lead = interpolate(pack.approvalOpeningRefusedLead, { object: subject.object, record: subject.record }); + const sentences = gaps.map((gap) => { + const { kind, ...params } = gap; + return interpolate(pack[GAP_SENTENCE[kind]], params as Record); + }); + return [lead, ...sentences].join(' '); +} diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index 610a641fdda..4cf242174aa 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -179,6 +179,8 @@ import { APPROVALS_INBOX_PATH, renderConfirmPage, renderResultPage } from './act import { consolePageLink, type ConsolePageComposer } from './public-base-url.js'; import { APPROVAL_EMAIL_CHANNELS, EMAILED_APPROVAL_TOPICS } from './approval-email-templates.js'; import { enMessages } from './translations/messages.js'; +import { closedValuesOf, judgeApprovalOpening, type OpeningFlow } from './approval-opening-check.js'; +import { openingRefusalText } from './approval-opening-refusal.js'; import { approvalMessageKey, approvalNotificationText, @@ -223,7 +225,18 @@ export interface ApprovalEngine { * registering door wrote for a package, with its `source`. Optional so a * double without it answers "origin unknown", and the gate refuses. */ - registry?: { getPackage?(id: string): { source?: unknown } | undefined }; + registry?: { + getPackage?(id: string): { source?: unknown } | undefined; + /** + * [ADR-0162 Execution item 7] Every registered object, read by the check + * when an approval opens ({@link ApprovalService.judgeOpening}) to learn + * whether any object declares `closedStates`: in an application where + * none does, nothing is read and no approval is refused. Optional: absent, + * the check reads the approval whenever its own record's object declares + * the key. + */ + getAllObjects?(): unknown[]; + }; /** * `ObjectQL.residualOwnerSource`: the registering door's statement for an * artifact residual's owner id, which has no registry row. Read by the same @@ -315,6 +328,17 @@ export interface ApprovalResumeSurface { flowSlotKey?(packageId: string | null, name: string): string | undefined; getFlowSlot?(packageId: string | null, name: string): any | null; getRunFlow?(run: { flowName: string }): any | null; + /** + * [ADR-0162 Execution item 7] The action descriptor a node type publishes + * (ADR-0018), or `undefined` where it publishes none: how the check when an + * approval opens reads whether a node between two steps can pause the run + * of itself (`supportsPause`), following `aliasOf` as the engine's own + * pause gate does. ⚠️ Declares a method `AutomationEngine` ALREADY + * implements publicly (`getActionDescriptor`); it widens no engine surface. + * Optional: absent, every node type but the structural ones counts as one + * that can pause. + */ + getActionDescriptor?(type: string): { supportsPause?: unknown; aliasOf?: unknown } | undefined; /** * [#35863] A flow name's registrations, oldest first: each body and when it * was registered. Read by {@link ApprovalService.attachFlowRoute} to tell @@ -2655,6 +2679,23 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega this.automation = automation; } + /** + * [ADR-0162 D5, Execution item 7] Whether the host runs this plugin's sweeps: + * the plugin calls {@link noteSweepClockScheduled} once it has scheduled them + * on the host's `job` service. The sweeps are what ends an approval nobody + * is at the door for (ADR-0162 item 8, the reconciler), so on a host with no + * `job` service the first request of every approval a step of which can act + * on an object that declares `closedStates` is refused, saying what is + * missing (seat rulings 7211509661 and 7211531658, the seat's ruling on the + * design note 7210179412). `false` until noted. + */ + private sweepClockScheduled = false; + + /** [ADR-0162 Execution item 7] The plugin scheduled its sweeps on the host's `job` service ({@link sweepClockScheduled}). */ + noteSweepClockScheduled(): void { + this.sweepClockScheduled = true; + } + /** Attach (or replace) the messaging surface used for thread notifications. */ attachMessaging(messaging: ApprovalMessagingSurface): void { this.messaging = messaging; @@ -5083,6 +5124,176 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega return Array.isArray(closed) && (closed.includes('approved') || closed.includes('rejected')); } + /** + * [ADR-0162 D5, Execution item 7 "The check"] Judge an approval at its first + * request, and answer the between-two-steps set the request carries + * (`between_steps_json`), or `null` where it carries none. Throws, with what + * is missing, where the approval may not open. + * + * - **Placed by its root run.** The approval is the request's root run + * (ADR-0162 item 7, slice A). A request whose run hands no root run cannot + * be placed: it is not judged and carries no set. A request of an approval + * that already has one is a later request: it is not judged again, since + * refusing it would end the approval between two steps, and it carries the + * set its approval's first request was stamped with. A request opened on + * the record since the root run started that records no root run makes + * this one unplaceable too: not judged, no set. + * - **Nothing read where nothing declares the key.** In an application where + * no object declares `closedStates`, the approval is not read. + * - **Read whole.** The flow the root run was started on and every flow a + * `subflow` or a `map` names, to any depth ({@link judgeApprovalOpening}). + * An approval that cannot be read whole is refused. + * - **Refused** where a step's mirror field is one the object closes on at a + * status of a request in flight and a condition of D5 fails, or where a + * step can act on an object that declares the key and the host runs no + * `job` service. The refusal is a `VALIDATION_FAILED`, whose sentence names + * the flow, the step, the object, the field and what is missing, in the + * run's locale where the plugin carries it ({@link openingRefusalText}). + * The node fails the run with it, which is what the submitter reads. + */ + private async judgeOpening( + input: { + object: string; recordId: string; runId: string; nodeId: string; + flowName?: string; flowKey?: string; runRoot?: boolean; + rootRun?: ApprovalRootRun | null; locale?: string; + }, + context: ExecutionContext, + ): Promise { + const rootRun = input.rootRun; + if (!rootRun?.runId) return null; + + // A later request of the same approval carries its first request's set. + let earlier: any[]; + try { + earlier = await this.engine.find('sys_approval_request', { + where: { root_run_id: rootRun.runId }, + fields: ['id', 'between_steps_json', 'created_at'], + orderBy: [{ field: 'created_at', order: 'asc' }], + limit: 1, context: SYSTEM_CTX, + }); + } catch (err: any) { + this.logger?.warn?.('[approvals] could not read whether a request is its approval\'s first; it opens unjudged and carries no between-two-steps set', { + run: input.runId, rootRun: rootRun.runId, error: err?.message ?? String(err), + }); + return null; + } + if (Array.isArray(earlier) && earlier[0]) { + const stamp = earlier[0].between_steps_json; + return typeof stamp === 'string' && stamp !== '' ? stamp : null; + } + // A request on the record since the root run started that records no root + // run: the plugin cannot tell whether it was this approval's first. + if (rootRun.startedAt) { + try { + const unplaced = await this.engine.find('sys_approval_request', { + where: { + object_name: input.object, record_id: input.recordId, root_run_id: null, + created_at: { $gte: rootRun.startedAt }, + }, + fields: ['id'], limit: 1, context: SYSTEM_CTX, + }); + if (Array.isArray(unplaced) && unplaced[0]) return null; + } catch (err: any) { + this.logger?.warn?.('[approvals] could not read the record\'s earlier requests; the request opens unjudged and carries no between-two-steps set', { + run: input.runId, rootRun: rootRun.runId, error: err?.message ?? String(err), + }); + return null; + } + } + + // Nothing is read in an application where no object declares the key. + const declares = (object: string | null | undefined): boolean => { + if (!object) return false; + try { return closedValuesOf(this.engine.getSchema?.(object)) !== undefined; } catch { return false; } + }; + let appDeclares: boolean; + let listed: unknown[] | undefined; + try { listed = this.engine.registry?.getAllObjects?.(); } catch { listed = undefined; } + if (Array.isArray(listed)) appDeclares = listed.some((o) => closedValuesOf(o) !== undefined); + else appDeclares = declares(input.object) || declares(rootRun.object); + if (!appDeclares) return null; + + const judgement = await judgeApprovalOpening({ + rootFlow: await this.openingRootFlow(input, rootRun), + rootFlowName: rootRun.flowName, + rootObject: rootRun.object ?? null, + }, { + objectSchema: (name) => { try { return this.engine.getSchema?.(name); } catch { return undefined; } }, + calleeFlow: (name, callerKey) => this.openingCalleeFlow(name, callerKey), + nodeDescriptor: (type) => { + if (typeof this.automation?.getActionDescriptor !== 'function') return 'unread'; + try { return this.automation.getActionDescriptor(type); } catch { return 'unread'; } + }, + hostRunsReconciler: this.sweepClockScheduled, + }); + if (judgement.gaps.length > 0) { + const locale = input.locale ?? (context as { locale?: string } | undefined)?.locale; + this.logger?.warn?.('[approvals] an approval was refused at its first request: the record\'s object closes on its approval field and the approval cannot show it in progress (ADR-0162 D5)', { + object: input.object, record: input.recordId, run: input.runId, rootRun: rootRun.runId, + gaps: judgement.gaps.map((g) => g.kind), + }); + throw new Error(`VALIDATION_FAILED: ${openingRefusalText(judgement.gaps, { object: input.object, record: input.recordId }, locale)}`); + } + if (!judgement.touchesClosedStates) return null; + return JSON.stringify(judgement.between); + } + + /** + * [ADR-0162 Execution item 7] The flow the approval's root run was started + * on, by the key the engine files it under: the request's own run's key + * where that run is the root, else the key the root run is parked under + * (it is parked at the `subflow` or the `map` that started this run), else + * the bare name. `null` where none can be read. + */ + private async openingRootFlow( + input: { flowName?: string; flowKey?: string; runRoot?: boolean }, + rootRun: ApprovalRootRun, + ): Promise { + const automation = this.automation; + if (!automation) return null; + const byKey = (key: string | undefined): any => { + if (!key || typeof automation.getRunFlow !== 'function') return null; + try { return automation.getRunFlow({ flowName: key }); } catch { return null; } + }; + try { + let key: string | undefined = input.runRoot ? (input.flowKey ?? input.flowName) : undefined; + if (!key) { + try { key = (await automation.suspensionOf?.(rootRun.runId))?.flowName; } catch { key = undefined; } + } + const body = byKey(key) ?? (typeof automation.getFlow === 'function' ? await automation.getFlow(rootRun.flowName) : null); + if (!body || typeof body !== 'object') return null; + return { key: key ?? rootRun.flowName, body }; + } catch { + return null; + } + } + + /** + * [ADR-0162 Execution item 7] The flow a `subflow` or a `map` of the flow + * filed under `callerKey` names as `name`: the one flow of a name one + * package holds (or none does), and for a name two packages hold, the + * caller's own package's slot. `null` where that cannot be read, which + * makes the approval one that cannot be read whole. + */ + private async openingCalleeFlow(name: string, callerKey: string): Promise { + const automation = this.automation; + if (!automation) return null; + try { + const slots = typeof automation.getFlowSlots === 'function' ? automation.getFlowSlots(name) : []; + if (slots.length > 1) { + const pkg = this.flowPackageOf(callerKey); + if (!pkg || typeof automation.getFlowSlot !== 'function') return null; + const body = automation.getFlowSlot(pkg, name); + const key = automation.flowSlotKey?.(pkg, name) ?? name; + return body && typeof body === 'object' ? { key, body } : null; + } + const body = typeof automation.getFlow === 'function' ? await automation.getFlow(name) : null; + return body && typeof body === 'object' ? { key: name, body } : null; + } catch { + return null; + } + } + /** * [ADR-0162 Execution item 8] Whether `row` is its approval's first request on * its record: no other request on the record names the same approval. The @@ -5431,6 +5642,12 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * store can be asked for. `null` or absent records none. */ recordRun?: ApprovalRecordRun | null; + /** + * [ADR-0162 Execution item 7] The run's locale (`AutomationContext.locale`): + * the language of a refused opening's sentence, which the run's failure + * carries to the person who submitted. + */ + locale?: string; }, context: ExecutionContext, ): Promise { @@ -5447,6 +5664,12 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega throw new Error(`DUPLICATE_REQUEST: a pending approval already exists for ${input.object}/${input.recordId}`); } + // [ADR-0162 D5, Execution item 7] The check when an approval opens, before + // anything is written: a refused opening writes no request, mirrors + // nothing and takes no lock. It answers the between-two-steps set this + // request carries from its opening. + const betweenSteps = await this.judgeOpening(input, context); + // `organizationId` is not on the envelope — see isOverrideActor(). const ctxOrg = (context as any)?.organizationId ?? context?.tenantId ?? input.organizationId ?? null; const nowDate = this.clock.now(); @@ -5841,6 +6064,9 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega root_run_id: input.rootRun?.runId ?? null, root_run_started_at: input.rootRun?.startedAt ?? null, record_run_id: input.recordRun?.runId ?? null, + // [ADR-0162 Execution item 7] The nodes that stand between two steps of + // the approval, stamped as the request opens ({@link judgeOpening}). + between_steps_json: betweenSteps, node_config_json: JSON.stringify(configSnapshot), organization_id: requestOrg, created_at: now, diff --git a/packages/plugins/plugin-approvals/src/approvals-plugin.ts b/packages/plugins/plugin-approvals/src/approvals-plugin.ts index c757c0d7beb..be3dbb05f21 100644 --- a/packages/plugins/plugin-approvals/src/approvals-plugin.ts +++ b/packages/plugins/plugin-approvals/src/approvals-plugin.ts @@ -548,6 +548,9 @@ export class ApprovalsServicePlugin implements Plugin { await jobs.schedule(ESCALATION_JOB_NAME, { type: 'interval', intervalMs }, sweep); this.jobService = jobs; this.escalationJobScheduled = true; + // [ADR-0162 Execution item 7] The sweeps run here, so an approval on an + // object that declares `closedStates` may open on this host. + svc.noteSweepClockScheduled(); void sweep().catch((err: any) => { ctx.logger.warn?.('[approvals] boot sweep failed', { error: err?.message }); }); diff --git a/packages/plugins/plugin-approvals/src/status-mirror-closing-field-refusal.integration.test.ts b/packages/plugins/plugin-approvals/src/status-mirror-closing-field-refusal.integration.test.ts index 1e3e7fe96ba..8cbc2659781 100644 --- a/packages/plugins/plugin-approvals/src/status-mirror-closing-field-refusal.integration.test.ts +++ b/packages/plugins/plugin-approvals/src/status-mirror-closing-field-refusal.integration.test.ts @@ -183,6 +183,10 @@ describe('[ADR-0162 item 8] a refused write of the status mirror on a field the messaging: { emit: async (e: any) => { emits.push(e); } } as any, }); (svc as any).organizationAdministrators = async (org: unknown) => ({ ids: org === ORG ? ['org_admin'] : [] }); + // [#37766 slice B] The host runs the plugin's sweeps, as one with a `job` + // service does: an approval on a closing object does not open on a host + // that runs none (ADR-0162 item 7), which is not what this file pins. + svc.noteSweepClockScheduled(); svc.attachAutomation(automation as any); registerApprovalNode(automation as any, svc, logger as any); bindApprovalLockHook(ql as any, logger as any); diff --git a/packages/plugins/plugin-approvals/src/sys-approval-request.object.ts b/packages/plugins/plugin-approvals/src/sys-approval-request.object.ts index f606582d10c..7b71d3b95cf 100644 --- a/packages/plugins/plugin-approvals/src/sys-approval-request.object.ts +++ b/packages/plugins/plugin-approvals/src/sys-approval-request.object.ts @@ -118,7 +118,7 @@ export const SysApprovalRequest = ObjectSchema.create({ searchableFields: [ 'process_name', 'process_package', 'process_label', 'object_name', 'record_id', 'submitter_comment', 'status', 'cancel_reason', 'current_step', 'current_step_label', 'pending_approvers', 'pending_approver_labels', - 'flow_run_id', 'flow_node_id', 'root_run_id', 'record_run_id', 'node_config_json', + 'flow_run_id', 'flow_node_id', 'root_run_id', 'record_run_id', 'between_steps_json', 'node_config_json', ], // Curated built-in list views — render as segmented tabs in the console. @@ -554,6 +554,23 @@ export const SysApprovalRequest = ObjectSchema.create({ group: 'State', }), + // [ADR-0162 Execution item 7] The nodes that stand between two steps of the + // request's approval: a JSON list of `{ flow, node }`, the flow by the key + // the engine files it under. The check when an approval opens works the set + // out at the approval's first request and stamps it on every request of + // the approval as it opens, so that a stop or a pause of the run can later + // be placed against it (ADR-0162 item 8). Engine-written at open and never + // re-derived; null on a request of an approval no step of which can act on + // an object that declares `closedStates`, and on one the plugin could not + // place. + between_steps_json: Field.textarea({ + label: 'Between Steps', + required: false, + readonly: true, + description: 'Flow nodes that stand between two steps of the approval this request belongs to.', + group: 'State', + }), + node_config_json: Field.textarea({ label: 'Node Config', required: false, diff --git a/packages/plugins/plugin-approvals/src/translations/ar.objects.generated.ts b/packages/plugins/plugin-approvals/src/translations/ar.objects.generated.ts index 15e13591861..2088ab9929f 100644 --- a/packages/plugins/plugin-approvals/src/translations/ar.objects.generated.ts +++ b/packages/plugins/plugin-approvals/src/translations/ar.objects.generated.ts @@ -117,6 +117,10 @@ export const arObjects: NonNullable = { label: "تشغيل السجل", help: "تشغيل الأتمتة الذي يحمل سجل هذا الطلب." }, + between_steps_json: { + label: "بين الخطوات", + help: "عُقد التدفق التي تقع بين خطوتين من الموافقة التي ينتمي إليها هذا الطلب." + }, node_config_json: { label: "إعداد العقدة", help: "لقطة من إعداد عقدة الموافقة (الموافِقون/السلوك) للطلبات التي تقودها العُقد." diff --git a/packages/plugins/plugin-approvals/src/translations/de.objects.generated.ts b/packages/plugins/plugin-approvals/src/translations/de.objects.generated.ts index f7a6e752006..8bffeec4815 100644 --- a/packages/plugins/plugin-approvals/src/translations/de.objects.generated.ts +++ b/packages/plugins/plugin-approvals/src/translations/de.objects.generated.ts @@ -117,6 +117,10 @@ export const deObjects: NonNullable = { label: "Datensatzausführung", help: "Automatisierungsausführung, die den Datensatz dieser Anfrage trägt." }, + between_steps_json: { + label: "Zwischen Schritten", + help: "Flussknoten, die zwischen zwei Schritten der Genehmigung stehen, zu der diese Anfrage gehört." + }, node_config_json: { label: "Knotenkonfiguration", help: "Momentaufnahme der Konfiguration des Genehmigungsknotens (Genehmiger/Verhalten) bei knotengesteuerten Anfragen." diff --git a/packages/plugins/plugin-approvals/src/translations/en.objects.generated.ts b/packages/plugins/plugin-approvals/src/translations/en.objects.generated.ts index 22a0e13f2e2..b13662521df 100644 --- a/packages/plugins/plugin-approvals/src/translations/en.objects.generated.ts +++ b/packages/plugins/plugin-approvals/src/translations/en.objects.generated.ts @@ -117,6 +117,10 @@ export const enObjects: NonNullable = { label: "Record Run", help: "Automation run that carries the record this request is on." }, + between_steps_json: { + label: "Between Steps", + help: "Flow nodes that stand between two steps of the approval this request belongs to." + }, node_config_json: { label: "Node Config", help: "Snapshot of the Approval node config (approvers/behavior) for node-driven requests." diff --git a/packages/plugins/plugin-approvals/src/translations/es-ES.objects.generated.ts b/packages/plugins/plugin-approvals/src/translations/es-ES.objects.generated.ts index 415a592b4b0..fc110876cf8 100644 --- a/packages/plugins/plugin-approvals/src/translations/es-ES.objects.generated.ts +++ b/packages/plugins/plugin-approvals/src/translations/es-ES.objects.generated.ts @@ -117,6 +117,10 @@ export const esESObjects: NonNullable = { label: "Ejecución del registro", help: "Ejecución de automatización que lleva el registro de esta solicitud." }, + between_steps_json: { + label: "Entre pasos", + help: "Nodos del flujo que están entre dos pasos de la aprobación a la que pertenece esta solicitud." + }, node_config_json: { label: "Node Config", help: "Snapshot of the Approval node config (approvers/behavior) for node-driven requests." diff --git a/packages/plugins/plugin-approvals/src/translations/fr.objects.generated.ts b/packages/plugins/plugin-approvals/src/translations/fr.objects.generated.ts index b02c1beb118..7f5d81ac7f9 100644 --- a/packages/plugins/plugin-approvals/src/translations/fr.objects.generated.ts +++ b/packages/plugins/plugin-approvals/src/translations/fr.objects.generated.ts @@ -117,6 +117,10 @@ export const frObjects: NonNullable = { label: "Exécution de l’enregistrement", help: "Exécution d’automatisation qui porte l’enregistrement de cette demande." }, + between_steps_json: { + label: "Entre les étapes", + help: "Nœuds du flux situés entre deux étapes de l'approbation à laquelle appartient cette demande." + }, node_config_json: { label: "Configuration du nœud", help: "Instantané de la configuration du nœud d’approbation (approbateurs/comportement) pour les demandes pilotées par un nœud." diff --git a/packages/plugins/plugin-approvals/src/translations/ja-JP.objects.generated.ts b/packages/plugins/plugin-approvals/src/translations/ja-JP.objects.generated.ts index e3106fa79b9..59912ac12c6 100644 --- a/packages/plugins/plugin-approvals/src/translations/ja-JP.objects.generated.ts +++ b/packages/plugins/plugin-approvals/src/translations/ja-JP.objects.generated.ts @@ -117,6 +117,10 @@ export const jaJPObjects: NonNullable = { label: "レコード実行", help: "この申請の対象レコードを担う自動化実行。" }, + between_steps_json: { + label: "ステップ間", + help: "この申請が属する承認で、二つのステップの間にあるフローノード。" + }, node_config_json: { label: "Node Config", help: "Snapshot of the Approval node config (approvers/behavior) for node-driven requests." diff --git a/packages/plugins/plugin-approvals/src/translations/ko.objects.generated.ts b/packages/plugins/plugin-approvals/src/translations/ko.objects.generated.ts index b0ebc188746..e8e20789290 100644 --- a/packages/plugins/plugin-approvals/src/translations/ko.objects.generated.ts +++ b/packages/plugins/plugin-approvals/src/translations/ko.objects.generated.ts @@ -117,6 +117,10 @@ export const koObjects: NonNullable = { label: "레코드 실행", help: "이 요청이 걸린 레코드를 담고 있는 자동화 실행입니다." }, + between_steps_json: { + label: "단계 사이", + help: "이 요청이 속한 승인에서 두 단계 사이에 있는 플로 노드입니다." + }, node_config_json: { label: "노드 구성", help: "노드 기반 요청의 승인 노드 구성(승인자/동작) 스냅숏입니다." diff --git a/packages/plugins/plugin-approvals/src/translations/messages.ts b/packages/plugins/plugin-approvals/src/translations/messages.ts index a95b39cd32a..ee99b8e5e41 100644 --- a/packages/plugins/plugin-approvals/src/translations/messages.ts +++ b/packages/plugins/plugin-approvals/src/translations/messages.ts @@ -122,6 +122,18 @@ const enSentences = { approvalSlaBreachedBody: 'A decision on {{object}} {{record}} is overdue.', approvalStatusMirrorRefusedTitle: 'Approval status not written', approvalStatusMirrorRefusedBody: 'The approval status of {{object}} {{record}} was refused by a rule or hook of the app: {{reason}} Change that rule or hook so the status can be written.', + approvalOpeningRefusedLead: 'The approval of {{object}} {{record}} was not started: the object closes on its approval field, and the approval cannot show itself in progress there.', + approvalOpeningNoPendingOption: 'Field {{field}} of {{object}} (step {{step}} of flow {{flow}}) does not declare the value pending; add it to the field\'s options.', + approvalOpeningClosesInFlight: '{{object}} closes on {{value}} of field {{field}} (step {{step}} of flow {{flow}}), a status of an approval in progress; remove {{value}} from the object\'s closedStates.', + approvalOpeningStateMachine: 'The state_machine rule {{rule}} on field {{field}} of {{object}} (step {{step}} of flow {{flow}}) declares the moves out of {{value}} without pending; add pending to them.', + approvalOpeningReadonlyWhen: 'Field {{field}} of {{object}} (step {{step}} of flow {{flow}}) carries a readonlyWhen; remove it.', + approvalOpeningOptionVisibleWhen: 'The option {{value}} of field {{field}} of {{object}} (step {{step}} of flow {{flow}}) carries a visibleWhen; remove it.', + approvalOpeningOtherField: 'Step {{step}} of flow {{flow}} can act on {{object}} but mirrors onto field {{other}}; every step that can act on {{object}} must mirror onto {{field}}.', + approvalOpeningNoField: 'Step {{step}} of flow {{flow}} can act on {{object}} but names no approval status field; every step that can act on {{object}} must mirror onto {{field}}.', + approvalOpeningPause: 'Node {{node}} ({{type}}) of flow {{flow}} can pause the run between two approval steps of {{object}}; move it before the first step or after the last.', + approvalOpeningMapApproval: 'The map node {{node}} of flow {{flow}} runs an approval step for each item, and the node does not show that no item is a record; an approval of another record would hold {{object}} between two steps.', + approvalOpeningUnreadableFlow: 'Flow {{flow}}, which the approval runs, could not be read, so the approval cannot be checked.', + approvalOpeningNoJobService: '{{object}} declares closedStates, and this host runs no job service, so nothing would end an approval nobody finishes; install a job service.', approvalSlaBreachedSubmitterTitle: 'Your approval request breached its SLA', approvalSlaBreachedSubmitterBody: "{{object}} {{record}}: escalation action '{{action}}' was taken.", approvalApprovedTitle: 'Request approved', @@ -257,6 +269,18 @@ export const zhCNMessages: ApprovalMessages = { approvalSlaBreachedBody: '{{object}} {{record}} 的审批决定已逾期。', approvalStatusMirrorRefusedTitle: '审批状态未能写入', approvalStatusMirrorRefusedBody: '{{object}} {{record}} 的审批状态被应用自己的规则或钩子拒绝:{{reason}} 请修改该规则或钩子,使状态可以写入。', + approvalOpeningRefusedLead: '{{object}} {{record}} 的审批没有发起:该对象会在审批字段上关闭,而这次审批无法在该字段上显示「审批中」。', + approvalOpeningNoPendingOption: '{{object}} 的字段 {{field}}(流程 {{flow}} 的步骤 {{step}})没有声明值 pending;请把它加入该字段的选项。', + approvalOpeningClosesInFlight: '{{object}} 在字段 {{field}} 的 {{value}} 上关闭(流程 {{flow}} 的步骤 {{step}}),而这是审批进行中的状态;请把 {{value}} 从对象的 closedStates 中去掉。', + approvalOpeningStateMachine: '{{object}} 字段 {{field}} 上的 state_machine 规则 {{rule}}(流程 {{flow}} 的步骤 {{step}})声明了从 {{value}} 出发的转移,但其中没有 pending;请加上 pending。', + approvalOpeningReadonlyWhen: '{{object}} 的字段 {{field}}(流程 {{flow}} 的步骤 {{step}})带有 readonlyWhen;请去掉它。', + approvalOpeningOptionVisibleWhen: '{{object}} 字段 {{field}} 的选项 {{value}}(流程 {{flow}} 的步骤 {{step}})带有 visibleWhen;请去掉它。', + approvalOpeningOtherField: '流程 {{flow}} 的步骤 {{step}} 可以作用于 {{object}},却把状态写到字段 {{other}};凡是能作用于 {{object}} 的步骤都必须写到 {{field}}。', + approvalOpeningNoField: '流程 {{flow}} 的步骤 {{step}} 可以作用于 {{object}},却没有指定审批状态字段;凡是能作用于 {{object}} 的步骤都必须写到 {{field}}。', + approvalOpeningPause: '流程 {{flow}} 的节点 {{node}}({{type}})可能在 {{object}} 的两个审批步骤之间暂停运行;请把它移到第一步之前或最后一步之后。', + approvalOpeningMapApproval: '流程 {{flow}} 的 map 节点 {{node}} 为每一项运行一个审批步骤,而该节点无法表明所有项都不是记录;另一条记录的审批会让 {{object}} 停在两个步骤之间。', + approvalOpeningUnreadableFlow: '审批要运行的流程 {{flow}} 无法读取,因此无法检查这次审批。', + approvalOpeningNoJobService: '{{object}} 声明了 closedStates,而本宿主没有运行 job 服务,没人完成的审批将无法结束;请安装 job 服务。', approvalSlaBreachedSubmitterTitle: '您的审批请求已超出时限', approvalSlaBreachedSubmitterBody: '{{object}} {{record}}:已执行升级操作「{{action}}」。', approvalApprovedTitle: '请求已批准', @@ -329,6 +353,18 @@ export const jaJPMessages: ApprovalMessages = { approvalSlaBreachedBody: '{{object}} {{record}} の承認判断が期限を過ぎています。', approvalStatusMirrorRefusedTitle: '承認ステータスを書き込めませんでした', approvalStatusMirrorRefusedBody: '{{object}} {{record}} の承認ステータスは、アプリのルールまたはフックに拒否されました:{{reason}} ステータスを書き込めるよう、そのルールまたはフックを変更してください。', + approvalOpeningRefusedLead: '{{object}} {{record}} の承認は開始されませんでした:このオブジェクトは承認フィールドでクローズしますが、この承認はそのフィールドに承認中を表示できません。', + approvalOpeningNoPendingOption: '{{object}} のフィールド {{field}}(フロー {{flow}} のステップ {{step}})は値 pending を宣言していません。フィールドの選択肢に追加してください。', + approvalOpeningClosesInFlight: '{{object}} はフィールド {{field}} の {{value}} でクローズします(フロー {{flow}} のステップ {{step}})。これは進行中の承認のステータスです。{{value}} をオブジェクトの closedStates から外してください。', + approvalOpeningStateMachine: '{{object}} のフィールド {{field}} にある state_machine ルール {{rule}}(フロー {{flow}} のステップ {{step}})は {{value}} からの遷移を宣言していますが、pending が含まれていません。pending を追加してください。', + approvalOpeningReadonlyWhen: '{{object}} のフィールド {{field}}(フロー {{flow}} のステップ {{step}})に readonlyWhen があります。削除してください。', + approvalOpeningOptionVisibleWhen: '{{object}} のフィールド {{field}} の選択肢 {{value}}(フロー {{flow}} のステップ {{step}})に visibleWhen があります。削除してください。', + approvalOpeningOtherField: 'フロー {{flow}} のステップ {{step}} は {{object}} に作用できますが、フィールド {{other}} にステータスを書き込みます。{{object}} に作用できるすべてのステップは {{field}} に書き込む必要があります。', + approvalOpeningNoField: 'フロー {{flow}} のステップ {{step}} は {{object}} に作用できますが、承認ステータスフィールドを指定していません。{{object}} に作用できるすべてのステップは {{field}} に書き込む必要があります。', + approvalOpeningPause: 'フロー {{flow}} のノード {{node}}({{type}})は {{object}} の二つの承認ステップの間で実行を一時停止する可能性があります。最初のステップの前か最後のステップの後に移動してください。', + approvalOpeningMapApproval: 'フロー {{flow}} の map ノード {{node}} は項目ごとに承認ステップを実行しますが、どの項目もレコードでないことをノードが示していません。別のレコードの承認により {{object}} が二つのステップの間で保留されます。', + approvalOpeningUnreadableFlow: '承認が実行するフロー {{flow}} を読み取れなかったため、承認を確認できません。', + approvalOpeningNoJobService: '{{object}} は closedStates を宣言していますが、このホストでは job サービスが動いていないため、誰も完了しない承認を終わらせるものがありません。job サービスをインストールしてください。', approvalSlaBreachedSubmitterTitle: 'あなたの承認申請が期限を超過しました', approvalSlaBreachedSubmitterBody: '{{object}} {{record}}:エスカレーション操作「{{action}}」が実行されました。', approvalApprovedTitle: '申請が承認されました', @@ -401,6 +437,18 @@ export const esESMessages: ApprovalMessages = { approvalSlaBreachedBody: 'La decisión sobre {{object}} {{record}} está vencida.', approvalStatusMirrorRefusedTitle: 'No se escribió el estado de aprobación', approvalStatusMirrorRefusedBody: 'Una regla o un hook de la aplicación rechazó el estado de aprobación de {{object}} {{record}}: {{reason}} Cambie esa regla o ese hook para que el estado pueda escribirse.', + approvalOpeningRefusedLead: 'No se inició la aprobación de {{object}} {{record}}: el objeto se cierra en su campo de aprobación y la aprobación no puede mostrarse en curso en él.', + approvalOpeningNoPendingOption: 'El campo {{field}} de {{object}} (paso {{step}} del flujo {{flow}}) no declara el valor pending; añádalo a las opciones del campo.', + approvalOpeningClosesInFlight: '{{object}} se cierra en {{value}} del campo {{field}} (paso {{step}} del flujo {{flow}}), un estado de una aprobación en curso; quite {{value}} de los closedStates del objeto.', + approvalOpeningStateMachine: 'La regla state_machine {{rule}} del campo {{field}} de {{object}} (paso {{step}} del flujo {{flow}}) declara las transiciones desde {{value}} sin pending; añada pending.', + approvalOpeningReadonlyWhen: 'El campo {{field}} de {{object}} (paso {{step}} del flujo {{flow}}) tiene un readonlyWhen; quítelo.', + approvalOpeningOptionVisibleWhen: 'La opción {{value}} del campo {{field}} de {{object}} (paso {{step}} del flujo {{flow}}) tiene un visibleWhen; quítelo.', + approvalOpeningOtherField: 'El paso {{step}} del flujo {{flow}} puede actuar sobre {{object}} pero escribe en el campo {{other}}; todo paso que pueda actuar sobre {{object}} debe escribir en {{field}}.', + approvalOpeningNoField: 'El paso {{step}} del flujo {{flow}} puede actuar sobre {{object}} pero no nombra ningún campo de estado de aprobación; todo paso que pueda actuar sobre {{object}} debe escribir en {{field}}.', + approvalOpeningPause: 'El nodo {{node}} ({{type}}) del flujo {{flow}} puede pausar la ejecución entre dos pasos de aprobación de {{object}}; muévalo antes del primer paso o después del último.', + approvalOpeningMapApproval: 'El nodo map {{node}} del flujo {{flow}} ejecuta un paso de aprobación por cada elemento, y el nodo no muestra que ningún elemento sea un registro; la aprobación de otro registro retendría {{object}} entre dos pasos.', + approvalOpeningUnreadableFlow: 'No se pudo leer el flujo {{flow}}, que la aprobación ejecuta, así que no se puede comprobar la aprobación.', + approvalOpeningNoJobService: '{{object}} declara closedStates y este host no ejecuta ningún servicio job, así que nada terminaría una aprobación que nadie complete; instale un servicio job.', approvalSlaBreachedSubmitterTitle: 'Su solicitud de aprobación ha superado su plazo', approvalSlaBreachedSubmitterBody: "{{object}} {{record}}: se ha ejecutado la acción de escalado '{{action}}'.", approvalApprovedTitle: 'Solicitud aprobada', @@ -473,6 +521,18 @@ export const zhHantMessages: ApprovalMessages = { approvalSlaBreachedBody: '{{object}} {{record}} 的核准決定已逾期。', approvalStatusMirrorRefusedTitle: '核准狀態未能寫入', approvalStatusMirrorRefusedBody: '{{object}} {{record}} 的核准狀態被應用程式自己的規則或掛鉤拒絕:{{reason}} 請修改該規則或掛鉤,讓狀態可以寫入。', + approvalOpeningRefusedLead: '{{object}} {{record}} 的核准沒有發起:該物件會在核准欄位上關閉,而這次核准無法在該欄位上顯示「核准中」。', + approvalOpeningNoPendingOption: '{{object}} 的欄位 {{field}}(流程 {{flow}} 的步驟 {{step}})沒有宣告值 pending;請把它加入該欄位的選項。', + approvalOpeningClosesInFlight: '{{object}} 在欄位 {{field}} 的 {{value}} 上關閉(流程 {{flow}} 的步驟 {{step}}),而這是核准進行中的狀態;請把 {{value}} 從物件的 closedStates 中移除。', + approvalOpeningStateMachine: '{{object}} 欄位 {{field}} 上的 state_machine 規則 {{rule}}(流程 {{flow}} 的步驟 {{step}})宣告了從 {{value}} 出發的轉移,但其中沒有 pending;請加上 pending。', + approvalOpeningReadonlyWhen: '{{object}} 的欄位 {{field}}(流程 {{flow}} 的步驟 {{step}})帶有 readonlyWhen;請移除它。', + approvalOpeningOptionVisibleWhen: '{{object}} 欄位 {{field}} 的選項 {{value}}(流程 {{flow}} 的步驟 {{step}})帶有 visibleWhen;請移除它。', + approvalOpeningOtherField: '流程 {{flow}} 的步驟 {{step}} 可以作用於 {{object}},卻把狀態寫到欄位 {{other}};凡是能作用於 {{object}} 的步驟都必須寫到 {{field}}。', + approvalOpeningNoField: '流程 {{flow}} 的步驟 {{step}} 可以作用於 {{object}},卻沒有指定核准狀態欄位;凡是能作用於 {{object}} 的步驟都必須寫到 {{field}}。', + approvalOpeningPause: '流程 {{flow}} 的節點 {{node}}({{type}})可能在 {{object}} 的兩個核准步驟之間暫停執行;請把它移到第一步之前或最後一步之後。', + approvalOpeningMapApproval: '流程 {{flow}} 的 map 節點 {{node}} 為每一項執行一個核准步驟,而該節點無法表明所有項目都不是記錄;另一筆記錄的核准會讓 {{object}} 停在兩個步驟之間。', + approvalOpeningUnreadableFlow: '核准要執行的流程 {{flow}} 無法讀取,因此無法檢查這次核准。', + approvalOpeningNoJobService: '{{object}} 宣告了 closedStates,而本主機沒有執行 job 服務,沒有人完成的核准將無法結束;請安裝 job 服務。', approvalSlaBreachedSubmitterTitle: '你的核准請求已逾時', approvalSlaBreachedSubmitterBody: '{{object}} {{record}}:已執行升級動作「{{action}}」。', approvalApprovedTitle: '請求已核准', @@ -545,6 +605,18 @@ export const arMessages: ApprovalMessages = { approvalSlaBreachedBody: 'القرار بشأن {{object}} {{record}} متأخر.', approvalStatusMirrorRefusedTitle: 'لم تُكتب حالة الموافقة', approvalStatusMirrorRefusedBody: 'رفضت قاعدة أو خطّاف في التطبيق حالة الموافقة على {{object}} {{record}}: {{reason}} غيّر تلك القاعدة أو ذلك الخطّاف لكي تُكتب الحالة.', + approvalOpeningRefusedLead: 'لم تبدأ الموافقة على {{object}} {{record}}: الكائن يُغلَق على حقل الموافقة، والموافقة لا تستطيع أن تُظهر فيه أنها جارية.', + approvalOpeningNoPendingOption: 'الحقل {{field}} في {{object}} (الخطوة {{step}} من التدفق {{flow}}) لا يصرّح بالقيمة pending؛ أضفها إلى خيارات الحقل.', + approvalOpeningClosesInFlight: 'يُغلَق {{object}} على القيمة {{value}} من الحقل {{field}} (الخطوة {{step}} من التدفق {{flow}})، وهي حالة موافقة جارية؛ أزل {{value}} من closedStates للكائن.', + approvalOpeningStateMachine: 'قاعدة state_machine {{rule}} على الحقل {{field}} في {{object}} (الخطوة {{step}} من التدفق {{flow}}) تصرّح بالانتقالات من {{value}} دون pending؛ أضف pending.', + approvalOpeningReadonlyWhen: 'الحقل {{field}} في {{object}} (الخطوة {{step}} من التدفق {{flow}}) يحمل readonlyWhen؛ أزله.', + approvalOpeningOptionVisibleWhen: 'الخيار {{value}} من الحقل {{field}} في {{object}} (الخطوة {{step}} من التدفق {{flow}}) يحمل visibleWhen؛ أزله.', + approvalOpeningOtherField: 'الخطوة {{step}} من التدفق {{flow}} يمكنها أن تعمل على {{object}} لكنها تكتب الحالة في الحقل {{other}}؛ يجب أن تكتب كل خطوة يمكنها العمل على {{object}} في {{field}}.', + approvalOpeningNoField: 'الخطوة {{step}} من التدفق {{flow}} يمكنها أن تعمل على {{object}} لكنها لا تسمّي حقلًا لحالة الموافقة؛ يجب أن تكتب كل خطوة يمكنها العمل على {{object}} في {{field}}.', + approvalOpeningPause: 'العقدة {{node}} ({{type}}) في التدفق {{flow}} قد توقف التشغيل مؤقتًا بين خطوتَي موافقة على {{object}}؛ انقلها قبل الخطوة الأولى أو بعد الأخيرة.', + approvalOpeningMapApproval: 'عقدة map {{node}} في التدفق {{flow}} تشغّل خطوة موافقة لكل عنصر، والعقدة لا تُظهر أن أي عنصر ليس سجلًا؛ موافقة سجل آخر ستحتجز {{object}} بين خطوتين.', + approvalOpeningUnreadableFlow: 'تعذّرت قراءة التدفق {{flow}} الذي تشغّله الموافقة، لذا لا يمكن فحص الموافقة.', + approvalOpeningNoJobService: 'يصرّح {{object}} بـ closedStates، وهذا المضيف لا يشغّل خدمة job، فلا شيء سينهي موافقة لا يكملها أحد؛ ثبّت خدمة job.', approvalSlaBreachedSubmitterTitle: 'تجاوز طلب الموافقة الخاص بك مهلته', approvalSlaBreachedSubmitterBody: '{{object}} {{record}}: نُفِّذ إجراء التصعيد «{{action}}».', approvalApprovedTitle: 'تمت الموافقة على الطلب', @@ -617,6 +689,18 @@ export const frMessages: ApprovalMessages = { approvalSlaBreachedBody: 'La décision sur {{object}} {{record}} est en retard.', approvalStatusMirrorRefusedTitle: 'Statut d’approbation non écrit', approvalStatusMirrorRefusedBody: 'Une règle ou un hook de l’application a refusé le statut d’approbation de {{object}} {{record}} : {{reason}} Modifiez cette règle ou ce hook pour que le statut puisse être écrit.', + approvalOpeningRefusedLead: 'L\'approbation de {{object}} {{record}} n\'a pas été lancée : l\'objet se ferme sur son champ d\'approbation, et l\'approbation ne peut pas s\'y afficher en cours.', + approvalOpeningNoPendingOption: 'Le champ {{field}} de {{object}} (étape {{step}} du flux {{flow}}) ne déclare pas la valeur pending ; ajoutez-la aux options du champ.', + approvalOpeningClosesInFlight: '{{object}} se ferme sur {{value}} du champ {{field}} (étape {{step}} du flux {{flow}}), un statut d\'approbation en cours ; retirez {{value}} des closedStates de l\'objet.', + approvalOpeningStateMachine: 'La règle state_machine {{rule}} du champ {{field}} de {{object}} (étape {{step}} du flux {{flow}}) déclare les transitions depuis {{value}} sans pending ; ajoutez pending.', + approvalOpeningReadonlyWhen: 'Le champ {{field}} de {{object}} (étape {{step}} du flux {{flow}}) porte un readonlyWhen ; retirez-le.', + approvalOpeningOptionVisibleWhen: 'L\'option {{value}} du champ {{field}} de {{object}} (étape {{step}} du flux {{flow}}) porte un visibleWhen ; retirez-le.', + approvalOpeningOtherField: 'L\'étape {{step}} du flux {{flow}} peut agir sur {{object}} mais écrit dans le champ {{other}} ; toute étape qui peut agir sur {{object}} doit écrire dans {{field}}.', + approvalOpeningNoField: 'L\'étape {{step}} du flux {{flow}} peut agir sur {{object}} mais ne nomme aucun champ de statut d\'approbation ; toute étape qui peut agir sur {{object}} doit écrire dans {{field}}.', + approvalOpeningPause: 'Le nœud {{node}} ({{type}}) du flux {{flow}} peut mettre l\'exécution en pause entre deux étapes d\'approbation de {{object}} ; placez-le avant la première étape ou après la dernière.', + approvalOpeningMapApproval: 'Le nœud map {{node}} du flux {{flow}} exécute une étape d\'approbation pour chaque élément, et le nœud ne montre pas qu\'aucun élément n\'est un enregistrement ; l\'approbation d\'un autre enregistrement retiendrait {{object}} entre deux étapes.', + approvalOpeningUnreadableFlow: 'Le flux {{flow}}, que l\'approbation exécute, n\'a pas pu être lu ; l\'approbation ne peut donc pas être vérifiée.', + approvalOpeningNoJobService: '{{object}} déclare closedStates et cet hôte n\'exécute aucun service job : rien ne terminerait une approbation que personne n\'achève ; installez un service job.', approvalSlaBreachedSubmitterTitle: 'Votre demande d’approbation a dépassé son délai', approvalSlaBreachedSubmitterBody: '{{object}} {{record}} : l’action d’escalade « {{action}} » a été exécutée.', approvalApprovedTitle: 'Demande approuvée', @@ -689,6 +773,18 @@ export const ptBRMessages: ApprovalMessages = { approvalSlaBreachedBody: 'A decisão sobre {{object}} {{record}} está atrasada.', approvalStatusMirrorRefusedTitle: 'Status de aprovação não gravado', approvalStatusMirrorRefusedBody: 'Uma regra ou um hook do aplicativo recusou o status de aprovação de {{object}} {{record}}: {{reason}} Altere essa regra ou esse hook para que o status possa ser gravado.', + approvalOpeningRefusedLead: 'A aprovação de {{object}} {{record}} não foi iniciada: o objeto é fechado no seu campo de aprovação, e a aprovação não consegue se mostrar em andamento nele.', + approvalOpeningNoPendingOption: 'O campo {{field}} de {{object}} (etapa {{step}} do fluxo {{flow}}) não declara o valor pending; adicione-o às opções do campo.', + approvalOpeningClosesInFlight: '{{object}} é fechado em {{value}} do campo {{field}} (etapa {{step}} do fluxo {{flow}}), um status de aprovação em andamento; remova {{value}} dos closedStates do objeto.', + approvalOpeningStateMachine: 'A regra state_machine {{rule}} no campo {{field}} de {{object}} (etapa {{step}} do fluxo {{flow}}) declara as transições a partir de {{value}} sem pending; adicione pending.', + approvalOpeningReadonlyWhen: 'O campo {{field}} de {{object}} (etapa {{step}} do fluxo {{flow}}) tem um readonlyWhen; remova-o.', + approvalOpeningOptionVisibleWhen: 'A opção {{value}} do campo {{field}} de {{object}} (etapa {{step}} do fluxo {{flow}}) tem um visibleWhen; remova-o.', + approvalOpeningOtherField: 'A etapa {{step}} do fluxo {{flow}} pode agir sobre {{object}}, mas grava no campo {{other}}; toda etapa que pode agir sobre {{object}} deve gravar em {{field}}.', + approvalOpeningNoField: 'A etapa {{step}} do fluxo {{flow}} pode agir sobre {{object}}, mas não indica nenhum campo de status de aprovação; toda etapa que pode agir sobre {{object}} deve gravar em {{field}}.', + approvalOpeningPause: 'O nó {{node}} ({{type}}) do fluxo {{flow}} pode pausar a execução entre duas etapas de aprovação de {{object}}; mova-o para antes da primeira etapa ou depois da última.', + approvalOpeningMapApproval: 'O nó map {{node}} do fluxo {{flow}} executa uma etapa de aprovação para cada item, e o nó não mostra que nenhum item é um registro; a aprovação de outro registro reteria {{object}} entre duas etapas.', + approvalOpeningUnreadableFlow: 'O fluxo {{flow}}, que a aprovação executa, não pôde ser lido, então a aprovação não pode ser verificada.', + approvalOpeningNoJobService: '{{object}} declara closedStates e este host não executa nenhum serviço job, então nada encerraria uma aprovação que ninguém conclua; instale um serviço job.', approvalSlaBreachedSubmitterTitle: 'Sua solicitação de aprovação estourou o prazo', approvalSlaBreachedSubmitterBody: '{{object}} {{record}}: a ação de escalonamento "{{action}}" foi executada.', approvalApprovedTitle: 'Solicitação aprovada', @@ -761,6 +857,18 @@ export const ruMessages: ApprovalMessages = { approvalSlaBreachedBody: 'Решение по {{object}} {{record}} просрочено.', approvalStatusMirrorRefusedTitle: 'Статус согласования не записан', approvalStatusMirrorRefusedBody: 'Правило или хук приложения отклонили статус согласования для {{object}} {{record}}: {{reason}} Измените это правило или хук, чтобы статус можно было записать.', + approvalOpeningRefusedLead: 'Согласование {{object}} {{record}} не запущено: объект закрывается по своему полю согласования, а согласование не может показать в нём, что оно идёт.', + approvalOpeningNoPendingOption: 'Поле {{field}} объекта {{object}} (шаг {{step}} процесса {{flow}}) не объявляет значение pending; добавьте его в варианты поля.', + approvalOpeningClosesInFlight: '{{object}} закрывается на значении {{value}} поля {{field}} (шаг {{step}} процесса {{flow}}), а это статус идущего согласования; уберите {{value}} из closedStates объекта.', + approvalOpeningStateMachine: 'Правило state_machine {{rule}} на поле {{field}} объекта {{object}} (шаг {{step}} процесса {{flow}}) объявляет переходы из {{value}} без pending; добавьте pending.', + approvalOpeningReadonlyWhen: 'Поле {{field}} объекта {{object}} (шаг {{step}} процесса {{flow}}) имеет readonlyWhen; уберите его.', + approvalOpeningOptionVisibleWhen: 'Вариант {{value}} поля {{field}} объекта {{object}} (шаг {{step}} процесса {{flow}}) имеет visibleWhen; уберите его.', + approvalOpeningOtherField: 'Шаг {{step}} процесса {{flow}} может действовать на {{object}}, но записывает статус в поле {{other}}; каждый шаг, который может действовать на {{object}}, должен записывать в {{field}}.', + approvalOpeningNoField: 'Шаг {{step}} процесса {{flow}} может действовать на {{object}}, но не называет поле статуса согласования; каждый шаг, который может действовать на {{object}}, должен записывать в {{field}}.', + approvalOpeningPause: 'Узел {{node}} ({{type}}) процесса {{flow}} может приостановить выполнение между двумя шагами согласования {{object}}; перенесите его до первого шага или после последнего.', + approvalOpeningMapApproval: 'Узел map {{node}} процесса {{flow}} запускает шаг согласования для каждого элемента, и узел не показывает, что ни один элемент не является записью; согласование другой записи задержит {{object}} между двумя шагами.', + approvalOpeningUnreadableFlow: 'Не удалось прочитать процесс {{flow}}, который запускает согласование, поэтому согласование нельзя проверить.', + approvalOpeningNoJobService: '{{object}} объявляет closedStates, а на этом хосте не работает служба job, поэтому согласование, которое никто не завершит, ничто не закончит; установите службу job.', approvalSlaBreachedSubmitterTitle: 'Ваш запрос на согласование нарушил срок', approvalSlaBreachedSubmitterBody: '{{object}} {{record}}: выполнено действие эскалации «{{action}}».', approvalApprovedTitle: 'Запрос одобрен', @@ -833,6 +941,18 @@ export const deMessages: ApprovalMessages = { approvalSlaBreachedBody: 'Die Entscheidung zu {{object}} {{record}} ist überfällig.', approvalStatusMirrorRefusedTitle: 'Genehmigungsstatus nicht geschrieben', approvalStatusMirrorRefusedBody: 'Eine Regel oder ein Hook der App hat den Genehmigungsstatus von {{object}} {{record}} abgelehnt: {{reason}} Ändern Sie diese Regel oder diesen Hook, damit der Status geschrieben werden kann.', + approvalOpeningRefusedLead: 'Die Genehmigung von {{object}} {{record}} wurde nicht gestartet: Das Objekt schließt auf seinem Genehmigungsfeld, und die Genehmigung kann sich dort nicht als laufend zeigen.', + approvalOpeningNoPendingOption: 'Das Feld {{field}} von {{object}} (Schritt {{step}} des Flows {{flow}}) deklariert den Wert pending nicht; fügen Sie ihn den Optionen des Feldes hinzu.', + approvalOpeningClosesInFlight: '{{object}} schließt auf {{value}} des Feldes {{field}} (Schritt {{step}} des Flows {{flow}}), einem Status einer laufenden Genehmigung; entfernen Sie {{value}} aus den closedStates des Objekts.', + approvalOpeningStateMachine: 'Die state_machine-Regel {{rule}} auf dem Feld {{field}} von {{object}} (Schritt {{step}} des Flows {{flow}}) deklariert die Übergänge aus {{value}} ohne pending; fügen Sie pending hinzu.', + approvalOpeningReadonlyWhen: 'Das Feld {{field}} von {{object}} (Schritt {{step}} des Flows {{flow}}) trägt ein readonlyWhen; entfernen Sie es.', + approvalOpeningOptionVisibleWhen: 'Die Option {{value}} des Feldes {{field}} von {{object}} (Schritt {{step}} des Flows {{flow}}) trägt ein visibleWhen; entfernen Sie es.', + approvalOpeningOtherField: 'Schritt {{step}} des Flows {{flow}} kann auf {{object}} wirken, schreibt aber in das Feld {{other}}; jeder Schritt, der auf {{object}} wirken kann, muss in {{field}} schreiben.', + approvalOpeningNoField: 'Schritt {{step}} des Flows {{flow}} kann auf {{object}} wirken, nennt aber kein Genehmigungsstatusfeld; jeder Schritt, der auf {{object}} wirken kann, muss in {{field}} schreiben.', + approvalOpeningPause: 'Der Knoten {{node}} ({{type}}) des Flows {{flow}} kann den Lauf zwischen zwei Genehmigungsschritten von {{object}} anhalten; verschieben Sie ihn vor den ersten oder hinter den letzten Schritt.', + approvalOpeningMapApproval: 'Der map-Knoten {{node}} des Flows {{flow}} führt für jedes Element einen Genehmigungsschritt aus, und der Knoten zeigt nicht, dass kein Element ein Datensatz ist; die Genehmigung eines anderen Datensatzes würde {{object}} zwischen zwei Schritten festhalten.', + approvalOpeningUnreadableFlow: 'Der Flow {{flow}}, den die Genehmigung ausführt, konnte nicht gelesen werden, daher kann die Genehmigung nicht geprüft werden.', + approvalOpeningNoJobService: '{{object}} deklariert closedStates, und dieser Host betreibt keinen job-Dienst, sodass nichts eine Genehmigung beenden würde, die niemand abschließt; installieren Sie einen job-Dienst.', approvalSlaBreachedSubmitterTitle: 'Ihre Genehmigungsanfrage hat ihre Frist überschritten', approvalSlaBreachedSubmitterBody: '{{object}} {{record}}: Die Eskalationsaktion „{{action}}“ wurde ausgeführt.', approvalApprovedTitle: 'Anfrage genehmigt', @@ -905,6 +1025,18 @@ export const koMessages: ApprovalMessages = { approvalSlaBreachedBody: '{{object}} {{record}}에 대한 결정이 기한을 넘겼습니다.', approvalStatusMirrorRefusedTitle: '승인 상태를 기록하지 못했습니다', approvalStatusMirrorRefusedBody: '앱의 규칙 또는 훅이 {{object}} {{record}}의 승인 상태를 거부했습니다: {{reason}} 상태를 기록할 수 있도록 해당 규칙 또는 훅을 변경하세요.', + approvalOpeningRefusedLead: '{{object}} {{record}}의 승인이 시작되지 않았습니다: 이 개체는 승인 필드에서 닫히는데, 이 승인은 그 필드에 진행 중임을 표시할 수 없습니다.', + approvalOpeningNoPendingOption: '{{object}}의 필드 {{field}}(흐름 {{flow}}의 단계 {{step}})는 값 pending을 선언하지 않습니다. 필드의 옵션에 추가하세요.', + approvalOpeningClosesInFlight: '{{object}}는 필드 {{field}}의 {{value}}에서 닫힙니다(흐름 {{flow}}의 단계 {{step}}). 이는 진행 중인 승인의 상태입니다. 개체의 closedStates에서 {{value}}를 제거하세요.', + approvalOpeningStateMachine: '{{object}}의 필드 {{field}}에 있는 state_machine 규칙 {{rule}}(흐름 {{flow}}의 단계 {{step}})은 {{value}}에서 나가는 전이를 선언하지만 pending이 없습니다. pending을 추가하세요.', + approvalOpeningReadonlyWhen: '{{object}}의 필드 {{field}}(흐름 {{flow}}의 단계 {{step}})에 readonlyWhen이 있습니다. 제거하세요.', + approvalOpeningOptionVisibleWhen: '{{object}}의 필드 {{field}}의 옵션 {{value}}(흐름 {{flow}}의 단계 {{step}})에 visibleWhen이 있습니다. 제거하세요.', + approvalOpeningOtherField: '흐름 {{flow}}의 단계 {{step}}는 {{object}}에 작용할 수 있지만 필드 {{other}}에 상태를 기록합니다. {{object}}에 작용할 수 있는 모든 단계는 {{field}}에 기록해야 합니다.', + approvalOpeningNoField: '흐름 {{flow}}의 단계 {{step}}는 {{object}}에 작용할 수 있지만 승인 상태 필드를 지정하지 않습니다. {{object}}에 작용할 수 있는 모든 단계는 {{field}}에 기록해야 합니다.', + approvalOpeningPause: '흐름 {{flow}}의 노드 {{node}}({{type}})는 {{object}}의 두 승인 단계 사이에서 실행을 일시 중지할 수 있습니다. 첫 단계 앞이나 마지막 단계 뒤로 옮기세요.', + approvalOpeningMapApproval: '흐름 {{flow}}의 map 노드 {{node}}는 항목마다 승인 단계를 실행하며, 노드는 어떤 항목도 레코드가 아님을 보여 주지 않습니다. 다른 레코드의 승인이 {{object}}를 두 단계 사이에 붙잡아 둘 수 있습니다.', + approvalOpeningUnreadableFlow: '승인이 실행하는 흐름 {{flow}}을 읽을 수 없어 승인을 확인할 수 없습니다.', + approvalOpeningNoJobService: '{{object}}는 closedStates를 선언하지만 이 호스트는 job 서비스를 실행하지 않아, 아무도 끝내지 않는 승인을 종료할 수단이 없습니다. job 서비스를 설치하세요.', approvalSlaBreachedSubmitterTitle: '승인 요청이 기한을 넘겼습니다', approvalSlaBreachedSubmitterBody: "{{object}} {{record}}: 에스컬레이션 작업 '{{action}}'이(가) 실행되었습니다.", approvalApprovedTitle: '요청 승인됨', diff --git a/packages/plugins/plugin-approvals/src/translations/pt-BR.objects.generated.ts b/packages/plugins/plugin-approvals/src/translations/pt-BR.objects.generated.ts index c2b46cb3ee0..085246ac1d1 100644 --- a/packages/plugins/plugin-approvals/src/translations/pt-BR.objects.generated.ts +++ b/packages/plugins/plugin-approvals/src/translations/pt-BR.objects.generated.ts @@ -117,6 +117,10 @@ export const ptBRObjects: NonNullable = { label: "Execução do registro", help: "Execução de automação que carrega o registro desta solicitação." }, + between_steps_json: { + label: "Entre etapas", + help: "Nós do fluxo que ficam entre duas etapas da aprovação à qual esta solicitação pertence." + }, node_config_json: { label: "Configuração do nó", help: "Instantâneo da configuração do nó de aprovação (aprovadores/comportamento) para solicitações conduzidas por nó." diff --git a/packages/plugins/plugin-approvals/src/translations/ru.objects.generated.ts b/packages/plugins/plugin-approvals/src/translations/ru.objects.generated.ts index b6cabc06994..d8bcf649534 100644 --- a/packages/plugins/plugin-approvals/src/translations/ru.objects.generated.ts +++ b/packages/plugins/plugin-approvals/src/translations/ru.objects.generated.ts @@ -117,6 +117,10 @@ export const ruObjects: NonNullable = { label: "Запуск записи", help: "Запуск автоматизации, который несёт запись этого запроса." }, + between_steps_json: { + label: "Между шагами", + help: "Узлы потока, стоящие между двумя шагами согласования, к которому относится этот запрос." + }, node_config_json: { label: "Конфигурация узла", help: "Снимок конфигурации узла согласования (согласующие/поведение) для запросов, запускаемых узлом." diff --git a/packages/plugins/plugin-approvals/src/translations/zh-CN.objects.generated.ts b/packages/plugins/plugin-approvals/src/translations/zh-CN.objects.generated.ts index 09fdcc49087..ea9abebff29 100644 --- a/packages/plugins/plugin-approvals/src/translations/zh-CN.objects.generated.ts +++ b/packages/plugins/plugin-approvals/src/translations/zh-CN.objects.generated.ts @@ -117,6 +117,10 @@ export const zhCNObjects: NonNullable = { label: "记录运行", help: "承载此请求所在记录的自动化运行。" }, + between_steps_json: { + label: "步骤之间", + help: "审批中位于两个步骤之间的流程节点。" + }, node_config_json: { label: "Node Config", help: "Snapshot of the Approval node config (approvers/behavior) for node-driven requests." diff --git a/packages/plugins/plugin-approvals/src/translations/zh-Hant.objects.generated.ts b/packages/plugins/plugin-approvals/src/translations/zh-Hant.objects.generated.ts index 16384bf84d7..ef80bead5ac 100644 --- a/packages/plugins/plugin-approvals/src/translations/zh-Hant.objects.generated.ts +++ b/packages/plugins/plugin-approvals/src/translations/zh-Hant.objects.generated.ts @@ -117,6 +117,10 @@ export const zhHantObjects: NonNullable = { label: "記錄執行", help: "承載此請求所在記錄的自動化執行。" }, + between_steps_json: { + label: "步驟之間", + help: "審批中位於兩個步驟之間的流程節點。" + }, node_config_json: { label: "節點設定", help: "由節點驅動之請求的核准節點設定(核准人/行為)快照。" From c84dfff49ef07cffde7a510304874735dc4b4ea1 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 06:03:10 +0000 Subject: [PATCH 20/32] test(approvals): the abandoned-mirror arms meet the opening check; the changeset is patch The abandoned-request status-mirror tests (merged from the trunk) now note the plugin's sweeps on their hand-built service, as a host with a job service does, and open the no-pending arm before the object declares closedStates, the case the opening check does not judge. The changeset is graded patch: the metadata protocol is unchanged. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5nzgcVrZ8Neqqd1AFi --- .changeset/37766-opening-check.md | 2 +- ...abandoned-closed-value.integration.test.ts | 23 ++++++++++++++++--- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/.changeset/37766-opening-check.md b/.changeset/37766-opening-check.md index 1a40086ab2c..f2f02cb2a13 100644 --- a/.changeset/37766-opening-check.md +++ b/.changeset/37766-opening-check.md @@ -1,5 +1,5 @@ --- -'@objectstack/plugin-approvals': minor +'@objectstack/plugin-approvals': patch --- feat(approvals): an approval that cannot show itself in progress on a field its object closes on does not open (ADR-0162 Execution item 7, the check) 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 8179524343b..b98b6ed217b 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 @@ -183,6 +183,10 @@ describe('ADR-0162 D5 — an abandoned approval never writes a closed value on i } logger = recordingLogger(); svc = new ApprovalService({ engine: engine as any, logger }); + // [#37766 slice B] The host runs the plugin's sweeps, as one with a `job` + // service does: an approval on a closing object does not open on a host + // that runs none (ADR-0162 item 7), which is not what this file pins. + svc.noteSweepClockScheduled(); automation = new AutomationEngine(silent, new InMemorySuspendedRunStore()); installBuiltinNodes(automation, { logger: silent, getService() { throw new Error('none'); } } as any); registerApprovalNode(automation as any, svc, silent); @@ -426,8 +430,21 @@ describe('ADR-0162 D5 — an abandoned approval never writes a closed value on i // 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", () => { + // [#37766 slice B] The check would refuse this approval at its first + // request (the field declares no `pending`). An approval it did not judge + // is one opened before the object declared `closedStates`: the request + // opens on the object as it stood, and the declaration comes after. + const NO_PENDING = OBJECTS.find((o) => o.name === 'doc_no_pending')!; + const submitBeforeDeclared = async (...args: Parameters) => { + const { closedStates: _later, ...undeclared } = NO_PENDING as typeof NO_PENDING & { closedStates?: unknown }; + engine.registry.registerObject(undeclared as any, 'approvals-test', 'approvals-test'); + try { return await submit(...args); } finally { + engine.registry.registerObject(NO_PENDING as any, 'approvals-test', 'approvals-test'); + } + }; + it('that step in the same run', async () => { - const { id, request } = await submit('doc_no_pending', { atSubmit: 'approved', flow: 'two' }); + const { id, request } = await submitBeforeDeclared('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); @@ -436,7 +453,7 @@ describe('ADR-0162 D5 — an abandoned approval never writes a closed value on i }); it('that step in a child run', async () => { - const { id, request } = await submit('doc_no_pending', { atSubmit: 'draft', flow: 'child_first' }); + const { id, request } = await submitBeforeDeclared('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); @@ -446,7 +463,7 @@ describe('ADR-0162 D5 — an abandoned approval never writes a closed value on i }); 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' }); + const { id, request } = await submitBeforeDeclared('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); From a07507914d63bb699560c705431ec20ee6d69315 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 06:36:32 +0000 Subject: [PATCH 21/32] chore(changeset): the opening check's release text matches the tree Name the optional `locale` member of openNodeRequest's input among the widened surface, and say that an approval one of whose flows cannot be read is refused wherever some object declares closedStates. Prose only. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5nzgcVrZ8Neqqd1AFi --- .changeset/37766-opening-check.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.changeset/37766-opening-check.md b/.changeset/37766-opening-check.md index f2f02cb2a13..ce7e3b7040f 100644 --- a/.changeset/37766-opening-check.md +++ b/.changeset/37766-opening-check.md @@ -7,7 +7,7 @@ feat(approvals): an approval that cannot show itself in progress on a field its Clause-②: yes (widening) Metadata-protocol: none -Widened: `sys_approval_request` gains the engine-written, read-only column `between_steps_json`; `ApprovalService` gains `noteSweepClockScheduled()`; the plugin's message catalog gains twelve `approvalOpening*` sentences in all 11 locale packs. +Widened: `sys_approval_request` gains the engine-written, read-only column `between_steps_json`; `ApprovalService` gains `noteSweepClockScheduled()`, and the input of `ApprovalService.openNodeRequest` gains the optional member `locale` (the run's locale, for the refusal's wording); the plugin's message catalog gains twelve `approvalOpening*` sentences in all 11 locale packs. At an approval's first request the plugin now reads the approval whole: the flow its root run was started on and every flow a `subflow` or a `map` in it names, to any depth. Where a step can act on an object that declares `closedStates`: @@ -16,4 +16,4 @@ At an approval's first request the plugin now reads the approval whole: the flow A refused approval fails its run at the step with `VALIDATION_FAILED` and one sentence per gap naming the flow, the step, the object, the field and what is missing, in the run's locale. No request row is written. -Not judged, and unchanged: an application in which no object declares `closedStates`; an approval whose objects declare none; a request whose run hands no root run; a later request of an approval already open (also one opened before the object declared the key); a request that cannot be placed because an earlier request on the record since its root run started records no root run. A writing node between two steps of a flow that runs as the user is not refused. +Not judged, and unchanged: an application in which no object declares `closedStates`; an approval whose objects declare none, once it has been read whole (in an application where some object declares the key, an approval one of whose flows cannot be read is refused, whatever objects the parts that were read act on, since its objects cannot be known); a request whose run hands no root run; a later request of an approval already open (also one opened before the object declared the key); a request that cannot be placed because an earlier request on the record since its root run started records no root run. A writing node between two steps of a flow that runs as the user is not refused. From 8749c1895d8163df71ad85235e1ed07e2298e565 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 07:27:37 +0000 Subject: [PATCH 22/32] wip(approvals): hold a closing field's decision until the approval is over, and judge it at each door Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5pigknx7rC8rXnA3my --- .../plugin-approvals/src/approval-service.ts | 753 ++++++++++++++++-- .../src/sys-approval-request.object.ts | 17 + .../src/translations/messages.ts | 22 + 3 files changed, 734 insertions(+), 58 deletions(-) diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index 6b0c526b581..5622e1649d7 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -365,8 +365,19 @@ export interface ApprovalResumeSurface { * therefore acts only on an explicit terminal-failure status and treats * `null` — unknown run, evicted log, no durable store, no automation engine — * as "still alive". + * + * [ADR-0162 Execution item 8] Its step log is read too + * (`ExecutionLogEntry.steps`, which the engine already answers): the door + * that judges an approval places where the run stopped, and a failure the + * flow routed, against the set the approval's requests carry. A step inside + * a region names its container (`parentNodeId`). */ - getRun?(runId: string): Promise<{ status?: string; flowName?: string; startedAt?: string } | null>; + getRun?(runId: string): Promise<{ + status?: string; + flowName?: string; + startedAt?: string; + steps?: ReadonlyArray<{ nodeId?: string; nodeType?: string; status?: string; parentNodeId?: string; startedAt?: string }>; + } | null>; /** * Whether a suspension still exists for `runId` — the pre-flight that keeps * a decision from being recorded against a run that can never advance @@ -1839,6 +1850,81 @@ interface MirrorRefusal { */ const REFUSED_MIRROR_TOPIC = 'approval.status_mirror_refused'; +/** + * [ADR-0162 D5, Execution item 8] The topic of the notice the submitter gets + * when the approval of their record ended between two of its steps and the + * plugin put the record back. + */ +const ABANDONED_APPROVAL_TOPIC = 'approval.abandoned'; + +/** + * [ADR-0162 Execution item 8] The keys of a request's config snapshot that the + * judgement of an approval leaves: the approval was abandoned (`__abandoned`), + * and a later step of it could not open (`__laterStepNotOpened`). Internal + * stamps, like `__round`: the snapshot is not authored config. + */ +const ABANDONED_KEY = '__abandoned'; +const LATER_STEP_NOT_OPENED_KEY = '__laterStepNotOpened'; + +/** The run statuses a run reports while it is being advanced, or is about to be. */ +const ADVANCING_RUN_STATUSES: ReadonlySet = new Set(['pending', 'running', 'retrying']); + +/** + * [ADR-0162 Execution item 8] What the door answered for an approval after it + * resumed or cancelled one of its runs (`ApprovalService.judgeApprovalAfterDoor`). + * `unstamped`: the approval was not stamped, and nothing is judged. `judged`: + * no request of it carries the mark, or a writer that recalled its latest + * request already wrote what it leaves. `ended`: it ended between two steps + * and held nothing back, so only the mark was cleared. + */ +type ApprovalJudgement = 'unstamped' | 'judged' | 'in_progress' | 'undetermined' | 'finished' | 'abandoned' | 'ended'; + +/** One node of the between-two-steps set a request carries (`between_steps_json`). */ +interface StampedNode { + readonly flow: string; + readonly node: string; +} + +/** + * [ADR-0162 Execution item 8] The between-two-steps set `row` carries, or + * `undefined` where its approval was not stamped: no step of it can act on an + * object that declares `closedStates`, or the plugin could not place it. An + * empty set (`[]`) is a stamp: such an approval is judged like any other. + */ +function stampOf(row: any): StampedNode[] | undefined { + const raw = row?.between_steps_json; + if (typeof raw !== 'string' || raw === '') return undefined; + const parsed = parseJson(raw, undefined); + if (!Array.isArray(parsed)) return undefined; + return parsed + .filter((n): n is { flow?: unknown; node?: unknown } => !!n && typeof n === 'object') + .map((n) => ({ flow: String(n.flow ?? ''), node: String(n.node ?? '') })) + .filter((n) => n.node !== ''); +} + +/** + * [ADR-0162 Execution item 8] Whether the node `nodeId` of the flow `flow` + * stands in `stamp`. The set names each flow by the key the engine files it + * under; where the run's own flow key is unknown, or names no flow of the set, + * the node is matched by its id alone, which can only read more stops as + * between two steps (a resubmission), never fewer (a closed document on an + * unfinished approval). + */ +function standsBetweenSteps(stamp: readonly StampedNode[], flow: string | undefined, nodeId: string): boolean { + if (flow && stamp.some((n) => n.flow === flow)) return stamp.some((n) => n.flow === flow && n.node === nodeId); + return stamp.some((n) => n.node === nodeId); +} + +/** [ADR-0162 Execution item 8] Whether `row` carries the mark: it was decided, and what follows is not judged yet. */ +function isMarked(row: any): boolean { + return row?.unjudged_since != null && row.unjudged_since !== ''; +} + +/** The timeline line an approval that ended between two steps leaves on its latest request. */ +function abandonedNoteText(why: string, left: string): string { + return `The approval did not go on: ${why} ${left}`; +} + /** The timeline line a refused write of the status mirror leaves on its request. */ function refusedMirrorNoteText(status: string, reason: string): string { return `The approval status '${status}' could not be written to the record: ${reason}`; @@ -5148,6 +5234,476 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega return Array.isArray(closed) && (closed.includes('approved') || closed.includes('rejected')); } + /** + * [ADR-0162 D5, Execution item 8] Whether a decision on `row`'s step is held + * back: `row` is a request of an approval the check stamped when it opened, + * and its object closes on `field` at `approved` or `rejected`. Both + * decisions are held back, whichever of the two the object closes on, and + * the field keeps `pending` until the approval is over + * ({@link judgeApprovalAfterDoor}). Every other status is written as before. + */ + private holdsBackDecision(row: any, field: string): boolean { + return stampOf(row) !== undefined && this.closesOnApprovalOutcome(String(row?.object_name ?? ''), field); + } + + /** + * [ADR-0162 D5, Execution item 8] The door's judgement of an approval, after + * a door resumed or cancelled one of its runs: a decision (by a person or + * the platform's clock), a send-back, a resubmission, a recall and the + * continuation of a restored run. It never takes the resume's own answer + * for it, which is about the request's own run. + * + * The approval is the request's root run, on the request's record. The door + * asks its own table for the approval's requests on the record and reads + * the run that carries the record (`record_run_id`), and answers one of: + * + * - **in progress**: a request of the approval is pending or returned on + * the record, or the run is parked at a pause a step can follow (a node + * of the set the request carries). Nothing is written, and the mark + * stays. + * - **finished**: the run completed, stopped on a node outside the set, or + * is parked at a pause outside it, and no failure it routed, nor a later + * step that could not open, ended it between two steps. The mirror writes + * the decision of the approval's latest request on the record, where that + * request was decided and its decision was held back, in the name of + * whoever decided it ({@link attributedMirrorContext}). + * - **abandoned**: the run ended between two steps + * ({@link abandonApproval}). + * - **cannot tell**: another process is advancing the run, or the run or + * the table cannot be read. Nothing is written, and the mark stays for + * the reconciler. + * + * In an approval that holds nothing back, finished and abandoned both end + * the hold: the mark is cleared and nothing is written. Where the approval's + * latest request was recalled, the writer that recalled it already wrote + * what an abandoned approval leaves: the mark is cleared and nothing more is + * written. Where no request of the approval carries the mark, it was judged + * already, and nothing is done. The marks are cleared once the outcome or + * the put-back lands; a write a rule or a hook of the app refused leaves + * them, so that the reconciler tries it again. + * + * Best-effort and never throws: the door's own action is durable before + * this runs. + */ + private async judgeApprovalAfterDoor( + request: { id?: unknown } | null | undefined, + door: string, + decided?: { requestId: string; actorId: string | null }, + ): Promise { + const requestId = request?.id != null ? String(request.id) : ''; + if (!requestId) return 'unstamped'; + try { + const own = await this.engine.find('sys_approval_request', { + where: { id: requestId }, limit: 1, context: SYSTEM_CTX, + }); + const row: any = Array.isArray(own) ? own[0] : undefined; + const stamp = stampOf(row); + if (!row || stamp === undefined || !row.root_run_id) return 'unstamped'; + + const approval: any[] = (await this.engine.find('sys_approval_request', { + where: { root_run_id: row.root_run_id, object_name: row.object_name, record_id: row.record_id }, + orderBy: [{ field: 'created_at', order: 'asc' }], + limit: 500, context: SYSTEM_CTX, + })) ?? []; + if (approval.some((r) => r.status === 'pending' || r.status === 'returned')) return 'in_progress'; + const marked = approval.filter(isMarked); + if (marked.length === 0) return 'judged'; + const latest = approval[approval.length - 1] ?? row; + if (latest.status !== 'approved' && latest.status !== 'rejected') { + await this.clearMarks(marked); + return 'judged'; + } + + const reading = await this.readCarryingRun(latest, stamp, approval); + if (reading.answer === 'undetermined') { + this.logger?.info?.( + `[approvals] after ${door}, the approval of ${row.object_name}/${row.record_id} could not be judged yet: ${reading.why} ` + + 'Nothing was written; the request keeps its mark, and the reconciler judges it.', + { request: requestId, latest: latest.id, run: reading.runId ?? null }, + ); + return 'undetermined'; + } + if (reading.answer === 'in_progress') return 'in_progress'; + + const config = parseJson(latest.node_config_json, { approvers: [] } as any); + const field = typeof config.approvalStatusField === 'string' && config.approvalStatusField + ? config.approvalStatusField : undefined; + const holds = !!field && this.holdsBackDecision(latest, field); + if (reading.answer === 'finished') { + if (!holds) { + await this.clearMarks(marked); + return 'finished'; + } + const actor = decided && decided.requestId === String(latest.id) + ? decided.actorId + : await this.deciderOf(latest); + const refusal = await this.mirrorStatusField( + latest.object_name, latest.record_id, field!, String(latest.status), actor, + latest.organization_id ?? null, undefined, { request: latest, step: latest.flow_node_id ?? latest.current_step ?? null }, + ); + if (!refusal) await this.clearMarks(marked); + return 'finished'; + } + if (!holds) { + await this.clearMarks(marked); + return 'ended'; + } + await this.abandonApproval(latest, marked, field!, reading.why); + return 'abandoned'; + } catch (err: any) { + this.logger?.warn?.( + `[approvals] after ${door}, the approval of request '${requestId}' could not be judged: ${err?.message ?? err}. ` + + 'Nothing was written; its marks stand, and the reconciler judges it.', + { request: requestId, error: err?.message ?? String(err) }, + ); + return 'undetermined'; + } + } + + /** + * [ADR-0162 D5, Execution item 8] Read the run that carries `latest`'s + * record, once no request of the approval is pending or returned on it, and + * place where it stopped against `stamp`. + * + * - A run another process is advancing, or one that cannot be read: + * `undetermined`. + * - Parked: at a node of the set, `in_progress`; elsewhere it is over. + * - Ended (completed, failed, cancelled, timed out, refused): over. + * + * Over, it ended between two steps where a later step of the approval was + * reached and could not open (the note on `latest`, {@link noteLaterStepNotOpened}), + * whatever the flow did with that failure; where a node of the set failed at + * the top level of the run and the flow routed the failure, and no request + * of the approval opened after it (N46 c′: a failure handled in a + * `try_catch` region is the author's statement that it needs no later step); + * and where the run stopped on a node of the set. Otherwise it finished: an + * end after the last step is the approval's end, also where a node after + * the last step failed. + */ + private async readCarryingRun( + latest: any, + stamp: readonly StampedNode[], + approval: readonly any[], + ): Promise< + | { answer: 'undetermined'; why: string; runId?: string } + | { answer: 'in_progress' } + | { answer: 'finished' } + | { answer: 'abandoned'; why: string } + > { + const runId = String(latest.record_run_id ?? latest.root_run_id ?? ''); + const automation = this.automation; + if (!runId) return { answer: 'undetermined', why: 'the request records no run that carries its record.' }; + if (typeof automation?.getRun !== 'function') { + return { answer: 'undetermined', why: 'no automation engine that reports a run is attached.', runId }; + } + let run: { status?: string; flowName?: string; steps?: unknown } | null; + try { + run = await automation.getRun(runId); + } catch (err: any) { + return { answer: 'undetermined', why: `the run '${runId}' could not be read (${err?.message ?? err}).`, runId }; + } + const status = typeof run?.status === 'string' ? run.status : ''; + if (!run || !status) return { answer: 'undetermined', why: `the run '${runId}' reports no status.`, runId }; + if (ADVANCING_RUN_STATUSES.has(status)) { + return { answer: 'undetermined', why: `the run '${runId}' is ${status}, so another process may be advancing it.`, runId }; + } + const flow = typeof run.flowName === 'string' ? run.flowName : undefined; + const steps = (Array.isArray(run.steps) ? run.steps : []) as Array<{ + nodeId?: unknown; nodeType?: unknown; status?: unknown; parentNodeId?: unknown; startedAt?: unknown; + }>; + + let stoppedAt: string | undefined; + if (status === 'paused') { + let parked: { nodeId?: string; flowName?: string } | undefined; + try { + parked = await automation.suspensionOf?.(runId); + } catch (err: any) { + return { answer: 'undetermined', why: `where the run '${runId}' is parked could not be read (${err?.message ?? err}).`, runId }; + } + if (!parked?.nodeId) return { answer: 'undetermined', why: `the run '${runId}' reports paused, and no pause of it can be found.`, runId }; + if (standsBetweenSteps(stamp, parked.flowName ?? flow, parked.nodeId)) return { answer: 'in_progress' }; + } else if (!TERMINAL_RUN_STATUSES.has(status)) { + return { answer: 'undetermined', why: `the run '${runId}' reports the status '${status}', which the plugin does not place.`, runId }; + } else if (status !== 'completed') { + const failed = [...steps].reverse().find((s) => s?.status === 'failure' && !s.parentNodeId); + const last = failed ?? steps[steps.length - 1]; + stoppedAt = last && typeof last.nodeId === 'string' ? last.nodeId : undefined; + } + + const config = parseJson>(latest.node_config_json, {}); + const notOpened = config[LATER_STEP_NOT_OPENED_KEY] as { node?: unknown; reason?: unknown } | undefined; + if (notOpened && typeof notOpened === 'object') { + return { + answer: 'abandoned', + why: `its step '${String(notOpened.node ?? '')}' could not open (${String(notOpened.reason ?? 'no reason recorded')}).`, + }; + } + // A failure the flow routed, at the top level of the run, on a node of the + // set, after which no request of the approval opened. + const instant = (v: unknown): number => (v == null || v === '' ? NaN : new Date(v as string).getTime()); + const lastOpened = approval.reduce((acc, r) => { + const at = instant(r?.created_at); + return Number.isFinite(at) && at > acc ? at : acc; + }, -Infinity); + const routed = steps.find((s) => s?.status === 'failure' + && !s.parentNodeId + && typeof s.nodeId === 'string' + && s.nodeId !== stoppedAt + && standsBetweenSteps(stamp, flow, s.nodeId) + && !(instant(s.startedAt) < lastOpened)); + if (routed) { + return { answer: 'abandoned', why: `its node '${String(routed.nodeId)}' failed between two steps, and the flow went on to its end without asking the next step.` }; + } + if (status !== 'paused' && status !== 'completed') { + if (!stoppedAt) return { answer: 'abandoned', why: `its run ended ${status}, at a node the plugin cannot place.` }; + if (standsBetweenSteps(stamp, flow, stoppedAt)) { + return { answer: 'abandoned', why: `its run ended ${status} at node '${stoppedAt}', between two steps.` }; + } + } + return { answer: 'finished' }; + } + + /** + * [ADR-0162 D5, Execution item 8] Abandon an approval whose run ended + * between two steps, for its record, once no request of it is open. The + * decisions already made stay on their requests, with who decided and when. + * + * 1. The approval is marked abandoned on its latest request (`__abandoned` + * on its snapshot), first, so that the door that continues a restored + * run refuses it however far the rest gets ({@link continueRestoredRun}). + * 2. The mirror writes what an abandoned approval leaves, by item 7's + * order ({@link abandonedValueOnClosingField}): `recalled` where the + * field declares it and the object does not close on it, otherwise the + * value at submit, the default or empty, never a closed value. Where a + * request of another approval is pending or returned on the record and + * mirrors onto the same field, it writes nothing: the field is that + * approval's now. + * 3. A line with no actor on the latest request's timeline says that the + * approval did not go on, why, and what the record was put back to. + * 4. The submitter is told, and submits again. + * + * The marks are cleared where the put-back landed or nothing was to be + * written; a put-back a rule or a hook of the app refused is reported by the + * mirror and leaves them, for the reconciler to try again. + */ + private async abandonApproval(latest: any, marked: readonly any[], field: string, why: string): Promise { + const now = this.clock.now().toISOString(); + const object = String(latest.object_name); + const recordId = String(latest.record_id); + const org = latest.organization_id ?? null; + const step = latest.flow_node_id ?? latest.current_step ?? null; + + const snapshot = parseJson>(latest.node_config_json, {}); + await this.engine.update('sys_approval_request', { + id: latest.id, updated_at: now, + node_config_json: JSON.stringify({ ...snapshot, [ABANDONED_KEY]: { at: now, reason: why } }), + }, { context: SYSTEM_CTX }); + + let other: any; + try { + const open = await this.engine.find('sys_approval_request', { + where: { object_name: object, record_id: recordId, status: { $in: ['pending', 'returned'] } }, + limit: 50, context: SYSTEM_CTX, + }); + other = (Array.isArray(open) ? open : []).find((r: any) => + String(r?.root_run_id ?? '') !== String(latest.root_run_id ?? '') + && parseJson(r?.node_config_json, { approvers: [] } as any).approvalStatusField === field); + } catch (err: any) { + this.logger?.warn?.('[approvals] could not read whether another approval is open on the record of an abandoned one; the put-back goes ahead', { + request: latest.id, object, record: recordId, error: err?.message ?? String(err), + }); + } + + let refusal: MirrorRefusal | undefined; + let left: string; + if (other) { + left = `The record's ${field} was left as it is: the request '${String(other.id)}' of another approval is open on it.`; + } else { + refusal = await this.mirrorStatusField( + object, recordId, field, 'recalled', null, org, + { payloadJson: latest.payload_json }, { request: latest, step }, + ); + if (refusal) { + left = `The record's ${field} could not be put back: ${refusal.message}`; + } else { + let value: unknown; + try { + const rows = await this.engine.find(object, { where: { id: recordId }, fields: ['id', field], limit: 1, context: SYSTEM_CTX }); + value = Array.isArray(rows) ? rows[0]?.[field] : undefined; + } catch { value = undefined; } + left = value == null || value === '' + ? `The record's ${field} was put back to empty.` + : `The record's ${field} was put back to '${String(value)}'.`; + } + } + + try { + await this.engine.insert('sys_approval_action', await this.actionRow(latest, { + id: uid('aact'), request_id: latest.id, organization_id: org, + step_name: step, step_index: 0, action: 'comment', + actor_id: null, + comment: abandonedNoteText(why, left), + created_at: now, + }), { context: SYSTEM_CTX }); + } catch (err: any) { + this.logger?.warn?.('[approvals] could not note an abandoned approval on its request timeline', { + request: latest.id, error: err?.message ?? String(err), + }); + } + this.logger?.warn?.( + `[approvals] the approval of ${object}/${recordId} ended between two steps and was abandoned: ${why} ${left} ` + + 'The decisions already made stay on their requests; the submitter was told, and submits again.', + { request: latest.id, object, record: recordId, field }, + ); + + if (latest.submitter_id) { + try { + await this.notify({ + topic: ABANDONED_APPROVAL_TOPIC, + organizationId: org, + audience: [String(latest.submitter_id)], + source: { object: 'sys_approval_request', id: String(latest.id) }, + dedupKey: `approval-abandoned-${String(latest.id)}`, + about: { object, recordId }, + text: (subject) => approvalNotificationText({ + title: 'approvalAbandonedTitle', body: 'approvalAbandonedBody', params: subject, + }), + }); + } catch (err: any) { + this.logger?.warn?.('[approvals] could not tell the submitter of an abandoned approval', { + request: latest.id, error: err?.message ?? String(err), + }); + } + } + + if (!refusal) await this.clearMarks(marked); + } + + /** + * [ADR-0162 Execution item 8] Clear the mark on `rows`, one keyed update + * each: the approval they belong to has been judged, or their requests' + * approval has moved on, or a writer abandoned it. Best-effort: a mark that + * stays is judged again by the reconciler, which writes nothing twice. + */ + private async clearMarks(rows: readonly any[]): Promise { + for (const r of rows) { + if (!isMarked(r)) continue; + try { + await this.engine.update('sys_approval_request', { id: r.id, unjudged_since: null }, { context: SYSTEM_CTX }); + } catch (err: any) { + this.logger?.warn?.('[approvals] could not clear the mark on a judged request; the reconciler judges it again', { + request: r.id, error: err?.message ?? String(err), + }); + } + } + } + + /** + * [ADR-0162 Execution item 8] Clear the marks on the requests of `row`'s + * approval on its record other than `row` itself. A recall, an override and + * the dead-run sweep abandon the approval at its open request, and the + * marks its earlier decisions left would otherwise hold the record. A new + * request of the approval, as it opens, ends the passage its earlier + * decisions began. No-op for a request of an approval that was not stamped. + */ + private async clearEarlierMarks(row: any): Promise { + if (stampOf(row) === undefined || !row?.root_run_id) return; + try { + const rows = await this.engine.find('sys_approval_request', { + where: { root_run_id: row.root_run_id, object_name: row.object_name, record_id: row.record_id }, + fields: ['id', 'unjudged_since'], limit: 500, context: SYSTEM_CTX, + }); + await this.clearMarks((Array.isArray(rows) ? rows : []).filter((r: any) => String(r.id) !== String(row.id))); + } catch (err: any) { + this.logger?.warn?.('[approvals] could not read the marks of an approval\'s earlier requests; the reconciler judges them', { + request: row?.id, error: err?.message ?? String(err), + }); + } + } + + /** + * [ADR-0162 D5, Execution item 8] An abandoned approval does not go on. + * Refuse {@link continueRestoredRun} for a request of an approval the door + * or the reconciler marked abandoned on its record: an operator who put a + * failed run's pause back would otherwise open the next step on a document + * that has since been put back, and perhaps submitted again. The operator + * cancels the restored run instead. A read that fails refuses as well: the + * continuation is a repair, and it waits for a store that answers. + */ + private async refuseAbandonedContinuation(raw: any, requestId: string): Promise { + if (stampOf(raw) === undefined || !raw?.root_run_id) return; + const rows = await this.engine.find('sys_approval_request', { + where: { root_run_id: raw.root_run_id, object_name: raw.object_name, record_id: raw.record_id }, + fields: ['id', 'node_config_json'], limit: 500, context: SYSTEM_CTX, + }); + const abandoned = (Array.isArray(rows) ? rows : []).find((r: any) => + parseJson>(r?.node_config_json, {})[ABANDONED_KEY] !== undefined); + if (!abandoned) return; + const runId = String(raw.flow_run_id ?? ''); + throw new Error( + `INVALID_STATE: the approval of ${String(raw.object_name)}/${String(raw.record_id)} that request ${requestId} ` + + `belongs to was abandoned when its run ended between two steps (request '${String(abandoned.id)}'), and its ` + + `record was put back, so it does not go on. Cancel the restored run '${runId}' with the automation engine's ` + + `cancelRun('${runId}'); the submitter submits the record again.`, + ); + } + + /** + * [ADR-0162 Execution item 8] Who decided `request`: the actor of its last + * `approve` or `reject` row, or `null` (a write with no actor) where none + * names one, as for the SLA sweep's auto-decision. + */ + private async deciderOf(request: any): Promise { + try { + const rows = await this.engine.find('sys_approval_action', { + where: { request_id: request.id, action: { $in: ['approve', 'reject'] } }, + orderBy: [{ field: 'created_at', order: 'desc' }], + fields: ['id', 'actor_id'], limit: 1, context: SYSTEM_CTX, + }); + const actor = Array.isArray(rows) ? rows[0]?.actor_id : undefined; + return actor != null && String(actor) !== '' ? String(actor) : null; + } catch { + return null; + } + } + + /** + * [ADR-0162 Execution item 8] Keep a durable note on the approval's latest + * request on the record where a later step of it was reached and could not + * open (an empty slate under `onEmptyApprovers: 'fail'`, another request + * pending on the record, or any other failure of its opening), so that the + * judgement of the approval does not depend on how the flow routed that + * failure ({@link readCarryingRun}). A failure of the approval's first + * request leaves no note: no request of it exists. Best-effort. + */ + private async noteLaterStepNotOpened( + input: { object: string; recordId: string; nodeId: string; rootRun?: ApprovalRootRun | null }, + failure: unknown, + ): Promise { + const rootRunId = input.rootRun?.runId; + if (!rootRunId) return; + try { + const rows = await this.engine.find('sys_approval_request', { + where: { root_run_id: rootRunId, object_name: input.object, record_id: input.recordId }, + orderBy: [{ field: 'created_at', order: 'desc' }], + limit: 1, context: SYSTEM_CTX, + }); + const latest: any = Array.isArray(rows) ? rows[0] : undefined; + if (!latest || stampOf(latest) === undefined) return; + const now = this.clock.now().toISOString(); + const reason = String((failure as { message?: unknown } | undefined)?.message ?? failure).slice(0, 500); + const snapshot = parseJson>(latest.node_config_json, {}); + await this.engine.update('sys_approval_request', { + id: latest.id, updated_at: now, + node_config_json: JSON.stringify({ ...snapshot, [LATER_STEP_NOT_OPENED_KEY]: { node: input.nodeId, at: now, reason } }), + }, { context: SYSTEM_CTX }); + } catch (err: any) { + this.logger?.warn?.('[approvals] could not note on the approval that a later step could not open; the run\'s own stop decides its judgement', { + object: input.object, record: input.recordId, node: input.nodeId, error: err?.message ?? String(err), + }); + } + } + /** * [ADR-0162 D5, Execution item 7 "The check"] Judge an approval at its first * request, and answer the between-two-steps set the request carries @@ -5857,6 +6413,21 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega locale?: string; }, context: ExecutionContext, + ): Promise { + try { + return await this.openNodeRequestBody(input, context); + } catch (err) { + // [ADR-0162 Execution item 8] A later step of an approval that could not + // open leaves a note on the approval's latest request. + await this.noteLaterStepNotOpened(input, err); + throw err; + } + } + + /** {@link openNodeRequest}'s body: its docblock is this method's contract. */ + private async openNodeRequestBody( + input: Parameters[0], + context: ExecutionContext, ): Promise { if (!input.object) throw new Error('VALIDATION_FAILED: object is required'); if (!input.recordId) throw new Error('VALIDATION_FAILED: recordId is required'); @@ -6281,6 +6852,9 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega }; await this.engine.insert('sys_approval_request', row, { context: SYSTEM_CTX }); await this.syncApproverIndex(id, approvers, requestOrg, now, platformSlotOpened); + // [ADR-0162 Execution item 8] A new request of the approval ends the + // passage its earlier decisions began: their marks are cleared. + await this.clearEarlierMarks(row); await this.engine.insert('sys_approval_action', await this.actionRow(row, { id: uid('aact'), request_id: id, organization_id: requestOrg, step_name: input.nodeId, step_index: 0, action: 'submit', @@ -6959,14 +7533,17 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega acceptedOutputs || (config as any).__decisionOutputs ? { ...((config as any).__decisionOutputs ?? {}), ...(acceptedOutputs ?? {}) } : undefined; + // [ADR-0162 Execution item 8] The decision leaves the mark on a request of + // an approval the check stamped, in the update that records it. await this.engine.update('sys_approval_request', { id: requestId, status: finalStatus, pending_approvers: null, pending_approver_labels: null, completed_at: now, updated_at: now, + ...(stampOf(raw) !== undefined ? { unjudged_since: now } : {}), ...(mergedOutputs ? { node_config_json: JSON.stringify({ ...config, __decisionOutputs: mergedOutputs }), } : {}), }, { context: SYSTEM_CTX }); await this.syncApproverIndex(requestId, [], org, now); - if (config.approvalStatusField) { + if (config.approvalStatusField && !this.holdsBackDecision(raw, config.approvalStatusField)) { await this.mirrorStatusField( raw.object_name, raw.record_id, config.approvalStatusField, finalStatus, actingUserId(context), org, undefined, { request: raw, step: nodeId }, @@ -7487,6 +8064,11 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega submitterToldBy: 'outcome' | 'escalation', ): Promise { const result = await this.decideNode(requestId, input, context); + // [ADR-0162 Execution item 8] After the resume, the door judges the + // approval: the outcome is written only once it is over. + const judge = () => this.judgeApprovalAfterDoor( + result.request, `the ${result.decision} decision`, { requestId: String(requestId), actorId: actingUserId(context) }, + ); let resumed = false; let resumeError: string | undefined; @@ -7510,21 +8092,29 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega // session), never off the input: the decider's segment names them, as // the decision's own audit row does. Only beside a decider. const impersonatedBy = decider ? impersonatorOf(context) : undefined; - const outcome = await this.resumeRecordedOutcome( - result.runId, requestId, `the ${result.decision} decision`, - { - branchLabel, - // #3447 P2: accepted decision outputs ride the resume envelope and - // land as `.` flow variables — a later approval node's - // `expression` approver reads them as `vars..`. - // Reserved keys are spread LAST so no output can shadow them (the - // whitelist already rejects them; this is defense in depth). - output: { ...(result.outputs ?? {}), decision: result.decision, requestId }, - ...(decider ? { resumedBy: decider } : {}), - ...(impersonatedBy ? { impersonatedBy } : {}), - }, - result.decision, - ); + let outcome: Awaited>; + try { + outcome = await this.resumeRecordedOutcome( + result.runId, requestId, `the ${result.decision} decision`, + { + branchLabel, + // #3447 P2: accepted decision outputs ride the resume envelope and + // land as `.` flow variables — a later approval node's + // `expression` approver reads them as `vars..`. + // Reserved keys are spread LAST so no output can shadow them (the + // whitelist already rejects them; this is defense in depth). + output: { ...(result.outputs ?? {}), decision: result.decision, requestId }, + ...(decider ? { resumedBy: decider } : {}), + ...(impersonatedBy ? { impersonatedBy } : {}), + }, + result.decision, + ); + } catch (err) { + // [ADR-0162 Execution item 8] A run that failed after the decision + // ended where it stopped: the door judges it before it reports the strand. + await judge(); + throw err; + } resumed = outcome.resumed; resumeError = outcome.resumeError; resumeFailure = outcome.resumeFailure; @@ -7534,7 +8124,9 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega // whether this decision ended the process or moved it to a further // approval step. A resume that strands has thrown above, so — as on the // send-back — a stranded decision tells no one. - if (result.finalized && submitterToldBy === 'outcome') { + // An approval the door abandoned told its submitter so itself. + const judgement = result.finalized ? await judge() : undefined; + if (result.finalized && submitterToldBy === 'outcome' && judgement !== 'abandoned') { await this.notifyDecisionOutcome(result.request, result.decision, input.comment, context); } @@ -7770,6 +8362,9 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega actingUserId(context), org, { payloadJson: raw.payload_json }, { request: raw, step: nodeId }, ); } + // [ADR-0162 Execution item 8] The recall abandons the approval at its open + // request: the marks its earlier decisions left are cleared. + await this.clearEarlierMarks(raw); // A recall ABANDONS the request, so a run that cannot be resumed must not // fail the call — the withdrawal and the record-lock release are the point, @@ -7879,6 +8474,10 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega } } + // [ADR-0162 Execution item 8] After the resume or the cancel the recall + // made, the door judges the approval. + await this.judgeApprovalAfterDoor(raw, 'the recall'); + const fresh = await this.readBackRequest(requestId, context); return { request: fresh, @@ -8378,9 +8977,11 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega }), { context: SYSTEM_CTX }); await this.engine.update('sys_approval_request', { id: requestId, status: 'rejected', pending_approvers: null, pending_approver_labels: null, completed_at: now, updated_at: now, + // [ADR-0162 Execution item 8] A decision, so it leaves the mark. + ...(stampOf(raw) !== undefined ? { unjudged_since: now } : {}), }, { context: SYSTEM_CTX }); await this.syncApproverIndex(requestId, [], org, now); - if (config.approvalStatusField) { + if (config.approvalStatusField && !this.holdsBackDecision(raw, config.approvalStatusField)) { await this.mirrorStatusField( raw.object_name, raw.record_id, config.approvalStatusField, 'rejected', actingUserId(context), org, undefined, { request: raw, step: nodeId }, @@ -8389,17 +8990,25 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega let resumed = false; let resumeError: string | undefined; if (runId) { - const outcome = await this.resumeRecordedOutcome( - runId, requestId, 'the auto-rejection', - { - branchLabel: APPROVAL_BRANCH_LABELS.reject, - output: { decision: 'reject', autoRejected: true, requestId }, - }, - 'reject', - ); + let outcome: Awaited>; + try { + outcome = await this.resumeRecordedOutcome( + runId, requestId, 'the auto-rejection', + { + branchLabel: APPROVAL_BRANCH_LABELS.reject, + output: { decision: 'reject', autoRejected: true, requestId }, + }, + 'reject', + ); + } catch (err) { + await this.judgeApprovalAfterDoor(raw, 'the auto-rejection', { requestId: String(requestId), actorId: actingUserId(context) }); + throw err; + } resumed = outcome.resumed; resumeError = outcome.resumeError; } + // [ADR-0162 Execution item 8] The auto-rejection is a decision: the door judges the approval. + await this.judgeApprovalAfterDoor(raw, 'the auto-rejection', { requestId: String(requestId), actorId: actingUserId(context) }); if (raw.submitter_id) { await this.notify({ topic: 'approval.returned', @@ -8432,17 +9041,25 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega let resumed = false; let resumeError: string | undefined; if (runId) { - const outcome = await this.resumeRecordedOutcome( - runId, requestId, 'the send-back', - { - branchLabel: APPROVAL_BRANCH_LABELS.revise, - output: { decision: 'revise', requestId }, - }, - 'revise', - ); + let outcome: Awaited>; + try { + outcome = await this.resumeRecordedOutcome( + runId, requestId, 'the send-back', + { + branchLabel: APPROVAL_BRANCH_LABELS.revise, + output: { decision: 'revise', requestId }, + }, + 'revise', + ); + } catch (err) { + await this.judgeApprovalAfterDoor(raw, 'the send-back'); + throw err; + } resumed = outcome.resumed; resumeError = outcome.resumeError; } + // [ADR-0162 Execution item 8] The door judges the approval after the send-back. + await this.judgeApprovalAfterDoor(raw, 'the send-back'); if (raw.submitter_id) { // [#24978] The approver's own words, when they wrote some, are the body @@ -8531,17 +9148,25 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega let resumed = false; let resumeError: string | undefined; if (runId) { - const outcome = await this.resumeRecordedOutcome( - runId, requestId, 'the resubmit', - { - branchLabel: APPROVAL_BRANCH_LABELS.resubmit, - output: { resubmitted: true, requestId }, - }, - 'resubmit', - ); + let outcome: Awaited>; + try { + outcome = await this.resumeRecordedOutcome( + runId, requestId, 'the resubmit', + { + branchLabel: APPROVAL_BRANCH_LABELS.resubmit, + output: { resubmitted: true, requestId }, + }, + 'resubmit', + ); + } catch (err) { + await this.judgeApprovalAfterDoor(raw, 'the resubmission'); + throw err; + } resumed = outcome.resumed; resumeError = outcome.resumeError; } + // [ADR-0162 Execution item 8] The door judges the approval after the resubmission. + await this.judgeApprovalAfterDoor(raw, 'the resubmission'); const fresh = await this.readBackRequest(requestId, context); return { request: fresh, runId, resumed, ...(resumeError ? { resumeError } : {}) }; @@ -10274,6 +10899,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega // next round. Same guard `recall`-in-revise-window and `resubmit` already // use, for the same reason. await this.assertLatestForRun(raw); + await this.refuseAbandonedContinuation(raw, requestId); // The signal, before the store is asked anything — a request this verb // cannot serve is refused without a suspension read. @@ -10352,21 +10978,29 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega // `RESUME_IN_PROGRESS` tolerance, the same stranded envelope with the // engine's own `repairable` discriminator, and the same re-journalling — // so a continuation that strands AGAIN is repairable exactly like the first. - const outcome = await this.resumeRecordedOutcome( - runId, requestId, signal.what, - { - branchLabel: signal.branchLabel, output: signal.output, - // The journalled decider (ruling A): the replayed nodes after the - // decision run as the person who decided, not as the run's trigger. - ...(typeof signal.resumedBy === 'string' && signal.resumedBy ? { resumedBy: signal.resumedBy } : {}), - // The journalled impersonator beside that decider: the replayed - // segment is stamped exactly as the decision's own resume would have. - ...(typeof signal.resumedBy === 'string' && signal.resumedBy - && typeof signal.impersonatedBy === 'string' && signal.impersonatedBy.trim() - ? { impersonatedBy: signal.impersonatedBy.trim() } : {}), - }, - signal.decision, - ); + let outcome: Awaited>; + try { + outcome = await this.resumeRecordedOutcome( + runId, requestId, signal.what, + { + branchLabel: signal.branchLabel, output: signal.output, + // The journalled decider (ruling A): the replayed nodes after the + // decision run as the person who decided, not as the run's trigger. + ...(typeof signal.resumedBy === 'string' && signal.resumedBy ? { resumedBy: signal.resumedBy } : {}), + // The journalled impersonator beside that decider: the replayed + // segment is stamped exactly as the decision's own resume would have. + ...(typeof signal.resumedBy === 'string' && signal.resumedBy + && typeof signal.impersonatedBy === 'string' && signal.impersonatedBy.trim() + ? { impersonatedBy: signal.impersonatedBy.trim() } : {}), + }, + signal.decision, + ); + } catch (err) { + await this.judgeApprovalAfterDoor(raw, 'the continuation of a restored run'); + throw err; + } + // [ADR-0162 Execution item 8] The door judges the approval after the continuation. + await this.judgeApprovalAfterDoor(raw, 'the continuation of a restored run'); return { resumed: outcome.resumed, @@ -10470,6 +11104,9 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega { payloadJson: raw.payload_json }, { request: raw, step: raw.current_step ?? null }, ); } + // [ADR-0162 Execution item 8] The sweep abandons the approval at its open + // request: the marks its earlier decisions left are cleared. + await this.clearEarlierMarks(raw); this.logger?.warn?.('[approvals] released a record held by a dead approval run', { request: raw.id, run: runId, runStatus, object: raw.object_name, record: raw.record_id, diff --git a/packages/plugins/plugin-approvals/src/sys-approval-request.object.ts b/packages/plugins/plugin-approvals/src/sys-approval-request.object.ts index 7b71d3b95cf..a12b49ea3bb 100644 --- a/packages/plugins/plugin-approvals/src/sys-approval-request.object.ts +++ b/packages/plugins/plugin-approvals/src/sys-approval-request.object.ts @@ -571,6 +571,21 @@ export const SysApprovalRequest = ObjectSchema.create({ group: 'State', }), + // [ADR-0162 D5, Execution item 8] The mark: when the request was decided, + // while what follows that decision has not been judged yet. Set in the + // update that records an approve or a reject on a request of an approval + // the check stamped (`between_steps_json`), and cleared when the plugin + // has judged the approval: finished, abandoned, or moved on to its next + // request on the record. The store filters on it, oldest first, so that + // whatever no door judged can be found; null on every other request. + unjudged_since: Field.datetime({ + label: 'Unjudged Since', + required: false, + readonly: true, + description: 'When this request was decided, while what follows the decision has not been judged yet.', + group: 'State', + }), + node_config_json: Field.textarea({ label: 'Node Config', required: false, @@ -639,6 +654,8 @@ export const SysApprovalRequest = ObjectSchema.create({ { fields: ['root_run_id', 'object_name', 'record_id'] }, // Every request on the record one run carries. { fields: ['record_run_id'] }, + // [ADR-0162 Execution item 8] The decided requests whose approval is not judged yet, oldest first. + { fields: ['unjudged_since'] }, ], // Server-declared decision actions (objectui#2678 P2-4). The console's diff --git a/packages/plugins/plugin-approvals/src/translations/messages.ts b/packages/plugins/plugin-approvals/src/translations/messages.ts index ee99b8e5e41..2523492c39f 100644 --- a/packages/plugins/plugin-approvals/src/translations/messages.ts +++ b/packages/plugins/plugin-approvals/src/translations/messages.ts @@ -152,6 +152,8 @@ const enSentences = { approvalReassignedBody: 'You are now an approver on {{object}} {{record}}.', approvalAutoRejectedTitle: 'Approval auto-rejected', approvalAutoRejectedBody: 'Your {{object}} {{record}} exceeded the revision limit ({{limit}}) and was rejected.', + approvalAbandonedTitle: 'Approval did not finish', + approvalAbandonedBody: 'The approval of your {{object}} {{record}} stopped between two of its steps, so it did not finish and the record was put back to an open status. Submit it again when it is ready.', approvalReturnedTitle: 'Sent back for revision', approvalReturnedBody: 'Your {{object}} {{record}} needs rework before it can be approved.', approvalRequestInfoTitle: 'More information requested', @@ -299,6 +301,8 @@ export const zhCNMessages: ApprovalMessages = { approvalReassignedBody: '您现在是 {{object}} {{record}} 的审批人。', approvalAutoRejectedTitle: '审批已自动驳回', approvalAutoRejectedBody: '您的{{object}} {{record}} 已超过退回修改次数上限({{limit}}),已被驳回。', + approvalAbandonedTitle: '审批未能完成', + approvalAbandonedBody: '您的{{object}} {{record}} 的审批在两个步骤之间停止,未能完成,记录已恢复为未关闭的状态。准备好后请重新提交。', approvalReturnedTitle: '已退回修改', approvalReturnedBody: '您的{{object}} {{record}} 需要修改后才能获批。', approvalRequestInfoTitle: '需要补充信息', @@ -383,6 +387,8 @@ export const jaJPMessages: ApprovalMessages = { approvalReassignedBody: 'あなたは {{object}} {{record}} の承認者になりました。', approvalAutoRejectedTitle: '承認が自動的に却下されました', approvalAutoRejectedBody: 'あなたの{{object}} {{record}} は差し戻し回数の上限({{limit}})を超えたため却下されました。', + approvalAbandonedTitle: '承認が完了しませんでした', + approvalAbandonedBody: 'あなたの{{object}} {{record}} の承認は 2 つのステップの間で停止したため完了せず、レコードは閉じていないステータスに戻されました。準備ができたら再度申請してください。', approvalReturnedTitle: '修正のため差し戻されました', approvalReturnedBody: 'あなたの{{object}} {{record}} は、承認を受ける前に修正が必要です。', approvalRequestInfoTitle: '追加情報が求められています', @@ -467,6 +473,8 @@ export const esESMessages: ApprovalMessages = { approvalReassignedBody: 'Ahora es aprobador de {{object}} {{record}}.', approvalAutoRejectedTitle: 'Aprobación rechazada automáticamente', approvalAutoRejectedBody: 'Su {{object}} {{record}} superó el límite de revisiones ({{limit}}) y se ha rechazado.', + approvalAbandonedTitle: 'La aprobación no terminó', + approvalAbandonedBody: 'La aprobación de su {{object}} {{record}} se detuvo entre dos de sus pasos, así que no terminó y el registro volvió a un estado abierto. Envíelo de nuevo cuando esté listo.', approvalReturnedTitle: 'Devuelto para revisión', approvalReturnedBody: 'Su {{object}} {{record}} necesita cambios antes de poder aprobarse.', approvalRequestInfoTitle: 'Se solicita más información', @@ -551,6 +559,8 @@ export const zhHantMessages: ApprovalMessages = { approvalReassignedBody: '你現在是 {{object}} {{record}} 的核准人。', approvalAutoRejectedTitle: '核准已自動駁回', approvalAutoRejectedBody: '你的{{object}} {{record}} 已超過退回修改次數上限({{limit}}),因此被駁回。', + approvalAbandonedTitle: '核准未能完成', + approvalAbandonedBody: '你的{{object}} {{record}} 的核准在兩個步驟之間停止,未能完成,記錄已恢復為未關閉的狀態。準備好後請重新送出。', approvalReturnedTitle: '已退回修改', approvalReturnedBody: '你的{{object}} {{record}} 需要修改後才能獲得核准。', approvalRequestInfoTitle: '需要補充資訊', @@ -635,6 +645,8 @@ export const arMessages: ApprovalMessages = { approvalReassignedBody: 'أصبحت الآن موافِقًا على {{object}} {{record}}.', approvalAutoRejectedTitle: 'رُفضت الموافقة تلقائيًا', approvalAutoRejectedBody: 'تجاوز طلبك بشأن {{object}} {{record}} حد المراجعات ({{limit}}) فرُفض.', + approvalAbandonedTitle: 'لم تكتمل الموافقة', + approvalAbandonedBody: 'توقفت الموافقة على {{object}} {{record}} بين خطوتين من خطواتها، فلم تكتمل وأُعيد السجل إلى حالة مفتوحة. أعد إرساله عندما يكون جاهزًا.', approvalReturnedTitle: 'أُعيد للمراجعة', approvalReturnedBody: 'يحتاج طلبك بشأن {{object}} {{record}} إلى تعديل قبل أن تمكن الموافقة عليه.', approvalRequestInfoTitle: 'مطلوب مزيد من المعلومات', @@ -719,6 +731,8 @@ export const frMessages: ApprovalMessages = { approvalReassignedBody: 'Vous êtes désormais approbateur de {{object}} {{record}}.', approvalAutoRejectedTitle: 'Approbation rejetée automatiquement', approvalAutoRejectedBody: 'Votre demande sur {{object}} {{record}} a dépassé la limite de révisions ({{limit}}) et a été rejetée.', + approvalAbandonedTitle: 'L’approbation n’a pas abouti', + approvalAbandonedBody: 'L’approbation de votre {{object}} {{record}} s’est arrêtée entre deux de ses étapes : elle n’a pas abouti et l’enregistrement est revenu à un statut ouvert. Soumettez-le à nouveau lorsqu’il est prêt.', approvalReturnedTitle: 'Renvoyé pour révision', approvalReturnedBody: 'Votre demande sur {{object}} {{record}} doit être retravaillée avant de pouvoir être approuvée.', approvalRequestInfoTitle: 'Informations complémentaires demandées', @@ -803,6 +817,8 @@ export const ptBRMessages: ApprovalMessages = { approvalReassignedBody: 'Agora você é aprovador de {{object}} {{record}}.', approvalAutoRejectedTitle: 'Aprovação rejeitada automaticamente', approvalAutoRejectedBody: 'Sua solicitação sobre {{object}} {{record}} excedeu o limite de revisões ({{limit}}) e foi rejeitada.', + approvalAbandonedTitle: 'A aprovação não foi concluída', + approvalAbandonedBody: 'A aprovação de {{object}} {{record}} parou entre duas de suas etapas, por isso não foi concluída e o registro voltou a um status aberto. Envie-o novamente quando estiver pronto.', approvalReturnedTitle: 'Devolvido para revisão', approvalReturnedBody: 'Sua solicitação sobre {{object}} {{record}} precisa de ajustes antes de poder ser aprovada.', approvalRequestInfoTitle: 'Mais informações solicitadas', @@ -887,6 +903,8 @@ export const ruMessages: ApprovalMessages = { approvalReassignedBody: 'Теперь вы согласующий по {{object}} {{record}}.', approvalAutoRejectedTitle: 'Согласование отклонено автоматически', approvalAutoRejectedBody: 'Ваш запрос по {{object}} {{record}} превысил лимит доработок ({{limit}}) и был отклонён.', + approvalAbandonedTitle: 'Согласование не завершено', + approvalAbandonedBody: 'Согласование {{object}} {{record}} остановилось между двумя шагами, поэтому не завершилось, и запись возвращена в открытый статус. Отправьте её снова, когда она будет готова.', approvalReturnedTitle: 'Возвращено на доработку', approvalReturnedBody: 'Ваш запрос по {{object}} {{record}} нужно доработать, прежде чем его можно будет одобрить.', approvalRequestInfoTitle: 'Запрошены дополнительные сведения', @@ -971,6 +989,8 @@ export const deMessages: ApprovalMessages = { approvalReassignedBody: 'Sie sind jetzt Genehmiger für {{object}} {{record}}.', approvalAutoRejectedTitle: 'Genehmigung automatisch abgelehnt', approvalAutoRejectedBody: 'Ihre Anfrage zu {{object}} {{record}} hat das Überarbeitungslimit ({{limit}}) überschritten und wurde abgelehnt.', + approvalAbandonedTitle: 'Genehmigung nicht abgeschlossen', + approvalAbandonedBody: 'Die Genehmigung zu {{object}} {{record}} hat zwischen zwei ihrer Schritte angehalten. Sie wurde nicht abgeschlossen, und der Datensatz wurde auf einen offenen Status zurückgesetzt. Reichen Sie ihn erneut ein, wenn er bereit ist.', approvalReturnedTitle: 'Zur Überarbeitung zurückgesendet', approvalReturnedBody: 'Ihre Anfrage zu {{object}} {{record}} muss überarbeitet werden, bevor sie genehmigt werden kann.', approvalRequestInfoTitle: 'Weitere Informationen angefordert', @@ -1055,6 +1075,8 @@ export const koMessages: ApprovalMessages = { approvalReassignedBody: '이제 {{object}} {{record}}의 승인자입니다.', approvalAutoRejectedTitle: '승인이 자동 반려되었습니다', approvalAutoRejectedBody: '{{object}} {{record}}이(가) 수정 횟수 한도({{limit}})를 넘어 반려되었습니다.', + approvalAbandonedTitle: '승인이 완료되지 않았습니다', + approvalAbandonedBody: '{{object}} {{record}}의 승인이 두 단계 사이에서 멈춰 완료되지 않았고, 레코드는 열린 상태로 되돌아갔습니다. 준비가 되면 다시 제출하세요.', approvalReturnedTitle: '수정 요청됨', approvalReturnedBody: '{{object}} {{record}}을(를) 승인받으려면 먼저 수정해야 합니다.', approvalRequestInfoTitle: '추가 정보 요청', From 9cd8adcaaac8e4130eb974374f458e5c8c8fd545 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 07:34:46 +0000 Subject: [PATCH 23/32] test(approvals): the outcome when the approval is over, case by case; the mark's translations and changeset Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5pigknx7rC8rXnA3my --- .../37767-outcome-when-approval-over.md | 20 + ...utcome-when-over-37767.integration.test.ts | 515 ++++++++++++++++++ .../plugin-approvals/src/approval-service.ts | 27 +- .../src/approver-address-readers.test.ts | 8 +- ...-closing-field-refusal.integration.test.ts | 9 +- .../stored-process-package-backfill.test.ts | 2 + .../src/translations/ar.objects.generated.ts | 4 + .../src/translations/de.objects.generated.ts | 4 + .../src/translations/en.objects.generated.ts | 4 + .../translations/es-ES.objects.generated.ts | 4 + .../src/translations/fr.objects.generated.ts | 4 + .../translations/ja-JP.objects.generated.ts | 4 + .../src/translations/ko.objects.generated.ts | 4 + .../translations/pt-BR.objects.generated.ts | 4 + .../src/translations/ru.objects.generated.ts | 4 + .../translations/zh-CN.objects.generated.ts | 4 + .../translations/zh-Hant.objects.generated.ts | 4 + 17 files changed, 615 insertions(+), 10 deletions(-) create mode 100644 .changeset/37767-outcome-when-approval-over.md create mode 100644 packages/plugins/plugin-approvals/src/approval-outcome-when-over-37767.integration.test.ts diff --git a/.changeset/37767-outcome-when-approval-over.md b/.changeset/37767-outcome-when-approval-over.md new file mode 100644 index 00000000000..131a7031538 --- /dev/null +++ b/.changeset/37767-outcome-when-approval-over.md @@ -0,0 +1,20 @@ +--- +'@objectstack/plugin-approvals': patch +--- + +feat(approvals): on a field its object closes on, an approval's decision is written when the approval is over (ADR-0162 Execution item 8, the outcome) + +Clause-②: yes (widening) +Metadata-protocol: none + +Widened: `sys_approval_request` gains the engine-written, read-only datetime column `unjudged_since` (the mark) and an index on it; the `getRun` member of the automation surface the plugin declares (`ApprovalResumeSurface`) now also types the step log the engine already returns; the plugin's message catalog gains `approvalAbandonedTitle` and `approvalAbandonedBody` in all 11 locale packs, sent on the topic `approval.abandoned`. + +What changes, only for an approval the check stamped when it opened (one with a step that can act on an object that declares `closedStates`): + +- **The decision is held back.** Where the object closes on the step's mirror field at `approved` or `rejected`, neither decision is written onto the record when it is made. The request records it as before, and the field keeps `pending`. Every other status (`pending` as a request opens, `returned` at a send-back, what a recall leaves) is written as before. +- **The mark.** Every decision on a request of such an approval sets `unjudged_since` in the update that records it, also where nothing is held back. It is cleared when the approval is judged, and when the approval's next request opens on the record. A recall, an administrator's override and the dead-run sweep clear it on the approval's earlier requests. +- **The door judges the approval.** After a decision (by a person or the SLA clock), a send-back (and its auto-rejection), a resubmission, a recall and the continuation of a restored run, the plugin reads the run that carries the record and the approval's requests on it. Finished (the run completed, stopped after the last step, or is parked at a pause no step can follow): it writes the latest request's decision, as the person who decided it. In progress (a request is open, or the run is parked at a pause a step can follow): nothing. Ended between two steps (the run stopped on a node a step could still follow, a failure the flow routed at the top level ended it, or a later step could not open, whatever the flow did with that): the approval is abandoned. Cannot tell (the run is being advanced or cannot be read): nothing, and the mark stays. +- **An abandoned approval.** The latest request is marked abandoned, the field is put back by item 7's order (never a closed value, and nothing where another approval's request is open on the record on the same field), a timeline line with no actor says why and what the record was put back to, and the submitter is told on `approval.abandoned` instead of `approval.approved` or `approval.rejected`. The decisions already made stay on their requests. +- **A restored run is refused.** `continueRestoredRun` refuses a request of an abandoned approval with `INVALID_STATE` and tells the operator to cancel the restored run. + +Unchanged: an object that declares no `closedStates`; an approval that opened before its object declared the key, or whose requests could not be placed. An approval on an object that declares the key on another field than the approval's holds nothing back: its decisions are written at once, as before, and the door only clears the mark. diff --git a/packages/plugins/plugin-approvals/src/approval-outcome-when-over-37767.integration.test.ts b/packages/plugins/plugin-approvals/src/approval-outcome-when-over-37767.integration.test.ts new file mode 100644 index 00000000000..fdbdc7e45de --- /dev/null +++ b/packages/plugins/plugin-approvals/src/approval-outcome-when-over-37767.integration.test.ts @@ -0,0 +1,515 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 D5, Execution item 8 "The outcome when the approval is over", + * #37767 slice 3] On a field the object closes on at `approved` or + * `rejected`, every step's decision is held back and the field keeps + * `pending` until the approval is over for the record. After each door that + * resumes or cancels a run of the approval, the plugin reads the run that + * carries the record and asks its own table for a request of the approval on + * the record: finished, it writes the decision of the approval's latest + * request; in progress, nothing; ended between two steps, it abandons the + * approval and puts the field back; cannot tell, nothing, and the mark stays. + * + * Each case records the value the field keeps. Real kernel, real ObjectQL + * engine, real automation engine, real approval node, driver-sql on + * better-sqlite3 `:memory:`. + */ + +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { APPROVAL_REVISE_NODE_TYPE } from '@objectstack/spec/automation'; +import { strandedDecisionDetails } from '@objectstack/types'; +import { ObjectKernel } from '@objectstack/core'; +import { ObjectQLPlugin, type ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { AutomationServicePlugin, type AutomationEngine } from '@objectstack/service-automation'; +import { ApprovalService } from './approval-service.js'; +import { registerApprovalNode } from './approval-node.js'; +import { SysApprovalRequest } from './sys-approval-request.object.js'; +import { SysApprovalAction } from './sys-approval-action.object.js'; +import { SysApprovalApprover } from './sys-approval-approver.object.js'; +import { SysApprovalDelegation } from './sys-approval-delegation.object.js'; +import { SysApprovalToken } from './sys-approval-token.object.js'; + +const ORG = 'org_default'; +const SYS = { isSystem: true } as const; +const asPerson = (userId: string) => ({ userId, positions: [], permissions: [] }) as any; + +const text = (name: string) => ({ name, type: 'text' as const }); +const PLATFORM_GLOBAL = { enabled: false }; +const authzObjects = [ + { owner: '@objectstack/plugin-auth', def: { name: 'sys_user', label: 'User', tenancy: PLATFORM_GLOBAL, fields: { id: { ...text('id'), primaryKey: true }, email: text('email') } } }, + { owner: '@objectstack/plugin-auth', def: { name: 'sys_member', label: 'Member', tenancy: PLATFORM_GLOBAL, fields: { id: { ...text('id'), primaryKey: true }, user_id: text('user_id'), organization_id: text('organization_id'), role: text('role') } } }, + { owner: '@objectstack/plugin-security', def: { name: 'sys_user_position', label: 'User Position', tenancy: PLATFORM_GLOBAL, fields: { id: { ...text('id'), primaryKey: true }, user_id: text('user_id'), position: text('position'), organization_id: text('organization_id') } } }, + { owner: '@objectstack/plugin-security', def: { name: 'sys_user_permission_set', label: 'User Permission Set', tenancy: PLATFORM_GLOBAL, fields: { id: { ...text('id'), primaryKey: true }, user_id: text('user_id'), permission_set: text('permission_set'), organization_id: text('organization_id') } } }, +] as const; + +const statusField = { + name: 'approval_status', type: 'select' as const, defaultValue: 'draft', + options: ['draft', 'pending', 'returned', 'approved', 'rejected', 'recalled'].map((value) => ({ label: value, value })), +}; +const fields = { name: text('name'), approval_status: statusField, stage: text('stage') }; +/** Closes on its approval's outcome, both ways. */ +const invoice = { name: 'crm_invoice', label: 'Invoice', fields, closedStates: { approval_status: ['approved', 'rejected'] } }; +/** Closes on `approved` alone: a rejected order moves on. */ +const order = { name: 'crm_order', label: 'Order', fields, closedStates: { approval_status: ['approved'] } }; +/** Closes on `rejected` alone: an approved claim moves on. */ +const claim = { name: 'crm_claim', label: 'Claim', fields, closedStates: { approval_status: ['rejected'] } }; +/** Declares closed states, on another field than the approval's: its approval holds nothing back. */ +const ticket = { name: 'crm_ticket', label: 'Ticket', fields, closedStates: { stage: ['done'] } }; +/** Declares no closed state: the control, which behaves as before. */ +const memo = { name: 'crm_memo', label: 'Memo', fields }; + +const step = (id: string, approver: string, extra: Record = {}) => ({ + id, type: 'approval', label: id, + config: { approvers: [{ type: 'user', value: approver }], approvalStatusField: 'approval_status', ...extra }, +}); +const mark = (id: string) => ({ id, type: 'mark', label: id }); +const START = { id: 'start', type: 'start', label: 'Start' }; +const END = { id: 'end', type: 'end', label: 'End' }; +const edge = (source: string, target: string, label?: string, type?: string) => + ({ id: `${source}_${target}_${label ?? type ?? ''}`, source, target, ...(label ? { label } : {}), ...(type ? { type } : {}) }); +const flow = (name: string, nodes: unknown[], edges: unknown[], extra: Record = {}) => + ({ name, label: name, type: 'autolaunched', nodes: [START, ...nodes, END], edges, ...extra }); +/** `a` then `b`, each step's reject edge to the end. */ +const decided = (a: string, b: string) => [edge(a, b, 'approve'), edge(a, 'end', 'reject')]; + +const FLOWS = [ + // Two steps: the second opens in the segment the first decision resumes. + flow('two_step', [step('first', 'approver'), step('second', 'approver2')], + [edge('start', 'first'), ...decided('first', 'second'), ...decided('second', 'end')]), + // Two steps and a node after the last that reads the record. + flow('two_step_then_read', [step('first', 'approver'), step('second', 'approver2'), mark('read')], + [edge('start', 'first'), ...decided('first', 'second'), edge('second', 'read', 'approve'), edge('second', 'read', 'reject'), edge('read', 'end')]), + // A timer after the last step. + flow('wait_after', [step('first', 'approver'), step('second', 'approver2'), + { id: 'hold', type: 'wait', label: 'Hold', waitEventConfig: { eventType: 'timer', timerDuration: 'PT1H' } }], + [edge('start', 'first'), ...decided('first', 'second'), edge('second', 'hold', 'approve'), edge('second', 'end', 'reject'), edge('hold', 'end')]), + // A node that fails after the last step. + flow('fail_after', [step('first', 'approver'), step('second', 'approver2'), mark('boom')], + [edge('start', 'first'), ...decided('first', 'second'), edge('second', 'boom', 'approve'), edge('second', 'end', 'reject'), edge('boom', 'end')]), + // The second step resolves to no one under `fail`: unrouted, with a fault edge to the end, and with one to a third step. + flow('second_empty', [step('first', 'approver'), step('second', 'nobody', { onEmptyApprovers: 'fail' })], + [edge('start', 'first'), ...decided('first', 'second'), ...decided('second', 'end')]), + flow('second_empty_fault_end', [step('first', 'approver'), step('second', 'nobody', { onEmptyApprovers: 'fail' })], + [edge('start', 'first'), ...decided('first', 'second'), ...decided('second', 'end'), edge('second', 'end', undefined, 'fault')]), + flow('second_empty_fault_third', [step('first', 'approver'), step('second', 'nobody', { onEmptyApprovers: 'fail' }), step('third', 'approver2')], + [edge('start', 'first'), ...decided('first', 'second'), ...decided('second', 'end'), edge('second', 'third', undefined, 'fault'), ...decided('third', 'end')]), + // Another node between two steps fails: with a fault edge to the end, and unrouted. + flow('boom_between_fault_end', [step('first', 'approver'), mark('boom'), step('second', 'approver2')], + [edge('start', 'first'), edge('first', 'boom', 'approve'), edge('first', 'end', 'reject'), edge('boom', 'second'), edge('boom', 'end', undefined, 'fault'), ...decided('second', 'end')]), + flow('boom_between', [step('first', 'approver'), mark('boom'), step('second', 'approver2')], + [edge('start', 'first'), edge('first', 'boom', 'approve'), edge('first', 'end', 'reject'), edge('boom', 'second'), ...decided('second', 'end')]), + // That node's failure handled in a try_catch region, after which a gateway ends the flow. + flow('boom_handled', [step('first', 'approver'), + { id: 'guard', type: 'try_catch', label: 'Guard', config: { try: { nodes: [mark('boom')], edges: [] }, catch: { nodes: [mark('handled')], edges: [] } } }, + { id: 'gate', type: 'decision', label: 'Gate' }, + step('second', 'approver2')], + [edge('start', 'first'), edge('first', 'guard', 'approve'), edge('first', 'end', 'reject'), edge('guard', 'gate'), + { id: 'gate_end', source: 'gate', target: 'end', condition: 'true' }, + { id: 'gate_second', source: 'gate', target: 'second', condition: 'false' }, + ...decided('second', 'end')]), + // The second step can send back into a revise window. + flow('second_revise', [step('first', 'approver'), step('second', 'approver2'), { id: 'revise', type: APPROVAL_REVISE_NODE_TYPE, label: 'Revise' }], + [edge('start', 'first'), ...decided('first', 'second'), ...decided('second', 'end'), edge('second', 'revise', 'revise'), + { id: 'back', source: 'revise', target: 'second', label: 'resubmit', type: 'back' }]), + // The same, with no send-back left: a send-back auto-rejects. + flow('second_revise_spent', [step('first', 'approver'), step('second', 'approver2', { maxRevisions: 0 }), { id: 'revise', type: APPROVAL_REVISE_NODE_TYPE, label: 'Revise' }], + [edge('start', 'first'), ...decided('first', 'second'), ...decided('second', 'end'), edge('second', 'revise', 'revise'), + { id: 'back', source: 'revise', target: 'second', label: 'resubmit', type: 'back' }]), + // A batch whose items are records, each approved in its own run of `item_step`. + flow('item_step', [step('only', 'approver'), mark('after')], [edge('start', 'only'), edge('only', 'after', 'approve'), edge('only', 'end', 'reject'), edge('after', 'end')]), + { name: 'batch', label: 'batch', type: 'autolaunched', variables: [{ name: 'items', type: 'list', isInput: true }], + nodes: [START, { id: 'each', type: 'map', label: 'Each', config: { collection: { dialect: 'cel', source: 'items' }, flowName: 'item_step', itemObject: 'crm_invoice' } }, END], + edges: [edge('start', 'each'), edge('each', 'end')] }, +]; + +describe('[ADR-0162 item 8] the outcome is written when the approval is over', () => { + let kernel: ObjectKernel; + let ql: ObjectQL; + let automation: AutomationEngine; + let svc: ApprovalService; + /** Nodes of type `mark` that throw, by id. */ + let throwOn: Set; + /** What each `read` node saw on the record's field. */ + let seen: unknown[]; + let notices: Array<{ topic: string; audience: string[] }>; + + afterEach(async () => { + try { await kernel?.shutdown(); } catch { /* noop */ } + }); + + beforeEach(async () => { + throwOn = new Set(); + seen = []; + notices = []; + kernel = new ObjectKernel({ logger: { level: 'silent' } } as any); + await kernel.use(new ObjectQLPlugin()); + await kernel.use(new AutomationServicePlugin()); + await kernel.bootstrap(); + ql = kernel.getService('objectql'); + automation = kernel.getService('automation'); + + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); + await driver.connect(); + ql.registerDriver(driver, true); + for (const def of [invoice, order, claim, ticket, memo, SysApprovalRequest, SysApprovalAction, SysApprovalApprover, SysApprovalDelegation, SysApprovalToken]) { + ql.registry.registerObject(def as any, 'approvals-test', 'approvals-test'); + } + for (const o of authzObjects) ql.registry.registerObject(o.def as any, o.owner); + ql.registry.registerObject( + { name: 'sys_organization', label: 'Organization', managedBy: 'better-auth', fields: { name: text('name'), slug: text('slug') } } as any, + '@objectstack/plugin-auth', + ); + await ql.syncSchemas(); + await ql.insert('sys_organization', { id: ORG, name: 'Default Organization', slug: 'default' }, { context: SYS }); + for (const id of ['owner', 'approver', 'approver2']) { + await ql.insert('sys_user', { id, email: `${id}@example.test` }, { context: SYS }); + await ql.insert('sys_member', { id: `mem_${id}`, user_id: id, organization_id: ORG, role: 'member' }, { context: SYS }); + } + const quiet = { debug: () => {}, info: () => {}, warn: () => {}, error: () => {} }; + svc = new ApprovalService({ engine: ql, logger: quiet as any }); + svc.noteSweepClockScheduled(); + svc.attachMessaging({ emit: async (n: any) => { notices.push({ topic: n.topic, audience: n.audience }); } } as any); + svc.attachAutomation(automation as any); + registerApprovalNode(automation as any, svc, quiet as any); + (automation as any).registerNodeExecutor({ + type: 'mark', + descriptor: { type: 'mark', supportsPause: false }, + async execute(node: any, _variables: any, context: any) { + if (throwOn.has(node.id)) throw new Error(`${node.id} failed`); + if (node.id === 'read') { + const id = context?.record?.id; + seen.push((await ql.find(context?.object ?? 'crm_invoice', { where: { id }, context: SYS }))[0]?.approval_status); + } + return { success: true }; + }, + }); + for (const f of FLOWS) automation.registerFlow(f.name, f as any); + }); + + const read = async (object: string, id: string) => (await ql.find(object, { where: { id }, context: SYS }))[0]; + const field = async (object: string, id: string) => (await read(object, id))?.approval_status; + const requestsOn = async (id: string) => + (await ql.find('sys_approval_request', { where: { record_id: id }, orderBy: [{ field: 'created_at', order: 'asc' }], context: SYS })) as any[]; + const steps = async (id: string) => (await requestsOn(id)).map((r) => [r.flow_node_id, r.status]); + const marks = async (id: string) => (await requestsOn(id)).map((r) => r.unjudged_since != null); + const pendingOn = async (id: string) => (await requestsOn(id)).find((r) => r.status === 'pending' || r.status === 'returned'); + const timeline = async (requestId: string) => + (await ql.find('sys_approval_action', { where: { request_id: requestId }, orderBy: [{ field: 'created_at', order: 'asc' }], context: SYS }) as any[]) + .map((a) => [a.action, a.actor_id ?? null, a.comment ?? null]); + const seed = (object: string, id: string) => + ql.insert(object, { id, name: id, organization_id: ORG }, { context: { isSystem: true, tenantId: ORG } }); + const start = async (name: string, object: string, id: string) => { + await seed(object, id); + return automation.execute(name, { object, record: await read(object, id), userId: 'owner' } as any) as Promise; + }; + const decide = async (id: string, decision: 'approve' | 'reject', who: string) => + svc.decide(String((await requestsOn(id)).find((r) => r.status === 'pending').id), { decision, actorId: who, ...(decision === 'reject' ? { comment: 'no' } : {}) } as any, asPerson(who)); + const settle = (p: Promise) => p.then((v) => ({ ok: v as T }), (e: any) => ({ error: e as Error })); + + describe('the decision is held back, and written when the approval is over', () => { + it('two steps approved: the field reads pending after the first and approved once the run ends; marks are set and cleared', async () => { + expect((await start('two_step', 'crm_invoice', 'i_two')).status).toBe('paused'); + await decide('i_two', 'approve', 'approver'); + expect(await steps('i_two')).toEqual([['first', 'approved'], ['second', 'pending']]); + expect(await field('crm_invoice', 'i_two'), 'the first decision is held back').toBe('pending'); + expect(await marks('i_two'), 'the next request opened, so the first decision\'s passage ended').toEqual([false, false]); + + await decide('i_two', 'approve', 'approver2'); + expect(await field('crm_invoice', 'i_two')).toBe('approved'); + expect(await marks('i_two'), 'judged: no mark stands').toEqual([false, false]); + }); + + it('a node after the last decision reads pending; the outcome lands as the run ends', async () => { + await start('two_step_then_read', 'crm_invoice', 'i_read'); + await decide('i_read', 'approve', 'approver'); + await decide('i_read', 'approve', 'approver2'); + expect(seen).toEqual(['pending']); + expect(await field('crm_invoice', 'i_read')).toBe('approved'); + }); + + it('a second step that rejects on an object that closes on approved alone: pending until the approval is over, then rejected', async () => { + await start('two_step_then_read', 'crm_order', 'o_rej'); + await decide('o_rej', 'approve', 'approver'); + expect(await field('crm_order', 'o_rej'), 'the first decision is held back').toBe('pending'); + await decide('o_rej', 'reject', 'approver2'); + expect(seen, 'held back although the object does not close on rejected').toEqual(['pending']); + expect(await field('crm_order', 'o_rej')).toBe('rejected'); + }); + + it('a first step that approves on an object that closes on rejected alone: pending until the approval is over', async () => { + await start('two_step_then_read', 'crm_claim', 'c_app'); + await decide('c_app', 'approve', 'approver'); + expect(await field('crm_claim', 'c_app'), 'the object does not close on approved, and it is held back all the same').toBe('pending'); + await decide('c_app', 'approve', 'approver2'); + expect(seen).toEqual(['pending']); + expect(await field('crm_claim', 'c_app')).toBe('approved'); + }); + + it('a wait after the last step: the outcome is written as the run parks', async () => { + await start('wait_after', 'crm_invoice', 'i_wait'); + await decide('i_wait', 'approve', 'approver'); + await decide('i_wait', 'approve', 'approver2'); + expect((await automation.getRun(String((await requestsOn('i_wait'))[0].record_run_id)))?.status).toBe('paused'); + expect(await field('crm_invoice', 'i_wait')).toBe('approved'); + }); + + it('a node that fails after the last step: the outcome stands', async () => { + await start('fail_after', 'crm_invoice', 'i_fail_after'); + await decide('i_fail_after', 'approve', 'approver'); + throwOn.add('boom'); + const out = await settle(decide('i_fail_after', 'approve', 'approver2')); + expect('error' in out && out.error.message).toMatch(/^RESUME_FAILED/); + expect(await field('crm_invoice', 'i_fail_after')).toBe('approved'); + expect(await marks('i_fail_after')).toEqual([false, false]); + }); + + it('the outcome is written in the name of the person who decided the last step', async () => { + await start('two_step', 'crm_invoice', 'i_who'); + await decide('i_who', 'approve', 'approver'); + const writes: unknown[] = []; + const original = ql.update.bind(ql); + (ql as any).update = async (object: string, data: any, options?: any) => { + if (object === 'crm_invoice') writes.push([data.approval_status, options?.context?.userId, options?.context?.isSystem]); + return original(object, data, options); + }; + await decide('i_who', 'approve', 'approver2'); + expect(writes).toEqual([['approved', 'approver2', true]]); + }); + }); + + describe('a map item that is a record', () => { + it('its outcome does not wait for the later items, and a later item\'s failure does not undo it', async () => { + await seed('crm_invoice', 'i_m1'); + await seed('crm_invoice', 'i_m2'); + const items = [await read('crm_invoice', 'i_m1'), await read('crm_invoice', 'i_m2')]; + const batch: any = await automation.execute('batch', { params: { items }, userId: 'owner' } as any); + expect(batch.status).toBe('paused'); + + await decide('i_m1', 'approve', 'approver'); + expect(await pendingOn('i_m2'), 'the next item is in approval').toBeTruthy(); + expect(await field('crm_invoice', 'i_m1'), 'the first item\'s approval is over for its record').toBe('approved'); + + throwOn.add('after'); + await settle(decide('i_m2', 'approve', 'approver')); + expect(await field('crm_invoice', 'i_m1')).toBe('approved'); + // A node after the last step of a `map` body stands before that step's + // next opening (ADR-0162 D5): the second item's run stopped between two + // steps, and only its own record is put back. + expect(await field('crm_invoice', 'i_m2')).toBe('recalled'); + }); + }); + + describe('an abandoned latest request: nothing is written', () => { + it('a first step approved, a second recalled, and a run that then completes: no approved', async () => { + await start('two_step', 'crm_invoice', 'i_recall'); + await decide('i_recall', 'approve', 'approver'); + const second = await pendingOn('i_recall'); + await svc.recall(String(second.id), { actorId: 'owner' } as any, asPerson('owner')); + const run = await automation.getRun(String(second.record_run_id)); + expect(run?.status).toBe('completed'); + expect(await steps('i_recall')).toEqual([['first', 'approved'], ['second', 'recalled']]); + expect(await field('crm_invoice', 'i_recall')).toBe('recalled'); + expect(await marks('i_recall')).toEqual([false, false]); + }); + + it('the same for a returned request recalled in its revise window', async () => { + await start('second_revise', 'crm_invoice', 'i_revise'); + await decide('i_revise', 'approve', 'approver'); + const second = await pendingOn('i_revise'); + await svc.sendBack(String(second.id), { actorId: 'approver2', comment: 'fix it' } as any, asPerson('approver2')); + expect(await field('crm_invoice', 'i_revise')).toBe('returned'); + await svc.recall(String(second.id), { actorId: 'owner' } as any, asPerson('owner')); + expect(await steps('i_revise')).toEqual([['first', 'approved'], ['second', 'recalled']]); + expect(await field('crm_invoice', 'i_revise')).toBe('recalled'); + expect(await marks('i_revise')).toEqual([false, false]); + }); + }); + + describe('the other doors', () => { + it('a send-back, a resubmission and the decision of the new round: the field reads returned, then pending, then approved', async () => { + await start('second_revise', 'crm_invoice', 'i_round'); + await decide('i_round', 'approve', 'approver'); + const second = await pendingOn('i_round'); + await svc.sendBack(String(second.id), { actorId: 'approver2', comment: 'fix it' } as any, asPerson('approver2')); + expect(await field('crm_invoice', 'i_round')).toBe('returned'); + await svc.resubmit(String(second.id), { actorId: 'owner' } as any, asPerson('owner')); + expect(await field('crm_invoice', 'i_round')).toBe('pending'); + await decide('i_round', 'approve', 'approver2'); + expect(await steps('i_round')).toEqual([['first', 'approved'], ['second', 'returned'], ['second', 'approved']]); + expect(await field('crm_invoice', 'i_round')).toBe('approved'); + expect(await marks('i_round')).toEqual([false, false, false]); + }); + + it('a send-back past the revision limit auto-rejects: held back, then written when the approval is over', async () => { + await start('second_revise_spent', 'crm_invoice', 'i_spent'); + await decide('i_spent', 'approve', 'approver'); + const second = await pendingOn('i_spent'); + const out: any = await svc.sendBack(String(second.id), { actorId: 'approver2' } as any, asPerson('approver2')); + expect(out.autoRejected).toBe(true); + expect(await steps('i_spent')).toEqual([['first', 'approved'], ['second', 'rejected']]); + expect(await field('crm_invoice', 'i_spent')).toBe('rejected'); + expect(await marks('i_spent')).toEqual([false, false]); + }); + + it('a recall clears a mark an earlier decision of the approval left', async () => { + await start('two_step', 'crm_invoice', 'i_clear'); + await decide('i_clear', 'approve', 'approver'); + const [first, second] = await requestsOn('i_clear'); + // The shape a process that died before the next request cleared it leaves. + await ql.update('sys_approval_request', { id: first.id, unjudged_since: new Date().toISOString() }, { context: SYS }); + expect(await marks('i_clear')).toEqual([true, false]); + await svc.recall(String(second.id), { actorId: 'owner' } as any, asPerson('owner')); + expect(await marks('i_clear')).toEqual([false, false]); + expect(await field('crm_invoice', 'i_clear')).toBe('recalled'); + }); + }); + + describe('a later step that cannot open', () => { + it('on an empty slate, unrouted: the approval is abandoned and the field is put back', async () => { + await start('second_empty', 'crm_invoice', 'i_empty'); + const out = await settle(decide('i_empty', 'approve', 'approver')); + expect('error' in out && out.error.message).toMatch(/^RESUME_FAILED/); + const [first] = await requestsOn('i_empty'); + expect(first.status, 'the decision stays on its request').toBe('approved'); + expect(await field('crm_invoice', 'i_empty')).toBe('recalled'); + expect(JSON.parse(first.node_config_json).__abandoned).toBeTruthy(); + expect(JSON.parse(first.node_config_json).__laterStepNotOpened.node).toBe('second'); + const line = (await timeline(String(first.id))).at(-1)!; + expect(line.slice(0, 2), 'a line with no actor').toEqual(['comment', null]); + expect(line[2]).toMatch(/^The approval did not go on: its step 'second' could not open \(.*NO_APPROVERS.*\)\. The record's approval_status was put back to 'recalled'\.$/); + expect(notices.filter((n) => n.topic === 'approval.abandoned').map((n) => n.audience)).toEqual([['owner']]); + expect(notices.some((n) => n.topic === 'approval.approved'), 'no approved notice for an approval that did not finish').toBe(false); + expect(await marks('i_empty')).toEqual([false]); + }); + + it('with a fault edge to the end: abandoned', async () => { + await start('second_empty_fault_end', 'crm_invoice', 'i_empty_end'); + await decide('i_empty_end', 'approve', 'approver'); + expect((await automation.getRun(String((await requestsOn('i_empty_end'))[0].record_run_id)))?.status).toBe('completed'); + expect(await field('crm_invoice', 'i_empty_end')).toBe('recalled'); + }); + + it('with a fault edge to another step, which opens: in progress, then finished', async () => { + await start('second_empty_fault_third', 'crm_invoice', 'i_empty_third'); + await decide('i_empty_third', 'approve', 'approver'); + expect(await steps('i_empty_third')).toEqual([['first', 'approved'], ['third', 'pending']]); + expect(await field('crm_invoice', 'i_empty_third')).toBe('pending'); + await decide('i_empty_third', 'approve', 'approver2'); + expect(await field('crm_invoice', 'i_empty_third')).toBe('approved'); + }); + + it('on a request of another approval already pending on the record: the field keeps that approval\'s pending', async () => { + await start('two_step', 'crm_invoice', 'i_dup'); + const [first] = await requestsOn('i_dup'); + // Another approval's request on the record, on the same field: the + // shape a second approval leaves when it opens between two steps. + await ql.insert('sys_approval_request', { + id: 'areq_other', process_name: 'flow:other', object_name: 'crm_invoice', record_id: 'i_dup', status: 'pending', + root_run_id: 'run_other', record_run_id: 'run_other', flow_run_id: 'run_other', flow_node_id: 'x', + node_config_json: JSON.stringify({ approvers: [], approvalStatusField: 'approval_status' }), + organization_id: ORG, created_at: new Date().toISOString(), + }, { context: SYS }); + const out = await settle(svc.decide(String(first.id), { decision: 'approve', actorId: 'approver' } as any, asPerson('approver'))); + expect('error' in out && out.error.message).toMatch(/^RESUME_FAILED/); + const mine = (await requestsOn('i_dup')).filter((r) => r.root_run_id !== 'run_other'); + expect(mine.map((r) => [r.flow_node_id, r.status])).toEqual([['first', 'approved']]); + expect(JSON.parse(mine[0].node_config_json).__abandoned).toBeTruthy(); + expect(await field('crm_invoice', 'i_dup')).toBe('pending'); + expect((await timeline(String(first.id))).at(-1)![2]).toMatch(/left as it is: the request 'areq_other' of another approval is open on it\.$/); + }); + }); + + describe('another node between two steps fails', () => { + it('with a fault edge to the end: abandoned', async () => { + await start('boom_between_fault_end', 'crm_invoice', 'i_boom_end'); + throwOn.add('boom'); + await decide('i_boom_end', 'approve', 'approver'); + expect((await automation.getRun(String((await requestsOn('i_boom_end'))[0].record_run_id)))?.status).toBe('completed'); + expect(await field('crm_invoice', 'i_boom_end')).toBe('recalled'); + const [first] = await requestsOn('i_boom_end'); + expect((await timeline(String(first.id))).at(-1)![2]).toMatch(/its node 'boom' failed between two steps/); + }); + + it('handled in a try_catch region, after which a gateway ends the flow: finished', async () => { + await start('boom_handled', 'crm_invoice', 'i_handled'); + throwOn.add('boom'); + await decide('i_handled', 'approve', 'approver'); + expect((await automation.getRun(String((await requestsOn('i_handled'))[0].record_run_id)))?.status).toBe('completed'); + expect(await steps('i_handled')).toEqual([['first', 'approved']]); + expect(await field('crm_invoice', 'i_handled')).toBe('approved'); + }); + + it('unrouted: the run fails between two steps, the approval is abandoned, and a restored run is refused', async () => { + await start('boom_between', 'crm_invoice', 'i_boom'); + throwOn.add('boom'); + const out = await settle(decide('i_boom', 'approve', 'approver')); + expect('error' in out && strandedDecisionDetails(out.error)?.repairable).toBe(true); + expect(await field('crm_invoice', 'i_boom')).toBe('recalled'); + const [first] = await requestsOn('i_boom'); + + throwOn.clear(); + const restored = await (automation as any).restoreConsumedSuspension(String(first.flow_run_id), { requestedBy: 'ops', reason: 'test' }); + expect(restored.restored).toBe(true); + const refused = await settle(svc.continueRestoredRun(String(first.id))); + expect('error' in refused && refused.error.message).toMatch(/^INVALID_STATE: .*was abandoned when its run ended between two steps.*Cancel the restored run/); + expect(await steps('i_boom'), 'no next step opened').toEqual([['first', 'approved']]); + }); + }); + + describe('an approval that holds nothing back, and the control', () => { + it('an object whose closed states are on another field: the decision is written at once, the mark is set and cleared', async () => { + await start('two_step_then_read', 'crm_ticket', 't_two'); + const [first] = await requestsOn('t_two'); + expect(first.between_steps_json, 'stamped: the object declares the key').toBeTruthy(); + await decide('t_two', 'approve', 'approver'); + await decide('t_two', 'approve', 'approver2'); + expect(seen, 'as on main: a node after the decision reads it').toEqual(['approved']); + expect(await field('crm_ticket', 't_two')).toBe('approved'); + expect(await marks('t_two')).toEqual([false, false]); + }); + + it('the same object, whose run ends between two steps: nothing is written and the mark is cleared', async () => { + await start('boom_between_fault_end', 'crm_ticket', 't_boom'); + throwOn.add('boom'); + await decide('t_boom', 'approve', 'approver'); + const [first] = await requestsOn('t_boom'); + expect(await field('crm_ticket', 't_boom')).toBe('approved'); + expect(JSON.parse(first.node_config_json).__abandoned ?? null).toBeNull(); + expect(await marks('t_boom')).toEqual([false]); + }); + + it('an object that declares no closed state: unstamped, no mark, written as before', async () => { + await start('two_step_then_read', 'crm_memo', 'm_two'); + await decide('m_two', 'approve', 'approver'); + await decide('m_two', 'approve', 'approver2'); + const rows = await requestsOn('m_two'); + expect(rows.map((r) => r.between_steps_json ?? null)).toEqual([null, null]); + expect(rows.map((r) => r.unjudged_since ?? null)).toEqual([null, null]); + expect(seen).toEqual(['approved']); + expect(await field('crm_memo', 'm_two')).toBe('approved'); + }); + }); + + describe('cannot tell', () => { + it('a run another process is advancing: nothing is written, and the mark stays', async () => { + await start('two_step', 'crm_invoice', 'i_busy'); + await decide('i_busy', 'approve', 'approver'); + const original = automation.getRun.bind(automation); + (automation as any).getRun = async (id: string) => ({ ...(await original(id)), status: 'running' }); + await decide('i_busy', 'approve', 'approver2'); + expect(await field('crm_invoice', 'i_busy')).toBe('pending'); + expect(await marks('i_busy')).toEqual([false, true]); + }); + + it('a run that cannot be read: nothing is written, and the mark stays', async () => { + await start('two_step', 'crm_invoice', 'i_unread'); + await decide('i_unread', 'approve', 'approver'); + (automation as any).getRun = async () => { throw new Error('store down'); }; + await decide('i_unread', 'approve', 'approver2'); + expect(await field('crm_invoice', 'i_unread')).toBe('pending'); + expect(await marks('i_unread')).toEqual([false, true]); + }); + }); +}); diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index 5622e1649d7..97ef2cf320c 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -5305,10 +5305,12 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega orderBy: [{ field: 'created_at', order: 'asc' }], limit: 500, context: SYSTEM_CTX, })) ?? []; - if (approval.some((r) => r.status === 'pending' || r.status === 'returned')) return 'in_progress'; + // Open: a pending request, or a returned one in its revise window, which + // is the approval's latest (a resubmitted round stays `returned`). + const latest = approval[approval.length - 1] ?? row; + if (approval.some((r) => r.status === 'pending') || latest.status === 'returned') return 'in_progress'; const marked = approval.filter(isMarked); if (marked.length === 0) return 'judged'; - const latest = approval[approval.length - 1] ?? row; if (latest.status !== 'approved' && latest.status !== 'rejected') { await this.clearMarks(marked); return 'judged'; @@ -5505,9 +5507,24 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega where: { object_name: object, record_id: recordId, status: { $in: ['pending', 'returned'] } }, limit: 50, context: SYSTEM_CTX, }); - other = (Array.isArray(open) ? open : []).find((r: any) => - String(r?.root_run_id ?? '') !== String(latest.root_run_id ?? '') - && parseJson(r?.node_config_json, { approvers: [] } as any).approvalStatusField === field); + for (const r of Array.isArray(open) ? open : []) { + if (String(r?.root_run_id ?? '') === String(latest.root_run_id ?? '')) continue; + if (parseJson(r?.node_config_json, { approvers: [] } as any).approvalStatusField !== field) continue; + // A returned request is open only in its revise window: no later + // request of its approval on the record (a resubmitted round stays + // `returned`). + if (r.status === 'returned') { + const later = await this.engine.find('sys_approval_request', { + where: r.root_run_id + ? { root_run_id: r.root_run_id, object_name: object, record_id: recordId, created_at: { $gt: r.created_at } } + : { flow_run_id: r.flow_run_id, object_name: object, record_id: recordId, created_at: { $gt: r.created_at } }, + fields: ['id'], limit: 1, context: SYSTEM_CTX, + }); + if (Array.isArray(later) && later.length > 0) continue; + } + other = r; + break; + } } catch (err: any) { this.logger?.warn?.('[approvals] could not read whether another approval is open on the record of an abandoned one; the put-back goes ahead', { request: latest.id, object, record: recordId, error: err?.message ?? String(err), diff --git a/packages/plugins/plugin-approvals/src/approver-address-readers.test.ts b/packages/plugins/plugin-approvals/src/approver-address-readers.test.ts index 75501d513b6..2aa9c3663b9 100644 --- a/packages/plugins/plugin-approvals/src/approver-address-readers.test.ts +++ b/packages/plugins/plugin-approvals/src/approver-address-readers.test.ts @@ -168,7 +168,7 @@ const SLOT_COLUMNS = new Set(['approver', 'acted_as', 'pending_approvers']); /** The person column of `sys_approval_action` (#21411). */ const PERSON_COLUMN = 'actor_id'; -type PersonRole = 'caller-user-id' | 'display' | 'migration'; +type PersonRole = 'caller-user-id' | 'display' | 'migration' | 'attribution'; /** * Every read of `actor_id` in this package, keyed ` · { + it("a later request's `pending` refused: the request stays open, the refusal is reported, and the field keeps `pending`", async () => { await seed('crm_invoice', 'i_later'); const first = await open('two_step', 'crm_invoice', 'i_later'); hookRefuses.add('pending'); @@ -286,9 +286,10 @@ describe('[ADR-0162 item 8] a refused write of the status mirror on a field the { id: first, step: 'first', status: 'approved' }, { id: second.id, step: 'second', status: 'pending' }, ]); - // The outcome is still written at each decision on this branch; holding it - // back until the approval is over is the next piece of the item. - expect(await field('crm_invoice', 'i_later'), 'the value the field keeps').toBe('approved'); + // [ADR-0162 item 8, slice 3] The first step's decision is held back until + // the approval is over, so the field still holds the `pending` the first + // request wrote. + expect(await field('crm_invoice', 'i_later'), 'the value the field keeps').toBe('pending'); await expectReported('crm_invoice', 'i_later', second.id, 'pending', HOOK_REFUSAL); }); diff --git a/packages/plugins/plugin-approvals/src/stored-process-package-backfill.test.ts b/packages/plugins/plugin-approvals/src/stored-process-package-backfill.test.ts index ffba6519a24..ced440da7e7 100644 --- a/packages/plugins/plugin-approvals/src/stored-process-package-backfill.test.ts +++ b/packages/plugins/plugin-approvals/src/stored-process-package-backfill.test.ts @@ -172,6 +172,8 @@ describe('R7 — an open approval request gains the package that holds its flow' // ADR-0162 item 7 (the root run) adds these two, after this card. { fields: ['root_run_id', 'object_name', 'record_id'], unique: false }, { fields: ['record_run_id'], unique: false }, + // ADR-0162 item 8 (the mark) adds this one. + { fields: ['unjudged_since'], unique: false }, ])); expect((SysApprovalRequest.fields as Record).process_package).toMatchObject({ type: 'text', required: false, readonly: true, diff --git a/packages/plugins/plugin-approvals/src/translations/ar.objects.generated.ts b/packages/plugins/plugin-approvals/src/translations/ar.objects.generated.ts index 2088ab9929f..ae1412ca4c4 100644 --- a/packages/plugins/plugin-approvals/src/translations/ar.objects.generated.ts +++ b/packages/plugins/plugin-approvals/src/translations/ar.objects.generated.ts @@ -121,6 +121,10 @@ export const arObjects: NonNullable = { label: "بين الخطوات", help: "عُقد التدفق التي تقع بين خطوتين من الموافقة التي ينتمي إليها هذا الطلب." }, + unjudged_since: { + label: "غير محسوم منذ", + help: "وقت البتّ في هذا الطلب، ما دام ما يلي القرار لم يُحسم بعد." + }, node_config_json: { label: "إعداد العقدة", help: "لقطة من إعداد عقدة الموافقة (الموافِقون/السلوك) للطلبات التي تقودها العُقد." diff --git a/packages/plugins/plugin-approvals/src/translations/de.objects.generated.ts b/packages/plugins/plugin-approvals/src/translations/de.objects.generated.ts index 8bffeec4815..eb6407dc6ac 100644 --- a/packages/plugins/plugin-approvals/src/translations/de.objects.generated.ts +++ b/packages/plugins/plugin-approvals/src/translations/de.objects.generated.ts @@ -121,6 +121,10 @@ export const deObjects: NonNullable = { label: "Zwischen Schritten", help: "Flussknoten, die zwischen zwei Schritten der Genehmigung stehen, zu der diese Anfrage gehört." }, + unjudged_since: { + label: "Nicht beurteilt seit", + help: "Wann diese Anfrage entschieden wurde, solange noch nicht beurteilt ist, was auf die Entscheidung folgt." + }, node_config_json: { label: "Knotenkonfiguration", help: "Momentaufnahme der Konfiguration des Genehmigungsknotens (Genehmiger/Verhalten) bei knotengesteuerten Anfragen." diff --git a/packages/plugins/plugin-approvals/src/translations/en.objects.generated.ts b/packages/plugins/plugin-approvals/src/translations/en.objects.generated.ts index b13662521df..8b691d648b8 100644 --- a/packages/plugins/plugin-approvals/src/translations/en.objects.generated.ts +++ b/packages/plugins/plugin-approvals/src/translations/en.objects.generated.ts @@ -121,6 +121,10 @@ export const enObjects: NonNullable = { label: "Between Steps", help: "Flow nodes that stand between two steps of the approval this request belongs to." }, + unjudged_since: { + label: "Unjudged Since", + help: "When this request was decided, while what follows the decision has not been judged yet." + }, node_config_json: { label: "Node Config", help: "Snapshot of the Approval node config (approvers/behavior) for node-driven requests." diff --git a/packages/plugins/plugin-approvals/src/translations/es-ES.objects.generated.ts b/packages/plugins/plugin-approvals/src/translations/es-ES.objects.generated.ts index fc110876cf8..f9fb91e1361 100644 --- a/packages/plugins/plugin-approvals/src/translations/es-ES.objects.generated.ts +++ b/packages/plugins/plugin-approvals/src/translations/es-ES.objects.generated.ts @@ -121,6 +121,10 @@ export const esESObjects: NonNullable = { label: "Entre pasos", help: "Nodos del flujo que están entre dos pasos de la aprobación a la que pertenece esta solicitud." }, + unjudged_since: { + label: "Sin evaluar desde", + help: "Cuándo se decidió esta solicitud, mientras aún no se ha evaluado lo que sigue a la decisión." + }, node_config_json: { label: "Node Config", help: "Snapshot of the Approval node config (approvers/behavior) for node-driven requests." diff --git a/packages/plugins/plugin-approvals/src/translations/fr.objects.generated.ts b/packages/plugins/plugin-approvals/src/translations/fr.objects.generated.ts index 7f5d81ac7f9..3f00197197e 100644 --- a/packages/plugins/plugin-approvals/src/translations/fr.objects.generated.ts +++ b/packages/plugins/plugin-approvals/src/translations/fr.objects.generated.ts @@ -121,6 +121,10 @@ export const frObjects: NonNullable = { label: "Entre les étapes", help: "Nœuds du flux situés entre deux étapes de l'approbation à laquelle appartient cette demande." }, + unjudged_since: { + label: "Non évaluée depuis", + help: "Date à laquelle cette demande a été décidée, tant que la suite de la décision n'a pas encore été évaluée." + }, node_config_json: { label: "Configuration du nœud", help: "Instantané de la configuration du nœud d’approbation (approbateurs/comportement) pour les demandes pilotées par un nœud." diff --git a/packages/plugins/plugin-approvals/src/translations/ja-JP.objects.generated.ts b/packages/plugins/plugin-approvals/src/translations/ja-JP.objects.generated.ts index 59912ac12c6..df8aca292a8 100644 --- a/packages/plugins/plugin-approvals/src/translations/ja-JP.objects.generated.ts +++ b/packages/plugins/plugin-approvals/src/translations/ja-JP.objects.generated.ts @@ -121,6 +121,10 @@ export const jaJPObjects: NonNullable = { label: "ステップ間", help: "この申請が属する承認で、二つのステップの間にあるフローノード。" }, + unjudged_since: { + label: "未判定の開始日時", + help: "この申請が決定された日時。その決定に続く処理がまだ判定されていない間だけ記録されます。" + }, node_config_json: { label: "Node Config", help: "Snapshot of the Approval node config (approvers/behavior) for node-driven requests." diff --git a/packages/plugins/plugin-approvals/src/translations/ko.objects.generated.ts b/packages/plugins/plugin-approvals/src/translations/ko.objects.generated.ts index e8e20789290..a36e7e8df6f 100644 --- a/packages/plugins/plugin-approvals/src/translations/ko.objects.generated.ts +++ b/packages/plugins/plugin-approvals/src/translations/ko.objects.generated.ts @@ -121,6 +121,10 @@ export const koObjects: NonNullable = { label: "단계 사이", help: "이 요청이 속한 승인에서 두 단계 사이에 있는 플로 노드입니다." }, + unjudged_since: { + label: "미판정 시작 시각", + help: "이 요청이 결정된 시각으로, 그 결정 이후의 진행이 아직 판정되지 않은 동안 기록됩니다." + }, node_config_json: { label: "노드 구성", help: "노드 기반 요청의 승인 노드 구성(승인자/동작) 스냅숏입니다." diff --git a/packages/plugins/plugin-approvals/src/translations/pt-BR.objects.generated.ts b/packages/plugins/plugin-approvals/src/translations/pt-BR.objects.generated.ts index 085246ac1d1..48536977db7 100644 --- a/packages/plugins/plugin-approvals/src/translations/pt-BR.objects.generated.ts +++ b/packages/plugins/plugin-approvals/src/translations/pt-BR.objects.generated.ts @@ -121,6 +121,10 @@ export const ptBRObjects: NonNullable = { label: "Entre etapas", help: "Nós do fluxo que ficam entre duas etapas da aprovação à qual esta solicitação pertence." }, + unjudged_since: { + label: "Não avaliada desde", + help: "Quando esta solicitação foi decidida, enquanto o que segue a decisão ainda não foi avaliado." + }, node_config_json: { label: "Configuração do nó", help: "Instantâneo da configuração do nó de aprovação (aprovadores/comportamento) para solicitações conduzidas por nó." diff --git a/packages/plugins/plugin-approvals/src/translations/ru.objects.generated.ts b/packages/plugins/plugin-approvals/src/translations/ru.objects.generated.ts index d8bcf649534..37e4895ac26 100644 --- a/packages/plugins/plugin-approvals/src/translations/ru.objects.generated.ts +++ b/packages/plugins/plugin-approvals/src/translations/ru.objects.generated.ts @@ -121,6 +121,10 @@ export const ruObjects: NonNullable = { label: "Между шагами", help: "Узлы потока, стоящие между двумя шагами согласования, к которому относится этот запрос." }, + unjudged_since: { + label: "Не оценено с", + help: "Когда по этому запросу было принято решение, пока то, что следует за решением, ещё не оценено." + }, node_config_json: { label: "Конфигурация узла", help: "Снимок конфигурации узла согласования (согласующие/поведение) для запросов, запускаемых узлом." diff --git a/packages/plugins/plugin-approvals/src/translations/zh-CN.objects.generated.ts b/packages/plugins/plugin-approvals/src/translations/zh-CN.objects.generated.ts index ea9abebff29..34a3c318b97 100644 --- a/packages/plugins/plugin-approvals/src/translations/zh-CN.objects.generated.ts +++ b/packages/plugins/plugin-approvals/src/translations/zh-CN.objects.generated.ts @@ -121,6 +121,10 @@ export const zhCNObjects: NonNullable = { label: "步骤之间", help: "审批中位于两个步骤之间的流程节点。" }, + unjudged_since: { + label: "待判定起始时间", + help: "此请求被决定的时间;在此决定之后的流程尚未判定时记录。" + }, node_config_json: { label: "Node Config", help: "Snapshot of the Approval node config (approvers/behavior) for node-driven requests." diff --git a/packages/plugins/plugin-approvals/src/translations/zh-Hant.objects.generated.ts b/packages/plugins/plugin-approvals/src/translations/zh-Hant.objects.generated.ts index ef80bead5ac..2b4c6bb8517 100644 --- a/packages/plugins/plugin-approvals/src/translations/zh-Hant.objects.generated.ts +++ b/packages/plugins/plugin-approvals/src/translations/zh-Hant.objects.generated.ts @@ -121,6 +121,10 @@ export const zhHantObjects: NonNullable = { label: "步驟之間", help: "審批中位於兩個步驟之間的流程節點。" }, + unjudged_since: { + label: "待判定起始時間", + help: "此請求被決定的時間;在此決定之後的流程尚未判定時記錄。" + }, node_config_json: { label: "節點設定", help: "由節點驅動之請求的核准節點設定(核准人/行為)快照。" From 47f42865a1517f27f02e579115248a0e00b081aa Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 07:43:02 +0000 Subject: [PATCH 24/32] fix(approvals): the door also reads the latest request's own run, for a subflow body's routed failure; census regenerated Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5pigknx7rC8rXnA3my --- .../plugins/plugin-approvals.md | 18 +++---- ...utcome-when-over-37767.integration.test.ts | 13 +++++ .../plugin-approvals/src/approval-service.ts | 50 +++++++++++++------ 3 files changed, 58 insertions(+), 23 deletions(-) diff --git a/docs/audits/2026-08-tenant-audit-write-call-sites.counts/plugins/plugin-approvals.md b/docs/audits/2026-08-tenant-audit-write-call-sites.counts/plugins/plugin-approvals.md index b3808a404c1..607d59f8519 100644 --- a/docs/audits/2026-08-tenant-audit-write-call-sites.counts/plugins/plugin-approvals.md +++ b/docs/audits/2026-08-tenant-audit-write-call-sites.counts/plugins/plugin-approvals.md @@ -14,24 +14,24 @@ a row or a number here — fix the code, or the census, and regenerate. | Measure | Value | |---|---:| -| Write call sites | 45 | -| Object name statically decidable | 43 | +| Write call sites | 49 | +| Object name statically decidable | 47 | | Object name chosen at run time | 2 | -| Object name spelled inline | 41 | +| Object name spelled inline | 45 | | Object name spelled through a `const` | 2 | | Object name is an `object: string` parameter | 1 | | Object name is some other run-time expression | 1 | -| Against a tenancy-enabled object | 43 | +| Against a tenancy-enabled object | 47 | | Against an object declaring tenancy off | 0 | -| Threading a tenant context | 45 | +| Threading a tenant context | 49 | | Provably carrying none (options read, no context key) | 0 | | …and decidably tenancy-enabled | 0 | | Options argument unreadable | 0 | | …and decidably tenancy-enabled | 0 | -| Threading a decidably elevated (`isSystem`) context | 43 | +| Threading a decidably elevated (`isSystem`) context | 47 | | Threading a decidably non-elevated context | 0 | | Threading a context of undecidable elevation | 2 | -| Receiver carried a readable engine type | 45 | +| Receiver carried a readable engine type | 49 | | Receiver erased, placed by the object NAME | 0 | | Receiver erased, placed by an `object: string` PARAMETER | 0 | | Receiver erased, placed by an `UNTYPED_RECEIVERS` row | 0 | @@ -50,11 +50,11 @@ a row or a number here — fix the code, or the census, and regenerate. | `packages/plugins/plugin-approvals/src/action-slot-backfill.ts` | `update` | `sys_approval_action` | enabled | elevated | 2 | | `packages/plugins/plugin-approvals/src/approval-activity-feed.ts` | `insert` | `sys_activity` | enabled | elevated | 1 | | `packages/plugins/plugin-approvals/src/approval-service.ts` | `update` | `object` | undecidable | context, elevation undecidable | 1 | -| `packages/plugins/plugin-approvals/src/approval-service.ts` | `insert` | `sys_approval_action` | enabled | elevated | 19 | +| `packages/plugins/plugin-approvals/src/approval-service.ts` | `insert` | `sys_approval_action` | enabled | elevated | 20 | | `packages/plugins/plugin-approvals/src/approval-service.ts` | `delete` | `sys_approval_approver` | enabled | elevated | 2 | | `packages/plugins/plugin-approvals/src/approval-service.ts` | `insert` | `sys_approval_approver` | enabled | elevated | 2 | | `packages/plugins/plugin-approvals/src/approval-service.ts` | `insert` | `sys_approval_request` | enabled | elevated | 1 | -| `packages/plugins/plugin-approvals/src/approval-service.ts` | `update` | `sys_approval_request` | enabled | elevated | 11 | +| `packages/plugins/plugin-approvals/src/approval-service.ts` | `update` | `sys_approval_request` | enabled | elevated | 14 | | `packages/plugins/plugin-approvals/src/approval-service.ts` | `insert` | `sys_approval_token` | enabled | elevated | 1 | | `packages/plugins/plugin-approvals/src/approval-service.ts` | `update` | `sys_approval_token` | enabled | elevated | 1 | | `packages/plugins/plugin-approvals/src/backfill-platform-row-organizations.ts` | `update` | `objectPlan.object` | undecidable | context, elevation undecidable | 1 | diff --git a/packages/plugins/plugin-approvals/src/approval-outcome-when-over-37767.integration.test.ts b/packages/plugins/plugin-approvals/src/approval-outcome-when-over-37767.integration.test.ts index fdbdc7e45de..ebcd807abe4 100644 --- a/packages/plugins/plugin-approvals/src/approval-outcome-when-over-37767.integration.test.ts +++ b/packages/plugins/plugin-approvals/src/approval-outcome-when-over-37767.integration.test.ts @@ -100,6 +100,9 @@ const FLOWS = [ [edge('start', 'first'), edge('first', 'boom', 'approve'), edge('first', 'end', 'reject'), edge('boom', 'second'), edge('boom', 'end', undefined, 'fault'), ...decided('second', 'end')]), flow('boom_between', [step('first', 'approver'), mark('boom'), step('second', 'approver2')], [edge('start', 'first'), edge('first', 'boom', 'approve'), edge('first', 'end', 'reject'), edge('boom', 'second'), ...decided('second', 'end')]), + // The same two steps in a `subflow` child, whose steps the parent's run does not log. + flow('parent_of_boom', [{ id: 'sub', type: 'subflow', label: 'Approval', config: { flowName: 'boom_between_fault_end' } }], + [edge('start', 'sub'), edge('sub', 'end')]), // That node's failure handled in a try_catch region, after which a gateway ends the flow. flow('boom_handled', [step('first', 'approver'), { id: 'guard', type: 'try_catch', label: 'Guard', config: { try: { nodes: [mark('boom')], edges: [] }, catch: { nodes: [mark('handled')], edges: [] } } }, @@ -432,6 +435,16 @@ describe('[ADR-0162 item 8] the outcome is written when the approval is over', ( expect((await timeline(String(first.id))).at(-1)![2]).toMatch(/its node 'boom' failed between two steps/); }); + it('in a subflow child, with a fault edge to the child\'s end: abandoned, read off the child\'s own run', async () => { + await start('parent_of_boom', 'crm_invoice', 'i_child'); + throwOn.add('boom'); + await decide('i_child', 'approve', 'approver'); + const [first] = await requestsOn('i_child'); + expect(first.flow_run_id, 'the request is the child run\'s').not.toBe(first.record_run_id); + expect((await automation.getRun(String(first.record_run_id)))?.status).toBe('completed'); + expect(await field('crm_invoice', 'i_child')).toBe('recalled'); + }); + it('handled in a try_catch region, after which a gateway ends the flow: finished', async () => { await start('boom_handled', 'crm_invoice', 'i_handled'); throwOn.add('boom'); diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index 97ef2cf320c..cde5a60e96e 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -5441,25 +5441,47 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega }; } // A failure the flow routed, at the top level of the run, on a node of the - // set, after which no request of the approval opened. + // set, after which no request of the approval opened; or a stop on a node + // of the set. Read on the run that carries the record, and on the latest + // request's own run where that is another (a `subflow` body runs in a + // child run of its own, whose steps the carrying run does not log). const instant = (v: unknown): number => (v == null || v === '' ? NaN : new Date(v as string).getTime()); const lastOpened = approval.reduce((acc, r) => { const at = instant(r?.created_at); return Number.isFinite(at) && at > acc ? at : acc; }, -Infinity); - const routed = steps.find((s) => s?.status === 'failure' - && !s.parentNodeId - && typeof s.nodeId === 'string' - && s.nodeId !== stoppedAt - && standsBetweenSteps(stamp, flow, s.nodeId) - && !(instant(s.startedAt) < lastOpened)); - if (routed) { - return { answer: 'abandoned', why: `its node '${String(routed.nodeId)}' failed between two steps, and the flow went on to its end without asking the next step.` }; - } - if (status !== 'paused' && status !== 'completed') { - if (!stoppedAt) return { answer: 'abandoned', why: `its run ended ${status}, at a node the plugin cannot place.` }; - if (standsBetweenSteps(stamp, flow, stoppedAt)) { - return { answer: 'abandoned', why: `its run ended ${status} at node '${stoppedAt}', between two steps.` }; + const endedBetween = ( + log: ReadonlyArray<{ nodeId?: unknown; status?: unknown; parentNodeId?: unknown; startedAt?: unknown }>, + logFlow: string | undefined, + logStatus: string, + stop: string | undefined, + ): string | undefined => { + const routed = log.find((s) => s?.status === 'failure' + && !s.parentNodeId + && typeof s.nodeId === 'string' + && s.nodeId !== stop + && standsBetweenSteps(stamp, logFlow, s.nodeId) + && !(instant(s.startedAt) < lastOpened)); + if (routed) return `its node '${String(routed.nodeId)}' failed between two steps, and the flow went on to its end without asking the next step.`; + if (logStatus === 'paused' || logStatus === 'completed') return undefined; + if (!stop) return `its run ended ${logStatus}, at a node the plugin cannot place.`; + if (standsBetweenSteps(stamp, logFlow, stop)) return `its run ended ${logStatus} at node '${stop}', between two steps.`; + return undefined; + }; + const carried = endedBetween(steps, flow, status, stoppedAt); + if (carried) return { answer: 'abandoned', why: carried }; + const ownRunId = latest.flow_run_id != null ? String(latest.flow_run_id) : ''; + if (ownRunId && ownRunId !== runId) { + let own: { status?: string; flowName?: string; steps?: unknown } | null = null; + try { own = await automation.getRun(ownRunId); } catch { own = null; } + const ownStatus = typeof own?.status === 'string' ? own.status : ''; + if (own && TERMINAL_RUN_STATUSES.has(ownStatus)) { + const ownSteps = (Array.isArray(own.steps) ? own.steps : []) as typeof steps; + const failed = ownStatus === 'completed' ? undefined + : ([...ownSteps].reverse().find((s) => s?.status === 'failure' && !s.parentNodeId) ?? ownSteps[ownSteps.length - 1]); + const ownStop = failed && typeof failed.nodeId === 'string' ? failed.nodeId : undefined; + const inChild = endedBetween(ownSteps, typeof own.flowName === 'string' ? own.flowName : undefined, ownStatus, ownStop); + if (inChild) return { answer: 'abandoned', why: inChild }; } } return { answer: 'finished' }; From 1ada3a4ed06f92d7dbff7bce1e9a9da6e5765b54 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 08:15:52 +0000 Subject: [PATCH 25/32] fix(approvals): say the object closes on its approval field only where a gap is about that field The host's gap and an unreadable flow are raised on an object that declares closedStates on any field; where they are the only gaps, the opening refusal's lead now says the approval can act on an object that declares closedStates, in all 11 locale packs of the plugin's catalog. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5phEgfPTCgvPqh4ER2 --- .changeset/37766-opening-lead.md | 12 ++++ .../src/approval-opening-refusal.test.ts | 72 +++++++++++++++++++ .../src/approval-opening-refusal.ts | 14 +++- .../src/translations/messages.ts | 11 +++ 4 files changed, 108 insertions(+), 1 deletion(-) create mode 100644 .changeset/37766-opening-lead.md create mode 100644 packages/plugins/plugin-approvals/src/approval-opening-refusal.test.ts diff --git a/.changeset/37766-opening-lead.md b/.changeset/37766-opening-lead.md new file mode 100644 index 00000000000..41fcfa5b582 --- /dev/null +++ b/.changeset/37766-opening-lead.md @@ -0,0 +1,12 @@ +--- +'@objectstack/plugin-approvals': patch +--- + +fix(approvals): the opening refusal no longer says the object closes on its approval field when its only gaps are the host's or an unreadable flow + +Clause-②: yes (widening) +Metadata-protocol: none + +Widened: the plugin's message catalog gains the sentence `approvalOpeningRefusedClosedStatesLead` in all 11 locale packs. + +An approval's first request is refused when an object it can act on declares `closedStates` and the host runs no job service, or when a flow it runs cannot be read. Those gaps are raised whatever field the object closes on. The refusal's lead used to say "the object closes on its approval field" in every case, which is false for an object that closes on another field. Where every gap is one of those two, the lead now says only what is true: the approval can act on an object that declares `closedStates`. The sentences per gap are unchanged. diff --git a/packages/plugins/plugin-approvals/src/approval-opening-refusal.test.ts b/packages/plugins/plugin-approvals/src/approval-opening-refusal.test.ts new file mode 100644 index 00000000000..a0036fc52ff --- /dev/null +++ b/packages/plugins/plugin-approvals/src/approval-opening-refusal.test.ts @@ -0,0 +1,72 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 Execution item 7] The lead of the refusal at an approval's first + * request says the object closes on its approval field only where a gap is + * about that field. The host's gap (`no_job_service`) and a flow that could + * not be read (`unreadable_flow`) are raised on an object that declares + * `closedStates` on any field, so where they are the only gaps the lead says + * what is true in every case: the approval can act on an object that declares + * `closedStates`. + * + * The expected sentences are read from the catalog, not written out here: what + * these tests hold is WHICH lead is chosen, and in which pack; the wording is + * the catalog's, and `approval-notification-text.test.ts` holds every locale + * to the same ids and holes. + */ + +import { describe, expect, it } from 'vitest'; +import { interpolate } from './approval-notification-text.js'; +import type { OpeningGap } from './approval-opening-check.js'; +import { openingRefusalText } from './approval-opening-refusal.js'; +import { approvalMessages } from './translations/messages.js'; + +const subject = { object: 'crm_deal', record: 'd1' }; +type Locale = keyof typeof approvalMessages; +const fieldLead = (locale: Locale) => interpolate(approvalMessages[locale].approvalOpeningRefusedLead, subject); +const neutralLead = (locale: Locale) => interpolate(approvalMessages[locale].approvalOpeningRefusedClosedStatesLead, subject); +const sentence = (gap: OpeningGap, id: 'approvalOpeningNoJobService' | 'approvalOpeningUnreadableFlow') => { + const { kind: _kind, ...params } = gap; + return interpolate(approvalMessages.en[id], params as Record); +}; + +const host: OpeningGap = { kind: 'no_job_service', object: 'crm_deal' }; +const unreadable: OpeningGap = { kind: 'unreadable_flow', flow: 'deal_sub' }; +const pause: OpeningGap = { kind: 'pause_between_steps', flow: 'deal_flow', node: 'hold', type: 'wait', object: 'crm_deal' }; + +describe('the opening refusal: its lead', () => { + it('the two leads are two sentences, in every pack', () => { + for (const locale of Object.keys(approvalMessages) as Locale[]) { + expect(neutralLead(locale), locale).not.toBe(fieldLead(locale)); + } + }); + + it('does not say the object closes on its approval field where the host\'s gap is the only one', () => { + const text = openingRefusalText([host], subject, 'en'); + expect(text).toBe(`${neutralLead('en')} ${sentence(host, 'approvalOpeningNoJobService')}`); + }); + + it('does not say it where a flow that could not be read is the only gap', () => { + const text = openingRefusalText([unreadable], subject, 'en'); + expect(text).toBe(`${neutralLead('en')} ${sentence(unreadable, 'approvalOpeningUnreadableFlow')}`); + }); + + it('does not say it where the host\'s gap and an unreadable flow are the only gaps', () => { + const text = openingRefusalText([unreadable, host], subject, 'en'); + expect(text.startsWith(`${neutralLead('en')} `)).toBe(true); + expect(text).not.toContain(fieldLead('en')); + }); + + it('says it where a gap is about the field, alone or beside the host\'s', () => { + expect(openingRefusalText([pause], subject, 'en').startsWith(`${fieldLead('en')} `)).toBe(true); + expect(openingRefusalText([pause, host], subject, 'en').startsWith(`${fieldLead('en')} `)).toBe(true); + expect(openingRefusalText([host, pause], subject, 'en').startsWith(`${fieldLead('en')} `)).toBe(true); + }); + + it('words the lead that says nothing about the field in the run\'s locale', () => { + const text = openingRefusalText([host], subject, 'zh-CN'); + expect(text.startsWith(`${neutralLead('zh-CN')} `)).toBe(true); + expect(text).not.toContain(fieldLead('zh-CN')); + expect(neutralLead('zh-CN')).not.toBe(neutralLead('en')); + }); +}); diff --git a/packages/plugins/plugin-approvals/src/approval-opening-refusal.ts b/packages/plugins/plugin-approvals/src/approval-opening-refusal.ts index 3018bdec513..fa1b1a4a64e 100644 --- a/packages/plugins/plugin-approvals/src/approval-opening-refusal.ts +++ b/packages/plugins/plugin-approvals/src/approval-opening-refusal.ts @@ -44,6 +44,14 @@ export function openingRefusalPack(locale: string | undefined): Pack { return same ? packs[same]! : approvalMessages.en; } +/** + * The gaps that say nothing about the approval field: the host's, and a flow + * that could not be read. Where every gap is one of these, the lead does not + * say the object closes on its approval field, which may be false: an object + * can declare `closedStates` on another field. + */ +const NOT_ABOUT_THE_FIELD: ReadonlySet = new Set(['no_job_service', 'unreadable_flow']); + /** The refusal text for `gaps`, on the record `subject`, in `locale`. */ export function openingRefusalText( gaps: readonly OpeningGap[], @@ -51,7 +59,11 @@ export function openingRefusalText( locale?: string, ): string { const pack = openingRefusalPack(locale); - const lead = interpolate(pack.approvalOpeningRefusedLead, { object: subject.object, record: subject.record }); + const aboutTheField = gaps.some((gap) => !NOT_ABOUT_THE_FIELD.has(gap.kind)); + const lead = interpolate( + aboutTheField ? pack.approvalOpeningRefusedLead : pack.approvalOpeningRefusedClosedStatesLead, + { object: subject.object, record: subject.record }, + ); const sentences = gaps.map((gap) => { const { kind, ...params } = gap; return interpolate(pack[GAP_SENTENCE[kind]], params as Record); diff --git a/packages/plugins/plugin-approvals/src/translations/messages.ts b/packages/plugins/plugin-approvals/src/translations/messages.ts index ee99b8e5e41..1b11c1744e4 100644 --- a/packages/plugins/plugin-approvals/src/translations/messages.ts +++ b/packages/plugins/plugin-approvals/src/translations/messages.ts @@ -123,6 +123,7 @@ const enSentences = { approvalStatusMirrorRefusedTitle: 'Approval status not written', approvalStatusMirrorRefusedBody: 'The approval status of {{object}} {{record}} was refused by a rule or hook of the app: {{reason}} Change that rule or hook so the status can be written.', approvalOpeningRefusedLead: 'The approval of {{object}} {{record}} was not started: the object closes on its approval field, and the approval cannot show itself in progress there.', + approvalOpeningRefusedClosedStatesLead: 'The approval of {{object}} {{record}} was not started: it can act on an object that declares closedStates.', approvalOpeningNoPendingOption: 'Field {{field}} of {{object}} (step {{step}} of flow {{flow}}) does not declare the value pending; add it to the field\'s options.', approvalOpeningClosesInFlight: '{{object}} closes on {{value}} of field {{field}} (step {{step}} of flow {{flow}}), a status of an approval in progress; remove {{value}} from the object\'s closedStates.', approvalOpeningStateMachine: 'The state_machine rule {{rule}} on field {{field}} of {{object}} (step {{step}} of flow {{flow}}) declares the moves out of {{value}} without pending; add pending to them.', @@ -270,6 +271,7 @@ export const zhCNMessages: ApprovalMessages = { approvalStatusMirrorRefusedTitle: '审批状态未能写入', approvalStatusMirrorRefusedBody: '{{object}} {{record}} 的审批状态被应用自己的规则或钩子拒绝:{{reason}} 请修改该规则或钩子,使状态可以写入。', approvalOpeningRefusedLead: '{{object}} {{record}} 的审批没有发起:该对象会在审批字段上关闭,而这次审批无法在该字段上显示「审批中」。', + approvalOpeningRefusedClosedStatesLead: '{{object}} {{record}} 的审批没有发起:它可能作用到一个声明了 closedStates 的对象。', approvalOpeningNoPendingOption: '{{object}} 的字段 {{field}}(流程 {{flow}} 的步骤 {{step}})没有声明值 pending;请把它加入该字段的选项。', approvalOpeningClosesInFlight: '{{object}} 在字段 {{field}} 的 {{value}} 上关闭(流程 {{flow}} 的步骤 {{step}}),而这是审批进行中的状态;请把 {{value}} 从对象的 closedStates 中去掉。', approvalOpeningStateMachine: '{{object}} 字段 {{field}} 上的 state_machine 规则 {{rule}}(流程 {{flow}} 的步骤 {{step}})声明了从 {{value}} 出发的转移,但其中没有 pending;请加上 pending。', @@ -354,6 +356,7 @@ export const jaJPMessages: ApprovalMessages = { approvalStatusMirrorRefusedTitle: '承認ステータスを書き込めませんでした', approvalStatusMirrorRefusedBody: '{{object}} {{record}} の承認ステータスは、アプリのルールまたはフックに拒否されました:{{reason}} ステータスを書き込めるよう、そのルールまたはフックを変更してください。', approvalOpeningRefusedLead: '{{object}} {{record}} の承認は開始されませんでした:このオブジェクトは承認フィールドでクローズしますが、この承認はそのフィールドに承認中を表示できません。', + approvalOpeningRefusedClosedStatesLead: '{{object}} {{record}} の承認は開始されませんでした:この承認は closedStates を宣言するオブジェクトに作用する可能性があります。', approvalOpeningNoPendingOption: '{{object}} のフィールド {{field}}(フロー {{flow}} のステップ {{step}})は値 pending を宣言していません。フィールドの選択肢に追加してください。', approvalOpeningClosesInFlight: '{{object}} はフィールド {{field}} の {{value}} でクローズします(フロー {{flow}} のステップ {{step}})。これは進行中の承認のステータスです。{{value}} をオブジェクトの closedStates から外してください。', approvalOpeningStateMachine: '{{object}} のフィールド {{field}} にある state_machine ルール {{rule}}(フロー {{flow}} のステップ {{step}})は {{value}} からの遷移を宣言していますが、pending が含まれていません。pending を追加してください。', @@ -438,6 +441,7 @@ export const esESMessages: ApprovalMessages = { approvalStatusMirrorRefusedTitle: 'No se escribió el estado de aprobación', approvalStatusMirrorRefusedBody: 'Una regla o un hook de la aplicación rechazó el estado de aprobación de {{object}} {{record}}: {{reason}} Cambie esa regla o ese hook para que el estado pueda escribirse.', approvalOpeningRefusedLead: 'No se inició la aprobación de {{object}} {{record}}: el objeto se cierra en su campo de aprobación y la aprobación no puede mostrarse en curso en él.', + approvalOpeningRefusedClosedStatesLead: 'No se inició la aprobación de {{object}} {{record}}: puede actuar sobre un objeto que declara closedStates.', approvalOpeningNoPendingOption: 'El campo {{field}} de {{object}} (paso {{step}} del flujo {{flow}}) no declara el valor pending; añádalo a las opciones del campo.', approvalOpeningClosesInFlight: '{{object}} se cierra en {{value}} del campo {{field}} (paso {{step}} del flujo {{flow}}), un estado de una aprobación en curso; quite {{value}} de los closedStates del objeto.', approvalOpeningStateMachine: 'La regla state_machine {{rule}} del campo {{field}} de {{object}} (paso {{step}} del flujo {{flow}}) declara las transiciones desde {{value}} sin pending; añada pending.', @@ -522,6 +526,7 @@ export const zhHantMessages: ApprovalMessages = { approvalStatusMirrorRefusedTitle: '核准狀態未能寫入', approvalStatusMirrorRefusedBody: '{{object}} {{record}} 的核准狀態被應用程式自己的規則或掛鉤拒絕:{{reason}} 請修改該規則或掛鉤,讓狀態可以寫入。', approvalOpeningRefusedLead: '{{object}} {{record}} 的核准沒有發起:該物件會在核准欄位上關閉,而這次核准無法在該欄位上顯示「核准中」。', + approvalOpeningRefusedClosedStatesLead: '{{object}} {{record}} 的核准沒有發起:它可能作用到一個宣告了 closedStates 的物件。', approvalOpeningNoPendingOption: '{{object}} 的欄位 {{field}}(流程 {{flow}} 的步驟 {{step}})沒有宣告值 pending;請把它加入該欄位的選項。', approvalOpeningClosesInFlight: '{{object}} 在欄位 {{field}} 的 {{value}} 上關閉(流程 {{flow}} 的步驟 {{step}}),而這是核准進行中的狀態;請把 {{value}} 從物件的 closedStates 中移除。', approvalOpeningStateMachine: '{{object}} 欄位 {{field}} 上的 state_machine 規則 {{rule}}(流程 {{flow}} 的步驟 {{step}})宣告了從 {{value}} 出發的轉移,但其中沒有 pending;請加上 pending。', @@ -606,6 +611,7 @@ export const arMessages: ApprovalMessages = { approvalStatusMirrorRefusedTitle: 'لم تُكتب حالة الموافقة', approvalStatusMirrorRefusedBody: 'رفضت قاعدة أو خطّاف في التطبيق حالة الموافقة على {{object}} {{record}}: {{reason}} غيّر تلك القاعدة أو ذلك الخطّاف لكي تُكتب الحالة.', approvalOpeningRefusedLead: 'لم تبدأ الموافقة على {{object}} {{record}}: الكائن يُغلَق على حقل الموافقة، والموافقة لا تستطيع أن تُظهر فيه أنها جارية.', + approvalOpeningRefusedClosedStatesLead: 'لم تبدأ الموافقة على {{object}} {{record}}: قد تعمل على كائن يُعلن closedStates.', approvalOpeningNoPendingOption: 'الحقل {{field}} في {{object}} (الخطوة {{step}} من التدفق {{flow}}) لا يصرّح بالقيمة pending؛ أضفها إلى خيارات الحقل.', approvalOpeningClosesInFlight: 'يُغلَق {{object}} على القيمة {{value}} من الحقل {{field}} (الخطوة {{step}} من التدفق {{flow}})، وهي حالة موافقة جارية؛ أزل {{value}} من closedStates للكائن.', approvalOpeningStateMachine: 'قاعدة state_machine {{rule}} على الحقل {{field}} في {{object}} (الخطوة {{step}} من التدفق {{flow}}) تصرّح بالانتقالات من {{value}} دون pending؛ أضف pending.', @@ -690,6 +696,7 @@ export const frMessages: ApprovalMessages = { approvalStatusMirrorRefusedTitle: 'Statut d’approbation non écrit', approvalStatusMirrorRefusedBody: 'Une règle ou un hook de l’application a refusé le statut d’approbation de {{object}} {{record}} : {{reason}} Modifiez cette règle ou ce hook pour que le statut puisse être écrit.', approvalOpeningRefusedLead: 'L\'approbation de {{object}} {{record}} n\'a pas été lancée : l\'objet se ferme sur son champ d\'approbation, et l\'approbation ne peut pas s\'y afficher en cours.', + approvalOpeningRefusedClosedStatesLead: 'L\'approbation de {{object}} {{record}} n\'a pas été lancée : elle peut agir sur un objet qui déclare closedStates.', approvalOpeningNoPendingOption: 'Le champ {{field}} de {{object}} (étape {{step}} du flux {{flow}}) ne déclare pas la valeur pending ; ajoutez-la aux options du champ.', approvalOpeningClosesInFlight: '{{object}} se ferme sur {{value}} du champ {{field}} (étape {{step}} du flux {{flow}}), un statut d\'approbation en cours ; retirez {{value}} des closedStates de l\'objet.', approvalOpeningStateMachine: 'La règle state_machine {{rule}} du champ {{field}} de {{object}} (étape {{step}} du flux {{flow}}) déclare les transitions depuis {{value}} sans pending ; ajoutez pending.', @@ -774,6 +781,7 @@ export const ptBRMessages: ApprovalMessages = { approvalStatusMirrorRefusedTitle: 'Status de aprovação não gravado', approvalStatusMirrorRefusedBody: 'Uma regra ou um hook do aplicativo recusou o status de aprovação de {{object}} {{record}}: {{reason}} Altere essa regra ou esse hook para que o status possa ser gravado.', approvalOpeningRefusedLead: 'A aprovação de {{object}} {{record}} não foi iniciada: o objeto é fechado no seu campo de aprovação, e a aprovação não consegue se mostrar em andamento nele.', + approvalOpeningRefusedClosedStatesLead: 'A aprovação de {{object}} {{record}} não foi iniciada: ela pode agir sobre um objeto que declara closedStates.', approvalOpeningNoPendingOption: 'O campo {{field}} de {{object}} (etapa {{step}} do fluxo {{flow}}) não declara o valor pending; adicione-o às opções do campo.', approvalOpeningClosesInFlight: '{{object}} é fechado em {{value}} do campo {{field}} (etapa {{step}} do fluxo {{flow}}), um status de aprovação em andamento; remova {{value}} dos closedStates do objeto.', approvalOpeningStateMachine: 'A regra state_machine {{rule}} no campo {{field}} de {{object}} (etapa {{step}} do fluxo {{flow}}) declara as transições a partir de {{value}} sem pending; adicione pending.', @@ -858,6 +866,7 @@ export const ruMessages: ApprovalMessages = { approvalStatusMirrorRefusedTitle: 'Статус согласования не записан', approvalStatusMirrorRefusedBody: 'Правило или хук приложения отклонили статус согласования для {{object}} {{record}}: {{reason}} Измените это правило или хук, чтобы статус можно было записать.', approvalOpeningRefusedLead: 'Согласование {{object}} {{record}} не запущено: объект закрывается по своему полю согласования, а согласование не может показать в нём, что оно идёт.', + approvalOpeningRefusedClosedStatesLead: 'Согласование {{object}} {{record}} не запущено: оно может действовать на объект, который объявляет closedStates.', approvalOpeningNoPendingOption: 'Поле {{field}} объекта {{object}} (шаг {{step}} процесса {{flow}}) не объявляет значение pending; добавьте его в варианты поля.', approvalOpeningClosesInFlight: '{{object}} закрывается на значении {{value}} поля {{field}} (шаг {{step}} процесса {{flow}}), а это статус идущего согласования; уберите {{value}} из closedStates объекта.', approvalOpeningStateMachine: 'Правило state_machine {{rule}} на поле {{field}} объекта {{object}} (шаг {{step}} процесса {{flow}}) объявляет переходы из {{value}} без pending; добавьте pending.', @@ -942,6 +951,7 @@ export const deMessages: ApprovalMessages = { approvalStatusMirrorRefusedTitle: 'Genehmigungsstatus nicht geschrieben', approvalStatusMirrorRefusedBody: 'Eine Regel oder ein Hook der App hat den Genehmigungsstatus von {{object}} {{record}} abgelehnt: {{reason}} Ändern Sie diese Regel oder diesen Hook, damit der Status geschrieben werden kann.', approvalOpeningRefusedLead: 'Die Genehmigung von {{object}} {{record}} wurde nicht gestartet: Das Objekt schließt auf seinem Genehmigungsfeld, und die Genehmigung kann sich dort nicht als laufend zeigen.', + approvalOpeningRefusedClosedStatesLead: 'Die Genehmigung von {{object}} {{record}} wurde nicht gestartet: Sie kann auf ein Objekt wirken, das closedStates deklariert.', approvalOpeningNoPendingOption: 'Das Feld {{field}} von {{object}} (Schritt {{step}} des Flows {{flow}}) deklariert den Wert pending nicht; fügen Sie ihn den Optionen des Feldes hinzu.', approvalOpeningClosesInFlight: '{{object}} schließt auf {{value}} des Feldes {{field}} (Schritt {{step}} des Flows {{flow}}), einem Status einer laufenden Genehmigung; entfernen Sie {{value}} aus den closedStates des Objekts.', approvalOpeningStateMachine: 'Die state_machine-Regel {{rule}} auf dem Feld {{field}} von {{object}} (Schritt {{step}} des Flows {{flow}}) deklariert die Übergänge aus {{value}} ohne pending; fügen Sie pending hinzu.', @@ -1026,6 +1036,7 @@ export const koMessages: ApprovalMessages = { approvalStatusMirrorRefusedTitle: '승인 상태를 기록하지 못했습니다', approvalStatusMirrorRefusedBody: '앱의 규칙 또는 훅이 {{object}} {{record}}의 승인 상태를 거부했습니다: {{reason}} 상태를 기록할 수 있도록 해당 규칙 또는 훅을 변경하세요.', approvalOpeningRefusedLead: '{{object}} {{record}}의 승인이 시작되지 않았습니다: 이 개체는 승인 필드에서 닫히는데, 이 승인은 그 필드에 진행 중임을 표시할 수 없습니다.', + approvalOpeningRefusedClosedStatesLead: '{{object}} {{record}}의 승인이 시작되지 않았습니다: 이 승인은 closedStates를 선언한 개체에 작용할 수 있습니다.', approvalOpeningNoPendingOption: '{{object}}의 필드 {{field}}(흐름 {{flow}}의 단계 {{step}})는 값 pending을 선언하지 않습니다. 필드의 옵션에 추가하세요.', approvalOpeningClosesInFlight: '{{object}}는 필드 {{field}}의 {{value}}에서 닫힙니다(흐름 {{flow}}의 단계 {{step}}). 이는 진행 중인 승인의 상태입니다. 개체의 closedStates에서 {{value}}를 제거하세요.', approvalOpeningStateMachine: '{{object}}의 필드 {{field}}에 있는 state_machine 규칙 {{rule}}(흐름 {{flow}}의 단계 {{step}})은 {{value}}에서 나가는 전이를 선언하지만 pending이 없습니다. pending을 추가하세요.', From cf61012af8a260135d512b7cecf5c063a68ec1a2 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 08:20:12 +0000 Subject: [PATCH 26/32] test(approvals): name the test that holds every locale to the same ids and holes Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5phEgfPTCgvPqh4ER2 --- .../plugin-approvals/src/approval-opening-refusal.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/plugins/plugin-approvals/src/approval-opening-refusal.test.ts b/packages/plugins/plugin-approvals/src/approval-opening-refusal.test.ts index a0036fc52ff..5ea0e31c29b 100644 --- a/packages/plugins/plugin-approvals/src/approval-opening-refusal.test.ts +++ b/packages/plugins/plugin-approvals/src/approval-opening-refusal.test.ts @@ -11,7 +11,7 @@ * * The expected sentences are read from the catalog, not written out here: what * these tests hold is WHICH lead is chosen, and in which pack; the wording is - * the catalog's, and `approval-notification-text.test.ts` holds every locale + * the catalog's, and `approval-notification-keyed-text.integration.test.ts` holds every locale * to the same ids and holes. */ From 2668361c1b12b3c7504dd8ee2311ef1c2c6fa78c Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 08:54:37 +0000 Subject: [PATCH 27/32] fix(approvals): the opening refusal's log line says the object closes on its approval field only where a gap is about that field The service's warn line at every opening refusal now chooses its wording by the same predicate as the refusal's lead, exported from approval-opening-refusal.ts, so a refusal whose only gaps are the host's or an unreadable flow no longer logs that the object closes on its approval field. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5phEgfPTCgvPqh4ER2 --- ...al-opening-check-37766.integration.test.ts | 32 +++++++++++++++++-- .../src/approval-opening-refusal.ts | 12 +++++-- .../plugin-approvals/src/approval-service.ts | 6 ++-- 3 files changed, 44 insertions(+), 6 deletions(-) diff --git a/packages/plugins/plugin-approvals/src/approval-opening-check-37766.integration.test.ts b/packages/plugins/plugin-approvals/src/approval-opening-check-37766.integration.test.ts index 33fe0a448a9..f298162934b 100644 --- a/packages/plugins/plugin-approvals/src/approval-opening-check-37766.integration.test.ts +++ b/packages/plugins/plugin-approvals/src/approval-opening-check-37766.integration.test.ts @@ -92,7 +92,7 @@ describe('[ADR-0162 item 7] the check when an approval opens', () => { try { await kernel?.shutdown(); } catch { /* noop */ } }); - async function boot(opts: { sweeps?: boolean; invoiceDef?: Record } = {}) { + async function boot(opts: { sweeps?: boolean; invoiceDef?: Record; warns?: string[] } = {}) { kernel = new ObjectKernel({ logger: { level: 'silent' } } as any); await kernel.use(new ObjectQLPlugin()); await kernel.use(new AutomationServicePlugin()); @@ -118,7 +118,9 @@ describe('[ADR-0162 item 7] the check when an approval opens', () => { await ql.insert('sys_member', { id: `mem_${id}`, user_id: id, organization_id: ORG, role: 'member' }, { context: SYS }); } const quiet = { debug: () => {}, info: () => {}, warn: () => {}, error: () => {} }; - svc = new ApprovalService({ engine: ql, logger: quiet as any }); + const sink = opts.warns; + const serviceLogger = sink ? { ...quiet, warn: (message: string) => { sink.push(message); } } : quiet; + svc = new ApprovalService({ engine: ql, logger: serviceLogger as any }); if (opts.sweeps !== false) svc.noteSweepClockScheduled(); svc.attachAutomation(automation as any); registerApprovalNode(automation as any, svc, quiet as any); @@ -229,4 +231,30 @@ describe('[ADR-0162 item 7] the check when an approval opens', () => { await seed('crm_memo', 'm_host'); expect((await start('two_step', 'crm_memo', 'm_host')).status).toBe('paused'); }); + + describe('the log line at a refusal says the object closes on its approval field only where a gap is about it', () => { + const FIELD_CLAIM = 'closes on its approval field'; + const refusalWarns = (warns: string[]) => warns.filter((w) => w.includes('was refused at its first request')); + + it('does not say it where the host\'s gap is the only one', async () => { + const warns: string[] = []; + await boot({ sweeps: false, warns }); + await seed('crm_invoice', 'i_host_log'); + expect((await start('two_step', 'crm_invoice', 'i_host_log')).status).toBe('failed'); + const logged = refusalWarns(warns); + expect(logged).toHaveLength(1); + expect(logged[0]).not.toContain(FIELD_CLAIM); + expect(logged[0]).toContain('declares closedStates'); + }); + + it('says it where a gap is about the field (control)', async () => { + const warns: string[] = []; + await boot({ warns }); + await seed('crm_invoice', 'i_wait_log'); + expect((await start('wait_between', 'crm_invoice', 'i_wait_log')).status).toBe('failed'); + const logged = refusalWarns(warns); + expect(logged).toHaveLength(1); + expect(logged[0]).toContain(FIELD_CLAIM); + }); + }); }); diff --git a/packages/plugins/plugin-approvals/src/approval-opening-refusal.ts b/packages/plugins/plugin-approvals/src/approval-opening-refusal.ts index fa1b1a4a64e..6251c07bab4 100644 --- a/packages/plugins/plugin-approvals/src/approval-opening-refusal.ts +++ b/packages/plugins/plugin-approvals/src/approval-opening-refusal.ts @@ -52,6 +52,15 @@ export function openingRefusalPack(locale: string | undefined): Pack { */ const NOT_ABOUT_THE_FIELD: ReadonlySet = new Set(['no_job_service', 'unreadable_flow']); +/** + * Whether any of `gaps` is about the approval field, so that "the object + * closes on its approval field" is true of the refusal. The one rule for every + * text that says so: the refusal's lead here, and the service's log line. + */ +export function gapsAreAboutTheField(gaps: readonly OpeningGap[]): boolean { + return gaps.some((gap) => !NOT_ABOUT_THE_FIELD.has(gap.kind)); +} + /** The refusal text for `gaps`, on the record `subject`, in `locale`. */ export function openingRefusalText( gaps: readonly OpeningGap[], @@ -59,9 +68,8 @@ export function openingRefusalText( locale?: string, ): string { const pack = openingRefusalPack(locale); - const aboutTheField = gaps.some((gap) => !NOT_ABOUT_THE_FIELD.has(gap.kind)); const lead = interpolate( - aboutTheField ? pack.approvalOpeningRefusedLead : pack.approvalOpeningRefusedClosedStatesLead, + gapsAreAboutTheField(gaps) ? pack.approvalOpeningRefusedLead : pack.approvalOpeningRefusedClosedStatesLead, { object: subject.object, record: subject.record }, ); const sentences = gaps.map((gap) => { diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index 6b0c526b581..99f0f848903 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -180,7 +180,7 @@ import { consolePageLink, type ConsolePageComposer } from './public-base-url.js' import { APPROVAL_EMAIL_CHANNELS, EMAILED_APPROVAL_TOPICS } from './approval-email-templates.js'; import { enMessages } from './translations/messages.js'; import { closedValuesOf, judgeApprovalOpening, type OpeningFlow } from './approval-opening-check.js'; -import { openingRefusalText } from './approval-opening-refusal.js'; +import { gapsAreAboutTheField, openingRefusalText } from './approval-opening-refusal.js'; import { approvalMessageKey, approvalNotificationText, @@ -5252,7 +5252,9 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega }); if (judgement.gaps.length > 0) { const locale = input.locale ?? (context as { locale?: string } | undefined)?.locale; - this.logger?.warn?.('[approvals] an approval was refused at its first request: the record\'s object closes on its approval field and the approval cannot show it in progress (ADR-0162 D5)', { + this.logger?.warn?.(gapsAreAboutTheField(judgement.gaps) + ? '[approvals] an approval was refused at its first request: the record\'s object closes on its approval field and the approval cannot show it in progress (ADR-0162 D5)' + : '[approvals] an approval was refused at its first request: it can act on an object that declares closedStates, and this host runs no job service or a flow it runs could not be read (ADR-0162 D5)', { object: input.object, record: input.recordId, run: input.runId, rootRun: rootRun.runId, gaps: judgement.gaps.map((g) => g.kind), }); From a5d0d155f8089a548d38a1a50c35b407d21d5c41 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 09:00:16 +0000 Subject: [PATCH 28/32] test(approvals): the held-back decision and the advancing run each have an observation an ablation turns red The two-step case now records every value written to the field: the second step's opening writes `pending` straight after the first decision, so the field read alone could not tell a held-back decision from a written one. The two cannot-tell cases assert the reason the door logs, since a run that is advancing and a status the plugin does not place answer alike. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5pigknx7rC8rXnA3my --- ...utcome-when-over-37767.integration.test.ts | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/packages/plugins/plugin-approvals/src/approval-outcome-when-over-37767.integration.test.ts b/packages/plugins/plugin-approvals/src/approval-outcome-when-over-37767.integration.test.ts index ebcd807abe4..f1d621e56a1 100644 --- a/packages/plugins/plugin-approvals/src/approval-outcome-when-over-37767.integration.test.ts +++ b/packages/plugins/plugin-approvals/src/approval-outcome-when-over-37767.integration.test.ts @@ -137,6 +137,7 @@ describe('[ADR-0162 item 8] the outcome is written when the approval is over', ( /** What each `read` node saw on the record's field. */ let seen: unknown[]; let notices: Array<{ topic: string; audience: string[] }>; + let infos: string[]; afterEach(async () => { try { await kernel?.shutdown(); } catch { /* noop */ } @@ -171,7 +172,9 @@ describe('[ADR-0162 item 8] the outcome is written when the approval is over', ( await ql.insert('sys_member', { id: `mem_${id}`, user_id: id, organization_id: ORG, role: 'member' }, { context: SYS }); } const quiet = { debug: () => {}, info: () => {}, warn: () => {}, error: () => {} }; - svc = new ApprovalService({ engine: ql, logger: quiet as any }); + infos = []; + const heard = { ...quiet, info: (m: unknown) => { infos.push(String(m)); } }; + svc = new ApprovalService({ engine: ql, logger: heard as any }); svc.noteSweepClockScheduled(); svc.attachMessaging({ emit: async (n: any) => { notices.push({ topic: n.topic, audience: n.audience }); } } as any); svc.attachAutomation(automation as any); @@ -213,6 +216,15 @@ describe('[ADR-0162 item 8] the outcome is written when the approval is over', ( describe('the decision is held back, and written when the approval is over', () => { it('two steps approved: the field reads pending after the first and approved once the run ends; marks are set and cleared', async () => { + // Every value written to the field, in order: the second step's opening + // writes `pending` straight after the first decision, so the field read + // alone cannot tell a held-back decision from a written one. + const written: unknown[] = []; + const update = ql.update.bind(ql); + (ql as any).update = async (object: string, data: any, opts?: any) => { + if (object === 'crm_invoice' && data?.id === 'i_two' && 'approval_status' in data) written.push(data.approval_status); + return update(object, data, opts); + }; expect((await start('two_step', 'crm_invoice', 'i_two')).status).toBe('paused'); await decide('i_two', 'approve', 'approver'); expect(await steps('i_two')).toEqual([['first', 'approved'], ['second', 'pending']]); @@ -221,6 +233,7 @@ describe('[ADR-0162 item 8] the outcome is written when the approval is over', ( await decide('i_two', 'approve', 'approver2'); expect(await field('crm_invoice', 'i_two')).toBe('approved'); + expect(written, 'the first decision was never written onto the record').toEqual(['pending', 'pending', 'approved']); expect(await marks('i_two'), 'judged: no mark stands').toEqual([false, false]); }); @@ -514,6 +527,9 @@ describe('[ADR-0162 item 8] the outcome is written when the approval is over', ( await decide('i_busy', 'approve', 'approver2'); expect(await field('crm_invoice', 'i_busy')).toBe('pending'); expect(await marks('i_busy')).toEqual([false, true]); + // The reason names the advancing run, not only an unplaced status: the + // two answer alike, and only the reason tells them apart. + expect(infos.some((m) => m.includes('i_busy') && m.includes("is running, so another process may be advancing it"))).toBe(true); }); it('a run that cannot be read: nothing is written, and the mark stays', async () => { @@ -523,6 +539,7 @@ describe('[ADR-0162 item 8] the outcome is written when the approval is over', ( await decide('i_unread', 'approve', 'approver2'); expect(await field('crm_invoice', 'i_unread')).toBe('pending'); expect(await marks('i_unread')).toEqual([false, true]); + expect(infos.some((m) => m.includes('i_unread') && m.includes('could not be read (store down)'))).toBe(true); }); }); }); From a3b666ce0f924639fb77cdc71f371608f79d4982 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 09:14:32 +0000 Subject: [PATCH 29/32] fix(approvals): where a run stopped is its last top-level step, and a refusing end is an end A run that ends on an `end` declaring `outcome: 'refused'` reached an end of the flow, as a completed run did; it logs no step for the `end`, so its last step is the approval just decided and was read as a stop between two steps, abandoning a rejection. A cancelled run, or one failed by a child or settled as unresumable, logs nothing after the node it stood on, so the stop is its last top-level step; an earlier failure the flow routed on is no longer taken for it. The approval's requests are read newest first, so the latest is in the window however many there are, and an auto-rejection the door abandoned no longer also sends the auto-rejected notice. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5pigknx7rC8rXnA3my --- ...utcome-when-over-37767.integration.test.ts | 34 +++++++++++++ .../plugin-approvals/src/approval-service.ts | 49 ++++++++++++++----- 2 files changed, 72 insertions(+), 11 deletions(-) diff --git a/packages/plugins/plugin-approvals/src/approval-outcome-when-over-37767.integration.test.ts b/packages/plugins/plugin-approvals/src/approval-outcome-when-over-37767.integration.test.ts index f1d621e56a1..08297d72bc1 100644 --- a/packages/plugins/plugin-approvals/src/approval-outcome-when-over-37767.integration.test.ts +++ b/packages/plugins/plugin-approvals/src/approval-outcome-when-over-37767.integration.test.ts @@ -120,6 +120,14 @@ const FLOWS = [ flow('second_revise_spent', [step('first', 'approver'), step('second', 'approver2', { maxRevisions: 0 }), { id: 'revise', type: APPROVAL_REVISE_NODE_TYPE, label: 'Revise' }], [edge('start', 'first'), ...decided('first', 'second'), ...decided('second', 'end'), edge('second', 'revise', 'revise'), { id: 'back', source: 'revise', target: 'second', label: 'resubmit', type: 'back' }]), + // The first step's reject edge to an `end` that refuses: the run ends `refused`, an `end` logging no step. + flow('refuse_on_reject', [step('first', 'approver'), step('second', 'approver2'), + { id: 'refuse', type: 'end', label: 'Refuse', config: { outcome: 'refused', message: 'Refused' } }], + [edge('start', 'first'), edge('first', 'second', 'approve'), edge('first', 'refuse', 'reject'), ...decided('second', 'end')]), + // A node before the first step fails and is routed on; the first step is in a `subflow` child, the second after it. + flow('child_one_step', [step('only', 'approver')], [edge('start', 'only'), edge('only', 'end', 'approve'), edge('only', 'end', 'reject')]), + flow('early_fault_then_sub', [mark('early'), { id: 'sub', type: 'subflow', label: 'Approval', config: { flowName: 'child_one_step' } }, step('second', 'approver2')], + [edge('start', 'early'), edge('early', 'sub'), edge('early', 'sub', undefined, 'fault'), edge('sub', 'second'), ...decided('second', 'end')]), // A batch whose items are records, each approved in its own run of `item_step`. flow('item_step', [step('only', 'approver'), mark('after')], [edge('start', 'only'), edge('only', 'after', 'approve'), edge('only', 'end', 'reject'), edge('after', 'end')]), { name: 'batch', label: 'batch', type: 'autolaunched', variables: [{ name: 'items', type: 'list', isInput: true }], @@ -518,6 +526,32 @@ describe('[ADR-0162 item 8] the outcome is written when the approval is over', ( }); }); + describe('where a run stopped', () => { + it('a run that ends on a refusing end is finished: the rejection is written, not abandoned', async () => { + await start('refuse_on_reject', 'crm_invoice', 'i_refused'); + await decide('i_refused', 'reject', 'approver'); + const [only] = await requestsOn('i_refused'); + expect((await automation.getRun(String(only.record_run_id)))?.status).toBe('refused'); + expect(await field('crm_invoice', 'i_refused')).toBe('rejected'); + expect(await marks('i_refused')).toEqual([false]); + expect(notices.some((n) => n.topic === 'approval.abandoned')).toBe(false); + expect(notices.filter((n) => n.topic === 'approval.rejected').map((n) => n.audience)).toEqual([['owner']]); + }); + + it('a cancelled run stopped where it stood, not at an earlier failure the flow routed on: abandoned', async () => { + throwOn.add('early'); + await start('early_fault_then_sub', 'crm_invoice', 'i_cancel'); + const [child] = await requestsOn('i_cancel'); + expect(child.flow_run_id, 'the request is the child run\'s').not.toBe(child.record_run_id); + await automation.cancelRun(String(child.record_run_id)); + await settle(decide('i_cancel', 'approve', 'approver')); + expect((await automation.getRun(String(child.record_run_id)))?.status).toBe('cancelled'); + expect(await steps('i_cancel'), 'the second step was never asked').toEqual([['only', 'approved']]); + expect(await field('crm_invoice', 'i_cancel'), 'stopped at the subflow, between two steps').toBe('recalled'); + expect(await marks('i_cancel')).toEqual([false]); + }); + }); + describe('cannot tell', () => { it('a run another process is advancing: nothing is written, and the mark stays', async () => { await start('two_step', 'crm_invoice', 'i_busy'); diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index cde5a60e96e..65fcbcc58df 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -1869,6 +1869,33 @@ const LATER_STEP_NOT_OPENED_KEY = '__laterStepNotOpened'; /** The run statuses a run reports while it is being advanced, or is about to be. */ const ADVANCING_RUN_STATUSES: ReadonlySet = new Set(['pending', 'running', 'retrying']); +/** + * [ADR-0162 Execution item 8] The terminal statuses of a run that reached an + * `end` the flow declares: `completed`, and `refused` (an `end` with + * `outcome: 'refused'`, a successful evaluation that said no). Such a run + * stopped nowhere between two steps, so the door reads it as finished, a + * failure it routed on the way apart. An `end` logs no step of its own, so + * the last step of a refused run is the node before it, often the approval + * that was just decided, and must not be read as where the run stopped. + */ +const REACHED_AN_END: ReadonlySet = new Set(['completed', 'refused']); + +/** + * [ADR-0162 Execution item 8] Where a terminal run stopped, read off its step + * log: the last step at the top level of the run (one that ran in no + * `loop`, `parallel` or `try_catch` region), else the last step. An + * unrouted failure is the last step a run logs, and a run that was cancelled, + * failed by a child's failure or settled as unresumable logs nothing after + * the node it stood on, so the last step names the node in every case; an + * earlier failure that the flow routed on is not where the run stopped. + * `undefined` for a run that reached an `end` ({@link REACHED_AN_END}). + */ +function stopOf(log: ReadonlyArray<{ nodeId?: unknown; parentNodeId?: unknown }>, status: string): string | undefined { + if (REACHED_AN_END.has(status)) return undefined; + const last = [...log].reverse().find((s) => !s?.parentNodeId) ?? log[log.length - 1]; + return last && typeof last.nodeId === 'string' ? last.nodeId : undefined; +} + /** * [ADR-0162 Execution item 8] What the door answered for an approval after it * resumed or cancelled one of its runs (`ApprovalService.judgeApprovalAfterDoor`). @@ -5302,9 +5329,12 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega const approval: any[] = (await this.engine.find('sys_approval_request', { where: { root_run_id: row.root_run_id, object_name: row.object_name, record_id: row.record_id }, - orderBy: [{ field: 'created_at', order: 'asc' }], + orderBy: [{ field: 'created_at', order: 'desc' }], limit: 500, context: SYSTEM_CTX, })) ?? []; + // Newest first, so the latest is in the window however many requests + // the approval has; read oldest first below. + approval.reverse(); // Open: a pending request, or a returned one in its revise window, which // is the approval's latest (a resubmitted round stays `returned`). const latest = approval[approval.length - 1] ?? row; @@ -5426,10 +5456,8 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega if (standsBetweenSteps(stamp, parked.flowName ?? flow, parked.nodeId)) return { answer: 'in_progress' }; } else if (!TERMINAL_RUN_STATUSES.has(status)) { return { answer: 'undetermined', why: `the run '${runId}' reports the status '${status}', which the plugin does not place.`, runId }; - } else if (status !== 'completed') { - const failed = [...steps].reverse().find((s) => s?.status === 'failure' && !s.parentNodeId); - const last = failed ?? steps[steps.length - 1]; - stoppedAt = last && typeof last.nodeId === 'string' ? last.nodeId : undefined; + } else { + stoppedAt = stopOf(steps, status); } const config = parseJson>(latest.node_config_json, {}); @@ -5463,7 +5491,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega && standsBetweenSteps(stamp, logFlow, s.nodeId) && !(instant(s.startedAt) < lastOpened)); if (routed) return `its node '${String(routed.nodeId)}' failed between two steps, and the flow went on to its end without asking the next step.`; - if (logStatus === 'paused' || logStatus === 'completed') return undefined; + if (logStatus === 'paused' || REACHED_AN_END.has(logStatus)) return undefined; if (!stop) return `its run ended ${logStatus}, at a node the plugin cannot place.`; if (standsBetweenSteps(stamp, logFlow, stop)) return `its run ended ${logStatus} at node '${stop}', between two steps.`; return undefined; @@ -5477,9 +5505,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega const ownStatus = typeof own?.status === 'string' ? own.status : ''; if (own && TERMINAL_RUN_STATUSES.has(ownStatus)) { const ownSteps = (Array.isArray(own.steps) ? own.steps : []) as typeof steps; - const failed = ownStatus === 'completed' ? undefined - : ([...ownSteps].reverse().find((s) => s?.status === 'failure' && !s.parentNodeId) ?? ownSteps[ownSteps.length - 1]); - const ownStop = failed && typeof failed.nodeId === 'string' ? failed.nodeId : undefined; + const ownStop = stopOf(ownSteps, ownStatus); const inChild = endedBetween(ownSteps, typeof own.flowName === 'string' ? own.flowName : undefined, ownStatus, ownStop); if (inChild) return { answer: 'abandoned', why: inChild }; } @@ -9047,8 +9073,9 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega resumeError = outcome.resumeError; } // [ADR-0162 Execution item 8] The auto-rejection is a decision: the door judges the approval. - await this.judgeApprovalAfterDoor(raw, 'the auto-rejection', { requestId: String(requestId), actorId: actingUserId(context) }); - if (raw.submitter_id) { + // An abandoned approval has told its submitter already, on its own topic. + const judged = await this.judgeApprovalAfterDoor(raw, 'the auto-rejection', { requestId: String(requestId), actorId: actingUserId(context) }); + if (raw.submitter_id && judged !== 'abandoned') { await this.notify({ topic: 'approval.returned', organizationId: raw.organization_id, From aae6cb05836c6d0700ff7c8f38c36333ef75e538 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 09:33:32 +0000 Subject: [PATCH 30/32] docs(approvals): approvals on an object that declares closedStates What the check at an approval's first request asks of the mirror field and the flow, what a refused opening is for the submitter, what an abandoned approval leaves, and how an approval that does not mirror onto the closing field and an approval per map item behave. Read against the trunk's approvals plugin and ADR-0162 as revised. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5phEgfPTCgvPqh4ER2 --- content/docs/automation/approvals.mdx | 190 +++++++++++++++++++++++++- 1 file changed, 189 insertions(+), 1 deletion(-) diff --git a/content/docs/automation/approvals.mdx b/content/docs/automation/approvals.mdx index 9adaf844c92..e12d0d4f765 100644 --- a/content/docs/automation/approvals.mdx +++ b/content/docs/automation/approvals.mdx @@ -1410,6 +1410,194 @@ in-flight request, `reassign` hands one slot to another user directly. - Forget rejection paths - Hard-code approvers +## Approvals on an object that declares `closedStates` [#closed-states] + +An object can declare [`closedStates`](/docs/references/data/object) (ADR-0162): +values of its own `select` fields on which a record and its direct +`master_detail` lines are closed to every caller that is not a system context, +who is refused `409 RECORD_LOCKED`. The approval status mirror writes in a system +context, so it can move such a record: the `pending` of a new approval takes a +document off a closed `approved`. That is why the platform asks more of an +approval on such an object, and what this section describes. In an application +where no object declares `closedStates`, none of it applies and nothing is read. + +### Which approvals are judged, and when + +An approval here is one passage of a record through its approval flow, taken +whole: the run started for the record and every child run under it, a `subflow` +body or an item of a `map`, to any depth. It holds one request for each step it +reaches, and one more each time a returned request is resubmitted. ADR-0044 +numbers those resubmissions as the rounds of a request, and the word means +nothing else on this page. + +The platform judges an approval once, at its first request, before anything is +written. It reads every approval step of the flow the record's run was started +on and of every flow a `subflow` or a `map` in it names, to any depth, each with +its own `approvalStatusField` and every object it can act on: the record's +object, and under a `map` the object the node names for its items as well. A +later request of the same approval is not judged again, since refusing it would +end the approval between two steps that were already decided. Nor is a request +the platform cannot place as first or later, which is a request of an approval +whose earlier requests were opened before requests recorded the run they +belong to. So an approval that was in flight when its object first declared +`closedStates` is not held to what follows. + +A step is **concerned** where the object closes on its mirror field at a status +the mirror writes for a request that is not abandoned: `pending`, `returned`, +`approved` or `rejected`. An object that closes on that field only on values of +its own, such as `paid` or `void`, is asked none of the field and flow +conditions below. + +### What the mirror field owes + +For every concerned step, the step's mirror field: + +- **declares `pending`**, and the object closes on **neither `pending` nor + `returned`**. Those are the statuses of a request in flight, and the revise + window of a returned request opens on `returned` (ADR-0044). +- has **`pending` among the moves out of a closed `approved` or `rejected`**, + wherever a `state_machine` rule on the field declares those moves. A new + approval of a decided document opens it by writing `pending`. +- carries **no `readonlyWhen`**, and **no `visibleWhen` on its options for a + request's status** (`pending`, `returned`, `approved`, `rejected`, + `recalled`). The platform does not evaluate those predicates ahead, and on a + record where one holds it takes away a write the mirror needs. Keep callers + off a mirror field with `readonly`, which the mirror passes. + +The field's other rules and hooks cannot be read ahead, and they meet every +write of the mirror. A `state_machine` rule on the field owes the mirror its +other moves as well: from `pending` to each outcome, and out of `pending` and +`returned` when a request is abandoned. Where the object closes on the field at +`approved` or `rejected`, a write of the mirror that a rule or a hook refuses is +not swallowed: + +- **The `pending` of an approval's first request.** The approval does not open. + The request just written is voided as `cancelled`, its timeline carries the + refusal, no lock is taken, and the run fails at that step with the refusal's + own message. The record keeps the value it held. +- **Any other write.** The field keeps the value it holds, and the refusal is + reported three ways: an `error` line in the server log, a line with no actor on + the request's timeline that carries the refusal's message, and a notice to the + organization's administrators, who can change the rule. + +### What the flow owes + +- **One mirror field for every step.** Every approval step that can act on a + record of the object names the same mirror field as the concerned step. A + step that names another field, or none, refuses the approval, whether it comes + ahead of the concerned step or after it. A step in a `map` body counts as one + that can act on the parent's record, unless the node writes its items out and + every one of them is a record. +- **No pause between two steps.** *Between two steps* means after a step is + decided, either way, and before the next step opens. The next step can be the + same step opened again, so in a `map` or a `loop` body that holds a step, a + node after the body's last step stands between two steps too. No node that can + pause the run of itself may stand there, in a flow that runs as the user or in + one that runs as system: a `wait` or a `screen` there would hold the document + in approval with nobody asked to decide. The platform reads this off the node + type's descriptor (`supportsPause`), and reads a `subflow` or a `map` through + the body it calls. The revise window of a returned request (`approval_revise`) + is not such a pause. +- **A node type without a descriptor.** A node whose type publishes no + descriptor counts as one that can pause, and so does a node whose type the + platform cannot read: such a node between two approval steps refuses the + approval. The structural types `start` and `end` have no executor and never + pause, so the `end` of a `map` body or of a `subflow` body refuses nothing. +- **No `map` of approvals on the parent's record.** Where a concerned step can + act on the parent's record, the approval holds no `map` with an approval step + in its body, at any depth, unless the node writes its items out and none of + them is a record. An item that is a record has its request filed on the item, + and the parent's run waits on it as it would on a pause. A parent run that + carries no record, such as a batch sign-off that hands a `map` its items, is + not refused on this ground. +- **Readable whole.** Every flow a `subflow` or a `map` names is one the + platform can read. An approval it cannot read whole cannot be judged, and is + refused. + +One more ground is the host's, not the author's. An approval any step of which +can act on an object that declares `closedStates`, concerned or not, opens only +on a host that runs the approvals plugin's sweeps, which needs a `job` service. +The sweeps are what release a record held by a dead run, below. + +### An approval that does not mirror onto the closing field + +An approval none of whose steps mirrors onto a field the object closes on is +asked none of the field and flow conditions, only the host's. It moves nothing on +the closing field, so it does not open a closed document: a record that is closed +stays closed through it, on the value its last writer left, and every caller's +edit of it is refused, in the revise window after a send-back as well. Such an +approval is not a way out of the closed state. Where a closed document should +not be sent for approval at all, gate the flow's start on the state. + +### Each item under a `map` is an approval of its own record + +Under a `map` whose items are records, each item's request is filed on that +item, on the object the node names for its items, and what follows is judged for +that record alone: + +- the item object's closed values and mirror field are judged, with the rest of + the approval, at the approval's first request; +- the submitter is told an item's outcome without waiting for the items after it; +- when an item's request is abandoned, only the requests on that item's record + count, never another item's (below). + +### What a refused opening is for the person who submitted + +When the check refuses, the approval does not open: no request is written, +nothing is mirrored, no lock is taken, and nobody is asked to decide. The +approval node fails the run with a `VALIDATION_FAILED` error, and that failed run +is what the person who submitted sees. Its message names the record whose +approval was not started, and then, for each gap, the flow, the step, the object, +the field and what is missing. Its lead says that the object closes on its +approval field only where a gap concerns that field; where the only gaps are the +host's or a flow that could not be read, the lead says instead that the approval +can act on an object that declares `closedStates`. The message is in the run's +locale where the plugin carries it, and in English otherwise. The record keeps the +value it held, and the server log carries a warning that names the gaps. + +Nothing in the message is the submitter's to fix: every gap is the app's +configuration or the host's. Whoever maintains the app fixes the field, the flow +or the host, and the submitter then submits again. + +### What an abandoned approval leaves + +Three writers abandon a request: its submitter's recall, of a pending request or +of a returned one in its revise window; an administrator's override of a pending +request, the override arm of the same recall; and the sweep that releases a +record held by a dead run. Each records `recalled` on the request. Where the +object closes on the mirror field at any value, one of its own or a status, an +abandoned request never writes a closed value of that field: + +1. **A closed value the approval did not write is left alone.** Where the field + holds a closed value that no request of this approval on this record had as + its status, another writer put it there, and the mirror writes nothing. A + request of the same approval on another record, another item of a `map`, does + not count. +2. **Otherwise `recalled`**, where the field declares it, or declares no options, + and the object does not close on it. +3. **Otherwise the first usable value in this order:** the value the field 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. On a required + field an empty value at submit is passed over for the default. + +So listing `recalled` among the field's closed values closes nothing through the +mirror: a withdrawn approval leaves the record open. A record that was closed +when it was submitted, and that the approval opened, is left open on the value a +never-submitted record carries, its default or empty. To close a withdrawn +document, use an action or a flow of the app's own. To show a withdrawn approval +on the record, declare `recalled` among the field's options and do not close on +it. + +Where the platform cannot tell whether the approval wrote the closed value the +field holds, because the abandoned request, or one opened on the record since the +approval's run started, does not record the run it belongs to, it goes down the +order. The server log says when the mirror withholds a declared `recalled` (a +warning) and when it passes over a closed value or leaves one alone. On a +required field that is not `readonly`, with no default the mirror can use, the +write of empty is refused: the field keeps the value it holds, and the refusal is +logged, and reported as above where the object closes on the field at `approved` +or `rejected`. + ## Why Separating *who configures* from *who approves* from *as whom it runs* is the same capability/assignment/requirement decoupling as the rest of authorization (ADR-0066). The `runAs` default of `user` means an approval flow can't silently grant the submitter cross-tenant or cross-owner reach — elevation is opt-in and auditable. That is the safe-by-default posture: the common case respects RLS; the elevated case is explicit. @@ -1427,6 +1615,6 @@ Separating *who configures* from *who approves* from *as whom it runs* is the sa ## See also -- Decision records: **ADR-0049** (`runAs`), **ADR-0066** (unified authorization). +- Decision records: **ADR-0049** (`runAs`), **ADR-0066** (unified authorization), **ADR-0044** (send-back and resubmission), **ADR-0162** (closed states and the approvals on them). - Guide: [Hooks](/docs/automation/hooks) and [Flows](/docs/automation/flows); [Who can see data / automation / interface](/docs/permissions/access-recipes). - Reference: [Flow](/docs/references/automation/flow), [Approval](/docs/references/automation/approval). From 1b5824c01e3e04cdcfc54670fd9c842b96518c89 Mon Sep 17 00:00:00 2001 From: "objectstack-fleet[bot]" <332303061+objectstack-fleet[bot]@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:22:52 +0800 Subject: [PATCH 31/32] feat(lint): an approval's closed-state gap is refused at every authoring door, through the first request's one judge (ADR-0162 item 7, slice N45) (#38562) --- ...6-approval-closed-states-authoring-rule.md | 14 + .../37766-opening-judge-metadata-core.md | 10 + .../37766-opening-judge-plugin-approvals.md | 10 + content/docs/automation/approvals.mdx | 26 + ...cord-and-its-lines-are-closed-to-change.md | 25 +- packages/lint/src/finding-user-text.ts | 2 + packages/lint/src/index.ts | 7 + .../src/reference-integrity-suite.test.ts | 3 + .../lint/src/reference-integrity-suite.ts | 16 + ...untime-gate.approval-closed-states.test.ts | 114 +++ .../src/runtime-gate.object-writes.test.ts | 6 + .../validate-approval-closed-states.test.ts | 142 ++++ .../src/validate-approval-closed-states.ts | 191 +++++ ...lidate-approval-closed-states.user-text.ts | 183 +++++ .../src/approval-opening.test.ts | 67 ++ .../metadata-core/src/approval-opening.ts | 719 ++++++++++++++++++ packages/metadata-core/src/index.ts | 5 + ...al-closed-states-37766.integration.test.ts | 155 ++++ .../approval-closed-states-sentences.test.ts | 48 ++ .../src/approval-opening-check.ts | 656 +--------------- 20 files changed, 1762 insertions(+), 637 deletions(-) create mode 100644 .changeset/37766-approval-closed-states-authoring-rule.md create mode 100644 .changeset/37766-opening-judge-metadata-core.md create mode 100644 .changeset/37766-opening-judge-plugin-approvals.md create mode 100644 packages/lint/src/runtime-gate.approval-closed-states.test.ts create mode 100644 packages/lint/src/validate-approval-closed-states.test.ts create mode 100644 packages/lint/src/validate-approval-closed-states.ts create mode 100644 packages/lint/src/validate-approval-closed-states.user-text.ts create mode 100644 packages/metadata-core/src/approval-opening.test.ts create mode 100644 packages/metadata-core/src/approval-opening.ts create mode 100644 packages/plugins/plugin-approvals/src/approval-closed-states-37766.integration.test.ts create mode 100644 packages/plugins/plugin-approvals/src/approval-closed-states-sentences.test.ts diff --git a/.changeset/37766-approval-closed-states-authoring-rule.md b/.changeset/37766-approval-closed-states-authoring-rule.md new file mode 100644 index 00000000000..a89a93a2bab --- /dev/null +++ b/.changeset/37766-approval-closed-states-authoring-rule.md @@ -0,0 +1,14 @@ +--- +'@objectstack/lint': patch +--- + +feat(lint): an approval that cannot show itself in progress on a field its object closes on is refused where it is authored (ADR-0162 D5) + +Clause-②: yes (widening) +Metadata-protocol: none + +Widened: `@objectstack/lint` exports `validateApprovalClosedStates`, `approvalRootObjectsOf`, `APPROVAL_CLOSED_STATE_GAP` and the type `ApprovalClosedStateFinding`; the rule's sentences are registered in all 11 platform locales. + +A new member of the reference-integrity suite, `validateApprovalClosedStates` (finding `approval-closed-state-gap`, at error), judges each flow of a stack as the root of an approval, on each object it can start on a record of, through the one judge the approvals plugin's first request asks (`judgeApprovalOpeningSync`, `@objectstack/metadata-core`). `os validate`, `os build` and `os lint` refuse the gap on a project's stack, and the runtime publish door (Studio, REST `/meta`, MCP) refuses it with `INVALID_METADATA` (422) on a `flow` or an `object` write: an active save, a draft's promotion, a restore and a package publish (a draft save is not refused). An `object` write judges the written package's live flows and is charged only with a gap it adds. In a package publish each draft is judged against the batch's objects, and a flow the batch redrafts is judged as its draft, so a package that declares `closedStates` and repairs its flow in the same publish passes. The rule refuses only what it has in view: a call to a flow the stack does not hold, a node type the spec does not ship and a host with no `job` service are not refused here, and are judged at the approval's first request, which stays the rule. An object that declares no `closedStates` is judged nowhere. + +Why the protocol line reads none: the rule reads only `closedStates`, which this release adds. No object a released version accepts declares it, so nothing that could be published before is refused now. diff --git a/.changeset/37766-opening-judge-metadata-core.md b/.changeset/37766-opening-judge-metadata-core.md new file mode 100644 index 00000000000..545d0778953 --- /dev/null +++ b/.changeset/37766-opening-judge-metadata-core.md @@ -0,0 +1,10 @@ +--- +'@objectstack/metadata-core': patch +--- + +feat(metadata-core): the judge of an approval's opening conditions on a closing field lives here, so every door asks one copy (ADR-0162 D5) + +Clause-②: yes (widening) +Metadata-protocol: none + +Widened: `@objectstack/metadata-core` exports the judge the approvals plugin's first-request check used to hold, `judgeApprovalOpening` (it awaits each flow it reads), with `judgeApprovalOpeningSync` (over a stack in hand: a flow read that answers a promise counts as a flow it cannot read), the walk both drive, `approvalFlowWalk`, and the helper and types they read (`closedValuesOf`, `OpeningCheckSource`, `OpeningFlow`, `OpeningFlowBody`, `OpeningGap`, `OpeningJudgement` and the rest). `OpeningCheckSource.calleeFlow` may answer a flow or a promise of one. The verdict and its gaps are unchanged; nothing an author writes changes. diff --git a/.changeset/37766-opening-judge-plugin-approvals.md b/.changeset/37766-opening-judge-plugin-approvals.md new file mode 100644 index 00000000000..1f4f4cfe96b --- /dev/null +++ b/.changeset/37766-opening-judge-plugin-approvals.md @@ -0,0 +1,10 @@ +--- +'@objectstack/plugin-approvals': patch +--- + +refactor(approvals): the first-request check asks the opening judge in `@objectstack/metadata-core` (ADR-0162 D5) + +Clause-②: no +Metadata-protocol: none + +The check an approval's first request makes on a field its object closes on now calls `judgeApprovalOpening` from `@objectstack/metadata-core`, the same judge the authoring rule `validateApprovalClosedStates` asks. `approval-opening-check.ts` re-exports it and its types under the names it exported before. Which approvals open, the refusal and its sentences are unchanged. diff --git a/content/docs/automation/approvals.mdx b/content/docs/automation/approvals.mdx index e12d0d4f765..3639c51f278 100644 --- a/content/docs/automation/approvals.mdx +++ b/content/docs/automation/approvals.mdx @@ -1559,6 +1559,32 @@ Nothing in the message is the submitter's to fix: every gap is the app's configuration or the host's. Whoever maintains the app fixes the field, the flow or the host, and the submitter then submits again. +### Refused where the approval is authored + +The same conditions are refused before anyone submits, wherever the flow and +the object are in view together. `os validate`, `os build` and `os lint` fail +on a project's stack with the finding `approval-closed-state-gap`, one per gap, +in the same words as the refused opening. Studio, the REST `/meta` API and MCP +refuse to save or publish a `flow` or an `object` that would leave a gap, with +`INVALID_METADATA` (422) and the same words: at an active save, when a draft is +promoted, at a restore, and in a package publish. A draft save is not refused; +its promotion is. A package that declares `closedStates` and fixes its flow in +the same publish passes. + +An authoring door judges only what it has in view, so the refusal at the first +request stays the rule. These are left to the first request: + +- a flow that a `subflow` or a `map` names and the project or the deployment + does not hold there. When one flow is saved on its own, the flows it calls and + the flows that call it are not in view; +- a node type that a plugin adds, between two steps. At authoring only the + spec's own pausing types, such as `wait` and `screen`, count as a pause; +- whether the host runs a `job` service; +- a flow that declares no object, with no `start` object and no record input, + started by an action or by name on a record. At authoring a flow is judged on + its `start` object, or where it declares none, on the object of each record + input; the first request judges on the record the run was started on. + ### What an abandoned approval leaves Three writers abandon a request: its submitter's recall, of a pending request or diff --git a/docs/adr/0162-an-object-declares-its-closed-states-the-record-and-its-lines-are-closed-to-change.md b/docs/adr/0162-an-object-declares-its-closed-states-the-record-and-its-lines-are-closed-to-change.md index 9e7c7481736..8664adec081 100644 --- a/docs/adr/0162-an-object-declares-its-closed-states-the-record-and-its-lines-are-closed-to-change.md +++ b/docs/adr/0162-an-object-declares-its-closed-states-the-record-and-its-lines-are-closed-to-change.md @@ -1,6 +1,6 @@ # ADR-0162: An object declares its closed states — in them the record and its master-detail lines are closed to change for every caller, a closed record is not deleted, and one lock read answers for pending approvals and for closed states -**Status**: Proposed — 2026-11-26, written for objectstack#36253 on the maintainer's ruling of 2026-11-22 (ruling record [`7073676422`](https://github.com/objectstack-ai/objectstack/issues/32004#issuecomment-7073676422), item ② = C). `docs/adr/**` is Tier H (Prime Directive #14): this record becomes **Accepted** by an authorized approval or the maintainer's merge of the PR that carries it, and is in force from that merge. **This record declares; it implements nothing** — no schema key, no engine code, no route, no changeset; every mechanism below lands through a build card ([Execution](#execution-after-acceptance)). **Five points go past the ruling's words**; each is marked ▲ where it stands and all five are listed in [Points the ruling does not settle](#points-the-ruling-does-not-settle). The maintainer ruled on four of them on 2026-11-26 (ruling record [`7200732942`](https://github.com/objectstack-ai/objectstack/issues/36253#issuecomment-7200732942)): each stands as written, and item ③ of the same batch is scoped to `readonlyWhen`. A second ruling the same day (ruling record [`7201405662`](https://github.com/objectstack-ai/objectstack/issues/36253#issuecomment-7201405662)) adds one platform rule: an abandoned approval never writes a closed value ([D5](#d5--who-is-bound-every-caller-a-system-context-is-not)). A third ruling the same day (ruling record [`7205949718`](https://github.com/objectstack-ai/objectstack/issues/36253#issuecomment-7205949718)) settles the fifth point, in [D5](#d5--who-is-bound-every-caller-a-system-context-is-not): the platform refuses the configuration that would leave a document reading a decision its approval did not finish. **Revised 2026-11-27** on two further rulings of the maintainer, made that day on the design of [Execution](#execution-after-acceptance) item 8 (ruling record [`7210179412`](https://github.com/objectstack-ai/objectstack/issues/37767#issuecomment-7210179412)): on a field the object closes on at an approval's outcome, each step's decision is written only when the approval is over for the record, and on an object that declares `closedStates` a document is held through every approval ([D5](#d5--who-is-bound-every-caller-a-system-context-is-not)). After the contract review of the revision the seat read both rulings by their words (seat rulings [`7211509661`](https://github.com/objectstack-ai/objectstack/issues/37817#issuecomment-7211509661) and [`7211531658`](https://github.com/objectstack-ai/objectstack/issues/37817#issuecomment-7211531658)). The revision implements nothing either. +**Status**: Proposed — 2026-11-26, written for objectstack#36253 on the maintainer's ruling of 2026-11-22 (ruling record [`7073676422`](https://github.com/objectstack-ai/objectstack/issues/32004#issuecomment-7073676422), item ② = C). `docs/adr/**` is Tier H (Prime Directive #14): this record becomes **Accepted** by an authorized approval or the maintainer's merge of the PR that carries it, and is in force from that merge. **This record declares; it implements nothing** — no schema key, no engine code, no route, no changeset; every mechanism below lands through a build card ([Execution](#execution-after-acceptance)). **Five points go past the ruling's words**; each is marked ▲ where it stands and all five are listed in [Points the ruling does not settle](#points-the-ruling-does-not-settle). The maintainer ruled on four of them on 2026-11-26 (ruling record [`7200732942`](https://github.com/objectstack-ai/objectstack/issues/36253#issuecomment-7200732942)): each stands as written, and item ③ of the same batch is scoped to `readonlyWhen`. A second ruling the same day (ruling record [`7201405662`](https://github.com/objectstack-ai/objectstack/issues/36253#issuecomment-7201405662)) adds one platform rule: an abandoned approval never writes a closed value ([D5](#d5--who-is-bound-every-caller-a-system-context-is-not)). A third ruling the same day (ruling record [`7205949718`](https://github.com/objectstack-ai/objectstack/issues/36253#issuecomment-7205949718)) settles the fifth point, in [D5](#d5--who-is-bound-every-caller-a-system-context-is-not): the platform refuses the configuration that would leave a document reading a decision its approval did not finish. **Revised 2026-11-27** on two further rulings of the maintainer, made that day on the design of [Execution](#execution-after-acceptance) item 8 (ruling record [`7210179412`](https://github.com/objectstack-ai/objectstack/issues/37767#issuecomment-7210179412)): on a field the object closes on at an approval's outcome, each step's decision is written only when the approval is over for the record, and on an object that declares `closedStates` a document is held through every approval ([D5](#d5--who-is-bound-every-caller-a-system-context-is-not)). After the contract review of the revision the seat read both rulings by their words (seat rulings [`7211509661`](https://github.com/objectstack-ai/objectstack/issues/37817#issuecomment-7211509661) and [`7211531658`](https://github.com/objectstack-ai/objectstack/issues/37817#issuecomment-7211531658)). The revision implements nothing either. · **Amended** (2026-11-29, option D on [#37766](https://github.com/objectstack-ai/objectstack/issues/37766), ruling record [`7253749311`](https://github.com/objectstack-ai/objectstack/issues/37766#issuecomment-7253749311), maintainer 「D 统一校验,各入口都拒绝」): where a flow or an object is authored, the conditions an approval opens on are refused at every authoring door, and no longer only reported. One dated note under [D5](#d5--who-is-bound-every-caller-a-system-context-is-not) says how four passages of this record read after that ruling, and marks what in the note is not in the ruling's words. The refusal at the first request stays the rule, and the four passages are left as written. - **Date**: 2026-11-26 - **Card**: [#36253](https://github.com/objectstack-ai/objectstack/issues/36253) (p2, `area:data`). Its rule, as the card carries it: @@ -241,6 +241,29 @@ An approval none of whose steps mirrors onto a field the object closes on is ask **The approval is judged whole, once, at its first request.** That is the first point at which the objects and the flows are certainly all in hand: they are published apart, and any of them can change after the others. The node reads the approval from its definition: every approval step of the flow the record's run was started on, and of every flow that a `subflow` or a `map` in it names, to any depth. It judges each step on that step's own mirror field and on each object the step can act on: the object of the run's record, and under a `map` the object that node names for its items as well. Every step has therefore been judged before the first request is written, one that opens later on another record or another object too. A first step that names no mirror field does not open the approval unjudged: where another step that can act on the same object is one the conditions concern, the approval is refused for the step that names none. A later request of the same approval is not judged again: refusing it would end the approval between two steps, after steps that were already decided. A request that the plugin cannot place as first or later is not judged either, for the same reason, below. Where a part of the approval cannot be read ahead, a flow that a node names and the plugin cannot read, the approval cannot be judged, and its first request is refused. The same conditions are reported where a flow or an object is authored, wherever the parts are in view together; that report is early notice, and the refusal at the first request is the rule. The rule holds for an approval of one step as for one of several, since a single step fails too, on a decided document that is sent for approval again. In an application where no object declares the key, nothing is read and no approval is refused. +> **Note (2026-11-29, ruling record [`7253749311`](https://github.com/objectstack-ai/objectstack/issues/37766#issuecomment-7253749311) on [#37766](https://github.com/objectstack-ai/objectstack/issues/37766), option D) — where a flow or an object is authored, the conditions are refused at every authoring door, and no longer only reported.** Card #37766 builds [Execution](#execution-after-acceptance) item 7. One item of it asked what an author is told before the first request: an error, or only a notice. The seat put that to the maintainer as a choice, and the maintainer chose the option that reads, verbatim and untranslated, 「D 统一校验,各入口都拒绝」, D: one check, and every door refuses. The line under that option, as the maintainer read it, reads in full 「写文件的项目在校验和构建时、设计器和 AI 在发布时都报错并说明缺什么。现有草稿 PR 的入口部分作废,重做一个 PR;您批一条决策记录修订。」: a project written in files gets an error at validate and at build, and the designer and an AI author get one at publish, each error saying what is missing; the door half of the draft PR is set aside and the work is redone as one PR; the maintainer approves one amendment of a decision record. As the ruling record states it: at authoring the gap is an error, and a notice alone is not the answer; the refusal is made at every authoring door, from one check in the platform's shared rule table; this record is amended by one dated note, and [ADR-0094](./0094-sys-permission-set-pure-projection.md) is not amended. This note is that amendment. +> +> Four passages of this record are read with this note, and each is left as written. +> +> - **The paragraph above**: "The same conditions are reported where a flow or an object is authored, wherever the parts are in view together; that report is early notice, and the refusal at the first request is the rule." For "reported" read "refused", and for "that report is early notice" read "that refusal comes early". The rest of the sentence stands. +> - **[Execution](#execution-after-acceptance) item 7, the check**: "The same conditions are reported at authoring wherever the parts are in view together." For "reported" read "refused". +> - **[Points the ruling does not settle](#points-the-ruling-does-not-settle), the list under the third ruling of 2026-11-26**: "the refusal is made when an approval opens and reported at authoring, and is not made at publish, where the option's words allow either". Read: the refusal is made when an approval opens, and at authoring too, publish included. Not refusing at publish was this record's choice inside that ruling, and the ruling of 2026-11-29 replaces it. The other points of the list are untouched. +> - **[Alternatives considered](#alternatives-considered)**: "Refuse the configuration only where the object or the flow is published." It stays not chosen as the rule, for the reason the entry gives: a publish check sees the pair only some of the time. For its last sentence, "It is kept as early notice.", read: it is kept as a refusal beside the rule. +> +> The rest of this note is not in the maintainer's words. The ruling record lists each point below as carried from the decision analysis ([`7252928345`](https://github.com/objectstack-ai/objectstack/issues/37766#issuecomment-7252928345)) or as not ruled. They are the seat's proposals, built in the change that carries this note, for the maintainer to accept with it or strike. +> +> - **The first request stays the rule** (carried from the analysis). The refusal at authoring is added to it and replaces nothing. An authoring door has the parts of an approval in view only some of the time, and the first request has them all. +> - **One judge** (carried from the analysis; where it lives is the seat's choice). The first request and the rule ask the same code (`packages/metadata-core/src/approval-opening.ts#judgeApprovalOpening`, `#judgeApprovalOpeningSync`): the first request through the entry that awaits each flow it reads, the rule through the entry that reads a stack in hand. Both entries drive one walk of the approval's flows and one judging function, so the conditions are written once. The two verdicts can still differ, because the two doors do not have the same things in view: the last point below says where. +> - **Released with the key** (carried from the analysis). The refusal at authoring is part of item 7's check and is released as item 7 is: the release that first publishes `closedStates` carries it. +> - **The rule** (the seat's). `validateApprovalClosedStates` (`packages/lint/src/validate-approval-closed-states.ts#validateApprovalClosedStates`) reports the finding `approval-closed-state-gap` at severity `error`. It is a member of the reference-integrity suite (`packages/lint/src/reference-integrity-suite.ts#REFERENCE_INTEGRITY_RULES`), which is one entry of the shared author-time rule table (`packages/lint/src/authoring-rules.ts#AUTHORING_RULES`), so `os validate`, `os build` and `os lint` run it over a project's stack. The approvals plugin registers no gate of its own, and the authoring-gate seam that ADR-0094 records gains no member. +> - **The runtime publish door** (the seat's). The write path behind Studio, REST `/meta` and MCP runs the rule on a `flow` write and on an `object` write: at an active save, at a draft's promotion, at a restore, and for each draft of a package publish. It refuses with `INVALID_METADATA` (422), a code that door already gives. A draft is not refused, because no rule of the table refuses a draft there. On an `object` write the door judges the live flows of the written object's package against the written object, and charges the write only with a gap it adds: a gap the stored universe already holds is not that write's. In a package publish each draft is judged against the batch's objects, and a flow the batch redrafts is judged as its draft, at its own write. A package that declares `closedStates` and repairs its flow in one publish therefore passes, and one that declares it without repairing the live flow is refused (`packages/plugins/plugin-approvals/src/approval-closed-states-37766.integration.test.ts`). +> - **What an authoring door does not judge** (the seat's). At authoring there is no run. The first request judges on the object its root run was started on. The rule reads an object off the flow's definition instead (`packages/lint/src/validate-approval-closed-states.ts#approvalRootObjectsOf`): the `start` node's object where the flow declares one, and only where it declares none, the object of each start input that is a record, each read as a record the flow can be started on. It judges each flow in view as the root of an approval, on the objects so read. A door refuses only for what it has in view, and not for the following. The first request has each of them in hand and judges it: +> - a run on a record of an object the rule did not read: a flow that declares no object, neither a `start` object nor a record input, and is started by an action or by name on a record, is judged at authoring with no object for the run's record; and a flow that declares only record inputs can be started on a record of another object, on which the first request then judges; +> - a flow that is not in view: one that a `subflow` or a `map` names and the stack does not hold; on a `flow` write at the runtime door, every flow but the written one, the flows it calls and the flows that call it included; on an `object` write, every flow of another package; +> - a pause by a node whose type the spec does not list as pausing (`packages/spec/src/automation/flow.zod.ts#FLOW_PAUSE_CAPABLE_NODE_TYPES`, a `wait` and a `screen` among them): at every authoring door, the runtime door included, such a node counts as one that does not pause, a plugin's type too, because the rule is handed none of the engine's descriptors; +> - the host's `job` service, which is a fact of the deployment and not of what is authored; +> - an object that is not in view. + **What the conditions do not reach.** The platform reads ahead what can be read: a field's options, with the `visibleWhen` of those the mirror writes for a request's status, and its `readonlyWhen`; an object's closed values; the one move of a `state_machine` rule that a lock depends on; and the nodes of the approval's flows, with each step's mirror field, every node that pauses, and every `map` that holds an approval step. An author who puts a `state_machine` rule on the mirror field owes the mirror its other moves as well, from one status to the next and out of `pending` and `returned` when a request is abandoned. A move the rule refuses leaves the field on the status it holds, which is then an open one, and it is a refused write of the mirror like any other, below. Four things cannot be read ahead. When this record was merged, each of them could leave a record on an earlier step's outcome, closed, with its approval unfinished. For the first three it fixed what must hold, that the record is not left closed on a value its own approval wrote, and left the means to a card of its own ([Execution](#execution-after-acceptance), item 8). The ruling of 2026-11-27 meets that bound for the three at its root: the outcome is not on the record before the approval is over, so none of them can leave it there. What each leaves in its place is stated here, as the seat ruled it on that card's design note (ruling record [`7210179412`](https://github.com/objectstack-ai/objectstack/issues/37767#issuecomment-7210179412)). The key is still not released before that card is built. - **A rule or a hook of the app's own that refuses a write of the mirror.** A rule of another kind than `state_machine`, or a hook, can turn on the record's data, so no reading of a definition shows what it will do. A `visibleWhen` on an option that is not a request's status can refuse a value the mirror puts back, and it is held to the same. On `main` every such refusal is logged and swallowed, on every write of the mirror. On a field the object closes on at `approved` or `rejected` none is swallowed, and what follows depends on the write. diff --git a/packages/lint/src/finding-user-text.ts b/packages/lint/src/finding-user-text.ts index 797ad896683..33f22156b5f 100644 --- a/packages/lint/src/finding-user-text.ts +++ b/packages/lint/src/finding-user-text.ts @@ -59,6 +59,7 @@ import { FLOW_TRIGGER_READINESS_USER_TEXT } from './validate-flow-trigger-readin import { FLOW_TEMPLATE_PATHS_USER_TEXT } from './validate-flow-template-paths.user-text.js'; import { FLOW_NODE_WRITES_USER_TEXT } from './validate-flow-node-writes.user-text.js'; import { READONLY_FLOW_WRITES_USER_TEXT } from './validate-readonly-flow-writes.user-text.js'; +import { APPROVAL_CLOSED_STATES_USER_TEXT } from './validate-approval-closed-states.user-text.js'; import { FLOW_CREDENTIAL_LITERALS_USER_TEXT } from './lint-flow-credential-literals.user-text.js'; import { FLOW_PATTERNS_USER_TEXT } from './lint-flow-patterns.user-text.js'; import { WIDGET_BINDINGS_USER_TEXT } from './validate-widget-bindings.user-text.js'; @@ -181,6 +182,7 @@ export const FINDING_USER_TEXT_CATALOG: UserTextCatalog = mergeUserTextCatalogs( FLOW_TEMPLATE_PATHS_USER_TEXT, FLOW_NODE_WRITES_USER_TEXT, READONLY_FLOW_WRITES_USER_TEXT, + APPROVAL_CLOSED_STATES_USER_TEXT, FLOW_CREDENTIAL_LITERALS_USER_TEXT, FLOW_PATTERNS_USER_TEXT, // The dashboard writes: widget and chart binding advisories. diff --git a/packages/lint/src/index.ts b/packages/lint/src/index.ts index 57f1d56abef..916082b9350 100644 --- a/packages/lint/src/index.ts +++ b/packages/lint/src/index.ts @@ -213,6 +213,13 @@ export type { ReadonlyFlowWriteSeverity, } from './validate-readonly-flow-writes.js'; +export { + validateApprovalClosedStates, + approvalRootObjectsOf, + APPROVAL_CLOSED_STATE_GAP, +} from './validate-approval-closed-states.js'; +export type { ApprovalClosedStateFinding } from './validate-approval-closed-states.js'; + export { validateReadonlyHookWrites, HOOK_API_UPDATE_READONLY_FIELD, diff --git a/packages/lint/src/reference-integrity-suite.test.ts b/packages/lint/src/reference-integrity-suite.test.ts index 8ea57a88785..949ee4da80a 100644 --- a/packages/lint/src/reference-integrity-suite.test.ts +++ b/packages/lint/src/reference-integrity-suite.test.ts @@ -92,6 +92,9 @@ describe('reference-integrity suite — membership', () => { // resolves the same flow's CRUD write maps against that object. 'validateNotifyEmailFieldRecipients', 'validateReadonlyFlowWrites', + // [ADR-0162 D5, #37766] The approval opening conditions at authoring, + // the same two writes and the same subject as the member above. + 'validateApprovalClosedStates', // [#13653] The hook-side half of the readonly write judgement: a body's // `ctx.api` update to a declared-`readonly` field, placed beside the flow // twin that asks the identical question one surface over. diff --git a/packages/lint/src/reference-integrity-suite.ts b/packages/lint/src/reference-integrity-suite.ts index 0954d55f274..7393bc98fcf 100644 --- a/packages/lint/src/reference-integrity-suite.ts +++ b/packages/lint/src/reference-integrity-suite.ts @@ -133,6 +133,7 @@ import { validateActionBodyWrites } from './validate-action-body-writes.js'; import { validateFlowNodeWrites } from './validate-flow-node-writes.js'; import { validateNotifyEmailFieldRecipients } from './validate-notify-email-field-recipients.js'; import { validateReadonlyFlowWrites } from './validate-readonly-flow-writes.js'; +import { validateApprovalClosedStates } from './validate-approval-closed-states.js'; import { validateReadonlyHookWrites } from './validate-readonly-hook-writes.js'; import { validateReadonlyActionWrites } from './validate-readonly-action-writes.js'; import { validateReactPageProps } from './validate-react-page-props.js'; @@ -834,6 +835,21 @@ export const REFERENCE_INTEGRITY_RULES: readonly ReferenceIntegrityRule[] = [ subjects: ['flows'], run: validateReadonlyFlowWrites, }, + // [ADR-0162 D5, Execution item 7; #37766 N45, maintainer ruling 7253749311, + // option D] An approval that could not show itself in progress on a field its + // object closes on is refused at authoring, at every door, by the one judge + // the approval's first request also asks (`@objectstack/metadata-core`, + // `approval-opening.ts`). The same two writes as the member above, for the + // same two reasons: a `flow` write judges the written flow against the live + // objects; an `object` write that starts to close on an approval's field + // judges the written package's live flows, carried as subjects, and the + // differential charges it only with the gaps it adds. + { + name: 'validateApprovalClosedStates', + runtimeTypes: ['flow', 'object'], + subjects: ['flows'], + run: validateApprovalClosedStates, + }, // [commit 36d287803] The SAME question as the member above, on the surface that had no // answer for it: a hook body's `ctx.api.object('x').update({ readonlyField })`. // A hook's `ctx.api` is a ScopedContext over the TRIGGERING operation's diff --git a/packages/lint/src/runtime-gate.approval-closed-states.test.ts b/packages/lint/src/runtime-gate.approval-closed-states.test.ts new file mode 100644 index 00000000000..84c8332d1e3 --- /dev/null +++ b/packages/lint/src/runtime-gate.approval-closed-states.test.ts @@ -0,0 +1,114 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 D5, Execution item 7; #37766 N45, ruling 7253749311 option D] + * `validateApprovalClosedStates` at the runtime publish door (Studio, REST + * `/meta`, MCP), through the real gate: a `flow` write judges the written + * flow against the live objects, its callees not in the snapshot are not + * refused; an `object` write that starts to close on an approval's field + * judges the written package's live flows (the subject pass), and a gap the + * stored universe already holds is not charged to it. The rule over whole + * stacks (the three CLI commands) is pinned in + * `validate-approval-closed-states.test.ts`. + */ + +import { describe, expect, it } from 'vitest'; +import { runRuntimeAuthoringRules } from './runtime-gate.js'; + +type AnyRec = Record; + +const STATUSES = ['draft', 'pending', 'returned', 'approved', 'rejected', 'recalled']; +const statusField = { type: 'select', label: 'Status', options: STATUSES.map((value) => ({ value, label: value })) }; + +/** As stored: no closed state. */ +const deal = (over: AnyRec = {}): AnyRec => ({ name: 'crm_deal', label: 'Deal', fields: { name: { type: 'text', label: 'Name' }, status: statusField }, ...over }); +const closingDeal = () => deal({ closedStates: { status: ['approved', 'rejected'] } }); + +const node = (id: string, type: string, config: AnyRec = {}): AnyRec => ({ id, type, label: id, config }); +const step = (id: string) => node(id, 'approval', { approvers: [{ type: 'user', value: 'u1' }], approvalStatusField: 'status' }); + +/** Two steps on the deal's approval field, with a timer between them where `hold`. */ +function approvalFlow(name: string, hold: boolean, extra: AnyRec[] = []): AnyRec { + const nodes = [ + node('start', 'start', { objectName: 'crm_deal', triggerType: 'record-after-update' }), + ...extra, + step('first'), + ...(hold ? [{ id: 'hold', type: 'wait', label: 'Hold', waitEventConfig: { eventType: 'timer', timerDuration: 'PT1H' } }] : []), + step('second'), + node('end', 'end'), + ]; + const ids = nodes.map((n) => n.id as string); + return { + name, label: name, type: 'autolaunched', nodes, + edges: ids.slice(1).map((target, i) => ({ id: `e${i}`, source: ids[i], target, ...(ids[i] === 'first' || ids[i] === 'second' ? { label: 'approve' } : {}) })), + }; +} + +const gaps = (fs: readonly F[]): F[] => fs.filter((f) => f.rule === 'approval-closed-state-gap'); + +describe('[#37766 N45] the opening conditions at the runtime publish door', () => { + it('refuses a flow write whose approval holds a pause between two steps on a closing field', () => { + const result = runRuntimeAuthoringRules({ type: 'flow', item: approvalFlow('deal_wait', true), context: { objects: [closingDeal()] } }); + expect(result.rulesRun).toContain('validateReferenceIntegrity'); + expect(gaps(result.errors)).toEqual([expect.objectContaining({ + severity: 'error', + // The written flow is the snapshot's only flow; a carried subject is keyed by its name (below). + path: 'flows[0]', + message: 'Node hold (wait) of flow deal_wait can pause the run between two approval steps of crm_deal; move it before the first step or after the last.', + })]); + }); + + it('lets a flow write through that meets every condition', () => { + const result = runRuntimeAuthoringRules({ type: 'flow', item: approvalFlow('deal_ok', false), context: { objects: [closingDeal()] } }); + expect(gaps([...result.errors, ...result.advisories])).toEqual([]); + }); + + it('does not refuse a flow write on an object that declares no closed state', () => { + const result = runRuntimeAuthoringRules({ type: 'flow', item: approvalFlow('deal_wait', true), context: { objects: [deal()] } }); + expect(gaps([...result.errors, ...result.advisories])).toEqual([]); + }); + + it('does not refuse a flow write for a callee the snapshot does not hold, and judges the rest', () => { + const call = node('call', 'subflow', { flowName: 'not_in_view' }); + const clean = runRuntimeAuthoringRules({ type: 'flow', item: approvalFlow('deal_call', false, [call]), context: { objects: [closingDeal()] } }); + expect(gaps([...clean.errors, ...clean.advisories])).toEqual([]); + const held = runRuntimeAuthoringRules({ type: 'flow', item: approvalFlow('deal_call', true, [call]), context: { objects: [closingDeal()] } }); + expect(gaps(held.errors)).toHaveLength(1); + }); + + it('refuses an object write that starts to close on the field of a live flow\'s approval that pauses between two steps', () => { + const result = runRuntimeAuthoringRules({ + type: 'object', item: closingDeal(), context: { objects: [deal()], flows: [approvalFlow('deal_wait', true)] }, + }); + expect(gaps(result.errors)).toEqual([expect.objectContaining({ severity: 'error', path: 'flows.deal_wait' })]); + }); + + it('lets an object write through where the live flows meet every condition', () => { + const result = runRuntimeAuthoringRules({ + type: 'object', item: closingDeal(), context: { objects: [deal()], flows: [approvalFlow('deal_ok', false)] }, + }); + expect(gaps([...result.errors, ...result.advisories])).toEqual([]); + }); + + it('does not charge an unrelated object write with a gap the stored universe already holds', () => { + const relabelled = { ...closingDeal(), label: 'Opportunity' }; + const result = runRuntimeAuthoringRules({ + type: 'object', item: relabelled, context: { objects: [closingDeal()], flows: [approvalFlow('deal_wait', true)] }, + }); + expect(gaps([...result.errors, ...result.advisories])).toEqual([]); + }); + + it('judges a package publish in two halves: the object write without the flow the batch redrafts, and that flow at its own write against the batch\'s object', () => { + // In a package publish the door leaves a live flow the batch redrafts out + // of an object write's subjects (`objectWriteFlowSubjects`) and judges the + // draft at its own write, against the batch's objects. The real batch is + // pinned on the kernel in plugin-approvals' + // `approval-closed-states-37766.integration.test.ts`. + const objectHalf = runRuntimeAuthoringRules({ type: 'object', item: closingDeal(), context: { objects: [deal()], flows: [] } }); + expect(gaps([...objectHalf.errors, ...objectHalf.advisories])).toEqual([]); + const repaired = runRuntimeAuthoringRules({ type: 'flow', item: approvalFlow('deal_wait', false), context: { objects: [closingDeal()] } }); + expect(gaps([...repaired.errors, ...repaired.advisories])).toEqual([]); + const unrepaired = runRuntimeAuthoringRules({ type: 'flow', item: approvalFlow('deal_wait', true), context: { objects: [closingDeal()] } }); + expect(gaps(unrepaired.errors)).toHaveLength(1); + }); +}); diff --git a/packages/lint/src/runtime-gate.object-writes.test.ts b/packages/lint/src/runtime-gate.object-writes.test.ts index b91b3e9ab2c..631cfa77a37 100644 --- a/packages/lint/src/runtime-gate.object-writes.test.ts +++ b/packages/lint/src/runtime-gate.object-writes.test.ts @@ -336,6 +336,12 @@ describe('the object write door dispatches at the adjudicated scope (#4716)', () // the shipped corpus, 0 findings; its pins live in // `runtime-gate.object-readonly-flow-writes.test.ts`. 'validateReadonlyFlowWrites', + // [ADR-0162 D5] The eighth, the same kind as the seventh: the written + // package's live flows as judged subjects, the opening conditions of an + // approval on a field the object closes on. No shipped object declares + // `closedStates`, so it reads nothing over the shipped corpus (0 + // findings); its pins live in `runtime-gate.approval-closed-states.test.ts`. + 'validateApprovalClosedStates', ]); // Every crossed member still judges flow snapshots — the #4463 P1 surface // is not narrowed by the member axis existing. diff --git a/packages/lint/src/validate-approval-closed-states.test.ts b/packages/lint/src/validate-approval-closed-states.test.ts new file mode 100644 index 00000000000..dc89ea2f9cf --- /dev/null +++ b/packages/lint/src/validate-approval-closed-states.test.ts @@ -0,0 +1,142 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 D5, Execution item 7; #37766 N45, ruling 7253749311 option D] + * `validateApprovalClosedStates` over stacks: what it refuses, through the one + * judge (`judgeApprovalOpeningSync`), and what an authoring door does not have + * in view and so does not refuse: a flow the stack does not hold, a node type + * the spec does not ship, the host's job service, an object that declares no + * `closedStates`. The door half is pinned in `runtime-gate.approval-closed-states.test.ts`. + */ + +import { describe, expect, it } from 'vitest'; +import { findingUserMessage } from './finding-user-text.js'; +import { APPROVAL_CLOSED_STATE_GAP, approvalRootObjectsOf, validateApprovalClosedStates } from './validate-approval-closed-states.js'; + +const STATUSES = ['draft', 'pending', 'returned', 'approved', 'rejected', 'recalled']; +const statusField = (values: string[] = STATUSES) => ({ type: 'select', options: values.map((value) => ({ value, label: value })) }); + +/** Closes on its approval's outcome, and meets every condition of D5. */ +const deal = (over: Record = {}) => + ({ name: 'deal', closedStates: { status: ['approved', 'rejected'] }, fields: { status: statusField(), stage: statusField(['open', 'won']) }, ...over }); + +const node = (id: string, type: string, config: Record = {}) => ({ id, type, config }); +const step = (id: string) => node(id, 'approval', { approvalStatusField: 'status' }); + +/** A flow whose nodes run one after another, starting on `object`'s records. */ +function flow(name: string, object: string | null, ...nodes: ReturnType[]) { + const all = [node('start', 'start', object ? { objectName: object } : {}), ...nodes, node('end', 'end')]; + return { name, nodes: all, edges: all.slice(1).map((b, i) => ({ id: `e${i}`, source: all[i]!.id, target: b.id })) }; +} + +const kinds = (stack: Record) => validateApprovalClosedStates(stack).map((f) => f.userTextParams.kind); + +describe('validateApprovalClosedStates: what it refuses', () => { + it('refuses a pause between two approval steps on a closing field, at error, located on the flow', () => { + const findings = validateApprovalClosedStates({ + objects: [deal()], + flows: [flow('ok', 'deal', step('a1'), step('a2')), flow('held', 'deal', step('a1'), node('w', 'wait'), step('a2'))], + }); + expect(findings).toEqual([expect.objectContaining({ + severity: 'error', rule: APPROVAL_CLOSED_STATE_GAP, where: 'flow "held"', path: 'flows[1]', + message: 'Node w (wait) of flow held can pause the run between two approval steps of deal; move it before the first step or after the last.', + userTextParams: { kind: 'pause_between_steps', flow: 'held', node: 'w', type: 'wait', object: 'deal' }, + })]); + }); + + it('refuses each field condition of D5', () => { + const noPending = deal({ fields: { status: statusField(['draft', 'approved', 'rejected']) } }); + expect(kinds({ objects: [noPending], flows: [flow('f', 'deal', step('a1'))] })).toEqual(['no_pending_option']); + const inFlight = deal({ closedStates: { status: ['pending', 'approved'] } }); + expect(kinds({ objects: [inFlight], flows: [flow('f', 'deal', step('a1'))] })).toContain('closes_in_flight'); + const readonlyWhen = deal({ fields: { status: { ...statusField(), readonlyWhen: 'true' } } }); + expect(kinds({ objects: [readonlyWhen], flows: [flow('f', 'deal', step('a1'))] })).toEqual(['readonly_when']); + }); + + it('refuses a step that mirrors onto another field than the one the object closes on', () => { + const other = flow('f', 'deal', step('a1'), node('a2', 'approval', { approvalStatusField: 'stage' })); + expect(kinds({ objects: [deal()], flows: [other] })).toContain('other_field'); + }); + + it('judges a subflow in the stack through its caller, on the caller\'s record', () => { + const child = { name: 'child', nodes: [node('s', 'start'), step('c1'), node('w', 'wait'), step('c2'), node('e', 'end')], edges: [ + { id: 'x1', source: 's', target: 'c1' }, { id: 'x2', source: 'c1', target: 'w' }, { id: 'x3', source: 'w', target: 'c2' }, { id: 'x4', source: 'c2', target: 'e' }, + ] }; + const parent = flow('parent', 'deal', node('call', 'subflow', { flowName: 'child' })); + const findings = validateApprovalClosedStates({ objects: [deal()], flows: [parent, child] }); + expect(findings.map((f) => [f.where, f.path, f.userTextParams.kind])).toEqual([['flow "child"', 'flows[1]', 'pause_between_steps']]); + }); + + it('judges a flow whose start input is a record of a closing object (#29425)', () => { + const f = { ...flow('f', null, step('a1'), node('w', 'wait'), step('a2')), variables: [{ name: 'rec', isInput: true, objectName: 'deal' }] }; + expect(kinds({ objects: [deal()], flows: [f] })).toEqual(['pause_between_steps']); + }); + + it('reads a record input as a root only where the flow declares no start object', () => { + // A run's object is a fact of how it was started; the first request judges on it alone. + const beside = { ...flow('f', 'invoice', step('a1'), node('w', 'wait'), step('a2')), variables: [{ name: 'po', isInput: true, objectName: 'deal' }] }; + expect(validateApprovalClosedStates({ objects: [deal(), { name: 'invoice', fields: {} }], flows: [beside] })).toEqual([]); + expect(approvalRootObjectsOf(beside)).toEqual(['invoice']); + }); + + it('judges a flow that declares no object on no object, leaving it to the first request', () => { + const bare = flow('f', null, step('a1'), node('w', 'wait'), step('a2')); + expect(approvalRootObjectsOf(bare)).toEqual([]); + expect(validateApprovalClosedStates({ objects: [deal()], flows: [bare] })).toEqual([]); + }); + + it('reports a gap once, however many roots reach it', () => { + const child = flow('child', null, step('c1'), node('w', 'wait'), step('c2')); + const p1 = flow('p1', 'deal', node('call', 'subflow', { flowName: 'child' })); + const p2 = flow('p2', 'deal', node('call', 'subflow', { flowName: 'child' })); + expect(validateApprovalClosedStates({ objects: [deal()], flows: [p1, p2, child] })).toHaveLength(1); + }); + + it('lets through an approval that meets every condition', () => { + expect(validateApprovalClosedStates({ objects: [deal()], flows: [flow('ok', 'deal', step('a1'), node('d', 'decision'), step('a2'))] })).toEqual([]); + }); +}); + +describe('validateApprovalClosedStates: what an authoring door does not refuse', () => { + it('does not refuse a call to a flow the stack does not hold, and judges the rest', () => { + const f = flow('f', 'deal', node('call', 'subflow', { flowName: 'elsewhere' }), step('a1'), node('w', 'wait'), step('a2')); + expect(kinds({ objects: [deal()], flows: [f] })).toEqual(['pause_between_steps']); + const clean = flow('g', 'deal', node('call', 'subflow', { flowName: 'elsewhere' }), step('a1')); + expect(validateApprovalClosedStates({ objects: [deal()], flows: [clean] })).toEqual([]); + }); + + it('does not refuse a node type the spec does not ship, between two steps; the spec\'s pausing types are refused', () => { + const plugin = flow('f', 'deal', step('a1'), node('p', 'acme_pausing_step'), step('a2')); + expect(validateApprovalClosedStates({ objects: [deal()], flows: [plugin] })).toEqual([]); + const screen = flow('g', 'deal', step('a1'), node('s', 'screen'), step('a2')); + expect(kinds({ objects: [deal()], flows: [screen] })).toEqual(['pause_between_steps']); + }); + + it('does not judge the host: no job service is not refused', () => { + // The judge reports `no_job_service` only where the host runs none; the rule always reads the host as running one. + expect(validateApprovalClosedStates({ objects: [deal()], flows: [flow('ok', 'deal', step('a1'))] })).toEqual([]); + }); + + it('reads nothing in a stack where no object declares closedStates', () => { + const open = { name: 'deal', fields: { status: statusField(['draft', 'approved']) } }; + expect(validateApprovalClosedStates({ objects: [open], flows: [flow('f', 'deal', step('a1'), node('w', 'wait'), step('a2'))] })).toEqual([]); + }); + + it('does not refuse a flow on an object the stack does not hold', () => { + expect(validateApprovalClosedStates({ objects: [deal()], flows: [flow('f', 'invoice', step('a1'), node('w', 'wait'), step('a2'))] })).toEqual([]); + }); + + it('does not refuse an object that closes on another field than the approval\'s', () => { + const stageCloser = deal({ closedStates: { stage: ['won'] } }); + expect(validateApprovalClosedStates({ objects: [stageCloser], flows: [flow('f', 'deal', step('a1'), node('w', 'wait'), step('a2'))] })).toEqual([]); + }); +}); + +describe('validateApprovalClosedStates: the user sentence', () => { + it('is the first request\'s sentence for the gap, in the author\'s locale', () => { + const [finding] = validateApprovalClosedStates({ objects: [deal()], flows: [flow('held', 'deal', step('a1'), node('w', 'wait'), step('a2'))] }); + expect(findingUserMessage(finding!, ['en'])).toBe(finding!.message); + expect(findingUserMessage(finding!, ['zh-Hans'])).toContain('held'); + expect(findingUserMessage(finding!, ['zh-Hans'])).not.toBe(finding!.message); + }); +}); diff --git a/packages/lint/src/validate-approval-closed-states.ts b/packages/lint/src/validate-approval-closed-states.ts new file mode 100644 index 00000000000..275a1b7b46b --- /dev/null +++ b/packages/lint/src/validate-approval-closed-states.ts @@ -0,0 +1,191 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 D5, Execution item 7; #37766 N45, maintainer ruling 7253749311, + * option D] An approval that could not show itself in progress on a field its + * object closes on is refused where it is authored, at every authoring door. + * + * The rule is the refusal at the approval's first request + * (`@objectstack/plugin-approvals`): only that request has every part of the + * approval in hand. This member reports the same conditions earlier, wherever + * the parts are in view together, and refuses the author: `os validate`, + * `os build` and `os lint` on a project's stack, and the runtime publish door + * (Studio, REST `/meta`, MCP) on a `flow` or an `object` write. The judgement + * is the one judge both doors ask, `judgeApprovalOpeningSync` + * (`@objectstack/metadata-core`, `approval-opening.ts`), so the author and the + * first request read the same verdict and the same sentences. + * + * Each flow of the stack is judged as the root of an approval, on the object + * of the record its run is started on, with the flows it calls read from the + * same stack. A run's object is a fact of how it was started, which the first + * request reads off the run; at authoring it is read off the definition: the + * `start` node's `objectName` where the flow declares one, and only where it + * declares none, the object of each start input that is a record + * (`variables[].objectName` with `isInput`, #29425), each read as a record the + * flow can be started on. A flow another one calls is judged through its caller + * as well, so a gap that only shows from the caller is reported there. + * + * What a door does not have in view is not refused here, each a reading + * pinned by a test: + * + * - **A flow not in the stack.** A `subflow` or a `map` that names a flow the + * stack does not hold is not refused (`unreadable_flow` is dropped). At the + * runtime door a `flow` write's snapshot holds the written flow alone, so a + * gap that shows only across the written flow and a flow it calls, or one + * that calls it, is refused by the CLI over the whole stack and at the + * first request, not at that write; #35143's gate owns a call to a flow the + * deployment does not hold. + * - **A node type the spec does not ship.** The pause condition is judged for + * the spec's pausing types (`FLOW_PAUSE_CAPABLE_NODE_TYPES`); any other + * type, a plugin's included, counts as one that does not pause. The first + * request reads the engine's descriptors and judges it. + * - **The host.** Whether the host runs a `job` service is a fact of the + * deployment, not of what is authored (`no_job_service` is not judged). + * - **A flow that declares no object** (no `start` object and no record + * input), started by an action or by name on a record: it is judged with no + * object for the run's record here (an object a `map` names for its items + * is still read), and the first request judges it on the run's record. + * - **An object the stack does not hold**, or one that declares no + * `closedStates`: nothing is read for it. + * + * On an `object` write the runtime door carries the written package's live + * flows as judged subjects (`subjects: ['flows']`), as it does for + * `validateReadonlyFlowWrites`, and its differential charges the write only + * with what it adds: a gap the stored universe already holds is not this + * write's. In a package publish each draft is judged against the batch's + * objects, and a live flow the batch redrafts is judged as its draft, at its + * own write (`objectWriteFlowSubjects` leaves it out of an object write's + * subjects), so a package that declares `closedStates` and repairs its flow in + * one publish passes, and one that leaves the live flow as it is is refused. + */ + +import { + judgeApprovalOpeningSync, + type OpeningCheckSource, + type OpeningFlowBody, + type OpeningGap, +} from '@objectstack/metadata-core'; +import { FLOW_PAUSE_CAPABLE_NODE_TYPES } from '@objectstack/spec/automation'; +import { recordsOf } from './object-graph.js'; +import type { UserTextParams } from './finding-user-text.js'; + +type AnyRec = Record; + +/** The one rule id: a condition of ADR-0162 D5 an approval in the stack does not meet. */ +export const APPROVAL_CLOSED_STATE_GAP = 'approval-closed-state-gap'; + +export interface ApprovalClosedStateFinding { + severity: 'error'; + rule: string; + /** e.g. `flow "deal_approval"`. */ + where: string; + /** e.g. `flows[2]`, the flow the gap is in. */ + path: string; + message: string; + hint: string; + /** The gap's `kind` and its names (flow, step, node, object, field, value, …), for the user sentence. */ + userTextParams: UserTextParams; +} + +/** The gap kinds an authoring door does not judge (see the module header). */ +const NOT_AT_AUTHORING: ReadonlySet = new Set(['unreadable_flow', 'no_job_service']); + +const PAUSING: ReadonlySet = new Set(FLOW_PAUSE_CAPABLE_NODE_TYPES); + +/** The developer-facing sentence of each gap kind (the first request's `en` sentence). */ +const MESSAGE: Readonly, (g: AnyRec) => string>> = { + no_pending_option: (g) => `Field ${g.field} of ${g.object} (step ${g.step} of flow ${g.flow}) does not declare the value pending; add it to the field's options.`, + closes_in_flight: (g) => `${g.object} closes on ${g.value} of field ${g.field} (step ${g.step} of flow ${g.flow}), a status of an approval in progress; remove ${g.value} from the object's closedStates.`, + state_machine_no_pending: (g) => `The state_machine rule ${g.rule} on field ${g.field} of ${g.object} (step ${g.step} of flow ${g.flow}) declares the moves out of ${g.value} without pending; add pending to them.`, + readonly_when: (g) => `Field ${g.field} of ${g.object} (step ${g.step} of flow ${g.flow}) carries a readonlyWhen; remove it.`, + option_visible_when: (g) => `The option ${g.value} of field ${g.field} of ${g.object} (step ${g.step} of flow ${g.flow}) carries a visibleWhen; remove it.`, + other_field: (g) => `Step ${g.step} of flow ${g.flow} can act on ${g.object} but mirrors onto field ${g.other}; every step that can act on ${g.object} must mirror onto ${g.field}.`, + no_field: (g) => `Step ${g.step} of flow ${g.flow} can act on ${g.object} but names no approval status field; every step that can act on ${g.object} must mirror onto ${g.field}.`, + pause_between_steps: (g) => `Node ${g.node} (${g.type}) of flow ${g.flow} can pause the run between two approval steps of ${g.object}; move it before the first step or after the last.`, + map_with_approval: (g) => `The map node ${g.node} of flow ${g.flow} runs an approval step for each item, and the node does not show that no item is a record; an approval of another record would hold ${g.object} between two steps.`, +}; + +const HINT = + 'An approval on an object that declares closedStates must be able to show itself in progress on the field the ' + + 'object closes on (ADR-0162 D5): fix the flow or the object as the sentence says. The approval\'s first request ' + + 'judges the same conditions on the record its run is started on.'; + +/** + * The objects a flow's run can be started on a record of, read off its + * definition: its `start` node's `objectName` where it declares one; only + * where it declares none, the object of each start input that is a record + * (`variables[].objectName` with `isInput`, #29425). A record input beside a + * declared start object is a record the run reads, not the run's own: the + * first request judges on the run's object alone. + */ +export function approvalRootObjectsOf(flow: AnyRec): string[] { + const out = new Set(); + for (const node of recordsOf(flow.nodes)) { + if (node.type !== 'start') continue; + const object = (node.config as AnyRec | undefined)?.objectName; + if (typeof object === 'string' && object) out.add(object); + } + if (out.size > 0) return [...out].sort(); + for (const v of recordsOf(flow.variables)) { + if (v.isInput === true && typeof v.objectName === 'string' && v.objectName) out.add(v.objectName); + } + return [...out].sort(); +} + +/** Judge every approval the stack holds whole enough to judge (see the module header). */ +export function validateApprovalClosedStates(stack: AnyRec): ApprovalClosedStateFinding[] { + const objects = recordsOf(stack.objects); + const byObject = new Map(); + for (const o of objects) if (typeof o.name === 'string') byObject.set(o.name, o); + // Nothing is read in a stack where no object declares the key. + if (![...byObject.values()].some((o) => o.closedStates != null)) return []; + + const flows = recordsOf(stack.flows); + const flowIndex = new Map(); + flows.forEach((f, i) => { if (typeof f.name === 'string' && !flowIndex.has(f.name)) flowIndex.set(f.name, i); }); + const bodyOf = (f: AnyRec): OpeningFlowBody => f as unknown as OpeningFlowBody; + + const source: OpeningCheckSource = { + objectSchema: (name) => byObject.get(name), + calleeFlow: (name) => { + const i = flowIndex.get(name); + return i === undefined ? null : { key: name, body: bodyOf(flows[i]!) }; + }, + nodeDescriptor: (type) => ({ supportsPause: PAUSING.has(type) }), + hostRunsReconciler: true, + }; + + const findings: ApprovalClosedStateFinding[] = []; + const seen = new Set(); + flows.forEach((flow, i) => { + const name = typeof flow.name === 'string' ? flow.name : `#${i}`; + const roots = approvalRootObjectsOf(flow); + for (const rootObject of roots.length > 0 ? roots : [null]) { + const judgement = judgeApprovalOpeningSync( + { rootFlow: { key: name, body: bodyOf(flow) }, rootFlowName: name, rootObject }, + source, + ); + for (const gap of judgement.gaps) { + if (NOT_AT_AUTHORING.has(gap.kind)) continue; + const key = JSON.stringify(gap); + if (seen.has(key)) continue; + seen.add(key); + const g = gap as unknown as AnyRec; + const at = typeof g.flow === 'string' ? g.flow : name; + const index = flowIndex.get(at) ?? i; + const params: Record = {}; + for (const [k, v] of Object.entries(g)) if (typeof v === 'string') params[k] = v; + findings.push({ + severity: 'error', + rule: APPROVAL_CLOSED_STATE_GAP, + where: `flow "${at}"`, + path: `flows[${index}]`, + message: MESSAGE[gap.kind as keyof typeof MESSAGE](g), + hint: HINT, + userTextParams: params, + }); + } + } + }); + return findings; +} diff --git a/packages/lint/src/validate-approval-closed-states.user-text.ts b/packages/lint/src/validate-approval-closed-states.user-text.ts new file mode 100644 index 00000000000..8411bb2784f --- /dev/null +++ b/packages/lint/src/validate-approval-closed-states.user-text.ts @@ -0,0 +1,183 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The user-facing sentences of `validate-approval-closed-states.ts`'s + * `approval-closed-state-gap` findings, in every platform locale + * (`PLATFORM_LOCALE_TAGS`, `@objectstack/spec/system`). The finding mechanism + * and the locale ladder are `finding-user-text.ts`'s; this file is the rule's + * own half of it. + * + * Who reads these: the person who published a flow or an object in Studio, or + * an AI author reading its draft's verdict, in their own language. Each + * sentence is the one an approval's first request is refused with for the + * same gap (`@objectstack/plugin-approvals`, `translations/messages.ts`, the + * `approvalOpening*` keys), so the author is told at publish exactly what the + * submitter would have been told later. The two catalogs hold the same words; + * the judge behind them is one (`@objectstack/metadata-core`, + * `approval-opening.ts`). + * + * The entry reads the finding's `userTextParams`: `kind` (the gap kind, one + * of the nine below) and the names that kind carries (`flow`, `step`, `node`, + * `type`, `object`, `field`, `value`, `rule`, `other`). + */ + +import type { UserTextCatalog, UserTextParams } from './finding-user-text.js'; +import { APPROVAL_CLOSED_STATE_GAP } from './validate-approval-closed-states.js'; + +type Kind = + | 'no_pending_option' + | 'closes_in_flight' + | 'state_machine_no_pending' + | 'readonly_when' + | 'option_visible_when' + | 'other_field' + | 'no_field' + | 'pause_between_steps' + | 'map_with_approval'; + +/** Each gap kind's sentence per locale, with `{{name}}` holes for the finding's params. */ +const SENTENCES: Readonly>>> = { + en: { + no_pending_option: "Field {{field}} of {{object}} (step {{step}} of flow {{flow}}) does not declare the value pending; add it to the field's options.", + closes_in_flight: "{{object}} closes on {{value}} of field {{field}} (step {{step}} of flow {{flow}}), a status of an approval in progress; remove {{value}} from the object's closedStates.", + state_machine_no_pending: "The state_machine rule {{rule}} on field {{field}} of {{object}} (step {{step}} of flow {{flow}}) declares the moves out of {{value}} without pending; add pending to them.", + readonly_when: "Field {{field}} of {{object}} (step {{step}} of flow {{flow}}) carries a readonlyWhen; remove it.", + option_visible_when: "The option {{value}} of field {{field}} of {{object}} (step {{step}} of flow {{flow}}) carries a visibleWhen; remove it.", + other_field: "Step {{step}} of flow {{flow}} can act on {{object}} but mirrors onto field {{other}}; every step that can act on {{object}} must mirror onto {{field}}.", + no_field: "Step {{step}} of flow {{flow}} can act on {{object}} but names no approval status field; every step that can act on {{object}} must mirror onto {{field}}.", + pause_between_steps: "Node {{node}} ({{type}}) of flow {{flow}} can pause the run between two approval steps of {{object}}; move it before the first step or after the last.", + map_with_approval: "The map node {{node}} of flow {{flow}} runs an approval step for each item, and the node does not show that no item is a record; an approval of another record would hold {{object}} between two steps.", + }, + 'zh-Hans': { + no_pending_option: "{{object}} 的字段 {{field}}(流程 {{flow}} 的步骤 {{step}})没有声明值 pending;请把它加入该字段的选项。", + closes_in_flight: "{{object}} 在字段 {{field}} 的 {{value}} 上关闭(流程 {{flow}} 的步骤 {{step}}),而这是审批进行中的状态;请把 {{value}} 从对象的 closedStates 中去掉。", + state_machine_no_pending: "{{object}} 字段 {{field}} 上的 state_machine 规则 {{rule}}(流程 {{flow}} 的步骤 {{step}})声明了从 {{value}} 出发的转移,但其中没有 pending;请加上 pending。", + readonly_when: "{{object}} 的字段 {{field}}(流程 {{flow}} 的步骤 {{step}})带有 readonlyWhen;请去掉它。", + option_visible_when: "{{object}} 字段 {{field}} 的选项 {{value}}(流程 {{flow}} 的步骤 {{step}})带有 visibleWhen;请去掉它。", + other_field: "流程 {{flow}} 的步骤 {{step}} 可以作用于 {{object}},却把状态写到字段 {{other}};凡是能作用于 {{object}} 的步骤都必须写到 {{field}}。", + no_field: "流程 {{flow}} 的步骤 {{step}} 可以作用于 {{object}},却没有指定审批状态字段;凡是能作用于 {{object}} 的步骤都必须写到 {{field}}。", + pause_between_steps: "流程 {{flow}} 的节点 {{node}}({{type}})可能在 {{object}} 的两个审批步骤之间暂停运行;请把它移到第一步之前或最后一步之后。", + map_with_approval: "流程 {{flow}} 的 map 节点 {{node}} 为每一项运行一个审批步骤,而该节点无法表明所有项都不是记录;另一条记录的审批会让 {{object}} 停在两个步骤之间。", + }, + 'zh-Hant': { + no_pending_option: "{{object}} 的欄位 {{field}}(流程 {{flow}} 的步驟 {{step}})沒有宣告值 pending;請把它加入該欄位的選項。", + closes_in_flight: "{{object}} 在欄位 {{field}} 的 {{value}} 上關閉(流程 {{flow}} 的步驟 {{step}}),而這是核准進行中的狀態;請把 {{value}} 從物件的 closedStates 中移除。", + state_machine_no_pending: "{{object}} 欄位 {{field}} 上的 state_machine 規則 {{rule}}(流程 {{flow}} 的步驟 {{step}})宣告了從 {{value}} 出發的轉移,但其中沒有 pending;請加上 pending。", + readonly_when: "{{object}} 的欄位 {{field}}(流程 {{flow}} 的步驟 {{step}})帶有 readonlyWhen;請移除它。", + option_visible_when: "{{object}} 欄位 {{field}} 的選項 {{value}}(流程 {{flow}} 的步驟 {{step}})帶有 visibleWhen;請移除它。", + other_field: "流程 {{flow}} 的步驟 {{step}} 可以作用於 {{object}},卻把狀態寫到欄位 {{other}};凡是能作用於 {{object}} 的步驟都必須寫到 {{field}}。", + no_field: "流程 {{flow}} 的步驟 {{step}} 可以作用於 {{object}},卻沒有指定核准狀態欄位;凡是能作用於 {{object}} 的步驟都必須寫到 {{field}}。", + pause_between_steps: "流程 {{flow}} 的節點 {{node}}({{type}})可能在 {{object}} 的兩個核准步驟之間暫停執行;請把它移到第一步之前或最後一步之後。", + map_with_approval: "流程 {{flow}} 的 map 節點 {{node}} 為每一項執行一個核准步驟,而該節點無法表明所有項目都不是記錄;另一筆記錄的核准會讓 {{object}} 停在兩個步驟之間。", + }, + es: { + no_pending_option: "El campo {{field}} de {{object}} (paso {{step}} del flujo {{flow}}) no declara el valor pending; añádalo a las opciones del campo.", + closes_in_flight: "{{object}} se cierra en {{value}} del campo {{field}} (paso {{step}} del flujo {{flow}}), un estado de una aprobación en curso; quite {{value}} de los closedStates del objeto.", + state_machine_no_pending: "La regla state_machine {{rule}} del campo {{field}} de {{object}} (paso {{step}} del flujo {{flow}}) declara las transiciones desde {{value}} sin pending; añada pending.", + readonly_when: "El campo {{field}} de {{object}} (paso {{step}} del flujo {{flow}}) tiene un readonlyWhen; quítelo.", + option_visible_when: "La opción {{value}} del campo {{field}} de {{object}} (paso {{step}} del flujo {{flow}}) tiene un visibleWhen; quítelo.", + other_field: "El paso {{step}} del flujo {{flow}} puede actuar sobre {{object}} pero escribe en el campo {{other}}; todo paso que pueda actuar sobre {{object}} debe escribir en {{field}}.", + no_field: "El paso {{step}} del flujo {{flow}} puede actuar sobre {{object}} pero no nombra ningún campo de estado de aprobación; todo paso que pueda actuar sobre {{object}} debe escribir en {{field}}.", + pause_between_steps: "El nodo {{node}} ({{type}}) del flujo {{flow}} puede pausar la ejecución entre dos pasos de aprobación de {{object}}; muévalo antes del primer paso o después del último.", + map_with_approval: "El nodo map {{node}} del flujo {{flow}} ejecuta un paso de aprobación por cada elemento, y el nodo no muestra que ningún elemento sea un registro; la aprobación de otro registro retendría {{object}} entre dos pasos.", + }, + ar: { + no_pending_option: "الحقل {{field}} في {{object}} (الخطوة {{step}} من التدفق {{flow}}) لا يصرّح بالقيمة pending؛ أضفها إلى خيارات الحقل.", + closes_in_flight: "يُغلَق {{object}} على القيمة {{value}} من الحقل {{field}} (الخطوة {{step}} من التدفق {{flow}})، وهي حالة موافقة جارية؛ أزل {{value}} من closedStates للكائن.", + state_machine_no_pending: "قاعدة state_machine {{rule}} على الحقل {{field}} في {{object}} (الخطوة {{step}} من التدفق {{flow}}) تصرّح بالانتقالات من {{value}} دون pending؛ أضف pending.", + readonly_when: "الحقل {{field}} في {{object}} (الخطوة {{step}} من التدفق {{flow}}) يحمل readonlyWhen؛ أزله.", + option_visible_when: "الخيار {{value}} من الحقل {{field}} في {{object}} (الخطوة {{step}} من التدفق {{flow}}) يحمل visibleWhen؛ أزله.", + other_field: "الخطوة {{step}} من التدفق {{flow}} يمكنها أن تعمل على {{object}} لكنها تكتب الحالة في الحقل {{other}}؛ يجب أن تكتب كل خطوة يمكنها العمل على {{object}} في {{field}}.", + no_field: "الخطوة {{step}} من التدفق {{flow}} يمكنها أن تعمل على {{object}} لكنها لا تسمّي حقلًا لحالة الموافقة؛ يجب أن تكتب كل خطوة يمكنها العمل على {{object}} في {{field}}.", + pause_between_steps: "العقدة {{node}} ({{type}}) في التدفق {{flow}} قد توقف التشغيل مؤقتًا بين خطوتَي موافقة على {{object}}؛ انقلها قبل الخطوة الأولى أو بعد الأخيرة.", + map_with_approval: "عقدة map {{node}} في التدفق {{flow}} تشغّل خطوة موافقة لكل عنصر، والعقدة لا تُظهر أن أي عنصر ليس سجلًا؛ موافقة سجل آخر ستحتجز {{object}} بين خطوتين.", + }, + fr: { + no_pending_option: "Le champ {{field}} de {{object}} (étape {{step}} du flux {{flow}}) ne déclare pas la valeur pending ; ajoutez-la aux options du champ.", + closes_in_flight: "{{object}} se ferme sur {{value}} du champ {{field}} (étape {{step}} du flux {{flow}}), un statut d'approbation en cours ; retirez {{value}} des closedStates de l'objet.", + state_machine_no_pending: "La règle state_machine {{rule}} du champ {{field}} de {{object}} (étape {{step}} du flux {{flow}}) déclare les transitions depuis {{value}} sans pending ; ajoutez pending.", + readonly_when: "Le champ {{field}} de {{object}} (étape {{step}} du flux {{flow}}) porte un readonlyWhen ; retirez-le.", + option_visible_when: "L'option {{value}} du champ {{field}} de {{object}} (étape {{step}} du flux {{flow}}) porte un visibleWhen ; retirez-le.", + other_field: "L'étape {{step}} du flux {{flow}} peut agir sur {{object}} mais écrit dans le champ {{other}} ; toute étape qui peut agir sur {{object}} doit écrire dans {{field}}.", + no_field: "L'étape {{step}} du flux {{flow}} peut agir sur {{object}} mais ne nomme aucun champ de statut d'approbation ; toute étape qui peut agir sur {{object}} doit écrire dans {{field}}.", + pause_between_steps: "Le nœud {{node}} ({{type}}) du flux {{flow}} peut mettre l'exécution en pause entre deux étapes d'approbation de {{object}} ; placez-le avant la première étape ou après la dernière.", + map_with_approval: "Le nœud map {{node}} du flux {{flow}} exécute une étape d'approbation pour chaque élément, et le nœud ne montre pas qu'aucun élément n'est un enregistrement ; l'approbation d'un autre enregistrement retiendrait {{object}} entre deux étapes.", + }, + 'pt-BR': { + no_pending_option: "O campo {{field}} de {{object}} (etapa {{step}} do fluxo {{flow}}) não declara o valor pending; adicione-o às opções do campo.", + closes_in_flight: "{{object}} é fechado em {{value}} do campo {{field}} (etapa {{step}} do fluxo {{flow}}), um status de aprovação em andamento; remova {{value}} dos closedStates do objeto.", + state_machine_no_pending: "A regra state_machine {{rule}} no campo {{field}} de {{object}} (etapa {{step}} do fluxo {{flow}}) declara as transições a partir de {{value}} sem pending; adicione pending.", + readonly_when: "O campo {{field}} de {{object}} (etapa {{step}} do fluxo {{flow}}) tem um readonlyWhen; remova-o.", + option_visible_when: "A opção {{value}} do campo {{field}} de {{object}} (etapa {{step}} do fluxo {{flow}}) tem um visibleWhen; remova-o.", + other_field: "A etapa {{step}} do fluxo {{flow}} pode agir sobre {{object}}, mas grava no campo {{other}}; toda etapa que pode agir sobre {{object}} deve gravar em {{field}}.", + no_field: "A etapa {{step}} do fluxo {{flow}} pode agir sobre {{object}}, mas não indica nenhum campo de status de aprovação; toda etapa que pode agir sobre {{object}} deve gravar em {{field}}.", + pause_between_steps: "O nó {{node}} ({{type}}) do fluxo {{flow}} pode pausar a execução entre duas etapas de aprovação de {{object}}; mova-o para antes da primeira etapa ou depois da última.", + map_with_approval: "O nó map {{node}} do fluxo {{flow}} executa uma etapa de aprovação para cada item, e o nó não mostra que nenhum item é um registro; a aprovação de outro registro reteria {{object}} entre duas etapas.", + }, + ru: { + no_pending_option: "Поле {{field}} объекта {{object}} (шаг {{step}} процесса {{flow}}) не объявляет значение pending; добавьте его в варианты поля.", + closes_in_flight: "{{object}} закрывается на значении {{value}} поля {{field}} (шаг {{step}} процесса {{flow}}), а это статус идущего согласования; уберите {{value}} из closedStates объекта.", + state_machine_no_pending: "Правило state_machine {{rule}} на поле {{field}} объекта {{object}} (шаг {{step}} процесса {{flow}}) объявляет переходы из {{value}} без pending; добавьте pending.", + readonly_when: "Поле {{field}} объекта {{object}} (шаг {{step}} процесса {{flow}}) имеет readonlyWhen; уберите его.", + option_visible_when: "Вариант {{value}} поля {{field}} объекта {{object}} (шаг {{step}} процесса {{flow}}) имеет visibleWhen; уберите его.", + other_field: "Шаг {{step}} процесса {{flow}} может действовать на {{object}}, но записывает статус в поле {{other}}; каждый шаг, который может действовать на {{object}}, должен записывать в {{field}}.", + no_field: "Шаг {{step}} процесса {{flow}} может действовать на {{object}}, но не называет поле статуса согласования; каждый шаг, который может действовать на {{object}}, должен записывать в {{field}}.", + pause_between_steps: "Узел {{node}} ({{type}}) процесса {{flow}} может приостановить выполнение между двумя шагами согласования {{object}}; перенесите его до первого шага или после последнего.", + map_with_approval: "Узел map {{node}} процесса {{flow}} запускает шаг согласования для каждого элемента, и узел не показывает, что ни один элемент не является записью; согласование другой записи задержит {{object}} между двумя шагами.", + }, + de: { + no_pending_option: "Das Feld {{field}} von {{object}} (Schritt {{step}} des Flows {{flow}}) deklariert den Wert pending nicht; fügen Sie ihn den Optionen des Feldes hinzu.", + closes_in_flight: "{{object}} schließt auf {{value}} des Feldes {{field}} (Schritt {{step}} des Flows {{flow}}), einem Status einer laufenden Genehmigung; entfernen Sie {{value}} aus den closedStates des Objekts.", + state_machine_no_pending: "Die state_machine-Regel {{rule}} auf dem Feld {{field}} von {{object}} (Schritt {{step}} des Flows {{flow}}) deklariert die Übergänge aus {{value}} ohne pending; fügen Sie pending hinzu.", + readonly_when: "Das Feld {{field}} von {{object}} (Schritt {{step}} des Flows {{flow}}) trägt ein readonlyWhen; entfernen Sie es.", + option_visible_when: "Die Option {{value}} des Feldes {{field}} von {{object}} (Schritt {{step}} des Flows {{flow}}) trägt ein visibleWhen; entfernen Sie es.", + other_field: "Schritt {{step}} des Flows {{flow}} kann auf {{object}} wirken, schreibt aber in das Feld {{other}}; jeder Schritt, der auf {{object}} wirken kann, muss in {{field}} schreiben.", + no_field: "Schritt {{step}} des Flows {{flow}} kann auf {{object}} wirken, nennt aber kein Genehmigungsstatusfeld; jeder Schritt, der auf {{object}} wirken kann, muss in {{field}} schreiben.", + pause_between_steps: "Der Knoten {{node}} ({{type}}) des Flows {{flow}} kann den Lauf zwischen zwei Genehmigungsschritten von {{object}} anhalten; verschieben Sie ihn vor den ersten oder hinter den letzten Schritt.", + map_with_approval: "Der map-Knoten {{node}} des Flows {{flow}} führt für jedes Element einen Genehmigungsschritt aus, und der Knoten zeigt nicht, dass kein Element ein Datensatz ist; die Genehmigung eines anderen Datensatzes würde {{object}} zwischen zwei Schritten festhalten.", + }, + ja: { + no_pending_option: "{{object}} のフィールド {{field}}(フロー {{flow}} のステップ {{step}})は値 pending を宣言していません。フィールドの選択肢に追加してください。", + closes_in_flight: "{{object}} はフィールド {{field}} の {{value}} でクローズします(フロー {{flow}} のステップ {{step}})。これは進行中の承認のステータスです。{{value}} をオブジェクトの closedStates から外してください。", + state_machine_no_pending: "{{object}} のフィールド {{field}} にある state_machine ルール {{rule}}(フロー {{flow}} のステップ {{step}})は {{value}} からの遷移を宣言していますが、pending が含まれていません。pending を追加してください。", + readonly_when: "{{object}} のフィールド {{field}}(フロー {{flow}} のステップ {{step}})に readonlyWhen があります。削除してください。", + option_visible_when: "{{object}} のフィールド {{field}} の選択肢 {{value}}(フロー {{flow}} のステップ {{step}})に visibleWhen があります。削除してください。", + other_field: "フロー {{flow}} のステップ {{step}} は {{object}} に作用できますが、フィールド {{other}} にステータスを書き込みます。{{object}} に作用できるすべてのステップは {{field}} に書き込む必要があります。", + no_field: "フロー {{flow}} のステップ {{step}} は {{object}} に作用できますが、承認ステータスフィールドを指定していません。{{object}} に作用できるすべてのステップは {{field}} に書き込む必要があります。", + pause_between_steps: "フロー {{flow}} のノード {{node}}({{type}})は {{object}} の二つの承認ステップの間で実行を一時停止する可能性があります。最初のステップの前か最後のステップの後に移動してください。", + map_with_approval: "フロー {{flow}} の map ノード {{node}} は項目ごとに承認ステップを実行しますが、どの項目もレコードでないことをノードが示していません。別のレコードの承認により {{object}} が二つのステップの間で保留されます。", + }, + ko: { + no_pending_option: "{{object}}의 필드 {{field}}(흐름 {{flow}}의 단계 {{step}})는 값 pending을 선언하지 않습니다. 필드의 옵션에 추가하세요.", + closes_in_flight: "{{object}}는 필드 {{field}}의 {{value}}에서 닫힙니다(흐름 {{flow}}의 단계 {{step}}). 이는 진행 중인 승인의 상태입니다. 개체의 closedStates에서 {{value}}를 제거하세요.", + state_machine_no_pending: "{{object}}의 필드 {{field}}에 있는 state_machine 규칙 {{rule}}(흐름 {{flow}}의 단계 {{step}})은 {{value}}에서 나가는 전이를 선언하지만 pending이 없습니다. pending을 추가하세요.", + readonly_when: "{{object}}의 필드 {{field}}(흐름 {{flow}}의 단계 {{step}})에 readonlyWhen이 있습니다. 제거하세요.", + option_visible_when: "{{object}}의 필드 {{field}}의 옵션 {{value}}(흐름 {{flow}}의 단계 {{step}})에 visibleWhen이 있습니다. 제거하세요.", + other_field: "흐름 {{flow}}의 단계 {{step}}는 {{object}}에 작용할 수 있지만 필드 {{other}}에 상태를 기록합니다. {{object}}에 작용할 수 있는 모든 단계는 {{field}}에 기록해야 합니다.", + no_field: "흐름 {{flow}}의 단계 {{step}}는 {{object}}에 작용할 수 있지만 승인 상태 필드를 지정하지 않습니다. {{object}}에 작용할 수 있는 모든 단계는 {{field}}에 기록해야 합니다.", + pause_between_steps: "흐름 {{flow}}의 노드 {{node}}({{type}})는 {{object}}의 두 승인 단계 사이에서 실행을 일시 중지할 수 있습니다. 첫 단계 앞이나 마지막 단계 뒤로 옮기세요.", + map_with_approval: "흐름 {{flow}}의 map 노드 {{node}}는 항목마다 승인 단계를 실행하며, 노드는 어떤 항목도 레코드가 아님을 보여 주지 않습니다. 다른 레코드의 승인이 {{object}}를 두 단계 사이에 붙잡아 둘 수 있습니다.", + }, +}; + +function render(tag: string, p: UserTextParams): string { + const pack = SENTENCES[tag] ?? SENTENCES.en!; + const template = pack[p.kind as Kind] ?? SENTENCES.en![p.kind as Kind] ?? ''; + return template.replace(/\{\{(\w+)\}\}/g, (_, name: string) => p[name] ?? ''); +} + +export const APPROVAL_CLOSED_STATES_USER_TEXT: UserTextCatalog = Object.freeze({ + [APPROVAL_CLOSED_STATE_GAP]: { + en: (p) => render('en', p), + 'zh-Hans': (p) => render('zh-Hans', p), + 'zh-Hant': (p) => render('zh-Hant', p), + es: (p) => render('es', p), + ar: (p) => render('ar', p), + fr: (p) => render('fr', p), + 'pt-BR': (p) => render('pt-BR', p), + ru: (p) => render('ru', p), + de: (p) => render('de', p), + ja: (p) => render('ja', p), + ko: (p) => render('ko', p), + }, +}); diff --git a/packages/metadata-core/src/approval-opening.test.ts b/packages/metadata-core/src/approval-opening.test.ts new file mode 100644 index 00000000000..4b0eeac16ba --- /dev/null +++ b/packages/metadata-core/src/approval-opening.test.ts @@ -0,0 +1,67 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 D5; #37766] The one judge's two drivers agree: the first + * request's (`judgeApprovalOpening`, awaiting each read) and the authoring + * rule's (`judgeApprovalOpeningSync`, over a stack in hand). The conditions + * themselves are pinned arm by arm through the approvals plugin + * (`approval-opening-check.test.ts`) and the lint rule + * (`validate-approval-closed-states.test.ts`). + */ + +import { describe, expect, it } from 'vitest'; +import { + approvalFlowWalk, + judgeApprovalOpening, + judgeApprovalOpeningSync, + type OpeningCheckSource, + type OpeningFlow, + type OpeningFlowBody, +} from './approval-opening.js'; + +const STATUSES = ['draft', 'pending', 'returned', 'approved', 'rejected', 'recalled']; +const deal = { name: 'deal', closedStates: { status: ['approved', 'rejected'] }, fields: { status: { type: 'select', options: STATUSES.map((value) => ({ value })) } } }; + +const node = (id: string, type: string, config: Record = {}) => ({ id, type, config }); +function chain(...nodes: ReturnType[]): OpeningFlowBody { + const all = [node('start', 'start'), ...nodes, node('end', 'end')]; + return { nodes: all, edges: all.slice(1).map((b, i) => ({ source: all[i]!.id, target: b.id })) }; +} +const step = (id: string) => node(id, 'approval', { approvalStatusField: 'status' }); + +const flows: Record = { + root: chain(step('a1'), node('call', 'subflow', { flowName: 'child' }), step('a2')), + child: chain(node('w', 'wait')), +}; +const read = (name: string): OpeningFlow | null => (flows[name] ? { key: name, body: flows[name]! } : null); +const base = { + objectSchema: (name: string) => (name === 'deal' ? deal : undefined), + nodeDescriptor: (type: string) => ({ supportsPause: type === 'wait' }), + hostRunsReconciler: true, +}; +const input = { rootFlow: read('root'), rootFlowName: 'root', rootObject: 'deal' }; + +describe('the opening judge: one walk, two drivers', () => { + it('answers the same judgement over a reader that awaits and one that does not', async () => { + const sync: OpeningCheckSource = { ...base, calleeFlow: (name) => read(name) }; + const awaited: OpeningCheckSource = { ...base, calleeFlow: async (name) => read(name) }; + const a = judgeApprovalOpeningSync(input, sync); + const b = await judgeApprovalOpening(input, awaited); + expect(a).toEqual(b); + expect(a.gaps.map((g) => g.kind)).toEqual(['pause_between_steps']); + }); + + it('reads a promise handed to the synchronous driver as a flow it cannot read', () => { + const out = judgeApprovalOpeningSync(input, { ...base, calleeFlow: async (name) => read(name) }); + expect(out.gaps).toContainEqual({ kind: 'unreadable_flow', flow: 'child' }); + }); + + it('walks each callee once, and asks for each read with its caller', () => { + const asked: string[] = []; + const walk = approvalFlowWalk(read('root')!); + let step = walk.next(); + while (!step.done) { asked.push(`${step.value.callerKey}>${step.value.name}`); step = walk.next(read(step.value.name)); } + expect(asked).toEqual(['root>child']); + expect([...step.value.flows.keys()]).toEqual(['root', 'child']); + }); +}); diff --git a/packages/metadata-core/src/approval-opening.ts b/packages/metadata-core/src/approval-opening.ts new file mode 100644 index 00000000000..91d9ec8de5e --- /dev/null +++ b/packages/metadata-core/src/approval-opening.ts @@ -0,0 +1,719 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 D5, Execution item 7 "The check"; #37766] The ONE judge of the + * conditions an approval opens on, wherever they are asked. + * + * Two doors ask it, and both read this module so that they cannot disagree: + * + * - **The approval's first request** (`@objectstack/plugin-approvals`, + * `ApprovalService.judgeOpening`), which reads the engine as it holds the + * approval and refuses the request. That stays the rule (ADR-0162 D5). + * - **Authoring** (`@objectstack/lint`, `validateApprovalClosedStates`, a + * member of the reference-integrity suite in the shared author-time rule + * table), which `os validate`, `os build`, `os lint` and the runtime publish + * door run on what is in view, and refuses the author (maintainer ruling + * 7253749311 on #37766, option D). + * + * Both depend on this package, which depends on `@objectstack/spec` alone, as + * `flow-cycle.ts` is shared between the engine and the authoring gate. The + * first request reads asynchronously ({@link judgeApprovalOpening}); the + * authoring rule reads a stack in hand ({@link judgeApprovalOpeningSync}). The + * two drivers walk the approval through one generator + * ({@link approvalFlowWalk}) and judge it with one function, so the verdict + * has one copy. + * + * An approval is one passage of a record through its approval flow, taken as + * a whole: the flow its root run was started on, and every flow a `subflow` + * or a `map` in it names, to any depth. This module reads that whole once and + * answers three things: + * + * 1. **Whether the approval touches an object that declares `closedStates`**: + * a step of it can act on such an object. Only then is anything stamped or + * refused. + * 2. **The set of nodes that stand between two steps** ({@link OpeningJudgement.between}), + * which each request of the approval carries from its opening, so that the + * plugin can later place a stop or a pause against it (ADR-0162 item 8, + * design note 7210179412 question 3, T2). It is stamped for every approval + * that touches such an object, also one the conditions do not concern. + * 3. **What is missing**, for every step whose mirror field the object closes + * on at a status the mirror writes for a request that is not abandoned + * (`pending`, `returned`, `approved`, `rejected`): the five conditions of + * ADR-0162 D5 as revised on 2026-11-27, the approval's unread parts, and + * the host's `job` service. + * + * Between two steps means after a step is decided, whichever way, and before + * the next step opens; the next step can be the same step opened again (a + * `map` body or a `loop` body that holds one). The read is a reachability + * over one graph of the whole approval: every node of every flow, a `subflow` + * or a `map` joined to the body it calls, every region (`loop`, `parallel`, + * `try_catch`) joined to its container. It is context-insensitive and errs one + * way only: a node that could stand between two steps on some path counts as + * standing there. A stop wrongly read as "between" costs a resubmission; the + * other error would close a document on an unfinished approval (ADR-0162 D5). + * + * Pure over a {@link OpeningCheckSource}: each door hands it the readers it + * has, and the tests hand it fixtures. + */ + +import { FLOW_REGION_SLOTS_BY_TYPE } from '@objectstack/spec/automation'; + +/** The statuses the mirror writes for a request that is not abandoned. */ +const IN_APPROVAL_STATUSES = ['pending', 'returned', 'approved', 'rejected'] as const; +/** The statuses of a request whose option may carry no `visibleWhen` (D5 condition 3). */ +const REQUEST_STATUSES = ['pending', 'returned', 'approved', 'rejected', 'recalled'] as const; +/** The node types that have no executor and cannot pause (N43). */ +const STRUCTURAL_TYPES: ReadonlySet = new Set(['start', 'end']); +/** The type of an approval step. */ +const APPROVAL_TYPE = 'approval'; +/** The revise window of a returned request: not a pause between two steps (D5, ADR-0044). */ +const REVISE_WINDOW_TYPE = 'approval_revise'; +/** The two node types that call another flow; they are read by their bodies. */ +const CALL_TYPES: ReadonlySet = new Set(['subflow', 'map']); +/** How many flows one approval may name before it is read as not readable whole. */ +const MAX_FLOWS = 64; +/** How many region levels the read descends. */ +const MAX_REGION_DEPTH = 16; +/** How many `aliasOf` hops a node type's descriptor is followed. */ +const MAX_ALIAS_HOPS = 8; + +/** A flow body as the engine holds it: the parts this check reads. */ +export interface OpeningFlowBody { + nodes?: ReadonlyArray; + edges?: ReadonlyArray; +} +export interface OpeningFlowNode { + id: string; + type?: string; + label?: string; + config?: Record | null; +} +export interface OpeningFlowEdge { + source: string; + target: string; +} + +/** A flow the check read, by the key the engine files it under. */ +export interface OpeningFlow { + key: string; + body: OpeningFlowBody; +} + +/** The readers the check needs. Every one answers, never throws: the service wraps its reads. */ +export interface OpeningCheckSource { + /** The object definition registered under `name`, or `undefined`. */ + objectSchema(name: string): unknown; + /** + * The flow a `subflow` or a `map` of the flow filed under `callerKey` names + * as `name`; `null` when it cannot be read. {@link judgeApprovalOpeningSync} + * reads a promise as a flow it cannot read. + */ + calleeFlow(name: string, callerKey: string): OpeningFlow | null | Promise; + /** + * The published descriptor of a node type: `undefined` where the type + * publishes none, `'unread'` where the engine cannot be asked. + */ + nodeDescriptor(type: string): { supportsPause?: unknown; aliasOf?: unknown } | undefined | 'unread'; + /** Whether the host runs the plugin's sweeps, the reconciler of ADR-0162 item 8 (a `job` service). */ + hostRunsReconciler: boolean; +} + +/** One thing that keeps the approval from opening. */ +export type OpeningGap = + | { kind: 'no_pending_option'; flow: string; step: string; object: string; field: string } + | { kind: 'closes_in_flight'; flow: string; step: string; object: string; field: string; value: string } + | { kind: 'state_machine_no_pending'; flow: string; step: string; object: string; field: string; value: string; rule: string } + | { kind: 'readonly_when'; flow: string; step: string; object: string; field: string } + | { kind: 'option_visible_when'; flow: string; step: string; object: string; field: string; value: string } + | { kind: 'other_field'; flow: string; step: string; object: string; field: string; other: string } + | { kind: 'no_field'; flow: string; step: string; object: string; field: string } + | { kind: 'pause_between_steps'; flow: string; node: string; type: string; object: string } + | { kind: 'map_with_approval'; flow: string; node: string; object: string } + | { kind: 'unreadable_flow'; flow: string } + | { kind: 'no_job_service'; object: string }; + +/** One node of the between-two-steps set: the flow it is in, by the key the engine files it under, and its id. */ +export interface BetweenNode { + flow: string; + node: string; +} + +/** What the check answers for an approval's first request. */ +export interface OpeningJudgement { + /** Whether a step of the approval can act on an object that declares `closedStates`. */ + touchesClosedStates: boolean; + /** The nodes that stand between two steps, sorted; stamped only where {@link touchesClosedStates}. */ + between: BetweenNode[]; + /** What keeps the approval from opening; empty when it opens. */ + gaps: OpeningGap[]; +} + +/** What the check is handed about the run that opens the request. */ +export interface OpeningCheckInput { + /** The flow the approval's root run was started on, read by the caller; `null` when it could not be read. */ + rootFlow: OpeningFlow | null; + /** The flow name of the root run, for a refusal that names an unread root flow. */ + rootFlowName: string; + /** The object of the root run's record; `null` for a root run that carries none (a batch). */ + rootObject: string | null; +} + +/** An object's declared closed values, field → values, or `undefined` when it declares none. */ +export function closedValuesOf(schema: unknown): ReadonlyMap> | undefined { + const declared = (schema as { closedStates?: unknown } | null | undefined)?.closedStates; + if (!declared || typeof declared !== 'object' || Array.isArray(declared)) return undefined; + const out = new Map>(); + for (const [field, values] of Object.entries(declared as Record)) { + if (!Array.isArray(values)) continue; + const set = new Set(values.filter((v): v is string => typeof v === 'string')); + if (set.size > 0) out.set(field, set); + } + return out.size > 0 ? out : undefined; +} + +/** A vertex of the approval's graph. A node is one vertex; a container or a call is two (its entry and its exit). */ +type Vertex = string; + +interface StepInfo { + flow: string; + node: OpeningFlowNode; + field: string | undefined; +} + +interface MapInfo { + flow: string; + node: OpeningFlowNode; + callee: string | null; + /** Whether the node shows that none of its items is a record (items written out, none of them one). */ + noRecordItems: boolean; +} + +/** One read the walk asks of its driver: the flow a call node names. */ +export interface ApprovalFlowRead { + name: string; + callerKey: string; +} + +/** What the walk of an approval's flows answers. */ +export interface ApprovalFlowWalk { + flows: Map; + calls: Map>; + gaps: OpeningGap[]; +} + +/** + * Read every flow of the approval, to any depth, from its root: a generator + * that yields each read it needs ({@link ApprovalFlowRead}) and is resumed + * with the flow read, or `null`. The two drivers below answer the reads, one + * awaiting them and one not, so the walk has one copy. + */ +export function* approvalFlowWalk(root: OpeningFlow): Generator { + const gaps: OpeningGap[] = []; + const flows = new Map(); + /** For each flow: the flows it calls, by call node, with how the call hands objects down. */ + const calls = new Map>(); + const queue: OpeningFlow[] = [root]; + flows.set(root.key, root.body); + while (queue.length > 0) { + const { key, body } = queue.shift()!; + const out: Array<{ node: OpeningFlowNode; callee: string | null; kind: 'subflow' | 'map' }> = []; + for (const node of allNodes(body)) { + if (!node.type || !CALL_TYPES.has(node.type)) continue; + const name = typeof node.config?.flowName === 'string' ? node.config.flowName : ''; + if (!name) { + gaps.push({ kind: 'unreadable_flow', flow: `${key} › ${node.id}` }); + out.push({ node, callee: null, kind: node.type as 'subflow' | 'map' }); + continue; + } + const callee = yield { name, callerKey: key }; + if (!callee) { + gaps.push({ kind: 'unreadable_flow', flow: name }); + out.push({ node, callee: null, kind: node.type as 'subflow' | 'map' }); + continue; + } + out.push({ node, callee: callee.key, kind: node.type as 'subflow' | 'map' }); + if (!flows.has(callee.key)) { + if (flows.size >= MAX_FLOWS) { + gaps.push({ kind: 'unreadable_flow', flow: name }); + continue; + } + flows.set(callee.key, callee.body); + queue.push(callee); + } + } + calls.set(key, out); + } + return { flows, calls, gaps }; +} + +/** + * Read the approval whole and judge it, awaiting each read (the first + * request). Never throws: a part that cannot be read is a gap + * ({@link OpeningGap} `unreadable_flow`), and an approval with one cannot be + * judged, so it does not open. + */ +export async function judgeApprovalOpening(input: OpeningCheckInput, source: OpeningCheckSource): Promise { + if (!input.rootFlow) return unreadRoot(input); + const walk = approvalFlowWalk(input.rootFlow); + let step = walk.next(); + while (!step.done) step = walk.next(await source.calleeFlow(step.value.name, step.value.callerKey)); + return judgeWalkedApproval(input, input.rootFlow, step.value, source); +} + +/** + * The same judgement over readers that answer at once (a stack in hand: the + * authoring rule). A read answered with a promise is a flow it cannot read. + */ +export function judgeApprovalOpeningSync(input: OpeningCheckInput, source: OpeningCheckSource): OpeningJudgement { + if (!input.rootFlow) return unreadRoot(input); + const walk = approvalFlowWalk(input.rootFlow); + let step = walk.next(); + while (!step.done) { + const read = source.calleeFlow(step.value.name, step.value.callerKey); + step = walk.next(read instanceof Promise ? null : read); + } + return judgeWalkedApproval(input, input.rootFlow, step.value, source); +} + +function unreadRoot(input: OpeningCheckInput): OpeningJudgement { + return { touchesClosedStates: true, between: [], gaps: [{ kind: 'unreadable_flow', flow: input.rootFlowName }] }; +} + +/** Judge an approval whose flows {@link approvalFlowWalk} has read. */ +function judgeWalkedApproval( + input: OpeningCheckInput, + rootFlow: OpeningFlow, + walked: ApprovalFlowWalk, + source: OpeningCheckSource, +): OpeningJudgement { + const { flows, calls } = walked; + const gaps: OpeningGap[] = [...walked.gaps]; + + // ── 2. The objects each flow's steps can act on ─────────────────────────── + // The root flow acts on the root run's record. A `subflow` body acts on its + // caller's record. A `map` body acts on an item where the item is a record, + // on the object the node names for its items (else its caller's), and on its + // caller's record where the item is not one; the check cannot read ahead + // whether an item is a record unless the items are written out in the node. + const objects = new Map>(); + for (const key of flows.keys()) objects.set(key, new Set()); + if (input.rootObject) objects.get(rootFlow.key)!.add(input.rootObject); + const maps: MapInfo[] = []; + for (const [key, list] of calls) { + for (const call of list) { + if (call.kind === 'map') maps.push({ flow: key, node: call.node, callee: call.callee, noRecordItems: itemsShowNoRecord(call.node) }); + } + } + for (let changed = true, rounds = 0; changed && rounds <= flows.size + 1; rounds++) { + changed = false; + for (const [key, list] of calls) { + const mine = objects.get(key)!; + for (const call of list) { + if (!call.callee) continue; + const theirs = objects.get(call.callee)!; + const before = theirs.size; + if (call.kind === 'subflow') { + for (const o of mine) theirs.add(o); + } else { + const items = mapItems(call.node); + const anyRecord = items === undefined || items.some(isRecordItem); + const anyOther = items === undefined || items.some((i) => !isRecordItem(i)); + if (anyOther) for (const o of mine) theirs.add(o); + if (anyRecord) { + const itemObject = typeof call.node.config?.itemObject === 'string' && call.node.config.itemObject + ? call.node.config.itemObject : undefined; + if (itemObject) theirs.add(itemObject); + else for (const o of mine) theirs.add(o); + } + } + if (theirs.size !== before) changed = true; + } + } + } + + // ── 3. The steps, and whether the approval touches a closing object ─────── + const steps: StepInfo[] = []; + for (const [key, body] of flows) { + for (const node of allNodes(body)) { + if (node.type !== APPROVAL_TYPE) continue; + const field = typeof node.config?.approvalStatusField === 'string' && node.config.approvalStatusField + ? node.config.approvalStatusField : undefined; + steps.push({ flow: key, node, field }); + } + } + const declaring = (object: string) => closedValuesOf(source.objectSchema(object)) !== undefined; + const touchesClosedStates = gaps.length > 0 + || steps.some((s) => [...objects.get(s.flow)!].some(declaring)); + if (!touchesClosedStates) return { touchesClosedStates: false, between: [], gaps: [] }; + + // ── 4. The nodes between two steps ──────────────────────────────────────── + const graph = buildGraph(flows, calls); + const stepVertices = steps.map((s) => vertexOf(s.flow, s.node.id)); + const after = reach(graph.succ, stepVertices); + const before = reach(graph.pred, stepVertices); + const betweenKeys = new Set(); + const pausing: Array<{ flow: string; node: OpeningFlowNode }> = []; + // A node other than a step is between two steps where a step can come + // before it and a step can follow it. A step is in the set where a step can + // follow it: a run that stops on a step decided with no later step logged + // (design note question 3, T2) stopped between two steps exactly then. + for (const [vertex, owner] of graph.owner) { + if (!before.has(vertex)) continue; + const isStep = owner.node.type === APPROVAL_TYPE; + if (!isStep && !after.has(vertex)) continue; + const k = `${owner.flow}\u0000${owner.node.id}`; + if (betweenKeys.has(k)) continue; + betweenKeys.add(k); + if (!isStep && canPause(owner.node, source)) pausing.push(owner); + } + // A `map` or a `loop` whose body holds a step stands between two steps + // where it is entered before a step and left after one: between one item's + // (one pass's) step and the next, the run is parked at the node or back on + // it. A `subflow` is not: its body runs once. + for (const { flow, node } of graph.owner.values()) { + if (node.type !== 'map' && node.type !== 'loop') continue; + if (before.has(vertexOf(flow, node.id, 'in')) && after.has(vertexOf(flow, node.id, 'out'))) { + betweenKeys.add(`${flow}\u0000${node.id}`); + } + } + const between = [...betweenKeys] + .map((k) => { const [flow, node] = k.split('\u0000'); return { flow, node }; }) + .sort((a, b) => (a.flow === b.flow ? cmp(a.node, b.node) : cmp(a.flow, b.flow))); + + // ── 5. The conditions, for every step they concern ──────────────────────── + const concernedObjects = new Set(); + for (const step of steps) { + for (const object of objects.get(step.flow)!) { + const schema = source.objectSchema(object); + const closed = closedValuesOf(schema); + if (!closed || !step.field) continue; + const values = closed.get(step.field); + if (!values || !IN_APPROVAL_STATUSES.some((s) => values.has(s))) continue; + concernedObjects.add(object); + judgeField(step, object, step.field, schema, values, gaps); + // Condition 4: every step that can act on a record of the object names that field. + for (const other of steps) { + if (other === step || !objects.get(other.flow)!.has(object)) continue; + if (other.field === step.field) continue; + if (other.field) gaps.push({ kind: 'other_field', flow: other.flow, step: other.node.id, object, field: step.field, other: other.field }); + else gaps.push({ kind: 'no_field', flow: other.flow, step: other.node.id, object, field: step.field }); + } + } + } + if (concernedObjects.size > 0) { + const object = [...concernedObjects].sort(cmp)[0]; + // Condition 5: no node that can pause the run of itself stands between two steps. + for (const p of pausing) { + gaps.push({ kind: 'pause_between_steps', flow: p.flow, node: p.node.id, type: String(p.node.type ?? ''), object }); + } + // Condition 5, its second half: no `map` with an approval step in its body, + // at any depth, where the parent's object is one the conditions concern, + // unless the node shows that none of its items is a record. + const holdsStep = flowsHoldingSteps(flows, calls, steps); + for (const m of maps) { + if (!m.callee || !holdsStep.has(m.callee) || m.noRecordItems) continue; + const parentObjects = [...objects.get(m.flow)!].filter((o) => concernedObjects.has(o)).sort(cmp); + if (parentObjects.length > 0) gaps.push({ kind: 'map_with_approval', flow: m.flow, node: m.node.id, object: parentObjects[0] }); + } + } + + // ── 6. The host ─────────────────────────────────────────────────────────── + if (!source.hostRunsReconciler) { + const object = steps.flatMap((s) => [...objects.get(s.flow)!]).filter(declaring).sort(cmp)[0]; + if (object) gaps.push({ kind: 'no_job_service', object }); + } + + return { touchesClosedStates, between, gaps: dedupe(gaps) }; +} + +/** D5 conditions 1 to 3, on the field `field` of `object`, for `step`. */ +function judgeField( + step: StepInfo, object: string, field: string, schema: unknown, + closed: ReadonlySet, gaps: OpeningGap[], +): void { + const flow = step.flow; + const stepId = step.node.id; + const def = (schema as { fields?: Record } | undefined)?.fields?.[field] as + { options?: unknown; readonlyWhen?: unknown } | undefined; + const options = Array.isArray(def?.options) ? def!.options as unknown[] : []; + const optionOf = (value: string): Record | undefined => { + for (const o of options) { + if (o && typeof o === 'object' && String((o as { value?: unknown }).value) === value) return o as Record; + } + return undefined; + }; + const declares = (value: string) => options.some((o) => (o && typeof o === 'object' ? String((o as { value?: unknown }).value) : String(o)) === value); + + // 1. The field declares `pending`, and the object closes on neither `pending` nor `returned`. + if (!declares('pending')) gaps.push({ kind: 'no_pending_option', flow, step: stepId, object, field }); + for (const value of ['pending', 'returned']) { + if (closed.has(value)) gaps.push({ kind: 'closes_in_flight', flow, step: stepId, object, field, value }); + } + + // 2. A `state_machine` rule on the field that declares the moves out of a + // closed `approved` or `rejected` has `pending` among them. + const rules = (schema as { validations?: unknown } | undefined)?.validations; + if (Array.isArray(rules)) { + for (const rule of rules) { + const r = rule as { type?: unknown; field?: unknown; active?: unknown; transitions?: unknown; name?: unknown } | null; + if (!r || r.type !== 'state_machine' || r.field !== field || r.active === false) continue; + const transitions = r.transitions && typeof r.transitions === 'object' ? r.transitions as Record : {}; + for (const value of ['approved', 'rejected']) { + if (!closed.has(value) || !Object.prototype.hasOwnProperty.call(transitions, value)) continue; + const moves = transitions[value]; + if (!Array.isArray(moves) || !moves.includes('pending')) { + gaps.push({ kind: 'state_machine_no_pending', flow, step: stepId, object, field, value, rule: String(r.name ?? '') }); + } + } + } + } + + // 3. The field carries no `readonlyWhen`, and none of its options for a request's status carries a `visibleWhen`. + if (def?.readonlyWhen != null) gaps.push({ kind: 'readonly_when', flow, step: stepId, object, field }); + for (const value of REQUEST_STATUSES) { + const option = optionOf(value); + if (option && option.visibleWhen != null) gaps.push({ kind: 'option_visible_when', flow, step: stepId, object, field, value }); + } +} + +/** Whether a node can pause the run of itself, by what its type declares (D5 condition 5, N43). */ +function canPause(node: OpeningFlowNode, source: OpeningCheckSource): boolean { + const type = node.type; + if (!type) return true; // a node it cannot place counts as one that can + if (STRUCTURAL_TYPES.has(type) || type === APPROVAL_TYPE || type === REVISE_WINDOW_TYPE || CALL_TYPES.has(type)) return false; + let descriptor = source.nodeDescriptor(type); + for (let hop = 0; descriptor && descriptor !== 'unread' && typeof descriptor.aliasOf === 'string' && hop < MAX_ALIAS_HOPS; hop++) { + const canonical = source.nodeDescriptor(descriptor.aliasOf as string); + if (!canonical || canonical === 'unread' || canonical === descriptor) break; + descriptor = canonical; + } + if (descriptor === 'unread' || descriptor === undefined) return true; + return descriptor.supportsPause === true; +} + +/** Every node of a body, its regions' nodes included, to {@link MAX_REGION_DEPTH}. */ +function allNodes(body: OpeningFlowBody): OpeningFlowNode[] { + const out: OpeningFlowNode[] = []; + const visit = (nodes: ReadonlyArray | undefined, depth: number) => { + for (const node of nodes ?? []) { + if (!node || typeof node !== 'object' || typeof node.id !== 'string') continue; + out.push(node); + if (depth >= MAX_REGION_DEPTH) continue; + for (const region of regionsOf(node)) visit(region.nodes, depth + 1); + } + }; + visit(body.nodes, 0); + return out; +} + +/** The regions a container node holds, in slot order. */ +function regionsOf(node: OpeningFlowNode): Array<{ slot: string; region: OpeningFlowBody } & OpeningFlowBody> { + const slots = node.type ? FLOW_REGION_SLOTS_BY_TYPE.get(node.type) : undefined; + if (!slots) return []; + const out: Array<{ slot: string; region: OpeningFlowBody } & OpeningFlowBody> = []; + for (const slot of slots) { + const value = node.config?.[slot.key]; + const list = slot.arity === 'many' ? (Array.isArray(value) ? value : []) : (value ? [value] : []); + list.forEach((raw, i) => { + // A `parallel` branch carries its region beside its name; read either shape. + const region = raw && typeof raw === 'object' && 'region' in (raw as object) + ? (raw as { region?: OpeningFlowBody }).region : raw as OpeningFlowBody; + if (region && typeof region === 'object') { + out.push({ slot: `${slot.key}[${i}]`, region, nodes: region.nodes, edges: region.edges }); + } + }); + } + return out; +} + +/** The items a `map` node writes out in itself, or `undefined` where they are read from an expression. */ +function mapItems(node: OpeningFlowNode): unknown[] | undefined { + const collection = node.config?.collection; + return Array.isArray(collection) ? collection : undefined; +} + +/** Whether an item is a record, read as the `map` node reads it (an object with a string `id`). */ +function isRecordItem(item: unknown): boolean { + return item != null && typeof item === 'object' && typeof (item as { id?: unknown }).id === 'string'; +} + +/** Whether a `map` node shows that none of its items is a record: its items are written out, and none is one. */ +function itemsShowNoRecord(node: OpeningFlowNode): boolean { + const items = mapItems(node); + return items !== undefined && !items.some(isRecordItem); +} + +/** The flows whose body holds an approval step at any depth, through the flows it calls. */ +function flowsHoldingSteps( + flows: Map, + calls: Map>, + steps: StepInfo[], +): Set { + const holds = new Set(steps.map((s) => s.flow)); + for (let changed = true, rounds = 0; changed && rounds <= flows.size + 1; rounds++) { + changed = false; + for (const [key, list] of calls) { + if (holds.has(key)) continue; + if (list.some((c) => c.callee && holds.has(c.callee))) { holds.add(key); changed = true; } + } + } + return holds; +} + +function vertexOf(flow: string, node: string, part = ''): Vertex { + return `${flow}\u0000${node}\u0000${part}`; +} + +interface Graph { + succ: Map>; + pred: Map>; + /** Each vertex that stands for a node, with the node and its flow. Synthetic vertices are absent. */ + owner: Map; +} + +/** + * One graph of the whole approval. A plain node is one vertex. A container + * (`loop`, `parallel`, `try_catch`) and a call (`subflow`, `map`) are two, its + * entry and its exit, joined through the regions or the body it runs: + * - a region or a called body is entered from the entry and left to the exit; + * - a `loop` body and a `map` body may run again (exit → entry) or not at all + * (entry → exit); + * - the branches of a `parallel` may interleave, so each branch's exit leads + * into every other branch; + * - every node of a `try` region may fail into its `catch` region and to the + * container's exit; + * - an edge of the flow, a `fault` edge included, leads from its source's exit + * to its target's entry. + * A step is one vertex: its decision leaves it. + */ +function buildGraph( + flows: Map, + calls: Map>, +): Graph { + const succ = new Map>(); + const pred = new Map>(); + const owner = new Map(); + const link = (a: Vertex, b: Vertex) => { + if (!succ.has(a)) succ.set(a, new Set()); + if (!pred.has(b)) pred.set(b, new Set()); + succ.get(a)!.add(b); + pred.get(b)!.add(a); + }; + const entryOfFlow = (key: string) => vertexOf(key, '', 'flow-entry'); + const exitOfFlow = (key: string) => vertexOf(key, '', 'flow-exit'); + const calleeOf = new Map(); + for (const [key, list] of calls) for (const c of list) calleeOf.set(`${key}\u0000${c.node.id}`, c); + + const isCompound = (node: OpeningFlowNode) => !!node.type && (CALL_TYPES.has(node.type) || FLOW_REGION_SLOTS_BY_TYPE.has(node.type)); + const inOf = (flow: string, node: OpeningFlowNode) => vertexOf(flow, node.id, isCompound(node) ? 'in' : ''); + const outOf = (flow: string, node: OpeningFlowNode) => vertexOf(flow, node.id, isCompound(node) ? 'out' : ''); + + /** Wire one graph (a flow's top level or a region); answers its entry and exit vertices. */ + const wire = (flow: string, nodes: ReadonlyArray | undefined, edges: ReadonlyArray | undefined, depth: number): + { entries: Vertex[]; exits: Vertex[]; inner: Vertex[] } => { + const list = (nodes ?? []).filter((n) => n && typeof n === 'object' && typeof n.id === 'string'); + const byId = new Map(list.map((n) => [n.id, n])); + const inner: Vertex[] = []; + const hasIn = new Set(); + const hasOut = new Set(); + for (const e of edges ?? []) { + const a = byId.get(e?.source); + const b = byId.get(e?.target); + if (!a || !b) continue; + link(outOf(flow, a), inOf(flow, b)); + hasOut.add(a.id); + hasIn.add(b.id); + } + for (const node of list) { + const vin = inOf(flow, node); + const vout = outOf(flow, node); + owner.set(vin, { flow, node }); + owner.set(vout, { flow, node }); + inner.push(vin); + if (vout !== vin) inner.push(vout); + const call = calleeOf.get(`${flow}\u0000${node.id}`); + if (call) { + if (call.callee) { + link(vin, entryOfFlow(call.callee)); + link(exitOfFlow(call.callee), vout); + if (call.kind === 'map') link(exitOfFlow(call.callee), entryOfFlow(call.callee)); + } else { + link(vin, vout); + } + if (call.kind === 'map') link(vin, vout); + continue; + } + const regions = depth < MAX_REGION_DEPTH ? regionsOf(node) : []; + if (node.type && FLOW_REGION_SLOTS_BY_TYPE.has(node.type)) { + const wired = regions.map((r) => ({ slot: r.slot, ...wire(flow, r.nodes, r.edges, depth + 1) })); + if (wired.length === 0) link(vin, vout); + if (node.type === 'try_catch') { + const tryR = wired.filter((w) => w.slot.startsWith('try')); + const catchR = wired.filter((w) => w.slot.startsWith('catch')); + for (const t of tryR) { + for (const e of t.entries) link(vin, e); + for (const x of t.exits) link(x, vout); + for (const v of t.inner) { + link(v, vout); + for (const c of catchR) for (const e of c.entries) link(v, e); + } + } + for (const c of catchR) for (const x of c.exits) link(x, vout); + } else { + for (const w of wired) { + for (const e of w.entries) link(vin, e); + for (const x of w.exits) link(x, vout); + } + if (node.type === 'loop') { + link(vin, vout); + for (const w of wired) for (const x of w.exits) for (const e of w.entries) link(x, e); + } + if (node.type === 'parallel') { + for (const a of wired) for (const b of wired) { + if (a === b) continue; + for (const x of a.exits) for (const e of b.entries) link(x, e); + } + } + } + } + } + const entries = list.filter((n) => (depth === 0 ? n.type === 'start' || !hasIn.has(n.id) : !hasIn.has(n.id))).map((n) => inOf(flow, n)); + const exits = list.filter((n) => !hasOut.has(n.id)).map((n) => outOf(flow, n)); + return { entries, exits, inner }; + }; + + for (const [key, body] of flows) { + const { entries, exits } = wire(key, body.nodes, body.edges, 0); + for (const e of entries) link(entryOfFlow(key), e); + for (const x of exits) link(x, exitOfFlow(key)); + } + return { succ, pred, owner }; +} + +/** The vertices reachable from `starts` by one edge or more. */ +function reach(edges: Map>, starts: Vertex[]): Set { + const seen = new Set(); + const stack: Vertex[] = []; + for (const s of starts) for (const n of edges.get(s) ?? []) stack.push(n); + while (stack.length > 0) { + const v = stack.pop()!; + if (seen.has(v)) continue; + seen.add(v); + for (const n of edges.get(v) ?? []) if (!seen.has(n)) stack.push(n); + } + return seen; +} + +function cmp(a: string, b: string): number { + return a < b ? -1 : a > b ? 1 : 0; +} + +function dedupe(gaps: OpeningGap[]): OpeningGap[] { + const seen = new Set(); + return gaps.filter((g) => { + const k = JSON.stringify(g); + if (seen.has(k)) return false; + seen.add(k); + return true; + }); +} diff --git a/packages/metadata-core/src/index.ts b/packages/metadata-core/src/index.ts index 7ff5e75a786..1ca977714e1 100644 --- a/packages/metadata-core/src/index.ts +++ b/packages/metadata-core/src/index.ts @@ -158,6 +158,11 @@ export * from './extension-field-patch-targets.js'; // engine refuses to register no longer reads valid and publishes. export * from './flow-cycle.js'; +// [ADR-0162 D5, #37766] The ONE judge of the conditions an approval opens on: +// the approvals plugin asks it at an approval's first request, and the lint +// rule `validateApprovalClosedStates` asks it at every authoring door. +export * from './approval-opening.js'; + // [epic cloud#3652 Q3] The package upgrade plan — one comparison of an installed // package version with the incoming one, read by `os diff`, the marketplace // install door's dry run and the `manifest` service's `planUpgrade`, so the diff --git a/packages/plugins/plugin-approvals/src/approval-closed-states-37766.integration.test.ts b/packages/plugins/plugin-approvals/src/approval-closed-states-37766.integration.test.ts new file mode 100644 index 00000000000..bf50f446ff0 --- /dev/null +++ b/packages/plugins/plugin-approvals/src/approval-closed-states-37766.integration.test.ts @@ -0,0 +1,155 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 D5, Execution item 7; #37766 N45, ruling 7253749311 option D] The + * opening conditions at the real metadata door, from the shared author-time + * rule `validateApprovalClosedStates` (`@objectstack/lint`): an active save of + * a flow or an object where an approval could not show itself in progress on + * a closing field is refused; a draft is not, its promotion is; and a package + * publish is judged as the batch leaves it live (S3 of the review of #38527, + * confirmed here: the door's pending declarations already carry the batch). + * The approvals plugin adds no gate of its own. + * + * Real kernel, real ObjectQL engine and metadata protocol, real automation + * engine, the real approvals plugin, driver-sql on better-sqlite3 `:memory:`. + */ + +import { describe, it, expect, afterEach } from 'vitest'; +import { ObjectKernel } from '@objectstack/core'; +import { ObjectQLPlugin, type ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { AutomationServicePlugin } from '@objectstack/service-automation'; +import { ApprovalsServicePlugin } from './approvals-plugin.js'; + +const text = (name: string) => ({ name, type: 'text' as const }); +const statusField = { + name: 'approval_status', type: 'select' as const, defaultValue: 'draft', + options: ['draft', 'pending', 'returned', 'approved', 'rejected', 'recalled'].map((value) => ({ label: value, value })), +}; +const fields = { name: text('name'), approval_status: statusField }; + +const step = (id: string, approver: string) => ({ + id, type: 'approval', label: id, + config: { approvers: [{ type: 'user', value: approver }], approvalStatusField: 'approval_status' }, +}); + +/** Two steps on `object`'s approval field, with a timer between them where `hold`: D5 condition 5. */ +function approvalFlow(name: string, object: string, hold: boolean) { + const nodes: any[] = [ + { id: 'start', type: 'start', label: 'Start', config: { objectName: object, triggerType: 'record-after-update' } }, + step('first', 'approver'), + ...(hold ? [{ id: 'hold', type: 'wait', label: 'Hold', waitEventConfig: { eventType: 'timer', timerDuration: 'PT1H' } }] : []), + step('second', 'approver2'), + { id: 'end', type: 'end', label: 'End' }, + ]; + const afterFirst = hold ? 'hold' : 'second'; + return { + name, label: name, type: 'autolaunched', + nodes, + edges: [ + { id: 'e0', source: 'start', target: 'first' }, + { id: 'e1a', source: 'first', target: afterFirst, label: 'approve' }, + { id: 'e1r', source: 'first', target: 'end', label: 'reject' }, + ...(hold ? [{ id: 'e2', source: 'hold', target: 'second' }] : []), + { id: 'e3a', source: 'second', target: 'end', label: 'approve' }, + { id: 'e3r', source: 'second', target: 'end', label: 'reject' }, + ], + }; +} + +describe('[ADR-0162 item 7, N45 as ruled] the opening conditions at the metadata door', () => { + let kernel: ObjectKernel; + let ql: ObjectQL; + let protocol: any; + + afterEach(async () => { + try { await kernel?.shutdown(); } catch { /* noop */ } + }); + + async function boot() { + kernel = new ObjectKernel({ logger: { level: 'silent' } } as any); + await kernel.use(new ObjectQLPlugin()); + await kernel.use(new AutomationServicePlugin()); + await kernel.use(new ApprovalsServicePlugin()); + await kernel.bootstrap(); + ql = kernel.getService('objectql'); + protocol = kernel.getService('protocol'); + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); + await driver.connect(); + ql.registerDriver(driver, true); + (ql.registry as any).installPackage({ id: PKG, name: PKG, version: '1.0.0', type: 'app', namespace: 'crm' }, 'authored'); + await ql.syncSchemas(); + } + + /** An authored package the saves go into, as `POST /packages` installs one. */ + const PKG = 'app.crm'; + const authored = { name: 'crm_note', label: 'Note', sharingModel: 'private', fields }; + const closing = { ...authored, closedStates: { approval_status: ['approved', 'rejected'] } }; + const flowRows = async (name: string) => + (await ql.find('sys_metadata', { where: { type: 'flow', name }, context: { isSystem: true } })) as any[]; + const refusalText = (err: any) => JSON.stringify({ message: err?.message, issues: err?.issues ?? err?.details }); + + it('refuses an active flow save whose approval holds a pause between two steps on a closing field', async () => { + await boot(); + expect((await protocol.saveMetaItem({ type: 'object', name: 'crm_note', item: closing, packageId: PKG })).success).toBe(true); + const err = await protocol.saveMetaItem({ + type: 'flow', name: 'note_wait', item: approvalFlow('note_wait', 'crm_note', true), packageId: PKG, + }).catch((e: any) => e); + expect(err).toBeInstanceOf(Error); + // The door's existing authoring refusal: no new error code (S4 of the review of #38527 falls away). + expect(err).toMatchObject({ code: 'INVALID_METADATA', status: 422 }); + expect(refusalText(err)).toContain('approval-closed-state-gap'); + expect(refusalText(err)).toContain('Node hold (wait) of flow note_wait can pause the run between two approval steps of crm_note'); + expect((await flowRows('note_wait')).filter((r) => r.state === 'active')).toEqual([]); + }); + + it('lets an active flow save through that meets every condition', async () => { + await boot(); + expect((await protocol.saveMetaItem({ type: 'object', name: 'crm_note', item: closing, packageId: PKG })).success).toBe(true); + const out = await protocol.saveMetaItem({ type: 'flow', name: 'note_ok', item: approvalFlow('note_ok', 'crm_note', false), packageId: PKG }); + expect(out.success).toBe(true); + }); + + it('does not refuse a draft, and refuses its promotion', async () => { + await boot(); + expect((await protocol.saveMetaItem({ type: 'object', name: 'crm_note', item: closing, packageId: PKG })).success).toBe(true); + const saved = await protocol.saveMetaItem({ + type: 'flow', name: 'note_wait', item: approvalFlow('note_wait', 'crm_note', true), packageId: PKG, mode: 'draft', + }); + expect(saved.success).toBe(true); + const err = await protocol.publishMetaItem({ type: 'flow', name: 'note_wait', packageId: PKG }).catch((e: any) => e); + expect(err).toBeInstanceOf(Error); + expect(refusalText(err)).toContain('approval-closed-state-gap'); + expect((await flowRows('note_wait')).filter((r) => r.state === 'active')).toEqual([]); + }); + + it('refuses an object save that starts to close on the field of a live approval that pauses between two steps', async () => { + await boot(); + expect((await protocol.saveMetaItem({ type: 'object', name: 'crm_note', item: authored, packageId: PKG })).success).toBe(true); + expect((await protocol.saveMetaItem({ type: 'flow', name: 'note_wait', item: approvalFlow('note_wait', 'crm_note', true), packageId: PKG })).success).toBe(true); + const err = await protocol.saveMetaItem({ type: 'object', name: 'crm_note', item: closing, packageId: PKG }).catch((e: any) => e); + expect(err).toBeInstanceOf(Error); + expect(refusalText(err)).toContain('Node hold (wait) of flow note_wait can pause the run between two approval steps of crm_note'); + }); + + it('judges a package publish as it will be live: the closing object and the flow it repairs, in one batch', async () => { + await boot(); + expect((await protocol.saveMetaItem({ type: 'object', name: 'crm_note', item: authored, packageId: PKG })).success).toBe(true); + expect((await protocol.saveMetaItem({ type: 'flow', name: 'note_wait', item: approvalFlow('note_wait', 'crm_note', true), packageId: PKG })).success).toBe(true); + await protocol.saveMetaItem({ type: 'object', name: 'crm_note', item: closing, packageId: PKG, mode: 'draft' }); + await protocol.saveMetaItem({ type: 'flow', name: 'note_wait', item: approvalFlow('note_wait', 'crm_note', false), packageId: PKG, mode: 'draft' }); + const out = await protocol.publishPackageDrafts({ packageId: PKG }); + expect(out.failed ?? []).toEqual([]); + expect(out.success).toBe(true); + }); + + it('refuses a package publish whose object starts to close while the batch leaves the live flow pausing', async () => { + await boot(); + expect((await protocol.saveMetaItem({ type: 'object', name: 'crm_note', item: authored, packageId: PKG })).success).toBe(true); + expect((await protocol.saveMetaItem({ type: 'flow', name: 'note_wait', item: approvalFlow('note_wait', 'crm_note', true), packageId: PKG })).success).toBe(true); + await protocol.saveMetaItem({ type: 'object', name: 'crm_note', item: closing, packageId: PKG, mode: 'draft' }); + const out = await protocol.publishPackageDrafts({ packageId: PKG }); + expect(out.success).toBe(false); + expect(JSON.stringify(out.failed)).toContain('Node hold (wait) of flow note_wait can pause the run between two approval steps of crm_note'); + }); +}); diff --git a/packages/plugins/plugin-approvals/src/approval-closed-states-sentences.test.ts b/packages/plugins/plugin-approvals/src/approval-closed-states-sentences.test.ts new file mode 100644 index 00000000000..fc1ee43d092 --- /dev/null +++ b/packages/plugins/plugin-approvals/src/approval-closed-states-sentences.test.ts @@ -0,0 +1,48 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 D5] The author and the first request read the same sentence for a + * gap: the authoring rule's catalog (`@objectstack/lint`, + * `validate-approval-closed-states.user-text.ts`) holds a copy of this + * plugin's `approvalOpening*` sentences, and this test holds the two equal, + * kind by kind and locale by locale. + */ + +import { describe, expect, it } from 'vitest'; +import { APPROVAL_CLOSED_STATE_GAP, findingUserMessage } from '@objectstack/lint'; +import { approvalMessages } from './translations/messages.js'; + +/** Each gap kind the authoring rule reports, and the first request's message id for it. */ +const KIND_TO_ID = { + no_pending_option: 'approvalOpeningNoPendingOption', + closes_in_flight: 'approvalOpeningClosesInFlight', + state_machine_no_pending: 'approvalOpeningStateMachine', + readonly_when: 'approvalOpeningReadonlyWhen', + option_visible_when: 'approvalOpeningOptionVisibleWhen', + other_field: 'approvalOpeningOtherField', + no_field: 'approvalOpeningNoField', + pause_between_steps: 'approvalOpeningPause', + map_with_approval: 'approvalOpeningMapApproval', +} as const; + +/** The platform locale tag the rule's catalog uses, and the plugin's pack for it. */ +const LOCALES = { + en: 'en', 'zh-Hans': 'zh-CN', 'zh-Hant': 'zh-Hant', es: 'es-ES', ar: 'ar', fr: 'fr', + 'pt-BR': 'pt-BR', ru: 'ru', de: 'de', ja: 'ja-JP', ko: 'ko', +} as const; + +const HOLES = ['field', 'object', 'step', 'flow', 'value', 'rule', 'other', 'node', 'type']; + +describe('the authoring rule and the first request: one sentence per gap', () => { + for (const [tag, pack] of Object.entries(LOCALES)) { + it(`agrees in ${tag}`, () => { + for (const [kind, id] of Object.entries(KIND_TO_ID)) { + // Each hole rendered as its own spelling, so the two templates compare as written. + const params: Record = { kind }; + for (const h of HOLES) params[h] = `{{${h}}}`; + const authored = findingUserMessage({ rule: APPROVAL_CLOSED_STATE_GAP, userTextParams: params }, [tag]); + expect([kind, authored]).toEqual([kind, (approvalMessages[pack] as Record)[id]]); + } + }); + } +}); diff --git a/packages/plugins/plugin-approvals/src/approval-opening-check.ts b/packages/plugins/plugin-approvals/src/approval-opening-check.ts index 7bf8bd0ec74..d5f3d62e880 100644 --- a/packages/plugins/plugin-approvals/src/approval-opening-check.ts +++ b/packages/plugins/plugin-approvals/src/approval-opening-check.ts @@ -4,641 +4,25 @@ * [ADR-0162 D5, Execution item 7 "The check"] The check when an approval * opens, read off the approval's definition at its first request. * - * An approval is one passage of a record through its approval flow, taken as - * a whole: the flow its root run was started on, and every flow a `subflow` - * or a `map` in it names, to any depth. This module reads that whole once and - * answers three things: - * - * 1. **Whether the approval touches an object that declares `closedStates`**: - * a step of it can act on such an object. Only then is anything stamped or - * refused. - * 2. **The set of nodes that stand between two steps** ({@link OpeningJudgement.between}), - * which each request of the approval carries from its opening, so that the - * plugin can later place a stop or a pause against it (ADR-0162 item 8, - * design note 7210179412 question 3, T2). It is stamped for every approval - * that touches such an object, also one the conditions do not concern. - * 3. **What is missing**, for every step whose mirror field the object closes - * on at a status the mirror writes for a request that is not abandoned - * (`pending`, `returned`, `approved`, `rejected`): the five conditions of - * ADR-0162 D5 as revised on 2026-11-27, the approval's unread parts, and - * the host's `job` service. - * - * Between two steps means after a step is decided, whichever way, and before - * the next step opens; the next step can be the same step opened again (a - * `map` body or a `loop` body that holds one). The read is a reachability - * over one graph of the whole approval: every node of every flow, a `subflow` - * or a `map` joined to the body it calls, every region (`loop`, `parallel`, - * `try_catch`) joined to its container. It is context-insensitive and errs one - * way only: a node that could stand between two steps on some path counts as - * standing there. A stop wrongly read as "between" costs a resubmission; the - * other error would close a document on an unfinished approval (ADR-0162 D5). - * - * Pure over a {@link OpeningCheckSource}: the service hands it the readers it - * has (the engine's object registry, the automation engine's flow lookup and - * node descriptors, whether the host runs a `job` service), and the tests hand - * it fixtures. - */ - -import { FLOW_REGION_SLOTS_BY_TYPE } from '@objectstack/spec/automation'; - -/** The statuses the mirror writes for a request that is not abandoned. */ -const IN_APPROVAL_STATUSES = ['pending', 'returned', 'approved', 'rejected'] as const; -/** The statuses of a request whose option may carry no `visibleWhen` (D5 condition 3). */ -const REQUEST_STATUSES = ['pending', 'returned', 'approved', 'rejected', 'recalled'] as const; -/** The node types that have no executor and cannot pause (N43). */ -const STRUCTURAL_TYPES: ReadonlySet = new Set(['start', 'end']); -/** The type of an approval step. */ -const APPROVAL_TYPE = 'approval'; -/** The revise window of a returned request: not a pause between two steps (D5, ADR-0044). */ -const REVISE_WINDOW_TYPE = 'approval_revise'; -/** The two node types that call another flow; they are read by their bodies. */ -const CALL_TYPES: ReadonlySet = new Set(['subflow', 'map']); -/** How many flows one approval may name before it is read as not readable whole. */ -const MAX_FLOWS = 64; -/** How many region levels the read descends. */ -const MAX_REGION_DEPTH = 16; -/** How many `aliasOf` hops a node type's descriptor is followed. */ -const MAX_ALIAS_HOPS = 8; - -/** A flow body as the engine holds it: the parts this check reads. */ -export interface OpeningFlowBody { - nodes?: ReadonlyArray; - edges?: ReadonlyArray; -} -export interface OpeningFlowNode { - id: string; - type?: string; - label?: string; - config?: Record | null; -} -export interface OpeningFlowEdge { - source: string; - target: string; -} - -/** A flow the check read, by the key the engine files it under. */ -export interface OpeningFlow { - key: string; - body: OpeningFlowBody; -} - -/** The readers the check needs. Every one answers, never throws: the service wraps its reads. */ -export interface OpeningCheckSource { - /** The object definition registered under `name`, or `undefined`. */ - objectSchema(name: string): unknown; - /** The flow a `subflow` or a `map` of the flow filed under `callerKey` names as `name`; `null` when it cannot be read. */ - calleeFlow(name: string, callerKey: string): Promise; - /** - * The published descriptor of a node type: `undefined` where the type - * publishes none, `'unread'` where the engine cannot be asked. - */ - nodeDescriptor(type: string): { supportsPause?: unknown; aliasOf?: unknown } | undefined | 'unread'; - /** Whether the host runs the plugin's sweeps, the reconciler of ADR-0162 item 8 (a `job` service). */ - hostRunsReconciler: boolean; -} - -/** One thing that keeps the approval from opening. */ -export type OpeningGap = - | { kind: 'no_pending_option'; flow: string; step: string; object: string; field: string } - | { kind: 'closes_in_flight'; flow: string; step: string; object: string; field: string; value: string } - | { kind: 'state_machine_no_pending'; flow: string; step: string; object: string; field: string; value: string; rule: string } - | { kind: 'readonly_when'; flow: string; step: string; object: string; field: string } - | { kind: 'option_visible_when'; flow: string; step: string; object: string; field: string; value: string } - | { kind: 'other_field'; flow: string; step: string; object: string; field: string; other: string } - | { kind: 'no_field'; flow: string; step: string; object: string; field: string } - | { kind: 'pause_between_steps'; flow: string; node: string; type: string; object: string } - | { kind: 'map_with_approval'; flow: string; node: string; object: string } - | { kind: 'unreadable_flow'; flow: string } - | { kind: 'no_job_service'; object: string }; - -/** One node of the between-two-steps set: the flow it is in, by the key the engine files it under, and its id. */ -export interface BetweenNode { - flow: string; - node: string; -} - -/** What the check answers for an approval's first request. */ -export interface OpeningJudgement { - /** Whether a step of the approval can act on an object that declares `closedStates`. */ - touchesClosedStates: boolean; - /** The nodes that stand between two steps, sorted; stamped only where {@link touchesClosedStates}. */ - between: BetweenNode[]; - /** What keeps the approval from opening; empty when it opens. */ - gaps: OpeningGap[]; -} - -/** What the check is handed about the run that opens the request. */ -export interface OpeningCheckInput { - /** The flow the approval's root run was started on, read by the caller; `null` when it could not be read. */ - rootFlow: OpeningFlow | null; - /** The flow name of the root run, for a refusal that names an unread root flow. */ - rootFlowName: string; - /** The object of the root run's record; `null` for a root run that carries none (a batch). */ - rootObject: string | null; -} - -/** An object's declared closed values, field → values, or `undefined` when it declares none. */ -export function closedValuesOf(schema: unknown): ReadonlyMap> | undefined { - const declared = (schema as { closedStates?: unknown } | null | undefined)?.closedStates; - if (!declared || typeof declared !== 'object' || Array.isArray(declared)) return undefined; - const out = new Map>(); - for (const [field, values] of Object.entries(declared as Record)) { - if (!Array.isArray(values)) continue; - const set = new Set(values.filter((v): v is string => typeof v === 'string')); - if (set.size > 0) out.set(field, set); - } - return out.size > 0 ? out : undefined; -} - -/** A vertex of the approval's graph. A node is one vertex; a container or a call is two (its entry and its exit). */ -type Vertex = string; - -interface StepInfo { - flow: string; - node: OpeningFlowNode; - field: string | undefined; -} - -interface MapInfo { - flow: string; - node: OpeningFlowNode; - callee: string | null; - /** Whether the node shows that none of its items is a record (items written out, none of them one). */ - noRecordItems: boolean; -} - -/** - * Read the approval whole and judge it. Never throws: a part that cannot be - * read is a gap ({@link OpeningGap} `unreadable_flow`), and an approval with - * one cannot be judged, so it does not open. + * The judge itself lives in `@objectstack/metadata-core` + * (`approval-opening.ts`), because the authoring rule + * `validateApprovalClosedStates` (`@objectstack/lint`) asks the same + * conditions at every authoring door, and one copy of the judge is what keeps + * the two from disagreeing (maintainer ruling 7253749311 on #37766). The + * first request reads the engine asynchronously, so it calls + * {@link judgeApprovalOpening}; this module keeps the plugin's import path. */ -export async function judgeApprovalOpening(input: OpeningCheckInput, source: OpeningCheckSource): Promise { - const gaps: OpeningGap[] = []; - if (!input.rootFlow) { - return { touchesClosedStates: true, between: [], gaps: [{ kind: 'unreadable_flow', flow: input.rootFlowName }] }; - } - - // ── 1. Read every flow of the approval, to any depth ────────────────────── - const flows = new Map(); - /** For each flow: the flows it calls, by call node, with how the call hands objects down. */ - const calls = new Map>(); - const queue: OpeningFlow[] = [input.rootFlow]; - flows.set(input.rootFlow.key, input.rootFlow.body); - while (queue.length > 0) { - const { key, body } = queue.shift()!; - const out: Array<{ node: OpeningFlowNode; callee: string | null; kind: 'subflow' | 'map' }> = []; - for (const node of allNodes(body)) { - if (!node.type || !CALL_TYPES.has(node.type)) continue; - const name = typeof node.config?.flowName === 'string' ? node.config.flowName : ''; - if (!name) { - gaps.push({ kind: 'unreadable_flow', flow: `${key} › ${node.id}` }); - out.push({ node, callee: null, kind: node.type as 'subflow' | 'map' }); - continue; - } - const callee = await source.calleeFlow(name, key); - if (!callee) { - gaps.push({ kind: 'unreadable_flow', flow: name }); - out.push({ node, callee: null, kind: node.type as 'subflow' | 'map' }); - continue; - } - out.push({ node, callee: callee.key, kind: node.type as 'subflow' | 'map' }); - if (!flows.has(callee.key)) { - if (flows.size >= MAX_FLOWS) { - gaps.push({ kind: 'unreadable_flow', flow: name }); - continue; - } - flows.set(callee.key, callee.body); - queue.push(callee); - } - } - calls.set(key, out); - } - - // ── 2. The objects each flow's steps can act on ─────────────────────────── - // The root flow acts on the root run's record. A `subflow` body acts on its - // caller's record. A `map` body acts on an item where the item is a record, - // on the object the node names for its items (else its caller's), and on its - // caller's record where the item is not one; the check cannot read ahead - // whether an item is a record unless the items are written out in the node. - const objects = new Map>(); - for (const key of flows.keys()) objects.set(key, new Set()); - if (input.rootObject) objects.get(input.rootFlow.key)!.add(input.rootObject); - const maps: MapInfo[] = []; - for (const [key, list] of calls) { - for (const call of list) { - if (call.kind === 'map') maps.push({ flow: key, node: call.node, callee: call.callee, noRecordItems: itemsShowNoRecord(call.node) }); - } - } - for (let changed = true, rounds = 0; changed && rounds <= flows.size + 1; rounds++) { - changed = false; - for (const [key, list] of calls) { - const mine = objects.get(key)!; - for (const call of list) { - if (!call.callee) continue; - const theirs = objects.get(call.callee)!; - const before = theirs.size; - if (call.kind === 'subflow') { - for (const o of mine) theirs.add(o); - } else { - const items = mapItems(call.node); - const anyRecord = items === undefined || items.some(isRecordItem); - const anyOther = items === undefined || items.some((i) => !isRecordItem(i)); - if (anyOther) for (const o of mine) theirs.add(o); - if (anyRecord) { - const itemObject = typeof call.node.config?.itemObject === 'string' && call.node.config.itemObject - ? call.node.config.itemObject : undefined; - if (itemObject) theirs.add(itemObject); - else for (const o of mine) theirs.add(o); - } - } - if (theirs.size !== before) changed = true; - } - } - } - - // ── 3. The steps, and whether the approval touches a closing object ─────── - const steps: StepInfo[] = []; - for (const [key, body] of flows) { - for (const node of allNodes(body)) { - if (node.type !== APPROVAL_TYPE) continue; - const field = typeof node.config?.approvalStatusField === 'string' && node.config.approvalStatusField - ? node.config.approvalStatusField : undefined; - steps.push({ flow: key, node, field }); - } - } - const declaring = (object: string) => closedValuesOf(source.objectSchema(object)) !== undefined; - const touchesClosedStates = gaps.length > 0 - || steps.some((s) => [...objects.get(s.flow)!].some(declaring)); - if (!touchesClosedStates) return { touchesClosedStates: false, between: [], gaps: [] }; - - // ── 4. The nodes between two steps ──────────────────────────────────────── - const graph = buildGraph(flows, calls); - const stepVertices = steps.map((s) => vertexOf(s.flow, s.node.id)); - const after = reach(graph.succ, stepVertices); - const before = reach(graph.pred, stepVertices); - const betweenKeys = new Set(); - const pausing: Array<{ flow: string; node: OpeningFlowNode }> = []; - // A node other than a step is between two steps where a step can come - // before it and a step can follow it. A step is in the set where a step can - // follow it: a run that stops on a step decided with no later step logged - // (design note question 3, T2) stopped between two steps exactly then. - for (const [vertex, owner] of graph.owner) { - if (!before.has(vertex)) continue; - const isStep = owner.node.type === APPROVAL_TYPE; - if (!isStep && !after.has(vertex)) continue; - const k = `${owner.flow}\u0000${owner.node.id}`; - if (betweenKeys.has(k)) continue; - betweenKeys.add(k); - if (!isStep && canPause(owner.node, source)) pausing.push(owner); - } - // A `map` or a `loop` whose body holds a step stands between two steps - // where it is entered before a step and left after one: between one item's - // (one pass's) step and the next, the run is parked at the node or back on - // it. A `subflow` is not: its body runs once. - for (const { flow, node } of graph.owner.values()) { - if (node.type !== 'map' && node.type !== 'loop') continue; - if (before.has(vertexOf(flow, node.id, 'in')) && after.has(vertexOf(flow, node.id, 'out'))) { - betweenKeys.add(`${flow}\u0000${node.id}`); - } - } - const between = [...betweenKeys] - .map((k) => { const [flow, node] = k.split('\u0000'); return { flow, node }; }) - .sort((a, b) => (a.flow === b.flow ? cmp(a.node, b.node) : cmp(a.flow, b.flow))); - - // ── 5. The conditions, for every step they concern ──────────────────────── - const concernedObjects = new Set(); - for (const step of steps) { - for (const object of objects.get(step.flow)!) { - const schema = source.objectSchema(object); - const closed = closedValuesOf(schema); - if (!closed || !step.field) continue; - const values = closed.get(step.field); - if (!values || !IN_APPROVAL_STATUSES.some((s) => values.has(s))) continue; - concernedObjects.add(object); - judgeField(step, object, step.field, schema, values, gaps); - // Condition 4: every step that can act on a record of the object names that field. - for (const other of steps) { - if (other === step || !objects.get(other.flow)!.has(object)) continue; - if (other.field === step.field) continue; - if (other.field) gaps.push({ kind: 'other_field', flow: other.flow, step: other.node.id, object, field: step.field, other: other.field }); - else gaps.push({ kind: 'no_field', flow: other.flow, step: other.node.id, object, field: step.field }); - } - } - } - if (concernedObjects.size > 0) { - const object = [...concernedObjects].sort(cmp)[0]; - // Condition 5: no node that can pause the run of itself stands between two steps. - for (const p of pausing) { - gaps.push({ kind: 'pause_between_steps', flow: p.flow, node: p.node.id, type: String(p.node.type ?? ''), object }); - } - // Condition 5, its second half: no `map` with an approval step in its body, - // at any depth, where the parent's object is one the conditions concern, - // unless the node shows that none of its items is a record. - const holdsStep = flowsHoldingSteps(flows, calls, steps); - for (const m of maps) { - if (!m.callee || !holdsStep.has(m.callee) || m.noRecordItems) continue; - const parentObjects = [...objects.get(m.flow)!].filter((o) => concernedObjects.has(o)).sort(cmp); - if (parentObjects.length > 0) gaps.push({ kind: 'map_with_approval', flow: m.flow, node: m.node.id, object: parentObjects[0] }); - } - } - - // ── 6. The host ─────────────────────────────────────────────────────────── - if (!source.hostRunsReconciler) { - const object = steps.flatMap((s) => [...objects.get(s.flow)!]).filter(declaring).sort(cmp)[0]; - if (object) gaps.push({ kind: 'no_job_service', object }); - } - - return { touchesClosedStates, between, gaps: dedupe(gaps) }; -} - -/** D5 conditions 1 to 3, on the field `field` of `object`, for `step`. */ -function judgeField( - step: StepInfo, object: string, field: string, schema: unknown, - closed: ReadonlySet, gaps: OpeningGap[], -): void { - const flow = step.flow; - const stepId = step.node.id; - const def = (schema as { fields?: Record } | undefined)?.fields?.[field] as - { options?: unknown; readonlyWhen?: unknown } | undefined; - const options = Array.isArray(def?.options) ? def!.options as unknown[] : []; - const optionOf = (value: string): Record | undefined => { - for (const o of options) { - if (o && typeof o === 'object' && String((o as { value?: unknown }).value) === value) return o as Record; - } - return undefined; - }; - const declares = (value: string) => options.some((o) => (o && typeof o === 'object' ? String((o as { value?: unknown }).value) : String(o)) === value); - - // 1. The field declares `pending`, and the object closes on neither `pending` nor `returned`. - if (!declares('pending')) gaps.push({ kind: 'no_pending_option', flow, step: stepId, object, field }); - for (const value of ['pending', 'returned']) { - if (closed.has(value)) gaps.push({ kind: 'closes_in_flight', flow, step: stepId, object, field, value }); - } - - // 2. A `state_machine` rule on the field that declares the moves out of a - // closed `approved` or `rejected` has `pending` among them. - const rules = (schema as { validations?: unknown } | undefined)?.validations; - if (Array.isArray(rules)) { - for (const rule of rules) { - const r = rule as { type?: unknown; field?: unknown; active?: unknown; transitions?: unknown; name?: unknown } | null; - if (!r || r.type !== 'state_machine' || r.field !== field || r.active === false) continue; - const transitions = r.transitions && typeof r.transitions === 'object' ? r.transitions as Record : {}; - for (const value of ['approved', 'rejected']) { - if (!closed.has(value) || !Object.prototype.hasOwnProperty.call(transitions, value)) continue; - const moves = transitions[value]; - if (!Array.isArray(moves) || !moves.includes('pending')) { - gaps.push({ kind: 'state_machine_no_pending', flow, step: stepId, object, field, value, rule: String(r.name ?? '') }); - } - } - } - } - - // 3. The field carries no `readonlyWhen`, and none of its options for a request's status carries a `visibleWhen`. - if (def?.readonlyWhen != null) gaps.push({ kind: 'readonly_when', flow, step: stepId, object, field }); - for (const value of REQUEST_STATUSES) { - const option = optionOf(value); - if (option && option.visibleWhen != null) gaps.push({ kind: 'option_visible_when', flow, step: stepId, object, field, value }); - } -} - -/** Whether a node can pause the run of itself, by what its type declares (D5 condition 5, N43). */ -function canPause(node: OpeningFlowNode, source: OpeningCheckSource): boolean { - const type = node.type; - if (!type) return true; // a node it cannot place counts as one that can - if (STRUCTURAL_TYPES.has(type) || type === APPROVAL_TYPE || type === REVISE_WINDOW_TYPE || CALL_TYPES.has(type)) return false; - let descriptor = source.nodeDescriptor(type); - for (let hop = 0; descriptor && descriptor !== 'unread' && typeof descriptor.aliasOf === 'string' && hop < MAX_ALIAS_HOPS; hop++) { - const canonical = source.nodeDescriptor(descriptor.aliasOf as string); - if (!canonical || canonical === 'unread' || canonical === descriptor) break; - descriptor = canonical; - } - if (descriptor === 'unread' || descriptor === undefined) return true; - return descriptor.supportsPause === true; -} - -/** Every node of a body, its regions' nodes included, to {@link MAX_REGION_DEPTH}. */ -function allNodes(body: OpeningFlowBody): OpeningFlowNode[] { - const out: OpeningFlowNode[] = []; - const visit = (nodes: ReadonlyArray | undefined, depth: number) => { - for (const node of nodes ?? []) { - if (!node || typeof node !== 'object' || typeof node.id !== 'string') continue; - out.push(node); - if (depth >= MAX_REGION_DEPTH) continue; - for (const region of regionsOf(node)) visit(region.nodes, depth + 1); - } - }; - visit(body.nodes, 0); - return out; -} - -/** The regions a container node holds, in slot order. */ -function regionsOf(node: OpeningFlowNode): Array<{ slot: string; region: OpeningFlowBody } & OpeningFlowBody> { - const slots = node.type ? FLOW_REGION_SLOTS_BY_TYPE.get(node.type) : undefined; - if (!slots) return []; - const out: Array<{ slot: string; region: OpeningFlowBody } & OpeningFlowBody> = []; - for (const slot of slots) { - const value = node.config?.[slot.key]; - const list = slot.arity === 'many' ? (Array.isArray(value) ? value : []) : (value ? [value] : []); - list.forEach((raw, i) => { - // A `parallel` branch carries its region beside its name; read either shape. - const region = raw && typeof raw === 'object' && 'region' in (raw as object) - ? (raw as { region?: OpeningFlowBody }).region : raw as OpeningFlowBody; - if (region && typeof region === 'object') { - out.push({ slot: `${slot.key}[${i}]`, region, nodes: region.nodes, edges: region.edges }); - } - }); - } - return out; -} - -/** The items a `map` node writes out in itself, or `undefined` where they are read from an expression. */ -function mapItems(node: OpeningFlowNode): unknown[] | undefined { - const collection = node.config?.collection; - return Array.isArray(collection) ? collection : undefined; -} - -/** Whether an item is a record, read as the `map` node reads it (an object with a string `id`). */ -function isRecordItem(item: unknown): boolean { - return item != null && typeof item === 'object' && typeof (item as { id?: unknown }).id === 'string'; -} - -/** Whether a `map` node shows that none of its items is a record: its items are written out, and none is one. */ -function itemsShowNoRecord(node: OpeningFlowNode): boolean { - const items = mapItems(node); - return items !== undefined && !items.some(isRecordItem); -} - -/** The flows whose body holds an approval step at any depth, through the flows it calls. */ -function flowsHoldingSteps( - flows: Map, - calls: Map>, - steps: StepInfo[], -): Set { - const holds = new Set(steps.map((s) => s.flow)); - for (let changed = true, rounds = 0; changed && rounds <= flows.size + 1; rounds++) { - changed = false; - for (const [key, list] of calls) { - if (holds.has(key)) continue; - if (list.some((c) => c.callee && holds.has(c.callee))) { holds.add(key); changed = true; } - } - } - return holds; -} - -function vertexOf(flow: string, node: string, part = ''): Vertex { - return `${flow}\u0000${node}\u0000${part}`; -} - -interface Graph { - succ: Map>; - pred: Map>; - /** Each vertex that stands for a node, with the node and its flow. Synthetic vertices are absent. */ - owner: Map; -} - -/** - * One graph of the whole approval. A plain node is one vertex. A container - * (`loop`, `parallel`, `try_catch`) and a call (`subflow`, `map`) are two, its - * entry and its exit, joined through the regions or the body it runs: - * - a region or a called body is entered from the entry and left to the exit; - * - a `loop` body and a `map` body may run again (exit → entry) or not at all - * (entry → exit); - * - the branches of a `parallel` may interleave, so each branch's exit leads - * into every other branch; - * - every node of a `try` region may fail into its `catch` region and to the - * container's exit; - * - an edge of the flow, a `fault` edge included, leads from its source's exit - * to its target's entry. - * A step is one vertex: its decision leaves it. - */ -function buildGraph( - flows: Map, - calls: Map>, -): Graph { - const succ = new Map>(); - const pred = new Map>(); - const owner = new Map(); - const link = (a: Vertex, b: Vertex) => { - if (!succ.has(a)) succ.set(a, new Set()); - if (!pred.has(b)) pred.set(b, new Set()); - succ.get(a)!.add(b); - pred.get(b)!.add(a); - }; - const entryOfFlow = (key: string) => vertexOf(key, '', 'flow-entry'); - const exitOfFlow = (key: string) => vertexOf(key, '', 'flow-exit'); - const calleeOf = new Map(); - for (const [key, list] of calls) for (const c of list) calleeOf.set(`${key}\u0000${c.node.id}`, c); - - const isCompound = (node: OpeningFlowNode) => !!node.type && (CALL_TYPES.has(node.type) || FLOW_REGION_SLOTS_BY_TYPE.has(node.type)); - const inOf = (flow: string, node: OpeningFlowNode) => vertexOf(flow, node.id, isCompound(node) ? 'in' : ''); - const outOf = (flow: string, node: OpeningFlowNode) => vertexOf(flow, node.id, isCompound(node) ? 'out' : ''); - - /** Wire one graph (a flow's top level or a region); answers its entry and exit vertices. */ - const wire = (flow: string, nodes: ReadonlyArray | undefined, edges: ReadonlyArray | undefined, depth: number): - { entries: Vertex[]; exits: Vertex[]; inner: Vertex[] } => { - const list = (nodes ?? []).filter((n) => n && typeof n === 'object' && typeof n.id === 'string'); - const byId = new Map(list.map((n) => [n.id, n])); - const inner: Vertex[] = []; - const hasIn = new Set(); - const hasOut = new Set(); - for (const e of edges ?? []) { - const a = byId.get(e?.source); - const b = byId.get(e?.target); - if (!a || !b) continue; - link(outOf(flow, a), inOf(flow, b)); - hasOut.add(a.id); - hasIn.add(b.id); - } - for (const node of list) { - const vin = inOf(flow, node); - const vout = outOf(flow, node); - owner.set(vin, { flow, node }); - owner.set(vout, { flow, node }); - inner.push(vin); - if (vout !== vin) inner.push(vout); - const call = calleeOf.get(`${flow}\u0000${node.id}`); - if (call) { - if (call.callee) { - link(vin, entryOfFlow(call.callee)); - link(exitOfFlow(call.callee), vout); - if (call.kind === 'map') link(exitOfFlow(call.callee), entryOfFlow(call.callee)); - } else { - link(vin, vout); - } - if (call.kind === 'map') link(vin, vout); - continue; - } - const regions = depth < MAX_REGION_DEPTH ? regionsOf(node) : []; - if (node.type && FLOW_REGION_SLOTS_BY_TYPE.has(node.type)) { - const wired = regions.map((r) => ({ slot: r.slot, ...wire(flow, r.nodes, r.edges, depth + 1) })); - if (wired.length === 0) link(vin, vout); - if (node.type === 'try_catch') { - const tryR = wired.filter((w) => w.slot.startsWith('try')); - const catchR = wired.filter((w) => w.slot.startsWith('catch')); - for (const t of tryR) { - for (const e of t.entries) link(vin, e); - for (const x of t.exits) link(x, vout); - for (const v of t.inner) { - link(v, vout); - for (const c of catchR) for (const e of c.entries) link(v, e); - } - } - for (const c of catchR) for (const x of c.exits) link(x, vout); - } else { - for (const w of wired) { - for (const e of w.entries) link(vin, e); - for (const x of w.exits) link(x, vout); - } - if (node.type === 'loop') { - link(vin, vout); - for (const w of wired) for (const x of w.exits) for (const e of w.entries) link(x, e); - } - if (node.type === 'parallel') { - for (const a of wired) for (const b of wired) { - if (a === b) continue; - for (const x of a.exits) for (const e of b.entries) link(x, e); - } - } - } - } - } - const entries = list.filter((n) => (depth === 0 ? n.type === 'start' || !hasIn.has(n.id) : !hasIn.has(n.id))).map((n) => inOf(flow, n)); - const exits = list.filter((n) => !hasOut.has(n.id)).map((n) => outOf(flow, n)); - return { entries, exits, inner }; - }; - - for (const [key, body] of flows) { - const { entries, exits } = wire(key, body.nodes, body.edges, 0); - for (const e of entries) link(entryOfFlow(key), e); - for (const x of exits) link(x, exitOfFlow(key)); - } - return { succ, pred, owner }; -} - -/** The vertices reachable from `starts` by one edge or more. */ -function reach(edges: Map>, starts: Vertex[]): Set { - const seen = new Set(); - const stack: Vertex[] = []; - for (const s of starts) for (const n of edges.get(s) ?? []) stack.push(n); - while (stack.length > 0) { - const v = stack.pop()!; - if (seen.has(v)) continue; - seen.add(v); - for (const n of edges.get(v) ?? []) if (!seen.has(n)) stack.push(n); - } - return seen; -} - -function cmp(a: string, b: string): number { - return a < b ? -1 : a > b ? 1 : 0; -} -function dedupe(gaps: OpeningGap[]): OpeningGap[] { - const seen = new Set(); - return gaps.filter((g) => { - const k = JSON.stringify(g); - if (seen.has(k)) return false; - seen.add(k); - return true; - }); -} +export { + closedValuesOf, + judgeApprovalOpening, + type BetweenNode, + type OpeningCheckInput, + type OpeningCheckSource, + type OpeningFlow, + type OpeningFlowBody, + type OpeningFlowEdge, + type OpeningFlowNode, + type OpeningGap, + type OpeningJudgement, +} from '@objectstack/metadata-core'; From 37e97a83661e1df9b4ad870b311167db32ceb648 Mon Sep 17 00:00:00 2001 From: "objectstack-fleet[bot]" <332303061+objectstack-fleet[bot]@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:54:22 +0800 Subject: [PATCH 32/32] feat(spec,objectql): the closed-state refusal's own sentences, in every locale (closedStates slice C, ADR-0162 D8) (#38516) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit _Requested by **Leehom** · [project thread](https://claude.ai/code/project/chan_01TenzsRopZj4jMbvjX8uz1X?thread=cmsg_01TenzsRopZj4jMbvjX8uz1XM4tETbvX1rGDEEdPX6wiRw)_ Part of #37768 Clause-②: yes (widening: new keys in the published Operation Message Catalog and the upload-link copy; contract-review-tier review owed) Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:业务用户改动、删除一张已关闭(已结清、已完成)的单据或它的明细时,看到的是用自己语言写的一句话,说清是哪张单据、为什么改不了。 - 为什么做:这是「单据关闭后锁定」这项能力的第三部分,补上用户看到的提示文字;前两部分(锁本身、审批状态写回)已在同一主干上。 - 出错会怎样:最坏是提示句措辞不准或落成笼统说法,锁本身照常拦截、数据不受影响;本改动只换文字,可整体撤回。 - 要你做什么:无(合同层评审由席位按档安排)。 ## What changes This slice gives the closed-state refusal (`409 RECORD_LOCKED`, ADR-0162) the person-facing sentence D8 rules, in every locale each surface carries. Lands on the trunk `claude/o5-data-approvals-trunk` (978bb2b1d7: bfe2df88b plus #37766 slices C and B, the opening-refusal lead #38546 and #37767 piece 3 #38540, merged into this branch with `--no-ff` at 26b9eec2b7, 470235dada, 63d1e62ea6 and 8b1644b9ba); the trunk's own PR carries the card. **New catalog keys** (`packages/spec/src/system/operation-message.ts`, `BUILTIN_OPERATION_MESSAGES`), in en, zh-CN, ja-JP and es-ES. The en sentences, for review: | key | en | |---|---| | `record_closed` | `{{object}} '{{title}}' is closed, so it and its lines can no longer be changed or deleted` | | `record_closed_unlabeled` | `'{{title}}' is closed, so it and its lines can no longer be changed or deleted` | | `record_closed_untitled` | `This {{object}} is closed, so it and its lines can no longer be changed or deleted` | | `record_closed_opaque` | `This record is closed, so it and its lines can no longer be changed or deleted` | | `record_closed_delete_blocked` | `{{object}} '{{title}}' cannot be deleted: deleting it would also remove a closed {{blockingObject}} or one of its lines` | | `record_closed_delete_blocked_untitled` | `This {{object}} cannot be deleted: deleting it would also remove a closed {{blockingObject}} or one of its lines` | | `record_closed_delete_blocked_opaque` | `This record cannot be deleted: deleting it would also remove a closed record or one of its lines` | Upload-link page: a closed-state refusal reaches the page with the engine's declared catalog sentence as its `userMessage`, and the page shows that sentence (`storage-routes.ts` `relayUploadLinkRefusal`). The page's `recordLocked` answers only a `RECORD_LOCKED` with no declared sentence. `upload-link-copy.ts` also gains `recordClosed` in all 11 languages, en: `Nothing was attached: the record is closed, so no file can be added to it.`; choosing it by the lock read's reason stays with item 2. **The engine words the refusal** (`packages/objectql/src/closed-state-lock.ts`): - The refusal names a title only from a field that holds display text and that the writer's generic read returns: the display field gives no title when it is a field the generic read withholds (`internal`, or a credential type: `collectInternalReadFields`, `collectCredentialFields`), a reference field (`REFERENCE_VALUE_TYPES`), or a field the object's `closedStates` names. - The title is also one the writer is served: the security service's `getReadableFields` and `getQueryableFields` for the writer both hold the field. The service comes from the engine's existing security-service slot (the one `ObjectQLPlugin` fills). An empty slot, or a source that answers `null` or nothing, is no field-level security, so the title is served. So it is when the source throws and no `security` service is registered at all: `ObjectQLPlugin` fills a second slot beside the source (`SECURITY_SERVICE_REGISTERED_SLOT`, not public surface) with a probe that answers whether one is registered, read without building one, and only this title rule reads it. A source that throws for a service that is registered (a factory that throws, or one the sync accessor does not build), a service that cannot say, or a field the writer is not served or is served masked, gives the label form. The rules on which field a title is read from apply first, on every kernel. - A record's own write (by id): titled, or the label form. A predicate write: the label form. - A line's write, a new line, a line moved, a line restored: the master's label alone (`record_closed_untitled` of the master). - A delete refused for what it would also remove: the record asked to be deleted, plus the label of the object in the way. The root's title is used only when the delete names exactly one record by id and its title is served; a delete that names its rows by a predicate, one row matched or many, takes the untitled form. - An object with no label: the `_unlabeled` / `_opaque` forms. Never the API name. - On the error: `userMessage` = the sentence; `message` = `RECORD_LOCKED: ` followed by the sentence (the pending lock's shape); `developerMessage` = the developer sentence (API names), which the REST layer does not relay. No new member on the published error body; `ClosedStateRefusalWording` is module-internal (not exported from the package index). - `packages/objectql/src/plugin.ts` sets the registration probe beside the security source. The probe answers `false` only on the kernel's branded "never registered" rejection (`isServiceNotRegisteredError`); a factory-registered service the sync accessor refuses ("is async") counts as registered and is not built. Every other reader of the source slot (the `ReadableIds` resolution, the search's queryable-field read) reads only the source and answers as before. - Plumbing only: `engine-cascade-planning.ts`, `engine-delete-and-aggregate.ts` and `engine.ts` pass `facade`, `validationMessageContext` and `logger` into the hosts that judge the cascade and the delete, and the by-id delete passes the id it names to the cascade. `engine.ts` keeps its line count (the facade ceiling). ### Measured answers to the four mechanism assumptions 1. **Held.** At the trunk tip (bfe2df88b9) the refusal carried only the developer `message`, with no `userMessage`. REST `mapDataError` writes the `message` (without its `CODE: ` head) to the body's `error`, which the Console toast shows. Pinned on the wire now (`closed-state-refusal-wire.dogfood.test.ts`): `error` and `userMessage` both carry the catalog sentence; `developerMessage`, `reason`, `lockReason` and `blockingObject` are not in the body. 2. **Held in part; no new seam needed.** The pending lock (plugin-approvals `lifecycle-hooks.ts`, `lockedError` + `recordTitleOf`) carries its sentence as `userMessage` and `RECORD_LOCKED: sentence` as `message`, and REST relays a declared `userMessage` (`withDeclaredUserMessage`). The engine reaches the same field-permission reading through the security-service slot objectql already owns (`SECURITY_SERVICE_SOURCE_SLOT`), with a registration probe beside it in a second internal slot (`SECURITY_SERVICE_REGISTERED_SLOT`, not public surface). No dependency on plugin-approvals, no new service, no new published type or error member. So no `needs_decision`. 3. **Counted from the tree.** The catalog carries 4 locales (en, zh-CN, ja-JP, es-ES), and each new key is in all 4. The upload-link copy carries 11 (one per platform locale tag, as its test pins), and `recordClosed` is in all 11. 4. **Approval mirror held; assignment rules: there is no write to exempt.** The approval status mirror's `pending` (on opening) and `approved` (on decision) both land on a record closed by another field. They are system writes, and the caller's own write is refused 409 between and after (`closed-state-system-writes.test.ts`). The assignment rules write no stored record: the engine evaluates them only on a row it is inserting, before the write, and an update never evaluates a rule (`assignment-rules.ts` docblock, "An update never evaluates a rule"). A caller inserting a row already in its closed state has it routed, and the insert lands (an insert of the record itself is not judged). The caller's later write is refused, and the refused update ran no rule. ## Tests - `packages/spec/src/system/operation-message.test.ts`, new describe for the D8 keys. Checks: each key in every locale with placeholder parity; translations differ from en; each form differs from its pending twin and carries no approval word; no `RECORD_LOCKED`, `closedStates`, `master_detail`, `_id` or cascade wording; distinct from every other key; zh and ja render, de falls back to en; a deployment override wins. - `packages/services/service-storage/src/upload-link-copy.test.ts`: `recordClosed` exists in every platform locale and differs from `recordLocked`; a `RECORD_LOCKED` with no declared sentence reads `recordLocked`; the table's locales equal the platform's. - `packages/qa/dogfood/test/closed-state-refusal-sentence.test.ts`, engine over SQLite with a field-security stand-in in the engine slot. Covers: - titled, unread-field and masked-field forms, and no service at all; - a security-service source that throws gives the label form, and one that answers `null` gives the title; - a title field the generic read withholds (`internal`, credential), a reference title field, and a title field `closedStates` names: the label form on the record's update, its delete, and a cascade-delete root, with a display-text control; - a delete that names its rows by a predicate takes the cascade's label form, one row matched or many; - a service lacking `getQueryableFields` falls to the label form; - predicate writes; - line update, delete, create and move, all with the master label; - cascade titled and untitled, and a cascade through a lookup reaching a closed invoice's line; - many-root delete; - unlabeled and opaque forms; - zh-CN and es-ES; - restore; - `developerMessage` keeps the API name; - could-not-judge carries no `userMessage`; - a title read that fails on the refusal path is reported at `warn` and the refusal stands in the label form (ablation: with the report removed from the rebuilt dist, this case goes red with `expected [] to have a length of 1`); - ablation for the title-field, source and named-ids rules: with the three rules reverted in a rebuilt dist, the 6 cases above go red, and they are green with the rules restored. - Every case asserts `code` + `status`, and every person-facing string is checked for the absence of every API name, record id and state value. - `packages/qa/dogfood/test/closed-state-refusal-wire.dogfood.test.ts`, `bootStack` with the real `SecurityPlugin`. Covers: - titled update; - the field-withheld writer gets the label form (control: its read carries no title field); - closed delete; - line update and create; - cascade delete, titled; - zh-CN; - what the wire does not relay; - D10 at the security layer: object permission refuses, so the closed and open records give the same status and body (403 `PERMISSION_DENIED`); row access refuses, so the same body with the ids normalized (control: the owner gets 409). - `packages/qa/dogfood/test/closed-state-system-writes.test.ts`: the approval mirror and assignment-rule results above. The host runs the approvals sweeps (`noteSweepClockScheduled`), as #37766 slice B's opening check requires. It registers no `security` service, so the caller's refusal there names the record's title. - `packages/qa/dogfood/test/closed-state-refusal-security-source.test.ts`, real `ObjectKernel` with `ObjectQLPlugin`, by what the kernel registers under `security`. Covers: - no `security` service registered: the title on update, delete and a cascade-delete root; - on that kernel, a title field the generic read withholds (`internal`, credential), a reference title field and a title field `closedStates` names: the label form, on update, delete and a cascade-delete root; - a `security` service registered as a factory that throws: the label form; - a `security` service registered as a factory the sync accessor does not build: the label form, and the refusal builds nothing (the factory's call count and the other readers' answers are the same before and after); - the other readers of the source (`resolveReadableIdsSecurity`, `resolveSearchQueryableFields`) give the same answer before and after a refusal, with no service registered and with a factory that throws; - a source that throws with no probe beside it: the label form. - Ablation: with the probe read removed from the rebuilt dist, the no-security title case here and both system-writes cases go red (3 failed, 8 passed). With the "is async" line removed from the probe, the builds-nothing case goes red. All are green with the source restored.
Suite readings (head 8b1644b9ba, the merge of trunk 978bb2b1d7; the slice's 14 paths are byte-identical to 37e4afad98) - On the merged tree 8b1644b9ba, closure rebuilt first: plugin-approvals full suite (138 files / 2142 passed) and `typecheck`; the slice's dogfood files with `closed-state-lock.test.ts` (5 files / 108 passed, `closed-state-system-writes` 2/2) and dogfood `typecheck`; objectql `registry-closed-state-fold.test.ts` and `federated-injected-column-readers.test.ts` (2 files / 18 passed) and `typecheck`; spec `operation-message.test.ts` (112 passed) and `typecheck`; service-storage `upload-link-copy.test.ts` (7 passed). Every run VERDICT command-exit 0. - On the earlier merged tree 63d1e62ea6 (trunk d31309867d), closure rebuilt first: plugin-approvals `approval-opening-refusal.test.ts` and `approval-opening-check-37766.integration.test.ts` (2 files / 15 passed) and `typecheck`; objectql `registry-closed-state-fold.test.ts` and `federated-injected-column-readers.test.ts` (2 files / 18 passed) and `typecheck`; spec `operation-message.test.ts` (112 passed) and `typecheck`; service-storage `upload-link-copy.test.ts` (7 passed); the slice's dogfood files with `closed-state-lock.test.ts` (5 files / 108 passed). Every run VERDICT command-exit 0. - The readings below were taken at 37e4afad98 (the 7f9538fc02 tree plus the changeset), before the merge. - `pnpm --filter @objectstack/objectql typecheck` then the full objectql vitest run: Test Files 644 passed (644) · Tests 14559 passed. VERDICT command-exit 0, at 7f9538fc02's tree. - Dogfood: `closed-state-refusal-security-source` (9), `closed-state-refusal-sentence` (19), `closed-state-refusal-wire.dogfood` (9), `closed-state-system-writes` (2) and the trunk's `closed-state-lock.test.ts`: 5 files / 108 tests passed, then dogfood `typecheck`. VERDICT command-exit 0. The closure (`@objectstack/dogfood^...`) was rebuilt from this tree first. - service-storage `upload-link-copy.test.ts` (7 passed) and `typecheck`; spec `operation-message.test.ts` (112 passed) and `typecheck`. VERDICT command-exit 0. This round changed only docblocks in those two packages. - Earlier rounds, sources unchanged since: service-storage full test (88 files, 1745 passed, 1 skipped); spec full test (915 files, 28942 passed, 1 todo, at 67dd8de483); plugin-approvals opening-check and status-mirror integration files (4 files / 112 tests).
## Acceptance notes - **Could-not-judge keeps the developer sentence.** A refusal the lock gives because it could not judge the write (an unsupported predicate shape, for example) sets no `userMessage`; its `message` is the developer sentence. This follows the pending lock's bound refusal. D8's family has no form for it; see the report's open question. Carrier for a sentence form of its own: #38518. - **No `security` service registered names the title; a registered one that cannot be resolved does not.** On a kernel with `ObjectQLPlugin` and no `security` service, the source throws and the registration probe answers that nothing is registered, so the refusal names the title D8 gives (after the title-field rules). A service registered as a factory, one that throws or one the sync accessor does not build, takes the label form, as does an engine whose source throws with no probe beside it. An engine whose slot is empty, or whose source answers `null`, names the title. - **The probe reads one message.** To avoid building a factory-registered service, the probe treats the sync accessor's "is async" refusal (the message the kernel keeps verbatim for callers that match on it) as registered. That read can only make the answer "registered", which names no title. If the message ever changed, the probe would fall through to the async accessor, which builds the factory; the builds-nothing test pins that it does not. Carrier for a public, non-building registration read in core that would remove this message read: #38559. - **The untitled cascade form is pinned at the engine, not on the wire.** On the booted stack, a writer whose permission set has the customer's title field `readable: false` is refused the delete of its own customer, in its own organization, with 403 `PERMISSION_DENIED` (`record_access_denied`). The security layer refuses before the engine is reached, while the same writer's GET of that row answers 200. Reported out of scope (plugin-security lease), not worked around. Carrier: #38517. - The PR base is the trunk; `dispatch-gates.mjs` was given this slice's 14 paths explicitly, because its default change set is measured against `origin/main` and would include slices A and B. - A title read that fails on the refusal path is reported at `warn` through the engine's logger (threaded to the cascade judge's host), and the refusal stays whole in the label form (`check:durability-log-level`). - `overlap-check` (base `origin/claude/o5-data-approvals-trunk`): VERDICT overlap exit 1, for the one known #38268 conflict in `engine-delete-and-aggregate.ts` and `engine-update.ts`, which exists between the trunk tip and #38268 already (measured with `git merge-tree`). This slice adds no new conflicted file. ## Verification Read first, by risk: 1. `packages/objectql/src/closed-state-lock.ts`, `titleFieldOf`, `titleFieldIsServed` and `servedTitleOf`, with `packages/objectql/src/plugin.ts` `securityServiceRegistered`: the rules that decide whether a title appears. 2. `closed-state-lock.ts`, `judgeClosedStateCascadeSet`, and `engine-cascade-planning.ts` `cascadeDeleteRelations`: the `named` ids decide titled versus untitled for a cascade. 3. `packages/spec/src/system/operation-message.ts`: the seven new keys in four locales. Two-minute check: `pnpm --filter @objectstack/dogfood exec vitest run --maxWorkers=2 test/closed-state-refusal-wire.dogfood.test.ts`. Expect 9 passed, including "a writer whose field permissions withhold the title field is told the label form, never the stored title".
Gates (run at 37e4afad98; reconciled at 8b1644b9ba) - `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` was given this slice's 14 paths (the diff against the trunk, then 4cc09b16f4; the same 14 paths against 978bb2b1d7) and derived 101 commands (the 98 of last round plus `check:init-service-contract`, `check:startup-registry-verdict` and `check:wildcard-fallthrough`, from `plugin.ts`). All 101 ran unlocked at 7f9538fc02, one after another, each exit code captured before any pipe: 100 exited 0, and `check:dual-build-cjs-loads` answered `PREREQUISITE NOT MET` (exit 3, three packages had no dist in this worktree). After building those three it exited 0. The 21 families the changeset path derives were re-run at 37e4afad98, the changeset's own commit, and all 21 exited 0. - `--ran` reconciliation, derived at 8b1644b9ba against 978bb2b1d7: `✓ dispatch-gates --ran: 101 derived famil(ies) accounted for — 101 run, 0 NOT-MEASURED (a DERIVED zero — all 101 recorded an exit code and none of them is 3).` - The derivation warns that this tree is behind `origin/main` (by order, the trunk is not merged with main). Families CI runs on the PR are read from the PR's check-runs, not re-run here.
🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01FEkQ5nGQtUA88SthJbYyRw --------- Co-authored-by: Claude --- .../37768-closed-state-refusal-sentences.md | 17 + packages/objectql/src/closed-state-lock.ts | 365 ++++++++++++++- .../objectql/src/engine-cascade-planning.ts | 10 +- .../src/engine-delete-and-aggregate.ts | 6 +- packages/objectql/src/engine.ts | 8 +- packages/objectql/src/plugin.ts | 43 +- ...osed-state-refusal-security-source.test.ts | 223 ++++++++++ .../closed-state-refusal-sentence.test.ts | 418 ++++++++++++++++++ .../closed-state-refusal-wire.dogfood.test.ts | 330 ++++++++++++++ .../test/closed-state-system-writes.test.ts | 195 ++++++++ .../src/upload-link-copy.test.ts | 20 + .../service-storage/src/upload-link-copy.ts | 26 +- .../spec/src/system/operation-message.test.ts | 95 ++++ packages/spec/src/system/operation-message.ts | 91 +++- 14 files changed, 1815 insertions(+), 32 deletions(-) create mode 100644 .changeset/37768-closed-state-refusal-sentences.md create mode 100644 packages/qa/dogfood/test/closed-state-refusal-security-source.test.ts create mode 100644 packages/qa/dogfood/test/closed-state-refusal-sentence.test.ts create mode 100644 packages/qa/dogfood/test/closed-state-refusal-wire.dogfood.test.ts create mode 100644 packages/qa/dogfood/test/closed-state-system-writes.test.ts diff --git a/.changeset/37768-closed-state-refusal-sentences.md b/.changeset/37768-closed-state-refusal-sentences.md new file mode 100644 index 00000000000..7cd9079c9bb --- /dev/null +++ b/.changeset/37768-closed-state-refusal-sentences.md @@ -0,0 +1,17 @@ +--- +'@objectstack/spec': patch +'@objectstack/objectql': patch +'@objectstack/service-storage': patch +--- + +feat(spec,objectql): the closed-state refusal's own sentences, in every locale (ADR-0162 D8) + +Clause-②: yes (widening: new keys in the published Operation Message Catalog and the upload-link copy; contract-review-tier review owed) +Metadata-protocol: none + +A write refused because a record is in a closed state (`409 RECORD_LOCKED`, ADR-0162) tells the person what happened, in their own language, with a sentence from the Operation Message Catalog. + +- **New catalog keys** in `BUILTIN_OPERATION_MESSAGES`, in every locale the catalog carries (en, zh-CN, ja-JP, es-ES), overridable per deployment under `errors.` like every other key: `record_closed` with its `_unlabeled`, `_untitled` and `_opaque` forms, and `record_closed_delete_blocked` with its `_untitled` and `_opaque` forms. English, for example: "Invoice 'Northwind March' is closed, so it and its lines can no longer be changed or deleted", and "Customer 'Contoso Holdings' cannot be deleted: deleting it would also remove a closed Invoice or one of its lines". +- **The engine words the refusal from them.** The refusal names a title only from a field that holds display text and that the writer's generic read returns, and that the writer is served under its own field permissions (readable and queryable): not a field the generic read withholds (`internal`, or a credential type), not a reference field, not a field the object's `closedStates` names. Otherwise the sentence names the object's label only, and so it does when a registered security service cannot be resolved. With no security service registered there is no field-level security, and the title is named. A line's write names its master by label alone. A delete refused for what it would also remove names the record asked to be deleted and the label of the object in the way, with the title only when the delete names exactly one record by id. No sentence carries a record id, an API name or a state value. +- **On the error**: `userMessage` and the wire's `error` carry the sentence; `message` reads `RECORD_LOCKED: ` followed by the sentence, as the approval lock's refusal does; the developer sentence moves to `developerMessage`, which the REST layer does not relay. A refusal that could not judge the write keeps the developer sentence and sets no `userMessage`. +- **Upload-link page**: a closed-state refusal reaches the page with the engine's declared catalog sentence, which the page shows. The page's own `recordLocked` answers only a `RECORD_LOCKED` with no declared sentence. The page also carries a closed-state sentence (`recordClosed`) in each of its 11 languages; choosing it by the lock's reason comes with a later change. diff --git a/packages/objectql/src/closed-state-lock.ts b/packages/objectql/src/closed-state-lock.ts index 79422ac9956..ce3bf64287d 100644 --- a/packages/objectql/src/closed-state-lock.ts +++ b/packages/objectql/src/closed-state-lock.ts @@ -55,21 +55,54 @@ * hangs under is judged on its stored state, whoever the writer is: that read * is the engine's, above the writer's grants and inside its organization scope. * - * ## The refusal + * ## The refusal (D8) * * `409 RECORD_LOCKED`, the code the pending-approval lock already answers - * with. The sentence family a person reads (ADR-0162 D8) is the message - * catalog's; the `message` here is the developer's and carries no record id - * and no state value. + * with. What a person reads is the Operation Message Catalog's sentence + * (`@objectstack/spec/system`), in the caller's language, carried as the + * error's `userMessage` and as its `message` behind the code, the shape the + * pending lock's refusal has, so the wire's `error` reads the same sentence + * ({@link closedStateRefusalSentence}): + * + * - a record's own write: `record_closed*`, naming the record by its + * object's label and the title the WRITER would be served under its own + * field permissions ({@link servedTitleOf}); ⛔ never the title as stored; + * - a write that matched rows by a predicate: the label form, no title; + * - a line write, a line's restore: the label form, naming the MASTER (the + * engine reads the master's state to judge, and reads nothing of it to word + * the refusal); + * - a delete refused for what it would also remove: + * `record_closed_delete_blocked*`, naming the record asked to be deleted + * and the label of the object in the way, the title only where the caller + * is served one and the delete names exactly one record by id. + * + * The title is named only from a field that holds display text and that the + * writer's generic read returns: never a field the generic read withholds + * (`internal`, or a credential type: `secret-fields.ts`), a reference field, + * or a field the object's `closedStates` names ({@link titleFieldOf}). + * + * No form carries a record id, an API name or the state's value. The + * developer's sentence, which names objects by their API names, is carried on + * `developerMessage`, which no person-facing surface reads and the data door + * does not relay. A refusal that could not judge the write (D4's three cases) + * keeps the developer's sentence as its `message` and marks no `userMessage`: + * it is addressed to whoever scoped the write, as the pending lock's + * unanswerable-bound refusal is. */ -import { MAX_BULK_PER_ROW_HOOK_ROWS, ReadableIds, type FilterCondition } from '@objectstack/spec/data'; +import { MAX_BULK_PER_ROW_HOOK_ROWS, REFERENCE_VALUE_TYPES, ReadableIds, resolveDisplayField, type FilterCondition } from '@objectstack/spec/data'; import { postureEnforcesWall, type TenancyPosture } from '@objectstack/spec/security'; import type { ExecutionContext } from '@objectstack/spec/kernel'; +import type { ISecurityService } from '@objectstack/spec/contracts'; +import { renderOperationMessage } from '@objectstack/spec/system'; +import { objectDisplayLabel } from './engine-validation-messages.js'; +import { SECURITY_SERVICE_SOURCE_SLOT } from './engine-top-level.js'; +import type { ValidationMessageContext } from './validation/record-validator.js'; import { isDriverTenantScopedSchema } from './engine-driver-options.js'; import { isFederatedObject } from './federated-object.js'; import { driverCompilesReadableIdsLeaf } from './relation-semi-join.js'; import { closedValuesOf, type ClosedValues } from './closed-state-values.js'; +import { collectCredentialFields, collectInternalReadFields } from './secret-fields.js'; export { closedValuesOf, type ClosedValues }; @@ -102,6 +135,19 @@ export interface ClosedStateLockHost { buildDriverOptions(object: string, context: ExecutionContext | undefined, base?: any, extra?: any): any; masterDetailHeadersCallerReads(master: string, ids: ReadonlyArray, context: ExecutionContext | undefined): Promise>; resolveEnginePosture(): TenancyPosture; + /** + * [D8] The caller's locale and translator, which the refusal's sentence and + * the labels it names are worded in (`engine-validation-messages.ts`). + * Absent: English and the declared labels. + */ + validationMessageContext?(object: string, context?: { locale?: string }): ValidationMessageContext; + /** + * [D8] The engine, whose security-service source slot answers which fields + * the writer is served ({@link servedTitleOf}). Absent: no title is named. + */ + readonly facade?: object; + /** [D8] Where a title read that failed on the refusal path is reported. */ + readonly logger?: { warn(message: string, meta?: Record): void }; } /** The verbs a refusal names. */ @@ -130,6 +176,10 @@ export interface ClosedStateLockError extends Error { readonly blockingObject?: string; /** What the lock read: `closed_state`, the one lock read's reason (ADR-0162 D9). */ readonly lockReason: 'closed_state'; + /** [D8] The catalog's sentence, in the caller's locale. Absent on a refusal that could not judge the write. */ + readonly userMessage?: string; + /** [D8] The developer's sentence (API names), where `message` carries the person's. */ + readonly developerMessage?: string; } /** @@ -171,6 +221,229 @@ function verbPast(verb: ClosedStateWriteVerb): string { } } +// ── The sentence a person reads (D8) ───────────────────────────────────────── + +/** The host members the sentence is worded from. */ +type WordingHost = Pick; + +/** What a refusal names, by the case it answers. */ +export type ClosedStateRefusalWording = + /** A record's own write. `row` is the record as stored; absent for a write that matched rows by a predicate. */ + | { readonly kind: 'record'; readonly object: string; readonly row?: Record } + /** A line write, or a line's restore: the master, by its label alone. */ + | { readonly kind: 'master'; readonly master: string } + /** A delete refused for what it would also remove: the record asked to be deleted, and the object in the way. */ + | { readonly kind: 'delete_blocked'; readonly object: string; readonly row?: Record; readonly blockingObject: string }; + +function messagesFor(host: WordingHost, object: string, context: ExecutionContext | undefined): ValidationMessageContext | undefined { + try { + return host.validationMessageContext?.(object, context); + } catch { + // A misbehaving i18n service words the refusal in English; it never turns a 409 into a 500. + return undefined; + } +} + +/** + * The object's label in the caller's locale: the translation, else the + * declared label. `undefined` when it has neither: the API name, the last + * rung of `objectDisplayLabel`, never reaches this sentence. + */ +function objectLabelOf(host: WordingHost, object: string, messages: ValidationMessageContext | undefined): string | undefined { + let declared: string | undefined; + try { + const raw = (host._registry.getObject(object) as { label?: unknown } | undefined)?.label; + declared = typeof raw === 'string' && raw.trim() !== '' ? raw.trim() : undefined; + } catch { + declared = undefined; + } + let label: string; + try { + label = objectDisplayLabel(object, declared, messages ?? {}); + } catch { + label = declared ?? object; + } + return label && !(label === object && declared === undefined) ? label : undefined; +} + +/** + * The field an object's title is read from (ADR-0079's one arbiter), or + * `undefined`. A title is named only from a field whose value is display + * text and that the generic read returns, so the arbiter's answer gives no + * title when it is: + * - the id; + * - a field the generic read withholds: `internal` + * (`collectInternalReadFields`, left out of every row `engine-find.ts` + * returns) or a credential type (`collectCredentialFields`, served masked + * in those rows); `engine-find.ts`'s search scan skips the union of the + * two; + * - a reference field (`REFERENCE_VALUE_TYPES`): its value is a record id; + * - a field the object's `closedStates` names: its value is an option code. + */ +function titleFieldOf(host: Pick, object: string): string | undefined { + try { + const schema = host._registry.getObject(object) as { fields?: Record } | undefined; + const field = resolveDisplayField(schema as never); + if (!field || field === 'id' || field === '_id') return undefined; + if (collectInternalReadFields(schema as never).includes(field)) return undefined; + if (collectCredentialFields(schema as never).includes(field)) return undefined; + const type = schema?.fields?.[field]?.type; + if (typeof type === 'string' && REFERENCE_VALUE_TYPES.has(type)) return undefined; + if (closedValuesOf(schema)?.has(field)) return undefined; + return field; + } catch { + return undefined; + } +} + +/** + * [D8] The engine slot `ObjectQLPlugin` fills, beside + * `SECURITY_SERVICE_SOURCE_SLOT`, with a probe answering whether a `security` + * service is registered at all, read without building one (`false`: nothing + * is registered under the name). Read only by {@link titleFieldIsServed}, and + * only when the security source throws; no other reader of the source slot + * consults it. Not public surface. + */ +export const SECURITY_SERVICE_REGISTERED_SLOT: unique symbol = Symbol.for('objectstack.objectql.securityServiceRegistered'); + +/** + * [D8] True only when the host's registration probe answers that no + * `security` service is registered. A missing probe, a probe that throws, and + * any answer but `false` mean a service may be registered: no title. + */ +async function noSecurityServiceRegistered(facade: unknown): Promise { + const probe = (facade as Record)[SECURITY_SERVICE_REGISTERED_SLOT]; + if (typeof probe !== 'function') return false; + try { + return (await probe()) === false; + } catch { + return false; + } +} + +/** + * [D8] May the writer be served `field` of `object`? The rule the pending lock + * picks its title by (`plugin-approvals` `resolveReadableSnapshotFields`): the + * field is readable for the writer AND not served masked to it (the security + * contract's `getQueryableFields` is the read projection minus the masked + * fields), asked of the registered `security` service with the writer's own + * execution context. + * + * With no security service registered (the slot empty, or its source + * answering `null` or nothing) there is no field-level security: a read serves + * every field, so the stored title is the served one. So it is when the + * source throws and the host's registration probe + * (`SECURITY_SERVICE_REGISTERED_SLOT`) answers that no `security` service is + * registered: the in-repo kernels throw on a name nothing registered. Every + * other answer short of a clear yes names no title: a host that lends no + * engine, a slot that holds no function, a source that throws for a service + * that is registered (or with no probe to say it is not), a service without + * either member, a question that throws or answers nothing. + */ +async function titleFieldIsServed(host: WordingHost, object: string, field: string, context: ExecutionContext | undefined): Promise { + if (!host.facade) return false; + // Read from the engine slot at use (see SECURITY_SERVICE_SOURCE_SLOT), never cached. + const source = (host.facade as Record)[SECURITY_SERVICE_SOURCE_SLOT]; + if (source === undefined || source === null) return true; + if (typeof source !== 'function') return false; + let svc: Partial> | null | undefined; + try { + svc = source() as typeof svc; + } catch { + // A source that throws names no title, unless the host's registration + // probe answers that no `security` service is registered at all. + return noSecurityServiceRegistered(host.facade); + } + if (svc === undefined || svc === null) return true; + if (typeof svc.getReadableFields !== 'function' || typeof svc.getQueryableFields !== 'function') return false; + try { + const readable = await svc.getReadableFields(object, context as never); + if (!Array.isArray(readable) || !readable.includes(field)) return false; + const unmasked = await svc.getQueryableFields(object, context as never); + return Array.isArray(unmasked) && unmasked.includes(field); + } catch { + return false; + } +} + +/** + * [D8] The record's title as the writer would be served it, or `undefined`. + * Read off `row`, the record as stored (the engine's own read), and named only + * when the writer may be served the title field ({@link titleFieldIsServed}). + * An empty title, or one whose value is the record's id, is no title. + */ +export async function servedTitleOf( + this: WordingHost, + object: string, + row: Record | null | undefined, + context: ExecutionContext | undefined, +): Promise { + if (!row || typeof row !== 'object') return undefined; + const field = titleFieldOf(this, object); + if (!field) return undefined; + const raw = row[field]; + if (raw === null || raw === undefined || typeof raw === 'object') return undefined; + const title = String(raw).trim(); + if (!title) return undefined; + const id = row.id ?? row._id; + if (id !== undefined && id !== null && title === String(id)) return undefined; + return (await titleFieldIsServed(this, object, field, context)) ? title : undefined; +} + +/** + * [D8] The sentence a person reads for a closed-state refusal, rendered from + * the Operation Message Catalog in the caller's locale. Which form applies + * picks the KEY; the labels and the title are its parameters. + */ +export async function closedStateRefusalSentence( + this: WordingHost, + wording: ClosedStateRefusalWording, + context: ExecutionContext | undefined, +): Promise { + const subject = wording.kind === 'master' ? wording.master : wording.object; + const messages = messagesFor(this, subject, context); + const render = (messageKey: string, params: Record = {}) => + renderOperationMessage({ messageKey, params }, { locale: messages?.locale, translate: messages?.translate }); + try { + if (wording.kind === 'master') { + const label = objectLabelOf(this, wording.master, messages); + return label ? render('record_closed_untitled', { object: label }) : render('record_closed_opaque'); + } + const label = objectLabelOf(this, wording.object, messages); + const title = await servedTitleOf.call(this, wording.object, wording.row, context); + if (wording.kind === 'record') { + if (title) return label ? render('record_closed', { object: label, title }) : render('record_closed_unlabeled', { title }); + return label ? render('record_closed_untitled', { object: label }) : render('record_closed_opaque'); + } + const blocking = objectLabelOf(this, wording.blockingObject, messages); + if (!label || !blocking) return render('record_closed_delete_blocked_opaque'); + return title + ? render('record_closed_delete_blocked', { object: label, title, blockingObject: blocking }) + : render('record_closed_delete_blocked_untitled', { object: label, blockingObject: blocking }); + } catch { + return render(wording.kind === 'delete_blocked' ? 'record_closed_delete_blocked_opaque' : 'record_closed_opaque'); + } +} + +/** + * [D8] The refusal as a person reads it: `err`'s developer sentence is carried + * on `developerMessage`, and the catalog's sentence becomes its `userMessage` and + * its `message` (behind the code, which the data door strips). + */ +async function sayClosed( + this: WordingHost, + err: ClosedStateLockError, + wording: ClosedStateRefusalWording, + context: ExecutionContext | undefined, +): Promise { + const sentence = await closedStateRefusalSentence.call(this, wording, context); + const e = err as unknown as Record; + e.developerMessage = err.message; + e.message = `${CLOSED_STATE_LOCK_CODE}: ${sentence}`; + e.userMessage = sentence; + return err; +} + /** * [D5] Is a write in `context` bound by the lock? Every write is, except one * made in a system context. A write with no context is bound: no identity is @@ -340,21 +613,25 @@ export async function judgeClosedStateByIdWrite(this: ClosedStateLockHost, write if (carriedKeys(payload).length === 0) return; if (isBareReferentialClear(payload, write.referentialClear)) return; } - if (unit.own && rowIsClosed(prior, unit.own)) throw closedStateLockError(object, verb, 'record_closed'); + if (unit.own && rowIsClosed(prior, unit.own)) { + throw await sayClosed.call(this, closedStateLockError(object, verb, 'record_closed'), { kind: 'record', object, row: prior }, context); + } const refuse = (detail: string) => closedStateLockError(object, verb, 'cannot_judge', undefined, detail); + const masterClosed = (master: string) => + sayClosed.call(this, closedStateLockError(object, verb, 'master_closed', master), { kind: 'master', master }, context); for (const edge of unit.masters) { // The master the stored row hangs under: its stored state, whoever writes. const stored = scalarIdOf(prior[edge.fk]); if (stored === undefined) throw refuse(`its '${edge.fk}' does not hold one id`); if (stored !== null && await anyClosedAmong.call(this, edge.master, [stored], edge.closed, context, refuse)) { - throw closedStateLockError(object, verb, 'master_closed', edge.master); + throw await masterClosed(edge.master); } // A move names the master it moves to: the caller's read door first. if (verb === 'update' && payload && Object.prototype.hasOwnProperty.call(payload, edge.fk)) { const named = scalarIdOf(payload[edge.fk]); if (named === undefined) throw refuse(`the master named by '${edge.fk}' is not one id`); if (named !== null && named !== stored && await namedMastersClosed.call(this, edge, [named], context, refuse)) { - throw closedStateLockError(object, verb, 'master_closed', edge.master); + throw await masterClosed(edge.master); } } } @@ -384,7 +661,7 @@ export async function judgeClosedStateCreate( if (id !== null) named.push(id); } if (await namedMastersClosed.call(this, edge, [...new Set(named)], context, refuse)) { - throw closedStateLockError(object, 'create', 'master_closed', edge.master); + throw await sayClosed.call(this, closedStateLockError(object, 'create', 'master_closed', edge.master), { kind: 'master', master: edge.master }, context); } } } @@ -457,8 +734,11 @@ export async function judgeClosedStatePredicateWrite(this: ClosedStateLockHost, } }; if (unit.own && await probe(andWhere(ast.where, closedPredicate(unit.own)))) { - throw closedStateLockError(object, verb, 'record_closed'); + // Matched by a predicate: no one row is named, so no title (the label form). + throw await sayClosed.call(this, closedStateLockError(object, verb, 'record_closed'), { kind: 'record', object }, context); } + const masterClosed = (master: string) => + sayClosed.call(this, closedStateLockError(object, verb, 'master_closed', master), { kind: 'master', master }, context); let matched: ReadonlyArray> | undefined; const matchedRows = async (): Promise>> => { if (matched) return matched; @@ -477,7 +757,7 @@ export async function judgeClosedStatePredicateWrite(this: ClosedStateLockHost, for (const edge of unit.masters) { if (lineProbeServes.call(this, object, edge.master)) { const semiJoin = { [edge.fk]: { $in: ReadableIds.compose(ReadableIds.of(edge.master), closedPredicate(edge.closed)) } } as FilterCondition; - if (await probe(andWhere(ast.where, semiJoin))) throw closedStateLockError(object, verb, 'master_closed', edge.master); + if (await probe(andWhere(ast.where, semiJoin))) throw await masterClosed(edge.master); } else { const ids: string[] = []; for (const row of await matchedRows()) { @@ -486,14 +766,14 @@ export async function judgeClosedStatePredicateWrite(this: ClosedStateLockHost, if (id !== null) ids.push(id); } if (await anyClosedAmong.call(this, edge.master, ids, edge.closed, context, refuse)) { - throw closedStateLockError(object, verb, 'master_closed', edge.master); + throw await masterClosed(edge.master); } } if (verb === 'update' && payload && Object.prototype.hasOwnProperty.call(payload, edge.fk)) { const named = scalarIdOf(payload[edge.fk]); if (named === undefined) throw refuse(`the master named by '${edge.fk}' is not one id`); if (named !== null && await namedMastersClosed.call(this, edge, [named], context, refuse)) { - throw closedStateLockError(object, verb, 'master_closed', edge.master); + throw await masterClosed(edge.master); } } } @@ -503,17 +783,28 @@ export async function judgeClosedStatePredicateWrite(this: ClosedStateLockHost, * [D6] Judge the set a delete's cascade will remove, collected whole before * any row is removed (`engine-cascade-planning.ts#cascadeDeleteRelations`). * Refused whole when a member is closed, or is a line of a closed record. The - * refusal names the record the caller asked to delete (its object) and the - * object whose closed record stands in the way, and nothing else. + * refusal names the record the caller asked to delete and the object whose + * closed record stands in the way, and nothing else (D8): the record by its + * title as the caller is served it where `named` (the ids the delete named, + * never the set planned so far) holds exactly one, else by its object's label + * alone. A delete that names its rows by a predicate passes none. */ export async function judgeClosedStateCascadeSet( - this: Pick, + this: Pick, root: string, members: ReadonlyMap>, context: ExecutionContext | undefined, + named: ReadonlyArray = [], ): Promise { if (!boundByClosedStates(context)) return; const refuse = (detail: string) => closedStateLockError(root, 'delete', 'cannot_judge', undefined, detail); + const blocked = async (blockingObject: string) => + sayClosed.call( + this, + closedStateLockError(root, 'delete', 'cascade_reaches_closed', blockingObject), + { kind: 'delete_blocked', object: root, row: named.length === 1 ? await storedTitleRow.call(this, root, named[0]!, context) : undefined, blockingObject }, + context, + ); for (const [object, idSet] of members) { const unit = closedStateUnitOf.call(this, object); if (!unit || idSet.size === 0) continue; @@ -531,7 +822,7 @@ export async function judgeClosedStateCascadeSet( }; if (unit.own) { for (const part of parts) { - if (await probe(part, closedPredicate(unit.own))) throw closedStateLockError(root, 'delete', 'cascade_reaches_closed', object); + if (await probe(part, closedPredicate(unit.own))) throw await blocked(object); } } for (const edge of unit.masters) { @@ -539,7 +830,7 @@ export async function judgeClosedStateCascadeSet( // The predicate door's semi-join, scoped to the set's ids. const semiJoin = { [edge.fk]: { $in: ReadableIds.compose(ReadableIds.of(edge.master), closedPredicate(edge.closed)) } } as FilterCondition; for (const part of parts) { - if (await probe(part, semiJoin)) throw closedStateLockError(root, 'delete', 'cascade_reaches_closed', edge.master); + if (await probe(part, semiJoin)) throw await blocked(edge.master); } continue; } @@ -561,12 +852,44 @@ export async function judgeClosedStateCascadeSet( throw Object.assign(refuse(`the rows of '${object}' its cascade reaches could not be read`), { cause: error }); } if (await anyClosedAmong.call(this, edge.master, masterIds, edge.closed, context, refuse)) { - throw closedStateLockError(root, 'delete', 'cascade_reaches_closed', edge.master); + throw await blocked(edge.master); } } } } +/** + * [D8] The title column of the one record a delete names, read by the engine + * from the store (inside the caller's organization scope and unit of work), so + * the refusal can name it as the caller is served it ({@link servedTitleOf}). + * Read only on the refusal path. A read that fails is reported at `warn` and + * names no title: the refusal stands whole either way, and only its wording + * falls back to the label form. + */ +async function storedTitleRow( + this: Pick, + object: string, + id: string | number, + context: ExecutionContext | undefined, +): Promise | undefined> { + const field = titleFieldOf(this, object); + if (!field) return undefined; + try { + const rows = (await this.getDriver(object).find( + object, + { object, where: { id }, fields: ['id', field], limit: 1 }, + this.buildDriverOptions(object, context), + )) as Array> | null; + return Array.isArray(rows) && rows[0] && typeof rows[0] === 'object' ? rows[0] : undefined; + } catch (error) { + this.logger?.warn( + `[closed-state] the title of the '${object}' record a refused delete names could not be read; the refusal names its object's label instead`, + { object, error: (error as Error)?.message ?? String(error) }, + ); + return undefined; + } +} + /** * [D7] Restore: an entry that would put a row back under a LIVE, closed master * that is not itself part of the entry is refused before anything is written. @@ -574,7 +897,7 @@ export async function judgeClosedStateCascadeSet( * the live master's id. */ export async function judgeClosedStateRestore( - this: Pick, + this: Pick, parents: ReadonlyArray<{ object: string; field: string; master: string; id: string }>, context: ExecutionContext | undefined, ): Promise { @@ -592,7 +915,7 @@ export async function judgeClosedStateRestore( for (const [master, { closed, ids, object }] of byMaster) { const refuse = (detail: string) => closedStateLockError(object, 'restore', 'cannot_judge', undefined, detail); if (await anyClosedAmong.call(this, master, ids, closed, context, refuse)) { - throw closedStateLockError(object, 'restore', 'master_closed', master); + throw await sayClosed.call(this, closedStateLockError(object, 'restore', 'master_closed', master), { kind: 'master', master }, context); } } } diff --git a/packages/objectql/src/engine-cascade-planning.ts b/packages/objectql/src/engine-cascade-planning.ts index 654cf66a52b..5d19e07c2fc 100644 --- a/packages/objectql/src/engine-cascade-planning.ts +++ b/packages/objectql/src/engine-cascade-planning.ts @@ -88,6 +88,10 @@ export interface CascadePlanningHost { /** [ADR-0162 D6] The driver options the closed-state lock reads the cascade set with. */ buildDriverOptions: ObjectQLClass['buildDriverOptions']; resolveEnginePosture: ObjectQLClass['resolveEnginePosture']; + /** [ADR-0162 D8] The engine, whose security-service slot answers whether the caller is served the root's title. */ + readonly facade: ObjectQLClass; + /** [ADR-0162 D8] The caller's locale and translator, which the closed-state refusal's sentence is worded in. */ + validationMessageContext: ObjectQLClass['validationMessageContext']; getDriver: ObjectQLClass['getDriver']; isTenantColumnSetNull: ObjectQLClass['isTenantColumnSetNull']; readonly logger: ObjectQLClass['logger']; @@ -536,7 +540,7 @@ export class CascadePlanningFacet { * (formula values, file references, hooks), so they are not the values a * restore must write back. */ - static async cascadeDeleteRelations(this: Pick, object: string, ids: ReadonlyArray, context?: ExecutionContext, depth = 0, onCollected?: (set: CascadeDeleteSet) => Promise): Promise { + static async cascadeDeleteRelations(this: Pick, object: string, ids: ReadonlyArray, context?: ExecutionContext, depth = 0, onCollected?: (set: CascadeDeleteSet) => Promise, named: ReadonlyArray = []): Promise { const roots: Array = []; const seen = new Set(); for (const id of ids) { @@ -583,7 +587,9 @@ export class CascadePlanningFacet { // point: after the caller's gates on the record it asked to delete and // before the first row is removed, never leg by leg. A member that is // closed, or is a line of a closed record, refuses the delete whole. - await judgeClosedStateCascadeSet.call(this, object, cascadeSet.members, context); + // [D8] The refusal's title form reads the ids the delete NAMED (`named`), + // never the set planned so far. + await judgeClosedStateCascadeSet.call(this, object, cascadeSet.members, context, named); if (onCollected) await onCollected(cascadeSet); await this.cascadeDeleteSets.run(cascadeSet, () => this.walkReferencingRelations(object, fresh, context, objects, cascadeSet), diff --git a/packages/objectql/src/engine-delete-and-aggregate.ts b/packages/objectql/src/engine-delete-and-aggregate.ts index 072787d6e74..c2718fa9afe 100644 --- a/packages/objectql/src/engine-delete-and-aggregate.ts +++ b/packages/objectql/src/engine-delete-and-aggregate.ts @@ -131,6 +131,8 @@ export interface DeleteAndAggregateHost { expandSearchOnOptions: ObjectQLClass['expandSearchOnOptions']; /** The engine itself: a moved body reads `this.facade` where the method read a bare `this` (#30020). */ readonly facade: ObjectQLClass; + /** [ADR-0162 D8] The caller's locale and translator, which the closed-state refusal's sentence is worded in. */ + validationMessageContext: ObjectQLClass['validationMessageContext']; getDriver: ObjectQLClass['getDriver']; getSummaryDescriptors: ObjectQLClass['getSummaryDescriptors']; hasHooksFor: ObjectQLClass['hasHooksFor']; @@ -164,7 +166,7 @@ export interface DeleteAndAggregateHost { /** The bodies of the "Delete, count, aggregate and execute" section of `ObjectQL`: a stateless facet, called by the class's stubs. */ export class DeleteAndAggregateFacet { /** The body of `ObjectQL#delete`; the method's docblock there is its contract. */ - static async delete(this: Pick, object: string, options?: EngineDeleteOptions & RecycleBinDeleteObservability): Promise { + static async delete(this: Pick, object: string, options?: EngineDeleteOptions & RecycleBinDeleteObservability): Promise { object = this.resolveObjectName(object); // [#22782, #34412] An aborting `afterDelete`, or a refusal after a `beforeDelete` hook's // `ctx.api` write, rolls this write back with it — see `opensAfterAbortUnit`. @@ -713,7 +715,7 @@ export class DeleteAndAggregateFacet { let cascadeChildVanished = false; const runByIdDelete = async (writeContext?: ExecutionContext) => { const bin = this.openRecycleBinCapture(object, hookContext.input.id as string | number, writeContext, options?.multi === true || permanent); - await this.cascadeDeleteRelations(object, [hookContext.input.id as string | number], writeContext, 0, bin?.onCollected) + await this.cascadeDeleteRelations(object, [hookContext.input.id as string | number], writeContext, 0, bin?.onCollected, [hookContext.input.id as string | number]) .catch((e: unknown) => { throw cascadeStoppedRefusal(e, object); }); // [ADR-0131 D9] The entry's organization, when neither the record // nor the context names one, is the engine's own system-insert diff --git a/packages/objectql/src/engine.ts b/packages/objectql/src/engine.ts index de840274a13..861715cdb58 100644 --- a/packages/objectql/src/engine.ts +++ b/packages/objectql/src/engine.ts @@ -4927,10 +4927,10 @@ export class ObjectQL implements IObjectQLEngine { ids: ReadonlyArray, context?: ExecutionContext, depth = 0, - onCollected?: (set: CascadeDeleteSet) => Promise, + onCollected?: (set: CascadeDeleteSet) => Promise, named?: ReadonlyArray, // [ADR-0162 D8] the ids the delete named ): Promise { // [#29986 codemod] The body moved to `engine-cascade-planning.ts`, its docblock with it (see `CascadePlanningHost`). - return CascadePlanningFacet.cascadeDeleteRelations.call(cascadePlanningHost.of(this), object, ids, context, depth, onCollected); + return CascadePlanningFacet.cascadeDeleteRelations.call(cascadePlanningHost.of(this), object, ids, context, depth, onCollected, named); } /** @@ -5826,7 +5826,7 @@ export class ObjectQL implements IObjectQLEngine { refuseRestrictsInsideOwnCascade: (...a) => engine.refuseRestrictsInsideOwnCascade(...a), resolveObjectName: (...a) => engine.resolveObjectName(...a), update: (...a) => engine.update(...a), - walkReferencingRelations: (...a) => engine.walkReferencingRelations(...a), buildDriverOptions: (...a) => engine.buildDriverOptions(...a), resolveEnginePosture: () => engine.resolveEnginePosture(), // [ADR-0162 D6] + walkReferencingRelations: (...a) => engine.walkReferencingRelations(...a), buildDriverOptions: (...a) => engine.buildDriverOptions(...a), resolveEnginePosture: () => engine.resolveEnginePosture(), facade: engine, validationMessageContext: (...a) => engine.validationMessageContext(...a), // [ADR-0162 D6, D8] })); compatibilitySectionHost.install((engine) => ({ get _registry() { return engine._registry; }, @@ -5899,7 +5899,7 @@ export class ObjectQL implements IObjectQLEngine { transaction: (...a) => engine.transaction(...a), triggerHooks: (...a) => engine.triggerHooks(...a), warnCascadeNotAtomic: (...a) => engine.warnCascadeNotAtomic(...a), - withResolvedWhere: (...a) => engine.withResolvedWhere(...a), masterDetailHeadersCallerReads: (...a) => engine.masterDetailHeadersCallerReads(...a), resolveEnginePosture: () => engine.resolveEnginePosture(), // [ADR-0162 D10] + withResolvedWhere: (...a) => engine.withResolvedWhere(...a), masterDetailHeadersCallerReads: (...a) => engine.masterDetailHeadersCallerReads(...a), resolveEnginePosture: () => engine.resolveEnginePosture(), validationMessageContext: (...a) => engine.validationMessageContext(...a), // [ADR-0162 D8, D10] })); findHost.install((engine) => ({ get _registry() { return engine._registry; }, diff --git a/packages/objectql/src/plugin.ts b/packages/objectql/src/plugin.ts index c8717fa8063..40b46c62d86 100644 --- a/packages/objectql/src/plugin.ts +++ b/packages/objectql/src/plugin.ts @@ -15,7 +15,8 @@ import { OWNERSHIP_QUEUE_SERVICE } from '@objectstack/spec/contracts'; import { assembleMetadataProtocol, isServedOverrideRowOf } from '@objectstack/metadata-protocol'; import { installedManifestsOf, isTenantAuthored, readLegacyOrganizationRows } from '@objectstack/metadata-core'; import type { MetadataAuthoringChannel } from '@objectstack/metadata-protocol'; -import { Plugin, PluginContext } from '@objectstack/core'; +import { Plugin, PluginContext, isServiceNotRegisteredError } from '@objectstack/core'; +import { SECURITY_SERVICE_REGISTERED_SLOT } from './closed-state-lock.js'; import { resolveArtifactPackageEntries, artifactPackageId, declaredDependencyIds, readDeploymentOrgScopingEntitlement } from '@objectstack/core'; // [ADR-0130 D4] The residual rule's decision half — which top-level items of a // multi-package stack no body declares, and the id they take. See @@ -561,6 +562,40 @@ export const OBJECTQL_DRIVERS_READY_HOOK = 'objectql:drivers-ready'; */ export const OBJECTQL_SCHEMA_SYNCED_HOOK = 'objectql:schema-synced'; +/** + * [ADR-0162 D8] Whether a `security` service is registered on the plugin's + * kernel, read without building one: `false` only when nothing is registered + * under the name, `true` for every other answer (the answer that names no + * title in a closed-state refusal). + * - The sync accessor returns it, or the context's service map holds the + * name: registered. + * - The sync accessor refuses a service registered as a factory and not yet + * built with "is async" (the message the kernel keeps verbatim for callers + * that match on it): registered, and the probe does not build it. + * - Otherwise the kernel's async accessor draws the line with the branded + * "never registered" rejection (`isServiceNotRegisteredError`), given + * before anything is built; any other answer is registered. + * - A host with no async accessor (`LiteKernel`) has no factories, so "not + * registered" is the only fault its sync accessor reports. + */ +async function securityServiceRegistered(ctx: PluginContext): Promise { + try { + ctx.getService('security'); + return true; + } catch (err) { + if (err instanceof Error && err.message.includes('is async')) return true; + } + if (ctx.getServices().has('security')) return true; + const kernel = ctx.getKernel?.() as { getServiceAsync?: (name: string) => Promise } | undefined; + if (typeof kernel?.getServiceAsync !== 'function') return false; + try { + await kernel.getServiceAsync('security'); + return true; + } catch (err) { + return !isServiceNotRegisteredError(err); + } +} + export class ObjectQLPlugin implements Plugin { name = 'com.objectstack.engine.objectql'; type = 'objectql' as const; @@ -923,6 +958,12 @@ export class ObjectQLPlugin implements Plugin { // `$in: []` (fail closed); a throw — the in-repo kernels' answer for a // name nothing registered — is one of them. (this.ql as unknown as Record)[SECURITY_SERVICE_SOURCE_SLOT] = () => ctx.getService('security'); + // [ADR-0162 D8] Beside the source, a probe that answers whether a + // `security` service is registered at all (SECURITY_SERVICE_REGISTERED_SLOT). + // Only the closed-state refusal's title rule reads it, and only when the + // source above throws; it builds no service, so every other reader of the + // source answers as before. + (this.ql as unknown as Record)[SECURITY_SERVICE_REGISTERED_SLOT] = () => securityServiceRegistered(ctx); // [ADR-0142 D5] The assignment seam reads the ownership-queue service the // same way: a source, resolved at use. ⛔ `ownership-queue`, never the job // queue's `queue`. diff --git a/packages/qa/dogfood/test/closed-state-refusal-security-source.test.ts b/packages/qa/dogfood/test/closed-state-refusal-security-source.test.ts new file mode 100644 index 00000000000..b1921b351f4 --- /dev/null +++ b/packages/qa/dogfood/test/closed-state-refusal-security-source.test.ts @@ -0,0 +1,223 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 D8] The closed-state refusal's title on a real kernel, by what the + * kernel registers under `security`. `ObjectQLPlugin` hands the engine the + * service as a source (`SECURITY_SERVICE_SOURCE_SLOT`) and, beside it, a + * probe that answers whether a `security` service is registered at all, + * read without building one (`SECURITY_SERVICE_REGISTERED_SLOT`). Only the + * refusal's title rule reads the probe. + * + * - No `security` service registered: there is no field-level security, so + * the refusal names the title D8 gives. The rules on which field a title + * is read from still apply first: a title field the generic read does not + * return (internal, credential) or whose value is not display text + * (reference, a field `closedStates` names) gives the label form there too. + * - A `security` service registered and not resolvable (a factory that + * throws, or one the sync accessor does not build): the label form. + * - Every other reader of the source answers as it did: the `ReadableIds` + * resolution and the search's queryable-field read, before and after a + * refusal, and the probe builds no factory-registered service. + * + * Real `ObjectKernel`, `ObjectQLPlugin`, driver-sql on better-sqlite3 + * `:memory:`. + */ + +import { afterEach, describe, expect, it } from 'vitest'; +import { ObjectKernel, type Plugin, type PluginContext } from '@objectstack/core'; +import { ObjectQLPlugin, type ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { BUILTIN_OPERATION_MESSAGES } from '@objectstack/spec/system'; +import { DEFAULT_ORGANIZATION_ID, installDefaultOrganization } from './default-organization.testkit.js'; + +const WRITER = { userId: 'usr_writer', tenantId: DEFAULT_ORGANIZATION_ID, positions: [], permissions: [] } as const; +const by = (context: unknown) => ({ context }) as never; + +const STATUS_OPTIONS = [{ label: 'Draft', value: 'draft' }, { label: 'Settled', value: 'settled' }]; +const TAG = 'dg_css_tag'; +const SLIP = 'dg_css_slip'; +const KINDS = [ + { key: 'plain', object: 'dg_css_plain', label: 'Memo', titleField: 'name', def: { type: 'text', label: 'Name' }, value: 'Northwind March' }, + { key: 'internal', object: 'dg_css_internal', label: 'Ledger', titleField: 'code', def: { type: 'text', label: 'Code', internal: true }, value: 'LEDGER-CODE-7' }, + { key: 'credential', object: 'dg_css_credential', label: 'Vault', titleField: 'passcode', def: { type: 'password', label: 'Passcode' }, value: 'PASSCODE-VALUE-7' }, + { key: 'reference', object: 'dg_css_reference', label: 'Tagged', titleField: 'tag', def: { type: 'lookup', label: 'Tag', reference: TAG }, value: 'tag1' }, + { key: 'state', object: 'dg_css_state', label: 'Stage', titleField: 'status', def: undefined, value: 'settled' }, +] as const; +const PLAIN = KINDS[0]; +const WITHHELD = KINDS.slice(1); + +const en = BUILTIN_OPERATION_MESSAGES.en; +const fill = (template: string, params: Record = {}) => template.replace(/\{\{(\w+)\}\}/g, (m, k: string) => params[k] ?? m); + +interface Refusal { code?: unknown; status?: unknown; message?: unknown; userMessage?: unknown } + +async function refusal(run: () => Promise): Promise { + try { + await run(); + } catch (e) { + return e as Refusal; + } + throw new Error('expected the write to be refused, and it landed'); +} + +function sentenceOf(err: Refusal): string { + expect([err.code, err.status]).toEqual(['RECORD_LOCKED', 409]); + expect(err.message).toBe(`RECORD_LOCKED: ${String(err.userMessage)}`); + return String(err.userMessage); +} + +/** A `security` service the sync accessor never builds: registered as a factory. */ +function securityFactoryPlugin(factory: () => unknown): Plugin { + return { + name: 'dg-closed-state-security-factory', + init: async (ctx: PluginContext) => { + ctx.registerServiceFactory('security', factory); + }, + } as Plugin; +} + +let kernel: ObjectKernel | undefined; +let ql: ObjectQL; + +afterEach(async () => { + try { await kernel?.shutdown(); } catch { /* noop */ } + kernel = undefined; +}); + +async function boot(extra: Plugin[] = []): Promise { + kernel = new ObjectKernel({ logger: { level: 'silent' } } as never); + await kernel.use(new ObjectQLPlugin()); + for (const plugin of extra) await kernel.use(plugin); + await kernel.bootstrap(); + ql = kernel.getService('objectql'); + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); + await driver.connect(); + ql.registerDriver(driver, true); + const kindObjects = KINDS.map((k) => ({ + name: k.object, + label: k.label, + nameField: k.titleField, + fields: { + status: { type: 'select', label: 'Status', options: STATUS_OPTIONS }, + note: { type: 'text', label: 'Note' }, + ...(k.def ? { [k.titleField]: k.def } : {}), + }, + closedStates: { status: ['settled'] }, + })); + const slip = { + name: SLIP, + label: 'Slip', + fields: { + name: { type: 'text', label: 'Name' }, + status: { type: 'select', label: 'Status', options: STATUS_OPTIONS }, + ...Object.fromEntries(KINDS.map((k) => [`${k.key}_ref`, { type: 'lookup', label: k.label, reference: k.object, deleteBehavior: 'cascade' }])), + }, + closedStates: { status: ['settled'] }, + }; + ql.registerApp({ + id: 'com.objectstack.dogfood.closed-state-refusal-security-source', + name: 'Closed-state refusal security source', + version: '1.0.0', + type: 'plugin', + scope: 'system', + objects: [{ name: TAG, label: 'Tag', fields: { name: { type: 'text', label: 'Name' } } }, ...kindObjects, slip], + } as never); + await ql.syncSchemas(); + await installDefaultOrganization(ql as never); + // Seeded through the driver: the rows are data at rest, whatever a write of each field type would do. + const put = (object: string, row: Record) => + ql.getDriverForObject(object)!.create(object, { organization_id: DEFAULT_ORGANIZATION_ID, ...row }); + await put(TAG, { id: 'tag1', name: 'Priority' }); + for (const k of KINDS) { + const title = k.key === 'state' ? {} : { [k.titleField]: k.value }; + await put(k.object, { id: `${k.key}_closed`, status: 'settled', ...title }); + await put(k.object, { id: `${k.key}_root`, status: 'draft', ...(k.key === 'state' ? {} : title) }); + await put(SLIP, { id: `slip_${k.key}`, name: `Slip ${k.key}`, status: 'settled', [`${k.key}_ref`]: `${k.key}_root` }); + } +} + +/** Update, by-id delete and cascade-delete root of one kind, as the writer. */ +async function refusalsOf(k: (typeof KINDS)[number]): Promise<{ update: string; del: string; cascade: string }> { + const update = sentenceOf(await refusal(() => ql.update(k.object, { id: `${k.key}_closed`, note: 'x' }, by(WRITER)))); + const del = sentenceOf(await refusal(() => ql.delete(k.object, { where: { id: `${k.key}_closed` }, context: WRITER } as never))); + const cascade = sentenceOf(await refusal(() => ql.delete(k.object, { where: { id: `${k.key}_root` }, context: WRITER } as never))); + return { update, del, cascade }; +} + +const untitledOf = (k: (typeof KINDS)[number]) => ({ + update: fill(en.record_closed_untitled, { object: k.label }), + del: fill(en.record_closed_untitled, { object: k.label }), + cascade: fill(en.record_closed_delete_blocked_untitled, { object: k.label, blockingObject: 'Slip' }), +}); + +/** What the engine's other readers of the security source answer now. */ +async function otherReaders(): Promise<{ readableIds: unknown; searchQueryable: unknown }> { + const engine = ql as unknown as { + resolveReadableIdsSecurity(): { kind: string; why?: string }; + resolveSearchQueryableFields(object: string, context: unknown): Promise; + }; + const resolution = engine.resolveReadableIdsSecurity(); + return { + readableIds: { kind: resolution.kind, threw: typeof resolution.why === 'string' && resolution.why.startsWith('resolving the "security" service threw') }, + searchQueryable: await engine.resolveSearchQueryableFields(PLAIN.object, WRITER), + }; +} + +const SOURCE_THREW = { readableIds: { kind: 'unusable', threw: true }, searchQueryable: undefined }; + +describe('[ADR-0162 D8] the closed-state refusal\'s title, by what the kernel registers under `security`', () => { + it('no `security` service registered: the refusal names the title, on update, delete and a cascade-delete root', async () => { + await boot(); + const { update, del, cascade } = await refusalsOf(PLAIN); + expect(update).toBe(fill(en.record_closed, { object: PLAIN.label, title: PLAIN.value })); + expect(del).toBe(fill(en.record_closed, { object: PLAIN.label, title: PLAIN.value })); + expect(cascade).toBe(fill(en.record_closed_delete_blocked, { object: PLAIN.label, title: PLAIN.value, blockingObject: 'Slip' })); + }); + + it.each(WITHHELD.map((k) => [k.key, k] as const))( + 'no `security` service registered, %s title field: the label form, the field rules applying first', + async (_key, k) => { + await boot(); + expect(await refusalsOf(k)).toEqual(untitledOf(k)); + }, + ); + + it('a `security` service registered as a factory that throws: the label form', async () => { + await boot([securityFactoryPlugin(() => { throw new Error('the security service cannot be built on this host'); })]); + expect(await refusalsOf(PLAIN)).toEqual(untitledOf(PLAIN)); + }); + + it('a `security` service registered as a factory the sync accessor does not build: the label form, and the refusal builds nothing', async () => { + let built = 0; + const svc = { + getReadFilter: async () => null, + canReadObject: async () => true, + getReadableFields: async () => ['id', 'name', 'status', 'note'], + getQueryableFields: async () => ['id', 'name', 'status', 'note'], + }; + await boot([securityFactoryPlugin(() => { built += 1; return svc; })]); + const before = { built, readers: await otherReaders() }; + expect(await refusalsOf(PLAIN)).toEqual(untitledOf(PLAIN)); + expect({ built, readers: await otherReaders() }).toEqual(before); + }); + + it('the other readers of the security source answer as before: no service registered, and one registered that throws', async () => { + await boot(); + expect(await otherReaders(), 'no service, before a refusal').toEqual(SOURCE_THREW); + await refusalsOf(PLAIN); + expect(await otherReaders(), 'no service, after a refusal').toEqual(SOURCE_THREW); + await kernel!.shutdown(); + kernel = undefined; + + await boot([securityFactoryPlugin(() => { throw new Error('the security service cannot be built on this host'); })]); + expect(await otherReaders(), 'a throwing factory, before a refusal').toEqual(SOURCE_THREW); + await refusalsOf(PLAIN); + expect(await otherReaders(), 'a throwing factory, after a refusal').toEqual(SOURCE_THREW); + }); + + it('a source that throws with no probe beside it names no title', async () => { + await boot(); + delete (ql as unknown as Record)[Symbol.for('objectstack.objectql.securityServiceRegistered')]; + expect(await refusalsOf(PLAIN)).toEqual(untitledOf(PLAIN)); + }); +}); diff --git a/packages/qa/dogfood/test/closed-state-refusal-sentence.test.ts b/packages/qa/dogfood/test/closed-state-refusal-sentence.test.ts new file mode 100644 index 00000000000..f68088b001a --- /dev/null +++ b/packages/qa/dogfood/test/closed-state-refusal-sentence.test.ts @@ -0,0 +1,418 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 D8] The closed-state refusal's sentence, on a real engine and store. + * + * The lock refuses `409 RECORD_LOCKED`; what a person reads is the Operation + * Message Catalog's sentence, carried as the refusal's `userMessage` and as its + * `message` behind the code. This file pins which form each refusal takes and + * what each may name, on `ObjectQL` over SQLite (`SqlDriver`, better-sqlite3 + * `:memory:`): + * + * - a record's own write: the title the writer would be served, by the + * security service's answer in the engine's slot (here a stand-in that + * answers per writer; the real plugin is booted in + * `closed-state-refusal-wire.dogfood.test.ts`): readable and not masked + * gives the title, unreadable or masked gives the label form; + * - a predicate write: the label form; + * - a line write and a line's restore: the master's label alone; + * - a delete refused for what it would also remove: the record asked to be + * deleted and the object in the way, the title only for one record; + * - an object with no label: the forms that name no label; never its API name; + * - a refusal that could not judge the write keeps the developer's sentence + * and marks no `userMessage`. + * + * Every person-facing string is checked for the absence of every API name, + * record id and state value of the fixture. + */ + +import { afterEach, describe, expect, it } from 'vitest'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { BUILTIN_OPERATION_MESSAGES } from '@objectstack/spec/system'; +import { SysRecycleBin } from '@objectstack/platform-objects/system'; +import { DEFAULT_ORGANIZATION_ID, installDefaultOrganization } from './default-organization.testkit.js'; + +const SYS = { isSystem: true, userId: 'usr_system' } as const; +const caller = (userId: string, locale?: string) => + ({ userId, tenantId: DEFAULT_ORGANIZATION_ID, positions: [], permissions: [], ...(locale ? { locale } : {}) }) as const; +/** May read every field. */ +const WRITER = caller('usr_writer'); +/** May not read the invoice's or the customer's title field. */ +const UNREAD = caller('usr_unread'); +/** Is served the invoice's title field masked: readable, not queryable. */ +const MASKED = caller('usr_masked'); + +/** The slot `ObjectQLPlugin` fills with the registered `security` service's source. */ +const SECURITY_SLOT = Symbol.for('objectstack.objectql.securityServiceSource'); + +const INVOICE = 'dg_csr_invoice'; +const LINE = 'dg_csr_line'; +const CUSTOMER = 'dg_csr_customer'; +const PRODUCT = 'dg_csr_product'; +const BARE = 'dg_csr_bare'; + +const STATUS_OPTIONS = [{ label: 'Draft', value: 'draft' }, { label: 'Settled', value: 'settled' }]; + +const OBJECTS = [ + { name: CUSTOMER, label: 'Customer', fields: { name: { type: 'text', label: 'Name' } } }, + { name: PRODUCT, label: 'Product', fields: { name: { type: 'text', label: 'Name' } } }, + { + name: INVOICE, + label: 'Invoice', + fields: { + name: { type: 'text', label: 'Number' }, + status: { type: 'select', label: 'Status', options: STATUS_OPTIONS }, + amount: { type: 'number', label: 'Amount' }, + customer: { type: 'lookup', label: 'Customer', reference: CUSTOMER, deleteBehavior: 'cascade' }, + }, + closedStates: { status: ['settled'] }, + }, + { + name: LINE, + label: 'Invoice line', + fields: { + name: { type: 'text', label: 'Description' }, + qty: { type: 'number', label: 'Quantity' }, + invoice: { type: 'master_detail', label: 'Invoice', reference: INVOICE, required: true }, + product: { type: 'lookup', label: 'Product', reference: PRODUCT, deleteBehavior: 'cascade' }, + }, + }, + { + // No label: the sentence names no label, and never the API name. + name: BARE, + fields: { + name: { type: 'text', label: 'Name' }, + status: { type: 'select', label: 'Status', options: STATUS_OPTIONS }, + }, + closedStates: { status: ['settled'] }, + }, +]; + +/** Synthetic titles and ids. */ +const T = { closed: 'Northwind March', open: 'Fabrikam April', customer: 'Contoso Holdings', bare: 'Litware Group' } as const; +const IDS = ['cu1', 'cu2', 'cu3', 'pr1', 'inv_closed', 'inv_open', 'inv_other', 'l_closed', 'l_open', 'bare_closed']; + +let engine: ObjectQL; + +/** A stand-in for the security service's two field answers, per writer. */ +function fieldSecurity() { + const asked: Array<{ object: string; userId: unknown }> = []; + const titleFields = new Set([`${INVOICE}.name`, `${CUSTOMER}.name`]); + const all = (object: string) => Object.keys((OBJECTS.find((o) => o.name === object)?.fields ?? {}) as object).concat('id'); + return { + asked, + svc: { + async getReadableFields(object: string, context?: { userId?: unknown }) { + asked.push({ object, userId: context?.userId }); + return all(object).filter((f) => !(context?.userId === UNREAD.userId && titleFields.has(`${object}.${f}`))); + }, + async getQueryableFields(object: string, context?: { userId?: unknown }) { + return all(object).filter((f) => !((context?.userId === UNREAD.userId || context?.userId === MASKED.userId) && titleFields.has(`${object}.${f}`))); + }, + }, + }; +} + +async function boot(opts: { security?: unknown; recycleBin?: boolean; source?: () => unknown } = {}): Promise { + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); + engine = new ObjectQL(); + engine.registerDriver(driver, true); + await engine.init(); + engine.registerApp({ + id: 'com.objectstack.dogfood.closed-state-refusal-sentence', + name: 'Closed-state refusal sentence', + version: '1.0.0', + type: 'plugin', + scope: 'system', + objects: [...OBJECTS, ...(opts.recycleBin ? [SysRecycleBin] : [])], + } as never); + await engine.syncSchemas(); + await installDefaultOrganization(engine); + const put = (object: string, row: Record) => engine.insert(object, row, { context: SYS } as never); + await put(CUSTOMER, { id: 'cu1', name: T.customer }); + await put(CUSTOMER, { id: 'cu2', name: 'Adventure Works' }); + await put(CUSTOMER, { id: 'cu3', name: 'Tailspin' }); + await put(PRODUCT, { id: 'pr1', name: 'Widget' }); + await put(INVOICE, { id: 'inv_closed', name: T.closed, status: 'settled', amount: 10, customer: 'cu1' }); + await put(INVOICE, { id: 'inv_open', name: T.open, status: 'draft', amount: 10, customer: 'cu2' }); + await put(INVOICE, { id: 'inv_other', name: 'Other', status: 'settled', amount: 10, customer: 'cu3' }); + await put(LINE, { id: 'l_closed', name: 'Widgets', qty: 1, invoice: 'inv_closed', product: 'pr1' }); + await put(LINE, { id: 'l_open', name: 'Gadgets', qty: 1, invoice: 'inv_open' }); + await put(BARE, { id: 'bare_closed', name: T.bare, status: 'settled' }); + if (opts.security !== undefined) (engine as unknown as Record)[SECURITY_SLOT] = () => opts.security; + if (opts.source !== undefined) (engine as unknown as Record)[SECURITY_SLOT] = opts.source; +} + +afterEach(async () => { + await engine?.destroy(); +}); + +interface Refusal { code?: unknown; status?: unknown; reason?: unknown; message?: unknown; userMessage?: unknown; developerMessage?: unknown } + +async function refusal(run: () => Promise): Promise { + try { + await run(); + } catch (e) { + return e as Refusal; + } + throw new Error('expected the write to be refused, and it landed'); +} + +const en = BUILTIN_OPERATION_MESSAGES.en; +const fill = (template: string, params: Record = {}) => template.replace(/\{\{(\w+)\}\}/g, (m, k: string) => params[k] ?? m); +const FORBIDDEN = [INVOICE, LINE, CUSTOMER, PRODUCT, BARE, 'dg_csr', 'settled', 'closedStates', ...IDS]; + +/** The sentence a person reads, checked for the code and for every value it must not carry. */ +function sentenceOf(err: Refusal): string { + expect([err.code, err.status]).toEqual(['RECORD_LOCKED', 409]); + expect(typeof err.userMessage).toBe('string'); + expect(err.message, 'message carries the same sentence behind the code').toBe(`RECORD_LOCKED: ${String(err.userMessage)}`); + for (const value of FORBIDDEN) expect(String(err.userMessage), `carries ${value}`).not.toContain(value); + return String(err.userMessage); +} + +const by = (context: unknown) => ({ context }) as never; + +describe('[ADR-0162 D8] the closed-state refusal names what the writer is served, and nothing else', () => { + it('a record\'s own write: the title when no field-level security is registered (a read serves every field)', async () => { + await boot(); + const update = await refusal(() => engine.update(INVOICE, { id: 'inv_closed', amount: 99 }, by(WRITER))); + expect(sentenceOf(update)).toBe(fill(en.record_closed, { object: 'Invoice', title: T.closed })); + const del = await refusal(() => engine.delete(INVOICE, { where: { id: 'inv_closed' }, context: WRITER } as never)); + expect(sentenceOf(del)).toBe(fill(en.record_closed, { object: 'Invoice', title: T.closed })); + }); + + it('the title only where the writer may be served the field: readable and unmasked yes, unreadable or masked no', async () => { + const { svc, asked } = fieldSecurity(); + await boot({ security: svc }); + const served = await refusal(() => engine.update(INVOICE, { id: 'inv_closed', amount: 99 }, by(WRITER))); + expect(sentenceOf(served)).toBe(fill(en.record_closed, { object: 'Invoice', title: T.closed })); + for (const writer of [UNREAD, MASKED]) { + const err = await refusal(() => engine.update(INVOICE, { id: 'inv_closed', amount: 99 }, by(writer))); + const sentence = sentenceOf(err); + expect(sentence, writer.userId).toBe(fill(en.record_closed_untitled, { object: 'Invoice' })); + expect(sentence, writer.userId).not.toContain(T.closed); + } + // Asked as the writer, with the writer's own context. + expect(asked.map((a) => a.userId)).toEqual([WRITER.userId, UNREAD.userId, MASKED.userId]); + }); + + it('a security service that cannot say what is masked names no title (fail closed)', async () => { + await boot({ security: { getReadableFields: async () => ['id', 'name', 'status', 'amount', 'customer'] } }); + const err = await refusal(() => engine.update(INVOICE, { id: 'inv_closed', amount: 99 }, by(WRITER))); + expect(sentenceOf(err)).toBe(fill(en.record_closed_untitled, { object: 'Invoice' })); + }); + + it('a security-service source that throws names no title; a source that answers null is no field-level security', async () => { + await boot({ source: () => { throw new Error('security service not resolvable'); } }); + const thrown = await refusal(() => engine.update(INVOICE, { id: 'inv_closed', amount: 99 }, by(WRITER))); + expect(sentenceOf(thrown)).toBe(fill(en.record_closed_untitled, { object: 'Invoice' })); + await engine.destroy(); + await boot({ source: () => null }); + const none = await refusal(() => engine.update(INVOICE, { id: 'inv_closed', amount: 99 }, by(WRITER))); + expect(sentenceOf(none)).toBe(fill(en.record_closed, { object: 'Invoice', title: T.closed })); + }); + + it('a predicate write names no one record: the label form', async () => { + await boot(); + const err = await refusal(() => engine.update(INVOICE, { amount: 1 }, { where: { amount: 10 }, multi: true, context: WRITER } as never)); + expect(sentenceOf(err)).toBe(fill(en.record_closed_untitled, { object: 'Invoice' })); + }); + + it('a line write names the master by its label alone: update, delete, create and move', async () => { + await boot(); + const master = fill(en.record_closed_untitled, { object: 'Invoice' }); + expect(sentenceOf(await refusal(() => engine.update(LINE, { id: 'l_closed', qty: 2 }, by(WRITER))))) + .toBe(master); + expect(sentenceOf(await refusal(() => engine.delete(LINE, { where: { id: 'l_closed' }, context: WRITER } as never)))) + .toBe(master); + expect(sentenceOf(await refusal(() => engine.insert(LINE, { name: 'Extra', qty: 1, invoice: 'inv_closed' }, by(WRITER))))) + .toBe(master); + expect(sentenceOf(await refusal(() => engine.update(LINE, { id: 'l_open', invoice: 'inv_closed' }, by(WRITER))))) + .toBe(master); + }); + + it('a delete refused for what it would also remove: the record asked, its title as served, and the object in the way', async () => { + const { svc } = fieldSecurity(); + await boot({ security: svc }); + // The closed record itself would go. + const writer = await refusal(() => engine.delete(CUSTOMER, { where: { id: 'cu1' }, context: WRITER } as never)); + expect(sentenceOf(writer)).toBe(fill(en.record_closed_delete_blocked, { object: 'Customer', title: T.customer, blockingObject: 'Invoice' })); + expect(writer.reason).toBe('cascade_reaches_closed'); + // The title only for a caller served it. + const unread = await refusal(() => engine.delete(CUSTOMER, { where: { id: 'cu1' }, context: UNREAD } as never)); + expect(sentenceOf(unread)).toBe(fill(en.record_closed_delete_blocked_untitled, { object: 'Customer', blockingObject: 'Invoice' })); + // A line of the closed record would go while the record stays: the master is the object in the way. + const line = await refusal(() => engine.delete(PRODUCT, { where: { id: 'pr1' }, context: WRITER } as never)); + expect(sentenceOf(line)).toBe(fill(en.record_closed_delete_blocked, { object: 'Product', title: 'Widget', blockingObject: 'Invoice' })); + }); + + it('a title read that fails on the refusal path is reported, and the refusal stands in the label form', async () => { + await boot(); + const driver = engine.getDriverForObject(CUSTOMER) as unknown as { find: (...a: unknown[]) => Promise }; + const find = driver.find.bind(driver); + driver.find = async (object: unknown, query: any, ...rest: unknown[]) => { + // Only the refusal's own title read: the record by id, its id and title column. + if (object === CUSTOMER && Array.isArray(query?.fields) && query.fields.join() === 'id,name' && query?.limit === 1) { + throw new Error('store unavailable'); + } + return find(object, query, ...rest); + }; + const warned: Array<[string, unknown]> = []; + const logger = (engine as unknown as { logger: { warn: (m: string, meta?: unknown) => void } }).logger; + const warn = logger.warn.bind(logger); + logger.warn = (m: string, meta?: unknown) => { warned.push([m, meta]); warn(m, meta); }; + const err = await refusal(() => engine.delete(CUSTOMER, { where: { id: 'cu1' }, context: WRITER } as never)); + expect(sentenceOf(err)).toBe(fill(en.record_closed_delete_blocked_untitled, { object: 'Customer', blockingObject: 'Invoice' })); + expect(warned.filter(([m]) => m.startsWith('[closed-state] the title of')), 'the failed read is reported').toHaveLength(1); + expect((await engine.find(CUSTOMER, { where: { id: 'cu1' }, context: SYS } as never)).length, 'nothing was deleted').toBe(1); + }); + + it('a delete that names many records takes the label form', async () => { + await boot(); + const err = await refusal(() => engine.delete(CUSTOMER, { where: { id: { $in: ['cu1', 'cu3'] } }, multi: true, context: WRITER } as never)); + expect(sentenceOf(err)).toBe(fill(en.record_closed_delete_blocked_untitled, { object: 'Customer', blockingObject: 'Invoice' })); + }); + + it('the cascade\'s title form reads the ids the delete named: a delete that names its rows by a predicate takes the label form, one row matched or many', async () => { + await boot(); + const untitled = fill(en.record_closed_delete_blocked_untitled, { object: 'Customer', blockingObject: 'Invoice' }); + const byTitle = await refusal(() => engine.delete(CUSTOMER, { where: { name: T.customer }, multi: true, context: WRITER } as never)); + expect(sentenceOf(byTitle)).toBe(untitled); + const oneOfIn = await refusal(() => engine.delete(CUSTOMER, { where: { id: { $in: ['cu1'] } }, multi: true, context: WRITER } as never)); + expect(sentenceOf(oneOfIn)).toBe(untitled); + }); + + it('an object with no label is never named by its API name', async () => { + await boot(); + expect(sentenceOf(await refusal(() => engine.update(BARE, { id: 'bare_closed', name: 'x' }, by(WRITER))))) + .toBe(fill(en.record_closed_unlabeled, { title: T.bare })); + expect(sentenceOf(await refusal(() => engine.update(BARE, { name: 'x' }, { where: { name: T.bare }, multi: true, context: WRITER } as never)))) + .toBe(en.record_closed_opaque); + }); + + it('answers in the caller\'s language', async () => { + await boot(); + const zh = await refusal(() => engine.update(INVOICE, { id: 'inv_closed', amount: 99 }, by(caller('usr_writer', 'zh-CN')))); + expect(sentenceOf(zh)).toBe(fill(BUILTIN_OPERATION_MESSAGES['zh-CN'].record_closed, { object: 'Invoice', title: T.closed })); + const es = await refusal(() => engine.update(LINE, { id: 'l_closed', qty: 2 }, by(caller('usr_writer', 'es')))); + expect(sentenceOf(es)).toBe(fill(BUILTIN_OPERATION_MESSAGES['es-ES'].record_closed_untitled, { object: 'Invoice' })); + }); + + it('a line\'s restore under a live closed master names the master by its label alone', async () => { + await boot({ recycleBin: true }); + await engine.delete(LINE, { where: { id: 'l_open' }, context: WRITER } as never); + await engine.update(INVOICE, { id: 'inv_open', status: 'settled' }, by(WRITER)); + const bin = (await engine.find('sys_recycle_bin', { context: SYS } as never)) as Array>; + const entry = bin.find((r) => r.object_name === LINE && r.record_id === 'l_open'); + expect(entry).toBeDefined(); + const err = await refusal(() => engine.restore(String(entry!.id), { context: WRITER } as never)); + expect(sentenceOf(err)).toBe(fill(en.record_closed_untitled, { object: 'Invoice' })); + }); + + it('the developer\'s sentence is kept on developerMessage; a refusal that could not judge keeps it as its message', async () => { + await boot(); + const err = await refusal(() => engine.update(INVOICE, { id: 'inv_closed', amount: 99 }, by(WRITER))); + sentenceOf(err); + expect(String(err.developerMessage)).toContain(`'${INVOICE}'`); + // A line write that names its master by something that is not one id cannot be judged. + const cannot = await refusal(() => engine.insert(LINE, { name: 'x', qty: 1, invoice: { $in: ['inv_closed'] } }, by(WRITER))); + expect([cannot.code, cannot.status, cannot.reason]).toEqual(['RECORD_LOCKED', 409, 'cannot_judge']); + expect(cannot.userMessage).toBeUndefined(); + expect(String(cannot.message)).toContain(LINE); + }); +}); + +/** + * [ADR-0162 D8] The title is named only from a field that holds display text + * and that the writer's generic read returns. Each object below declares its + * title field (`nameField`) as one that is not: a field the generic read + * withholds (`internal`; a credential type), a reference field, and the field + * the object's `closedStates` names. Each answers the label form on every path + * that reads a title: the record's update, its delete, and a delete whose + * cascade reaches a closed record (the root's title). + */ +describe('[ADR-0162 D8] the title comes only from a display-text field the generic read returns', () => { + const TAG = 'dg_csr_tag'; + const SLIP = 'dg_csr_slip'; + const KINDS = [ + { key: 'internal', object: 'dg_csr_internal', label: 'Ledger', titleField: 'code', def: { type: 'text', label: 'Code', internal: true }, value: 'LEDGER-CODE-7' }, + { key: 'credential', object: 'dg_csr_credential', label: 'Vault', titleField: 'passcode', def: { type: 'password', label: 'Passcode' }, value: 'PASSCODE-VALUE-7' }, + { key: 'reference', object: 'dg_csr_reference', label: 'Tagged', titleField: 'tag', def: { type: 'lookup', label: 'Tag', reference: TAG }, value: 'tag1' }, + { key: 'state', object: 'dg_csr_state', label: 'Stage', titleField: 'status', def: undefined, value: 'settled' }, + ] as const; + + async function bootKinds(): Promise { + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); + engine = new ObjectQL(); + engine.registerDriver(driver, true); + await engine.init(); + const kindObjects = KINDS.map((k) => ({ + name: k.object, + label: k.label, + nameField: k.titleField, + fields: { + status: { type: 'select', label: 'Status', options: STATUS_OPTIONS }, + note: { type: 'text', label: 'Note' }, + ...(k.def ? { [k.titleField]: k.def } : {}), + }, + closedStates: { status: ['settled'] }, + })); + const slip = { + name: SLIP, + label: 'Slip', + fields: { + name: { type: 'text', label: 'Name' }, + status: { type: 'select', label: 'Status', options: STATUS_OPTIONS }, + ...Object.fromEntries(KINDS.map((k) => [`${k.key}_ref`, { type: 'lookup', label: k.label, reference: k.object, deleteBehavior: 'cascade' }])), + }, + closedStates: { status: ['settled'] }, + }; + engine.registerApp({ + id: 'com.objectstack.dogfood.closed-state-refusal-title-fields', + name: 'Closed-state refusal title fields', + version: '1.0.0', + type: 'plugin', + scope: 'system', + objects: [{ name: TAG, label: 'Tag', fields: { name: { type: 'text', label: 'Name' } } }, ...kindObjects, slip], + } as never); + await engine.syncSchemas(); + await installDefaultOrganization(engine); + // Seeded through the driver: the rows are data at rest, whatever a write of each field type would do. + const put = (object: string, row: Record) => + engine.getDriverForObject(object)!.create(object, { organization_id: DEFAULT_ORGANIZATION_ID, ...row }); + await put(TAG, { id: 'tag1', name: 'Priority' }); + for (const k of KINDS) { + const title = k.key === 'state' ? {} : { [k.titleField]: k.value }; + await put(k.object, { id: `${k.key}_closed`, status: 'settled', ...title }); + await put(k.object, { id: `${k.key}_root`, status: 'draft', ...(k.key === 'state' ? {} : title) }); + await put(SLIP, { id: `slip_${k.key}`, name: `Slip ${k.key}`, status: 'settled', [`${k.key}_ref`]: `${k.key}_root` }); + } + } + + const ALL_VALUES = KINDS.map((k) => k.value).filter((v) => v !== 'settled'); + + it.each(KINDS.map((k) => [k.key, k] as const))('%s title field: the label form on update, delete and a cascade-delete root', async (_key, k) => { + await bootKinds(); + const untitled = fill(en.record_closed_untitled, { object: k.label }); + const update = await refusal(() => engine.update(k.object, { id: `${k.key}_closed`, note: 'x' }, by(WRITER))); + expect(sentenceOf(update), 'update').toBe(untitled); + const del = await refusal(() => engine.delete(k.object, { where: { id: `${k.key}_closed` }, context: WRITER } as never)); + expect(sentenceOf(del), 'delete').toBe(untitled); + const cascade = await refusal(() => engine.delete(k.object, { where: { id: `${k.key}_root` }, context: WRITER } as never)); + expect(sentenceOf(cascade), 'cascade-delete root').toBe(fill(en.record_closed_delete_blocked_untitled, { object: k.label, blockingObject: 'Slip' })); + for (const err of [update, del, cascade]) { + for (const value of [...ALL_VALUES, `${k.key}_closed`, `${k.key}_root`, 'Priority']) { + expect(String(err.userMessage), value).not.toContain(value); + } + } + }); + + it('control: the same objects with a display-text title field name the title', async () => { + await bootKinds(); + // The slip's own title field is `name`, display text the generic read returns. + const err = await refusal(() => engine.update(SLIP, { id: 'slip_internal', name: 'renamed' }, by(WRITER))); + expect(sentenceOf(err)).toBe(fill(en.record_closed, { object: 'Slip', title: 'Slip internal' })); + }); +}); diff --git a/packages/qa/dogfood/test/closed-state-refusal-wire.dogfood.test.ts b/packages/qa/dogfood/test/closed-state-refusal-wire.dogfood.test.ts new file mode 100644 index 00000000000..2094e1948cb --- /dev/null +++ b/packages/qa/dogfood/test/closed-state-refusal-wire.dogfood.test.ts @@ -0,0 +1,330 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// [ADR-0162 D8, D10] The closed-state refusal on the wire, on a real boot. +// +// ## The composition +// +// `bootStack` with the real `SecurityPlugin`, `ObjectQL`, SQL driver, REST and +// auth layers. Three synthetic objects: an invoice that closes at `settled`, +// its `master_detail` line, and a customer whose delete cascades to its +// invoices. A fourth, a private note that closes at `done`, carries the +// row-access case. Every row is written through the doors by the principals +// below, so each carries its organization and owner as a real write does. +// +// Principals, by permission set: +// +// - the writer: create, read, edit and delete on every object; +// - the withheld writer: the same, with the invoice's title field +// `readable: false` (field-level security); +// - the reader: read only on the invoice (the object permission refuses an +// edit), and edit on the note it does not own (row access refuses it). +// +// ## What is asserted, by class +// +// - The person-facing member: a refused write carries `userMessage`, the +// catalog's sentence in the caller's language, and the wire's `error` reads +// the same sentence. Neither names an API name, a record id or a state value. +// - The title is the one the writer would be served (D8): the titled form for +// the writer, the label form for the withheld writer, whose read of the same +// record does not carry the title field (the control that the field is +// really withheld). +// - A line write names the master by its label alone (D8). +// - A delete refused for what it would also remove names the record asked to +// be deleted and the label of the object in the way (D6, D8). Its untitled +// form is pinned at the engine (closed-state-refusal-sentence.test.ts). +// - D10 at the security layer: a caller the object permission or the row +// access refuses gets the same answer on a closed record as on an open one, +// status and body. +// +// What the wire relays of the refusal's other members is measured and pinned +// too: the developer sentence (API names) stays off the wire, and so do the +// lock's own `reason` / `lockReason` members (D8: nothing machine-readable in +// the refusal names the producer). + +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { bootStack, type VerifyStack } from '@objectstack/verify'; +import { defineStack } from '@objectstack/spec'; +import { ObjectSchema, Field } from '@objectstack/spec/data'; +import { PermissionSetSchema } from '@objectstack/spec/security'; +import { BUILTIN_OPERATION_MESSAGES } from '@objectstack/spec/system'; +import { SecurityPlugin, securityDefaultPermissionSets } from '@objectstack/plugin-security'; +import { catalogPermissionSet } from './catalog-permission-set.js'; + +const INVOICE = 'csr_invoice'; +const LINE = 'csr_line'; +const CUSTOMER = 'csr_customer'; +const NOTE = 'csr_note'; +const SYS = { context: { isSystem: true } } as const; + +/** Synthetic titles: words no sentence of the catalog contains. */ +const T = { + closedInvoice: 'Northwind March', + openInvoice: 'Fabrikam April', + customer: 'Contoso Holdings', + otherCustomer: 'Litware Group', +} as const; + +const Invoice = ObjectSchema.create({ + name: INVOICE, + label: 'Invoice', + pluralLabel: 'Invoices', + sharingModel: 'public_read_write', + fields: { + name: Field.text({ label: 'Number', required: true }), + status: Field.select({ label: 'Status', options: [{ label: 'Draft', value: 'draft' }, { label: 'Settled', value: 'settled' }] }), + amount: Field.number({ label: 'Amount' }), + customer: Field.lookup(CUSTOMER, { label: 'Customer', deleteBehavior: 'cascade' }), + }, + closedStates: { status: ['settled'] }, +}); + +const Line = ObjectSchema.create({ + name: LINE, + label: 'Invoice line', + pluralLabel: 'Invoice lines', + sharingModel: 'public_read_write', + fields: { + name: Field.text({ label: 'Description', required: true }), + qty: Field.number({ label: 'Quantity' }), + invoice: Field.masterDetail(INVOICE, { label: 'Invoice', required: true }), + }, +}); + +const Customer = ObjectSchema.create({ + name: CUSTOMER, + label: 'Customer', + pluralLabel: 'Customers', + sharingModel: 'public_read_write', + fields: { name: Field.text({ label: 'Name', required: true }) }, +}); + +const Note = ObjectSchema.create({ + name: NOTE, + label: 'Note', + pluralLabel: 'Notes', + sharingModel: 'private', + fields: { + name: Field.text({ label: 'Subject', required: true }), + state: Field.select({ label: 'State', options: [{ label: 'Open', value: 'open' }, { label: 'Done', value: 'done' }] }), + }, + closedStates: { state: ['done'] }, +}); + +const fixtureStack = defineStack({ + manifest: { + id: 'com.dogfood.closed-state-refusal', + namespace: 'csr', + version: '0.0.0', + type: 'app', + name: 'Closed-state refusal fixture', + description: 'An invoice that closes, its lines, a customer that cascades to it, and a private note that closes.', + }, + objects: [Invoice, Line, Customer, Note], +}); + +const FULL = { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true } as const; +const writerSet = PermissionSetSchema.parse({ + name: 'csr_writer', + label: 'Closed-state writer', + objects: { [INVOICE]: FULL, [LINE]: FULL, [CUSTOMER]: FULL, [NOTE]: FULL }, +}); +const withheldSet = PermissionSetSchema.parse({ + name: 'csr_withheld', + label: 'Closed-state writer, invoice title withheld', + objects: { [INVOICE]: FULL, [LINE]: FULL, [CUSTOMER]: FULL, [NOTE]: FULL }, + fields: { + [`${INVOICE}.name`]: { readable: false, editable: false }, + }, +}); +const readerSet = PermissionSetSchema.parse({ + name: 'csr_reader', + label: 'Closed-state reader', + objects: { + [INVOICE]: { allowRead: true, allowCreate: false, allowEdit: false, allowDelete: false }, + [NOTE]: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true }, + }, +}); + +const PRINCIPALS = { writer: writerSet.name, withheld: withheldSet.name, reader: readerSet.name } as const; +type Who = keyof typeof PRINCIPALS; + +const en = BUILTIN_OPERATION_MESSAGES.en; +const fill = (template: string, params: Record) => + template.replace(/\{\{(\w+)\}\}/g, (m, k: string) => params[k] ?? m); + +interface Answer { + status: number; + body: Record; +} + +describe('[ADR-0162 D8, D10] the closed-state refusal on the wire', () => { + let stack: VerifyStack; + let ql: any; + const token: Record = {} as never; + const id: Record = {}; + /** Every value a person-facing string must not carry: API names, ids, state values. */ + const forbidden = (): string[] => [INVOICE, LINE, CUSTOMER, NOTE, 'csr_', 'settled', 'closedStates', ...Object.values(id)]; + + const call = async (who: Who | 'admin', method: string, path: string, body?: unknown, locale?: string): Promise => { + const res = await stack.api(path, { + method, + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${token[who]}`, + ...(locale ? { 'Accept-Language': locale } : {}), + }, + ...(body !== undefined ? { body: JSON.stringify(body) } : {}), + }); + const text = await res.text(); + return { status: res.status, body: text ? JSON.parse(text) : {} }; + }; + const created = async (who: Who | 'admin', object: string, body: Record): Promise => { + const a = await call(who, 'POST', `/data/${object}`, body); + expect(a.status, JSON.stringify(a.body)).toBe(201); + return String(a.body?.id ?? a.body?.record?.id ?? ''); + }; + /** The two person-facing strings of a refusal, and what neither may carry. */ + const personFacing = (a: Answer): string => { + expect(a.status, JSON.stringify(a.body)).toBe(409); + expect(a.body.code).toBe('RECORD_LOCKED'); + expect(typeof a.body.userMessage, JSON.stringify(a.body)).toBe('string'); + expect(a.body.error, 'the wire\'s `error` reads the same sentence').toBe(a.body.userMessage); + for (const value of forbidden()) { + expect(a.body.userMessage, `userMessage carries ${value}`).not.toContain(value); + expect(a.body.error, `error carries ${value}`).not.toContain(value); + } + return a.body.userMessage as string; + }; + + beforeAll(async () => { + stack = await bootStack(fixtureStack as unknown as Parameters[0], { + security: new SecurityPlugin({ + defaultPermissionSets: [...securityDefaultPermissionSets, writerSet, withheldSet, readerSet], + fallbackPermissionSet: readerSet.name, + }), + }); + ql = await stack.kernel.getServiceAsync('objectql'); + const idOf = async (email: string) => + String((await ql.findOne('sys_user', { where: { email }, context: { isSystem: true } }))?.id ?? ''); + token.admin = await stack.signIn(); + for (const who of Object.keys(PRINCIPALS) as Who[]) { + const email = `csr-${who}@verify.test`; + token[who] = await stack.signUp(email); + const userId = await idOf(email); + id[`${who}User`] = userId; + expect(await catalogPermissionSet(ql, PRINCIPALS[who]), PRINCIPALS[who]).toBeTruthy(); + await ql.insert('sys_user_permission_set', { user_id: userId, permission_set: PRINCIPALS[who] }, SYS); + } + + // Every row through the doors. Lines are added while their invoice is + // open; the closing write lands whole (D4) and closes it. + id.customer = await created('writer', CUSTOMER, { name: T.customer }); + id.otherCustomer = await created('writer', CUSTOMER, { name: T.otherCustomer }); + id.closedInvoice = await created('writer', INVOICE, { name: T.closedInvoice, status: 'draft', amount: 10, customer: id.customer }); + id.openInvoice = await created('writer', INVOICE, { name: T.openInvoice, status: 'draft', amount: 10, customer: id.otherCustomer }); + id.closedLine = await created('writer', LINE, { name: 'Widgets', qty: 1, invoice: id.closedInvoice }); + id.openLine = await created('writer', LINE, { name: 'Gadgets', qty: 1, invoice: id.openInvoice }); + const closing = await call('writer', 'PATCH', `/data/${INVOICE}/${id.closedInvoice}`, { status: 'settled', amount: 12 }); + expect(closing.status, JSON.stringify(closing.body)).toBe(200); + // Notes owned by the administrator: private to the reader, who may edit the object. + id.closedNote = await created('admin', NOTE, { name: 'Quarter close', state: 'open' }); + id.openNote = await created('admin', NOTE, { name: 'Quarter plan', state: 'open' }); + expect((await call('admin', 'PATCH', `/data/${NOTE}/${id.closedNote}`, { state: 'done' })).status).toBe(200); + + // The scene is real: the withheld writer is served the invoice without + // its title field, the writer with it. + const read = async (who: Who) => (await call(who, 'GET', `/data/${INVOICE}/${id.closedInvoice}`)).body; + const withheld = read('withheld'); + const writer = read('writer'); + const w = (await withheld).record ?? (await withheld); + const v = (await writer).record ?? (await writer); + expect('name' in w, 'the withheld writer is served no title field').toBe(false); + expect(v.name).toBe(T.closedInvoice); + }, 180_000); + + afterAll(async () => { + if (stack) await stack.stop(); + }); + + it('an update of a closed record names it by the title the writer is served, in userMessage and error alike', async () => { + const a = await call('writer', 'PATCH', `/data/${INVOICE}/${id.closedInvoice}`, { amount: 99 }); + expect(personFacing(a)).toBe(fill(en.record_closed, { object: 'Invoice', title: T.closedInvoice })); + }); + + it('a writer whose field permissions withhold the title field is told the label form, never the stored title', async () => { + const a = await call('withheld', 'PATCH', `/data/${INVOICE}/${id.closedInvoice}`, { amount: 99 }); + const sentence = personFacing(a); + expect(sentence).toBe(fill(en.record_closed_untitled, { object: 'Invoice' })); + expect(sentence).not.toContain(T.closedInvoice); + }); + + it('a delete of a closed record answers the same sentence family', async () => { + const a = await call('writer', 'DELETE', `/data/${INVOICE}/${id.closedInvoice}`); + expect(personFacing(a)).toBe(fill(en.record_closed, { object: 'Invoice', title: T.closedInvoice })); + }); + + it('a line write names the master by its label alone: an update in place, and a new line', async () => { + const update = await call('writer', 'PATCH', `/data/${LINE}/${id.closedLine}`, { qty: 5 }); + expect(personFacing(update)).toBe(fill(en.record_closed_untitled, { object: 'Invoice' })); + const create = await call('writer', 'POST', `/data/${LINE}`, { name: 'Extra', qty: 1, invoice: id.closedInvoice }); + expect(personFacing(create)).toBe(fill(en.record_closed_untitled, { object: 'Invoice' })); + }); + + it('a delete refused for what it would also remove names the record asked to be deleted and the object in the way', async () => { + const writer = await call('writer', 'DELETE', `/data/${CUSTOMER}/${id.customer}`); + expect(personFacing(writer)).toBe(fill(en.record_closed_delete_blocked, { object: 'Customer', title: T.customer, blockingObject: 'Invoice' })); + // The untitled form (root title not served) is pinned at the engine in + // closed-state-refusal-sentence.test.ts: on this wire a writer whose + // field permissions withhold the customer's title field is refused the + // delete of its own customer by the security layer before the engine is + // reached (reported out of scope). + // Nothing was removed. + expect((await call('writer', 'GET', `/data/${INVOICE}/${id.closedInvoice}`)).status).toBe(200); + expect((await call('writer', 'GET', `/data/${CUSTOMER}/${id.customer}`)).status).toBe(200); + }); + + it('answers in the caller\'s language', async () => { + const a = await call('writer', 'PATCH', `/data/${INVOICE}/${id.closedInvoice}`, { amount: 99 }, 'zh-CN'); + expect(personFacing(a)).toBe(fill(BUILTIN_OPERATION_MESSAGES['zh-CN'].record_closed, { object: 'Invoice', title: T.closedInvoice })); + }); + + it('relays neither the developer sentence nor the lock\'s own members', async () => { + const a = await call('writer', 'PATCH', `/data/${INVOICE}/${id.closedInvoice}`, { amount: 99 }); + personFacing(a); + const wire = JSON.stringify(a.body); + expect(wire).not.toContain('closedStates'); + expect(a.body).not.toHaveProperty('developerMessage'); + expect(a.body).not.toHaveProperty('reason'); + expect(a.body).not.toHaveProperty('lockReason'); + expect(a.body).not.toHaveProperty('blockingObject'); + }); + + it('D10: a caller the object permission refuses gets the same answer on a closed record as on an open one', async () => { + const closed = await call('reader', 'PATCH', `/data/${INVOICE}/${id.closedInvoice}`, { amount: 1 }); + const open = await call('reader', 'PATCH', `/data/${INVOICE}/${id.openInvoice}`, { amount: 1 }); + expect(closed.status).toBe(403); + expect(closed.body.code).toBe('PERMISSION_DENIED'); + expect(closed).toEqual(open); + const closedDelete = await call('reader', 'DELETE', `/data/${INVOICE}/${id.closedInvoice}`); + const openDelete = await call('reader', 'DELETE', `/data/${INVOICE}/${id.openInvoice}`); + expect(closedDelete.status).toBe(403); + expect(closedDelete).toEqual(openDelete); + }); + + it('D10: a caller the row access refuses gets the same answer on a closed record as on an open one', async () => { + const closed = await call('reader', 'PATCH', `/data/${NOTE}/${id.closedNote}`, { name: 'x' }); + const open = await call('reader', 'PATCH', `/data/${NOTE}/${id.openNote}`, { name: 'x' }); + expect(closed.status).not.toBe(409); + expect(closed.body.code).not.toBe('RECORD_LOCKED'); + // The two answers differ only by the id the caller addressed, where the body echoes it. + expect(JSON.stringify(closed).split(id.closedNote).join('ID')).toBe(JSON.stringify(open).split(id.openNote).join('ID')); + const closedDelete = await call('reader', 'DELETE', `/data/${NOTE}/${id.closedNote}`); + const openDelete = await call('reader', 'DELETE', `/data/${NOTE}/${id.openNote}`); + expect(closedDelete.status).not.toBe(409); + expect(JSON.stringify(closedDelete).split(id.closedNote).join('ID')).toBe(JSON.stringify(openDelete).split(id.openNote).join('ID')); + // CONTROL: the owner is told the note is closed. + const owner = await call('admin', 'PATCH', `/data/${NOTE}/${id.closedNote}`, { name: 'x' }); + expect(owner.status).toBe(409); + expect(owner.body.code).toBe('RECORD_LOCKED'); + }); +}); diff --git a/packages/qa/dogfood/test/closed-state-system-writes.test.ts b/packages/qa/dogfood/test/closed-state-system-writes.test.ts new file mode 100644 index 00000000000..947cafc0589 --- /dev/null +++ b/packages/qa/dogfood/test/closed-state-system-writes.test.ts @@ -0,0 +1,195 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 D5, D7] Two writes the platform makes on its own, measured against + * a record in a closed state: the approval status mirror and the assignment + * rules. Each was listed as a system write with no test of it. + * + * - The approval status mirror writes `pending` when an approval opens on a + * record and `approved` when it is decided. On a record already closed by + * another field, both writes land: they are system writes, which the lock + * does not bind (D5). The caller's own write of the same record, between + * and after, is refused `409 RECORD_LOCKED` with the closed-state sentence. + * - The assignment rules write no stored record at all: the engine evaluates + * them on a row it is inserting, before the write, and an update never + * evaluates a rule (`assignment-rules.ts`). A row inserted already in its + * closed state by a caller is routed to its owner and lands; nothing about + * the rule writes the record afterwards, and the caller's later write of + * it is refused. + * + * Real kernel, real ObjectQL engine with the closed-state lock, real + * automation engine and approval node, driver-sql on better-sqlite3 + * `:memory:`. The approval's record lock (`lockRecord`) is off, so the one + * lock a caller meets is the closed-state one. + */ + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { ObjectKernel } from '@objectstack/core'; +import { ObjectQLPlugin, type ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { AutomationServicePlugin, type AutomationEngine } from '@objectstack/service-automation'; +import { + ApprovalService, + registerApprovalNode, + SysApprovalRequest, + SysApprovalAction, + SysApprovalApprover, + SysApprovalDelegation, +} from '@objectstack/plugin-approvals'; +import { BUILTIN_OPERATION_MESSAGES } from '@objectstack/spec/system'; + +const ORG = 'org_default'; +const SYS = { isSystem: true } as const; +const asPerson = (userId: string) => ({ userId, tenantId: ORG, positions: [], permissions: [] }) as any; + +const text = (name: string) => ({ name, type: 'text' as const }); +const PLATFORM_GLOBAL = { enabled: false }; +const platformObjects = [ + { owner: '@objectstack/plugin-auth', def: { name: 'sys_user', label: 'User', tenancy: PLATFORM_GLOBAL, fields: { id: { ...text('id'), primaryKey: true }, email: text('email'), banned: { name: 'banned', type: 'boolean' as const } } } }, + { owner: '@objectstack/plugin-auth', def: { name: 'sys_member', label: 'Member', tenancy: PLATFORM_GLOBAL, fields: { id: { ...text('id'), primaryKey: true }, user_id: text('user_id'), organization_id: text('organization_id'), role: text('role') } } }, +] as const; + +const INVOICE = 'dg_csw_invoice'; +const TICKET = 'dg_csw_ticket'; + +/** Closed by its own `status`; the approval mirrors onto another field. */ +const invoice = { + name: INVOICE, + label: 'Invoice', + fields: { + name: text('name'), + note: text('note'), + status: { name: 'status', type: 'select' as const, options: [{ label: 'Draft', value: 'draft' }, { label: 'Settled', value: 'settled' }] }, + approval_status: { name: 'approval_status', type: 'select' as const, options: ['draft', 'pending', 'approved', 'rejected'].map((value) => ({ label: value, value })) }, + }, + closedStates: { status: ['settled'] }, +}; +const ticket = { + name: TICKET, + label: 'Ticket', + fields: { + name: text('name'), + note: text('note'), + status: { name: 'status', type: 'select' as const, options: [{ label: 'Open', value: 'open' }, { label: 'Done', value: 'done' }] }, + }, + closedStates: { status: ['done'] }, +}; + +const review = { + name: 'csw_review', label: 'Review', type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'review', type: 'approval', label: 'Review', config: { approvers: [{ type: 'user', value: 'approver' }], lockRecord: false, approvalStatusField: 'approval_status' } }, + { 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' }, + ], +}; + +const en = BUILTIN_OPERATION_MESSAGES.en; +const fill = (template: string, params: Record) => + template.replace(/\{\{(\w+)\}\}/g, (m, k: string) => params[k] ?? m); + +describe('[ADR-0162 D5, D7] the platform\'s own writes on a record in a closed state', () => { + let kernel: ObjectKernel; + let ql: ObjectQL; + let automation: AutomationEngine; + let svc: ApprovalService; + + afterEach(async () => { + try { await kernel?.shutdown(); } catch { /* noop */ } + }); + + beforeEach(async () => { + kernel = new ObjectKernel({ logger: { level: 'silent' } } as any); + await kernel.use(new ObjectQLPlugin()); + await kernel.use(new AutomationServicePlugin()); + await kernel.bootstrap(); + ql = kernel.getService('objectql'); + automation = kernel.getService('automation'); + + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); + await driver.connect(); + ql.registerDriver(driver, true); + for (const def of [invoice, ticket, SysApprovalRequest, SysApprovalAction, SysApprovalApprover, SysApprovalDelegation]) { + ql.registry.registerObject(def as any, 'closed-state-system-writes', 'closed-state-system-writes'); + } + for (const o of platformObjects) ql.registry.registerObject(o.def as any, o.owner); + ql.registry.registerObject( + { name: 'sys_organization', label: 'Organization', managedBy: 'better-auth', fields: { name: text('name'), slug: text('slug') } } as any, + '@objectstack/plugin-auth', + ); + (ql as any).registerApp({ + id: 'com.objectstack.dogfood.closed-state-system-writes', name: 'closed_state_system_writes', queues: [], + assignmentRules: [{ name: 'ticket_owner', object: TICKET, active: true, entries: [{ name: 'all', assignTo: { type: 'user', value: 'lead' } }] }], + }); + await ql.syncSchemas(); + await ql.insert('sys_organization', { id: ORG, name: 'Default Organization', slug: 'default' }, { context: SYS }); + for (const id of ['owner', 'approver', 'lead']) { + await ql.insert('sys_user', { id, email: `${id}@example.test`, banned: false }, { context: SYS }); + await ql.insert('sys_member', { id: `mem_${id}`, user_id: id, organization_id: ORG, role: 'member' }, { context: SYS }); + } + + const quiet = { debug: () => {}, info: () => {}, warn: () => {}, error: () => {} }; + svc = new ApprovalService({ engine: ql, logger: quiet as any, messaging: { emit: async () => {} } as any }); + // The host runs the plugin's sweeps, as one with a `job` service does: an + // approval on an object that declares `closedStates` does not open on a + // host that runs none (ADR-0162 item 7), which is not what this file pins. + svc.noteSweepClockScheduled(); + svc.attachAutomation(automation as any); + registerApprovalNode(automation as any, svc, quiet as any); + automation.registerFlow(review.name, review as any); + }); + + const read = async (object: string, id: string) => (await ql.find(object, { where: { id }, context: SYS }))[0] as any; + const pendingRequest = async (id: string) => + (await ql.find('sys_approval_request', { where: { record_id: id, status: 'pending' }, context: SYS }) as any[]).map((r) => String(r.id)); + /** + * The caller's own write, refused by the closed-state lock with its sentence. + * This kernel registers no `security` service, so there is no field-level + * security and the sentence names the record's title. + */ + async function expectCallerRefused(object: string, id: string, label: string, title: string): Promise { + let caught: any; + try { + await ql.update(object, { id, note: 'edited by hand' }, { context: asPerson('owner') }); + } catch (err) { + caught = err; + } + expect(caught, 'the caller\'s write is refused').toBeDefined(); + expect(caught.code).toBe('RECORD_LOCKED'); + expect(caught.status ?? caught.statusCode).toBe(409); + expect(caught.userMessage).toBe(fill(en.record_closed, { object: label, title })); + expect((await read(object, id)).note ?? null, 'nothing of the refused write landed').toBeNull(); + } + + it('the approval status mirror\'s `pending` and `approved` land on a record closed by another field; the caller\'s write is refused between and after', async () => { + await ql.insert(INVOICE, { id: 'inv1', name: 'Northwind March', status: 'settled', approval_status: 'draft', organization_id: ORG }, { context: { ...SYS, tenantId: ORG } }); + + const run = (await automation.execute(review.name, { object: INVOICE, record: await read(INVOICE, 'inv1'), userId: 'owner' } as any)) as any; + expect(run.status, JSON.stringify(run)).toBe('paused'); + const opened = await read(INVOICE, 'inv1'); + expect(opened.approval_status, 'the mirror\'s `pending` landed on the closed record').toBe('pending'); + expect(opened.status).toBe('settled'); + await expectCallerRefused(INVOICE, 'inv1', 'Invoice', 'Northwind March'); + + const [request] = await pendingRequest('inv1'); + expect(request).toBeTruthy(); + await svc.decide(request, { decision: 'approve', actorId: 'approver' } as any, asPerson('approver')); + const decided = await read(INVOICE, 'inv1'); + expect(decided.approval_status, 'the mirror\'s `approved` landed on the closed record').toBe('approved'); + expect(decided.status).toBe('settled'); + await expectCallerRefused(INVOICE, 'inv1', 'Invoice', 'Northwind March'); + }); + + it('an assignment rule routes a row a caller inserts already closed, and the insert lands; the rule never writes it again, and the caller\'s write is refused', async () => { + const row = (await ql.insert(TICKET, { id: 't1', name: 'Quarter close', status: 'done', organization_id: ORG }, { context: asPerson('owner') })) as any; + expect(row.owner_id, 'the rule routed the row it was inserting').toBe('lead'); + expect((await read(TICKET, 't1')).owner_id).toBe('lead'); + await expectCallerRefused(TICKET, 't1', 'Ticket', 'Quarter close'); + expect((await read(TICKET, 't1')).owner_id, 'an update evaluates no rule').toBe('lead'); + }); +}); diff --git a/packages/services/service-storage/src/upload-link-copy.test.ts b/packages/services/service-storage/src/upload-link-copy.test.ts index 685e23314c3..ba2c0d1af78 100644 --- a/packages/services/service-storage/src/upload-link-copy.test.ts +++ b/packages/services/service-storage/src/upload-link-copy.test.ts @@ -127,6 +127,26 @@ describe('#32712 — the upload-link page\'s sentences', () => { .toBe('上传被拒绝:Amount must be positive.'); }); + /** + * [ADR-0162 D8] The page carries a closed-state sentence beside the approval + * one, in every language it carries. A closed-state refusal reaches the page + * with the engine's declared sentence, which the page shows; the code-only + * lookup below answers a `RECORD_LOCKED` that declares none. Choosing + * `recordClosed` by the lock read's reason stays with Execution item 2: this + * pins the table, not a selection. + */ + it('carries a closed-state sentence in every language, not the approval one; a RECORD_LOCKED with no declared sentence reads the approval one', () => { + for (const tag of PLATFORM_LOCALE_TAGS) { + const copy = UPLOAD_LINK_COPY[copyLocaleOf(tag)!]; + expect(copy.recordClosed.trim(), tag).not.toBe(''); + expect(copy.recordClosed, tag).not.toBe(copy.recordLocked); + expect(uploadLinkRefusalText(copy, 409, 'RECORD_LOCKED', 'producer text'), tag).toBe(copy.recordLocked); + } + expect(Object.keys(UPLOAD_LINK_COPY).sort()).toEqual( + [...new Set(PLATFORM_LOCALE_TAGS.map((tag) => copyLocaleOf(tag)!))].sort(), + ); + }); + it('writes the expiry in the page\'s language, in UTC and saying so', () => { const at = '2026-11-12T21:54:00.000Z'; expect(formatUploadLinkExpiry(UPLOAD_LINK_COPY['zh-CN'], at)).toBe('2026年11月12日 UTC 21:54'); diff --git a/packages/services/service-storage/src/upload-link-copy.ts b/packages/services/service-storage/src/upload-link-copy.ts index 06f2394b79a..617a70d82e5 100644 --- a/packages/services/service-storage/src/upload-link-copy.ts +++ b/packages/services/service-storage/src/upload-link-copy.ts @@ -47,8 +47,21 @@ export interface UploadLinkRefusalCopy { notAllowed: string; /** `FIELD_NOT_ACCESSIBLE`: the field is read-only on the record (statically or in its current state). */ fieldReadOnly: string; - /** `RECORD_LOCKED`: a pending approval locks the record. */ + /** + * `RECORD_LOCKED` that carries no declared sentence of its own. A refusal + * that declares one (`userMessage`) is shown with that sentence instead + * (`storage-routes.ts` `relayUploadLinkRefusal`). + */ recordLocked: string; + /** + * [ADR-0162 D8] The page's sentence for a record in one of its object's + * closed states. A closed-state refusal reaches this page with the engine's + * declared catalog sentence (`record_closed*`, worded in the link user's + * resolved context, `record-file-access.ts` `consumeUploadLinkFiles`) as + * its `userMessage`, and the page shows that sentence. Choosing this + * entry by the lock read's reason stays with ADR-0162 Execution item 2. + */ + recordClosed: string; /** `RECORD_NOT_FOUND`: the record is gone, or out of the user's reach. */ recordGone: string; /** Any `503`: the platform could not take the upload now. */ @@ -156,6 +169,7 @@ export const UPLOAD_LINK_COPY: Record = { fieldReadOnly: 'Nothing was attached: the field this link was made for is read-only on this record, so it cannot take a file.', recordLocked: 'Nothing was attached: the record is locked while an approval is in progress. Ask for a new link once the approval is decided.', + recordClosed: 'Nothing was attached: the record is closed, so no file can be added to it.', recordGone: 'Nothing was attached: the record this link was made for no longer exists, or you can no longer reach it.', unavailable: 'The upload cannot be taken right now. Try again in a few minutes.', refused: (reason) => reason, @@ -200,6 +214,7 @@ export const UPLOAD_LINK_COPY: Record = { notAllowed: '未添加任何文件:你已无法再向这条记录添加文件。', fieldReadOnly: '未添加任何文件:此链接对应的字段在这条记录上是只读的,无法接收文件。', recordLocked: '未添加任何文件:这条记录正在审批中,已被锁定。请在审批完成后索取新的链接。', + recordClosed: '未添加任何文件:这条记录已关闭,无法再添加文件。', recordGone: '未添加任何文件:此链接对应的记录已不存在,或你已无法访问它。', unavailable: '暂时无法接收上传。请几分钟后重试。', refused: (reason) => `上传被拒绝:${reason}`, @@ -244,6 +259,7 @@ export const UPLOAD_LINK_COPY: Record = { notAllowed: '未新增任何檔案:你已無法再向這筆記錄新增檔案。', fieldReadOnly: '未新增任何檔案:此連結對應的欄位在這筆記錄上是唯讀的,無法接收檔案。', recordLocked: '未新增任何檔案:這筆記錄正在簽核中,已被鎖定。請在簽核完成後索取新的連結。', + recordClosed: '未新增任何檔案:這筆記錄已關閉,無法再新增檔案。', recordGone: '未新增任何檔案:此連結對應的記錄已不存在,或你已無法存取它。', unavailable: '暫時無法接收上傳。請幾分鐘後重試。', refused: (reason) => `上傳遭拒:${reason}`, @@ -291,6 +307,7 @@ export const UPLOAD_LINK_COPY: Record = { notAllowed: '何も追加されませんでした: このレコードにはもうファイルを追加できません。', fieldReadOnly: '何も追加されませんでした: このリンクの項目はこのレコードでは読み取り専用のため、ファイルを受け付けません。', recordLocked: '何も追加されませんでした: 承認の処理中のため、レコードはロックされています。承認が完了してから新しいリンクを依頼してください。', + recordClosed: '何も追加されませんでした: レコードはクローズ済みのため、ファイルを追加できません。', recordGone: '何も追加されませんでした: このリンクのレコードは存在しないか、アクセスできなくなっています。', unavailable: '現在アップロードを受け付けられません。数分後にもう一度お試しください。', refused: (reason) => `アップロードが拒否されました: ${reason}`, @@ -338,6 +355,7 @@ export const UPLOAD_LINK_COPY: Record = { notAllowed: '아무것도 추가되지 않았습니다: 이 레코드에 더 이상 파일을 추가할 수 없습니다.', fieldReadOnly: '아무것도 추가되지 않았습니다: 이 링크의 필드는 이 레코드에서 읽기 전용이므로 파일을 받을 수 없습니다.', recordLocked: '아무것도 추가되지 않았습니다: 승인이 진행 중이어서 레코드가 잠겨 있습니다. 승인이 결정된 후 새 링크를 요청하세요.', + recordClosed: '아무것도 추가되지 않았습니다: 레코드가 종료되어 파일을 추가할 수 없습니다.', recordGone: '아무것도 추가되지 않았습니다: 이 링크의 레코드가 더 이상 없거나 더 이상 접근할 수 없습니다.', unavailable: '지금은 업로드를 받을 수 없습니다. 몇 분 후에 다시 시도하세요.', refused: (reason) => `업로드가 거부되었습니다: ${reason}`, @@ -384,6 +402,7 @@ export const UPLOAD_LINK_COPY: Record = { notAllowed: 'No se ha adjuntado nada: ya no puedes añadir archivos a este registro.', fieldReadOnly: 'No se ha adjuntado nada: el campo de este enlace es de solo lectura en este registro, así que no admite archivos.', recordLocked: 'No se ha adjuntado nada: el registro está bloqueado mientras hay una aprobación en curso. Pide un enlace nuevo cuando se haya resuelto la aprobación.', + recordClosed: 'No se ha adjuntado nada: el registro está cerrado, así que no se le puede añadir ningún archivo.', recordGone: 'No se ha adjuntado nada: el registro de este enlace ya no existe o ya no tienes acceso a él.', unavailable: 'Ahora mismo no se puede recibir la subida. Vuelve a intentarlo dentro de unos minutos.', refused: (reason) => `Se ha rechazado la subida: ${reason}`, @@ -428,6 +447,7 @@ export const UPLOAD_LINK_COPY: Record = { notAllowed: 'لم يُرفق شيء: لم يعد بإمكانك إضافة ملفات إلى هذا السجل.', fieldReadOnly: 'لم يُرفق شيء: حقل هذا الرابط للقراءة فقط في هذا السجل، لذا لا يمكنه استقبال ملف.', recordLocked: 'لم يُرفق شيء: السجل مقفل أثناء وجود موافقة قيد الإجراء. اطلب رابطًا جديدًا بعد البت في الموافقة.', + recordClosed: 'لم يُرفق شيء: السجل مغلق، لذا لا يمكن إضافة ملف إليه.', recordGone: 'لم يُرفق شيء: سجل هذا الرابط لم يعد موجودًا، أو لم يعد بإمكانك الوصول إليه.', unavailable: 'لا يمكن استقبال الرفع الآن. حاول مرة أخرى بعد بضع دقائق.', refused: (reason) => `رُفض الرفع: ${reason}`, @@ -475,6 +495,7 @@ export const UPLOAD_LINK_COPY: Record = { notAllowed: 'Rien n’a été joint : vous ne pouvez plus ajouter de fichier à cet enregistrement.', fieldReadOnly: 'Rien n’a été joint : le champ de ce lien est en lecture seule sur cet enregistrement, il ne peut donc pas recevoir de fichier.', recordLocked: 'Rien n’a été joint : l’enregistrement est verrouillé pendant qu’une approbation est en cours. Demandez un nouveau lien une fois l’approbation décidée.', + recordClosed: 'Rien n’a été joint : l’enregistrement est clôturé, on ne peut plus y ajouter de fichier.', recordGone: 'Rien n’a été joint : l’enregistrement de ce lien n’existe plus, ou vous n’y avez plus accès.', unavailable: 'L’envoi ne peut pas être reçu pour le moment. Réessayez dans quelques minutes.', refused: (reason) => `L’envoi a été refusé : ${reason}`, @@ -521,6 +542,7 @@ export const UPLOAD_LINK_COPY: Record = { notAllowed: 'Nada foi anexado: você não pode mais adicionar arquivos a este registro.', fieldReadOnly: 'Nada foi anexado: o campo deste link é somente leitura neste registro, então não pode receber um arquivo.', recordLocked: 'Nada foi anexado: o registro está bloqueado enquanto uma aprovação está em andamento. Peça um novo link quando a aprovação for decidida.', + recordClosed: 'Nada foi anexado: o registro está encerrado, então não é possível adicionar arquivos a ele.', recordGone: 'Nada foi anexado: o registro deste link não existe mais, ou você não tem mais acesso a ele.', unavailable: 'O envio não pode ser recebido agora. Tente novamente em alguns minutos.', refused: (reason) => `O envio foi recusado: ${reason}`, @@ -568,6 +590,7 @@ export const UPLOAD_LINK_COPY: Record = { notAllowed: 'Ничего не прикреплено: вы больше не можете добавлять файлы к этой записи.', fieldReadOnly: 'Ничего не прикреплено: поле этой ссылки в этой записи доступно только для чтения и не может принять файл.', recordLocked: 'Ничего не прикреплено: запись заблокирована, пока идёт согласование. Попросите новую ссылку, когда по согласованию будет принято решение.', + recordClosed: 'Ничего не прикреплено: запись закрыта, поэтому к ней нельзя добавить файл.', recordGone: 'Ничего не прикреплено: записи этой ссылки больше нет, или у вас больше нет к ней доступа.', unavailable: 'Сейчас загрузку принять невозможно. Попробуйте ещё раз через несколько минут.', refused: (reason) => `Загрузка отклонена: ${reason}`, @@ -615,6 +638,7 @@ export const UPLOAD_LINK_COPY: Record = { notAllowed: 'Es wurde nichts angehängt: Sie können diesem Datensatz keine Datei mehr hinzufügen.', fieldReadOnly: 'Es wurde nichts angehängt: Das Feld dieses Links ist in diesem Datensatz schreibgeschützt und kann keine Datei aufnehmen.', recordLocked: 'Es wurde nichts angehängt: Der Datensatz ist gesperrt, solange eine Genehmigung läuft. Fordern Sie einen neuen Link an, sobald über die Genehmigung entschieden ist.', + recordClosed: 'Es wurde nichts angehängt: Der Datensatz ist abgeschlossen, daher kann keine Datei hinzugefügt werden.', recordGone: 'Es wurde nichts angehängt: Der Datensatz dieses Links existiert nicht mehr, oder Sie haben keinen Zugriff mehr darauf.', unavailable: 'Der Upload kann gerade nicht angenommen werden. Versuchen Sie es in einigen Minuten erneut.', refused: (reason) => `Der Upload wurde abgelehnt: ${reason}`, diff --git a/packages/spec/src/system/operation-message.test.ts b/packages/spec/src/system/operation-message.test.ts index 5b66896d3a9..c66e24a8c70 100644 --- a/packages/spec/src/system/operation-message.test.ts +++ b/packages/spec/src/system/operation-message.test.ts @@ -698,6 +698,101 @@ describe('operation message catalog — the record-lock refusal', () => { }); }); +/** + * [ADR-0162 D8] The engine's closed-state lock (`409 RECORD_LOCKED`): one wire + * code with the pending lock, its own two sentence families. The emitter is + * pinned on a real engine in `packages/qa/dogfood/test/closed-state-refusal-sentence.test.ts`, + * and on the wire in `packages/qa/dogfood/test/closed-state-refusal-wire.dogfood.test.ts`. + */ +describe('operation message catalog — the closed-state refusal (ADR-0162 D8)', () => { + /** The four forms, the placeholder contract of `record_locked*`, key for key. */ + const RECORD = { + record_closed: ['{{object}}', '{{title}}'], + record_closed_untitled: ['{{object}}'], + record_closed_unlabeled: ['{{title}}'], + record_closed_opaque: [], + } as const; + /** The delete refused for what it would also remove. */ + const DELETE = { + record_closed_delete_blocked: ['{{object}}', '{{title}}', '{{blockingObject}}'], + record_closed_delete_blocked_untitled: ['{{object}}', '{{blockingObject}}'], + record_closed_delete_blocked_opaque: [], + } as const; + const ALL = { ...RECORD, ...DELETE }; + const PENDING_TWIN: Record = { + record_closed: 'record_locked', + record_closed_untitled: 'record_locked_untitled', + record_closed_unlabeled: 'record_locked_unlabeled', + record_closed_opaque: 'record_locked_opaque', + }; + + it('every locale the catalog carries defines all seven, each with exactly its own placeholders', () => { + const locales = Object.keys(BUILTIN_OPERATION_MESSAGES); + expect(locales).toEqual(expect.arrayContaining(['en', 'zh-CN', 'ja-JP', 'es-ES'])); + for (const [locale, catalog] of Object.entries(BUILTIN_OPERATION_MESSAGES)) { + for (const [key, placeholders] of Object.entries(ALL)) { + expect(catalog[key], `${locale} defines ${key}`).toBeTypeOf('string'); + expect(catalog[key].match(/\{\{\w+\}\}/g) ?? [], `${locale}.${key}`).toEqual([...placeholders]); + } + } + }); + + it('is translated: no locale but en repeats the English sentence', () => { + for (const locale of Object.keys(BUILTIN_OPERATION_MESSAGES).filter((l) => l !== 'en')) { + for (const key of Object.keys(ALL)) { + expect(BUILTIN_OPERATION_MESSAGES[locale][key], `${locale}.${key}`).not.toBe(BUILTIN_OPERATION_MESSAGES.en[key]); + } + } + }); + + it('is not the pending lock\'s sentence in any form or locale: a closed document has no approval to wait for', () => { + for (const [locale, catalog] of Object.entries(BUILTIN_OPERATION_MESSAGES)) { + for (const [key, twin] of Object.entries(PENDING_TWIN)) { + expect(catalog[key], `${locale}.${key}`).not.toBe(catalog[twin]); + } + for (const key of Object.keys(ALL)) { + // The pending lock's own word for its cause, per locale. + expect(catalog[key], `${locale}.${key}`).not.toMatch(/approval|审批|承認|aprobación/i); + } + } + }); + + it('carries no wire code, metadata key or API vocabulary in any form or locale', () => { + for (const [locale, catalog] of Object.entries(BUILTIN_OPERATION_MESSAGES)) { + for (const key of Object.keys(ALL)) { + expect(catalog[key], `${locale}.${key}`).not.toMatch(/RECORD_LOCKED|closedStates|master_detail|_id\b|cascade/i); + } + } + }); + + it('says something different from every other key, in every locale', () => { + for (const [locale, catalog] of Object.entries(BUILTIN_OPERATION_MESSAGES)) { + for (const key of Object.keys(ALL)) { + const others = Object.entries(catalog).filter(([k]) => k !== key).map(([, v]) => v); + expect(others, `${locale}.${key}`).not.toContain(catalog[key]); + } + } + }); + + it('renders the caller locale with the labels and title it is given, and falls back to en for a locale the catalog lacks', () => { + const zh = renderOperationMessage({ messageKey: 'record_closed', params: { object: '发票', title: 'INV-0042' } }, { locale: 'zh-CN' }); + expect(zh).toBe(BUILTIN_OPERATION_MESSAGES['zh-CN'].record_closed.replace('{{object}}', '发票').replace('{{title}}', 'INV-0042')); + const ja = renderOperationMessage( + { messageKey: 'record_closed_delete_blocked_untitled', params: { object: '取引先', blockingObject: '請求書' } }, + { locale: 'ja' }, + ); + expect(ja).toBe(BUILTIN_OPERATION_MESSAGES['ja-JP'].record_closed_delete_blocked_untitled.replace('{{object}}', '取引先').replace('{{blockingObject}}', '請求書')); + expect(renderOperationMessage({ messageKey: 'record_closed_opaque' }, { locale: 'de-DE' })).toBe(BUILTIN_OPERATION_MESSAGES.en.record_closed_opaque); + }); + + it('a deployment translation override wins, under the shared `errors.` address, and a title is printed as written', () => { + const translate = (k: string) => (k === operationMessageTranslationKey('record_closed') ? '{{object}}《{{title}}》已归档' : k); + const title = 'Q{{object}}'; + expect(renderOperationMessage({ messageKey: 'record_closed', params: { object: '发票', title } }, { locale: 'zh-CN', translate })) + .toBe(`发票《${title}》已归档`); + }); +}); + /** * #34699 — the user's half of three platform refusals whose `message` stays the * developer sentence: the by-id not-found, the filter-oracle guard and the diff --git a/packages/spec/src/system/operation-message.ts b/packages/spec/src/system/operation-message.ts index b7b02697e04..2974c71a7fa 100644 --- a/packages/spec/src/system/operation-message.ts +++ b/packages/spec/src/system/operation-message.ts @@ -16,7 +16,8 @@ * refusal (`approval_recall_not_submitter`; emitter conversion is #11993's * half) — and the unique-constraint refusal (`409 UNIQUE_VIOLATION` on the * wire, the engine's `DuplicateRecordError`) — and the `userMessage` of the - * master-detail write gate's `403 PERMISSION_DENIED` (ADR-0055 §3). The catalog is the seat for the rest of the family as they are + * master-detail write gate's `403 PERMISSION_DENIED` (ADR-0055 §3) — and the engine's + * closed-state lock (`409 RECORD_LOCKED`, ADR-0162 D8). The catalog is the seat for the rest of the family as they are * localized — a second mechanism for the second producer is exactly what this * module exists to prevent. * @@ -41,6 +42,8 @@ * | `master_record_edit_denied` / `master_record_read_denied` (and their `_opaque` forms) | they wrote a `controlled_by_parent` record (a detail) without the edit access (or, where the detail asks it, the read access) its master record requires | ask the master record's owner, or an administrator | * | `field_edit_denied` / `field_edit_denied_opaque` | they changed a field their permissions do not let them edit | undo that change, or ask an administrator | * | `record_locked` (and its `_untitled`, `_unlabeled` and `_opaque` forms) | they tried to change a record an approval in progress holds | wait until that approval is complete | + * | `record_closed` (and its `_untitled`, `_unlabeled` and `_opaque` forms) | they tried to change or delete a record, or a line of a record, that is in one of its object's closed states | nothing: the document is final; a closed state is where it ends up | + * | `record_closed_delete_blocked` (and its `_untitled` and `_opaque` forms) | they tried to delete a record whose deletion would also remove a closed record, or a line of one | nothing: deleting it would change a final document | * * `record_write_denied` (commit aa5994e17) is NOT `record_access_denied` restated: the * sharing middleware's by-id write gate fires on a row the READ path already @@ -292,6 +295,50 @@ export function operationMessageTranslationKey(messageKey: string): string { * Their English is byte-identical to the fixed sentence the hook answered * before it was localized. * + * [ADR-0162 D8] The four `record_closed*` keys are the end user's sentence of + * the engine's closed-state lock (`409 RECORD_LOCKED`, `@objectstack/objectql` + * `closed-state-lock.ts`): a record in one of its object's declared closed + * states, or a line of one, refuses a caller's change or delete. Same code as + * the pending lock, its own sentences, because "wait until that approval is + * complete" is false for a closed document. The same four forms and the same + * placeholder contract as `record_locked*`: + * + * - `record_closed` takes `{{object}}` (the object's LABEL in the caller's + * locale) and `{{title}}` (the record's title as the WRITER would be + * served it under its own field permissions, never the title as stored); + * - `record_closed_untitled` takes `{{object}}` alone: for a record whose + * title the writer may not be served (its title field is one the + * writer's generic read does not return, or the security service is + * registered but cannot be resolved), for a title field whose value is + * not display text (a reference, or a field the object's `closedStates` + * names), for a write that matched rows by a predicate, and for a line + * write, where `{{object}}` is the MASTER's label (the engine reads the + * master's state to judge and reads nothing of it to word the refusal); + * - `record_closed_unlabeled` takes `{{title}}` alone, for an object with no + * label; + * - `record_closed_opaque` names nothing. + * + * The three `record_closed_delete_blocked*` keys are the same lock's + * sentence for a delete refused for what it would also remove: a closed + * record, or a line of one, in the set the delete was planned to remove. It + * names the record the caller asked to delete and the label of the object + * whose closed record stands in the way, and nothing else: no title, id or + * count of the closed records. + * + * - `record_closed_delete_blocked` takes `{{object}}` and `{{title}}` (the + * record asked to be deleted, its title as the caller is served it) and + * `{{blockingObject}}` (the label of the object in the way); + * - `record_closed_delete_blocked_untitled` drops `{{title}}`: where the + * caller is served no title for that record (its title field is one the + * caller's generic read does not return or is not display text, or the + * security service is registered but cannot be resolved), and where the + * delete names many records or names its rows by a predicate; + * - `record_closed_delete_blocked_opaque` names nothing, where either + * object has no label. + * + * None of the seven carries a record id, an API name or the state's value: a + * reader who may see the state reads it off the record. + * * Three keys are the `userMessage` of refusals whose `message` stays the * developer sentence (code, status and `message` unchanged). None takes a * placeholder, re-derived per site: @@ -472,6 +519,20 @@ export const BUILTIN_OPERATION_MESSAGES: Record> 'This {{object}} is locked while an approval is in progress, and cannot be edited until that approval is complete', record_locked_opaque: 'This record is locked while an approval is in progress, and cannot be edited until that approval is complete', + record_closed: + "{{object}} '{{title}}' is closed, so it and its lines can no longer be changed or deleted", + record_closed_unlabeled: + "'{{title}}' is closed, so it and its lines can no longer be changed or deleted", + record_closed_untitled: + 'This {{object}} is closed, so it and its lines can no longer be changed or deleted', + record_closed_opaque: + 'This record is closed, so it and its lines can no longer be changed or deleted', + record_closed_delete_blocked: + "{{object}} '{{title}}' cannot be deleted: deleting it would also remove a closed {{blockingObject}} or one of its lines", + record_closed_delete_blocked_untitled: + 'This {{object}} cannot be deleted: deleting it would also remove a closed {{blockingObject}} or one of its lines', + record_closed_delete_blocked_opaque: + 'This record cannot be deleted: deleting it would also remove a closed record or one of its lines', record_not_found: 'This record does not exist, or you do not have access to it.', query_field_not_readable: 'This request filters, sorts or groups by a field you do not have access to. Remove that condition and try again, or contact your administrator if you need access.', @@ -606,6 +667,13 @@ export const BUILTIN_OPERATION_MESSAGES: Record> record_locked_unlabeled: '「{{title}}」正在审批中,已被锁定,审批完成前无法编辑', record_locked_untitled: '该{{object}}正在审批中,已被锁定,审批完成前无法编辑', record_locked_opaque: '该记录正在审批中,已被锁定,审批完成前无法编辑', + record_closed: '{{object}}「{{title}}」已关闭,它及其明细行都不能再修改或删除', + record_closed_unlabeled: '「{{title}}」已关闭,它及其明细行都不能再修改或删除', + record_closed_untitled: '该{{object}}已关闭,它及其明细行都不能再修改或删除', + record_closed_opaque: '该记录已关闭,它及其明细行都不能再修改或删除', + record_closed_delete_blocked: '无法删除{{object}}「{{title}}」:删除它会一并删除一条已关闭的{{blockingObject}}或其明细行', + record_closed_delete_blocked_untitled: '无法删除该{{object}}:删除它会一并删除一条已关闭的{{blockingObject}}或其明细行', + record_closed_delete_blocked_opaque: '无法删除该记录:删除它会一并删除一条已关闭的记录或其明细行', record_not_found: '该记录不存在,或您无权访问它。', query_field_not_readable: '当前请求按您无权查看的字段筛选、排序或分组,请去掉该条件后重试,或联系管理员。', delegation_scope_violation: '此更改超出了您被委派管理的范围,如需更改请联系管理员。', @@ -736,6 +804,13 @@ export const BUILTIN_OPERATION_MESSAGES: Record> record_locked_unlabeled: '「{{title}}」は承認処理中のためロックされています。承認が完了するまで編集できません', record_locked_untitled: 'この{{object}}は承認処理中のためロックされています。承認が完了するまで編集できません', record_locked_opaque: 'このレコードは承認処理中のためロックされています。承認が完了するまで編集できません', + record_closed: '{{object}}「{{title}}」はクローズ済みのため、明細を含めて変更も削除もできません', + record_closed_unlabeled: '「{{title}}」はクローズ済みのため、明細を含めて変更も削除もできません', + record_closed_untitled: 'この{{object}}はクローズ済みのため、明細を含めて変更も削除もできません', + record_closed_opaque: 'このレコードはクローズ済みのため、明細を含めて変更も削除もできません', + record_closed_delete_blocked: '{{object}}「{{title}}」は削除できません。削除すると、クローズ済みの{{blockingObject}}またはその明細も削除されます', + record_closed_delete_blocked_untitled: 'この{{object}}は削除できません。削除すると、クローズ済みの{{blockingObject}}またはその明細も削除されます', + record_closed_delete_blocked_opaque: 'このレコードは削除できません。削除すると、クローズ済みのレコードまたはその明細も削除されます', record_not_found: 'このレコードは存在しないか、アクセスする権限がありません。', query_field_not_readable: 'この要求は、閲覧権限のない項目で絞り込み、並べ替え、またはグループ化しています。その条件を削除して再試行するか、アクセスが必要な場合は管理者にお問い合わせください。', @@ -889,6 +964,20 @@ export const BUILTIN_OPERATION_MESSAGES: Record> 'Este registro de {{object}} está bloqueado mientras hay una aprobación en curso y no se puede editar hasta que esa aprobación finalice', record_locked_opaque: 'Este registro está bloqueado mientras hay una aprobación en curso y no se puede editar hasta que esa aprobación finalice', + record_closed: + 'El registro de {{object}} «{{title}}» está cerrado, por lo que ni él ni sus líneas se pueden modificar ni eliminar', + record_closed_unlabeled: + 'El registro «{{title}}» está cerrado, por lo que ni él ni sus líneas se pueden modificar ni eliminar', + record_closed_untitled: + 'Este registro de {{object}} está cerrado, por lo que ni él ni sus líneas se pueden modificar ni eliminar', + record_closed_opaque: + 'Este registro está cerrado, por lo que ni él ni sus líneas se pueden modificar ni eliminar', + record_closed_delete_blocked: + 'No se puede eliminar el registro de {{object}} «{{title}}»: al eliminarlo también se eliminaría un registro cerrado de {{blockingObject}} o una de sus líneas', + record_closed_delete_blocked_untitled: + 'No se puede eliminar este registro de {{object}}: al eliminarlo también se eliminaría un registro cerrado de {{blockingObject}} o una de sus líneas', + record_closed_delete_blocked_opaque: + 'No se puede eliminar este registro: al eliminarlo también se eliminaría un registro cerrado o una de sus líneas', record_not_found: 'Este registro no existe o no tiene acceso a él.', query_field_not_readable: 'Esta solicitud filtra, ordena o agrupa por un campo al que no tiene acceso. Quite esa condición e inténtelo de nuevo, o póngase en contacto con su administrador si necesita acceso.',