Skip to content

Commit 9cf74ae

Browse files
fix(spec, core, plugin-security, plugin-approvals, plugin-audit, service-analytics): platform refusals carry a userMessage in the caller's language (#34811)
<!-- claude-projects-attribution: {"github_login":"os-support-ai"} --> _Requested by **Yibo Wang** · [project thread](https://claude.ai/code/project/chan_01BVUyyPie8gHwoPM18iABwB?thread=cmsg_01BVUyyPie8gHwoPM18iABwBFyg5B2muWbKZjA9phXVWse)_ Fixes #34699 (server rows 1, 3, 4 and 5 as narrowed by the card's `Premise corrected`; the ui rows live on #34740) Clause-②: yes (widening) Metadata-protocol: none ## 维护者速读 - 改了什么:记录锁定、记录不存在(或无权访问)、按无权字段查询、超出委派管理范围这四类平台拒绝,现在都带一句面向最终用户的 `userMessage`,按请求语言(否则工作区默认语言,再否则英文)给出;数据、动作执行、流程启动三个入口对同一条"记录不存在"给同一种语言;code、状态码与 message 不变。 - 为什么改:中文用户此前看到的是英文的诊断句(含 API 名、id、字段名);控制台本来就优先显示 `userMessage`,缺的是服务端没给。 - 风险与回滚:只新增一个字段,不改既有字段;回滚 = 还原本 PR。新句子不点名字段、id 或对象,不泄露存在性(不存在与无权读同一句)。 - 先看:`packages/plugins/plugin-security/src/security-plugin-authz-middleware.ts`(两处标注)、`packages/core/src/utils/record-not-found.ts`、`packages/spec/src/system/operation-message.ts`(新增三键四语)。 - 两分钟验证:`pnpm --filter @objectstack/plugin-security exec vitest run src/platform-refusal-user-message.test.ts`,预期 10 条全绿,其中 zh-CN 用例断言中文句子。 - 需要你做的:无,席位落地。本 PR 非受管(`check-governed-merges.mjs --pr 34811` 判 NOT governed,0/43 路径,849 行),L1 通过、席位契约复审(contract review owed)PASS 且 CI 全绿后,由 o3-J 区落地。 ## What changes The platform answers four refusals with an end user's sentence on `userMessage`, in the caller's language: the request `locale`, else `workspaceLocale`, else `en` (the ladder the operation-message catalog already uses). `code`, HTTP status and `message` do not move; the operator half stays in `message`. | Row | Refusal | Key | Producers marked | |:--|:--|:--|:--| | 1 | per-row record lock (`RECORD_LOCKED`) | existing lock sentence | `plugin-approvals` `lifecycle-hooks.ts`: only the per-row lock; the three operator-facing bound refusals stay unmarked | | 3 | `RECORD_NOT_FOUND` | `record_not_found` (new) | `recordNotFoundError` in `@objectstack/core`, now taking the caller; every call site that has a context passes it | | 4 | masked-field query refusal (`PERMISSION_DENIED`) | `query_field_not_readable` (new) | all four producers: the security middleware's filter-oracle guard, `plugin-approvals` `payload-predicate-guard.ts`, `plugin-audit` `parent-field-query-guard.ts`, `service-analytics` `field-read-admission.ts`; the aggregate-role refusals stay unmarked (they are not row queries) | | 5 | `DELEGATION_SCOPE_VIOLATION` | `delegation_scope_violation` (new) | the security middleware's delegated-administration gate catch | - `packages/spec/src/system/operation-message.ts`: three placeholder-free keys in `en`, `zh-CN`, `ja-JP`, `es-ES`. None names a field, id, object or wire code. `record_not_found` reads the same for a missing row and an unreadable one (ruling 5985885287, existence hiding). - `packages/core/src/utils/operation-user-message.ts` (new, exported): `operationUserMessage(key, caller)` resolves the ladder against `BUILTIN_OPERATION_MESSAGES` and renders through `renderOperationMessage` with the built-in catalog. It is for producers that hold no `i18n` service, so it consults no deployment `errors.KEY` override; the security middleware's markings go through its own `userFacingDenialMessage`, which does. The caller is typed `object` (any context) and its `locale` / `workspaceLocale` are read defensively. - `mapDataError` and the batch-row classifier already relay a declared `userMessage`; nothing in the transport changed. - Docs: the flat `RECORD_NOT_FOUND` body examples in `content/docs/protocol/kernel/http-protocol.mdx` and `error-handling.mdx` now show `userMessage`. - The action and flow-start doors: `refuseDeniedSubjectLoad` and `refuseDeniedSubjectLoadBeforeDispatch` (`runtime/src/action-execution.ts`) take the caller, and every caller that holds the execution context passes it: the declarative update arm, the hand-off pre-check, the flow-start row admission (`refuseUnreadableFlowStartRecords`, shared by `POST /automation/:name/trigger`, the declared `type: flow` endpoint and the action door's flow branch) and the dispatch arm of every other action (`action-dispatch.ts`). So a routed row the caller cannot read, or an id that names nothing, answers the zh-CN sentence there exactly as the data door does for the same miss. - The bulk update faces' existence check: `assertRecordExists` (`metadata-protocol/src/protocol-record-reads.ts`, reached when the engine's update resolved `null` instead of refusing) takes the row's write context from `protocol-batch-data.ts`. - Not given a caller: the MCP-only sites (`runtime/src/domains/mcp.ts`'s `refuseDeniedSubjectLoad` call and the MCP metadata door). Their not-found carries the English `userMessage`; the MCP data doors relay it, the MCP metadata door carries no `userMessage` channel and answers as before. - **Clause-② widening.** `@objectstack/core` gains two public exports, `operationUserMessage` and the type `UserMessageCaller`, and `recordNotFoundError` an optional third parameter; `@objectstack/spec` gains three catalog keys, `record_not_found`, `query_field_not_readable` and `delegation_scope_violation`; the `/data` 404 body and the batch rows gain a `userMessage` key. Nothing is removed or narrowed. The changeset carries the same two declaration lines and stays `patch` (`Metadata-protocol: none`). ## Tests New: - `plugin-security/src/platform-refusal-user-message.test.ts` (10): real `ObjectQL` over a real `SqlDriver` with the real `SecurityPlugin`; zh-CN, workspace fallback and `en` for rows 3, 4, 5, plus relay through the real `mapDataError`, plus a CONTROL that a readable query is admitted. The delegated gate is a stub that throws the gate's real error class (the gate's own verdicts are pinned in `delegated-admin-gate.test.ts`). - `core/src/utils/operation-user-message.test.ts` (7): the ladder and the not-found envelope. - `spec/src/system/operation-message.test.ts`: every locale defines the three keys, no placeholders, no wire vocabulary, distinct texts, zh-CN render, unknown-locale fallback, deployment override. - zh-CN cases added to `payload-predicate-guard.test.ts`, `activity-predicate-guard.test.ts`, `field-read-admission-gate.test.ts`, `record-lock-user-facing-message.test.ts`. - `runtime/src/flow-start-record-admission.test.ts` (3, this round): the action door (`POST /actions`, a routed row the zh-CN caller cannot read) and the flow-start door (`POST /automation/:name/trigger`, a row key the zh-CN caller cannot read) answer the zh-CN `record_not_found` sentence with `code`, status and `message` unchanged and no run; CONTROL: the same start by a caller with no locale answers the English sentence. - `metadata-protocol/src/protocol.bulk-record-not-found.test.ts` (2, this round): an engine whose update resolves `null` for a missing row; `updateManyData` and `batchData` update give the zh-CN caller the zh-CN sentence on the row, CONTROL a caller with no locale the English one. Forced changes (tests that pin the exact error shape, now expecting the added field): - `metadata-protocol/src/protocol.batch-row-driver-text.test.ts`, `protocol.batch-row-http-status.test.ts`: the not-found batch row now carries `userMessage`. - `runtime/src/batch-row-http-status-real-driver.integration.test.ts`: same. - `plugin-approvals/src/record-lock-batch-row-status.integration.test.ts`: the lock row carries `userMessage`; its own-property list ends `statusCode, userMessage`. - `rest/src/record-field-access-route.test.ts`: the stub of the read path's not-found is now built by the real `recordNotFoundError`, so the "same 404 as the read path" comparison compares like with like. - `mcp/src/mcp-coded-refusal.test.ts` (data-door sites) and `mcp/src/stdio-data-bridge.not-found.test.ts`: the MCP not-found envelope carries the English `userMessage`. - `runtime/src/duplicate-record-user-message-doors-33790.test.ts` CONTROL: "a row whose producer marked nothing" used an id naming no row, which is now marked; it moves to a write naming an undeclared field. Its assertion (no `userMessage`) is unchanged. Ablation (each leg red, then restored; `git diff HEAD` empty on the touched source afterwards): | Leg | Mutation | Result | |:--|:--|:--| | 1 | filter-oracle guard rethrows without the marking | 3 failed / 10 | | 2 | delegation marking disabled | 3 failed / 10 | | 3 | `recordNotFoundError` marking deleted | 2 failed / 7 (core) | | 4 | record lock `lockedError(sentence)` without the user half | 2 failed / 19 | | 5 (this round) | `refuseDeniedSubjectLoad` drops its caller (`recordNotFoundError(objectName, recordId ?? '')`), via `scripts/ablation-replace.mjs` (anchor 1 → 0, blob `d9aad0e27984` → `9e3e53af6067`) | 2 failed / 35 (`flow-start-record-admission.test.ts`: the action-door and flow-start-door pins; the CONTROL stays green); restored, blob == HEAD `d9aad0e27984`, `git diff HEAD` empty; green leg 35 / 35 | ## Acceptance notes - Row 4's masked-field query is still served under Modify All on the object; that is the known open half of #33828, not widened or narrowed here. The new test grants no per-object Modify All. - The ui half (rows 6 and 8) is #34740. - **This round (L1 REWORK 6949320766):** S1 route (a) with N2 folded in, as above; the earlier body line saying `refuseDeniedSubjectLoad` and `assertRecordExists` had "no caller context in reach" was wrong and is gone. The fix also passes the caller at `action-dispatch.ts`'s dispatch arm (`refuseDeniedSubjectLoadBeforeDispatch`), which the verdict listed as taking none: its caller holds `ec`, and it is the path of every script, body and flow action, so without it the action door would still answer English. The out-of-surface paths of every round are named in claim amendment 6952327352 on #34699. `origin/main` is merged in (`c7362a7650`). - The MCP `run_action` hand-off pre-check (`subjectVerdictRefusal`, `action-dispatch.ts`) rebuilds the refusal from `message`, `status` and `code` only, so the caller passed at `refuseDeniedSubjectBeforeHandOff` does not reach that MCP answer as `userMessage`. MCP door, outside this PR's rows; noted, not filed (not measured at a public door). - `overlap-check.mjs` at this head: `origin/main` and #34850, #34784, #34709 merge cleanly; #34817 (open, ready) now conflicts on `plugin-audit/src/parent-field-query-guard.ts`, a file the first round edits (it merged cleanly at the takeover). Whichever of the two lands second merges the other. ## Verification ### This round (head `1130a716e0`) `origin/main` merged at `c7362a7650` (clean, no generated artifact deferred). After the merge, the dependency closure of `@objectstack/runtime` was rebuilt, and later every package under `packages/` (`turbo run build --concurrency=2`, lock verdict exit 0). The suites and typechecks below ran under the shared verify lock, and the exit codes are the commands' own. <details><summary>Package suites and typechecks</summary> | Command | Head | Result | |:--|:--|:--| | `pnpm --filter @objectstack/metadata-protocol typecheck` | `5ea3c15d15`, again at `1130a716e0` | exit 0 | | `pnpm --filter @objectstack/runtime typecheck` (includes `check:test-typecheck`) | `5ea3c15d15`, again at `1130a716e0` | exit 0 | | `pnpm --filter @objectstack/metadata-protocol test` | `5ea3c15d15` | exit 0 · Test Files 348 passed, 9 skipped · Tests 23093 passed, 45 skipped | | `pnpm --filter @objectstack/runtime test` (project `local`) | `5ea3c15d15` | exit 0 · Test Files 613 passed · Tests 11411 passed, 23 skipped | | mcp `mcp-coded-refusal.test.ts` + `stdio-data-bridge.not-found.test.ts` | `5ea3c15d15` | exit 0 · 186 / 186 | | rest `record-field-access-route.test.ts` | `5ea3c15d15` | exit 0 · 5 / 5 | | `flow-start-record-admission.test.ts` · `protocol.bulk-record-not-found.test.ts` | `1130a716e0` | exit 0 · 35 / 35 · 27 / 27 | `1130a716e0` changes only those two test files (one module-top import each), so the two files and both typechecks were re-run there. </details> <details><summary>Derived gates</summary> `node scripts/pm/dispatch-gates.mjs --commands` (no paths) derives 128 families for this PR's change set; the list is the same at `5ea3c15d15` and at `1130a716e0`. First pass at `5ea3c15d15`: 124 exit 0; three exited 3, PREREQUISITE NOT MET, because packages had no `dist/` (`spec check:skill-examples`, `check:dual-build-cjs-loads`, `check:i18n`); `check:test-source-alias` exited 1 on the two new pin files (their source under test loads `@objectstack/lint` and `@objectstack/metadata` inside a function). `1130a716e0` adds the module-top imports the gate asks for. After the full package build, all four were re-run at `1130a716e0`: each exit 0. The ratchet families `check:type-check-coverage` and `check:type-check-debt`, and `check:cross-package-test-inputs`, were re-run at `1130a716e0`: exit 0. Reconciliation: `dispatch-gates.mjs --ran` with an exit code on every line → 128 derived, 128 run, 0 NOT-MEASURED. `check-nul-bytes.mjs`: OK. No exported symbol was renamed or removed, so `check-platform-checklist.mjs` was not owed. CI runs the full farm on the PR. </details> <details><summary>Earlier rounds (through head d50700b)</summary> Package suites (shared box, under the verify lock): core, plugin-security, plugin-approvals, plugin-audit, service-analytics, service-print, metadata-protocol, rest, objectql (13603 tests), runtime, spec (27174 tests). The first run surfaced the six forced shape pins above; each failing file was re-run green after its fix. Merge-tree against the open PRs that share a file (none shares a hunk), and against main: | Against | Head | `git merge-tree` | |:--|:--|:--| | #34734 (`action-execution.ts`) | `08a588b12b` | exit 0, 0 conflicts | | #34709 (`engine-update.ts`) | `13741cb992` | exit 0, 0 conflicts | | #34565 (`engine-delete-and-aggregate.ts`) | `779d1aa330` | exit 0, 0 conflicts | | `origin/main` | `6dd5716329` | exit 0 | Derived gates: `node scripts/pm/dispatch-gates.mjs --commands` derives 102 for this file surface. After a full `turbo run build`, all 102 ran at `21b0016086`: 101 exit 0, and `check:test-source-alias` exit 1 on three test files this change edits (their source under test loads a dependency inside a function body). `f3d1774be2` adds the module-top imports the gate asks for; the gate then exits 0 and the three files re-run green. `f8ef82d7bb` adds the two doc examples, which derive 23 more docs gates: all 23 exit 0, and the four earlier doc-reading gates (`check:doc-authoring`, `check-affected-docs`, `check-drift-comment`, spec `check:docs`) re-ran exit 0. Reconciliation: `dispatch-gates.mjs --ran` → 125 derived, 125 run, 0 NOT-MEASURED. CI's workspace type check then caught a weak-type error (a context declaring neither locale field was refused for the caller type) in `plugin-audit` and the rest test; `1fce1406e2` types the caller as `object`, and `turbo run typecheck` over the 11 touched packages passes (52/52 tasks). CI's Test Core shard 9 then caught the two MCP shape pins above; `d50700b346` updates them. Before that push, the two MCP files re-ran green, and the other packages whose tests name the not-found refusal ran locally, all exit 0: plugin-auth, service-settings, downstream-contract, client, driver-sql, organizations, plugin-sharing, http-conformance, scenarios, service-mailbox, service-storage, verify, plugin-hono-server, types. `check-platform-checklist.mjs --changed-from origin/main`: OK, 21 anchors judged, 0 lost. `eslint --no-inline-config` on the changed `.ts` files: exit 0. </details> ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. (Only catalog strings added.) - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes. (eslint run on the changed files.) - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: its generated artifacts are regenerated and committed. (No generated artifact moves: the keys are catalog strings, not schema.) - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. - [x] The *Before Submitting* list in CONTRIBUTING.md is done. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01WGufzfr1xZSFZzCR8HnqXX <!-- signed: repo:objectstack#3 · os-support-ai · session_01WGufzfr1xZSFZzCR8HnqXX --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent cb7d514 commit 9cf74ae

43 files changed

Lines changed: 784 additions & 64 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
---
2+
"@objectstack/spec": patch
3+
"@objectstack/core": patch
4+
"@objectstack/plugin-security": patch
5+
"@objectstack/plugin-approvals": patch
6+
"@objectstack/plugin-audit": patch
7+
"@objectstack/service-analytics": patch
8+
"@objectstack/objectql": patch
9+
"@objectstack/metadata-protocol": patch
10+
"@objectstack/runtime": patch
11+
"@objectstack/rest": patch
12+
"@objectstack/service-print": patch
13+
---
14+
15+
Clause-②: yes (widening)
16+
Metadata-protocol: none
17+
18+
Four refusals the platform writes now carry a `userMessage` in the caller's language (the request locale, else the workspace default), beside a code, status and `message` that do not change. Before this a zh-CN user read each of them in English.
19+
20+
- `404 RECORD_NOT_FOUND`: "This record does not exist, or you do not have access to it." (`record_not_found`). It names no id and no API name, and it says both causes because the by-id doors answer an unreadable id exactly as a missing one.
21+
- `403 PERMISSION_DENIED` for a query that filters, sorts or groups by a field the caller may not read (`query_field_not_readable`), from all four producers of that refusal: plugin-security, the approval snapshot guard, the audit parent-field guard and analytics. It names no field. The aggregate refusal is unchanged.
22+
- `403 DELEGATION_SCOPE_VIOLATION`, a delegated administrator's write outside their own scope (`delegation_scope_violation`). The gate's reason stays in `message`.
23+
- `409 RECORD_LOCKED` from an approval's record lock: the localized sentence is now also the `userMessage`, without the `RECORD_LOCKED: ` prefix. The bound refusals that name an API name for the developer mark none.
24+
25+
The three sentences are new keys of the shared operation-message catalog (`BUILTIN_OPERATION_MESSAGES`, in `en`, `zh-CN`, `ja-JP` and `es-ES`), so a deployment can override them under `errors.<key>` where the producer holds an i18n service. The widening: `@objectstack/spec` adds the catalog keys `record_not_found`, `query_field_not_readable` and `delegation_scope_violation`; `@objectstack/core` exports `operationUserMessage(messageKey, caller)` and its caller type `UserMessageCaller` for producers that hold no i18n service, and `recordNotFoundError` takes the caller as an optional third argument. Every door that holds the caller's execution context passes it, the action door's subject load, the flow-start door's row admission and the bulk update faces' existence check included, so the same miss reads in the same language at the data, action and flow-start doors.

‎content/docs/protocol/kernel/error-handling.mdx‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -684,14 +684,16 @@ resource is named in `message`.
684684
685685
<Callout type="info">
686686
**The `/data` door answers a different code.** A record missing from a CRUD route is
687-
`RECORD_NOT_FOUND` in the flat envelope, with the object as a top-level sibling — see
687+
`RECORD_NOT_FOUND` in the flat envelope, with the object as a top-level sibling and the
688+
end user's sentence on `userMessage`, in the caller's language — see
688689
[HTTP API](/docs/protocol/kernel/http-protocol):
689690
690691
```json
691692
{
692693
"error": "Record acc_999 not found in account",
693694
"code": "RECORD_NOT_FOUND",
694-
"object": "account"
695+
"object": "account",
696+
"userMessage": "This record does not exist, or you do not have access to it."
695697
}
696698
```
697699

‎content/docs/protocol/kernel/http-protocol.mdx‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -583,12 +583,16 @@ A single-record read returns a `GetDataResponse`: the `object` name, the record
583583
**Not Found (HTTP 404):**
584584

585585
REST error responses use a flat envelope: a top-level `error` message string and
586-
a string `code`, plus optional context fields (`object`, per-field `fields`):
586+
a string `code`, plus optional context fields (`object`, per-field `fields`).
587+
`userMessage` is the sentence for the end user, in the caller's language (the
588+
request locale, else the workspace default, else English); it reads the same
589+
whether the row is missing or hidden from the caller:
587590
```json
588591
{
589592
"error": "Record acc_999 not found in account",
590593
"code": "RECORD_NOT_FOUND",
591-
"object": "account"
594+
"object": "account",
595+
"userMessage": "This record does not exist, or you do not have access to it."
592596
}
593597
```
594598

