From 11ee69ac1a62eea5c33ef67a1d2ebe2bd9ece9c5 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 23:55:32 +0000 Subject: [PATCH 01/14] 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/14] 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/14] 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/14] 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/14] 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/14] 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/14] 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/14] 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/14] 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/14] 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/14] 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/14] 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/14] 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/14] 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);