diff --git a/.changeset/32656-user-text-request-locale.md b/.changeset/32656-user-text-request-locale.md new file mode 100644 index 00000000000..4fdc0b32223 --- /dev/null +++ b/.changeset/32656-user-text-request-locale.md @@ -0,0 +1,21 @@ +--- +'@objectstack/spec': minor +'@objectstack/core': patch +'@objectstack/metadata-protocol': patch +'@objectstack/rest': patch +'@objectstack/runtime': patch +--- + +feat(metadata-protocol): a metadata write's advisories and refusals come back in the caller's language + +Clause-②: yes (widening) — `SaveMetaItemRequestSchema` and `PublishMetaItemRequestSchema` gain an optional, server-stated `userTextLocales` member (at most two locale codes; the doors build these requests member by member, so a wire body never sets it, like `client`), and `ExecutionContextSchema` gains an optional `workspaceLocale`. The batch publish body (`PublishPackageDraftsRequestSchema`) is unchanged; its door states the locales to the protocol call directly. Nothing that was accepted before is refused now; a request that states no locales composes in `en`, and a finding whose rule has no user sentence carries no `userMessage`, exactly as before. +Metadata-protocol: added +Skills-docs: none — `skills/**` and `content/docs/**` teach what a metadata author writes; `userTextLocales` and `workspaceLocale` are stated by the server from the caller's request and workspace, never authored or sent by a client, so no taught sentence moves. The generated reference pages (`content/docs/references/**`) are regenerated. + +Ruling C on #32440: the producer of a finding writes its user-facing sentence in the request's language, else the workspace's default language, else English, and every client shows it as received. The authoring rules already carry a sentence in twelve languages for most findings (#32790); this change composes it on the server: + +- Every `/meta` save, single-item publish and package publish now fills `userMessage` on each advisory, and on each issue of a 422 refusal, for a rule that has a user sentence. `rule`, `message`, `hint`, `path` and `where` are unchanged. +- The door states the two languages it resolved: the request's own (its `Accept-Language` header or `locale` query) and the workspace default. The execution context used to fold them into one `locale`, so a request in a language the platform has no text in fell straight to English; it now carries the workspace default on its own as `workspaceLocale`, and the core helper `userTextLocalesOf(ctx)` reads the pair in order. +- The REST server and the runtime dispatcher both state them, for saves, publishes and package publishes. + +Not in this change: the refusal sentences written outside the authoring rules (the packaged permission-set lock, the permission middleware's denials) move onto the same ladder in a follow-up PR on #32656. diff --git a/content/docs/references/api/protocol.mdx b/content/docs/references/api/protocol.mdx index 4c9f2a86416..9673a02d599 100644 --- a/content/docs/references/api/protocol.mdx +++ b/content/docs/references/api/protocol.mdx @@ -2538,6 +2538,7 @@ The authoring surface of a metadata write. Closed: `copilot` is an AI assistant' | **message** | `string` | optional | Optional human-readable note recorded with the publish history event. | | **packageId** | `string \| null` | optional | ADR-0048 — the software package the draft being promoted was listed under, when the caller has one to state (`?package=` on the REST door). Named, the publish promotes that package's draft and no other. ABSENT names no package: the publish promotes the draft a draft save that names no package writes — the draft of the one package the item's active rows are bound to, else its package-unbound draft, promoted into that package — and answers `404 NO_DRAFT` when neither exists, as the strict draft read does. For an item never published into a package it is the package-unbound draft, else the one package's draft. It is refused `409 RESOURCE_CONFLICT` when the active rows (or, with none and no package-unbound draft, the drafts) are bound to two or more packages. ⚠️ `null` is NOT the same as absent: the implementation branches on the KEY BEING PRESENT, and `null` pins the lookup to the package-UNBOUND row. Spread it in conditionally; a present-and-`undefined` key coerces to `null` downstream and makes a package-bound draft unfindable — a silent `no_draft`. | | **member** | `string` | optional | Bundle member selector, for a metadata type whose identity is a pair (today only `email_template`, identified by `(name, locale)`): the member this request addresses, spelled as its discriminator value (`zh-CN`). Absent, the canonical member (`en-US` for `email_template`), which is what a bare-name read answers; naming the canonical value is the same request. It is not the response translation locale, which `?locale=` and `Accept-Language` choose. Refused with 400 `VALIDATION_ERROR` on a type that has no members, and for a blank value or one longer than a stored member can be (100 characters). A well-formed member with nothing stored or shipped answers as that door answers an absent item. | +| **userTextLocales** | `string[]` | optional | The locales the user-facing sentences of this write's findings (`advisories[].userMessage`, and `issues[].userMessage` on its 422) are composed in, in ladder order: the locale the request names, then the workspace default. Each is read against the platform locale table, whole and then one subtag shorter at a time; a value that names no table language is passed over, and `en` is the last rung. Stated by the door that holds the request (the REST door and the dispatcher state `[ExecutionContext.locale, ExecutionContext.workspaceLocale]`), never read from a wire body. ABSENT ⇒ the sentences are composed in `en`. It selects a language only: what is judged, refused or saved does not depend on it. | --- @@ -2908,6 +2909,7 @@ Answer to a device registration: the device id the client keeps | **writeFace** | `Enum<'package-duplicate' \| 'meta-envelope' \| 'meta-dispatch' \| 'external-import'>` | optional | Which write door a refusal is being rendered FOR — stated by the SERVER, never by a remote caller: every door builds this request field by field and never spreads a request body into it, so there is no path for a client to smuggle a face in, and a face arriving in a wire body is simply never read. Two refusals branch on it, for different questions: the 409 destructive-change remedy names the acknowledgement mechanism that actually exists on the refusing door (`?force=true` on the REST doors; the dispatcher, the duplicate-package door and the external-table import have none), and the 422 invalid-metadata message adapts to whether a structured `issues[]` channel reaches the consumer beside it. Absent = the conservative default wording. | | **surface** | `Enum<'copilot' \| 'mcp' \| 'studio' \| 'api'>` | optional | The authoring surface this save is made through (see `MetadataAuthoringSurfaceSchema`). A draft save (`mode: 'draft'`) stamps it as `by` on every key path it changes, the entries the strict draft read serves as `draftChanges`; an active save records no per-key provenance. ABSENT stamps `api`. On the REST door and the runtime dispatcher it is the `?surface=` query parameter, which takes `studio` or `api` and refuses every other value `400 VALIDATION_ERROR`, `copilot` and `mcp` included: `copilot` is stated only by an in-process AI tool calling the save and `mcp` only by the MCP build door after it verified the client's token, never by a remote caller, so an HTTP request cannot mark its own write as the copilot's or an MCP agent's. A value outside the set in-process is refused `400 INVALID_REQUEST`, before anything is written. | | **client** | `{ id: string; name?: string }` | optional | The OAuth client this save is made by (see `MetadataAuthoringClientSchema`), stated only by the MCP build door, in-process, from the token it verified. Only with `surface: 'mcp'`: a `client` beside any other surface, or a malformed one, is refused `400 INVALID_REQUEST` before anything is written. A draft save stamps it as `client` beside `by: 'mcp'` on every key path it changes; an active save records it nowhere. No HTTP door reads it: the REST door and the dispatcher build this request member by member, so a `client` in a wire body or query is never read. | +| **userTextLocales** | `string[]` | optional | The locales the user-facing sentences of this write's findings (`advisories[].userMessage`, and `issues[].userMessage` on its 422) are composed in, in ladder order: the locale the request names, then the workspace default. Each is read against the platform locale table, whole and then one subtag shorter at a time; a value that names no table language is passed over, and `en` is the last rung. Stated by the door that holds the request (the REST door and the dispatcher state `[ExecutionContext.locale, ExecutionContext.workspaceLocale]`), never read from a wire body. ABSENT ⇒ the sentences are composed in `en`. It selects a language only: what is judged, refused or saved does not depend on it. | ### Nested Shape: `SaveMetaItemRequest.client` diff --git a/content/docs/references/data/data-engine.mdx b/content/docs/references/data/data-engine.mdx index 52b669a055a..99dbc5f8737 100644 --- a/content/docs/references/data/data-engine.mdx +++ b/content/docs/references/data/data-engine.mdx @@ -50,6 +50,7 @@ const result = BaseEngineOptionsSchema.parse(data); | **tenantId** | `string` | optional | | | **timezone** | `string` | optional | | | **locale** | `string` | optional | | +| **workspaceLocale** | `string` | optional | | | **currency** | `string` | optional | | | **positions** | `string[]` | optional (default: `[]`) | | | **principalKind** | `Enum<'human' \| 'agent' \| 'service' \| 'guest' \| 'system'>` | optional | | @@ -107,6 +108,7 @@ Options for DataEngine.aggregate operations | **tenantId** | `string` | optional | | | **timezone** | `string` | optional | | | **locale** | `string` | optional | | +| **workspaceLocale** | `string` | optional | | | **currency** | `string` | optional | | | **positions** | `string[]` | optional (default: `[]`) | | | **principalKind** | `Enum<'human' \| 'agent' \| 'service' \| 'guest' \| 'system'>` | optional | | @@ -162,6 +164,7 @@ Options for DataEngine.count operations | **tenantId** | `string` | optional | | | **timezone** | `string` | optional | | | **locale** | `string` | optional | | +| **workspaceLocale** | `string` | optional | | | **currency** | `string` | optional | | | **positions** | `string[]` | optional (default: `[]`) | | | **principalKind** | `Enum<'human' \| 'agent' \| 'service' \| 'guest' \| 'system'>` | optional | | @@ -218,6 +221,7 @@ Options for DataEngine.delete operations | **tenantId** | `string` | optional | | | **timezone** | `string` | optional | | | **locale** | `string` | optional | | +| **workspaceLocale** | `string` | optional | | | **currency** | `string` | optional | | | **positions** | `string[]` | optional (default: `[]`) | | | **principalKind** | `Enum<'human' \| 'agent' \| 'service' \| 'guest' \| 'system'>` | optional | | @@ -296,6 +300,7 @@ Options for DataEngine.insert operations | **tenantId** | `string` | optional | | | **timezone** | `string` | optional | | | **locale** | `string` | optional | | +| **workspaceLocale** | `string` | optional | | | **currency** | `string` | optional | | | **positions** | `string[]` | optional (default: `[]`) | | | **principalKind** | `Enum<'human' \| 'agent' \| 'service' \| 'guest' \| 'system'>` | optional | | @@ -357,6 +362,7 @@ Query options for IDataEngine.find() operations | **tenantId** | `string` | optional | | | **timezone** | `string` | optional | | | **locale** | `string` | optional | | +| **workspaceLocale** | `string` | optional | | | **currency** | `string` | optional | | | **positions** | `string[]` | optional (default: `[]`) | | | **principalKind** | `Enum<'human' \| 'agent' \| 'service' \| 'guest' \| 'system'>` | optional | | @@ -444,6 +450,7 @@ Options for DataEngine.update operations | **tenantId** | `string` | optional | | | **timezone** | `string` | optional | | | **locale** | `string` | optional | | +| **workspaceLocale** | `string` | optional | | | **currency** | `string` | optional | | | **positions** | `string[]` | optional (default: `[]`) | | | **principalKind** | `Enum<'human' \| 'agent' \| 'service' \| 'guest' \| 'system'>` | optional | | @@ -520,6 +527,7 @@ QueryAST-aligned options for DataEngine.aggregate operations | **tenantId** | `string` | optional | | | **timezone** | `string` | optional | | | **locale** | `string` | optional | | +| **workspaceLocale** | `string` | optional | | | **currency** | `string` | optional | | | **positions** | `string[]` | optional (default: `[]`) | | | **principalKind** | `Enum<'human' \| 'agent' \| 'service' \| 'guest' \| 'system'>` | optional | | @@ -608,6 +616,7 @@ QueryAST-aligned options for DataEngine.count operations | **tenantId** | `string` | optional | | | **timezone** | `string` | optional | | | **locale** | `string` | optional | | +| **workspaceLocale** | `string` | optional | | | **currency** | `string` | optional | | | **positions** | `string[]` | optional (default: `[]`) | | | **principalKind** | `Enum<'human' \| 'agent' \| 'service' \| 'guest' \| 'system'>` | optional | | @@ -678,6 +687,7 @@ QueryAST-aligned options for DataEngine.delete operations | **tenantId** | `string` | optional | | | **timezone** | `string` | optional | | | **locale** | `string` | optional | | +| **workspaceLocale** | `string` | optional | | | **currency** | `string` | optional | | | **positions** | `string[]` | optional (default: `[]`) | | | **principalKind** | `Enum<'human' \| 'agent' \| 'service' \| 'guest' \| 'system'>` | optional | | @@ -743,6 +753,7 @@ QueryAST-aligned query options for IDataEngine.find() operations | **tenantId** | `string` | optional | | | **timezone** | `string` | optional | | | **locale** | `string` | optional | | +| **workspaceLocale** | `string` | optional | | | **currency** | `string` | optional | | | **positions** | `string[]` | optional (default: `[]`) | | | **principalKind** | `Enum<'human' \| 'agent' \| 'service' \| 'guest' \| 'system'>` | optional | | @@ -836,6 +847,7 @@ QueryAST-aligned options for DataEngine.update operations | **tenantId** | `string` | optional | | | **timezone** | `string` | optional | | | **locale** | `string` | optional | | +| **workspaceLocale** | `string` | optional | | | **currency** | `string` | optional | | | **positions** | `string[]` | optional (default: `[]`) | | | **principalKind** | `Enum<'human' \| 'agent' \| 'service' \| 'guest' \| 'system'>` | optional | | diff --git a/content/docs/references/kernel/execution-context.mdx b/content/docs/references/kernel/execution-context.mdx index d4062ae74fa..c7582134596 100644 --- a/content/docs/references/kernel/execution-context.mdx +++ b/content/docs/references/kernel/execution-context.mdx @@ -56,6 +56,7 @@ const result = AuthGateCodeSchema.parse(data); | **tenantId** | `string` | optional | | | **timezone** | `string` | optional | | | **locale** | `string` | optional | | +| **workspaceLocale** | `string` | optional | | | **currency** | `string` | optional | | | **positions** | `string[]` | optional (default: `[]`) | | | **principalKind** | `Enum<'human' \| 'agent' \| 'service' \| 'guest' \| 'system'>` | optional | | diff --git a/packages/core/src/security/assemble-execution-context.test.ts b/packages/core/src/security/assemble-execution-context.test.ts index 5f2e06dcca2..c1ba4c9ab59 100644 --- a/packages/core/src/security/assemble-execution-context.test.ts +++ b/packages/core/src/security/assemble-execution-context.test.ts @@ -25,6 +25,7 @@ import { assembleExecutionContext, assembleExecutionContextOrGuest, ENTRY_EXECUTION_CONTEXT_FIELDS, + userTextLocalesOf, type EntryLocalization, type OAuthTokenProvenance, } from './assemble-execution-context.js'; @@ -252,11 +253,18 @@ describe('#6216 — runtime/dispatcher face: byte-for-byte parity with the pre-# // principal whose token names a client — absent everywhere else, // and carrying that client's id. The parity pin below is otherwise // unweakened: every other key still compares byte-for-byte. - const { performedBy, ...restOfNow } = observable(now); + // + // [#32656] The second argued delta, subtracted and pinned the same + // way: the envelope now also carries the workspace default locale + // on its own (ruling C on #32440 — the user-text ladder needs it + // UNFOLDED from `locale`). Present exactly when an authenticated + // principal's localization names one, and equal to that value. + const { performedBy, workspaceLocale, ...restOfNow } = observable(now); expect(restOfNow).toEqual(observable(before)); expect(performedBy).toEqual( authz.userId && oauth?.clientId ? { clientId: oauth.clientId } : undefined, ); + expect(workspaceLocale).toEqual(authz.userId ? localization?.locale : undefined); }); } } @@ -291,7 +299,11 @@ describe('#6216 — REST face: byte-for-byte parity with the pre-#6216 assembly' return; } expect(now).toBeDefined(); - expect(observable(now)).toEqual(observable(before)); + // [#32656] The one argued delta, subtracted and pinned positively + // (see the dispatcher face above): the workspace default locale. + const { workspaceLocale, ...restOfNow } = observable(now!); + expect(restOfNow).toEqual(observable(before)); + expect(workspaceLocale).toEqual(localization?.locale); }); } } @@ -724,3 +736,37 @@ describe('[ADR-0151 D3] an AI service account is an agent principal of its own: expect(person.onBehalfOf).toBeUndefined(); }); }); + +describe('[#32656] the user-text ladder: the workspace default rides the envelope UNFOLDED', () => { + const assembly = (localization: EntryLocalization | undefined, requestLocale: string | undefined, authz = HUMAN_MINIMAL) => ({ + authz, oauth: undefined, localization, requestLocale, accessToken: undefined, authGate: undefined, + }); + + it('a request locale wins `locale`, while `workspaceLocale` still names the workspace default', () => { + for (const ctx of [ + assembleExecutionContext(assembly({ locale: 'zh-CN' }, 'de')), + assembleExecutionContextOrGuest(assembly({ locale: 'zh-CN' }, 'de')), + ]) { + expect(ctx?.locale).toBe('de'); + expect(ctx?.workspaceLocale).toBe('zh-CN'); + expect(ExecutionContextSchema.parse(ctx).workspaceLocale).toBe('zh-CN'); + expect(userTextLocalesOf(ctx)).toEqual(['de', 'zh-CN']); + } + }); + + it('no workspace default ⇒ no workspaceLocale key; a guest envelope never carries one', () => { + expect('workspaceLocale' in assembleExecutionContext(assembly(undefined, 'de'))!).toBe(false); + const guest = assembleExecutionContextOrGuest(assembly({ locale: 'zh-CN' }, 'de', ANONYMOUS)); + expect(guest?.principalKind).toBe('guest'); + expect('workspaceLocale' in guest!).toBe(false); + }); + + it('userTextLocalesOf reads the ladder in order and drops what is absent or empty', () => { + expect(userTextLocalesOf(undefined)).toEqual([]); + expect(userTextLocalesOf(null)).toEqual([]); + expect(userTextLocalesOf({})).toEqual([]); + expect(userTextLocalesOf({ locale: 'fr' })).toEqual(['fr']); + expect(userTextLocalesOf({ workspaceLocale: 'ja' })).toEqual(['ja']); + expect(userTextLocalesOf({ locale: '', workspaceLocale: 'ja' })).toEqual(['ja']); + }); +}); diff --git a/packages/core/src/security/assemble-execution-context.ts b/packages/core/src/security/assemble-execution-context.ts index 99d8bde9b59..9cd91cbbb3b 100644 --- a/packages/core/src/security/assemble-execution-context.ts +++ b/packages/core/src/security/assemble-execution-context.ts @@ -162,6 +162,7 @@ export const ENTRY_EXECUTION_CONTEXT_FIELDS = [ 'oauthScopes', 'timezone', 'locale', + 'workspaceLocale', 'currency', ] as const satisfies readonly EntryExecutionContextField[]; @@ -422,6 +423,9 @@ function entryFields( // beside the Chinese label of the very field it names. timezone: anonymous ? undefined : localization?.timezone, locale: anonymous ? undefined : (requestLocale ?? localization?.locale), + // The workspace default alone, beside the fold above: the second rung of + // the user-text ladder (`ExecutionContextSchema.workspaceLocale`). + workspaceLocale: anonymous ? undefined : localization?.locale, currency: anonymous ? undefined : localization?.currency, }; } @@ -454,3 +458,22 @@ export function assembleExecutionContextOrGuest( ): ExecutionContext { return emit(entryFields(input, !input.authz.userId)); } + +/** + * The locales a door hands a producer of user-facing text, in ladder order: the + * request's locale (the fold `locale`, which is the request's own when it names + * one and the workspace default otherwise), then the workspace default alone + * (`workspaceLocale`). That is the ladder `ApiErrorSchema.userMessage` + * ("Language") declares, before its `en` floor, as the two values + * `SaveMetaItemRequestSchema.userTextLocales` carries. Unset rungs are left + * out, so an anonymous or unlocalized caller yields `[]`: the producer's `en`. + */ +export function userTextLocalesOf( + ctx: { readonly locale?: string; readonly workspaceLocale?: string } | null | undefined, +): string[] { + const locales: string[] = []; + for (const value of [ctx?.locale, ctx?.workspaceLocale]) { + if (typeof value === 'string' && value.length > 0) locales.push(value); + } + return locales; +} diff --git a/packages/core/src/security/index.ts b/packages/core/src/security/index.ts index b22f1eeb4af..279595f84c9 100644 --- a/packages/core/src/security/index.ts +++ b/packages/core/src/security/index.ts @@ -424,6 +424,7 @@ export { assembleExecutionContext, assembleExecutionContextOrGuest, ENTRY_EXECUTION_CONTEXT_FIELDS, + userTextLocalesOf, type EntryExecutionContextField, type ExecutionContextEntryFields, type ExecutionContextAssemblyInput, diff --git a/packages/metadata-protocol/src/protocol-authoring-gate.ts b/packages/metadata-protocol/src/protocol-authoring-gate.ts index 732e97188dd..4f440d5617d 100644 --- a/packages/metadata-protocol/src/protocol-authoring-gate.ts +++ b/packages/metadata-protocol/src/protocol-authoring-gate.ts @@ -323,6 +323,12 @@ export async function judgeRuntimeAuthoringRules( * round trip for a secret it still holds. */ restoredCredentialPaths?: () => Promise; + /** + * [#32656] The locales the findings' user-facing sentences are composed in + * (the write request's `userTextLocales`: the request's locale, then the + * workspace default). Absent ⇒ `en`. Selects a language, never a verdict. + */ + userTextLocales?: readonly (string | undefined)[]; }): Promise { const clean: RuntimeAuthoringVerdict = { error: null, advisories: [] }; // [#6710] The ADR-0005 carve-out, now DECLARED instead of inferred. @@ -379,6 +385,7 @@ export async function judgeRuntimeAuthoringRules( state: evt.state, body: evt.body, ...(hierarchyResolverMounted !== undefined ? { hierarchyResolverMounted } : {}), + ...(evt.userTextLocales !== undefined ? { userTextLocales: evt.userTextLocales } : {}), }).advisories, }; } @@ -572,6 +579,7 @@ export async function judgeRuntimeAuthoringRules( ...(tenancyPostureInForce !== undefined ? { tenancyPostureInForce } : {}), ...(engineJudge !== undefined ? { judgeFilter: engineJudge } : {}), ...(restoredCredentialPaths !== undefined ? { restoredCredentialPaths } : {}), + ...(evt.userTextLocales !== undefined ? { userTextLocales: evt.userTextLocales } : {}), // [#20312] The deployment's component manifest, read per publish; // with it the gate compiles an html page's source (ADR-0080 §5). ...(sduiManifest !== undefined ? { sduiManifest } : {}), diff --git a/packages/metadata-protocol/src/protocol-door-requests.ts b/packages/metadata-protocol/src/protocol-door-requests.ts index 68f65dadc65..dbbe11348b5 100644 --- a/packages/metadata-protocol/src/protocol-door-requests.ts +++ b/packages/metadata-protocol/src/protocol-door-requests.ts @@ -28,6 +28,12 @@ type SaveMetaItemRequest = { * already holds. Set by server code only; no HTTP door forwards it. */ inheritedGrantObjects?: readonly string[], + /** + * [#32656] The locales the findings' user sentences are composed in, in + * ladder order: the request's locale, then the workspace default + * (`SaveMetaItemRequestSchema.userTextLocales`). Stated by the door. + */ + userTextLocales?: readonly (string | undefined)[], }; /** The request of {@link ObjectStackProtocolImplementation.publishMetaItem}. */ @@ -86,6 +92,8 @@ type PublishMetaItemRequest = { _skipSeedApply?: boolean; /** [#22877] The bundle member whose draft to publish — {@link resolveBundleMemberSelector}; omitted, the canonical one. */ member?: string; + /** [#32656] The locales the findings' user sentences are composed in (`PublishMetaItemRequestSchema.userTextLocales`). */ + userTextLocales?: readonly (string | undefined)[]; }; /** The request of {@link ObjectStackProtocolImplementation.rollbackMetaItem}. */ diff --git a/packages/metadata-protocol/src/protocol-history-and-publish.ts b/packages/metadata-protocol/src/protocol-history-and-publish.ts index 884d24a1313..8211d011666 100644 --- a/packages/metadata-protocol/src/protocol-history-and-publish.ts +++ b/packages/metadata-protocol/src/protocol-history-and-publish.ts @@ -716,6 +716,8 @@ export class ProtocolHistoryAndPublishFacet { * all address it, so the body judged is the body that goes live. */ member?: string; + /** [#32656] The write request's `userTextLocales`, for the findings' `userMessage`. */ + userTextLocales?: readonly (string | undefined)[]; /** * [ADR-0144 D2 and D6, amended] The registry question this * promotion asks before the row goes live, stated by every producer @@ -1218,6 +1220,9 @@ export class ProtocolHistoryAndPublishFacet { // different narrowings, both needed for a package to be // judged as a self-consistent unit. ...(request.pending !== undefined ? { pending: request.pending } : {}), + // [#32656] The locales the publish door stated for the + // findings' user sentences (`advisories[].userMessage`). + ...(request.userTextLocales !== undefined ? { userTextLocales: request.userTextLocales } : {}), // [#20790] The publish gate's restored-credential read. The // stored draft holds no credential the write-only channel // holds — the draft's own save moved it there — so the gate is @@ -1500,6 +1505,8 @@ export class ProtocolHistoryAndPublishFacet { * the package. */ message?: string; + /** [#32656] The locales the door states for the findings' user sentences (stated by the door, never read from the body; see `SaveMetaItemRequestSchema.userTextLocales`). */ + userTextLocales?: readonly (string | undefined)[]; /** ADR-0067 — AI model that authored the turn (absent for human/CLI). */ aiModel?: string; /** @@ -2102,6 +2109,9 @@ export class ProtocolHistoryAndPublishFacet { // universe as it stood before the publish started. ...(pendingDeclarations !== undefined ? { pending: pendingDeclarations } : {}), + // [#32656] The door's locales for the findings' user sentences. + ...(request.userTextLocales !== undefined + ? { userTextLocales: request.userTextLocales } : {}), // [#26724] …and the datasources it drafts, which // an object draft beside them may name. batchDatasources, diff --git a/packages/metadata-protocol/src/protocol-publish-drafts-advisories.test.ts b/packages/metadata-protocol/src/protocol-publish-drafts-advisories.test.ts index adfd5284f7a..4dd416df86d 100644 --- a/packages/metadata-protocol/src/protocol-publish-drafts-advisories.test.ts +++ b/packages/metadata-protocol/src/protocol-publish-drafts-advisories.test.ts @@ -344,6 +344,40 @@ describe('publishPackageDrafts carries per-draft advisories on published[] eleme }); }); +describe('[#32656] publishPackageDrafts states the caller\'s user-text locales to the authoring gate', () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + // Ruling C on #32440: a finding's user sentence is composed in the request + // locale, else the workspace default, else `en`. The batch door's `/meta` + // twin (the runtime `packages` domain) states the two locales; the batch + // promotes each draft through the same gate the single-item doors judge + // with, so the locales must reach it for every element — and an + // unstated request must reach it unstated (the gate then composes `en`). + it('every promoted draft is judged with the stated locales; an unstated request states none', async () => { + const { engine } = makeStubEngine(); + const protocol = new ObjectStackProtocolImplementation(engine); + await stageFlowDraft(protocol, 'nightly_purge', advisoryFlow('nightly_purge')); + await stageFlowDraft(protocol, 'purge_clean', cleanFlow('purge_clean')); + const gate = vi.spyOn(protocol as any, 'assertRuntimeAuthoringRules'); + + const res = await protocol.publishPackageDrafts({ packageId: PKG, userTextLocales: ['zh-CN', 'en'] }); + expect(res).toMatchObject({ success: true, publishedCount: 2 }); + const stated = gate.mock.calls.map(([evt]: any[]) => [evt.name, evt.userTextLocales]); + expect(stated).toEqual(expect.arrayContaining([ + ['nightly_purge', ['zh-CN', 'en']], + ['purge_clean', ['zh-CN', 'en']], + ])); + + gate.mockClear(); + await stageFlowDraft(protocol, 'nightly_purge', advisoryFlow('nightly_purge')); + await protocol.publishPackageDrafts({ packageId: PKG }); + expect(gate.mock.calls.length).toBeGreaterThan(0); + for (const [evt] of gate.mock.calls as any[]) expect(evt.userTextLocales).toBeUndefined(); + }); +}); + // --------------------------------------------------------------------------- // [#30693] A refused object-storage sync rides the object's element too. // --------------------------------------------------------------------------- diff --git a/packages/metadata-protocol/src/protocol-save.ts b/packages/metadata-protocol/src/protocol-save.ts index b546db31363..02bff5a7fb8 100644 --- a/packages/metadata-protocol/src/protocol-save.ts +++ b/packages/metadata-protocol/src/protocol-save.ts @@ -1727,6 +1727,9 @@ export class ProtocolSaveFacet { // has carried it all along, it just never reached the gate. Null // (a bare tenant overlay) narrows nothing. packageId: request.packageId ?? null, + // [#32656] The locales the door stated for the findings' user + // sentences (`advisories[].userMessage`, the 422's `issues[]`). + ...(request.userTextLocales !== undefined ? { userTextLocales: request.userTextLocales } : {}), // [#20611] The redaction context. The read path withholds a // credential from every served definition (a flow's start-node // `config.secret`), so a body saved back after a read arrives diff --git a/packages/metadata-protocol/src/protocol.ts b/packages/metadata-protocol/src/protocol.ts index 35d7a6b39d7..e46a2e7eda5 100644 --- a/packages/metadata-protocol/src/protocol.ts +++ b/packages/metadata-protocol/src/protocol.ts @@ -1846,6 +1846,8 @@ export class ObjectStackProtocolImplementation implements * round trip for a secret it still holds. */ restoredCredentialPaths?: () => Promise; + /** [#32656] The write request's `userTextLocales`, for the findings' `userMessage`. */ + userTextLocales?: readonly (string | undefined)[]; }): Promise { // [#25467 cut 8] The body moved to `protocol-authoring-gate.ts` (see `AuthoringGateHost`). const readAuthoringChannel = () => this.authoringChannel; @@ -9725,6 +9727,8 @@ export class ObjectStackProtocolImplementation implements * all address it, so the body judged is the body that goes live. */ member?: string; + /** [#32656] The write request's `userTextLocales`, for the findings' `userMessage`. */ + userTextLocales?: readonly (string | undefined)[]; /** The registry question this promotion asks (`registry-question.ts`). */ registryQuestion: RegistryQuestion; /** [#32396] Judge every refusal, write nothing: the answer then carries no `result`. */ @@ -10044,6 +10048,8 @@ export class ObjectStackProtocolImplementation implements message?: string; /** ADR-0067 — AI model that authored the turn (absent for human/CLI). */ aiModel?: string; + /** [#32656] The locales the door states for the findings' user sentences (stated by the door, never read from the body; see `SaveMetaItemRequestSchema.userTextLocales`). */ + userTextLocales?: readonly (string | undefined)[]; /** * [#24253] Opt-in: fields THIS publish adds whose literal * `defaultValue` is written into the object's existing rows once the diff --git a/packages/metadata-protocol/src/runtime-authoring-gate.ts b/packages/metadata-protocol/src/runtime-authoring-gate.ts index 38fa433d9ef..1e431d562af 100644 --- a/packages/metadata-protocol/src/runtime-authoring-gate.ts +++ b/packages/metadata-protocol/src/runtime-authoring-gate.ts @@ -47,6 +47,7 @@ */ import { + findingUserMessage, runRuntimeAuthoringRules, type AuthoringFinding, type RuntimePackageScope, @@ -1179,14 +1180,27 @@ export function stampHtmlPageRequires(type: string, body: unknown, sduiManifest: return { ...(body as AnyRec), requires: [...compiled.result.requires] }; } -const toIssue = (f: AuthoringFinding): RuntimeAuthoringIssue => ({ - rule: f.rule, - path: f.path, - where: f.where, - message: f.message, - hint: f.hint, - severity: f.severity, -}); +/** + * One finding as the wire element. [#32656] `userMessage` is the finding's + * user-facing sentence, composed here because this is where the finding and + * the request's locales meet: a rule never sees the request, so it emits the + * names its sentence interpolates (`userTextParams`), and the door that holds + * the request states the locales (`SaveMetaItemRequestSchema.userTextLocales`). + * Present only when the rule authors a sentence for this finding; the six + * other keys are copied as before. + */ +const issueOf = (locales: readonly (string | undefined)[]) => (f: AuthoringFinding): RuntimeAuthoringIssue => { + const userMessage = findingUserMessage(f, locales); + return { + rule: f.rule, + path: f.path, + where: f.where, + message: f.message, + hint: f.hint, + severity: f.severity, + ...(userMessage !== undefined ? { userMessage } : {}), + }; +}; /** * The gate's whole verdict on one write — both severities, in one value. @@ -1402,7 +1416,15 @@ export function evaluateRuntimeAuthoringGate(args: { * predicate), nothing is judged. */ packagedRuleCopyRefusal?: PackagedRuleCopyRefusal | null; + /** + * [#32656] The locales the findings' user-facing sentences are composed + * in, in ladder order: the request's locale, then the workspace default + * (`SaveMetaItemRequestSchema.userTextLocales`). Absent ⇒ `en`. It picks a + * language and nothing else: no verdict depends on it. + */ + userTextLocales?: readonly (string | undefined)[]; }): RuntimeAuthoringVerdict { + const toIssue = issueOf(args.userTextLocales ?? []); // [#26188] The one finding a draft hears: a hierarchy scope this runtime // cannot enforce. Same rule as the publish refusal below, `warning` here. const hierarchyScopeGaps = findHierarchyScopeCapabilityGaps({ diff --git a/packages/rest/src/meta-item-history-routes.ts b/packages/rest/src/meta-item-history-routes.ts index 683523570a4..3b838cadb7e 100644 --- a/packages/rest/src/meta-item-history-routes.ts +++ b/packages/rest/src/meta-item-history-routes.ts @@ -151,7 +151,7 @@ * the module `rest-server.ts` imported it from. */ -import { rethrowAuthzStoreUnavailable } from '@objectstack/core'; +import { rethrowAuthzStoreUnavailable, userTextLocalesOf } from '@objectstack/core'; // [#12702 · #20156] The `/meta` item write doors' capability predicate — see // `rest-server.ts`' import of the same name for why it is shared — and the // metadata-plane FLS names the comparison door's and the published read's mask @@ -726,6 +726,9 @@ export function registerMetaItemHistoryRoutes(this: MetaItemHistoryRouteHost, sc ...(packageId ? { packageId } : {}), // [#22877] Publishes ONE member's draft of a bundled type. ...metaMemberSelector(req.query), + // [#32656] The languages the findings' `userMessage` is + // composed in, read off the resolved context. + userTextLocales: userTextLocalesOf(ctx), }; const result = await p.publishMetaItem(publishRequest); res.json(result); diff --git a/packages/rest/src/meta-item-write-routes.ts b/packages/rest/src/meta-item-write-routes.ts index 4c937600e1e..b22c9917970 100644 --- a/packages/rest/src/meta-item-write-routes.ts +++ b/packages/rest/src/meta-item-write-routes.ts @@ -85,7 +85,7 @@ * re-exports nothing from here, and the published surface does not move. */ -import { rethrowAuthzStoreUnavailable } from '@objectstack/core'; +import { rethrowAuthzStoreUnavailable, userTextLocalesOf } from '@objectstack/core'; // [#12702 · #20156] The `/meta` item write doors' capability predicate — see // `rest-server.ts`' import of the same name for why it is shared. import { metaWriteCapabilityVerdict } from '@objectstack/metadata-core'; @@ -360,6 +360,10 @@ export function registerMetaItemWriteRoutes(this: MetaItemWriteRouteHost, scope: ...(actor ? { actor } : {}), ...(force ? { force: true } : {}), ...(packageId ? { packageId } : {}), + // [#32656] The request's locale, then the workspace + // default: the languages the findings' `userMessage` is + // composed in. Read off the resolved context, never the body. + userTextLocales: userTextLocalesOf(ctx), }; const result = await p.saveMetaItem(saveRequest); res.json(result); diff --git a/packages/rest/src/rest-exec-ctx-principal-kind.test.ts b/packages/rest/src/rest-exec-ctx-principal-kind.test.ts index 03f9d677ea9..3bdcd49f887 100644 --- a/packages/rest/src/rest-exec-ctx-principal-kind.test.ts +++ b/packages/rest/src/rest-exec-ctx-principal-kind.test.ts @@ -297,6 +297,9 @@ describe('#6216 — the REST face assembles through the SHARED assembler, output 'positions', 'permissions', 'systemPermissions', 'isSystem', 'principalKind', 'userId', 'email', 'posture', 'org_user_ids', 'accessible_org_ids', 'timezone', 'locale', + // [#32656] The workspace default locale on its own, beside the + // folded `locale`: the user-text ladder's second rung. + 'workspaceLocale', // [ADR-0150 D3] The (package, name) each granted set resolved to, // beside `permissions`: the assembler fills it whenever a set is // granted (#31970's field, filled by #31971). diff --git a/packages/rest/src/rest-server-meta-door-closed-sets.test.ts b/packages/rest/src/rest-server-meta-door-closed-sets.test.ts index 2ac32e19d1a..9d29589c80d 100644 --- a/packages/rest/src/rest-server-meta-door-closed-sets.test.ts +++ b/packages/rest/src/rest-server-meta-door-closed-sets.test.ts @@ -39,6 +39,8 @@ import { META_ITEM_DIFF_PARAMS, META_ITEM_PUBLISHED_PARAMS, } from './rest-server.js'; +// Paid at collection, not inside a clocked case (check-test-source-alias). +import '@objectstack/objectql'; import { unknownQueryParamMessage } from './query-allowlist.js'; const META = '/api/v1/meta'; @@ -184,6 +186,8 @@ describe('[#23072] PRESERVATION — every name each door reads still reaches its expect(protocol.saveMetaItem.mock.calls[0][0]).toEqual({ type: 'email_template', name: 'acme.welcome', item: EN, writeFace: 'meta-envelope', mode: 'draft', actor: 'u1', force: true, packageId: 'com.acme.mail', + // [#32656] Server-stated off the caller's context, never read from the wire. + userTextLocales: [], }); }); diff --git a/packages/rest/src/rest-server-meta-member-selector.test.ts b/packages/rest/src/rest-server-meta-member-selector.test.ts index 616a390ecb4..42cedc31886 100644 --- a/packages/rest/src/rest-server-meta-member-selector.test.ts +++ b/packages/rest/src/rest-server-meta-member-selector.test.ts @@ -247,6 +247,8 @@ describe('[#22877] PRESERVATION — the request each protocol door receives', () expect(answer.status, JSON.stringify(answer.body)).toBe(200); expect(protocol.publishMetaItem.mock.calls[0][0]).toEqual({ type: 'email_template', name: 'acme.welcome', actor: 'u1', packageId: 'com.acme.mail', member: 'zh-CN', + // [#32656] Server-stated off the caller's context, never read from the wire. + userTextLocales: [], }); }); diff --git a/packages/runtime/src/domains/meta-save-user-text-locale.test.ts b/packages/runtime/src/domains/meta-save-user-text-locale.test.ts new file mode 100644 index 00000000000..f9c2c9b6d66 --- /dev/null +++ b/packages/runtime/src/domains/meta-save-user-text-locale.test.ts @@ -0,0 +1,200 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#32656] The save door's advisories come back in the request's language. + * + * Ruling C on #32440 (ruling record 6819749037): the producer of a finding + * composes its user-facing sentence in the request's locale, else the + * workspace default, else `en`, and every client renders it as received. The + * authoring rules emit the names their sentence interpolates; the metadata + * protocol composes the sentence; and only the DOOR holds the two locales. + * So each door states them (`SaveMetaItemRequestSchema.userTextLocales`), + * read off the execution context it resolved: `locale` (the request's own, + * else the workspace default) and `workspaceLocale` (the workspace default + * alone). + * + * Pinned on both `/meta` save doors, end to end over the real protocol and a + * real SQLite store: a permission set granting read on a `private` object + * earns the `security-private-no-readscope` advisory, whose `userMessage` must + * be in the caller's language, while `rule`, `message` and `hint` stay as + * they were. + */ + +import { describe, it, expect, afterEach } from 'vitest'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; +import { SysMetadata, SysMetadataHistoryObject, SysMetadataAuditObject } from '@objectstack/platform-objects/metadata'; +import { RestServer } from '@objectstack/rest'; +import { HttpDispatcher } from '../http-dispatcher.js'; +// Paid at collection, not inside a clocked case (check-test-source-alias). +import '@objectstack/metadata'; + +const PREFIX = '/api/v1'; +const META = `${PREFIX}/meta`; +const TEST_PACKAGE_ID = 'objectstack-test'; +const RULE = 'security-private-no-readscope'; + +interface Caller { + userId: string; + isSystem: boolean; + systemPermissions: string[]; + locale?: string; + workspaceLocale?: string; +} + +const caller = (locale?: string, workspaceLocale?: string): Caller => ({ + userId: 'u_admin', + isSystem: false, + systemPermissions: ['manage_metadata'], + ...(locale !== undefined ? { locale } : {}), + ...(workspaceLocale !== undefined ? { workspaceLocale } : {}), +}); + +const EXPENSE = { + name: 'expense', + label: 'Expense', + sharingModel: 'private', + fields: { + id: { name: 'id', type: 'text' as const, primaryKey: true, label: 'ID' }, + name: { name: 'name', type: 'text' as const, label: 'Name' }, + }, +}; + +const permissionSet = (name: string) => ({ name, label: 'Finance User', objects: { expense: { allowRead: true } } }); + +const clone = (v: T): T => JSON.parse(JSON.stringify(v)); + +const liveEngines: ObjectQL[] = []; +afterEach(async () => { + while (liveEngines.length) { + try { await liveEngines.pop()?.destroy(); } catch { /* noop */ } + } +}); + +async function bootStore() { + const engine = new ObjectQL(); + liveEngines.push(engine); + engine.registerDriver(new SqlDriver({ + client: 'better-sqlite3', + connection: { filename: ':memory:' }, + useNullAsDefault: true, + }), true); + await engine.init(); + engine.registry.registerObject(EXPENSE as any, TEST_PACKAGE_ID); + engine.registry.registerObject(SysMetadata as any, TEST_PACKAGE_ID); + engine.registry.registerObject(SysMetadataHistoryObject as any, TEST_PACKAGE_ID); + engine.registry.registerObject(SysMetadataAuditObject as any, TEST_PACKAGE_ID); + await engine.syncSchemas(); + const protocol = new ObjectStackProtocolImplementation(engine as any); + // What each save handed the protocol, read where the protocol receives it. + const stated: unknown[] = []; + const save = protocol.saveMetaItem.bind(protocol); + (protocol as any).saveMetaItem = (request: any) => { + stated.push(request.userTextLocales); + return save(request); + }; + return { protocol, stated }; +} + +interface Saved { status: number; body: any } +interface Door { + save(who: Caller, name: string): Promise; + stated: unknown[]; +} + +function makeRes() { + const res: any = { statusCode: 200, body: undefined, headers: {} as Record }; + res.status = (code: number) => { res.statusCode = code; return res; }; + res.json = (body: any) => { res.body = body; return res; }; + res.send = () => res; + res.end = () => res; + res.header = (k: string, v: string) => { res.headers[k] = v; return res; }; + res.setHeader = () => {}; + res.write = () => true; + return res; +} + +async function bootDispatcher(): Promise { + const { protocol, stated } = await bootStore(); + const get = (n: string) => (n === 'protocol' ? protocol : null); + const kernel: any = { context: { getService: get }, getService: get, getServiceAsync: async (n: string) => get(n) }; + const dispatcher = new HttpDispatcher(kernel); + return { + stated, + save: async (who, name) => { + (dispatcher as any).timedResolveExecutionContext = async () => clone(who); + const body = permissionSet(name); + const request = new Request(`http://localhost${META}/permission/${name}`, { + method: 'PUT', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify(body), + }); + const res = await dispatcher.dispatch('PUT', `/meta/permission/${name}`, body, {}, { request }, PREFIX); + const raw = res.response?.body as any; + return { status: res.response?.status ?? 0, body: raw?.data ?? raw }; + }, + }; +} + +async function bootRestServer(): Promise { + const { protocol, stated } = await bootStore(); + const noop = () => {}; + const server = { get: noop, post: noop, put: noop, delete: noop, patch: noop, use: noop, listen: async () => {}, close: async () => {} }; + const rest: any = new RestServer(server as any, protocol as any, { api: { requireAuth: false } } as any); + rest.registerRoutes(); + const route = rest.getRoutes().find((r: any) => r.method === 'PUT' && r.path === `${META}/:type/:name`); + if (!route) throw new Error(`PUT ${META}/:type/:name is not registered`); + return { + stated, + save: async (who, name) => { + rest.resolveExecCtx = async () => clone(who); + const res = makeRes(); + await route.handler({ + method: 'PUT', path: `${META}/permission/${name}`, params: { type: 'permission', name }, + headers: {}, query: {}, body: permissionSet(name), + }, res); + return { status: res.statusCode, body: res.body }; + }, + }; +} + +const advisoryOf = (saved: Saved) => { + expect(saved.status, JSON.stringify(saved.body)).toBe(200); + const advisory = (saved.body?.advisories ?? []).find((a: any) => a.rule === RULE); + expect(advisory, 'the private-object advisory rides the 2xx').toBeDefined(); + return advisory; +}; + +const DOORS: ReadonlyArray Promise]> = [ + ['the runtime dispatcher', bootDispatcher], + ['RestServer', bootRestServer], +]; + +for (const [doorName, boot] of DOORS) { + describe(`[#32656] ${doorName}: PUT /meta/permission/:name composes advisories in the caller's language`, () => { + it('states the request locale, then the workspace default, read off the execution context', async () => { + const door = await boot(); + await door.save(caller('zh-CN', 'de'), 'finance_user'); + await door.save(caller(), 'finance_user'); + expect(door.stated).toEqual([['zh-CN', 'de'], []]); + }, 60_000); + + it('a zh-CN request reads the advisory in Simplified Chinese; rule, message and hint are unchanged', async () => { + const door = await boot(); + const zh = advisoryOf(await door.save(caller('zh-CN', 'en'), 'finance_user')); + expect(zh.userMessage).toContain('权限集“finance_user”'); + const en = advisoryOf(await door.save(caller('en', 'en'), 'finance_user')); + expect(en.userMessage).toContain('permission set "finance_user"'); + expect({ rule: zh.rule, message: zh.message, hint: zh.hint }).toEqual({ rule: en.rule, message: en.message, hint: en.hint }); + }, 60_000); + + it('a request language the platform has no text in falls back to the workspace default, then to en', async () => { + const door = await boot(); + const workspace = advisoryOf(await door.save(caller('tlh', 'zh-CN'), 'finance_user')); + expect(workspace.userMessage).toContain('权限集“finance_user”'); + const floor = advisoryOf(await door.save(caller('tlh', 'tlh'), 'finance_user')); + expect(floor.userMessage).toContain('permission set "finance_user"'); + }, 60_000); + }); +} diff --git a/packages/runtime/src/domains/meta.ts b/packages/runtime/src/domains/meta.ts index 0b9a90160da..d7fd0cfbf51 100644 --- a/packages/runtime/src/domains/meta.ts +++ b/packages/runtime/src/domains/meta.ts @@ -10,6 +10,7 @@ import { shouldDenyAnonymous, ANONYMOUS_DENY_STATUS, ANONYMOUS_DENY_CODE, ANONYMOUS_DENY_MESSAGE, PackageScopedNameRefusedError, + userTextLocalesOf, type PackageScopedHolder, } from '@objectstack/core'; // [commit 67ceb9aef] `canonicalMetaUrlType` is the FOLD this transport was missing. @@ -1930,6 +1931,10 @@ export async function handleMetadataRequest(deps: DomainHandlerDeps, path: strin // `copilot`, which the mapping refuses on this door. ...saveOptions.request, ...(actor ? { actor } : {}), + // [#32656] The languages the findings' `userMessage` + // is composed in: the request's locale, then the + // workspace default, off the execution context. + userTextLocales: userTextLocalesOf(ec), }); return { handled: true, response: deps.success(result) }; } catch (e: any) { diff --git a/packages/runtime/src/domains/packages-publish-drafts-request-conformance.test.ts b/packages/runtime/src/domains/packages-publish-drafts-request-conformance.test.ts index 805e6600409..4d6555f48c9 100644 --- a/packages/runtime/src/domains/packages-publish-drafts-request-conformance.test.ts +++ b/packages/runtime/src/domains/packages-publish-drafts-request-conformance.test.ts @@ -37,6 +37,8 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; import { PublishPackageDraftsRequestSchema } from '@objectstack/spec/api'; import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; import { HttpDispatcher } from '../http-dispatcher.js'; +// Paid at collection, not inside a clocked case (check-test-source-alias). +import '@objectstack/metadata'; import { ROUTE_LEDGER } from '../route-ledger.js'; const PKG = 'com.workspace'; @@ -95,10 +97,13 @@ async function publishWith(body: unknown, apps?: Array>) /** The request members of what the protocol received: everything but the path id and the caller's context. */ function bodyMembersSent(sent: Record) { - const { packageId, context, actor, ...rest } = sent; + const { packageId, context, actor, userTextLocales, ...rest } = sent; expect(packageId).toBe(PKG); expect(actor).toBe(USER); expect(context).toMatchObject({ userId: USER }); + // [#32656] Stated by the door off the caller's execution context (which + // names no locale here), never read from the body. + expect(userTextLocales).toEqual([]); return rest; } @@ -146,7 +151,7 @@ describe('publish-drafts request body conforms to PublishPackageDraftsRequestSch }); it('members the protocol method takes but the schema does not declare are not read from the body', async () => { - const { sent } = await publishWith({ aiModel: 'some-model', context: { userId: 'u_other' }, packageId: 'com.other' }); + const { sent } = await publishWith({ aiModel: 'some-model', context: { userId: 'u_other' }, packageId: 'com.other', userTextLocales: ['ja'] }); expect(sent.aiModel).toBeUndefined(); expect(bodyMembersSent(sent)).toEqual({}); }); diff --git a/packages/runtime/src/domains/packages-seed-apply-org-scope.test.ts b/packages/runtime/src/domains/packages-seed-apply-org-scope.test.ts index d21ddc0cd69..d48000dade4 100644 --- a/packages/runtime/src/domains/packages-seed-apply-org-scope.test.ts +++ b/packages/runtime/src/domains/packages-seed-apply-org-scope.test.ts @@ -84,6 +84,8 @@ import { import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; import { DEFAULT_METADATA_TYPE_REGISTRY } from '@objectstack/spec/kernel'; import { HttpDispatcher } from '../http-dispatcher.js'; +// Paid at collection, not inside a clocked case (check-test-source-alias). +import '@objectstack/metadata'; /** * [#26708] The packages this file's saves name, installed: a save naming a @@ -405,8 +407,9 @@ describe('#15068 · 0 · the publish-then-read path really runs', () => { // probes read a widget's dataset AS that caller (the renderer's path), // and nothing in the publish derives a write scope from it. // [ADR-0146 D1] Its user id is the recorded actor; no organization is. + // [#32656] The caller's language ladder rides too (none named here). const caller = PKG_ADMIN(ORG).executionContext; - expect(publishRequest()).toEqual({ packageId: PKG, actor: caller.userId, context: caller }); + expect(publishRequest()).toEqual({ packageId: PKG, actor: caller.userId, context: caller, userTextLocales: [] }); expect(publishRequest()).not.toHaveProperty('organizationId'); }); }); diff --git a/packages/runtime/src/domains/packages.ts b/packages/runtime/src/domains/packages.ts index 29dc2a6d33e..3efcbdd3b24 100644 --- a/packages/runtime/src/domains/packages.ts +++ b/packages/runtime/src/domains/packages.ts @@ -76,7 +76,7 @@ import { isWritablePackage, READ_ONLY_PACKAGE_SCOPES, refuseNamespaceObjectNameC import { customizationPairManifestRefusal, runtimeNavigationContributionsRefusal } from '@objectstack/metadata-protocol'; // [#28117] The one reader of a manifest's declared dependency ids (ADR-0141), // shared with the registry's co-owner gate. -import { declaredDependencyIds } from '@objectstack/core'; +import { declaredDependencyIds, userTextLocalesOf } from '@objectstack/core'; // [#28914, ADR-0141 D5] The one sorter of installed packages by their declared // dependencies: the order a boot hydrates them in is the order the // whole-deployment export lists them in. @@ -2997,6 +2997,10 @@ export async function handlePackagesRequest(deps: DomainHandlerDeps, path: strin // its shape and what it names, and refuses the whole // request before anything is published. ...(body?.backfill !== undefined ? { backfill: body.backfill } : {}), + // [#32656] The languages the findings' `userMessage` is + // composed in: the request's locale, then the workspace + // default, off THIS caller's execution context. + userTextLocales: userTextLocalesOf(_context?.executionContext), // THIS caller's execution context, never a system one: // the backfill writes run as it, and [#25484] so do the // build probes' dashboard-widget reads — the renderer's diff --git a/packages/runtime/src/http-dispatcher.test.ts b/packages/runtime/src/http-dispatcher.test.ts index e7c5d84b1b6..12ea4605ff3 100644 --- a/packages/runtime/src/http-dispatcher.test.ts +++ b/packages/runtime/src/http-dispatcher.test.ts @@ -186,6 +186,10 @@ describe('HttpDispatcher', () => { // twin records it; rows are pinned in // `domains/meta-save-actor.test.ts`. actor: 'u1', + // [#32656] The caller's language ladder, off the admitted + // context (which names no locale here); pinned end to end in + // `domains/meta-save-user-text-locale.test.ts`. + userTextLocales: [], }); expect(result.response?.body).toEqual({ success: true, diff --git a/packages/spec/authorable-surface/api.json b/packages/spec/authorable-surface/api.json index 2cd44225745..5f43ca93e09 100644 --- a/packages/spec/authorable-surface/api.json +++ b/packages/spec/authorable-surface/api.json @@ -1442,6 +1442,7 @@ "api/PublishMetaItemRequest:name", "api/PublishMetaItemRequest:packageId", "api/PublishMetaItemRequest:type", + "api/PublishMetaItemRequest:userTextLocales", "api/PublishMetaItemResponse:advisories", "api/PublishMetaItemResponse:materializeApplied", "api/PublishMetaItemResponse:message", @@ -1770,6 +1771,7 @@ "api/SaveMetaItemRequest:parentVersion", "api/SaveMetaItemRequest:surface", "api/SaveMetaItemRequest:type", + "api/SaveMetaItemRequest:userTextLocales", "api/SaveMetaItemRequest:writeFace", "api/SaveMetaItemResponse:advisories", "api/SaveMetaItemResponse:message", diff --git a/packages/spec/authorable-surface/kernel.json b/packages/spec/authorable-surface/kernel.json index 578a9f42b70..6e7a3a8f0f6 100644 --- a/packages/spec/authorable-surface/kernel.json +++ b/packages/spec/authorable-surface/kernel.json @@ -203,6 +203,7 @@ "kernel/ExecutionContext:traceId", "kernel/ExecutionContext:transaction", "kernel/ExecutionContext:userId", + "kernel/ExecutionContext:workspaceLocale", "kernel/ExtensionPoint:cardinality", "kernel/ExtensionPoint:contract", "kernel/ExtensionPoint:description", diff --git a/packages/spec/src/api/protocol.zod.ts b/packages/spec/src/api/protocol.zod.ts index a69512cff09..1a1fcbf5c23 100644 --- a/packages/spec/src/api/protocol.zod.ts +++ b/packages/spec/src/api/protocol.zod.ts @@ -1067,6 +1067,27 @@ export const RuntimeAuthoringIssueSchema = lazySchema(() => z.object({ ), })); +/** + * The two locales a write door states for the user-facing sentences its + * findings carry (`RuntimeAuthoringIssueSchema.userMessage`), in ladder order: + * the locale the request names, then the workspace default. A write door holds + * both (`ExecutionContext.locale` and `ExecutionContext.workspaceLocale`); the + * metadata protocol that composes the sentences never sees the request. Two + * values, not their fold: once a request names a locale the fold has lost the + * workspace default, and the ladder needs it as its second rung (see + * `ApiErrorSchema.userMessage`, "Language"). + */ +const userTextLocalesMember = () => z.array(z.string()).max(2).optional().describe( + 'The locales the user-facing sentences of this write\'s findings (`advisories[].userMessage`, and ' + + '`issues[].userMessage` on its 422) are composed in, in ladder order: the locale the request names, ' + + 'then the workspace default. Each is read against the platform locale table, whole and then one ' + + 'subtag shorter at a time; a value that names no table language is passed over, and `en` is the ' + + 'last rung. Stated by the door that holds the request (the REST door and the dispatcher state ' + + '`[ExecutionContext.locale, ExecutionContext.workspaceLocale]`), never read from a wire body. ' + + 'ABSENT ⇒ the sentences are composed in `en`. It selects a language only: what is judged, refused ' + + 'or saved does not depend on it.', +); + /** * Save Metadata Item Request * Create or update a metadata item — the request shape for @@ -1233,6 +1254,7 @@ export const SaveMetaItemRequestSchema = lazySchema(() => z.object({ + 'dispatcher build this request member by member, so a `client` in a wire body or query is never ' + 'read.', ), + userTextLocales: userTextLocalesMember(), })); /** @@ -1433,6 +1455,7 @@ export const PublishMetaItemRequestSchema = lazySchema(() => z.object({ + '`no_draft`.', ), member: z.string().optional().describe(BUNDLE_MEMBER_SELECTOR_DESCRIPTION), + userTextLocales: userTextLocalesMember(), })); /** diff --git a/packages/spec/src/kernel/execution-context.zod.ts b/packages/spec/src/kernel/execution-context.zod.ts index ff7e5cdde04..4e44e14c916 100644 --- a/packages/spec/src/kernel/execution-context.zod.ts +++ b/packages/spec/src/kernel/execution-context.zod.ts @@ -177,6 +177,18 @@ export const ExecutionContextSchema = lazySchema(() => z.object({ */ locale: z.string().optional(), + /** + * The workspace default locale alone (BCP-47), resolved from the + * `localization` settings: the value `locale` falls back to when the request + * names none. `locale` is the fold of the two, so once a request names a + * locale the workspace default is gone from it; a producer of user-facing + * text needs it as the second rung of its ladder (the request's locale, else + * the workspace default, else `en`: `ApiErrorSchema.userMessage`, + * "Language"), and reads it here. Unset for an anonymous caller, and when no + * workspace default is configured. + */ + workspaceLocale: z.string().optional(), + /** * Active default currency (ISO 4217, e.g. `USD`, `CNY`), resolved from the * `localization` settings alongside `timezone`/`locale`. The tenant-level