‎packages/core/src/index.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,10 @@ export * from './utils/metadata-activation-store.js';
221221
// with. `@objectstack/metadata-protocol` re-exports it from its original home.
222222
export * from './utils/record-not-found.js';
223223

224+
// [#34699] A catalog sentence in the caller's language, for the `userMessage` a
225+
// producer that holds no `i18n` service marks beside its developer `message`.
226+
export * from './utils/operation-user-message.js';
227+
224228
// The one `OBJECT_NOT_FOUND` envelope: the data door's object-existence gate
225229
// and the engine's in-process verbs refuse a name the registry does not
226230
// resolve with it (one name space for both doors).

‎packages/core/src/security/own-row-delete-routes.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -216,7 +216,7 @@ export async function removeOwnRow(
216216
| Record<string, unknown>
217217
| null
218218
| undefined;
219-
if (!row) throw recordNotFoundError(door.object, id);
219+
if (!row) throw recordNotFoundError(door.object, id, context);
220220

221221
// Step 6: the structural check, and the only thing that admits the write below.
222222
if (row[door.ownerField] !== callerId) throw notYourRowError(door, id);
@@ -230,7 +230,7 @@ export async function removeOwnRow(
230230
} as ExecutionContext,
231231
});
232232
// The driver's own "nothing matched": the row went between the read and here.
233-
if (removed === false || removed === 0) throw recordNotFoundError(door.object, id);
233+
if (removed === false || removed === 0) throw recordNotFoundError(door.object, id, context);
234234
}
235235

