From 32d900eb9ad516035967d1c6a744780209fd2db4 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 05:13:17 +0000 Subject: [PATCH 01/10] feat(spec,service-storage): the closed-state refusal's sentences, in every locale (ADR-0162 D8) Two sentence families in the Operation Message Catalog for the engine's closed-state lock (record_closed, four forms; record_closed_delete_blocked, three forms) in en, zh-CN, ja-JP and es-ES, and a closed-state sentence on the upload-link page in its eleven languages. Selection on the upload-link door stays with the one lock read. Claude-Session: https://claude.ai/code/session_01FEkQ5nGQtUA88SthJbYyRw Co-Authored-By: Claude --- .../src/upload-link-copy.test.ts | 18 ++++ .../service-storage/src/upload-link-copy.ts | 19 ++++ .../spec/src/system/operation-message.test.ts | 95 +++++++++++++++++++ packages/spec/src/system/operation-message.ts | 86 ++++++++++++++++- 4 files changed, 217 insertions(+), 1 deletion(-) diff --git a/packages/services/service-storage/src/upload-link-copy.test.ts b/packages/services/service-storage/src/upload-link-copy.test.ts index 685e23314c3..7d48e2ab7f3 100644 --- a/packages/services/service-storage/src/upload-link-copy.test.ts +++ b/packages/services/service-storage/src/upload-link-copy.test.ts @@ -127,6 +127,24 @@ describe('#32712 — the upload-link page\'s sentences', () => { .toBe('上传被拒绝:Amount must be positive.'); }); + /** + * [ADR-0162 D8] The door gains a closed-state sentence beside the approval + * one, in every language it carries. Choosing between the two by the lock + * read's reason lands with the one lock read (Execution item 2), so the code + * still answers the approval sentence: this pins the table, not a selection. + */ + it('carries a closed-state sentence in every language, not the approval one, and RECORD_LOCKED still reads the approval one', () => { + for (const tag of PLATFORM_LOCALE_TAGS) { + const copy = UPLOAD_LINK_COPY[copyLocaleOf(tag)!]; + expect(copy.recordClosed.trim(), tag).not.toBe(''); + expect(copy.recordClosed, tag).not.toBe(copy.recordLocked); + expect(uploadLinkRefusalText(copy, 409, 'RECORD_LOCKED', 'producer text'), tag).toBe(copy.recordLocked); + } + expect(Object.keys(UPLOAD_LINK_COPY).sort()).toEqual( + [...new Set(PLATFORM_LOCALE_TAGS.map((tag) => copyLocaleOf(tag)!))].sort(), + ); + }); + it('writes the expiry in the page\'s language, in UTC and saying so', () => { const at = '2026-11-12T21:54:00.000Z'; expect(formatUploadLinkExpiry(UPLOAD_LINK_COPY['zh-CN'], at)).toBe('2026年11月12日 UTC 21:54'); diff --git a/packages/services/service-storage/src/upload-link-copy.ts b/packages/services/service-storage/src/upload-link-copy.ts index 06f2394b79a..63f7a62c4fc 100644 --- a/packages/services/service-storage/src/upload-link-copy.ts +++ b/packages/services/service-storage/src/upload-link-copy.ts @@ -49,6 +49,14 @@ export interface UploadLinkRefusalCopy { fieldReadOnly: string; /** `RECORD_LOCKED`: a pending approval locks the record. */ recordLocked: string; + /** + * [ADR-0162 D8] `RECORD_LOCKED`: the record is in one of its object's closed + * states. The same code as {@link recordLocked}; the page chooses between + * the two by the lock read's reason, which lands with the one lock read + * (ADR-0162 D9, Execution item 2). Until then the code answers + * {@link recordLocked}. + */ + recordClosed: string; /** `RECORD_NOT_FOUND`: the record is gone, or out of the user's reach. */ recordGone: string; /** Any `503`: the platform could not take the upload now. */ @@ -156,6 +164,7 @@ export const UPLOAD_LINK_COPY: Record = { fieldReadOnly: 'Nothing was attached: the field this link was made for is read-only on this record, so it cannot take a file.', recordLocked: 'Nothing was attached: the record is locked while an approval is in progress. Ask for a new link once the approval is decided.', + recordClosed: 'Nothing was attached: the record is closed, so no file can be added to it.', recordGone: 'Nothing was attached: the record this link was made for no longer exists, or you can no longer reach it.', unavailable: 'The upload cannot be taken right now. Try again in a few minutes.', refused: (reason) => reason, @@ -200,6 +209,7 @@ export const UPLOAD_LINK_COPY: Record = { notAllowed: '未添加任何文件:你已无法再向这条记录添加文件。', fieldReadOnly: '未添加任何文件:此链接对应的字段在这条记录上是只读的,无法接收文件。', recordLocked: '未添加任何文件:这条记录正在审批中,已被锁定。请在审批完成后索取新的链接。', + recordClosed: '未添加任何文件:这条记录已关闭,无法再添加文件。', recordGone: '未添加任何文件:此链接对应的记录已不存在,或你已无法访问它。', unavailable: '暂时无法接收上传。请几分钟后重试。', refused: (reason) => `上传被拒绝:${reason}`, @@ -244,6 +254,7 @@ export const UPLOAD_LINK_COPY: Record = { notAllowed: '未新增任何檔案:你已無法再向這筆記錄新增檔案。', fieldReadOnly: '未新增任何檔案:此連結對應的欄位在這筆記錄上是唯讀的,無法接收檔案。', recordLocked: '未新增任何檔案:這筆記錄正在簽核中,已被鎖定。請在簽核完成後索取新的連結。', + recordClosed: '未新增任何檔案:這筆記錄已關閉,無法再新增檔案。', recordGone: '未新增任何檔案:此連結對應的記錄已不存在,或你已無法存取它。', unavailable: '暫時無法接收上傳。請幾分鐘後重試。', refused: (reason) => `上傳遭拒:${reason}`, @@ -291,6 +302,7 @@ export const UPLOAD_LINK_COPY: Record = { notAllowed: '何も追加されませんでした: このレコードにはもうファイルを追加できません。', fieldReadOnly: '何も追加されませんでした: このリンクの項目はこのレコードでは読み取り専用のため、ファイルを受け付けません。', recordLocked: '何も追加されませんでした: 承認の処理中のため、レコードはロックされています。承認が完了してから新しいリンクを依頼してください。', + recordClosed: '何も追加されませんでした: レコードはクローズ済みのため、ファイルを追加できません。', recordGone: '何も追加されませんでした: このリンクのレコードは存在しないか、アクセスできなくなっています。', unavailable: '現在アップロードを受け付けられません。数分後にもう一度お試しください。', refused: (reason) => `アップロードが拒否されました: ${reason}`, @@ -338,6 +350,7 @@ export const UPLOAD_LINK_COPY: Record = { notAllowed: '아무것도 추가되지 않았습니다: 이 레코드에 더 이상 파일을 추가할 수 없습니다.', fieldReadOnly: '아무것도 추가되지 않았습니다: 이 링크의 필드는 이 레코드에서 읽기 전용이므로 파일을 받을 수 없습니다.', recordLocked: '아무것도 추가되지 않았습니다: 승인이 진행 중이어서 레코드가 잠겨 있습니다. 승인이 결정된 후 새 링크를 요청하세요.', + recordClosed: '아무것도 추가되지 않았습니다: 레코드가 종료되어 파일을 추가할 수 없습니다.', recordGone: '아무것도 추가되지 않았습니다: 이 링크의 레코드가 더 이상 없거나 더 이상 접근할 수 없습니다.', unavailable: '지금은 업로드를 받을 수 없습니다. 몇 분 후에 다시 시도하세요.', refused: (reason) => `업로드가 거부되었습니다: ${reason}`, @@ -384,6 +397,7 @@ export const UPLOAD_LINK_COPY: Record = { notAllowed: 'No se ha adjuntado nada: ya no puedes añadir archivos a este registro.', fieldReadOnly: 'No se ha adjuntado nada: el campo de este enlace es de solo lectura en este registro, así que no admite archivos.', recordLocked: 'No se ha adjuntado nada: el registro está bloqueado mientras hay una aprobación en curso. Pide un enlace nuevo cuando se haya resuelto la aprobación.', + recordClosed: 'No se ha adjuntado nada: el registro está cerrado, así que no se le puede añadir ningún archivo.', recordGone: 'No se ha adjuntado nada: el registro de este enlace ya no existe o ya no tienes acceso a él.', unavailable: 'Ahora mismo no se puede recibir la subida. Vuelve a intentarlo dentro de unos minutos.', refused: (reason) => `Se ha rechazado la subida: ${reason}`, @@ -428,6 +442,7 @@ export const UPLOAD_LINK_COPY: Record = { notAllowed: 'لم يُرفق شيء: لم يعد بإمكانك إضافة ملفات إلى هذا السجل.', fieldReadOnly: 'لم يُرفق شيء: حقل هذا الرابط للقراءة فقط في هذا السجل، لذا لا يمكنه استقبال ملف.', recordLocked: 'لم يُرفق شيء: السجل مقفل أثناء وجود موافقة قيد الإجراء. اطلب رابطًا جديدًا بعد البت في الموافقة.', + recordClosed: 'لم يُرفق شيء: السجل مغلق، لذا لا يمكن إضافة ملف إليه.', recordGone: 'لم يُرفق شيء: سجل هذا الرابط لم يعد موجودًا، أو لم يعد بإمكانك الوصول إليه.', unavailable: 'لا يمكن استقبال الرفع الآن. حاول مرة أخرى بعد بضع دقائق.', refused: (reason) => `رُفض الرفع: ${reason}`, @@ -475,6 +490,7 @@ export const UPLOAD_LINK_COPY: Record = { notAllowed: 'Rien n’a été joint : vous ne pouvez plus ajouter de fichier à cet enregistrement.', fieldReadOnly: 'Rien n’a été joint : le champ de ce lien est en lecture seule sur cet enregistrement, il ne peut donc pas recevoir de fichier.', recordLocked: 'Rien n’a été joint : l’enregistrement est verrouillé pendant qu’une approbation est en cours. Demandez un nouveau lien une fois l’approbation décidée.', + recordClosed: 'Rien n’a été joint : l’enregistrement est clôturé, on ne peut plus y ajouter de fichier.', recordGone: 'Rien n’a été joint : l’enregistrement de ce lien n’existe plus, ou vous n’y avez plus accès.', unavailable: 'L’envoi ne peut pas être reçu pour le moment. Réessayez dans quelques minutes.', refused: (reason) => `L’envoi a été refusé : ${reason}`, @@ -521,6 +537,7 @@ export const UPLOAD_LINK_COPY: Record = { notAllowed: 'Nada foi anexado: você não pode mais adicionar arquivos a este registro.', fieldReadOnly: 'Nada foi anexado: o campo deste link é somente leitura neste registro, então não pode receber um arquivo.', recordLocked: 'Nada foi anexado: o registro está bloqueado enquanto uma aprovação está em andamento. Peça um novo link quando a aprovação for decidida.', + recordClosed: 'Nada foi anexado: o registro está encerrado, então não é possível adicionar arquivos a ele.', recordGone: 'Nada foi anexado: o registro deste link não existe mais, ou você não tem mais acesso a ele.', unavailable: 'O envio não pode ser recebido agora. Tente novamente em alguns minutos.', refused: (reason) => `O envio foi recusado: ${reason}`, @@ -568,6 +585,7 @@ export const UPLOAD_LINK_COPY: Record = { notAllowed: 'Ничего не прикреплено: вы больше не можете добавлять файлы к этой записи.', fieldReadOnly: 'Ничего не прикреплено: поле этой ссылки в этой записи доступно только для чтения и не может принять файл.', recordLocked: 'Ничего не прикреплено: запись заблокирована, пока идёт согласование. Попросите новую ссылку, когда по согласованию будет принято решение.', + recordClosed: 'Ничего не прикреплено: запись закрыта, поэтому к ней нельзя добавить файл.', recordGone: 'Ничего не прикреплено: записи этой ссылки больше нет, или у вас больше нет к ней доступа.', unavailable: 'Сейчас загрузку принять невозможно. Попробуйте ещё раз через несколько минут.', refused: (reason) => `Загрузка отклонена: ${reason}`, @@ -615,6 +633,7 @@ export const UPLOAD_LINK_COPY: Record = { notAllowed: 'Es wurde nichts angehängt: Sie können diesem Datensatz keine Datei mehr hinzufügen.', fieldReadOnly: 'Es wurde nichts angehängt: Das Feld dieses Links ist in diesem Datensatz schreibgeschützt und kann keine Datei aufnehmen.', recordLocked: 'Es wurde nichts angehängt: Der Datensatz ist gesperrt, solange eine Genehmigung läuft. Fordern Sie einen neuen Link an, sobald über die Genehmigung entschieden ist.', + recordClosed: 'Es wurde nichts angehängt: Der Datensatz ist abgeschlossen, daher kann keine Datei hinzugefügt werden.', recordGone: 'Es wurde nichts angehängt: Der Datensatz dieses Links existiert nicht mehr, oder Sie haben keinen Zugriff mehr darauf.', unavailable: 'Der Upload kann gerade nicht angenommen werden. Versuchen Sie es in einigen Minuten erneut.', refused: (reason) => `Der Upload wurde abgelehnt: ${reason}`, diff --git a/packages/spec/src/system/operation-message.test.ts b/packages/spec/src/system/operation-message.test.ts index 5b66896d3a9..c66e24a8c70 100644 --- a/packages/spec/src/system/operation-message.test.ts +++ b/packages/spec/src/system/operation-message.test.ts @@ -698,6 +698,101 @@ describe('operation message catalog — the record-lock refusal', () => { }); }); +/** + * [ADR-0162 D8] The engine's closed-state lock (`409 RECORD_LOCKED`): one wire + * code with the pending lock, its own two sentence families. The emitter is + * pinned on a real engine in `packages/qa/dogfood/test/closed-state-refusal-sentence.test.ts`, + * and on the wire in `packages/qa/dogfood/test/closed-state-refusal-wire.dogfood.test.ts`. + */ +describe('operation message catalog — the closed-state refusal (ADR-0162 D8)', () => { + /** The four forms, the placeholder contract of `record_locked*`, key for key. */ + const RECORD = { + record_closed: ['{{object}}', '{{title}}'], + record_closed_untitled: ['{{object}}'], + record_closed_unlabeled: ['{{title}}'], + record_closed_opaque: [], + } as const; + /** The delete refused for what it would also remove. */ + const DELETE = { + record_closed_delete_blocked: ['{{object}}', '{{title}}', '{{blockingObject}}'], + record_closed_delete_blocked_untitled: ['{{object}}', '{{blockingObject}}'], + record_closed_delete_blocked_opaque: [], + } as const; + const ALL = { ...RECORD, ...DELETE }; + const PENDING_TWIN: Record = { + record_closed: 'record_locked', + record_closed_untitled: 'record_locked_untitled', + record_closed_unlabeled: 'record_locked_unlabeled', + record_closed_opaque: 'record_locked_opaque', + }; + + it('every locale the catalog carries defines all seven, each with exactly its own placeholders', () => { + const locales = Object.keys(BUILTIN_OPERATION_MESSAGES); + expect(locales).toEqual(expect.arrayContaining(['en', 'zh-CN', 'ja-JP', 'es-ES'])); + for (const [locale, catalog] of Object.entries(BUILTIN_OPERATION_MESSAGES)) { + for (const [key, placeholders] of Object.entries(ALL)) { + expect(catalog[key], `${locale} defines ${key}`).toBeTypeOf('string'); + expect(catalog[key].match(/\{\{\w+\}\}/g) ?? [], `${locale}.${key}`).toEqual([...placeholders]); + } + } + }); + + it('is translated: no locale but en repeats the English sentence', () => { + for (const locale of Object.keys(BUILTIN_OPERATION_MESSAGES).filter((l) => l !== 'en')) { + for (const key of Object.keys(ALL)) { + expect(BUILTIN_OPERATION_MESSAGES[locale][key], `${locale}.${key}`).not.toBe(BUILTIN_OPERATION_MESSAGES.en[key]); + } + } + }); + + it('is not the pending lock\'s sentence in any form or locale: a closed document has no approval to wait for', () => { + for (const [locale, catalog] of Object.entries(BUILTIN_OPERATION_MESSAGES)) { + for (const [key, twin] of Object.entries(PENDING_TWIN)) { + expect(catalog[key], `${locale}.${key}`).not.toBe(catalog[twin]); + } + for (const key of Object.keys(ALL)) { + // The pending lock's own word for its cause, per locale. + expect(catalog[key], `${locale}.${key}`).not.toMatch(/approval|审批|承認|aprobación/i); + } + } + }); + + it('carries no wire code, metadata key or API vocabulary in any form or locale', () => { + for (const [locale, catalog] of Object.entries(BUILTIN_OPERATION_MESSAGES)) { + for (const key of Object.keys(ALL)) { + expect(catalog[key], `${locale}.${key}`).not.toMatch(/RECORD_LOCKED|closedStates|master_detail|_id\b|cascade/i); + } + } + }); + + it('says something different from every other key, in every locale', () => { + for (const [locale, catalog] of Object.entries(BUILTIN_OPERATION_MESSAGES)) { + for (const key of Object.keys(ALL)) { + const others = Object.entries(catalog).filter(([k]) => k !== key).map(([, v]) => v); + expect(others, `${locale}.${key}`).not.toContain(catalog[key]); + } + } + }); + + it('renders the caller locale with the labels and title it is given, and falls back to en for a locale the catalog lacks', () => { + const zh = renderOperationMessage({ messageKey: 'record_closed', params: { object: '发票', title: 'INV-0042' } }, { locale: 'zh-CN' }); + expect(zh).toBe(BUILTIN_OPERATION_MESSAGES['zh-CN'].record_closed.replace('{{object}}', '发票').replace('{{title}}', 'INV-0042')); + const ja = renderOperationMessage( + { messageKey: 'record_closed_delete_blocked_untitled', params: { object: '取引先', blockingObject: '請求書' } }, + { locale: 'ja' }, + ); + expect(ja).toBe(BUILTIN_OPERATION_MESSAGES['ja-JP'].record_closed_delete_blocked_untitled.replace('{{object}}', '取引先').replace('{{blockingObject}}', '請求書')); + expect(renderOperationMessage({ messageKey: 'record_closed_opaque' }, { locale: 'de-DE' })).toBe(BUILTIN_OPERATION_MESSAGES.en.record_closed_opaque); + }); + + it('a deployment translation override wins, under the shared `errors.` address, and a title is printed as written', () => { + const translate = (k: string) => (k === operationMessageTranslationKey('record_closed') ? '{{object}}《{{title}}》已归档' : k); + const title = 'Q{{object}}'; + expect(renderOperationMessage({ messageKey: 'record_closed', params: { object: '发票', title } }, { locale: 'zh-CN', translate })) + .toBe(`发票《${title}》已归档`); + }); +}); + /** * #34699 — the user's half of three platform refusals whose `message` stays the * developer sentence: the by-id not-found, the filter-oracle guard and the diff --git a/packages/spec/src/system/operation-message.ts b/packages/spec/src/system/operation-message.ts index b7b02697e04..835eb35f021 100644 --- a/packages/spec/src/system/operation-message.ts +++ b/packages/spec/src/system/operation-message.ts @@ -16,7 +16,8 @@ * refusal (`approval_recall_not_submitter`; emitter conversion is #11993's * half) — and the unique-constraint refusal (`409 UNIQUE_VIOLATION` on the * wire, the engine's `DuplicateRecordError`) — and the `userMessage` of the - * master-detail write gate's `403 PERMISSION_DENIED` (ADR-0055 §3). The catalog is the seat for the rest of the family as they are + * master-detail write gate's `403 PERMISSION_DENIED` (ADR-0055 §3) — and the engine's + * closed-state lock (`409 RECORD_LOCKED`, ADR-0162 D8). The catalog is the seat for the rest of the family as they are * localized — a second mechanism for the second producer is exactly what this * module exists to prevent. * @@ -41,6 +42,8 @@ * | `master_record_edit_denied` / `master_record_read_denied` (and their `_opaque` forms) | they wrote a `controlled_by_parent` record (a detail) without the edit access (or, where the detail asks it, the read access) its master record requires | ask the master record's owner, or an administrator | * | `field_edit_denied` / `field_edit_denied_opaque` | they changed a field their permissions do not let them edit | undo that change, or ask an administrator | * | `record_locked` (and its `_untitled`, `_unlabeled` and `_opaque` forms) | they tried to change a record an approval in progress holds | wait until that approval is complete | + * | `record_closed` (and its `_untitled`, `_unlabeled` and `_opaque` forms) | they tried to change or delete a record, or a line of a record, that is in one of its object's closed states | nothing: the document is final; a closed state is where it ends up | + * | `record_closed_delete_blocked` (and its `_untitled` and `_opaque` forms) | they tried to delete a record whose deletion would also remove a closed record, or a line of one | nothing: deleting it would change a final document | * * `record_write_denied` (commit aa5994e17) is NOT `record_access_denied` restated: the * sharing middleware's by-id write gate fires on a row the READ path already @@ -292,6 +295,45 @@ export function operationMessageTranslationKey(messageKey: string): string { * Their English is byte-identical to the fixed sentence the hook answered * before it was localized. * + * [ADR-0162 D8] The four `record_closed*` keys are the end user's sentence of + * the engine's closed-state lock (`409 RECORD_LOCKED`, `@objectstack/objectql` + * `closed-state-lock.ts`): a record in one of its object's declared closed + * states, or a line of one, refuses a caller's change or delete. Same code as + * the pending lock, its own sentences, because "wait until that approval is + * complete" is false for a closed document. The same four forms and the same + * placeholder contract as `record_locked*`: + * + * - `record_closed` takes `{{object}}` (the object's LABEL in the caller's + * locale) and `{{title}}` (the record's title as the WRITER would be + * served it under its own field permissions, never the title as stored); + * - `record_closed_untitled` takes `{{object}}` alone: for a record whose + * title the writer may not be served, for a write that matched rows by a + * predicate, and for a line write, where `{{object}}` is the MASTER's + * label (the engine reads the master's state to judge and reads nothing + * of it to word the refusal); + * - `record_closed_unlabeled` takes `{{title}}` alone, for an object with no + * label; + * - `record_closed_opaque` names nothing. + * + * The three `record_closed_delete_blocked*` keys are the same lock's + * sentence for a delete refused for what it would also remove: a closed + * record, or a line of one, in the set the delete was planned to remove. It + * names the record the caller asked to delete and the label of the object + * whose closed record stands in the way, and nothing else: no title, id or + * count of the closed records. + * + * - `record_closed_delete_blocked` takes `{{object}}` and `{{title}}` (the + * record asked to be deleted, its title as the caller is served it) and + * `{{blockingObject}}` (the label of the object in the way); + * - `record_closed_delete_blocked_untitled` drops `{{title}}`: where the + * caller is served no title for that record, and where the delete names + * many records; + * - `record_closed_delete_blocked_opaque` names nothing, where either + * object has no label. + * + * None of the seven carries a record id, an API name or the state's value: a + * reader who may see the state reads it off the record. + * * Three keys are the `userMessage` of refusals whose `message` stays the * developer sentence (code, status and `message` unchanged). None takes a * placeholder, re-derived per site: @@ -472,6 +514,20 @@ export const BUILTIN_OPERATION_MESSAGES: Record> 'This {{object}} is locked while an approval is in progress, and cannot be edited until that approval is complete', record_locked_opaque: 'This record is locked while an approval is in progress, and cannot be edited until that approval is complete', + record_closed: + "{{object}} '{{title}}' is closed, so it and its lines can no longer be changed or deleted", + record_closed_unlabeled: + "'{{title}}' is closed, so it and its lines can no longer be changed or deleted", + record_closed_untitled: + 'This {{object}} is closed, so it and its lines can no longer be changed or deleted', + record_closed_opaque: + 'This record is closed, so it and its lines can no longer be changed or deleted', + record_closed_delete_blocked: + "{{object}} '{{title}}' cannot be deleted: deleting it would also remove a closed {{blockingObject}} or one of its lines", + record_closed_delete_blocked_untitled: + 'This {{object}} cannot be deleted: deleting it would also remove a closed {{blockingObject}} or one of its lines', + record_closed_delete_blocked_opaque: + 'This record cannot be deleted: deleting it would also remove a closed record or one of its lines', record_not_found: 'This record does not exist, or you do not have access to it.', query_field_not_readable: 'This request filters, sorts or groups by a field you do not have access to. Remove that condition and try again, or contact your administrator if you need access.', @@ -606,6 +662,13 @@ export const BUILTIN_OPERATION_MESSAGES: Record> record_locked_unlabeled: '「{{title}}」正在审批中,已被锁定,审批完成前无法编辑', record_locked_untitled: '该{{object}}正在审批中,已被锁定,审批完成前无法编辑', record_locked_opaque: '该记录正在审批中,已被锁定,审批完成前无法编辑', + record_closed: '{{object}}「{{title}}」已关闭,它及其明细行都不能再修改或删除', + record_closed_unlabeled: '「{{title}}」已关闭,它及其明细行都不能再修改或删除', + record_closed_untitled: '该{{object}}已关闭,它及其明细行都不能再修改或删除', + record_closed_opaque: '该记录已关闭,它及其明细行都不能再修改或删除', + record_closed_delete_blocked: '无法删除{{object}}「{{title}}」:删除它会一并删除一条已关闭的{{blockingObject}}或其明细行', + record_closed_delete_blocked_untitled: '无法删除该{{object}}:删除它会一并删除一条已关闭的{{blockingObject}}或其明细行', + record_closed_delete_blocked_opaque: '无法删除该记录:删除它会一并删除一条已关闭的记录或其明细行', record_not_found: '该记录不存在,或您无权访问它。', query_field_not_readable: '当前请求按您无权查看的字段筛选、排序或分组,请去掉该条件后重试,或联系管理员。', delegation_scope_violation: '此更改超出了您被委派管理的范围,如需更改请联系管理员。', @@ -736,6 +799,13 @@ export const BUILTIN_OPERATION_MESSAGES: Record> record_locked_unlabeled: '「{{title}}」は承認処理中のためロックされています。承認が完了するまで編集できません', record_locked_untitled: 'この{{object}}は承認処理中のためロックされています。承認が完了するまで編集できません', record_locked_opaque: 'このレコードは承認処理中のためロックされています。承認が完了するまで編集できません', + record_closed: '{{object}}「{{title}}」はクローズ済みのため、明細を含めて変更も削除もできません', + record_closed_unlabeled: '「{{title}}」はクローズ済みのため、明細を含めて変更も削除もできません', + record_closed_untitled: 'この{{object}}はクローズ済みのため、明細を含めて変更も削除もできません', + record_closed_opaque: 'このレコードはクローズ済みのため、明細を含めて変更も削除もできません', + record_closed_delete_blocked: '{{object}}「{{title}}」は削除できません。削除すると、クローズ済みの{{blockingObject}}またはその明細も削除されます', + record_closed_delete_blocked_untitled: 'この{{object}}は削除できません。削除すると、クローズ済みの{{blockingObject}}またはその明細も削除されます', + record_closed_delete_blocked_opaque: 'このレコードは削除できません。削除すると、クローズ済みのレコードまたはその明細も削除されます', record_not_found: 'このレコードは存在しないか、アクセスする権限がありません。', query_field_not_readable: 'この要求は、閲覧権限のない項目で絞り込み、並べ替え、またはグループ化しています。その条件を削除して再試行するか、アクセスが必要な場合は管理者にお問い合わせください。', @@ -889,6 +959,20 @@ export const BUILTIN_OPERATION_MESSAGES: Record> 'Este registro de {{object}} está bloqueado mientras hay una aprobación en curso y no se puede editar hasta que esa aprobación finalice', record_locked_opaque: 'Este registro está bloqueado mientras hay una aprobación en curso y no se puede editar hasta que esa aprobación finalice', + record_closed: + 'El registro de {{object}} «{{title}}» está cerrado, por lo que ni él ni sus líneas se pueden modificar ni eliminar', + record_closed_unlabeled: + 'El registro «{{title}}» está cerrado, por lo que ni él ni sus líneas se pueden modificar ni eliminar', + record_closed_untitled: + 'Este registro de {{object}} está cerrado, por lo que ni él ni sus líneas se pueden modificar ni eliminar', + record_closed_opaque: + 'Este registro está cerrado, por lo que ni él ni sus líneas se pueden modificar ni eliminar', + record_closed_delete_blocked: + 'No se puede eliminar el registro de {{object}} «{{title}}»: al eliminarlo también se eliminaría un registro cerrado de {{blockingObject}} o una de sus líneas', + record_closed_delete_blocked_untitled: + 'No se puede eliminar este registro de {{object}}: al eliminarlo también se eliminaría un registro cerrado de {{blockingObject}} o una de sus líneas', + record_closed_delete_blocked_opaque: + 'No se puede eliminar este registro: al eliminarlo también se eliminaría un registro cerrado o una de sus líneas', record_not_found: 'Este registro no existe o no tiene acceso a él.', query_field_not_readable: 'Esta solicitud filtra, ordena o agrupa por un campo al que no tiene acceso. Quite esa condición e inténtelo de nuevo, o póngase en contacto con su administrador si necesita acceso.', From badeef7116dc89ae298e5bed71db32536bdba2c9 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 05:26:14 +0000 Subject: [PATCH 02/10] feat(objectql): the closed-state refusal speaks the catalog's sentence, titled as the writer is served (ADR-0162 D8) The lock's refusal now carries the Operation Message Catalog's sentence as userMessage and as its message behind the code: the record's own write names the object's label and the title the writer would be served under its own field permissions (asked of the security service, never the stored title), a predicate write and a line write take the label form (a line names its master), and a delete refused for what it would also remove names the record asked to be deleted and the label of the object in the way. The developer's sentence moves to developerMessage. A refusal that could not judge the write keeps its developer message. Claude-Session: https://claude.ai/code/session_01FEkQ5nGQtUA88SthJbYyRw Co-Authored-By: Claude --- packages/objectql/src/closed-state-lock.ts | 298 ++++++++++++++-- .../objectql/src/engine-cascade-planning.ts | 8 +- .../src/engine-delete-and-aggregate.ts | 4 +- packages/objectql/src/engine.ts | 4 +- .../closed-state-refusal-wire.dogfood.test.ts | 328 ++++++++++++++++++ 5 files changed, 616 insertions(+), 26 deletions(-) create mode 100644 packages/qa/dogfood/test/closed-state-refusal-wire.dogfood.test.ts diff --git a/packages/objectql/src/closed-state-lock.ts b/packages/objectql/src/closed-state-lock.ts index 79422ac9956..def5b493741 100644 --- a/packages/objectql/src/closed-state-lock.ts +++ b/packages/objectql/src/closed-state-lock.ts @@ -55,17 +55,44 @@ * hangs under is judged on its stored state, whoever the writer is: that read * is the engine's, above the writer's grants and inside its organization scope. * - * ## The refusal + * ## The refusal (D8) * * `409 RECORD_LOCKED`, the code the pending-approval lock already answers - * with. The sentence family a person reads (ADR-0162 D8) is the message - * catalog's; the `message` here is the developer's and carries no record id - * and no state value. + * with. What a person reads is the Operation Message Catalog's sentence + * (`@objectstack/spec/system`), in the caller's language, carried as the + * error's `userMessage` and as its `message` behind the code, the shape the + * pending lock's refusal has, so the wire's `error` reads the same sentence + * ({@link closedStateRefusalSentence}): + * + * - a record's own write: `record_closed*`, naming the record by its + * object's label and the title the WRITER would be served under its own + * field permissions ({@link servedTitleOf}); ⛔ never the title as stored; + * - a write that matched rows by a predicate: the label form, no title; + * - a line write, a line's restore: the label form, naming the MASTER (the + * engine reads the master's state to judge, and reads nothing of it to word + * the refusal); + * - a delete refused for what it would also remove: + * `record_closed_delete_blocked*`, naming the record asked to be deleted + * and the label of the object in the way, the title only where the caller + * is served one and the delete names one record. + * + * No form carries a record id, an API name or the state's value. The + * developer's sentence, which names objects by their API names, moves to + * `developerMessage`, which no person-facing surface reads and the data door + * does not relay. A refusal that could not judge the write (D4's three cases) + * keeps the developer's sentence as its `message` and marks no `userMessage`: + * it is addressed to whoever scoped the write, as the pending lock's + * unanswerable-bound refusal is. */ -import { MAX_BULK_PER_ROW_HOOK_ROWS, ReadableIds, type FilterCondition } from '@objectstack/spec/data'; +import { MAX_BULK_PER_ROW_HOOK_ROWS, ReadableIds, resolveDisplayField, type FilterCondition } from '@objectstack/spec/data'; import { postureEnforcesWall, type TenancyPosture } from '@objectstack/spec/security'; import type { ExecutionContext } from '@objectstack/spec/kernel'; +import type { ISecurityService } from '@objectstack/spec/contracts'; +import { renderOperationMessage } from '@objectstack/spec/system'; +import { objectDisplayLabel } from './engine-validation-messages.js'; +import { SECURITY_SERVICE_SOURCE_SLOT } from './engine-top-level.js'; +import type { ValidationMessageContext } from './validation/record-validator.js'; import { isDriverTenantScopedSchema } from './engine-driver-options.js'; import { isFederatedObject } from './federated-object.js'; import { driverCompilesReadableIdsLeaf } from './relation-semi-join.js'; @@ -102,6 +129,17 @@ export interface ClosedStateLockHost { buildDriverOptions(object: string, context: ExecutionContext | undefined, base?: any, extra?: any): any; masterDetailHeadersCallerReads(master: string, ids: ReadonlyArray, context: ExecutionContext | undefined): Promise>; resolveEnginePosture(): TenancyPosture; + /** + * [D8] The caller's locale and translator, which the refusal's sentence and + * the labels it names are worded in (`engine-validation-messages.ts`). + * Absent: English and the declared labels. + */ + validationMessageContext?(object: string, context?: { locale?: string }): ValidationMessageContext; + /** + * [D8] The engine, whose security-service source slot answers which fields + * the writer is served ({@link servedTitleOf}). Absent: no title is named. + */ + readonly facade?: object; } /** The verbs a refusal names. */ @@ -130,6 +168,10 @@ export interface ClosedStateLockError extends Error { readonly blockingObject?: string; /** What the lock read: `closed_state`, the one lock read's reason (ADR-0162 D9). */ readonly lockReason: 'closed_state'; + /** [D8] The catalog's sentence, in the caller's locale. Absent on a refusal that could not judge the write. */ + readonly userMessage?: string; + /** [D8] The developer's sentence (API names), where `message` carries the person's. */ + readonly developerMessage?: string; } /** @@ -171,6 +213,177 @@ function verbPast(verb: ClosedStateWriteVerb): string { } } +// ── The sentence a person reads (D8) ───────────────────────────────────────── + +/** The host members the sentence is worded from. */ +type WordingHost = Pick; + +/** What a refusal names, by the case it answers. */ +export type ClosedStateRefusalWording = + /** A record's own write. `row` is the record as stored; absent for a write that matched rows by a predicate. */ + | { readonly kind: 'record'; readonly object: string; readonly row?: Record } + /** A line write, or a line's restore: the master, by its label alone. */ + | { readonly kind: 'master'; readonly master: string } + /** A delete refused for what it would also remove: the record asked to be deleted, and the object in the way. */ + | { readonly kind: 'delete_blocked'; readonly object: string; readonly row?: Record; readonly blockingObject: string }; + +function messagesFor(host: WordingHost, object: string, context: ExecutionContext | undefined): ValidationMessageContext | undefined { + try { + return host.validationMessageContext?.(object, context); + } catch { + // A misbehaving i18n service words the refusal in English; it never turns a 409 into a 500. + return undefined; + } +} + +/** + * The object's label in the caller's locale: the translation, else the + * declared label. `undefined` when it has neither: the API name, the last + * rung of `objectDisplayLabel`, never reaches this sentence. + */ +function objectLabelOf(host: WordingHost, object: string, messages: ValidationMessageContext | undefined): string | undefined { + let declared: string | undefined; + try { + const raw = (host._registry.getObject(object) as { label?: unknown } | undefined)?.label; + declared = typeof raw === 'string' && raw.trim() !== '' ? raw.trim() : undefined; + } catch { + declared = undefined; + } + let label: string; + try { + label = objectDisplayLabel(object, declared, messages ?? {}); + } catch { + label = declared ?? object; + } + return label && !(label === object && declared === undefined) ? label : undefined; +} + +/** The field an object's title is read from (ADR-0079's one arbiter), or `undefined`; ⛔ never the id. */ +function titleFieldOf(host: Pick, object: string): string | undefined { + try { + const field = resolveDisplayField(host._registry.getObject(object) as never); + return field && field !== 'id' && field !== '_id' ? field : undefined; + } catch { + return undefined; + } +} + +/** + * [D8] May the writer be served `field` of `object`? The rule the pending lock + * picks its title by (`plugin-approvals` `resolveReadableSnapshotFields`): the + * field is readable for the writer AND not served masked to it (the security + * contract's `getQueryableFields` is the read projection minus the masked + * fields), asked of the registered `security` service with the writer's own + * execution context. + * + * With no security service registered there is no field-level security: a + * read serves every field, so the stored title is the served one. Every other + * answer short of a clear yes names no title: a host that lends no engine, a + * service without either member, a question that throws or answers nothing. + */ +async function titleFieldIsServed(host: WordingHost, object: string, field: string, context: ExecutionContext | undefined): Promise { + if (!host.facade) return false; + // Read from the engine slot at use (see SECURITY_SERVICE_SOURCE_SLOT), never cached. + const source = (host.facade as Record)[SECURITY_SERVICE_SOURCE_SLOT]; + if (source === undefined || source === null) return true; + if (typeof source !== 'function') return false; + let svc: Partial> | null | undefined; + try { + svc = source() as typeof svc; + } catch { + // The in-repo kernels throw on a name nothing registered: no service, no field-level security. + return true; + } + if (svc === undefined || svc === null) return true; + if (typeof svc.getReadableFields !== 'function' || typeof svc.getQueryableFields !== 'function') return false; + try { + const readable = await svc.getReadableFields(object, context as never); + if (!Array.isArray(readable) || !readable.includes(field)) return false; + const unmasked = await svc.getQueryableFields(object, context as never); + return Array.isArray(unmasked) && unmasked.includes(field); + } catch { + return false; + } +} + +/** + * [D8] The record's title as the writer would be served it, or `undefined`. + * Read off `row`, the record as stored (the engine's own read), and named only + * when the writer may be served the title field ({@link titleFieldIsServed}). + * An empty title, or one whose value is the record's id, is no title. + */ +export async function servedTitleOf( + this: WordingHost, + object: string, + row: Record | null | undefined, + context: ExecutionContext | undefined, +): Promise { + if (!row || typeof row !== 'object') return undefined; + const field = titleFieldOf(this, object); + if (!field) return undefined; + const raw = row[field]; + if (raw === null || raw === undefined || typeof raw === 'object') return undefined; + const title = String(raw).trim(); + if (!title) return undefined; + const id = row.id ?? row._id; + if (id !== undefined && id !== null && title === String(id)) return undefined; + return (await titleFieldIsServed(this, object, field, context)) ? title : undefined; +} + +/** + * [D8] The sentence a person reads for a closed-state refusal, rendered from + * the Operation Message Catalog in the caller's locale. Which form applies + * picks the KEY; the labels and the title are its parameters. + */ +export async function closedStateRefusalSentence( + this: WordingHost, + wording: ClosedStateRefusalWording, + context: ExecutionContext | undefined, +): Promise { + const subject = wording.kind === 'master' ? wording.master : wording.object; + const messages = messagesFor(this, subject, context); + const render = (messageKey: string, params: Record = {}) => + renderOperationMessage({ messageKey, params }, { locale: messages?.locale, translate: messages?.translate }); + try { + if (wording.kind === 'master') { + const label = objectLabelOf(this, wording.master, messages); + return label ? render('record_closed_untitled', { object: label }) : render('record_closed_opaque'); + } + const label = objectLabelOf(this, wording.object, messages); + const title = await servedTitleOf.call(this, wording.object, wording.row, context); + if (wording.kind === 'record') { + if (title) return label ? render('record_closed', { object: label, title }) : render('record_closed_unlabeled', { title }); + return label ? render('record_closed_untitled', { object: label }) : render('record_closed_opaque'); + } + const blocking = objectLabelOf(this, wording.blockingObject, messages); + if (!label || !blocking) return render('record_closed_delete_blocked_opaque'); + return title + ? render('record_closed_delete_blocked', { object: label, title, blockingObject: blocking }) + : render('record_closed_delete_blocked_untitled', { object: label, blockingObject: blocking }); + } catch { + return render(wording.kind === 'delete_blocked' ? 'record_closed_delete_blocked_opaque' : 'record_closed_opaque'); + } +} + +/** + * [D8] The refusal as a person reads it: `err`'s developer sentence moves to + * `developerMessage`, and the catalog's sentence becomes its `userMessage` and + * its `message` (behind the code, which the data door strips). + */ +async function sayClosed( + this: WordingHost, + err: ClosedStateLockError, + wording: ClosedStateRefusalWording, + context: ExecutionContext | undefined, +): Promise { + const sentence = await closedStateRefusalSentence.call(this, wording, context); + const e = err as unknown as Record; + e.developerMessage = err.message; + e.message = `${CLOSED_STATE_LOCK_CODE}: ${sentence}`; + e.userMessage = sentence; + return err; +} + /** * [D5] Is a write in `context` bound by the lock? Every write is, except one * made in a system context. A write with no context is bound: no identity is @@ -340,21 +553,25 @@ export async function judgeClosedStateByIdWrite(this: ClosedStateLockHost, write if (carriedKeys(payload).length === 0) return; if (isBareReferentialClear(payload, write.referentialClear)) return; } - if (unit.own && rowIsClosed(prior, unit.own)) throw closedStateLockError(object, verb, 'record_closed'); + if (unit.own && rowIsClosed(prior, unit.own)) { + throw await sayClosed.call(this, closedStateLockError(object, verb, 'record_closed'), { kind: 'record', object, row: prior }, context); + } const refuse = (detail: string) => closedStateLockError(object, verb, 'cannot_judge', undefined, detail); + const masterClosed = (master: string) => + sayClosed.call(this, closedStateLockError(object, verb, 'master_closed', master), { kind: 'master', master }, context); for (const edge of unit.masters) { // The master the stored row hangs under: its stored state, whoever writes. const stored = scalarIdOf(prior[edge.fk]); if (stored === undefined) throw refuse(`its '${edge.fk}' does not hold one id`); if (stored !== null && await anyClosedAmong.call(this, edge.master, [stored], edge.closed, context, refuse)) { - throw closedStateLockError(object, verb, 'master_closed', edge.master); + throw await masterClosed(edge.master); } // A move names the master it moves to: the caller's read door first. if (verb === 'update' && payload && Object.prototype.hasOwnProperty.call(payload, edge.fk)) { const named = scalarIdOf(payload[edge.fk]); if (named === undefined) throw refuse(`the master named by '${edge.fk}' is not one id`); if (named !== null && named !== stored && await namedMastersClosed.call(this, edge, [named], context, refuse)) { - throw closedStateLockError(object, verb, 'master_closed', edge.master); + throw await masterClosed(edge.master); } } } @@ -384,7 +601,7 @@ export async function judgeClosedStateCreate( if (id !== null) named.push(id); } if (await namedMastersClosed.call(this, edge, [...new Set(named)], context, refuse)) { - throw closedStateLockError(object, 'create', 'master_closed', edge.master); + throw await sayClosed.call(this, closedStateLockError(object, 'create', 'master_closed', edge.master), { kind: 'master', master: edge.master }, context); } } } @@ -457,8 +674,11 @@ export async function judgeClosedStatePredicateWrite(this: ClosedStateLockHost, } }; if (unit.own && await probe(andWhere(ast.where, closedPredicate(unit.own)))) { - throw closedStateLockError(object, verb, 'record_closed'); + // Matched by a predicate: no one row is named, so no title (the label form). + throw await sayClosed.call(this, closedStateLockError(object, verb, 'record_closed'), { kind: 'record', object }, context); } + const masterClosed = (master: string) => + sayClosed.call(this, closedStateLockError(object, verb, 'master_closed', master), { kind: 'master', master }, context); let matched: ReadonlyArray> | undefined; const matchedRows = async (): Promise>> => { if (matched) return matched; @@ -477,7 +697,7 @@ export async function judgeClosedStatePredicateWrite(this: ClosedStateLockHost, for (const edge of unit.masters) { if (lineProbeServes.call(this, object, edge.master)) { const semiJoin = { [edge.fk]: { $in: ReadableIds.compose(ReadableIds.of(edge.master), closedPredicate(edge.closed)) } } as FilterCondition; - if (await probe(andWhere(ast.where, semiJoin))) throw closedStateLockError(object, verb, 'master_closed', edge.master); + if (await probe(andWhere(ast.where, semiJoin))) throw await masterClosed(edge.master); } else { const ids: string[] = []; for (const row of await matchedRows()) { @@ -486,14 +706,14 @@ export async function judgeClosedStatePredicateWrite(this: ClosedStateLockHost, if (id !== null) ids.push(id); } if (await anyClosedAmong.call(this, edge.master, ids, edge.closed, context, refuse)) { - throw closedStateLockError(object, verb, 'master_closed', edge.master); + throw await masterClosed(edge.master); } } if (verb === 'update' && payload && Object.prototype.hasOwnProperty.call(payload, edge.fk)) { const named = scalarIdOf(payload[edge.fk]); if (named === undefined) throw refuse(`the master named by '${edge.fk}' is not one id`); if (named !== null && await namedMastersClosed.call(this, edge, [named], context, refuse)) { - throw closedStateLockError(object, verb, 'master_closed', edge.master); + throw await masterClosed(edge.master); } } } @@ -503,17 +723,27 @@ export async function judgeClosedStatePredicateWrite(this: ClosedStateLockHost, * [D6] Judge the set a delete's cascade will remove, collected whole before * any row is removed (`engine-cascade-planning.ts#cascadeDeleteRelations`). * Refused whole when a member is closed, or is a line of a closed record. The - * refusal names the record the caller asked to delete (its object) and the - * object whose closed record stands in the way, and nothing else. + * refusal names the record the caller asked to delete and the object whose + * closed record stands in the way, and nothing else (D8): the record by its + * title as the caller is served it where `roots` names one record, else by its + * object's label alone. */ export async function judgeClosedStateCascadeSet( - this: Pick, + this: Pick, root: string, members: ReadonlyMap>, context: ExecutionContext | undefined, + roots: ReadonlyArray = [], ): Promise { if (!boundByClosedStates(context)) return; const refuse = (detail: string) => closedStateLockError(root, 'delete', 'cannot_judge', undefined, detail); + const blocked = async (blockingObject: string) => + sayClosed.call( + this, + closedStateLockError(root, 'delete', 'cascade_reaches_closed', blockingObject), + { kind: 'delete_blocked', object: root, row: roots.length === 1 ? await storedTitleRow.call(this, root, roots[0]!, context) : undefined, blockingObject }, + context, + ); for (const [object, idSet] of members) { const unit = closedStateUnitOf.call(this, object); if (!unit || idSet.size === 0) continue; @@ -531,7 +761,7 @@ export async function judgeClosedStateCascadeSet( }; if (unit.own) { for (const part of parts) { - if (await probe(part, closedPredicate(unit.own))) throw closedStateLockError(root, 'delete', 'cascade_reaches_closed', object); + if (await probe(part, closedPredicate(unit.own))) throw await blocked(object); } } for (const edge of unit.masters) { @@ -539,7 +769,7 @@ export async function judgeClosedStateCascadeSet( // The predicate door's semi-join, scoped to the set's ids. const semiJoin = { [edge.fk]: { $in: ReadableIds.compose(ReadableIds.of(edge.master), closedPredicate(edge.closed)) } } as FilterCondition; for (const part of parts) { - if (await probe(part, semiJoin)) throw closedStateLockError(root, 'delete', 'cascade_reaches_closed', edge.master); + if (await probe(part, semiJoin)) throw await blocked(edge.master); } continue; } @@ -561,12 +791,38 @@ export async function judgeClosedStateCascadeSet( throw Object.assign(refuse(`the rows of '${object}' its cascade reaches could not be read`), { cause: error }); } if (await anyClosedAmong.call(this, edge.master, masterIds, edge.closed, context, refuse)) { - throw closedStateLockError(root, 'delete', 'cascade_reaches_closed', edge.master); + throw await blocked(edge.master); } } } } +/** + * [D8] The title column of the one record a delete names, read by the engine + * from the store (inside the caller's organization scope and unit of work), so + * the refusal can name it as the caller is served it ({@link servedTitleOf}). + * Read only on the refusal path; a read that fails names no title. + */ +async function storedTitleRow( + this: Pick, + object: string, + id: string | number, + context: ExecutionContext | undefined, +): Promise | undefined> { + const field = titleFieldOf(this, object); + if (!field) return undefined; + try { + const rows = (await this.getDriver(object).find( + object, + { object, where: { id }, fields: ['id', field], limit: 1 }, + this.buildDriverOptions(object, context), + )) as Array> | null; + return Array.isArray(rows) && rows[0] && typeof rows[0] === 'object' ? rows[0] : undefined; + } catch { + return undefined; + } +} + /** * [D7] Restore: an entry that would put a row back under a LIVE, closed master * that is not itself part of the entry is refused before anything is written. @@ -574,7 +830,7 @@ export async function judgeClosedStateCascadeSet( * the live master's id. */ export async function judgeClosedStateRestore( - this: Pick, + this: Pick, parents: ReadonlyArray<{ object: string; field: string; master: string; id: string }>, context: ExecutionContext | undefined, ): Promise { @@ -592,7 +848,7 @@ export async function judgeClosedStateRestore( for (const [master, { closed, ids, object }] of byMaster) { const refuse = (detail: string) => closedStateLockError(object, 'restore', 'cannot_judge', undefined, detail); if (await anyClosedAmong.call(this, master, ids, closed, context, refuse)) { - throw closedStateLockError(object, 'restore', 'master_closed', master); + throw await sayClosed.call(this, closedStateLockError(object, 'restore', 'master_closed', master), { kind: 'master', master }, context); } } } diff --git a/packages/objectql/src/engine-cascade-planning.ts b/packages/objectql/src/engine-cascade-planning.ts index 654cf66a52b..a84028e23a5 100644 --- a/packages/objectql/src/engine-cascade-planning.ts +++ b/packages/objectql/src/engine-cascade-planning.ts @@ -88,6 +88,10 @@ export interface CascadePlanningHost { /** [ADR-0162 D6] The driver options the closed-state lock reads the cascade set with. */ buildDriverOptions: ObjectQLClass['buildDriverOptions']; resolveEnginePosture: ObjectQLClass['resolveEnginePosture']; + /** [ADR-0162 D8] The engine, whose security-service slot answers whether the caller is served the root's title. */ + readonly facade: ObjectQLClass; + /** [ADR-0162 D8] The caller's locale and translator, which the closed-state refusal's sentence is worded in. */ + validationMessageContext: ObjectQLClass['validationMessageContext']; getDriver: ObjectQLClass['getDriver']; isTenantColumnSetNull: ObjectQLClass['isTenantColumnSetNull']; readonly logger: ObjectQLClass['logger']; @@ -536,7 +540,7 @@ export class CascadePlanningFacet { * (formula values, file references, hooks), so they are not the values a * restore must write back. */ - static async cascadeDeleteRelations(this: Pick, object: string, ids: ReadonlyArray, context?: ExecutionContext, depth = 0, onCollected?: (set: CascadeDeleteSet) => Promise): Promise { + static async cascadeDeleteRelations(this: Pick, object: string, ids: ReadonlyArray, context?: ExecutionContext, depth = 0, onCollected?: (set: CascadeDeleteSet) => Promise): Promise { const roots: Array = []; const seen = new Set(); for (const id of ids) { @@ -583,7 +587,7 @@ export class CascadePlanningFacet { // point: after the caller's gates on the record it asked to delete and // before the first row is removed, never leg by leg. A member that is // closed, or is a line of a closed record, refuses the delete whole. - await judgeClosedStateCascadeSet.call(this, object, cascadeSet.members, context); + await judgeClosedStateCascadeSet.call(this, object, cascadeSet.members, context, fresh); if (onCollected) await onCollected(cascadeSet); await this.cascadeDeleteSets.run(cascadeSet, () => this.walkReferencingRelations(object, fresh, context, objects, cascadeSet), diff --git a/packages/objectql/src/engine-delete-and-aggregate.ts b/packages/objectql/src/engine-delete-and-aggregate.ts index 072787d6e74..dd841679c48 100644 --- a/packages/objectql/src/engine-delete-and-aggregate.ts +++ b/packages/objectql/src/engine-delete-and-aggregate.ts @@ -131,6 +131,8 @@ export interface DeleteAndAggregateHost { expandSearchOnOptions: ObjectQLClass['expandSearchOnOptions']; /** The engine itself: a moved body reads `this.facade` where the method read a bare `this` (#30020). */ readonly facade: ObjectQLClass; + /** [ADR-0162 D8] The caller's locale and translator, which the closed-state refusal's sentence is worded in. */ + validationMessageContext: ObjectQLClass['validationMessageContext']; getDriver: ObjectQLClass['getDriver']; getSummaryDescriptors: ObjectQLClass['getSummaryDescriptors']; hasHooksFor: ObjectQLClass['hasHooksFor']; @@ -164,7 +166,7 @@ export interface DeleteAndAggregateHost { /** The bodies of the "Delete, count, aggregate and execute" section of `ObjectQL`: a stateless facet, called by the class's stubs. */ export class DeleteAndAggregateFacet { /** The body of `ObjectQL#delete`; the method's docblock there is its contract. */ - static async delete(this: Pick, object: string, options?: EngineDeleteOptions & RecycleBinDeleteObservability): Promise { + static async delete(this: Pick, object: string, options?: EngineDeleteOptions & RecycleBinDeleteObservability): Promise { object = this.resolveObjectName(object); // [#22782, #34412] An aborting `afterDelete`, or a refusal after a `beforeDelete` hook's // `ctx.api` write, rolls this write back with it — see `opensAfterAbortUnit`. diff --git a/packages/objectql/src/engine.ts b/packages/objectql/src/engine.ts index de840274a13..266feb3dc86 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), resolveEnginePosture: () => engine.resolveEnginePosture(), // [ADR-0162 D6] + walkReferencingRelations: (...a) => engine.walkReferencingRelations(...a), buildDriverOptions: (...a) => engine.buildDriverOptions(...a), resolveEnginePosture: () => engine.resolveEnginePosture(), facade: engine, validationMessageContext: (...a) => engine.validationMessageContext(...a), // [ADR-0162 D6, D8] })); compatibilitySectionHost.install((engine) => ({ get _registry() { return engine._registry; }, @@ -5899,7 +5899,7 @@ export class ObjectQL implements IObjectQLEngine { transaction: (...a) => engine.transaction(...a), triggerHooks: (...a) => engine.triggerHooks(...a), warnCascadeNotAtomic: (...a) => engine.warnCascadeNotAtomic(...a), - withResolvedWhere: (...a) => engine.withResolvedWhere(...a), masterDetailHeadersCallerReads: (...a) => engine.masterDetailHeadersCallerReads(...a), resolveEnginePosture: () => engine.resolveEnginePosture(), // [ADR-0162 D10] + withResolvedWhere: (...a) => engine.withResolvedWhere(...a), masterDetailHeadersCallerReads: (...a) => engine.masterDetailHeadersCallerReads(...a), resolveEnginePosture: () => engine.resolveEnginePosture(), validationMessageContext: (...a) => engine.validationMessageContext(...a), // [ADR-0162 D8, D10] })); findHost.install((engine) => ({ get _registry() { return engine._registry; }, diff --git a/packages/qa/dogfood/test/closed-state-refusal-wire.dogfood.test.ts b/packages/qa/dogfood/test/closed-state-refusal-wire.dogfood.test.ts new file mode 100644 index 00000000000..43bff7fb362 --- /dev/null +++ b/packages/qa/dogfood/test/closed-state-refusal-wire.dogfood.test.ts @@ -0,0 +1,328 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// [ADR-0162 D8, D10] The closed-state refusal on the wire, on a real boot. +// +// ## The composition +// +// `bootStack` with the real `SecurityPlugin`, `ObjectQL`, SQL driver, REST and +// auth layers. Three synthetic objects: an invoice that closes at `settled`, +// its `master_detail` line, and a customer whose delete cascades to its +// invoices. A fourth, a private note that closes at `done`, carries the +// row-access case. Every row is written through the doors by the principals +// below, so each carries its organization and owner as a real write does. +// +// Principals, by permission set: +// +// - the writer: create, read, edit and delete on every object; +// - the withheld writer: the same, with the invoice's and the customer's +// title field `readable: false` (field-level security); +// - the reader: read only on the invoice (the object permission refuses an +// edit), and edit on the note it does not own (row access refuses it). +// +// ## What is asserted, by class +// +// - The person-facing member: a refused write carries `userMessage`, the +// catalog's sentence in the caller's language, and the wire's `error` reads +// the same sentence. Neither names an API name, a record id or a state value. +// - The title is the one the writer would be served (D8): the titled form for +// the writer, the label form for the withheld writer, whose read of the same +// record does not carry the title field (the control that the field is +// really withheld). +// - A line write names the master by its label alone (D8). +// - A delete refused for what it would also remove names the record asked to +// be deleted and the label of the object in the way (D6, D8), the title +// only for a caller served it. +// - D10 at the security layer: a caller the object permission or the row +// access refuses gets the same answer on a closed record as on an open one, +// status and body. +// +// What the wire relays of the refusal's other members is measured and pinned +// too: the developer sentence (API names) stays off the wire, and so do the +// lock's own `reason` / `lockReason` members (D8: nothing machine-readable in +// the refusal names the producer). + +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { bootStack, type VerifyStack } from '@objectstack/verify'; +import { defineStack } from '@objectstack/spec'; +import { ObjectSchema, Field } from '@objectstack/spec/data'; +import { PermissionSetSchema } from '@objectstack/spec/security'; +import { BUILTIN_OPERATION_MESSAGES } from '@objectstack/spec/system'; +import { SecurityPlugin, securityDefaultPermissionSets } from '@objectstack/plugin-security'; +import { catalogPermissionSet } from './catalog-permission-set.js'; + +const INVOICE = 'csr_invoice'; +const LINE = 'csr_line'; +const CUSTOMER = 'csr_customer'; +const NOTE = 'csr_note'; +const SYS = { context: { isSystem: true } } as const; + +/** Synthetic titles: words no sentence of the catalog contains. */ +const T = { + closedInvoice: 'Northwind March', + openInvoice: 'Fabrikam April', + customer: 'Contoso Holdings', + otherCustomer: 'Litware Group', +} as const; + +const Invoice = ObjectSchema.create({ + name: INVOICE, + label: 'Invoice', + pluralLabel: 'Invoices', + sharingModel: 'public_read_write', + fields: { + name: Field.text({ label: 'Number', required: true }), + status: Field.select({ label: 'Status', options: [{ label: 'Draft', value: 'draft' }, { label: 'Settled', value: 'settled' }] }), + amount: Field.number({ label: 'Amount' }), + customer: Field.lookup(CUSTOMER, { label: 'Customer', deleteBehavior: 'cascade' }), + }, + closedStates: { status: ['settled'] }, +}); + +const Line = ObjectSchema.create({ + name: LINE, + label: 'Invoice line', + pluralLabel: 'Invoice lines', + sharingModel: 'public_read_write', + fields: { + name: Field.text({ label: 'Description', required: true }), + qty: Field.number({ label: 'Quantity' }), + invoice: Field.masterDetail(INVOICE, { label: 'Invoice', required: true }), + }, +}); + +const Customer = ObjectSchema.create({ + name: CUSTOMER, + label: 'Customer', + pluralLabel: 'Customers', + sharingModel: 'public_read_write', + fields: { name: Field.text({ label: 'Name', required: true }) }, +}); + +const Note = ObjectSchema.create({ + name: NOTE, + label: 'Note', + pluralLabel: 'Notes', + sharingModel: 'private', + fields: { + name: Field.text({ label: 'Subject', required: true }), + state: Field.select({ label: 'State', options: [{ label: 'Open', value: 'open' }, { label: 'Done', value: 'done' }] }), + }, + closedStates: { state: ['done'] }, +}); + +const fixtureStack = defineStack({ + manifest: { + id: 'com.dogfood.closed-state-refusal', + namespace: 'csr', + version: '0.0.0', + type: 'app', + name: 'Closed-state refusal fixture', + description: 'An invoice that closes, its lines, a customer that cascades to it, and a private note that closes.', + }, + objects: [Invoice, Line, Customer, Note], +}); + +const FULL = { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true } as const; +const writerSet = PermissionSetSchema.parse({ + name: 'csr_writer', + label: 'Closed-state writer', + objects: { [INVOICE]: FULL, [LINE]: FULL, [CUSTOMER]: FULL, [NOTE]: FULL }, +}); +const withheldSet = PermissionSetSchema.parse({ + name: 'csr_withheld', + label: 'Closed-state writer, titles withheld', + objects: { [INVOICE]: FULL, [LINE]: FULL, [CUSTOMER]: FULL, [NOTE]: FULL }, + fields: { + [`${INVOICE}.name`]: { readable: false, editable: false }, + [`${CUSTOMER}.name`]: { readable: false, editable: false }, + }, +}); +const readerSet = PermissionSetSchema.parse({ + name: 'csr_reader', + label: 'Closed-state reader', + objects: { + [INVOICE]: { allowRead: true, allowCreate: false, allowEdit: false, allowDelete: false }, + [NOTE]: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true }, + }, +}); + +const PRINCIPALS = { writer: writerSet.name, withheld: withheldSet.name, reader: readerSet.name } as const; +type Who = keyof typeof PRINCIPALS; + +const en = BUILTIN_OPERATION_MESSAGES.en; +const fill = (template: string, params: Record) => + template.replace(/\{\{(\w+)\}\}/g, (m, k: string) => params[k] ?? m); + +interface Answer { + status: number; + body: Record; +} + +describe('[ADR-0162 D8, D10] the closed-state refusal on the wire', () => { + let stack: VerifyStack; + let ql: any; + const token: Record = {} as never; + const id: Record = {}; + /** Every value a person-facing string must not carry: API names, ids, state values. */ + const forbidden = (): string[] => [INVOICE, LINE, CUSTOMER, NOTE, 'csr_', 'settled', 'closedStates', ...Object.values(id)]; + + const call = async (who: Who | 'admin', method: string, path: string, body?: unknown, locale?: string): Promise => { + const res = await stack.api(path, { + method, + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${token[who]}`, + ...(locale ? { 'Accept-Language': locale } : {}), + }, + ...(body !== undefined ? { body: JSON.stringify(body) } : {}), + }); + const text = await res.text(); + return { status: res.status, body: text ? JSON.parse(text) : {} }; + }; + const created = async (who: Who | 'admin', object: string, body: Record): Promise => { + const a = await call(who, 'POST', `/data/${object}`, body); + expect(a.status, JSON.stringify(a.body)).toBe(201); + return String(a.body?.id ?? a.body?.record?.id ?? ''); + }; + /** The two person-facing strings of a refusal, and what neither may carry. */ + const personFacing = (a: Answer): string => { + expect(a.status, JSON.stringify(a.body)).toBe(409); + expect(a.body.code).toBe('RECORD_LOCKED'); + expect(typeof a.body.userMessage, JSON.stringify(a.body)).toBe('string'); + expect(a.body.error, 'the wire\'s `error` reads the same sentence').toBe(a.body.userMessage); + for (const value of forbidden()) { + expect(a.body.userMessage, `userMessage carries ${value}`).not.toContain(value); + expect(a.body.error, `error carries ${value}`).not.toContain(value); + } + return a.body.userMessage as string; + }; + + beforeAll(async () => { + stack = await bootStack(fixtureStack as unknown as Parameters[0], { + security: new SecurityPlugin({ + defaultPermissionSets: [...securityDefaultPermissionSets, writerSet, withheldSet, readerSet], + fallbackPermissionSet: readerSet.name, + }), + }); + ql = await stack.kernel.getServiceAsync('objectql'); + const idOf = async (email: string) => + String((await ql.findOne('sys_user', { where: { email }, context: { isSystem: true } }))?.id ?? ''); + token.admin = await stack.signIn(); + for (const who of Object.keys(PRINCIPALS) as Who[]) { + const email = `csr-${who}@verify.test`; + token[who] = await stack.signUp(email); + const userId = await idOf(email); + expect(await catalogPermissionSet(ql, PRINCIPALS[who]), PRINCIPALS[who]).toBeTruthy(); + await ql.insert('sys_user_permission_set', { user_id: userId, permission_set: PRINCIPALS[who] }, SYS); + } + + // Every row through the doors. Lines are added while their invoice is + // open; the closing write lands whole (D4) and closes it. + id.customer = await created('writer', CUSTOMER, { name: T.customer }); + id.otherCustomer = await created('writer', CUSTOMER, { name: T.otherCustomer }); + id.closedInvoice = await created('writer', INVOICE, { name: T.closedInvoice, status: 'draft', amount: 10, customer: id.customer }); + id.openInvoice = await created('writer', INVOICE, { name: T.openInvoice, status: 'draft', amount: 10, customer: id.otherCustomer }); + id.closedLine = await created('writer', LINE, { name: 'Widgets', qty: 1, invoice: id.closedInvoice }); + id.openLine = await created('writer', LINE, { name: 'Gadgets', qty: 1, invoice: id.openInvoice }); + const closing = await call('writer', 'PATCH', `/data/${INVOICE}/${id.closedInvoice}`, { status: 'settled', amount: 12 }); + expect(closing.status, JSON.stringify(closing.body)).toBe(200); + // Notes owned by the administrator: private to the reader, who may edit the object. + id.closedNote = await created('admin', NOTE, { name: 'Quarter close', state: 'open' }); + id.openNote = await created('admin', NOTE, { name: 'Quarter plan', state: 'open' }); + expect((await call('admin', 'PATCH', `/data/${NOTE}/${id.closedNote}`, { state: 'done' })).status).toBe(200); + + // The scene is real: the withheld writer is served the invoice without + // its title field, the writer with it. + const read = async (who: Who) => (await call(who, 'GET', `/data/${INVOICE}/${id.closedInvoice}`)).body; + const withheld = read('withheld'); + const writer = read('writer'); + const w = (await withheld).record ?? (await withheld); + const v = (await writer).record ?? (await writer); + expect('name' in w, 'the withheld writer is served no title field').toBe(false); + expect(v.name).toBe(T.closedInvoice); + }, 180_000); + + afterAll(async () => { + if (stack) await stack.stop(); + }); + + it('an update of a closed record names it by the title the writer is served, in userMessage and error alike', async () => { + const a = await call('writer', 'PATCH', `/data/${INVOICE}/${id.closedInvoice}`, { amount: 99 }); + expect(personFacing(a)).toBe(fill(en.record_closed, { object: 'Invoice', title: T.closedInvoice })); + }); + + it('a writer whose field permissions withhold the title field is told the label form, never the stored title', async () => { + const a = await call('withheld', 'PATCH', `/data/${INVOICE}/${id.closedInvoice}`, { amount: 99 }); + const sentence = personFacing(a); + expect(sentence).toBe(fill(en.record_closed_untitled, { object: 'Invoice' })); + expect(sentence).not.toContain(T.closedInvoice); + }); + + it('a delete of a closed record answers the same sentence family', async () => { + const a = await call('writer', 'DELETE', `/data/${INVOICE}/${id.closedInvoice}`); + expect(personFacing(a)).toBe(fill(en.record_closed, { object: 'Invoice', title: T.closedInvoice })); + }); + + it('a line write names the master by its label alone: an update in place, and a new line', async () => { + const update = await call('writer', 'PATCH', `/data/${LINE}/${id.closedLine}`, { qty: 5 }); + expect(personFacing(update)).toBe(fill(en.record_closed_untitled, { object: 'Invoice' })); + const create = await call('writer', 'POST', `/data/${LINE}`, { name: 'Extra', qty: 1, invoice: id.closedInvoice }); + expect(personFacing(create)).toBe(fill(en.record_closed_untitled, { object: 'Invoice' })); + }); + + it('a delete refused for what it would also remove names the record asked to be deleted and the object in the way', async () => { + const writer = await call('writer', 'DELETE', `/data/${CUSTOMER}/${id.customer}`); + expect(personFacing(writer)).toBe(fill(en.record_closed_delete_blocked, { object: 'Customer', title: T.customer, blockingObject: 'Invoice' })); + // The title only for a caller served it. + const withheld = await call('withheld', 'DELETE', `/data/${CUSTOMER}/${id.customer}`); + expect(personFacing(withheld)).toBe(fill(en.record_closed_delete_blocked_untitled, { object: 'Customer', blockingObject: 'Invoice' })); + // Nothing was removed. + expect((await call('writer', 'GET', `/data/${INVOICE}/${id.closedInvoice}`)).status).toBe(200); + expect((await call('writer', 'GET', `/data/${CUSTOMER}/${id.customer}`)).status).toBe(200); + }); + + it('answers in the caller\'s language', async () => { + const a = await call('writer', 'PATCH', `/data/${INVOICE}/${id.closedInvoice}`, { amount: 99 }, 'zh-CN'); + expect(personFacing(a)).toBe(fill(BUILTIN_OPERATION_MESSAGES['zh-CN'].record_closed, { object: 'Invoice', title: T.closedInvoice })); + }); + + it('relays neither the developer sentence nor the lock\'s own members', async () => { + const a = await call('writer', 'PATCH', `/data/${INVOICE}/${id.closedInvoice}`, { amount: 99 }); + personFacing(a); + const wire = JSON.stringify(a.body); + expect(wire).not.toContain('closedStates'); + expect(a.body).not.toHaveProperty('developerMessage'); + expect(a.body).not.toHaveProperty('reason'); + expect(a.body).not.toHaveProperty('lockReason'); + expect(a.body).not.toHaveProperty('blockingObject'); + }); + + it('D10: a caller the object permission refuses gets the same answer on a closed record as on an open one', async () => { + const closed = await call('reader', 'PATCH', `/data/${INVOICE}/${id.closedInvoice}`, { amount: 1 }); + const open = await call('reader', 'PATCH', `/data/${INVOICE}/${id.openInvoice}`, { amount: 1 }); + expect(closed.status).toBe(403); + expect(closed.body.code).toBe('PERMISSION_DENIED'); + expect(closed).toEqual(open); + const closedDelete = await call('reader', 'DELETE', `/data/${INVOICE}/${id.closedInvoice}`); + const openDelete = await call('reader', 'DELETE', `/data/${INVOICE}/${id.openInvoice}`); + expect(closedDelete.status).toBe(403); + expect(closedDelete).toEqual(openDelete); + }); + + it('D10: a caller the row access refuses gets the same answer on a closed record as on an open one', async () => { + const closed = await call('reader', 'PATCH', `/data/${NOTE}/${id.closedNote}`, { name: 'x' }); + const open = await call('reader', 'PATCH', `/data/${NOTE}/${id.openNote}`, { name: 'x' }); + expect(closed.status).not.toBe(409); + expect(closed.body.code).not.toBe('RECORD_LOCKED'); + // The two answers differ only by the id the caller addressed, where the body echoes it. + expect(JSON.stringify(closed).split(id.closedNote).join('ID')).toBe(JSON.stringify(open).split(id.openNote).join('ID')); + const closedDelete = await call('reader', 'DELETE', `/data/${NOTE}/${id.closedNote}`); + const openDelete = await call('reader', 'DELETE', `/data/${NOTE}/${id.openNote}`); + expect(closedDelete.status).not.toBe(409); + expect(JSON.stringify(closedDelete).split(id.closedNote).join('ID')).toBe(JSON.stringify(openDelete).split(id.openNote).join('ID')); + // CONTROL: the owner is told the note is closed. + const owner = await call('admin', 'PATCH', `/data/${NOTE}/${id.closedNote}`, { name: 'x' }); + expect(owner.status).toBe(409); + expect(owner.body.code).toBe('RECORD_LOCKED'); + }); +}); From 67dd8de483dce5ffc056b4226907d1faa4177f4c Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 05:34:45 +0000 Subject: [PATCH 03/10] test(dogfood): the closed-state refusal's sentence at the engine and on the wire (ADR-0162 D8, D10) Claude-Session: https://claude.ai/code/session_01FEkQ5nGQtUA88SthJbYyRw Co-Authored-By: Claude --- .../closed-state-refusal-sentence.test.ts | 284 ++++++++++++++++++ .../closed-state-refusal-wire.dogfood.test.ts | 20 +- 2 files changed, 295 insertions(+), 9 deletions(-) create mode 100644 packages/qa/dogfood/test/closed-state-refusal-sentence.test.ts diff --git a/packages/qa/dogfood/test/closed-state-refusal-sentence.test.ts b/packages/qa/dogfood/test/closed-state-refusal-sentence.test.ts new file mode 100644 index 00000000000..cdda6853dcb --- /dev/null +++ b/packages/qa/dogfood/test/closed-state-refusal-sentence.test.ts @@ -0,0 +1,284 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 D8] The closed-state refusal's sentence, on a real engine and store. + * + * The lock refuses `409 RECORD_LOCKED`; what a person reads is the Operation + * Message Catalog's sentence, carried as the refusal's `userMessage` and as its + * `message` behind the code. This file pins which form each refusal takes and + * what each may name, on `ObjectQL` over SQLite (`SqlDriver`, better-sqlite3 + * `:memory:`): + * + * - a record's own write: the title the writer would be served, by the + * security service's answer in the engine's slot (here a stand-in that + * answers per writer; the real plugin is booted in + * `closed-state-refusal-wire.dogfood.test.ts`): readable and not masked + * gives the title, unreadable or masked gives the label form; + * - a predicate write: the label form; + * - a line write and a line's restore: the master's label alone; + * - a delete refused for what it would also remove: the record asked to be + * deleted and the object in the way, the title only for one record; + * - an object with no label: the forms that name no label; never its API name; + * - a refusal that could not judge the write keeps the developer's sentence + * and marks no `userMessage`. + * + * Every person-facing string is checked for the absence of every API name, + * record id and state value of the fixture. + */ + +import { afterEach, describe, expect, it } from 'vitest'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { BUILTIN_OPERATION_MESSAGES } from '@objectstack/spec/system'; +import { SysRecycleBin } from '@objectstack/platform-objects/system'; +import { DEFAULT_ORGANIZATION_ID, installDefaultOrganization } from './default-organization.testkit.js'; + +const SYS = { isSystem: true, userId: 'usr_system' } as const; +const caller = (userId: string, locale?: string) => + ({ userId, tenantId: DEFAULT_ORGANIZATION_ID, positions: [], permissions: [], ...(locale ? { locale } : {}) }) as const; +/** May read every field. */ +const WRITER = caller('usr_writer'); +/** May not read the invoice's or the customer's title field. */ +const UNREAD = caller('usr_unread'); +/** Is served the invoice's title field masked: readable, not queryable. */ +const MASKED = caller('usr_masked'); + +/** The slot `ObjectQLPlugin` fills with the registered `security` service's source. */ +const SECURITY_SLOT = Symbol.for('objectstack.objectql.securityServiceSource'); + +const INVOICE = 'dg_csr_invoice'; +const LINE = 'dg_csr_line'; +const CUSTOMER = 'dg_csr_customer'; +const PRODUCT = 'dg_csr_product'; +const BARE = 'dg_csr_bare'; + +const STATUS_OPTIONS = [{ label: 'Draft', value: 'draft' }, { label: 'Settled', value: 'settled' }]; + +const OBJECTS = [ + { name: CUSTOMER, label: 'Customer', fields: { name: { type: 'text', label: 'Name' } } }, + { name: PRODUCT, label: 'Product', fields: { name: { type: 'text', label: 'Name' } } }, + { + name: INVOICE, + label: 'Invoice', + fields: { + name: { type: 'text', label: 'Number' }, + status: { type: 'select', label: 'Status', options: STATUS_OPTIONS }, + amount: { type: 'number', label: 'Amount' }, + customer: { type: 'lookup', label: 'Customer', reference: CUSTOMER, deleteBehavior: 'cascade' }, + }, + closedStates: { status: ['settled'] }, + }, + { + name: LINE, + label: 'Invoice line', + fields: { + name: { type: 'text', label: 'Description' }, + qty: { type: 'number', label: 'Quantity' }, + invoice: { type: 'master_detail', label: 'Invoice', reference: INVOICE, required: true }, + product: { type: 'lookup', label: 'Product', reference: PRODUCT, deleteBehavior: 'cascade' }, + }, + }, + { + // No label: the sentence names no label, and never the API name. + name: BARE, + fields: { + name: { type: 'text', label: 'Name' }, + status: { type: 'select', label: 'Status', options: STATUS_OPTIONS }, + }, + closedStates: { status: ['settled'] }, + }, +]; + +/** Synthetic titles and ids. */ +const T = { closed: 'Northwind March', open: 'Fabrikam April', customer: 'Contoso Holdings', bare: 'Litware Group' } as const; +const IDS = ['cu1', 'cu2', 'cu3', 'pr1', 'inv_closed', 'inv_open', 'inv_other', 'l_closed', 'l_open', 'bare_closed']; + +let engine: ObjectQL; + +/** A stand-in for the security service's two field answers, per writer. */ +function fieldSecurity() { + const asked: Array<{ object: string; userId: unknown }> = []; + const titleFields = new Set([`${INVOICE}.name`, `${CUSTOMER}.name`]); + const all = (object: string) => Object.keys((OBJECTS.find((o) => o.name === object)?.fields ?? {}) as object).concat('id'); + return { + asked, + svc: { + async getReadableFields(object: string, context?: { userId?: unknown }) { + asked.push({ object, userId: context?.userId }); + return all(object).filter((f) => !(context?.userId === UNREAD.userId && titleFields.has(`${object}.${f}`))); + }, + async getQueryableFields(object: string, context?: { userId?: unknown }) { + return all(object).filter((f) => !((context?.userId === UNREAD.userId || context?.userId === MASKED.userId) && titleFields.has(`${object}.${f}`))); + }, + }, + }; +} + +async function boot(opts: { security?: unknown; recycleBin?: boolean } = {}): Promise { + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); + engine = new ObjectQL(); + engine.registerDriver(driver, true); + await engine.init(); + engine.registerApp({ + id: 'com.objectstack.dogfood.closed-state-refusal-sentence', + name: 'Closed-state refusal sentence', + version: '1.0.0', + type: 'plugin', + scope: 'system', + objects: [...OBJECTS, ...(opts.recycleBin ? [SysRecycleBin] : [])], + } as never); + await engine.syncSchemas(); + await installDefaultOrganization(engine); + const put = (object: string, row: Record) => engine.insert(object, row, { context: SYS } as never); + await put(CUSTOMER, { id: 'cu1', name: T.customer }); + await put(CUSTOMER, { id: 'cu2', name: 'Adventure Works' }); + await put(CUSTOMER, { id: 'cu3', name: 'Tailspin' }); + await put(PRODUCT, { id: 'pr1', name: 'Widget' }); + await put(INVOICE, { id: 'inv_closed', name: T.closed, status: 'settled', amount: 10, customer: 'cu1' }); + await put(INVOICE, { id: 'inv_open', name: T.open, status: 'draft', amount: 10, customer: 'cu2' }); + await put(INVOICE, { id: 'inv_other', name: 'Other', status: 'settled', amount: 10, customer: 'cu3' }); + await put(LINE, { id: 'l_closed', name: 'Widgets', qty: 1, invoice: 'inv_closed', product: 'pr1' }); + await put(LINE, { id: 'l_open', name: 'Gadgets', qty: 1, invoice: 'inv_open' }); + await put(BARE, { id: 'bare_closed', name: T.bare, status: 'settled' }); + if (opts.security !== undefined) (engine as unknown as Record)[SECURITY_SLOT] = () => opts.security; +} + +afterEach(async () => { + await engine?.destroy(); +}); + +interface Refusal { code?: unknown; status?: unknown; reason?: unknown; message?: unknown; userMessage?: unknown; developerMessage?: unknown } + +async function refusal(run: () => Promise): Promise { + try { + await run(); + } catch (e) { + return e as Refusal; + } + throw new Error('expected the write to be refused, and it landed'); +} + +const en = BUILTIN_OPERATION_MESSAGES.en; +const fill = (template: string, params: Record = {}) => template.replace(/\{\{(\w+)\}\}/g, (m, k: string) => params[k] ?? m); +const FORBIDDEN = [INVOICE, LINE, CUSTOMER, PRODUCT, BARE, 'dg_csr', 'settled', 'closedStates', ...IDS]; + +/** The sentence a person reads, checked for the code and for every value it must not carry. */ +function sentenceOf(err: Refusal): string { + expect([err.code, err.status]).toEqual(['RECORD_LOCKED', 409]); + expect(typeof err.userMessage).toBe('string'); + expect(err.message, 'message carries the same sentence behind the code').toBe(`RECORD_LOCKED: ${String(err.userMessage)}`); + for (const value of FORBIDDEN) expect(String(err.userMessage), `carries ${value}`).not.toContain(value); + return String(err.userMessage); +} + +const by = (context: unknown) => ({ context }) as never; + +describe('[ADR-0162 D8] the closed-state refusal names what the writer is served, and nothing else', () => { + it('a record\'s own write: the title when no field-level security is registered (a read serves every field)', async () => { + await boot(); + const update = await refusal(() => engine.update(INVOICE, { id: 'inv_closed', amount: 99 }, by(WRITER))); + expect(sentenceOf(update)).toBe(fill(en.record_closed, { object: 'Invoice', title: T.closed })); + const del = await refusal(() => engine.delete(INVOICE, { where: { id: 'inv_closed' }, context: WRITER } as never)); + expect(sentenceOf(del)).toBe(fill(en.record_closed, { object: 'Invoice', title: T.closed })); + }); + + it('the title only where the writer may be served the field: readable and unmasked yes, unreadable or masked no', async () => { + const { svc, asked } = fieldSecurity(); + await boot({ security: svc }); + const served = await refusal(() => engine.update(INVOICE, { id: 'inv_closed', amount: 99 }, by(WRITER))); + expect(sentenceOf(served)).toBe(fill(en.record_closed, { object: 'Invoice', title: T.closed })); + for (const writer of [UNREAD, MASKED]) { + const err = await refusal(() => engine.update(INVOICE, { id: 'inv_closed', amount: 99 }, by(writer))); + const sentence = sentenceOf(err); + expect(sentence, writer.userId).toBe(fill(en.record_closed_untitled, { object: 'Invoice' })); + expect(sentence, writer.userId).not.toContain(T.closed); + } + // Asked as the writer, with the writer's own context. + expect(asked.map((a) => a.userId)).toEqual([WRITER.userId, UNREAD.userId, MASKED.userId]); + }); + + it('a security service that cannot say what is masked names no title (fail closed)', async () => { + await boot({ security: { getReadableFields: async () => ['id', 'name', 'status', 'amount', 'customer'] } }); + const err = await refusal(() => engine.update(INVOICE, { id: 'inv_closed', amount: 99 }, by(WRITER))); + expect(sentenceOf(err)).toBe(fill(en.record_closed_untitled, { object: 'Invoice' })); + }); + + it('a predicate write names no one record: the label form', async () => { + await boot(); + const err = await refusal(() => engine.update(INVOICE, { amount: 1 }, { where: { amount: 10 }, multi: true, context: WRITER } as never)); + expect(sentenceOf(err)).toBe(fill(en.record_closed_untitled, { object: 'Invoice' })); + }); + + it('a line write names the master by its label alone: update, delete, create and move', async () => { + await boot(); + const master = fill(en.record_closed_untitled, { object: 'Invoice' }); + expect(sentenceOf(await refusal(() => engine.update(LINE, { id: 'l_closed', qty: 2 }, by(WRITER))))) + .toBe(master); + expect(sentenceOf(await refusal(() => engine.delete(LINE, { where: { id: 'l_closed' }, context: WRITER } as never)))) + .toBe(master); + expect(sentenceOf(await refusal(() => engine.insert(LINE, { name: 'Extra', qty: 1, invoice: 'inv_closed' }, by(WRITER))))) + .toBe(master); + expect(sentenceOf(await refusal(() => engine.update(LINE, { id: 'l_open', invoice: 'inv_closed' }, by(WRITER))))) + .toBe(master); + }); + + it('a delete refused for what it would also remove: the record asked, its title as served, and the object in the way', async () => { + const { svc } = fieldSecurity(); + await boot({ security: svc }); + // The closed record itself would go. + const writer = await refusal(() => engine.delete(CUSTOMER, { where: { id: 'cu1' }, context: WRITER } as never)); + expect(sentenceOf(writer)).toBe(fill(en.record_closed_delete_blocked, { object: 'Customer', title: T.customer, blockingObject: 'Invoice' })); + expect(writer.reason).toBe('cascade_reaches_closed'); + // The title only for a caller served it. + const unread = await refusal(() => engine.delete(CUSTOMER, { where: { id: 'cu1' }, context: UNREAD } as never)); + expect(sentenceOf(unread)).toBe(fill(en.record_closed_delete_blocked_untitled, { object: 'Customer', blockingObject: 'Invoice' })); + // A line of the closed record would go while the record stays: the master is the object in the way. + const line = await refusal(() => engine.delete(PRODUCT, { where: { id: 'pr1' }, context: WRITER } as never)); + expect(sentenceOf(line)).toBe(fill(en.record_closed_delete_blocked, { object: 'Product', title: 'Widget', blockingObject: 'Invoice' })); + }); + + it('a delete that names many records takes the label form', async () => { + await boot(); + const err = await refusal(() => engine.delete(CUSTOMER, { where: { id: { $in: ['cu1', 'cu3'] } }, multi: true, context: WRITER } as never)); + expect(sentenceOf(err)).toBe(fill(en.record_closed_delete_blocked_untitled, { object: 'Customer', blockingObject: 'Invoice' })); + }); + + it('an object with no label is never named by its API name', async () => { + await boot(); + expect(sentenceOf(await refusal(() => engine.update(BARE, { id: 'bare_closed', name: 'x' }, by(WRITER))))) + .toBe(fill(en.record_closed_unlabeled, { title: T.bare })); + expect(sentenceOf(await refusal(() => engine.update(BARE, { name: 'x' }, { where: { name: T.bare }, multi: true, context: WRITER } as never)))) + .toBe(en.record_closed_opaque); + }); + + it('answers in the caller\'s language', async () => { + await boot(); + const zh = await refusal(() => engine.update(INVOICE, { id: 'inv_closed', amount: 99 }, by(caller('usr_writer', 'zh-CN')))); + expect(sentenceOf(zh)).toBe(fill(BUILTIN_OPERATION_MESSAGES['zh-CN'].record_closed, { object: 'Invoice', title: T.closed })); + const es = await refusal(() => engine.update(LINE, { id: 'l_closed', qty: 2 }, by(caller('usr_writer', 'es')))); + expect(sentenceOf(es)).toBe(fill(BUILTIN_OPERATION_MESSAGES['es-ES'].record_closed_untitled, { object: 'Invoice' })); + }); + + it('a line\'s restore under a live closed master names the master by its label alone', async () => { + await boot({ recycleBin: true }); + await engine.delete(LINE, { where: { id: 'l_open' }, context: WRITER } as never); + await engine.update(INVOICE, { id: 'inv_open', status: 'settled' }, by(WRITER)); + const bin = (await engine.find('sys_recycle_bin', { context: SYS } as never)) as Array>; + const entry = bin.find((r) => r.object_name === LINE && r.record_id === 'l_open'); + expect(entry).toBeDefined(); + const err = await refusal(() => engine.restore(String(entry!.id), { context: WRITER } as never)); + expect(sentenceOf(err)).toBe(fill(en.record_closed_untitled, { object: 'Invoice' })); + }); + + it('the developer\'s sentence is kept on developerMessage; a refusal that could not judge keeps it as its message', async () => { + await boot(); + const err = await refusal(() => engine.update(INVOICE, { id: 'inv_closed', amount: 99 }, by(WRITER))); + sentenceOf(err); + expect(String(err.developerMessage)).toContain(`'${INVOICE}'`); + // A line write that names its master by something that is not one id cannot be judged. + const cannot = await refusal(() => engine.insert(LINE, { name: 'x', qty: 1, invoice: { $in: ['inv_closed'] } }, by(WRITER))); + expect([cannot.code, cannot.status, cannot.reason]).toEqual(['RECORD_LOCKED', 409, 'cannot_judge']); + expect(cannot.userMessage).toBeUndefined(); + expect(String(cannot.message)).toContain(LINE); + }); +}); diff --git a/packages/qa/dogfood/test/closed-state-refusal-wire.dogfood.test.ts b/packages/qa/dogfood/test/closed-state-refusal-wire.dogfood.test.ts index 43bff7fb362..2094e1948cb 100644 --- a/packages/qa/dogfood/test/closed-state-refusal-wire.dogfood.test.ts +++ b/packages/qa/dogfood/test/closed-state-refusal-wire.dogfood.test.ts @@ -14,8 +14,8 @@ // Principals, by permission set: // // - the writer: create, read, edit and delete on every object; -// - the withheld writer: the same, with the invoice's and the customer's -// title field `readable: false` (field-level security); +// - the withheld writer: the same, with the invoice's title field +// `readable: false` (field-level security); // - the reader: read only on the invoice (the object permission refuses an // edit), and edit on the note it does not own (row access refuses it). // @@ -30,8 +30,8 @@ // really withheld). // - A line write names the master by its label alone (D8). // - A delete refused for what it would also remove names the record asked to -// be deleted and the label of the object in the way (D6, D8), the title -// only for a caller served it. +// be deleted and the label of the object in the way (D6, D8). Its untitled +// form is pinned at the engine (closed-state-refusal-sentence.test.ts). // - D10 at the security layer: a caller the object permission or the row // access refuses gets the same answer on a closed record as on an open one, // status and body. @@ -130,11 +130,10 @@ const writerSet = PermissionSetSchema.parse({ }); const withheldSet = PermissionSetSchema.parse({ name: 'csr_withheld', - label: 'Closed-state writer, titles withheld', + label: 'Closed-state writer, invoice title withheld', objects: { [INVOICE]: FULL, [LINE]: FULL, [CUSTOMER]: FULL, [NOTE]: FULL }, fields: { [`${INVOICE}.name`]: { readable: false, editable: false }, - [`${CUSTOMER}.name`]: { readable: false, editable: false }, }, }); const readerSet = PermissionSetSchema.parse({ @@ -212,6 +211,7 @@ describe('[ADR-0162 D8, D10] the closed-state refusal on the wire', () => { const email = `csr-${who}@verify.test`; token[who] = await stack.signUp(email); const userId = await idOf(email); + id[`${who}User`] = userId; expect(await catalogPermissionSet(ql, PRINCIPALS[who]), PRINCIPALS[who]).toBeTruthy(); await ql.insert('sys_user_permission_set', { user_id: userId, permission_set: PRINCIPALS[who] }, SYS); } @@ -273,9 +273,11 @@ describe('[ADR-0162 D8, D10] the closed-state refusal on the wire', () => { it('a delete refused for what it would also remove names the record asked to be deleted and the object in the way', async () => { const writer = await call('writer', 'DELETE', `/data/${CUSTOMER}/${id.customer}`); expect(personFacing(writer)).toBe(fill(en.record_closed_delete_blocked, { object: 'Customer', title: T.customer, blockingObject: 'Invoice' })); - // The title only for a caller served it. - const withheld = await call('withheld', 'DELETE', `/data/${CUSTOMER}/${id.customer}`); - expect(personFacing(withheld)).toBe(fill(en.record_closed_delete_blocked_untitled, { object: 'Customer', blockingObject: 'Invoice' })); + // The untitled form (root title not served) is pinned at the engine in + // closed-state-refusal-sentence.test.ts: on this wire a writer whose + // field permissions withhold the customer's title field is refused the + // delete of its own customer by the security layer before the engine is + // reached (reported out of scope). // Nothing was removed. expect((await call('writer', 'GET', `/data/${INVOICE}/${id.closedInvoice}`)).status).toBe(200); expect((await call('writer', 'GET', `/data/${CUSTOMER}/${id.customer}`)).status).toBe(200); From bd404c40be2e5bbb7a2338e1d83f02d0caa21e67 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 05:51:49 +0000 Subject: [PATCH 04/10] test(dogfood): the approval status mirror and the assignment rules on a closed record (ADR-0162 D5, D7) Claude-Session: https://claude.ai/code/session_01FEkQ5nGQtUA88SthJbYyRw Co-Authored-By: Claude --- .../test/closed-state-system-writes.test.ts | 187 ++++++++++++++++++ 1 file changed, 187 insertions(+) create mode 100644 packages/qa/dogfood/test/closed-state-system-writes.test.ts diff --git a/packages/qa/dogfood/test/closed-state-system-writes.test.ts b/packages/qa/dogfood/test/closed-state-system-writes.test.ts new file mode 100644 index 00000000000..9fb92096386 --- /dev/null +++ b/packages/qa/dogfood/test/closed-state-system-writes.test.ts @@ -0,0 +1,187 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 D5, D7] Two writes the platform makes on its own, measured against + * a record in a closed state: the approval status mirror and the assignment + * rules. Each was listed as a system write with no test of it. + * + * - The approval status mirror writes `pending` when an approval opens on a + * record and `approved` when it is decided. On a record already closed by + * another field, both writes land: they are system writes, which the lock + * does not bind (D5). The caller's own write of the same record, between + * and after, is refused `409 RECORD_LOCKED` with the closed-state sentence. + * - The assignment rules write no stored record at all: the engine evaluates + * them on a row it is inserting, before the write, and an update never + * evaluates a rule (`assignment-rules.ts`). A row inserted already in its + * closed state by a caller is routed to its owner and lands; nothing about + * the rule writes the record afterwards, and the caller's later write of + * it is refused. + * + * Real kernel, real ObjectQL engine with the closed-state lock, real + * automation engine and approval node, driver-sql on better-sqlite3 + * `:memory:`. The approval's record lock (`lockRecord`) is off, so the one + * lock a caller meets is the closed-state one. + */ + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { ObjectKernel } from '@objectstack/core'; +import { ObjectQLPlugin, type ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { AutomationServicePlugin, type AutomationEngine } from '@objectstack/service-automation'; +import { + ApprovalService, + registerApprovalNode, + SysApprovalRequest, + SysApprovalAction, + SysApprovalApprover, + SysApprovalDelegation, +} from '@objectstack/plugin-approvals'; +import { BUILTIN_OPERATION_MESSAGES } from '@objectstack/spec/system'; + +const ORG = 'org_default'; +const SYS = { isSystem: true } as const; +const asPerson = (userId: string) => ({ userId, tenantId: ORG, positions: [], permissions: [] }) as any; + +const text = (name: string) => ({ name, type: 'text' as const }); +const PLATFORM_GLOBAL = { enabled: false }; +const platformObjects = [ + { owner: '@objectstack/plugin-auth', def: { name: 'sys_user', label: 'User', tenancy: PLATFORM_GLOBAL, fields: { id: { ...text('id'), primaryKey: true }, email: text('email'), banned: { name: 'banned', type: 'boolean' as const } } } }, + { owner: '@objectstack/plugin-auth', def: { name: 'sys_member', label: 'Member', tenancy: PLATFORM_GLOBAL, fields: { id: { ...text('id'), primaryKey: true }, user_id: text('user_id'), organization_id: text('organization_id'), role: text('role') } } }, +] as const; + +const INVOICE = 'dg_csw_invoice'; +const TICKET = 'dg_csw_ticket'; + +/** Closed by its own `status`; the approval mirrors onto another field. */ +const invoice = { + name: INVOICE, + label: 'Invoice', + fields: { + name: text('name'), + note: text('note'), + status: { name: 'status', type: 'select' as const, options: [{ label: 'Draft', value: 'draft' }, { label: 'Settled', value: 'settled' }] }, + approval_status: { name: 'approval_status', type: 'select' as const, options: ['draft', 'pending', 'approved', 'rejected'].map((value) => ({ label: value, value })) }, + }, + closedStates: { status: ['settled'] }, +}; +const ticket = { + name: TICKET, + label: 'Ticket', + fields: { + name: text('name'), + note: text('note'), + status: { name: 'status', type: 'select' as const, options: [{ label: 'Open', value: 'open' }, { label: 'Done', value: 'done' }] }, + }, + closedStates: { status: ['done'] }, +}; + +const review = { + name: 'csw_review', label: 'Review', type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'review', type: 'approval', label: 'Review', config: { approvers: [{ type: 'user', value: 'approver' }], lockRecord: false, approvalStatusField: 'approval_status' } }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'review' }, + { id: 'e2', source: 'review', target: 'end', label: 'approve' }, + { id: 'e3', source: 'review', target: 'end', label: 'reject' }, + ], +}; + +const en = BUILTIN_OPERATION_MESSAGES.en; +const fill = (template: string, params: Record) => + template.replace(/\{\{(\w+)\}\}/g, (m, k: string) => params[k] ?? m); + +describe('[ADR-0162 D5, D7] the platform\'s own writes on a record in a closed state', () => { + let kernel: ObjectKernel; + let ql: ObjectQL; + let automation: AutomationEngine; + let svc: ApprovalService; + + afterEach(async () => { + try { await kernel?.shutdown(); } catch { /* noop */ } + }); + + beforeEach(async () => { + kernel = new ObjectKernel({ logger: { level: 'silent' } } as any); + await kernel.use(new ObjectQLPlugin()); + await kernel.use(new AutomationServicePlugin()); + await kernel.bootstrap(); + ql = kernel.getService('objectql'); + automation = kernel.getService('automation'); + + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); + await driver.connect(); + ql.registerDriver(driver, true); + for (const def of [invoice, ticket, SysApprovalRequest, SysApprovalAction, SysApprovalApprover, SysApprovalDelegation]) { + ql.registry.registerObject(def as any, 'closed-state-system-writes', 'closed-state-system-writes'); + } + for (const o of platformObjects) ql.registry.registerObject(o.def as any, o.owner); + ql.registry.registerObject( + { name: 'sys_organization', label: 'Organization', managedBy: 'better-auth', fields: { name: text('name'), slug: text('slug') } } as any, + '@objectstack/plugin-auth', + ); + (ql as any).registerApp({ + id: 'com.objectstack.dogfood.closed-state-system-writes', name: 'closed_state_system_writes', queues: [], + assignmentRules: [{ name: 'ticket_owner', object: TICKET, active: true, entries: [{ name: 'all', assignTo: { type: 'user', value: 'lead' } }] }], + }); + await ql.syncSchemas(); + await ql.insert('sys_organization', { id: ORG, name: 'Default Organization', slug: 'default' }, { context: SYS }); + for (const id of ['owner', 'approver', 'lead']) { + await ql.insert('sys_user', { id, email: `${id}@example.test`, banned: false }, { context: SYS }); + await ql.insert('sys_member', { id: `mem_${id}`, user_id: id, organization_id: ORG, role: 'member' }, { context: SYS }); + } + + const quiet = { debug: () => {}, info: () => {}, warn: () => {}, error: () => {} }; + svc = new ApprovalService({ engine: ql, logger: quiet as any, messaging: { emit: async () => {} } as any }); + svc.attachAutomation(automation as any); + registerApprovalNode(automation as any, svc, quiet as any); + automation.registerFlow(review.name, review as any); + }); + + const read = async (object: string, id: string) => (await ql.find(object, { where: { id }, context: SYS }))[0] as any; + const pendingRequest = async (id: string) => + (await ql.find('sys_approval_request', { where: { record_id: id, status: 'pending' }, context: SYS }) as any[]).map((r) => String(r.id)); + /** The caller's own write, refused by the closed-state lock with its sentence. */ + async function expectCallerRefused(object: string, id: string, label: string, title: string): Promise { + let caught: any; + try { + await ql.update(object, { id, note: 'edited by hand' }, { context: asPerson('owner') }); + } catch (err) { + caught = err; + } + expect(caught, 'the caller\'s write is refused').toBeDefined(); + expect(caught.code).toBe('RECORD_LOCKED'); + expect(caught.status ?? caught.statusCode).toBe(409); + expect(caught.userMessage).toBe(fill(en.record_closed, { object: label, title })); + expect((await read(object, id)).note ?? null, 'nothing of the refused write landed').toBeNull(); + } + + it('the approval status mirror\'s `pending` and `approved` land on a record closed by another field; the caller\'s write is refused between and after', async () => { + await ql.insert(INVOICE, { id: 'inv1', name: 'Northwind March', status: 'settled', approval_status: 'draft', organization_id: ORG }, { context: { ...SYS, tenantId: ORG } }); + + const run = (await automation.execute(review.name, { object: INVOICE, record: await read(INVOICE, 'inv1'), userId: 'owner' } as any)) as any; + expect(run.status, JSON.stringify(run)).toBe('paused'); + const opened = await read(INVOICE, 'inv1'); + expect(opened.approval_status, 'the mirror\'s `pending` landed on the closed record').toBe('pending'); + expect(opened.status).toBe('settled'); + await expectCallerRefused(INVOICE, 'inv1', 'Invoice', 'Northwind March'); + + const [request] = await pendingRequest('inv1'); + expect(request).toBeTruthy(); + await svc.decide(request, { decision: 'approve', actorId: 'approver' } as any, asPerson('approver')); + const decided = await read(INVOICE, 'inv1'); + expect(decided.approval_status, 'the mirror\'s `approved` landed on the closed record').toBe('approved'); + expect(decided.status).toBe('settled'); + await expectCallerRefused(INVOICE, 'inv1', 'Invoice', 'Northwind March'); + }); + + it('an assignment rule routes a row a caller inserts already closed, and the insert lands; the rule never writes it again, and the caller\'s write is refused', async () => { + const row = (await ql.insert(TICKET, { id: 't1', name: 'Quarter close', status: 'done', organization_id: ORG }, { context: asPerson('owner') })) as any; + expect(row.owner_id, 'the rule routed the row it was inserting').toBe('lead'); + expect((await read(TICKET, 't1')).owner_id).toBe('lead'); + await expectCallerRefused(TICKET, 't1', 'Ticket', 'Quarter close'); + expect((await read(TICKET, 't1')).owner_id, 'an update evaluates no rule').toBe('lead'); + }); +}); From 067a24b18f440b80a443b23527622560685eb181 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 05:52:11 +0000 Subject: [PATCH 05/10] chore(changeset): the closed-state refusal's sentences (ADR-0162 D8) Claude-Session: https://claude.ai/code/session_01FEkQ5nGQtUA88SthJbYyRw Co-Authored-By: Claude --- .../37768-closed-state-refusal-sentences.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 .changeset/37768-closed-state-refusal-sentences.md diff --git a/.changeset/37768-closed-state-refusal-sentences.md b/.changeset/37768-closed-state-refusal-sentences.md new file mode 100644 index 00000000000..58c0f97f08a --- /dev/null +++ b/.changeset/37768-closed-state-refusal-sentences.md @@ -0,0 +1,17 @@ +--- +'@objectstack/spec': patch +'@objectstack/objectql': patch +'@objectstack/service-storage': patch +--- + +feat(spec,objectql): the closed-state refusal's own sentences, in every locale (ADR-0162 D8) + +Clause-②: yes (widening: new keys in the published Operation Message Catalog and the upload-link copy; contract-review-tier review owed) +Metadata-protocol: none + +A write refused because a record is in a closed state (`409 RECORD_LOCKED`, ADR-0162) now tells the person what happened in their own language, instead of the developer sentence that named objects by their API names. + +- **New catalog keys** in `BUILTIN_OPERATION_MESSAGES`, in every locale the catalog carries (en, zh-CN, ja-JP, es-ES), overridable per deployment under `errors.` like every other key: `record_closed` with its `_unlabeled`, `_untitled` and `_opaque` forms, and `record_closed_delete_blocked` with its `_untitled` and `_opaque` forms. English, for example: "Invoice 'Northwind March' is closed, so it and its lines can no longer be changed or deleted", and "Customer 'Contoso Holdings' cannot be deleted: deleting it would also remove a closed Invoice or one of its lines". +- **The engine words the refusal from them.** The title is the one the writer would be served under its own field permissions (readable and queryable); when it is not, the sentence names the object's label only. A line's write names its master by label alone. A delete refused for what it would also remove names the record asked to be deleted and the label of the object in the way, and drops the title when the delete names many records. No sentence carries a record id, an API name or a state value. +- **On the error**: `userMessage` and the wire's `error` carry the sentence; `message` reads `RECORD_LOCKED: ` followed by the sentence, as the approval lock's refusal does; the developer sentence moves to `developerMessage`, which the REST layer does not relay. A refusal that could not judge the write keeps the developer sentence and sets no `userMessage`. +- **Upload-link page**: a closed-state sentence (`recordClosed`) in each of its 11 languages. The page still answers `RECORD_LOCKED` with the approval sentence; choosing between the two by the lock's reason comes later. From 088d94cb956a9bb8cdf77583468c966f8a075c01 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 06:15:29 +0000 Subject: [PATCH 06/10] fix(objectql): a title read that fails on the closed-state refusal path is reported (ADR-0162 D8) Claude-Session: https://claude.ai/code/session_01FEkQ5nGQtUA88SthJbYyRw Co-Authored-By: Claude --- packages/objectql/src/closed-state-lock.ts | 16 ++++++++++---- .../objectql/src/engine-cascade-planning.ts | 2 +- .../closed-state-refusal-sentence.test.ts | 21 +++++++++++++++++++ 3 files changed, 34 insertions(+), 5 deletions(-) diff --git a/packages/objectql/src/closed-state-lock.ts b/packages/objectql/src/closed-state-lock.ts index def5b493741..4de5247efd1 100644 --- a/packages/objectql/src/closed-state-lock.ts +++ b/packages/objectql/src/closed-state-lock.ts @@ -140,6 +140,8 @@ export interface ClosedStateLockHost { * the writer is served ({@link servedTitleOf}). Absent: no title is named. */ readonly facade?: object; + /** [D8] Where a title read that failed on the refusal path is reported. */ + readonly logger?: { warn(message: string, meta?: Record): void }; } /** The verbs a refusal names. */ @@ -729,7 +731,7 @@ export async function judgeClosedStatePredicateWrite(this: ClosedStateLockHost, * object's label alone. */ export async function judgeClosedStateCascadeSet( - this: Pick, + this: Pick, root: string, members: ReadonlyMap>, context: ExecutionContext | undefined, @@ -801,10 +803,12 @@ export async function judgeClosedStateCascadeSet( * [D8] The title column of the one record a delete names, read by the engine * from the store (inside the caller's organization scope and unit of work), so * the refusal can name it as the caller is served it ({@link servedTitleOf}). - * Read only on the refusal path; a read that fails names no title. + * Read only on the refusal path. A read that fails is reported at `warn` and + * names no title: the refusal stands whole either way, and only its wording + * falls back to the label form. */ async function storedTitleRow( - this: Pick, + this: Pick, object: string, id: string | number, context: ExecutionContext | undefined, @@ -818,7 +822,11 @@ async function storedTitleRow( this.buildDriverOptions(object, context), )) as Array> | null; return Array.isArray(rows) && rows[0] && typeof rows[0] === 'object' ? rows[0] : undefined; - } catch { + } catch (error) { + this.logger?.warn( + `[closed-state] the title of the '${object}' record a refused delete names could not be read; the refusal names its object's label instead`, + { object, error: (error as Error)?.message ?? String(error) }, + ); return undefined; } } diff --git a/packages/objectql/src/engine-cascade-planning.ts b/packages/objectql/src/engine-cascade-planning.ts index a84028e23a5..3172a61193b 100644 --- a/packages/objectql/src/engine-cascade-planning.ts +++ b/packages/objectql/src/engine-cascade-planning.ts @@ -540,7 +540,7 @@ export class CascadePlanningFacet { * (formula values, file references, hooks), so they are not the values a * restore must write back. */ - static async cascadeDeleteRelations(this: Pick, object: string, ids: ReadonlyArray, context?: ExecutionContext, depth = 0, onCollected?: (set: CascadeDeleteSet) => Promise): Promise { + static async cascadeDeleteRelations(this: Pick, object: string, ids: ReadonlyArray, context?: ExecutionContext, depth = 0, onCollected?: (set: CascadeDeleteSet) => Promise): Promise { const roots: Array = []; const seen = new Set(); for (const id of ids) { diff --git a/packages/qa/dogfood/test/closed-state-refusal-sentence.test.ts b/packages/qa/dogfood/test/closed-state-refusal-sentence.test.ts index cdda6853dcb..e2a4d24a01d 100644 --- a/packages/qa/dogfood/test/closed-state-refusal-sentence.test.ts +++ b/packages/qa/dogfood/test/closed-state-refusal-sentence.test.ts @@ -237,6 +237,27 @@ describe('[ADR-0162 D8] the closed-state refusal names what the writer is served expect(sentenceOf(line)).toBe(fill(en.record_closed_delete_blocked, { object: 'Product', title: 'Widget', blockingObject: 'Invoice' })); }); + it('a title read that fails on the refusal path is reported, and the refusal stands in the label form', async () => { + await boot(); + const driver = engine.getDriverForObject(CUSTOMER) as unknown as { find: (...a: unknown[]) => Promise }; + const find = driver.find.bind(driver); + driver.find = async (object: unknown, query: any, ...rest: unknown[]) => { + // Only the refusal's own title read: the record by id, its id and title column. + if (object === CUSTOMER && Array.isArray(query?.fields) && query.fields.join() === 'id,name' && query?.limit === 1) { + throw new Error('store unavailable'); + } + return find(object, query, ...rest); + }; + const warned: Array<[string, unknown]> = []; + const logger = (engine as unknown as { logger: { warn: (m: string, meta?: unknown) => void } }).logger; + const warn = logger.warn.bind(logger); + logger.warn = (m: string, meta?: unknown) => { warned.push([m, meta]); warn(m, meta); }; + const err = await refusal(() => engine.delete(CUSTOMER, { where: { id: 'cu1' }, context: WRITER } as never)); + expect(sentenceOf(err)).toBe(fill(en.record_closed_delete_blocked_untitled, { object: 'Customer', blockingObject: 'Invoice' })); + expect(warned.filter(([m]) => m.startsWith('[closed-state] the title of')), 'the failed read is reported').toHaveLength(1); + expect((await engine.find(CUSTOMER, { where: { id: 'cu1' }, context: SYS } as never)).length, 'nothing was deleted').toBe(1); + }); + it('a delete that names many records takes the label form', async () => { await boot(); const err = await refusal(() => engine.delete(CUSTOMER, { where: { id: { $in: ['cu1', 'cu3'] } }, multi: true, context: WRITER } as never)); From b95bcb4bfe501ca82754591b3ba124b37f5e577e Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 07:09:43 +0000 Subject: [PATCH 07/10] test(dogfood): the system-writes host runs the approvals sweeps, as the opening check now requires (ADR-0162 item 7) Claude-Session: https://claude.ai/code/session_01FEkQ5nGQtUA88SthJbYyRw Co-Authored-By: Claude --- packages/qa/dogfood/test/closed-state-system-writes.test.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/packages/qa/dogfood/test/closed-state-system-writes.test.ts b/packages/qa/dogfood/test/closed-state-system-writes.test.ts index 9fb92096386..a4a54e4f637 100644 --- a/packages/qa/dogfood/test/closed-state-system-writes.test.ts +++ b/packages/qa/dogfood/test/closed-state-system-writes.test.ts @@ -135,6 +135,10 @@ describe('[ADR-0162 D5, D7] the platform\'s own writes on a record in a closed s const quiet = { debug: () => {}, info: () => {}, warn: () => {}, error: () => {} }; svc = new ApprovalService({ engine: ql, logger: quiet as any, messaging: { emit: async () => {} } as any }); + // The host runs the plugin's sweeps, as one with a `job` service does: an + // approval on an object that declares `closedStates` does not open on a + // host that runs none (ADR-0162 item 7), which is not what this file pins. + svc.noteSweepClockScheduled(); svc.attachAutomation(automation as any); registerApprovalNode(automation as any, svc, quiet as any); automation.registerFlow(review.name, review as any); From f9936414b0484149fe95415e232021dbec3eba68 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 07:35:43 +0000 Subject: [PATCH 08/10] fix(objectql): the closed-state refusal names a title only from a display-text field the writer's generic read returns (ADR-0162 D8) The title field gives no title when the generic read withholds it (internal or credential), when it is a reference field, or when the object's closedStates names it. A security-service source that throws names no title. The cascade's title form reads the ids the delete named. The upload-link copy and the changeset state what the page shows. Claude-Session: https://claude.ai/code/session_01FEkQ5nGQtUA88SthJbYyRw Co-Authored-By: Claude --- .../37768-closed-state-refusal-sentences.md | 6 +- packages/objectql/src/closed-state-lock.ts | 64 +++++++--- .../objectql/src/engine-cascade-planning.ts | 6 +- .../src/engine-delete-and-aggregate.ts | 2 +- packages/objectql/src/engine.ts | 4 +- .../closed-state-refusal-sentence.test.ts | 115 +++++++++++++++++- .../test/closed-state-system-writes.test.ts | 16 ++- .../src/upload-link-copy.test.ts | 12 +- .../service-storage/src/upload-link-copy.ts | 16 ++- 9 files changed, 197 insertions(+), 44 deletions(-) diff --git a/.changeset/37768-closed-state-refusal-sentences.md b/.changeset/37768-closed-state-refusal-sentences.md index 58c0f97f08a..478f624b19b 100644 --- a/.changeset/37768-closed-state-refusal-sentences.md +++ b/.changeset/37768-closed-state-refusal-sentences.md @@ -9,9 +9,9 @@ feat(spec,objectql): the closed-state refusal's own sentences, in every locale ( Clause-②: yes (widening: new keys in the published Operation Message Catalog and the upload-link copy; contract-review-tier review owed) Metadata-protocol: none -A write refused because a record is in a closed state (`409 RECORD_LOCKED`, ADR-0162) now tells the person what happened in their own language, instead of the developer sentence that named objects by their API names. +A write refused because a record is in a closed state (`409 RECORD_LOCKED`, ADR-0162) tells the person what happened, in their own language, with a sentence from the Operation Message Catalog. - **New catalog keys** in `BUILTIN_OPERATION_MESSAGES`, in every locale the catalog carries (en, zh-CN, ja-JP, es-ES), overridable per deployment under `errors.` like every other key: `record_closed` with its `_unlabeled`, `_untitled` and `_opaque` forms, and `record_closed_delete_blocked` with its `_untitled` and `_opaque` forms. English, for example: "Invoice 'Northwind March' is closed, so it and its lines can no longer be changed or deleted", and "Customer 'Contoso Holdings' cannot be deleted: deleting it would also remove a closed Invoice or one of its lines". -- **The engine words the refusal from them.** The title is the one the writer would be served under its own field permissions (readable and queryable); when it is not, the sentence names the object's label only. A line's write names its master by label alone. A delete refused for what it would also remove names the record asked to be deleted and the label of the object in the way, and drops the title when the delete names many records. No sentence carries a record id, an API name or a state value. +- **The engine words the refusal from them.** The refusal names a title only from a field that holds display text and that the writer's generic read returns, and that the writer is served under its own field permissions (readable and queryable): not a field the generic read withholds (`internal`, or a credential type), not a reference field, not a field the object's `closedStates` names. Otherwise the sentence names the object's label only, and so it does when the security service cannot be asked. A line's write names its master by label alone. A delete refused for what it would also remove names the record asked to be deleted and the label of the object in the way, with the title only when the delete names exactly one record by id. No sentence carries a record id, an API name or a state value. - **On the error**: `userMessage` and the wire's `error` carry the sentence; `message` reads `RECORD_LOCKED: ` followed by the sentence, as the approval lock's refusal does; the developer sentence moves to `developerMessage`, which the REST layer does not relay. A refusal that could not judge the write keeps the developer sentence and sets no `userMessage`. -- **Upload-link page**: a closed-state sentence (`recordClosed`) in each of its 11 languages. The page still answers `RECORD_LOCKED` with the approval sentence; choosing between the two by the lock's reason comes later. +- **Upload-link page**: a closed-state refusal reaches the page with the engine's declared catalog sentence, which the page shows. The page's own `recordLocked` answers only a `RECORD_LOCKED` with no declared sentence. The page also carries a closed-state sentence (`recordClosed`) in each of its 11 languages; choosing it by the lock's reason comes with a later change. diff --git a/packages/objectql/src/closed-state-lock.ts b/packages/objectql/src/closed-state-lock.ts index 4de5247efd1..90fadb280d1 100644 --- a/packages/objectql/src/closed-state-lock.ts +++ b/packages/objectql/src/closed-state-lock.ts @@ -74,10 +74,15 @@ * - a delete refused for what it would also remove: * `record_closed_delete_blocked*`, naming the record asked to be deleted * and the label of the object in the way, the title only where the caller - * is served one and the delete names one record. + * is served one and the delete names exactly one record by id. + * + * The title is named only from a field that holds display text and that the + * writer's generic read returns: never a field the generic read withholds + * (`internal`, or a credential type: `secret-fields.ts`), a reference field, + * or a field the object's `closedStates` names ({@link titleFieldOf}). * * No form carries a record id, an API name or the state's value. The - * developer's sentence, which names objects by their API names, moves to + * developer's sentence, which names objects by their API names, is carried on * `developerMessage`, which no person-facing surface reads and the data door * does not relay. A refusal that could not judge the write (D4's three cases) * keeps the developer's sentence as its `message` and marks no `userMessage`: @@ -85,7 +90,7 @@ * unanswerable-bound refusal is. */ -import { MAX_BULK_PER_ROW_HOOK_ROWS, ReadableIds, resolveDisplayField, type FilterCondition } from '@objectstack/spec/data'; +import { MAX_BULK_PER_ROW_HOOK_ROWS, REFERENCE_VALUE_TYPES, ReadableIds, resolveDisplayField, type FilterCondition } from '@objectstack/spec/data'; import { postureEnforcesWall, type TenancyPosture } from '@objectstack/spec/security'; import type { ExecutionContext } from '@objectstack/spec/kernel'; import type { ISecurityService } from '@objectstack/spec/contracts'; @@ -97,6 +102,7 @@ import { isDriverTenantScopedSchema } from './engine-driver-options.js'; import { isFederatedObject } from './federated-object.js'; import { driverCompilesReadableIdsLeaf } from './relation-semi-join.js'; import { closedValuesOf, type ClosedValues } from './closed-state-values.js'; +import { collectCredentialFields, collectInternalReadFields } from './secret-fields.js'; export { closedValuesOf, type ClosedValues }; @@ -260,11 +266,29 @@ function objectLabelOf(host: WordingHost, object: string, messages: ValidationMe return label && !(label === object && declared === undefined) ? label : undefined; } -/** The field an object's title is read from (ADR-0079's one arbiter), or `undefined`; ⛔ never the id. */ +/** + * The field an object's title is read from (ADR-0079's one arbiter), or + * `undefined`. A title is named only from a field whose value is display + * text and that the generic read returns, so the arbiter's answer gives no + * title when it is: + * - the id; + * - a field the generic read withholds: `internal`, or a credential type + * (`collectInternalReadFields`, `collectCredentialFields`, the two sets + * `engine-find.ts` leaves out of every row it returns); + * - a reference field (`REFERENCE_VALUE_TYPES`): its value is a record id; + * - a field the object's `closedStates` names: its value is an option code. + */ function titleFieldOf(host: Pick, object: string): string | undefined { try { - const field = resolveDisplayField(host._registry.getObject(object) as never); - return field && field !== 'id' && field !== '_id' ? field : undefined; + const schema = host._registry.getObject(object) as { fields?: Record } | undefined; + const field = resolveDisplayField(schema as never); + if (!field || field === 'id' || field === '_id') return undefined; + if (collectInternalReadFields(schema as never).includes(field)) return undefined; + if (collectCredentialFields(schema as never).includes(field)) return undefined; + const type = schema?.fields?.[field]?.type; + if (typeof type === 'string' && REFERENCE_VALUE_TYPES.has(type)) return undefined; + if (closedValuesOf(schema)?.has(field)) return undefined; + return field; } catch { return undefined; } @@ -278,10 +302,13 @@ function titleFieldOf(host: Pick, object: stri * fields), asked of the registered `security` service with the writer's own * execution context. * - * With no security service registered there is no field-level security: a - * read serves every field, so the stored title is the served one. Every other - * answer short of a clear yes names no title: a host that lends no engine, a - * service without either member, a question that throws or answers nothing. + * With no security service registered (the slot empty, or its source + * answering `null` or nothing) there is no field-level security: a read serves + * every field, so the stored title is the served one. Every other answer short + * of a clear yes names no title: a host that lends no engine, a slot that + * holds no function, a source that throws (the slot's own rule: + * `SECURITY_SERVICE_SOURCE_SLOT`), a service without either member, a + * question that throws or answers nothing. */ async function titleFieldIsServed(host: WordingHost, object: string, field: string, context: ExecutionContext | undefined): Promise { if (!host.facade) return false; @@ -293,8 +320,8 @@ async function titleFieldIsServed(host: WordingHost, object: string, field: stri try { svc = source() as typeof svc; } catch { - // The in-repo kernels throw on a name nothing registered: no service, no field-level security. - return true; + // A source that throws is no answer: no title (fail closed). + return false; } if (svc === undefined || svc === null) return true; if (typeof svc.getReadableFields !== 'function' || typeof svc.getQueryableFields !== 'function') return false; @@ -368,8 +395,8 @@ export async function closedStateRefusalSentence( } /** - * [D8] The refusal as a person reads it: `err`'s developer sentence moves to - * `developerMessage`, and the catalog's sentence becomes its `userMessage` and + * [D8] The refusal as a person reads it: `err`'s developer sentence is carried + * on `developerMessage`, and the catalog's sentence becomes its `userMessage` and * its `message` (behind the code, which the data door strips). */ async function sayClosed( @@ -727,15 +754,16 @@ export async function judgeClosedStatePredicateWrite(this: ClosedStateLockHost, * 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 and the object whose * closed record stands in the way, and nothing else (D8): the record by its - * title as the caller is served it where `roots` names one record, else by its - * object's label alone. + * title as the caller is served it where `named` (the ids the delete named, + * never the set planned so far) holds exactly one, else by its object's label + * alone. A delete that names its rows by a predicate passes none. */ export async function judgeClosedStateCascadeSet( this: Pick, root: string, members: ReadonlyMap>, context: ExecutionContext | undefined, - roots: ReadonlyArray = [], + named: ReadonlyArray = [], ): Promise { if (!boundByClosedStates(context)) return; const refuse = (detail: string) => closedStateLockError(root, 'delete', 'cannot_judge', undefined, detail); @@ -743,7 +771,7 @@ export async function judgeClosedStateCascadeSet( sayClosed.call( this, closedStateLockError(root, 'delete', 'cascade_reaches_closed', blockingObject), - { kind: 'delete_blocked', object: root, row: roots.length === 1 ? await storedTitleRow.call(this, root, roots[0]!, context) : undefined, blockingObject }, + { kind: 'delete_blocked', object: root, row: named.length === 1 ? await storedTitleRow.call(this, root, named[0]!, context) : undefined, blockingObject }, context, ); for (const [object, idSet] of members) { diff --git a/packages/objectql/src/engine-cascade-planning.ts b/packages/objectql/src/engine-cascade-planning.ts index 3172a61193b..5d19e07c2fc 100644 --- a/packages/objectql/src/engine-cascade-planning.ts +++ b/packages/objectql/src/engine-cascade-planning.ts @@ -540,7 +540,7 @@ export class CascadePlanningFacet { * (formula values, file references, hooks), so they are not the values a * restore must write back. */ - static async cascadeDeleteRelations(this: Pick, object: string, ids: ReadonlyArray, context?: ExecutionContext, depth = 0, onCollected?: (set: CascadeDeleteSet) => Promise): Promise { + static async cascadeDeleteRelations(this: Pick, object: string, ids: ReadonlyArray, context?: ExecutionContext, depth = 0, onCollected?: (set: CascadeDeleteSet) => Promise, named: ReadonlyArray = []): Promise { const roots: Array = []; const seen = new Set(); for (const id of ids) { @@ -587,7 +587,9 @@ export class CascadePlanningFacet { // point: after the caller's gates on the record it asked to delete and // before the first row is removed, never leg by leg. A member that is // closed, or is a line of a closed record, refuses the delete whole. - await judgeClosedStateCascadeSet.call(this, object, cascadeSet.members, context, fresh); + // [D8] The refusal's title form reads the ids the delete NAMED (`named`), + // never the set planned so far. + await judgeClosedStateCascadeSet.call(this, object, cascadeSet.members, context, named); if (onCollected) await onCollected(cascadeSet); await this.cascadeDeleteSets.run(cascadeSet, () => this.walkReferencingRelations(object, fresh, context, objects, cascadeSet), diff --git a/packages/objectql/src/engine-delete-and-aggregate.ts b/packages/objectql/src/engine-delete-and-aggregate.ts index dd841679c48..c2718fa9afe 100644 --- a/packages/objectql/src/engine-delete-and-aggregate.ts +++ b/packages/objectql/src/engine-delete-and-aggregate.ts @@ -715,7 +715,7 @@ export class DeleteAndAggregateFacet { let cascadeChildVanished = false; const runByIdDelete = async (writeContext?: ExecutionContext) => { const bin = this.openRecycleBinCapture(object, hookContext.input.id as string | number, writeContext, options?.multi === true || permanent); - await this.cascadeDeleteRelations(object, [hookContext.input.id as string | number], writeContext, 0, bin?.onCollected) + await this.cascadeDeleteRelations(object, [hookContext.input.id as string | number], writeContext, 0, bin?.onCollected, [hookContext.input.id as string | number]) .catch((e: unknown) => { throw cascadeStoppedRefusal(e, object); }); // [ADR-0131 D9] The entry's organization, when neither the record // nor the context names one, is the engine's own system-insert diff --git a/packages/objectql/src/engine.ts b/packages/objectql/src/engine.ts index 266feb3dc86..861715cdb58 100644 --- a/packages/objectql/src/engine.ts +++ b/packages/objectql/src/engine.ts @@ -4927,10 +4927,10 @@ export class ObjectQL implements IObjectQLEngine { ids: ReadonlyArray, context?: ExecutionContext, depth = 0, - onCollected?: (set: CascadeDeleteSet) => Promise, + onCollected?: (set: CascadeDeleteSet) => Promise, named?: ReadonlyArray, // [ADR-0162 D8] the ids the delete named ): Promise { // [#29986 codemod] The body moved to `engine-cascade-planning.ts`, its docblock with it (see `CascadePlanningHost`). - return CascadePlanningFacet.cascadeDeleteRelations.call(cascadePlanningHost.of(this), object, ids, context, depth, onCollected); + return CascadePlanningFacet.cascadeDeleteRelations.call(cascadePlanningHost.of(this), object, ids, context, depth, onCollected, named); } /** diff --git a/packages/qa/dogfood/test/closed-state-refusal-sentence.test.ts b/packages/qa/dogfood/test/closed-state-refusal-sentence.test.ts index e2a4d24a01d..f68088b001a 100644 --- a/packages/qa/dogfood/test/closed-state-refusal-sentence.test.ts +++ b/packages/qa/dogfood/test/closed-state-refusal-sentence.test.ts @@ -114,7 +114,7 @@ function fieldSecurity() { }; } -async function boot(opts: { security?: unknown; recycleBin?: boolean } = {}): Promise { +async function boot(opts: { security?: unknown; recycleBin?: boolean; source?: () => unknown } = {}): Promise { const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); engine = new ObjectQL(); engine.registerDriver(driver, true); @@ -141,6 +141,7 @@ async function boot(opts: { security?: unknown; recycleBin?: boolean } = {}): Pr await put(LINE, { id: 'l_open', name: 'Gadgets', qty: 1, invoice: 'inv_open' }); await put(BARE, { id: 'bare_closed', name: T.bare, status: 'settled' }); if (opts.security !== undefined) (engine as unknown as Record)[SECURITY_SLOT] = () => opts.security; + if (opts.source !== undefined) (engine as unknown as Record)[SECURITY_SLOT] = opts.source; } afterEach(async () => { @@ -203,6 +204,16 @@ describe('[ADR-0162 D8] the closed-state refusal names what the writer is served expect(sentenceOf(err)).toBe(fill(en.record_closed_untitled, { object: 'Invoice' })); }); + it('a security-service source that throws names no title; a source that answers null is no field-level security', async () => { + await boot({ source: () => { throw new Error('security service not resolvable'); } }); + const thrown = await refusal(() => engine.update(INVOICE, { id: 'inv_closed', amount: 99 }, by(WRITER))); + expect(sentenceOf(thrown)).toBe(fill(en.record_closed_untitled, { object: 'Invoice' })); + await engine.destroy(); + await boot({ source: () => null }); + const none = await refusal(() => engine.update(INVOICE, { id: 'inv_closed', amount: 99 }, by(WRITER))); + expect(sentenceOf(none)).toBe(fill(en.record_closed, { object: 'Invoice', title: T.closed })); + }); + it('a predicate write names no one record: the label form', async () => { await boot(); const err = await refusal(() => engine.update(INVOICE, { amount: 1 }, { where: { amount: 10 }, multi: true, context: WRITER } as never)); @@ -264,6 +275,15 @@ describe('[ADR-0162 D8] the closed-state refusal names what the writer is served expect(sentenceOf(err)).toBe(fill(en.record_closed_delete_blocked_untitled, { object: 'Customer', blockingObject: 'Invoice' })); }); + it('the cascade\'s title form reads the ids the delete named: a delete that names its rows by a predicate takes the label form, one row matched or many', async () => { + await boot(); + const untitled = fill(en.record_closed_delete_blocked_untitled, { object: 'Customer', blockingObject: 'Invoice' }); + const byTitle = await refusal(() => engine.delete(CUSTOMER, { where: { name: T.customer }, multi: true, context: WRITER } as never)); + expect(sentenceOf(byTitle)).toBe(untitled); + const oneOfIn = await refusal(() => engine.delete(CUSTOMER, { where: { id: { $in: ['cu1'] } }, multi: true, context: WRITER } as never)); + expect(sentenceOf(oneOfIn)).toBe(untitled); + }); + it('an object with no label is never named by its API name', async () => { await boot(); expect(sentenceOf(await refusal(() => engine.update(BARE, { id: 'bare_closed', name: 'x' }, by(WRITER))))) @@ -303,3 +323,96 @@ describe('[ADR-0162 D8] the closed-state refusal names what the writer is served expect(String(cannot.message)).toContain(LINE); }); }); + +/** + * [ADR-0162 D8] The title is named only from a field that holds display text + * and that the writer's generic read returns. Each object below declares its + * title field (`nameField`) as one that is not: a field the generic read + * withholds (`internal`; a credential type), a reference field, and the field + * the object's `closedStates` names. Each answers the label form on every path + * that reads a title: the record's update, its delete, and a delete whose + * cascade reaches a closed record (the root's title). + */ +describe('[ADR-0162 D8] the title comes only from a display-text field the generic read returns', () => { + const TAG = 'dg_csr_tag'; + const SLIP = 'dg_csr_slip'; + const KINDS = [ + { key: 'internal', object: 'dg_csr_internal', label: 'Ledger', titleField: 'code', def: { type: 'text', label: 'Code', internal: true }, value: 'LEDGER-CODE-7' }, + { key: 'credential', object: 'dg_csr_credential', label: 'Vault', titleField: 'passcode', def: { type: 'password', label: 'Passcode' }, value: 'PASSCODE-VALUE-7' }, + { key: 'reference', object: 'dg_csr_reference', label: 'Tagged', titleField: 'tag', def: { type: 'lookup', label: 'Tag', reference: TAG }, value: 'tag1' }, + { key: 'state', object: 'dg_csr_state', label: 'Stage', titleField: 'status', def: undefined, value: 'settled' }, + ] as const; + + async function bootKinds(): Promise { + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); + engine = new ObjectQL(); + engine.registerDriver(driver, true); + await engine.init(); + const kindObjects = KINDS.map((k) => ({ + name: k.object, + label: k.label, + nameField: k.titleField, + fields: { + status: { type: 'select', label: 'Status', options: STATUS_OPTIONS }, + note: { type: 'text', label: 'Note' }, + ...(k.def ? { [k.titleField]: k.def } : {}), + }, + closedStates: { status: ['settled'] }, + })); + const slip = { + name: SLIP, + label: 'Slip', + fields: { + name: { type: 'text', label: 'Name' }, + status: { type: 'select', label: 'Status', options: STATUS_OPTIONS }, + ...Object.fromEntries(KINDS.map((k) => [`${k.key}_ref`, { type: 'lookup', label: k.label, reference: k.object, deleteBehavior: 'cascade' }])), + }, + closedStates: { status: ['settled'] }, + }; + engine.registerApp({ + id: 'com.objectstack.dogfood.closed-state-refusal-title-fields', + name: 'Closed-state refusal title fields', + version: '1.0.0', + type: 'plugin', + scope: 'system', + objects: [{ name: TAG, label: 'Tag', fields: { name: { type: 'text', label: 'Name' } } }, ...kindObjects, slip], + } as never); + await engine.syncSchemas(); + await installDefaultOrganization(engine); + // Seeded through the driver: the rows are data at rest, whatever a write of each field type would do. + const put = (object: string, row: Record) => + engine.getDriverForObject(object)!.create(object, { organization_id: DEFAULT_ORGANIZATION_ID, ...row }); + await put(TAG, { id: 'tag1', name: 'Priority' }); + for (const k of KINDS) { + const title = k.key === 'state' ? {} : { [k.titleField]: k.value }; + await put(k.object, { id: `${k.key}_closed`, status: 'settled', ...title }); + await put(k.object, { id: `${k.key}_root`, status: 'draft', ...(k.key === 'state' ? {} : title) }); + await put(SLIP, { id: `slip_${k.key}`, name: `Slip ${k.key}`, status: 'settled', [`${k.key}_ref`]: `${k.key}_root` }); + } + } + + const ALL_VALUES = KINDS.map((k) => k.value).filter((v) => v !== 'settled'); + + it.each(KINDS.map((k) => [k.key, k] as const))('%s title field: the label form on update, delete and a cascade-delete root', async (_key, k) => { + await bootKinds(); + const untitled = fill(en.record_closed_untitled, { object: k.label }); + const update = await refusal(() => engine.update(k.object, { id: `${k.key}_closed`, note: 'x' }, by(WRITER))); + expect(sentenceOf(update), 'update').toBe(untitled); + const del = await refusal(() => engine.delete(k.object, { where: { id: `${k.key}_closed` }, context: WRITER } as never)); + expect(sentenceOf(del), 'delete').toBe(untitled); + const cascade = await refusal(() => engine.delete(k.object, { where: { id: `${k.key}_root` }, context: WRITER } as never)); + expect(sentenceOf(cascade), 'cascade-delete root').toBe(fill(en.record_closed_delete_blocked_untitled, { object: k.label, blockingObject: 'Slip' })); + for (const err of [update, del, cascade]) { + for (const value of [...ALL_VALUES, `${k.key}_closed`, `${k.key}_root`, 'Priority']) { + expect(String(err.userMessage), value).not.toContain(value); + } + } + }); + + it('control: the same objects with a display-text title field name the title', async () => { + await bootKinds(); + // The slip's own title field is `name`, display text the generic read returns. + const err = await refusal(() => engine.update(SLIP, { id: 'slip_internal', name: 'renamed' }, by(WRITER))); + expect(sentenceOf(err)).toBe(fill(en.record_closed, { object: 'Slip', title: 'Slip internal' })); + }); +}); diff --git a/packages/qa/dogfood/test/closed-state-system-writes.test.ts b/packages/qa/dogfood/test/closed-state-system-writes.test.ts index a4a54e4f637..22521eca4ea 100644 --- a/packages/qa/dogfood/test/closed-state-system-writes.test.ts +++ b/packages/qa/dogfood/test/closed-state-system-writes.test.ts @@ -147,8 +147,12 @@ describe('[ADR-0162 D5, D7] the platform\'s own writes on a record in a closed s const read = async (object: string, id: string) => (await ql.find(object, { where: { id }, context: SYS }))[0] as any; const pendingRequest = async (id: string) => (await ql.find('sys_approval_request', { where: { record_id: id, status: 'pending' }, context: SYS }) as any[]).map((r) => String(r.id)); - /** The caller's own write, refused by the closed-state lock with its sentence. */ - async function expectCallerRefused(object: string, id: string, label: string, title: string): Promise { + /** + * The caller's own write, refused by the closed-state lock with its sentence. + * This kernel registers no `security` service, so the engine's security + * source cannot answer and the sentence names the object's label only. + */ + async function expectCallerRefused(object: string, id: string, label: string): Promise { let caught: any; try { await ql.update(object, { id, note: 'edited by hand' }, { context: asPerson('owner') }); @@ -158,7 +162,7 @@ describe('[ADR-0162 D5, D7] the platform\'s own writes on a record in a closed s expect(caught, 'the caller\'s write is refused').toBeDefined(); expect(caught.code).toBe('RECORD_LOCKED'); expect(caught.status ?? caught.statusCode).toBe(409); - expect(caught.userMessage).toBe(fill(en.record_closed, { object: label, title })); + expect(caught.userMessage).toBe(fill(en.record_closed_untitled, { object: label })); expect((await read(object, id)).note ?? null, 'nothing of the refused write landed').toBeNull(); } @@ -170,7 +174,7 @@ describe('[ADR-0162 D5, D7] the platform\'s own writes on a record in a closed s const opened = await read(INVOICE, 'inv1'); expect(opened.approval_status, 'the mirror\'s `pending` landed on the closed record').toBe('pending'); expect(opened.status).toBe('settled'); - await expectCallerRefused(INVOICE, 'inv1', 'Invoice', 'Northwind March'); + await expectCallerRefused(INVOICE, 'inv1', 'Invoice'); const [request] = await pendingRequest('inv1'); expect(request).toBeTruthy(); @@ -178,14 +182,14 @@ describe('[ADR-0162 D5, D7] the platform\'s own writes on a record in a closed s const decided = await read(INVOICE, 'inv1'); expect(decided.approval_status, 'the mirror\'s `approved` landed on the closed record').toBe('approved'); expect(decided.status).toBe('settled'); - await expectCallerRefused(INVOICE, 'inv1', 'Invoice', 'Northwind March'); + await expectCallerRefused(INVOICE, 'inv1', 'Invoice'); }); it('an assignment rule routes a row a caller inserts already closed, and the insert lands; the rule never writes it again, and the caller\'s write is refused', async () => { const row = (await ql.insert(TICKET, { id: 't1', name: 'Quarter close', status: 'done', organization_id: ORG }, { context: asPerson('owner') })) as any; expect(row.owner_id, 'the rule routed the row it was inserting').toBe('lead'); expect((await read(TICKET, 't1')).owner_id).toBe('lead'); - await expectCallerRefused(TICKET, 't1', 'Ticket', 'Quarter close'); + await expectCallerRefused(TICKET, 't1', 'Ticket'); expect((await read(TICKET, 't1')).owner_id, 'an update evaluates no rule').toBe('lead'); }); }); diff --git a/packages/services/service-storage/src/upload-link-copy.test.ts b/packages/services/service-storage/src/upload-link-copy.test.ts index 7d48e2ab7f3..ba2c0d1af78 100644 --- a/packages/services/service-storage/src/upload-link-copy.test.ts +++ b/packages/services/service-storage/src/upload-link-copy.test.ts @@ -128,12 +128,14 @@ describe('#32712 — the upload-link page\'s sentences', () => { }); /** - * [ADR-0162 D8] The door gains a closed-state sentence beside the approval - * one, in every language it carries. Choosing between the two by the lock - * read's reason lands with the one lock read (Execution item 2), so the code - * still answers the approval sentence: this pins the table, not a selection. + * [ADR-0162 D8] The page carries a closed-state sentence beside the approval + * one, in every language it carries. A closed-state refusal reaches the page + * with the engine's declared sentence, which the page shows; the code-only + * lookup below answers a `RECORD_LOCKED` that declares none. Choosing + * `recordClosed` by the lock read's reason stays with Execution item 2: this + * pins the table, not a selection. */ - it('carries a closed-state sentence in every language, not the approval one, and RECORD_LOCKED still reads the approval one', () => { + it('carries a closed-state sentence in every language, not the approval one; a RECORD_LOCKED with no declared sentence reads the approval one', () => { for (const tag of PLATFORM_LOCALE_TAGS) { const copy = UPLOAD_LINK_COPY[copyLocaleOf(tag)!]; expect(copy.recordClosed.trim(), tag).not.toBe(''); diff --git a/packages/services/service-storage/src/upload-link-copy.ts b/packages/services/service-storage/src/upload-link-copy.ts index 63f7a62c4fc..c78ca7f1fa0 100644 --- a/packages/services/service-storage/src/upload-link-copy.ts +++ b/packages/services/service-storage/src/upload-link-copy.ts @@ -47,14 +47,18 @@ export interface UploadLinkRefusalCopy { notAllowed: string; /** `FIELD_NOT_ACCESSIBLE`: the field is read-only on the record (statically or in its current state). */ fieldReadOnly: string; - /** `RECORD_LOCKED`: a pending approval locks the record. */ + /** + * `RECORD_LOCKED` that carries no declared sentence of its own. A refusal + * that declares one (`userMessage`) is shown with that sentence instead + * (`storage-routes.ts` `relayUploadLinkRefusal`). + */ recordLocked: string; /** - * [ADR-0162 D8] `RECORD_LOCKED`: the record is in one of its object's closed - * states. The same code as {@link recordLocked}; the page chooses between - * the two by the lock read's reason, which lands with the one lock read - * (ADR-0162 D9, Execution item 2). Until then the code answers - * {@link recordLocked}. + * [ADR-0162 D8] The page's sentence for a record in one of its object's + * closed states. A closed-state refusal reaches this page with the engine's + * declared catalog sentence (`record_closed*`, in the request's language) + * as its `userMessage`, and the page shows that sentence. Choosing this + * entry by the lock read's reason stays with ADR-0162 Execution item 2. */ recordClosed: string; /** `RECORD_NOT_FOUND`: the record is gone, or out of the user's reach. */ From 7f9538fc02780f6dc466db1a5f159efeb264fee2 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 08:46:53 +0000 Subject: [PATCH 09/10] fix(objectql): with no security service registered, the closed-state refusal names its title (ADR-0162 D8) The title rule asks a probe, beside the security source, whether a `security` service is registered at all, read without building one. When the source throws and the probe answers that nothing is registered, there is no field-level security and the refusal names the title D8 gives; the rules on which field a title is read from still apply first. A service that is registered and cannot be resolved still names no title. Only the title rule reads the probe: every other reader of the source answers as before. Docblocks: the upload-link sentence is worded in the link user's resolved context; the title-field rule cites the generic read (internal fields omitted, credentials masked); the catalog's `_untitled` when-lists name the new cases. Claude-Session: https://claude.ai/code/session_01FEkQ5nGQtUA88SthJbYyRw Co-Authored-By: Claude --- packages/objectql/src/closed-state-lock.ts | 51 +++- packages/objectql/src/plugin.ts | 43 +++- ...osed-state-refusal-security-source.test.ts | 223 ++++++++++++++++++ .../test/closed-state-system-writes.test.ts | 14 +- .../service-storage/src/upload-link-copy.ts | 5 +- packages/spec/src/system/operation-message.ts | 17 +- 6 files changed, 327 insertions(+), 26 deletions(-) create mode 100644 packages/qa/dogfood/test/closed-state-refusal-security-source.test.ts diff --git a/packages/objectql/src/closed-state-lock.ts b/packages/objectql/src/closed-state-lock.ts index 90fadb280d1..ce3bf64287d 100644 --- a/packages/objectql/src/closed-state-lock.ts +++ b/packages/objectql/src/closed-state-lock.ts @@ -272,9 +272,11 @@ function objectLabelOf(host: WordingHost, object: string, messages: ValidationMe * text and that the generic read returns, so the arbiter's answer gives no * title when it is: * - the id; - * - a field the generic read withholds: `internal`, or a credential type - * (`collectInternalReadFields`, `collectCredentialFields`, the two sets - * `engine-find.ts` leaves out of every row it returns); + * - a field the generic read withholds: `internal` + * (`collectInternalReadFields`, left out of every row `engine-find.ts` + * returns) or a credential type (`collectCredentialFields`, served masked + * in those rows); `engine-find.ts`'s search scan skips the union of the + * two; * - a reference field (`REFERENCE_VALUE_TYPES`): its value is a record id; * - a field the object's `closedStates` names: its value is an option code. */ @@ -294,6 +296,31 @@ function titleFieldOf(host: Pick, object: stri } } +/** + * [D8] The engine slot `ObjectQLPlugin` fills, beside + * `SECURITY_SERVICE_SOURCE_SLOT`, with a probe answering whether a `security` + * service is registered at all, read without building one (`false`: nothing + * is registered under the name). Read only by {@link titleFieldIsServed}, and + * only when the security source throws; no other reader of the source slot + * consults it. Not public surface. + */ +export const SECURITY_SERVICE_REGISTERED_SLOT: unique symbol = Symbol.for('objectstack.objectql.securityServiceRegistered'); + +/** + * [D8] True only when the host's registration probe answers that no + * `security` service is registered. A missing probe, a probe that throws, and + * any answer but `false` mean a service may be registered: no title. + */ +async function noSecurityServiceRegistered(facade: unknown): Promise { + const probe = (facade as Record)[SECURITY_SERVICE_REGISTERED_SLOT]; + if (typeof probe !== 'function') return false; + try { + return (await probe()) === false; + } catch { + return false; + } +} + /** * [D8] May the writer be served `field` of `object`? The rule the pending lock * picks its title by (`plugin-approvals` `resolveReadableSnapshotFields`): the @@ -304,11 +331,14 @@ function titleFieldOf(host: Pick, object: stri * * With no security service registered (the slot empty, or its source * answering `null` or nothing) there is no field-level security: a read serves - * every field, so the stored title is the served one. Every other answer short - * of a clear yes names no title: a host that lends no engine, a slot that - * holds no function, a source that throws (the slot's own rule: - * `SECURITY_SERVICE_SOURCE_SLOT`), a service without either member, a - * question that throws or answers nothing. + * every field, so the stored title is the served one. So it is when the + * source throws and the host's registration probe + * (`SECURITY_SERVICE_REGISTERED_SLOT`) answers that no `security` service is + * registered: the in-repo kernels throw on a name nothing registered. Every + * other answer short of a clear yes names no title: a host that lends no + * engine, a slot that holds no function, a source that throws for a service + * that is registered (or with no probe to say it is not), a service without + * either member, a question that throws or answers nothing. */ async function titleFieldIsServed(host: WordingHost, object: string, field: string, context: ExecutionContext | undefined): Promise { if (!host.facade) return false; @@ -320,8 +350,9 @@ async function titleFieldIsServed(host: WordingHost, object: string, field: stri try { svc = source() as typeof svc; } catch { - // A source that throws is no answer: no title (fail closed). - return false; + // A source that throws names no title, unless the host's registration + // probe answers that no `security` service is registered at all. + return noSecurityServiceRegistered(host.facade); } if (svc === undefined || svc === null) return true; if (typeof svc.getReadableFields !== 'function' || typeof svc.getQueryableFields !== 'function') return false; diff --git a/packages/objectql/src/plugin.ts b/packages/objectql/src/plugin.ts index c8717fa8063..40b46c62d86 100644 --- a/packages/objectql/src/plugin.ts +++ b/packages/objectql/src/plugin.ts @@ -15,7 +15,8 @@ import { OWNERSHIP_QUEUE_SERVICE } from '@objectstack/spec/contracts'; import { assembleMetadataProtocol, isServedOverrideRowOf } from '@objectstack/metadata-protocol'; import { installedManifestsOf, isTenantAuthored, readLegacyOrganizationRows } from '@objectstack/metadata-core'; import type { MetadataAuthoringChannel } from '@objectstack/metadata-protocol'; -import { Plugin, PluginContext } from '@objectstack/core'; +import { Plugin, PluginContext, isServiceNotRegisteredError } from '@objectstack/core'; +import { SECURITY_SERVICE_REGISTERED_SLOT } from './closed-state-lock.js'; import { resolveArtifactPackageEntries, artifactPackageId, declaredDependencyIds, readDeploymentOrgScopingEntitlement } from '@objectstack/core'; // [ADR-0130 D4] The residual rule's decision half — which top-level items of a // multi-package stack no body declares, and the id they take. See @@ -561,6 +562,40 @@ export const OBJECTQL_DRIVERS_READY_HOOK = 'objectql:drivers-ready'; */ export const OBJECTQL_SCHEMA_SYNCED_HOOK = 'objectql:schema-synced'; +/** + * [ADR-0162 D8] Whether a `security` service is registered on the plugin's + * kernel, read without building one: `false` only when nothing is registered + * under the name, `true` for every other answer (the answer that names no + * title in a closed-state refusal). + * - The sync accessor returns it, or the context's service map holds the + * name: registered. + * - The sync accessor refuses a service registered as a factory and not yet + * built with "is async" (the message the kernel keeps verbatim for callers + * that match on it): registered, and the probe does not build it. + * - Otherwise the kernel's async accessor draws the line with the branded + * "never registered" rejection (`isServiceNotRegisteredError`), given + * before anything is built; any other answer is registered. + * - A host with no async accessor (`LiteKernel`) has no factories, so "not + * registered" is the only fault its sync accessor reports. + */ +async function securityServiceRegistered(ctx: PluginContext): Promise { + try { + ctx.getService('security'); + return true; + } catch (err) { + if (err instanceof Error && err.message.includes('is async')) return true; + } + if (ctx.getServices().has('security')) return true; + const kernel = ctx.getKernel?.() as { getServiceAsync?: (name: string) => Promise } | undefined; + if (typeof kernel?.getServiceAsync !== 'function') return false; + try { + await kernel.getServiceAsync('security'); + return true; + } catch (err) { + return !isServiceNotRegisteredError(err); + } +} + export class ObjectQLPlugin implements Plugin { name = 'com.objectstack.engine.objectql'; type = 'objectql' as const; @@ -923,6 +958,12 @@ export class ObjectQLPlugin implements Plugin { // `$in: []` (fail closed); a throw — the in-repo kernels' answer for a // name nothing registered — is one of them. (this.ql as unknown as Record)[SECURITY_SERVICE_SOURCE_SLOT] = () => ctx.getService('security'); + // [ADR-0162 D8] Beside the source, a probe that answers whether a + // `security` service is registered at all (SECURITY_SERVICE_REGISTERED_SLOT). + // Only the closed-state refusal's title rule reads it, and only when the + // source above throws; it builds no service, so every other reader of the + // source answers as before. + (this.ql as unknown as Record)[SECURITY_SERVICE_REGISTERED_SLOT] = () => securityServiceRegistered(ctx); // [ADR-0142 D5] The assignment seam reads the ownership-queue service the // same way: a source, resolved at use. ⛔ `ownership-queue`, never the job // queue's `queue`. diff --git a/packages/qa/dogfood/test/closed-state-refusal-security-source.test.ts b/packages/qa/dogfood/test/closed-state-refusal-security-source.test.ts new file mode 100644 index 00000000000..b1921b351f4 --- /dev/null +++ b/packages/qa/dogfood/test/closed-state-refusal-security-source.test.ts @@ -0,0 +1,223 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 D8] The closed-state refusal's title on a real kernel, by what the + * kernel registers under `security`. `ObjectQLPlugin` hands the engine the + * service as a source (`SECURITY_SERVICE_SOURCE_SLOT`) and, beside it, a + * probe that answers whether a `security` service is registered at all, + * read without building one (`SECURITY_SERVICE_REGISTERED_SLOT`). Only the + * refusal's title rule reads the probe. + * + * - No `security` service registered: there is no field-level security, so + * the refusal names the title D8 gives. The rules on which field a title + * is read from still apply first: a title field the generic read does not + * return (internal, credential) or whose value is not display text + * (reference, a field `closedStates` names) gives the label form there too. + * - A `security` service registered and not resolvable (a factory that + * throws, or one the sync accessor does not build): the label form. + * - Every other reader of the source answers as it did: the `ReadableIds` + * resolution and the search's queryable-field read, before and after a + * refusal, and the probe builds no factory-registered service. + * + * Real `ObjectKernel`, `ObjectQLPlugin`, driver-sql on better-sqlite3 + * `:memory:`. + */ + +import { afterEach, describe, expect, it } from 'vitest'; +import { ObjectKernel, type Plugin, type PluginContext } from '@objectstack/core'; +import { ObjectQLPlugin, type ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { BUILTIN_OPERATION_MESSAGES } from '@objectstack/spec/system'; +import { DEFAULT_ORGANIZATION_ID, installDefaultOrganization } from './default-organization.testkit.js'; + +const WRITER = { userId: 'usr_writer', tenantId: DEFAULT_ORGANIZATION_ID, positions: [], permissions: [] } as const; +const by = (context: unknown) => ({ context }) as never; + +const STATUS_OPTIONS = [{ label: 'Draft', value: 'draft' }, { label: 'Settled', value: 'settled' }]; +const TAG = 'dg_css_tag'; +const SLIP = 'dg_css_slip'; +const KINDS = [ + { key: 'plain', object: 'dg_css_plain', label: 'Memo', titleField: 'name', def: { type: 'text', label: 'Name' }, value: 'Northwind March' }, + { key: 'internal', object: 'dg_css_internal', label: 'Ledger', titleField: 'code', def: { type: 'text', label: 'Code', internal: true }, value: 'LEDGER-CODE-7' }, + { key: 'credential', object: 'dg_css_credential', label: 'Vault', titleField: 'passcode', def: { type: 'password', label: 'Passcode' }, value: 'PASSCODE-VALUE-7' }, + { key: 'reference', object: 'dg_css_reference', label: 'Tagged', titleField: 'tag', def: { type: 'lookup', label: 'Tag', reference: TAG }, value: 'tag1' }, + { key: 'state', object: 'dg_css_state', label: 'Stage', titleField: 'status', def: undefined, value: 'settled' }, +] as const; +const PLAIN = KINDS[0]; +const WITHHELD = KINDS.slice(1); + +const en = BUILTIN_OPERATION_MESSAGES.en; +const fill = (template: string, params: Record = {}) => template.replace(/\{\{(\w+)\}\}/g, (m, k: string) => params[k] ?? m); + +interface Refusal { code?: unknown; status?: unknown; message?: unknown; userMessage?: unknown } + +async function refusal(run: () => Promise): Promise { + try { + await run(); + } catch (e) { + return e as Refusal; + } + throw new Error('expected the write to be refused, and it landed'); +} + +function sentenceOf(err: Refusal): string { + expect([err.code, err.status]).toEqual(['RECORD_LOCKED', 409]); + expect(err.message).toBe(`RECORD_LOCKED: ${String(err.userMessage)}`); + return String(err.userMessage); +} + +/** A `security` service the sync accessor never builds: registered as a factory. */ +function securityFactoryPlugin(factory: () => unknown): Plugin { + return { + name: 'dg-closed-state-security-factory', + init: async (ctx: PluginContext) => { + ctx.registerServiceFactory('security', factory); + }, + } as Plugin; +} + +let kernel: ObjectKernel | undefined; +let ql: ObjectQL; + +afterEach(async () => { + try { await kernel?.shutdown(); } catch { /* noop */ } + kernel = undefined; +}); + +async function boot(extra: Plugin[] = []): Promise { + kernel = new ObjectKernel({ logger: { level: 'silent' } } as never); + await kernel.use(new ObjectQLPlugin()); + for (const plugin of extra) await kernel.use(plugin); + await kernel.bootstrap(); + ql = kernel.getService('objectql'); + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); + await driver.connect(); + ql.registerDriver(driver, true); + const kindObjects = KINDS.map((k) => ({ + name: k.object, + label: k.label, + nameField: k.titleField, + fields: { + status: { type: 'select', label: 'Status', options: STATUS_OPTIONS }, + note: { type: 'text', label: 'Note' }, + ...(k.def ? { [k.titleField]: k.def } : {}), + }, + closedStates: { status: ['settled'] }, + })); + const slip = { + name: SLIP, + label: 'Slip', + fields: { + name: { type: 'text', label: 'Name' }, + status: { type: 'select', label: 'Status', options: STATUS_OPTIONS }, + ...Object.fromEntries(KINDS.map((k) => [`${k.key}_ref`, { type: 'lookup', label: k.label, reference: k.object, deleteBehavior: 'cascade' }])), + }, + closedStates: { status: ['settled'] }, + }; + ql.registerApp({ + id: 'com.objectstack.dogfood.closed-state-refusal-security-source', + name: 'Closed-state refusal security source', + version: '1.0.0', + type: 'plugin', + scope: 'system', + objects: [{ name: TAG, label: 'Tag', fields: { name: { type: 'text', label: 'Name' } } }, ...kindObjects, slip], + } as never); + await ql.syncSchemas(); + await installDefaultOrganization(ql as never); + // Seeded through the driver: the rows are data at rest, whatever a write of each field type would do. + const put = (object: string, row: Record) => + ql.getDriverForObject(object)!.create(object, { organization_id: DEFAULT_ORGANIZATION_ID, ...row }); + await put(TAG, { id: 'tag1', name: 'Priority' }); + for (const k of KINDS) { + const title = k.key === 'state' ? {} : { [k.titleField]: k.value }; + await put(k.object, { id: `${k.key}_closed`, status: 'settled', ...title }); + await put(k.object, { id: `${k.key}_root`, status: 'draft', ...(k.key === 'state' ? {} : title) }); + await put(SLIP, { id: `slip_${k.key}`, name: `Slip ${k.key}`, status: 'settled', [`${k.key}_ref`]: `${k.key}_root` }); + } +} + +/** Update, by-id delete and cascade-delete root of one kind, as the writer. */ +async function refusalsOf(k: (typeof KINDS)[number]): Promise<{ update: string; del: string; cascade: string }> { + const update = sentenceOf(await refusal(() => ql.update(k.object, { id: `${k.key}_closed`, note: 'x' }, by(WRITER)))); + const del = sentenceOf(await refusal(() => ql.delete(k.object, { where: { id: `${k.key}_closed` }, context: WRITER } as never))); + const cascade = sentenceOf(await refusal(() => ql.delete(k.object, { where: { id: `${k.key}_root` }, context: WRITER } as never))); + return { update, del, cascade }; +} + +const untitledOf = (k: (typeof KINDS)[number]) => ({ + update: fill(en.record_closed_untitled, { object: k.label }), + del: fill(en.record_closed_untitled, { object: k.label }), + cascade: fill(en.record_closed_delete_blocked_untitled, { object: k.label, blockingObject: 'Slip' }), +}); + +/** What the engine's other readers of the security source answer now. */ +async function otherReaders(): Promise<{ readableIds: unknown; searchQueryable: unknown }> { + const engine = ql as unknown as { + resolveReadableIdsSecurity(): { kind: string; why?: string }; + resolveSearchQueryableFields(object: string, context: unknown): Promise; + }; + const resolution = engine.resolveReadableIdsSecurity(); + return { + readableIds: { kind: resolution.kind, threw: typeof resolution.why === 'string' && resolution.why.startsWith('resolving the "security" service threw') }, + searchQueryable: await engine.resolveSearchQueryableFields(PLAIN.object, WRITER), + }; +} + +const SOURCE_THREW = { readableIds: { kind: 'unusable', threw: true }, searchQueryable: undefined }; + +describe('[ADR-0162 D8] the closed-state refusal\'s title, by what the kernel registers under `security`', () => { + it('no `security` service registered: the refusal names the title, on update, delete and a cascade-delete root', async () => { + await boot(); + const { update, del, cascade } = await refusalsOf(PLAIN); + expect(update).toBe(fill(en.record_closed, { object: PLAIN.label, title: PLAIN.value })); + expect(del).toBe(fill(en.record_closed, { object: PLAIN.label, title: PLAIN.value })); + expect(cascade).toBe(fill(en.record_closed_delete_blocked, { object: PLAIN.label, title: PLAIN.value, blockingObject: 'Slip' })); + }); + + it.each(WITHHELD.map((k) => [k.key, k] as const))( + 'no `security` service registered, %s title field: the label form, the field rules applying first', + async (_key, k) => { + await boot(); + expect(await refusalsOf(k)).toEqual(untitledOf(k)); + }, + ); + + it('a `security` service registered as a factory that throws: the label form', async () => { + await boot([securityFactoryPlugin(() => { throw new Error('the security service cannot be built on this host'); })]); + expect(await refusalsOf(PLAIN)).toEqual(untitledOf(PLAIN)); + }); + + it('a `security` service registered as a factory the sync accessor does not build: the label form, and the refusal builds nothing', async () => { + let built = 0; + const svc = { + getReadFilter: async () => null, + canReadObject: async () => true, + getReadableFields: async () => ['id', 'name', 'status', 'note'], + getQueryableFields: async () => ['id', 'name', 'status', 'note'], + }; + await boot([securityFactoryPlugin(() => { built += 1; return svc; })]); + const before = { built, readers: await otherReaders() }; + expect(await refusalsOf(PLAIN)).toEqual(untitledOf(PLAIN)); + expect({ built, readers: await otherReaders() }).toEqual(before); + }); + + it('the other readers of the security source answer as before: no service registered, and one registered that throws', async () => { + await boot(); + expect(await otherReaders(), 'no service, before a refusal').toEqual(SOURCE_THREW); + await refusalsOf(PLAIN); + expect(await otherReaders(), 'no service, after a refusal').toEqual(SOURCE_THREW); + await kernel!.shutdown(); + kernel = undefined; + + await boot([securityFactoryPlugin(() => { throw new Error('the security service cannot be built on this host'); })]); + expect(await otherReaders(), 'a throwing factory, before a refusal').toEqual(SOURCE_THREW); + await refusalsOf(PLAIN); + expect(await otherReaders(), 'a throwing factory, after a refusal').toEqual(SOURCE_THREW); + }); + + it('a source that throws with no probe beside it names no title', async () => { + await boot(); + delete (ql as unknown as Record)[Symbol.for('objectstack.objectql.securityServiceRegistered')]; + expect(await refusalsOf(PLAIN)).toEqual(untitledOf(PLAIN)); + }); +}); diff --git a/packages/qa/dogfood/test/closed-state-system-writes.test.ts b/packages/qa/dogfood/test/closed-state-system-writes.test.ts index 22521eca4ea..947cafc0589 100644 --- a/packages/qa/dogfood/test/closed-state-system-writes.test.ts +++ b/packages/qa/dogfood/test/closed-state-system-writes.test.ts @@ -149,10 +149,10 @@ describe('[ADR-0162 D5, D7] the platform\'s own writes on a record in a closed s (await ql.find('sys_approval_request', { where: { record_id: id, status: 'pending' }, context: SYS }) as any[]).map((r) => String(r.id)); /** * The caller's own write, refused by the closed-state lock with its sentence. - * This kernel registers no `security` service, so the engine's security - * source cannot answer and the sentence names the object's label only. + * This kernel registers no `security` service, so there is no field-level + * security and the sentence names the record's title. */ - async function expectCallerRefused(object: string, id: string, label: string): Promise { + async function expectCallerRefused(object: string, id: string, label: string, title: string): Promise { let caught: any; try { await ql.update(object, { id, note: 'edited by hand' }, { context: asPerson('owner') }); @@ -162,7 +162,7 @@ describe('[ADR-0162 D5, D7] the platform\'s own writes on a record in a closed s expect(caught, 'the caller\'s write is refused').toBeDefined(); expect(caught.code).toBe('RECORD_LOCKED'); expect(caught.status ?? caught.statusCode).toBe(409); - expect(caught.userMessage).toBe(fill(en.record_closed_untitled, { object: label })); + expect(caught.userMessage).toBe(fill(en.record_closed, { object: label, title })); expect((await read(object, id)).note ?? null, 'nothing of the refused write landed').toBeNull(); } @@ -174,7 +174,7 @@ describe('[ADR-0162 D5, D7] the platform\'s own writes on a record in a closed s const opened = await read(INVOICE, 'inv1'); expect(opened.approval_status, 'the mirror\'s `pending` landed on the closed record').toBe('pending'); expect(opened.status).toBe('settled'); - await expectCallerRefused(INVOICE, 'inv1', 'Invoice'); + await expectCallerRefused(INVOICE, 'inv1', 'Invoice', 'Northwind March'); const [request] = await pendingRequest('inv1'); expect(request).toBeTruthy(); @@ -182,14 +182,14 @@ describe('[ADR-0162 D5, D7] the platform\'s own writes on a record in a closed s const decided = await read(INVOICE, 'inv1'); expect(decided.approval_status, 'the mirror\'s `approved` landed on the closed record').toBe('approved'); expect(decided.status).toBe('settled'); - await expectCallerRefused(INVOICE, 'inv1', 'Invoice'); + await expectCallerRefused(INVOICE, 'inv1', 'Invoice', 'Northwind March'); }); it('an assignment rule routes a row a caller inserts already closed, and the insert lands; the rule never writes it again, and the caller\'s write is refused', async () => { const row = (await ql.insert(TICKET, { id: 't1', name: 'Quarter close', status: 'done', organization_id: ORG }, { context: asPerson('owner') })) as any; expect(row.owner_id, 'the rule routed the row it was inserting').toBe('lead'); expect((await read(TICKET, 't1')).owner_id).toBe('lead'); - await expectCallerRefused(TICKET, 't1', 'Ticket'); + await expectCallerRefused(TICKET, 't1', 'Ticket', 'Quarter close'); expect((await read(TICKET, 't1')).owner_id, 'an update evaluates no rule').toBe('lead'); }); }); diff --git a/packages/services/service-storage/src/upload-link-copy.ts b/packages/services/service-storage/src/upload-link-copy.ts index c78ca7f1fa0..617a70d82e5 100644 --- a/packages/services/service-storage/src/upload-link-copy.ts +++ b/packages/services/service-storage/src/upload-link-copy.ts @@ -56,8 +56,9 @@ export interface UploadLinkRefusalCopy { /** * [ADR-0162 D8] The page's sentence for a record in one of its object's * closed states. A closed-state refusal reaches this page with the engine's - * declared catalog sentence (`record_closed*`, in the request's language) - * as its `userMessage`, and the page shows that sentence. Choosing this + * declared catalog sentence (`record_closed*`, worded in the link user's + * resolved context, `record-file-access.ts` `consumeUploadLinkFiles`) as + * its `userMessage`, and the page shows that sentence. Choosing this * entry by the lock read's reason stays with ADR-0162 Execution item 2. */ recordClosed: string; diff --git a/packages/spec/src/system/operation-message.ts b/packages/spec/src/system/operation-message.ts index 835eb35f021..2974c71a7fa 100644 --- a/packages/spec/src/system/operation-message.ts +++ b/packages/spec/src/system/operation-message.ts @@ -307,10 +307,13 @@ export function operationMessageTranslationKey(messageKey: string): string { * locale) and `{{title}}` (the record's title as the WRITER would be * served it under its own field permissions, never the title as stored); * - `record_closed_untitled` takes `{{object}}` alone: for a record whose - * title the writer may not be served, for a write that matched rows by a - * predicate, and for a line write, where `{{object}}` is the MASTER's - * label (the engine reads the master's state to judge and reads nothing - * of it to word the refusal); + * title the writer may not be served (its title field is one the + * writer's generic read does not return, or the security service is + * registered but cannot be resolved), for a title field whose value is + * not display text (a reference, or a field the object's `closedStates` + * names), for a write that matched rows by a predicate, and for a line + * write, where `{{object}}` is the MASTER's label (the engine reads the + * master's state to judge and reads nothing of it to word the refusal); * - `record_closed_unlabeled` takes `{{title}}` alone, for an object with no * label; * - `record_closed_opaque` names nothing. @@ -326,8 +329,10 @@ export function operationMessageTranslationKey(messageKey: string): string { * record asked to be deleted, its title as the caller is served it) and * `{{blockingObject}}` (the label of the object in the way); * - `record_closed_delete_blocked_untitled` drops `{{title}}`: where the - * caller is served no title for that record, and where the delete names - * many records; + * caller is served no title for that record (its title field is one the + * caller's generic read does not return or is not display text, or the + * security service is registered but cannot be resolved), and where the + * delete names many records or names its rows by a predicate; * - `record_closed_delete_blocked_opaque` names nothing, where either * object has no label. * From 37e4afad98521096127aec7f651084d3a3e845cb Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 09:10:25 +0000 Subject: [PATCH 10/10] docs(changeset): the closed-state refusal names its title when no security service is registered (ADR-0162 D8) Claude-Session: https://claude.ai/code/session_01FEkQ5nGQtUA88SthJbYyRw Co-Authored-By: Claude --- .changeset/37768-closed-state-refusal-sentences.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/37768-closed-state-refusal-sentences.md b/.changeset/37768-closed-state-refusal-sentences.md index 478f624b19b..7cd9079c9bb 100644 --- a/.changeset/37768-closed-state-refusal-sentences.md +++ b/.changeset/37768-closed-state-refusal-sentences.md @@ -12,6 +12,6 @@ Metadata-protocol: none A write refused because a record is in a closed state (`409 RECORD_LOCKED`, ADR-0162) tells the person what happened, in their own language, with a sentence from the Operation Message Catalog. - **New catalog keys** in `BUILTIN_OPERATION_MESSAGES`, in every locale the catalog carries (en, zh-CN, ja-JP, es-ES), overridable per deployment under `errors.` like every other key: `record_closed` with its `_unlabeled`, `_untitled` and `_opaque` forms, and `record_closed_delete_blocked` with its `_untitled` and `_opaque` forms. English, for example: "Invoice 'Northwind March' is closed, so it and its lines can no longer be changed or deleted", and "Customer 'Contoso Holdings' cannot be deleted: deleting it would also remove a closed Invoice or one of its lines". -- **The engine words the refusal from them.** The refusal names a title only from a field that holds display text and that the writer's generic read returns, and that the writer is served under its own field permissions (readable and queryable): not a field the generic read withholds (`internal`, or a credential type), not a reference field, not a field the object's `closedStates` names. Otherwise the sentence names the object's label only, and so it does when the security service cannot be asked. A line's write names its master by label alone. A delete refused for what it would also remove names the record asked to be deleted and the label of the object in the way, with the title only when the delete names exactly one record by id. No sentence carries a record id, an API name or a state value. +- **The engine words the refusal from them.** The refusal names a title only from a field that holds display text and that the writer's generic read returns, and that the writer is served under its own field permissions (readable and queryable): not a field the generic read withholds (`internal`, or a credential type), not a reference field, not a field the object's `closedStates` names. Otherwise the sentence names the object's label only, and so it does when a registered security service cannot be resolved. With no security service registered there is no field-level security, and the title is named. A line's write names its master by label alone. A delete refused for what it would also remove names the record asked to be deleted and the label of the object in the way, with the title only when the delete names exactly one record by id. No sentence carries a record id, an API name or a state value. - **On the error**: `userMessage` and the wire's `error` carry the sentence; `message` reads `RECORD_LOCKED: ` followed by the sentence, as the approval lock's refusal does; the developer sentence moves to `developerMessage`, which the REST layer does not relay. A refusal that could not judge the write keeps the developer sentence and sets no `userMessage`. - **Upload-link page**: a closed-state refusal reaches the page with the engine's declared catalog sentence, which the page shows. The page's own `recordLocked` answers only a `RECORD_LOCKED` with no declared sentence. The page also carries a closed-state sentence (`recordClosed`) in each of its 11 languages; choosing it by the lock's reason comes with a later change.