236236
async function handleRemoveOwnRow(
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
import { describe, it, expect } from 'vitest';
4+
import { BUILTIN_OPERATION_MESSAGES } from '@objectstack/spec/system';
5+
import { operationUserMessage } from './operation-user-message.js';
6+
import { recordNotFoundError } from './record-not-found.js';
7+
8+
/**
9+
* [#34699] The catalog sentence a producer with no `i18n` service marks as a
10+
* refusal's `userMessage`, and the not-found that marks one.
11+
*/
12+
describe('operationUserMessage — the caller ladder', () => {
13+
const ZH = BUILTIN_OPERATION_MESSAGES['zh-CN'].record_not_found;
14+
const EN = BUILTIN_OPERATION_MESSAGES.en.record_not_found;
15+
16+
it('the request locale first', () => {
17+
expect(operationUserMessage('record_not_found', { locale: 'zh-CN', workspaceLocale: 'en' })).toBe(ZH);
18+
});
19+
20+
it('a request locale the catalog does not carry falls to the workspace default', () => {
21+
expect(operationUserMessage('record_not_found', { locale: 'xx-YY', workspaceLocale: 'zh-CN' })).toBe(ZH);
22+
});
23+
24+
it('a base language reaches its regional catalog (zh → zh-CN)', () => {
25+
expect(operationUserMessage('record_not_found', { locale: 'zh' })).toBe(ZH);
26+
});
27+
28+
it('no caller, or no rung the catalog carries: en', () => {
29+
expect(operationUserMessage('record_not_found')).toBe(EN);
30+
expect(operationUserMessage('record_not_found', null)).toBe(EN);
31+
expect(operationUserMessage('record_not_found', { locale: 'xx-YY', workspaceLocale: '' })).toBe(EN);
32+
});
33+
});
34+
35+
describe('recordNotFoundError — the userMessage beside an unchanged envelope', () => {
36+
it('keeps code, status, object and the developer message byte for byte', () => {
37+
const err = recordNotFoundError('account', 'acc_1', { locale: 'zh-CN' }) as Error & Record<string, unknown>;
38+
expect([err.code, err.status, err.object]).toEqual(['RECORD_NOT_FOUND', 404, 'account']);
39+
expect(err.message).toBe('Record acc_1 not found in account');
40+
});
41+
42+
it("marks the sentence in the caller's language, naming no id and no API name", () => {
43+
const err = recordNotFoundError('account', 'acc_1', { locale: 'zh-CN' }) as Error & { userMessage?: string };
44+
expect(err.userMessage).toBe(BUILTIN_OPERATION_MESSAGES['zh-CN'].record_not_found);
45+
expect(err.userMessage).not.toContain('acc_1');
46+
expect(err.userMessage).not.toContain('account');
47+
});
48+
49+
it('with no caller, the English sentence', () => {
50+
const err = recordNotFoundError('account', 'acc_1') as Error & { userMessage?: string };
51+
expect(err.userMessage).toBe(BUILTIN_OPERATION_MESSAGES.en.record_not_found);
52+
});
53+
});
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
import { BUILTIN_OPERATION_MESSAGES, renderOperationMessage, resolveBundleLocale } from '@objectstack/spec/system';
4+
5+
/**
6+
* [#34699] Whose language a refusal's `userMessage` is in: the operation's
7+
* execution context, or any object carrying its two locale fields —
8+
* `locale` (the request's own, `ExecutionContext.locale`) and
9+
* `workspaceLocale` (the workspace default, the ladder's second rung).
10+
*
11+
* Typed `object`, not an interface of two optional fields: the contexts that
12+
* reach producers (engine, hook and middleware contexts, test callers) mostly
13+
* declare neither field, and TypeScript refuses such a value for an all-optional
14+
* type it shares no property with. The fields are read defensively instead: a
15+
* rung that is not a non-empty string the catalog carries is skipped.
16+
*/
17+
export type UserMessageCaller = object;
18+
19+
interface CallerLocales {
20+
readonly locale?: unknown;
21+
readonly workspaceLocale?: unknown;
22+
}
23+
24+
/**
25+
* [#34699] A placeholder-free sentence of the shared operation-message catalog
26+
* (`BUILTIN_OPERATION_MESSAGES`, `@objectstack/spec/system`) in the caller's
27+
* language: the `userMessage` a producer marks beside a developer `message`.
28+
*
29+
* The locale is the first rung of the caller's ladder the built-in catalog
30+
* carries — the request's locale, then the workspace default — the ladder
31+
* plugin-security's refusals use, so a request in a language the catalog has
32+
* no text in falls to the workspace default before `en`. Absent both, `en`.
33+
*
34+
* For producers that hold no `i18n` service: no deployment `errors.<key>`
35+
* override is consulted. A producer that holds one renders through
36+
* `renderOperationMessage` with its `translate` instead.
37+
*/
38+
export function operationUserMessage(messageKey: string, caller?: UserMessageCaller | null): string {
39+
const rungs = caller as CallerLocales | null | undefined;
40+
const locale = [rungs?.locale, rungs?.workspaceLocale].find(
41+
(candidate): candidate is string =>
42+
typeof candidate === 'string' &&
43+
candidate.length > 0 &&
44+
resolveBundleLocale(BUILTIN_OPERATION_MESSAGES, candidate) !== undefined,
45+
);
46+
return renderOperationMessage({ messageKey }, { locale });
47+
}

‎packages/core/src/utils/record-not-found.ts‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
22

3+
import { operationUserMessage, type UserMessageCaller } from './operation-user-message.js';
4+
35
/**
46
* [#4435] The 404 a single-record operation answers when the id names no row.
57
*
@@ -51,14 +53,25 @@
5153
* This is the same move `engineCanRollBack` made for the same reason — a fact
5254
* two layers must agree on lives in the layer beneath both, not in a copy each.
5355
*/
54-
export function recordNotFoundError(object: string, id: string | number): Error {
56+
export function recordNotFoundError(
57+
object: string,
58+
id: string | number,
59+
caller?: UserMessageCaller | null,
60+
): Error {
5561
const err = new Error(`Record ${id} not found in ${object}`) as Error & {
5662
code?: string;
5763
status?: number;
5864
object?: string;
65+
userMessage?: string;
5966
};
6067
err.code = 'RECORD_NOT_FOUND';
6168
err.status = 404;
6269
err.object = object;
70+
// [#34699] The end user's half, beside the developer sentence above (which
71+
// keeps its id and API name byte for byte). The by-id doors answer an id
72+
// the caller cannot read exactly as an id naming no row (ruling of record
73+
// 5985885287), so `record_not_found` says both and decides neither; it
74+
// names no id and no API name (#7414).
75+
err.userMessage = operationUserMessage('record_not_found', caller);
6376
return err;
6477
}

‎packages/mcp/src/mcp-coded-refusal.test.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -197,7 +197,12 @@ describe('MCP tools over HTTP /mcp: a coded refusal carries its code (#23509)',
197197
expect(result.isError).toBe(true);
198198
expect(result.content).toHaveLength(1);
199199
expect(JSON.parse(result.content[0].text)).toEqual({
200-
error: { code: 'RECORD_NOT_FOUND', message: 'Record t9 not found in task', status: 404 },
200+
error: {
201+
code: 'RECORD_NOT_FOUND', message: 'Record t9 not found in task', status: 404,
202+
// The end user's sentence the producer marks (#34699): no caller here, so
203+
// English. The metadata door's answer carries no `userMessage` channel.
204+
...(site.metaDoor ? {} : { userMessage: 'This record does not exist, or you do not have access to it.' }),
205+
},
201206
});
202207
});
203208

‎packages/mcp/src/stdio-data-bridge.not-found.test.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -209,7 +209,14 @@ async function getRecordOverHttp(objectName: string, recordId: string) {
209209

210210
/** The coded envelope `get_record` answers a miss with, as both doors put it on the wire. */
211211
function notFoundWire(object: string, id: string) {
212-
return { error: { code: 'RECORD_NOT_FOUND', message: `Record ${id} not found in ${object}`, status: 404 } };
212+
// `userMessage`: the end user's sentence the producer marks (#34699). The stdio
213+
// bridge passes no caller locale, so it is the English one.
214+
return {
215+
error: {
216+
code: 'RECORD_NOT_FOUND', message: `Record ${id} not found in ${object}`, status: 404,
217+
userMessage: 'This record does not exist, or you do not have access to it.',
218+
},
219+
};
213220
}
214221

215222
describe('stdio get_record answers a missing or hidden id with the coded RECORD_NOT_FOUND / 404', () => {

0 commit comments

Comments
 (0)