From d8d794573a168ce24ec9b20865d47d1d6665bb80 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 14:43:40 +0000 Subject: [PATCH 1/8] wip(#32656): compose advisories' userMessage in the request's locale Claude-Session: https://claude.ai/code/session_016WV4cz2MxDkQYCC4U8indM Co-authored-by: Claude --- .../security/assemble-execution-context.ts | 23 +++++++++++ packages/core/src/security/index.ts | 1 + .../src/protocol-authoring-gate.ts | 8 ++++ .../src/protocol-history-and-publish.ts | 10 +++++ .../metadata-protocol/src/protocol-save.ts | 3 ++ packages/metadata-protocol/src/protocol.ts | 6 +++ .../src/runtime-authoring-gate.ts | 38 +++++++++++++++---- packages/rest/src/meta-item-history-routes.ts | 5 ++- packages/rest/src/meta-item-write-routes.ts | 6 ++- packages/runtime/src/domains/meta.ts | 5 +++ packages/runtime/src/domains/packages.ts | 6 ++- packages/spec/src/api/protocol.zod.ts | 24 ++++++++++++ .../spec/src/kernel/execution-context.zod.ts | 12 ++++++ 13 files changed, 136 insertions(+), 11 deletions(-) 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 aabfb76cca0..6f1114e18b7 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-history-and-publish.ts b/packages/metadata-protocol/src/protocol-history-and-publish.ts index 86da5bb5234..287c5b0e28d 100644 --- a/packages/metadata-protocol/src/protocol-history-and-publish.ts +++ b/packages/metadata-protocol/src/protocol-history-and-publish.ts @@ -692,6 +692,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 @@ -1194,6 +1196,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 @@ -1468,6 +1473,8 @@ export class ProtocolHistoryAndPublishFacet { * the package. */ message?: string; + /** [#32656] The locales the door states for the findings' user sentences (`PublishPackageDraftsRequestSchema.userTextLocales`). */ + userTextLocales?: readonly (string | undefined)[]; /** ADR-0067 — AI model that authored the turn (absent for human/CLI). */ aiModel?: string; /** @@ -2070,6 +2077,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-save.ts b/packages/metadata-protocol/src/protocol-save.ts index ca4b5d8c416..bf0f71a6458 100644 --- a/packages/metadata-protocol/src/protocol-save.ts +++ b/packages/metadata-protocol/src/protocol-save.ts @@ -1726,6 +1726,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 1ca6e7781a5..4008de6252a 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; @@ -9715,6 +9717,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`. */ @@ -10033,6 +10037,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 (`PublishPackageDraftsRequestSchema.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 b1244acd8c2..ccbd9cc43ee 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, @@ -1104,14 +1105,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. @@ -1325,7 +1339,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 29f553008ef..ceade07f5ec 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 @@ -710,6 +710,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/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.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/spec/src/api/protocol.zod.ts b/packages/spec/src/api/protocol.zod.ts index 57856cf5427..faf7b0afd11 100644 --- a/packages/spec/src/api/protocol.zod.ts +++ b/packages/spec/src/api/protocol.zod.ts @@ -1066,6 +1066,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 @@ -1232,6 +1253,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(), })); /** @@ -1432,6 +1454,7 @@ export const PublishMetaItemRequestSchema = lazySchema(() => z.object({ + '`no_draft`.', ), member: z.string().optional().describe(BUNDLE_MEMBER_SELECTOR_DESCRIPTION), + userTextLocales: userTextLocalesMember(), })); /** @@ -1735,6 +1758,7 @@ export const PublishPackageDraftsRequestSchema = lazySchema(() => z.object({ + 'is not new in this publish or declares no literal default; ' + '`backfillApplied` in the response reports the rows written per field.', ), + 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 From f562cc5c9f948bb5d702bdba88c63daac326c3ef Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 15:05:24 +0000 Subject: [PATCH 2/8] feat(metadata-protocol): compose write findings' userMessage in the caller's language (#32656) Doors state userTextLocales (request locale, then workspace default) read off the execution context, which now carries workspaceLocale unfolded. Claude-Session: https://claude.ai/code/session_016WV4cz2MxDkQYCC4U8indM Co-Authored-By: Claude --- .changeset/32656-user-text-request-locale.md | 20 ++ content/docs/references/api/protocol.mdx | 3 + content/docs/references/data/data-engine.mdx | 12 ++ .../references/kernel/execution-context.mdx | 1 + .../assemble-execution-context.test.ts | 50 ++++- .../src/protocol-door-requests.ts | 8 + ...protocol-publish-drafts-advisories.test.ts | 34 +++ .../meta-save-user-text-locale.test.ts | 198 ++++++++++++++++++ packages/spec/authorable-surface/api.json | 3 + packages/spec/authorable-surface/kernel.json | 1 + 10 files changed, 328 insertions(+), 2 deletions(-) create mode 100644 .changeset/32656-user-text-request-locale.md create mode 100644 packages/runtime/src/domains/meta-save-user-text-locale.test.ts diff --git a/.changeset/32656-user-text-request-locale.md b/.changeset/32656-user-text-request-locale.md new file mode 100644 index 00000000000..617bca97f90 --- /dev/null +++ b/.changeset/32656-user-text-request-locale.md @@ -0,0 +1,20 @@ +--- +'@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`, `PublishMetaItemRequestSchema` and `PublishPackageDraftsRequestSchema` gain an optional `userTextLocales` member (at most two locale codes), and `ExecutionContextSchema` gains an optional `workspaceLocale`. 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 + +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 4f54de75b87..ecf09f74a1d 100644 --- a/content/docs/references/api/protocol.mdx +++ b/content/docs/references/api/protocol.mdx @@ -2524,6 +2524,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. | --- @@ -2593,6 +2594,7 @@ The authoring surface of a metadata write. Closed: `copilot` is an AI assistant' | :--- | :--- | :--- | :--- | | **message** | `string` | optional | The author's change note (ADR-0146 D1). The package commit records it, and so does every item history row this publish writes, as `change_note` (read back as each history event's `message`). Absent or empty, those rows record the sentence naming the package instead. | | **backfill** | `{ object: string; field: string }[]` | optional | Opt-in: fields this publish adds whose literal `defaultValue` is written into the object's existing rows once the drafts are live, as the signed-in caller. Absent or `[]`, no row is touched. Each entry names an object and a field and nothing else, and names it once. The whole request is refused `400 VALIDATION_ERROR` before anything is published when an entry is malformed, repeated, or names a field that is not new in this publish or declares no literal default; `backfillApplied` in the response reports the rows written per field. | +| **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: `PublishPackageDraftsRequest.backfill[number]` @@ -2878,6 +2880,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/metadata-protocol/src/protocol-door-requests.ts b/packages/metadata-protocol/src/protocol-door-requests.ts index 984378c69f7..f8f600358ee 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-publish-drafts-advisories.test.ts b/packages/metadata-protocol/src/protocol-publish-drafts-advisories.test.ts index 16e555ed346..652ec14c059 100644 --- a/packages/metadata-protocol/src/protocol-publish-drafts-advisories.test.ts +++ b/packages/metadata-protocol/src/protocol-publish-drafts-advisories.test.ts @@ -342,6 +342,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/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..72ea8ee9a25 --- /dev/null +++ b/packages/runtime/src/domains/meta-save-user-text-locale.test.ts @@ -0,0 +1,198 @@ +// 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'; + +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/spec/authorable-surface/api.json b/packages/spec/authorable-surface/api.json index 12942fd998e..94bb6c26d72 100644 --- a/packages/spec/authorable-surface/api.json +++ b/packages/spec/authorable-surface/api.json @@ -1438,6 +1438,7 @@ "api/PublishMetaItemRequest:name", "api/PublishMetaItemRequest:packageId", "api/PublishMetaItemRequest:type", + "api/PublishMetaItemRequest:userTextLocales", "api/PublishMetaItemResponse:advisories", "api/PublishMetaItemResponse:materializeApplied", "api/PublishMetaItemResponse:message", @@ -1448,6 +1449,7 @@ "api/PublishMetaItemResponse:version", "api/PublishPackageDraftsRequest:backfill", "api/PublishPackageDraftsRequest:message", + "api/PublishPackageDraftsRequest:userTextLocales", "api/PublishPackageDraftsResponse:backfillApplied", "api/PublishPackageDraftsResponse:commitId", "api/PublishPackageDraftsResponse:failed", @@ -1760,6 +1762,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", From 0b4a03f69d3e60971f9b24795fd4cddee2c34e31 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 15:43:01 +0000 Subject: [PATCH 3/8] fix(plugin-security): permission refusals speak the caller's language, falling back to the workspace default (#32656) Claude-Session: https://claude.ai/code/session_016WV4cz2MxDkQYCC4U8indM Co-Authored-By: Claude --- .changeset/32656-refusal-user-text-locale.md | 14 +++ .../src/mutation-listeners.test.ts | 10 ++ .../src/protocol-authoring-channel.ts | 7 ++ .../src/protocol-authoring-gate.ts | 4 + .../metadata-protocol/src/protocol-save.ts | 1 + packages/metadata-protocol/src/protocol.ts | 1 + .../src/packaged-permission-set-lock-gate.ts | 4 +- .../src/packaged-permission-set-lock.test.ts | 40 ++++++ .../src/packaged-permission-set-lock.ts | 118 +++++++++++++++--- .../src/permission-denied-user-copy.test.ts | 14 +++ .../src/security-plugin-authz-middleware.ts | 81 +++++++++--- .../meta-save-user-text-locale.test.ts | 21 +++- 12 files changed, 279 insertions(+), 36 deletions(-) create mode 100644 .changeset/32656-refusal-user-text-locale.md diff --git a/.changeset/32656-refusal-user-text-locale.md b/.changeset/32656-refusal-user-text-locale.md new file mode 100644 index 00000000000..edb359d2a5e --- /dev/null +++ b/.changeset/32656-refusal-user-text-locale.md @@ -0,0 +1,14 @@ +--- +'@objectstack/plugin-security': patch +'@objectstack/metadata-protocol': patch +--- + +fix(plugin-security): permission refusals speak the caller's language, falling back to the workspace default + +Clause-②: no +Metadata-protocol: none + +Ruling C on #32440, second half of #32656: a refusal's user-facing sentence is composed in the request's language, else the workspace's default language, else English. Codes, statuses and the diagnostic `message` are unchanged. + +- **Packaged permission-set lock.** Saving a permission set an installed package provides, and the fail-closed refusal when the system cannot tell, used to answer their `userMessage` in English only. They now answer in the caller's language (English, Simplified and Traditional Chinese, Japanese, Korean, Spanish, French, German, Brazilian Portuguese, Russian and Arabic). The metadata write door hands each type's authoring gate the caller's two languages (`MetadataAuthoringGateContext.userTextLocales`); a caller that states none gets English, as before. +- **Permission denials.** The record, field, owner and queue denials of the security middleware were rendered in the request's language only, so a request in a language the platform has no text in fell to English even when the workspace default had text. They now fall back to the workspace default first. A deployment's `errors.` translation override counts as text for its language. diff --git a/packages/metadata-protocol/src/mutation-listeners.test.ts b/packages/metadata-protocol/src/mutation-listeners.test.ts index 3e6d3c1dac7..571ef58ec76 100644 --- a/packages/metadata-protocol/src/mutation-listeners.test.ts +++ b/packages/metadata-protocol/src/mutation-listeners.test.ts @@ -149,6 +149,16 @@ describe('ObjectStackProtocolImplementation.registerAuthoringGate (#3050)', () = }); }); + it('[#32656] hands the gate the caller\'s user-text locales, empty entries dropped; none stated, no key', async () => { + const p = makeProtocol(); + const seen: any[] = []; + p.registerAuthoringGate('object', (ctx) => { seen.push(ctx); }); + await (p as any).runAuthoringGate(save({ userTextLocales: ['zh-CN', undefined, '', 'de'] })); + await (p as any).runAuthoringGate(save()); + expect(seen[0].userTextLocales).toEqual(['zh-CN', 'de']); + expect('userTextLocales' in seen[1]).toBe(false); + }); + it('normalizes plural registrations to the singular type', async () => { const p = makeProtocol(); const gate = vi.fn(); diff --git a/packages/metadata-protocol/src/protocol-authoring-channel.ts b/packages/metadata-protocol/src/protocol-authoring-channel.ts index b1c4a0b1363..aa49bcfe063 100644 --- a/packages/metadata-protocol/src/protocol-authoring-channel.ts +++ b/packages/metadata-protocol/src/protocol-authoring-channel.ts @@ -36,6 +36,13 @@ export interface MetadataAuthoringGateContext { isArtifactBacked: boolean; /** The packaged (code-layer) baseline body when {@link isArtifactBacked}; the declaration an overlay customizes. */ declaredBody?: unknown; + /** + * [#32656] The locales a gate's refusal `userMessage` is composed in, in + * ladder order (the request's, then the workspace default), as the write + * door stated them (`SaveMetaItemRequestSchema.userTextLocales`). Absent + * when the door stated none: the gate composes `en`. + */ + userTextLocales?: readonly string[]; } export type MetadataAuthoringGate = (ctx: MetadataAuthoringGateContext) => void | Promise; diff --git a/packages/metadata-protocol/src/protocol-authoring-gate.ts b/packages/metadata-protocol/src/protocol-authoring-gate.ts index 6f1114e18b7..e69dc2bbd8c 100644 --- a/packages/metadata-protocol/src/protocol-authoring-gate.ts +++ b/packages/metadata-protocol/src/protocol-authoring-gate.ts @@ -185,6 +185,7 @@ export async function runAuthoringGate( this: Pick, evt: { type: string; name: string; state: 'draft' | 'active'; body: unknown; + userTextLocales?: readonly (string | undefined)[]; }): Promise { const singular = PLURAL_TO_SINGULAR[evt.type] ?? evt.type; const gate = this.authoringGates.get(singular); @@ -203,6 +204,9 @@ export async function runAuthoringGate( body: evt.body, isArtifactBacked: artifactBacked, ...(declaredBody !== undefined ? { declaredBody } : {}), + ...(evt.userTextLocales !== undefined + ? { userTextLocales: evt.userTextLocales.filter((l): l is string => typeof l === 'string' && l.length > 0) } + : {}), }); } diff --git a/packages/metadata-protocol/src/protocol-save.ts b/packages/metadata-protocol/src/protocol-save.ts index bf0f71a6458..4a6694445d8 100644 --- a/packages/metadata-protocol/src/protocol-save.ts +++ b/packages/metadata-protocol/src/protocol-save.ts @@ -1790,6 +1790,7 @@ export class ProtocolSaveFacet { name: request.name, state: mode === 'draft' ? 'draft' : 'active', body: request.item, + ...(request.userTextLocales !== undefined ? { userTextLocales: request.userTextLocales } : {}), }); } diff --git a/packages/metadata-protocol/src/protocol.ts b/packages/metadata-protocol/src/protocol.ts index 4008de6252a..4fa875efb15 100644 --- a/packages/metadata-protocol/src/protocol.ts +++ b/packages/metadata-protocol/src/protocol.ts @@ -1753,6 +1753,7 @@ export class ObjectStackProtocolImplementation implements */ private runAuthoringGate(evt: { type: string; name: string; state: 'draft' | 'active'; body: unknown; + userTextLocales?: readonly (string | undefined)[]; }): Promise { // [#25467 cut 8] The body moved to `protocol-authoring-gate.ts` (see `AuthoringGateHost`). const readAuthoringGates = () => this.authoringGates; diff --git a/packages/plugins/plugin-security/src/packaged-permission-set-lock-gate.ts b/packages/plugins/plugin-security/src/packaged-permission-set-lock-gate.ts index dd06cde20df..a1147ba8e87 100644 --- a/packages/plugins/plugin-security/src/packaged-permission-set-lock-gate.ts +++ b/packages/plugins/plugin-security/src/packaged-permission-set-lock-gate.ts @@ -78,6 +78,8 @@ export interface PermissionSetLockGateContext { type: string; name: string; body: unknown; + /** [#32656] The caller's language ladder, stated by the write door (`MetadataAuthoringGateContext`). */ + userTextLocales?: readonly string[]; } /** @@ -111,7 +113,7 @@ export function registerPackagedPermissionSetLockGate(protocol: any, ql: any): b // A metadata-door save that targets a package-declared name is an // override of the shipped base whether or not an overlay row exists yet, // so the remedy the refusal teaches is the clone path. - assertPermissionSetNotPackageDeclared(ctx.name, ql, 'update', probe); + assertPermissionSetNotPackageDeclared(ctx.name, ql, 'update', probe, ctx.userTextLocales); }); return true; } diff --git a/packages/plugins/plugin-security/src/packaged-permission-set-lock.test.ts b/packages/plugins/plugin-security/src/packaged-permission-set-lock.test.ts index f7fcf3a8864..b9ed6192ea4 100644 --- a/packages/plugins/plugin-security/src/packaged-permission-set-lock.test.ts +++ b/packages/plugins/plugin-security/src/packaged-permission-set-lock.test.ts @@ -259,6 +259,46 @@ describe('the lock refusal carries its guidance as `userMessage` on the wire env expect(String(rejection.message)).toContain('registry unavailable'); }); + // [#32656] Ruling C on #32440: the producer composes the sentence in the + // request's language, else the workspace default, else `en`. The write door + // states the two locales on the gate's context (`userTextLocales`). + it('[#32656] the refusal speaks the caller\'s language: request locale, then the workspace default, then en', async () => { + const gate = lockGate(makeQl([shippedArtifact()])); + const refuse = (userTextLocales?: string[]) => gate({ + type: 'permission', name: SET_NAME, body: packagedSet(), ...(userTextLocales ? { userTextLocales } : {}), + } as any).then(() => null, (e: any) => e); + + const zh = await refuse(['zh-CN', 'en']); + expect(zh).toBeInstanceOf(PackagedPermissionSetLockedError); + expect(zh.userMessage).toContain('此权限集由已安装的软件包提供'); + expectEndUserCopy(zh.userMessage, SET_NAME, PACKAGE_ID); + const ja = await refuse(['ja-JP', 'zh-CN']); + expect(ja.userMessage, 'the request language wins when it has text').toContain('この権限セット'); + const workspace = await refuse(['tlh', 'zh-TW']); + expect(workspace.userMessage, 'an unsupported request language falls back to the workspace default').toContain('此權限集'); + const floor = await refuse(['tlh', 'tlh']); + const unstated = await refuse(); + expect(floor.userMessage).toBe(unstated.userMessage); + expect(String(unstated.userMessage)).toMatch(/clone it instead/i); + // Only the user's half moves: code, status and the diagnostic are the same in every language. + for (const r of [zh, ja, workspace, floor]) { + expect(r.code).toBe('NOT_OVERRIDABLE'); + expect(r.status).toBe(403); + expect(r.message).toBe(unstated.message); + } + }); + + it('[#32656] the provenance-unknown refusal follows the same ladder', async () => { + const ql = makeQl([]); + ql.registry = { listItems: () => { throw new Error('registry unavailable'); } }; + const gate = lockGate(ql, async () => { throw new Error('metadata store unavailable'); }); + const rejection = await gate({ type: 'permission', name: 'unknown_provenance', body: {}, userTextLocales: ['de-DE'] } as any) + .then(() => null, (e: any) => e); + expect(rejection).toBeInstanceOf(PackagedPermissionSetProvenanceUnknownError); + expect(rejection.userMessage).toContain('kann gerade nicht gespeichert werden'); + expectEndUserCopy(rejection.userMessage, 'unknown_provenance', 'registry unavailable', 'metadata store unavailable'); + }); + it('a SchemaRegistry that answers with a NON-LIST is the same ambiguity: the save is refused, not read as "nothing declared"', async () => { const ql = makeQl([]); ql.registry = { listItems: () => undefined as any }; diff --git a/packages/plugins/plugin-security/src/packaged-permission-set-lock.ts b/packages/plugins/plugin-security/src/packaged-permission-set-lock.ts index 207369a6f75..bf6780d0388 100644 --- a/packages/plugins/plugin-security/src/packaged-permission-set-lock.ts +++ b/packages/plugins/plugin-security/src/packaged-permission-set-lock.ts @@ -86,6 +86,7 @@ */ import { isTenantAuthored } from '@objectstack/metadata-core'; +import { resolveBundleLocale } from '@objectstack/spec/system'; /** * ⛔ This module imports NOTHING from the rest of the plugin, and that is @@ -290,18 +291,96 @@ export function classifyPackagedPermissionSet( * carries no host state either: a sandboxed body that catches this error * receives static text. * - * English, like every platform refusal: there is no localization path for a - * thrown `userMessage`, and these texts do not invent one. + * [#32656] In the caller's language (ruling C on #32440): the producer + * composes the sentence in the request locale, else the workspace default, + * else `en` ({@link packagedSetUserMessage}). The write door states the two + * locales (`MetadataAuthoringGateContext.userTextLocales`); a caller that + * states none gets `en`, the text this refusal always carried. */ -const LOCKED_USER_MESSAGE = - `This permission set is provided by an installed package and can't be edited here. Clone it instead ` - + `with the Clone action, then edit the clone. The clone is your organization's own permission set, ` - + `and package upgrades keep reaching the original.`; +type PackagedSetUserText = Readonly>; -const PROVENANCE_UNKNOWN_USER_MESSAGE = - `This permission set can't be saved right now, because the system couldn't confirm whether an installed ` - + `package provides it. Try again in a moment. To customize a permission set that a package provides, ` - + `clone it with the Clone action and edit the clone.`; +const LOCKED_USER_TEXT: PackagedSetUserText = { + en: `This permission set is provided by an installed package and can't be edited here. Clone it instead ` + + `with the Clone action, then edit the clone. The clone is your organization's own permission set, ` + + `and package upgrades keep reaching the original.`, + 'zh-Hans': '此权限集由已安装的软件包提供,不能在这里编辑。请使用“克隆”操作克隆它,然后编辑克隆出的权限集。' + + '克隆出的权限集归贵组织所有,软件包升级仍会照常更新原权限集。', + 'zh-Hant': '此權限集由已安裝的套件提供,無法在這裡編輯。請使用「複製」動作複製它,然後編輯複製出的權限集。' + + '複製出的權限集歸貴組織所有,套件升級仍會照常更新原權限集。', + ja: 'この権限セットはインストール済みのパッケージが提供しているため、ここでは編集できません。' + + '「複製」アクションで複製し、複製したほうを編集してください。複製した権限セットは組織独自のものになり、' + + 'パッケージのアップグレードは引き続き元の権限セットに適用されます。', + ko: '이 권한 집합은 설치된 패키지가 제공하므로 여기에서 편집할 수 없습니다. 복제 작업으로 복제한 다음 복제본을 ' + + '편집하세요. 복제본은 조직 고유의 권한 집합이 되며, 패키지 업그레이드는 계속 원본에 적용됩니다.', + es: 'Este conjunto de permisos lo proporciona un paquete instalado y no se puede editar aquí. Clónelo con la ' + + 'acción Clonar y edite el clon. El clon es un conjunto de permisos propio de su organización, y las ' + + 'actualizaciones del paquete siguen llegando al original.', + fr: 'Cet ensemble d’autorisations est fourni par un package installé et ne peut pas être modifié ici. ' + + 'Clonez-le avec l’action Cloner, puis modifiez le clone. Le clone appartient à votre organisation, et les ' + + 'mises à jour du package continuent de s’appliquer à l’original.', + de: 'Dieser Berechtigungssatz wird von einem installierten Paket bereitgestellt und kann hier nicht bearbeitet ' + + 'werden. Klonen Sie ihn mit der Aktion „Klonen“ und bearbeiten Sie den Klon. Der Klon gehört Ihrer ' + + 'Organisation, und Paket-Upgrades erreichen weiterhin das Original.', + 'pt-BR': 'Este conjunto de permissões é fornecido por um pacote instalado e não pode ser editado aqui. Clone-o ' + + 'com a ação Clonar e edite o clone. O clone é um conjunto de permissões da sua organização, e as ' + + 'atualizações do pacote continuam chegando ao original.', + ru: 'Этот набор разрешений предоставлен установленным пакетом, и его нельзя изменить здесь. Клонируйте его ' + + 'действием «Клонировать» и измените клон. Клон принадлежит вашей организации, а обновления пакета ' + + 'по-прежнему применяются к оригиналу.', + ar: 'مجموعة الأذونات هذه يوفرها حزمة مثبتة ولا يمكن تعديلها هنا. انسخها باستخدام إجراء النسخ، ثم عدّل النسخة. ' + + 'النسخة مجموعة أذونات خاصة بمؤسستك، وتستمر ترقيات الحزمة في الوصول إلى المجموعة الأصلية.', +}; + +const PROVENANCE_UNKNOWN_USER_TEXT: PackagedSetUserText = { + en: `This permission set can't be saved right now, because the system couldn't confirm whether an installed ` + + `package provides it. Try again in a moment. To customize a permission set that a package provides, ` + + `clone it with the Clone action and edit the clone.`, + 'zh-Hans': '此权限集暂时无法保存,因为系统无法确认它是否由已安装的软件包提供。请稍后重试。' + + '如需自定义由软件包提供的权限集,请使用“克隆”操作克隆它,然后编辑克隆出的权限集。', + 'zh-Hant': '此權限集暫時無法儲存,因為系統無法確認它是否由已安裝的套件提供。請稍後再試。' + + '如需自訂由套件提供的權限集,請使用「複製」動作複製它,然後編輯複製出的權限集。', + ja: 'この権限セットは現在保存できません。インストール済みのパッケージが提供しているかどうかを確認できなかったためです。' + + 'しばらくしてからもう一度お試しください。パッケージが提供する権限セットをカスタマイズするには、' + + '「複製」アクションで複製し、複製したほうを編集してください。', + ko: '설치된 패키지가 이 권한 집합을 제공하는지 확인할 수 없어 지금은 저장할 수 없습니다. 잠시 후 다시 시도하세요. ' + + '패키지가 제공하는 권한 집합을 사용자 지정하려면 복제 작업으로 복제한 다음 복제본을 편집하세요.', + es: 'Este conjunto de permisos no se puede guardar ahora, porque el sistema no pudo confirmar si lo proporciona ' + + 'un paquete instalado. Vuelva a intentarlo en un momento. Para personalizar un conjunto de permisos que ' + + 'proporciona un paquete, clónelo con la acción Clonar y edite el clon.', + fr: 'Cet ensemble d’autorisations ne peut pas être enregistré pour le moment, car le système n’a pas pu ' + + 'confirmer s’il est fourni par un package installé. Réessayez dans un instant. Pour personnaliser un ' + + 'ensemble d’autorisations fourni par un package, clonez-le avec l’action Cloner et modifiez le clone.', + de: 'Dieser Berechtigungssatz kann gerade nicht gespeichert werden, weil das System nicht bestätigen konnte, ' + + 'ob ein installiertes Paket ihn bereitstellt. Versuchen Sie es gleich noch einmal. Um einen ' + + 'Berechtigungssatz anzupassen, den ein Paket bereitstellt, klonen Sie ihn mit der Aktion „Klonen“ und ' + + 'bearbeiten Sie den Klon.', + 'pt-BR': 'Este conjunto de permissões não pode ser salvo agora, porque o sistema não conseguiu confirmar se um ' + + 'pacote instalado o fornece. Tente novamente em instantes. Para personalizar um conjunto de permissões ' + + 'fornecido por um pacote, clone-o com a ação Clonar e edite o clone.', + ru: 'Этот набор разрешений сейчас нельзя сохранить: системе не удалось проверить, предоставлен ли он ' + + 'установленным пакетом. Повторите попытку чуть позже. Чтобы настроить набор разрешений из пакета, ' + + 'клонируйте его действием «Клонировать» и измените клон.', + ar: 'لا يمكن حفظ مجموعة الأذونات هذه الآن، لأن النظام لم يتمكن من التأكد مما إذا كانت حزمة مثبتة توفرها. ' + + 'حاول مرة أخرى بعد قليل. لتخصيص مجموعة أذونات توفرها حزمة، انسخها باستخدام إجراء النسخ ثم عدّل النسخة.', +}; + +/** + * The sentence of `text` in the first locale of `locales` it has, each code + * matched by the platform's one locale ladder ({@link resolveBundleLocale}: + * exact, case-insensitive, the platform table language, one subtag shorter); + * `en` when none matches or none is stated. + */ +function packagedSetUserMessage( + text: PackagedSetUserText, + locales: readonly (string | null | undefined)[] | undefined, +): string { + for (const locale of locales ?? []) { + if (typeof locale !== 'string' || locale.length === 0) continue; + const matched = resolveBundleLocale(text, locale); + if (matched !== undefined) return text[matched]!; + } + return text.en!; +} /** * The refusal a write door throws for a package-declared set. @@ -347,7 +426,13 @@ export class PackagedPermissionSetLockedError extends Error { * [ADR-0150 D2, #31698] `packageId`: the package that declares the set, or * every one that does, each named — never the first found alone. */ - constructor(name: string, packageId: string | readonly string[], _operation: 'insert' | 'update') { + constructor( + name: string, + packageId: string | readonly string[], + _operation: 'insert' | 'update', + /** [#32656] The caller's language ladder: request locale, then workspace default. */ + userTextLocales?: readonly (string | null | undefined)[], + ) { const declarers = (typeof packageId === 'string' ? [packageId] : packageId).map((id) => `'${id}'`); const by = declarers.length > 1 ? `packages ${declarers.slice(0, -1).join(', ')} and ${declarers[declarers.length - 1]}` : `package ${declarers[0]}`; super( @@ -359,7 +444,7 @@ export class PackagedPermissionSetLockedError extends Error { + `flowing to '${name}' untouched.`, ); this.name = 'PackagedPermissionSetLockedError'; - this.userMessage = LOCKED_USER_MESSAGE; + this.userMessage = packagedSetUserMessage(LOCKED_USER_TEXT, userTextLocales); } } @@ -375,7 +460,7 @@ export class PackagedPermissionSetProvenanceUnknownError extends Error { readonly statusCode = 403; /** The guidance addressed to the end user; `message` stays the diagnostic. */ readonly userMessage: string; - constructor(name: string, reason: string) { + constructor(name: string, reason: string, userTextLocales?: readonly (string | null | undefined)[]) { super( `[Security] Permission set '${name}' cannot be saved right now: this system could not determine ` + `whether the set is declared by an installed package (${reason}). The save is refused rather than ` @@ -383,7 +468,7 @@ export class PackagedPermissionSetProvenanceUnknownError extends Error { + `once the metadata layer is readable; if you meant to customize a packaged set, clone it instead.`, ); this.name = 'PackagedPermissionSetProvenanceUnknownError'; - this.userMessage = PROVENANCE_UNKNOWN_USER_MESSAGE; + this.userMessage = packagedSetUserMessage(PROVENANCE_UNKNOWN_USER_TEXT, userTextLocales); } } @@ -398,13 +483,14 @@ export function assertPermissionSetNotPackageDeclared( ql: any, operation: 'insert' | 'update', layered?: LayeredProbe, + userTextLocales?: readonly (string | null | undefined)[], ): PackagedSetVerdict { const verdict = classifyPackagedPermissionSet(name, ql, layered); if (verdict.status === 'packaged') { - throw new PackagedPermissionSetLockedError(name, verdict.packageIds, operation); + throw new PackagedPermissionSetLockedError(name, verdict.packageIds, operation, userTextLocales); } if (verdict.status === 'unknown') { - throw new PackagedPermissionSetProvenanceUnknownError(name, verdict.reason); + throw new PackagedPermissionSetProvenanceUnknownError(name, verdict.reason, userTextLocales); } return verdict; } diff --git a/packages/plugins/plugin-security/src/permission-denied-user-copy.test.ts b/packages/plugins/plugin-security/src/permission-denied-user-copy.test.ts index 41db69c8b4c..0bcfe4542bc 100644 --- a/packages/plugins/plugin-security/src/permission-denied-user-copy.test.ts +++ b/packages/plugins/plugin-security/src/permission-denied-user-copy.test.ts @@ -176,6 +176,7 @@ interface Denial { async function denyDelete( locale: string | undefined, i18n?: FileI18nAdapter, + workspaceLocale?: string, ): Promise { const engine = makeEngine(); const metadata = { @@ -221,6 +222,7 @@ async function denyDelete( positions: ['org_member'], permissions: ['app_reader'], ...(locale ? { locale } : {}), + ...(workspaceLocale ? { workspaceLocale } : {}), }, }; try { @@ -271,6 +273,18 @@ describe('#7414 — the 403 an end user reads', () => { } }); + // [#32656] Ruling C on #32440: the request's language, else the workspace + // default, else `en`. `locale` folds the two (the request wins), so the + // workspace default rides the context on its own as `workspaceLocale`. + it('[#32656] a request language with no text falls back to the workspace default, then to en', async () => { + const workspace = await denyDelete('de-DE', undefined, 'zh-CN'); + expect(workspace.message).toBe(BUILTIN_OPERATION_MESSAGES['zh-CN'].permission_denied); + const request = await denyDelete('ja-JP', undefined, 'zh-CN'); + expect(request.message, 'the request language wins when it has text').toBe(BUILTIN_OPERATION_MESSAGES['ja-JP'].permission_denied); + const floor = await denyDelete('de-DE', undefined, 'de-DE'); + expect(floor.message).toBe(BUILTIN_OPERATION_MESSAGES.en.permission_denied); + }); + it('names no object, no operation and no position — in every locale it can render', async () => { const locales = Object.keys(BUILTIN_OPERATION_MESSAGES); expect(locales.length).toBeGreaterThanOrEqual(4); diff --git a/packages/plugins/plugin-security/src/security-plugin-authz-middleware.ts b/packages/plugins/plugin-security/src/security-plugin-authz-middleware.ts index 3438ed8ec36..056b70a6994 100644 --- a/packages/plugins/plugin-security/src/security-plugin-authz-middleware.ts +++ b/packages/plugins/plugin-security/src/security-plugin-authz-middleware.ts @@ -94,7 +94,13 @@ import { markFilterSubtreeProvenance } from '@objectstack/spec/data'; // [#7414] The SHARED operation-message catalog #7307 built for the data path's // operation-level refusals. Second consumer, same mechanism — a second remedy // for one defect class is what that module exists to prevent. -import { objectFieldLabelKey, renderOperationMessage } from '@objectstack/spec/system'; +import { + BUILTIN_OPERATION_MESSAGES, + objectFieldLabelKey, + operationMessageTranslationKey, + renderOperationMessage, + resolveBundleLocale, +} from '@objectstack/spec/system'; // [#19989] The engine's own update-dispatch predicate, asked rather than // re-derived: step 3.6 needs to know which row the ENGINE will write. import { resolveEngineUpdateDispatch, type EngineUpdateDispatchData } from '@objectstack/metadata-core'; @@ -218,10 +224,51 @@ export interface WriteImageCheckSeam { function userFacingDenialMessage( ctx: PluginContext, messageKey: UserFacingDenialKey, - locale: string | undefined, + locales: DenialLocales, params?: Record, ): string { - return renderOperationMessage({ messageKey, params }, { locale, translate: denialTranslator(ctx) }); + const translate = denialTranslator(ctx); + return renderOperationMessage({ messageKey, params }, { locale: denialLocaleOf(messageKey, locales, translate), translate }); +} + +/** + * [#32656] The caller's language ladder for a refusal's user sentence: the + * request's locale, then the workspace default (ruling C on #32440), read off + * the operation's execution context. `locale` alone folds the two (the request + * locale wins the fold), so a request in a language the platform has no text + * in used to fall straight to `en` past a workspace default it does have. + */ +type DenialLocales = readonly (string | undefined)[]; + +function denialLocalesOf(context: { locale?: string; workspaceLocale?: string } | undefined): DenialLocales { + return [context?.locale, context?.workspaceLocale]; +} + +/** + * The first locale of the ladder this sentence has text in: a deployment's + * `errors.` override for it, else the built-in catalog (matched by the + * platform's one locale ladder). `undefined` when none has it, which + * {@link renderOperationMessage} renders in `en`. + */ +function denialLocaleOf( + messageKey: UserFacingDenialKey, + locales: DenialLocales, + translate: ReturnType, +): string | undefined { + const key = operationMessageTranslationKey(messageKey); + for (const locale of locales) { + if (typeof locale !== 'string' || locale.length === 0) continue; + if (translate) { + try { + const override = translate(key, locale); + if (typeof override === 'string' && override.length > 0 && override !== key) return locale; + } catch { + // A misbehaving i18n service must not turn a 403 into a 500. + } + } + if (resolveBundleLocale(BUILTIN_OPERATION_MESSAGES, locale) !== undefined) return locale; + } + return undefined; } /** @@ -310,10 +357,12 @@ function fieldEditDenialMessage( forbidden: readonly string[], schema: { fields?: Record } | null | undefined, readable: Record, - locale: string | undefined, + locales: DenialLocales, ): string { const translate = denialTranslator(ctx); - const loc = locale ?? 'en'; + // Labels are translated in the language the sentence itself resolves to. + const loc = denialLocaleOf('field_edit_denied', locales, translate) ?? 'en'; + const locale = [loc]; const labels: string[] = []; for (const field of forbidden) { if (readable[field]?.readable === false) return userFacingDenialMessage(ctx, 'field_edit_denied_opaque', locale); @@ -344,7 +393,7 @@ function fieldEditDenialMessage( * they fill, so they resolve by the catalog's own locale ladder and a * deployment's `errors.` override applies to them as to the sentence. */ -function labelList(ctx: PluginContext, labels: readonly string[], locale: string | undefined): string { +function labelList(ctx: PluginContext, labels: readonly string[], locale: DenialLocales): string { const separator = userFacingDenialMessage(ctx, 'field_label_list_separator', locale); return labels.map((label) => userFacingDenialMessage(ctx, 'field_label_quoted', locale, { label })).join(separator); } @@ -902,7 +951,7 @@ export function registerAuthzMiddleware( userId: opCtx.context?.userId ?? 'unknown', }); throw new PermissionDeniedError( - userFacingDenialMessage(ctx, 'permission_denied', opCtx.context?.locale), + userFacingDenialMessage(ctx, 'permission_denied', denialLocalesOf(opCtx.context)), { operation: opCtx.operation, object: opCtx.object, @@ -1042,7 +1091,7 @@ export function registerAuthzMiddleware( userId: opCtx.context?.userId ?? 'unknown', }); throw new PermissionDeniedError( - userFacingDenialMessage(ctx, 'permission_denied', opCtx.context?.locale), + userFacingDenialMessage(ctx, 'permission_denied', denialLocalesOf(opCtx.context)), { operation: opCtx.operation, object: opCtx.object, positions, permissionSets: explicitPermissionSets }, developerMessage, ); @@ -1365,7 +1414,7 @@ export function registerAuthzMiddleware( userId: opCtx.context?.userId ?? 'unknown', }); throw new PermissionDeniedError( - userFacingDenialMessage(ctx, 'record_access_denied', opCtx.context?.locale), + userFacingDenialMessage(ctx, 'record_access_denied', denialLocalesOf(opCtx.context)), { operation: opCtx.operation, object: opCtx.object, @@ -1499,7 +1548,7 @@ export function registerAuthzMiddleware( forbidden, typeof ql?.getSchema === 'function' ? ql.getSchema(opCtx.object) as any : undefined, this.computeQueryGuardFieldPerms(opCtx.object, secMeta, permissionSets, delegatorSets), - opCtx.context?.locale, + denialLocalesOf(opCtx.context), ), ); } @@ -1695,7 +1744,7 @@ export function registerAuthzMiddleware( `${action} requires the transfer grant (allowTransfer or modifyAllRecords)`, refusalDetails, ), - userFacingDenialMessage(ctx, userKey, opCtx.context?.locale), + userFacingDenialMessage(ctx, userKey, denialLocalesOf(opCtx.context)), ); }; // [ADR-0142 D4] A claim or a release the step did not admit names the @@ -1707,7 +1756,7 @@ export function registerAuthzMiddleware( 'other change of ownership requires the transfer grant (allowTransfer or modifyAllRecords)', refusalDetails, ), - userFacingDenialMessage(ctx, userKey, opCtx.context?.locale), + userFacingDenialMessage(ctx, userKey, denialLocalesOf(opCtx.context)), ); }; const denyQueueWrite = (condition: string, userKey: UserFacingDenialKey): never => { @@ -1717,7 +1766,7 @@ export function registerAuthzMiddleware( '(allowTransfer or modifyAllRecords)', refusalDetails, ), - userFacingDenialMessage(ctx, userKey, opCtx.context?.locale), + userFacingDenialMessage(ctx, userKey, denialLocalesOf(opCtx.context)), ); }; // [ADR-0138 D1] The guest branch (see the step's header). Its refusal @@ -2067,7 +2116,7 @@ export function registerAuthzMiddleware( userId: opCtx.context?.userId ?? 'unknown', }); throw new PermissionDeniedError( - userFacingDenialMessage(ctx, 'record_change_not_allowed', opCtx.context?.locale), + userFacingDenialMessage(ctx, 'record_change_not_allowed', denialLocalesOf(opCtx.context)), { operation: opCtx.operation, object: opCtx.object, positions, permissionSets: explicitPermissionSets }, developerMessage, ); @@ -2217,7 +2266,7 @@ export function registerAuthzMiddleware( userId: opCtx.context?.userId ?? 'unknown', }); throw new PermissionDeniedError( - userFacingDenialMessage(ctx, 'record_change_not_allowed', opCtx.context?.locale), + userFacingDenialMessage(ctx, 'record_change_not_allowed', denialLocalesOf(opCtx.context)), { operation: opCtx.operation, object: opCtx.object, positions, permissionSets: explicitPermissionSets }, developerMessage, ); @@ -2642,7 +2691,7 @@ export function registerAuthzMiddleware( userId: opCtx.context?.userId ?? 'unknown', }); throw new PermissionDeniedError( - userFacingDenialMessage(ctx, 'record_change_not_allowed', opCtx.context?.locale), + userFacingDenialMessage(ctx, 'record_change_not_allowed', denialLocalesOf(opCtx.context)), { operation: opCtx.operation, object: opCtx.object, positions, permissionSets: explicitPermissionSets }, developerMessage, ); 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 index 72ea8ee9a25..c2841a41be4 100644 --- a/packages/runtime/src/domains/meta-save-user-text-locale.test.ts +++ b/packages/runtime/src/domains/meta-save-user-text-locale.test.ts @@ -87,18 +87,24 @@ async function bootStore() { const protocol = new ObjectStackProtocolImplementation(engine as any); // What each save handed the protocol, read where the protocol receives it. const stated: unknown[] = []; + // …and what the type's authoring gate was handed (plugin-security's + // packaged permission-set lock registers here; its refusal's + // `userMessage` is composed from these). + const gated: unknown[] = []; + protocol.registerAuthoringGate('permission', (ctx) => { gated.push(ctx.userTextLocales); }); const save = protocol.saveMetaItem.bind(protocol); (protocol as any).saveMetaItem = (request: any) => { stated.push(request.userTextLocales); return save(request); }; - return { protocol, stated }; + return { protocol, stated, gated }; } interface Saved { status: number; body: any } interface Door { save(who: Caller, name: string): Promise; stated: unknown[]; + gated: unknown[]; } function makeRes() { @@ -114,12 +120,13 @@ function makeRes() { } async function bootDispatcher(): Promise { - const { protocol, stated } = await bootStore(); + const { protocol, stated, gated } = 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, + gated, save: async (who, name) => { (dispatcher as any).timedResolveExecutionContext = async () => clone(who); const body = permissionSet(name); @@ -136,7 +143,7 @@ async function bootDispatcher(): Promise { } async function bootRestServer(): Promise { - const { protocol, stated } = await bootStore(); + const { protocol, stated, gated } = 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); @@ -145,6 +152,7 @@ async function bootRestServer(): Promise { if (!route) throw new Error(`PUT ${META}/:type/:name is not registered`); return { stated, + gated, save: async (who, name) => { rest.resolveExecCtx = async () => clone(who); const res = makeRes(); @@ -178,6 +186,13 @@ for (const [doorName, boot] of DOORS) { expect(door.stated).toEqual([['zh-CN', 'de'], []]); }, 60_000); + it('the type\'s authoring gate receives the same locales, for its refusal\'s userMessage', async () => { + const door = await boot(); + await door.save(caller('zh-CN', 'de'), 'finance_user'); + await door.save(caller(), 'finance_user'); + expect(door.gated).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')); From caeb90463be47d31b3e87f0d4f1880ea943787e2 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 16:20:21 +0000 Subject: [PATCH 4/8] fix(#32656): keep the batch publish body closed; pin the server-stated locales on the doors' exact request pins The batch publish body schema is the body parser, so userTextLocales stays a protocol-call member there, never a body key. Exact request and execution-context key pins now name the new server-stated members. Claude-Session: https://claude.ai/code/session_016WV4cz2MxDkQYCC4U8indM Co-Authored-By: Claude --- .changeset/32656-user-text-request-locale.md | 3 ++- content/docs/references/api/protocol.mdx | 1 - .../src/protocol-history-and-publish.ts | 2 +- .../src/protocol-publish-drafts-advisories.test.ts | 2 ++ packages/metadata-protocol/src/protocol.ts | 2 +- packages/rest/src/rest-exec-ctx-principal-kind.test.ts | 3 +++ .../rest/src/rest-server-meta-door-closed-sets.test.ts | 4 ++++ .../rest/src/rest-server-meta-member-selector.test.ts | 2 ++ .../src/domains/meta-save-user-text-locale.test.ts | 2 ++ .../packages-publish-drafts-request-conformance.test.ts | 9 +++++++-- packages/runtime/src/http-dispatcher.test.ts | 4 ++++ packages/spec/authorable-surface/api.json | 1 - packages/spec/src/api/protocol.zod.ts | 1 - 13 files changed, 28 insertions(+), 8 deletions(-) diff --git a/.changeset/32656-user-text-request-locale.md b/.changeset/32656-user-text-request-locale.md index 617bca97f90..4fdc0b32223 100644 --- a/.changeset/32656-user-text-request-locale.md +++ b/.changeset/32656-user-text-request-locale.md @@ -8,8 +8,9 @@ feat(metadata-protocol): a metadata write's advisories and refusals come back in the caller's language -Clause-②: yes (widening) — `SaveMetaItemRequestSchema`, `PublishMetaItemRequestSchema` and `PublishPackageDraftsRequestSchema` gain an optional `userTextLocales` member (at most two locale codes), and `ExecutionContextSchema` gains an optional `workspaceLocale`. 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. +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: diff --git a/content/docs/references/api/protocol.mdx b/content/docs/references/api/protocol.mdx index ecf09f74a1d..264e1d8e11f 100644 --- a/content/docs/references/api/protocol.mdx +++ b/content/docs/references/api/protocol.mdx @@ -2594,7 +2594,6 @@ The authoring surface of a metadata write. Closed: `copilot` is an AI assistant' | :--- | :--- | :--- | :--- | | **message** | `string` | optional | The author's change note (ADR-0146 D1). The package commit records it, and so does every item history row this publish writes, as `change_note` (read back as each history event's `message`). Absent or empty, those rows record the sentence naming the package instead. | | **backfill** | `{ object: string; field: string }[]` | optional | Opt-in: fields this publish adds whose literal `defaultValue` is written into the object's existing rows once the drafts are live, as the signed-in caller. Absent or `[]`, no row is touched. Each entry names an object and a field and nothing else, and names it once. The whole request is refused `400 VALIDATION_ERROR` before anything is published when an entry is malformed, repeated, or names a field that is not new in this publish or declares no literal default; `backfillApplied` in the response reports the rows written per field. | -| **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: `PublishPackageDraftsRequest.backfill[number]` diff --git a/packages/metadata-protocol/src/protocol-history-and-publish.ts b/packages/metadata-protocol/src/protocol-history-and-publish.ts index 287c5b0e28d..070a01a4b60 100644 --- a/packages/metadata-protocol/src/protocol-history-and-publish.ts +++ b/packages/metadata-protocol/src/protocol-history-and-publish.ts @@ -1473,7 +1473,7 @@ export class ProtocolHistoryAndPublishFacet { * the package. */ message?: string; - /** [#32656] The locales the door states for the findings' user sentences (`PublishPackageDraftsRequestSchema.userTextLocales`). */ + /** [#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; 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 652ec14c059..ef442fc2117 100644 --- a/packages/metadata-protocol/src/protocol-publish-drafts-advisories.test.ts +++ b/packages/metadata-protocol/src/protocol-publish-drafts-advisories.test.ts @@ -37,6 +37,8 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFindOnePredicate } from '@objectstack/metadata-core'; import { ObjectStackProtocolImplementation } from './protocol.js'; +// Paid at collection, not inside a clocked case (check-test-source-alias). +import '@objectstack/lint'; interface Row { id: string; diff --git a/packages/metadata-protocol/src/protocol.ts b/packages/metadata-protocol/src/protocol.ts index 4008de6252a..b272f80f19d 100644 --- a/packages/metadata-protocol/src/protocol.ts +++ b/packages/metadata-protocol/src/protocol.ts @@ -10037,7 +10037,7 @@ 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 (`PublishPackageDraftsRequestSchema.userTextLocales`). */ + /** [#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 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 a14901e365b..406777cab07 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 index 72ea8ee9a25..f9c2c9b6d66 100644 --- a/packages/runtime/src/domains/meta-save-user-text-locale.test.ts +++ b/packages/runtime/src/domains/meta-save-user-text-locale.test.ts @@ -27,6 +27,8 @@ import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protoco 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`; 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/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 94bb6c26d72..68e018b0c31 100644 --- a/packages/spec/authorable-surface/api.json +++ b/packages/spec/authorable-surface/api.json @@ -1449,7 +1449,6 @@ "api/PublishMetaItemResponse:version", "api/PublishPackageDraftsRequest:backfill", "api/PublishPackageDraftsRequest:message", - "api/PublishPackageDraftsRequest:userTextLocales", "api/PublishPackageDraftsResponse:backfillApplied", "api/PublishPackageDraftsResponse:commitId", "api/PublishPackageDraftsResponse:failed", diff --git a/packages/spec/src/api/protocol.zod.ts b/packages/spec/src/api/protocol.zod.ts index faf7b0afd11..c94fbfebcab 100644 --- a/packages/spec/src/api/protocol.zod.ts +++ b/packages/spec/src/api/protocol.zod.ts @@ -1758,7 +1758,6 @@ export const PublishPackageDraftsRequestSchema = lazySchema(() => z.object({ + 'is not new in this publish or declares no literal default; ' + '`backfillApplied` in the response reports the rows written per field.', ), - userTextLocales: userTextLocalesMember(), })); /** From fa8f2f5d0a7bdd78250b80084ba3c9105a65322d Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 16:22:36 +0000 Subject: [PATCH 5/8] test(#32656): pay the lint load at collection in the gate pass-through pin Claude-Session: https://claude.ai/code/session_016WV4cz2MxDkQYCC4U8indM Co-Authored-By: Claude --- packages/metadata-protocol/src/mutation-listeners.test.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/metadata-protocol/src/mutation-listeners.test.ts b/packages/metadata-protocol/src/mutation-listeners.test.ts index 571ef58ec76..61922f09d0a 100644 --- a/packages/metadata-protocol/src/mutation-listeners.test.ts +++ b/packages/metadata-protocol/src/mutation-listeners.test.ts @@ -13,6 +13,8 @@ import { describe, it, expect, vi } from 'vitest'; import { ObjectStackProtocolImplementation } from './protocol.js'; +// Paid at collection, not inside a clocked case (check-test-source-alias). +import '@objectstack/lint'; import type { MetadataMutationEvent } from './protocol.js'; function makeProtocol() { From fedb4843bb2f3942b1892b5f417c023cb31d26a2 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 17:11:24 +0000 Subject: [PATCH 6/8] test(#32656): name the server-stated locales on the publish-then-read request pin Claude-Session: https://claude.ai/code/session_016WV4cz2MxDkQYCC4U8indM Co-Authored-By: Claude --- .../src/domains/packages-seed-apply-org-scope.test.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) 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'); }); }); From 1cffbad85e173c44382e98e866f69639619a5628 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 18:39:28 +0000 Subject: [PATCH 7/8] chore(spec): regenerate the reference page and authorable-surface shard on the merged tree Claude-Session: https://claude.ai/code/session_016WV4cz2MxDkQYCC4U8indM Co-Authored-By: Claude --- content/docs/references/api/protocol.mdx | 13 +++++++++++++ packages/spec/authorable-surface/api.json | 3 +++ 2 files changed, 16 insertions(+) diff --git a/content/docs/references/api/protocol.mdx b/content/docs/references/api/protocol.mdx index 264e1d8e11f..454b54fa4ef 100644 --- a/content/docs/references/api/protocol.mdx +++ b/content/docs/references/api/protocol.mdx @@ -749,6 +749,7 @@ A write-path strip event: caller-supplied fields legally dropped from the payloa | **seq** | `integer` | optional | Monotonic sequence number of the metadata event this delete appended to the item history (sys_metadata_history.event_seq) — the ordering token the history/audit trail is read by, and the same key both write-verb siblings declare. Unlike `version` it is not an OCC token. Optional HERE, unlike on those siblings, because only the repository path's delete-ful branch appends an event: a no-op reset (no overlay row existed) and the control-plane legacy raw-engine path both answer without one. Absence means "this branch appended no history event", never "nothing was deleted" — read `reset` for that. | | **projectionApplied** | `{ success: boolean; error?: string }` | optional | Outcome of the awaited ADR-0094 mutation projector — the post-persist step that materializes this metadata into its derived data-plane read model. The same receipt `{@link SaveMetaItemResponseSchema}` and `{@link PublishMetaItemResponseSchema}` carry, because the projector runs on all three verbs of this door: on a delete it re-reads the layered state and either retires the derived record or resets it to the artifact baseline. Present ONLY when a projector is registered for this metadata type AND a row was actually deleted, which is why it is optional: its absence means "no projector ran", never "the projection failed". Best-effort by design — a projector failure is reported here and logged, never thrown, so a caller that needs the read model to be live must check `projectionApplied.success` rather than rely on the 200. | | **message** | `string` | optional | | +| **advisories** | `{ rule: string; path: string; where: string; message: string; … }[]` | optional | What the delete did to the rows of the object it changed, in the same element shape and omitted-when-empty discipline as `SaveMetaItemResponseSchema.advisories`. Present ONLY when at least one entry was raised: an empty array is never emitted, so a clean answer's bytes are unchanged and a caller that ignores this key behaves exactly as before. A removal that hands an object back the definition beneath it (an `object_extension` that re-declared a field) can make a stored computed field (a non-`formula` field declaring `expression`) compute something new; per such field, the fill of the object's existing rows the save door also runs: `stored-expression-filled` (`info`, the rows written) or `stored-expression-fill-incomplete` (`warning`, what is left and how to fill it). The delete itself SUCCEEDED either way. | ### Nested Shape: `DeleteMetaItemResponse.projectionApplied` @@ -757,6 +758,18 @@ A write-path strip event: caller-supplied fields legally dropped from the payloa | **success** | `boolean` | ✅ | False when the projector threw; the metadata delete itself still succeeded. | | **error** | `string` | optional | Projector failure message, present only when `success` is false. | +### Nested Shape: `DeleteMetaItemResponse.advisories[number]` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **rule** | `string` | ✅ | Stable diagnostic rule id (`flow-multi-write-unfiltered`, `approval-expression-invalid`, …). Machine-readable and stable across releases — the key a renderer groups or suppresses by. | +| **path** | `string` | ✅ | Config path inside the SUBMITTED body (`flows[0].nodes[1].config.multi`), so an editor can jump to the offending key. May be empty when the finding is about the item as a whole. The TOP-LEVEL collection entry follows one rule. The gate evaluates against a private per-write snapshot whose indexes no caller can resolve; a collection-resident write type is one whose collection that snapshot fills with the tenant's other stored items beside the written one, and there the entry is keyed by NAME, never by an array index — for example `objects.acme_invoice.sharingModel` (an `object` write) or `datasets.acme_invoice_metrics.dimensions[0].field` (a `dataset` write). Every other write type is the sole member of its own collection in that snapshot, so its `[0]` IS the written item and stays positional (for example `flows[0]...`). Which write types are collection-resident is derived, never listed: `@objectstack/lint`'s runtime gate computes the set (`NAME_KEYED_STACK_KEYS`) as the collections it carries as resolution context that a gated write type also lands in, so it changes with the gate, not with this text. An entry whose name cannot be spliced into a dotted path keeps its index. Nested positions inside one named item stay positional (`objects.acme_invoice.indexes[1]`): they index the author's own document. | +| **where** | `string` | ✅ | Human-readable location — `flow "leave_approval" · node "approve"`. Prose for a person; use `path` for anything mechanical. | +| **message** | `string` | ✅ | What is wrong, in the rule author's own words. | +| **hint** | `string` | ✅ | How to fix it. | +| **severity** | `Enum<'error' \| 'warning' \| 'info'>` | ✅ | How the gate treated this finding. `error` means the write was REFUSED (these appear on the 422, never on a 2xx); `warning` / `info` are advisory — the write succeeded and the finding is FYI. | +| **userMessage** | `string` | optional | The finding's user-facing sentence, composed by its producer in the request's locale (else the workspace default locale, else `en`) — the same field name and producer-marked meaning as `ApiErrorSchema.userMessage`. Present only when the producer authors a user sentence for this `rule`; absent, a consumer renders `message` as before. Consumers render it as received; `rule` stays the stable id and `message` / `hint` stay the developer-facing text. | + --- diff --git a/packages/spec/authorable-surface/api.json b/packages/spec/authorable-surface/api.json index 68e018b0c31..c7b9470aa7d 100644 --- a/packages/spec/authorable-surface/api.json +++ b/packages/spec/authorable-surface/api.json @@ -215,7 +215,9 @@ "api/AuthFeaturesConfig:degradedTenancy", "api/AuthFeaturesConfig:developerEditionCreate", "api/AuthFeaturesConfig:deviceAuthorization", + "api/AuthFeaturesConfig:directSignIn", "api/AuthFeaturesConfig:emailDelivery", + "api/AuthFeaturesConfig:localSignIn", "api/AuthFeaturesConfig:magicLink [RETIRED]", "api/AuthFeaturesConfig:multiOrgEnabled", "api/AuthFeaturesConfig:oidcProvider", @@ -525,6 +527,7 @@ "api/DeleteMetaItemRequest:parentVersion", "api/DeleteMetaItemRequest:state", "api/DeleteMetaItemRequest:type", + "api/DeleteMetaItemResponse:advisories", "api/DeleteMetaItemResponse:message", "api/DeleteMetaItemResponse:projectionApplied", "api/DeleteMetaItemResponse:reset", From 24f2148f6bc4845bde87f441164c52c71eb8f35b Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 21:49:20 +0000 Subject: [PATCH 8/8] chore(spec): regenerate the API surface and protocol reference on the merged tree Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cz2MxDkQYCC4U8indM --- content/docs/references/api/protocol.mdx | 23 ++++++++++++++++++++--- packages/spec/authorable-surface/api.json | 7 +++++++ 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/content/docs/references/api/protocol.mdx b/content/docs/references/api/protocol.mdx index 454b54fa4ef..9673a02d599 100644 --- a/content/docs/references/api/protocol.mdx +++ b/content/docs/references/api/protocol.mdx @@ -1,7 +1,7 @@ --- title: Protocol schema — API Protocol reference navTitle: Protocol -description: "Protocol schemas of the ObjectStack API Protocol: AiAgentCapabilities and 143 more — each property with its type, default and a TypeScript example." +description: "Protocol schemas of the ObjectStack API Protocol: AiAgentCapabilities and 144 more — each property with its type, default and a TypeScript example." --- {/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} @@ -13,8 +13,8 @@ description: "Protocol schemas of the ObjectStack API Protocol: AiAgentCapabilit ## TypeScript Usage ```typescript -import { AiAgentCapabilitiesSchema, AiAgentChatRequestSchema, AiAgentSummarySchema, AiAgentsResponseSchema, AiChatRequestSchema, AiChatResponseSchema, AiCompleteRequestSchema, AiConversationSchema, AiMessageSchema, AiModelsResponseSchema, AiPendingActionSchema, AiPendingActionStatusSchema, AiStreamChunkSchema, ApproveAiPendingActionResponseSchema, AuditMetaItemRequestSchema, AuditMetaItemResponseSchema, AutomationActionsResponseSchema, AutomationTriggerRequestSchema, AutomationTriggerResponseSchema, BatchDataRequestSchema, BatchDataResponseSchema, CheckPermissionRequestSchema, CheckPermissionResponseSchema, CloneDataResponseSchema, CreateAiConversationRequestSchema, CreateDataRequestSchema, CreateDataResponseSchema, CreateManyDataRequestSchema, CreateManyDataResponseSchema, DeleteDataRequestSchema, DeleteDataResponseSchema, DeleteManyDataRequestSchema, DeleteManyDataResponseSchema, DeleteMetaItemRequestSchema, DeleteMetaItemResponseSchema, DiffMetaItemResponseSchema, DisablePackageRequestSchema, DisablePackageResponseSchema, EnablePackageRequestSchema, EnablePackageResponseSchema, FindDataRequestSchema, FindDataResponseSchema, FindReferencesToMetaResponseSchema, FlowRegistrationSchema, FlowRegistrationRefusalSchema, GetDataRequestSchema, GetDataResponseSchema, GetDiscoveryRequestSchema, GetDiscoveryResponseSchema, GetEffectivePermissionsRequestSchema, GetEffectivePermissionsResponseSchema, GetFieldLabelsRequestSchema, GetFieldLabelsResponseSchema, GetLocalesRequestSchema, GetLocalesResponseSchema, GetMetaDiagnosticsResponseSchema, GetMetaItemCachedRequestSchema, GetMetaItemCachedResponseSchema, GetMetaItemLayeredRequestSchema, GetMetaItemLayeredResponseSchema, GetMetaItemRequestSchema, GetMetaItemResponseSchema, GetMetaItemsRequestSchema, GetMetaItemsResponseSchema, GetMetaTypesRequestSchema, GetMetaTypesResponseSchema, GetNotificationPreferencesRequestSchema, GetNotificationPreferencesResponseSchema, GetObjectPermissionsRequestSchema, GetObjectPermissionsResponseSchema, GetPackageRequestSchema, GetPackageResponseSchema, GetPresenceRequestSchema, GetPresenceResponseSchema, GetPublishedMetaItemResponseSchema, GetRecordFieldAccessResponseSchema, GetTranslationsRequestSchema, GetTranslationsResponseSchema, GetUiViewRequestSchema, GetUiViewResponseSchema, HistoryMetaItemRequestSchema, HistoryMetaItemResponseSchema, HttpFindQueryParamsSchema, InstallPackageRequestSchema, InstallPackageResponseSchema, ListAiConversationsRequestSchema, ListAiConversationsResponseSchema, ListAiPendingActionsRequestSchema, ListAiPendingActionsResponseSchema, ListDraftsResponseSchema, ListNotificationsRequestSchema, ListNotificationsResponseSchema, ListPackagesRequestSchema, ListPackagesResponseSchema, MarkAllNotificationsReadRequestSchema, MarkAllNotificationsReadResponseSchema, MarkNotificationsReadRequestSchema, MarkNotificationsReadResponseSchema, MetadataAuthoringClientSchema, MetadataAuthoringSurfaceSchema, MetadataConflictErrorSchema, NotificationSchema, NotificationPreferencesSchema, PublicFormSubmitResponseSchema, PublishMetaItemRequestSchema, PublishMetaItemResponseSchema, PublishPackageDraftsRequestSchema, PublishPackageDraftsResponseSchema, RealtimeConnectRequestSchema, RealtimeConnectResponseSchema, RealtimeDisconnectRequestSchema, RealtimeDisconnectResponseSchema, RealtimeSubscribeRequestSchema, RealtimeSubscribeResponseSchema, RealtimeUnsubscribeRequestSchema, RealtimeUnsubscribeResponseSchema, RegisterDeviceRequestSchema, RegisterDeviceResponseSchema, RejectAiPendingActionResponseSchema, RollbackMetaItemResponseSchema, RuntimeAuthoringIssueSchema, SaveMetaItemRequestSchema, SaveMetaItemResponseSchema, SearchAllHitSchema, SearchAllPageHitSchema, SearchAllResponseSchema, SeedAppliedIdListSchema, SeedAppliedLandedSchema, SetPresenceRequestSchema, SetPresenceResponseSchema, UninstallPackageRequestSchema, UninstallPackageResponseSchema, UnregisterDeviceRequestSchema, UnregisterDeviceResponseSchema, UpdateAiConversationRequestSchema, UpdateDataRequestSchema, UpdateDataResponseSchema, UpdateManyDataRequestSchema, UpdateManyDataResponseSchema, UpdateNotificationPreferencesRequestSchema, UpdateNotificationPreferencesResponseSchema, ValidateDataIssueSchema, ValidateDataRequestSchema, ValidateDataResponseSchema } from '@objectstack/spec/api'; -import type { AiAgentCapabilities, AiAgentChatRequest, AiAgentSummary, AiAgentsResponse, AiChatRequest, AiChatResponse, AiCompleteRequest, AiConversation, AiMessage, AiModelsResponse, AiPendingAction, AiPendingActionStatus, AiStreamChunk, ApproveAiPendingActionResponse, AuditMetaItemRequest, AuditMetaItemResponse, AutomationActionsResponse, AutomationTriggerRequest, AutomationTriggerResponse, BatchDataRequest, BatchDataResponse, CheckPermissionRequest, CheckPermissionResponse, CloneDataResponse, CreateAiConversationRequest, CreateDataRequest, CreateDataResponse, CreateManyDataRequest, CreateManyDataResponse, DeleteDataRequest, DeleteDataResponse, DeleteManyDataRequest, DeleteManyDataResponse, DeleteMetaItemRequest, DeleteMetaItemResponse, DiffMetaItemResponse, DisablePackageRequest, DisablePackageResponse, EnablePackageRequest, EnablePackageResponse, FindDataRequest, FindDataResponse, FindReferencesToMetaResponse, FlowRegistration, FlowRegistrationRefusal, GetDataRequest, GetDataResponse, GetDiscoveryRequest, GetDiscoveryResponse, GetEffectivePermissionsRequest, GetEffectivePermissionsResponse, GetFieldLabelsRequest, GetFieldLabelsResponse, GetLocalesRequest, GetLocalesResponse, GetMetaDiagnosticsResponse, GetMetaItemCachedRequest, GetMetaItemCachedResponse, GetMetaItemLayeredRequest, GetMetaItemLayeredResponse, GetMetaItemRequest, GetMetaItemResponse, GetMetaItemsRequest, GetMetaItemsResponse, GetMetaTypesRequest, GetMetaTypesResponse, GetNotificationPreferencesRequest, GetNotificationPreferencesResponse, GetObjectPermissionsRequest, GetObjectPermissionsResponse, GetPackageRequest, GetPackageResponse, GetPresenceRequest, GetPresenceResponse, GetPublishedMetaItemResponse, GetRecordFieldAccessResponse, GetTranslationsRequest, GetTranslationsResponse, GetUiViewRequest, GetUiViewResponse, HistoryMetaItemRequest, HistoryMetaItemResponse, InstallPackageRequest, InstallPackageResponse, ListAiConversationsRequest, ListAiConversationsResponse, ListAiPendingActionsRequest, ListAiPendingActionsResponse, ListDraftsResponse, ListNotificationsRequest, ListNotificationsResponse, ListPackagesRequest, ListPackagesResponse, MarkAllNotificationsReadRequest, MarkAllNotificationsReadResponse, MarkNotificationsReadRequest, MarkNotificationsReadResponse, MetadataAuthoringClient, MetadataAuthoringSurface, MetadataConflictError, Notification, NotificationPreferences, PublicFormSubmitResponse, PublishMetaItemRequest, PublishMetaItemResponse, PublishPackageDraftsRequest, PublishPackageDraftsResponse, RealtimeConnectRequest, RealtimeConnectResponse, RealtimeDisconnectRequest, RealtimeDisconnectResponse, RealtimeSubscribeRequest, RealtimeSubscribeResponse, RealtimeUnsubscribeRequest, RealtimeUnsubscribeResponse, RegisterDeviceRequest, RegisterDeviceResponse, RejectAiPendingActionResponse, RollbackMetaItemResponse, RuntimeAuthoringIssue, SaveMetaItemRequest, SaveMetaItemResponse, SearchAllHit, SearchAllPageHit, SearchAllResponse, SeedAppliedIdList, SeedAppliedLanded, SetPresenceRequest, SetPresenceResponse, UninstallPackageRequest, UninstallPackageResponse, UnregisterDeviceRequest, UnregisterDeviceResponse, UpdateAiConversationRequest, UpdateDataRequest, UpdateDataResponse, UpdateManyDataRequest, UpdateManyDataResponse, UpdateNotificationPreferencesRequest, UpdateNotificationPreferencesResponse, ValidateDataIssue, ValidateDataRequest, ValidateDataResponse } from '@objectstack/spec/api'; +import { AiAgentCapabilitiesSchema, AiAgentChatRequestSchema, AiAgentSummarySchema, AiAgentsResponseSchema, AiChatRequestSchema, AiChatResponseSchema, AiCompleteRequestSchema, AiConversationSchema, AiMessageSchema, AiModelsResponseSchema, AiPendingActionSchema, AiPendingActionStatusSchema, AiStreamChunkSchema, ApproveAiPendingActionResponseSchema, AuditMetaItemRequestSchema, AuditMetaItemResponseSchema, AutomationActionsResponseSchema, AutomationTriggerRequestSchema, AutomationTriggerResponseSchema, BatchDataRequestSchema, BatchDataResponseSchema, CheckPermissionRequestSchema, CheckPermissionResponseSchema, CloneDataResponseSchema, CreateAiConversationRequestSchema, CreateDataRequestSchema, CreateDataResponseSchema, CreateManyDataRequestSchema, CreateManyDataResponseSchema, DeleteDataRequestSchema, DeleteDataResponseSchema, DeleteManyDataRequestSchema, DeleteManyDataResponseSchema, DeleteMetaItemRequestSchema, DeleteMetaItemResponseSchema, DiffMetaItemResponseSchema, DisablePackageRequestSchema, DisablePackageResponseSchema, EnablePackageRequestSchema, EnablePackageResponseSchema, FindDataRequestSchema, FindDataResponseSchema, FindReferencesToMetaResponseSchema, FlowRegistrationSchema, FlowRegistrationRefusalSchema, GetDataRequestSchema, GetDataResponseSchema, GetDiscoveryRequestSchema, GetDiscoveryResponseSchema, GetEffectivePermissionsRequestSchema, GetEffectivePermissionsResponseSchema, GetFieldLabelsRequestSchema, GetFieldLabelsResponseSchema, GetLocalesRequestSchema, GetLocalesResponseSchema, GetMetaDiagnosticsResponseSchema, GetMetaItemCachedRequestSchema, GetMetaItemCachedResponseSchema, GetMetaItemLayeredRequestSchema, GetMetaItemLayeredResponseSchema, GetMetaItemRequestSchema, GetMetaItemResponseSchema, GetMetaItemsRequestSchema, GetMetaItemsResponseSchema, GetMetaTypesRequestSchema, GetMetaTypesResponseSchema, GetNotificationPreferencesRequestSchema, GetNotificationPreferencesResponseSchema, GetObjectPermissionsRequestSchema, GetObjectPermissionsResponseSchema, GetPackageRequestSchema, GetPackageResponseSchema, GetPresenceRequestSchema, GetPresenceResponseSchema, GetPublishedMetaItemResponseSchema, GetRecordFieldAccessResponseSchema, GetTranslationsRequestSchema, GetTranslationsResponseSchema, GetUiViewRequestSchema, GetUiViewResponseSchema, HistoryMetaItemRequestSchema, HistoryMetaItemResponseSchema, HttpFindQueryParamsSchema, InstallPackageRequestSchema, InstallPackageResponseSchema, ListAiConversationsRequestSchema, ListAiConversationsResponseSchema, ListAiPendingActionsRequestSchema, ListAiPendingActionsResponseSchema, ListDraftsResponseSchema, ListNotificationsRequestSchema, ListNotificationsResponseSchema, ListPackagesRequestSchema, ListPackagesResponseSchema, MarkAllNotificationsReadRequestSchema, MarkAllNotificationsReadResponseSchema, MarkNotificationsReadRequestSchema, MarkNotificationsReadResponseSchema, MetadataAuthoringClientSchema, MetadataAuthoringSurfaceSchema, MetadataConflictErrorSchema, NotificationSchema, NotificationPreferencesSchema, PublicFormSubmitResponseSchema, PublishMetaItemRequestSchema, PublishMetaItemResponseSchema, PublishPackageDraftsRequestSchema, PublishPackageDraftsResponseSchema, RealtimeConnectRequestSchema, RealtimeConnectResponseSchema, RealtimeDisconnectRequestSchema, RealtimeDisconnectResponseSchema, RealtimeSubscribeRequestSchema, RealtimeSubscribeResponseSchema, RealtimeUnsubscribeRequestSchema, RealtimeUnsubscribeResponseSchema, RegisterDeviceRequestSchema, RegisterDeviceResponseSchema, RejectAiPendingActionResponseSchema, RollbackMetaItemRequestSchema, RollbackMetaItemResponseSchema, RuntimeAuthoringIssueSchema, SaveMetaItemRequestSchema, SaveMetaItemResponseSchema, SearchAllHitSchema, SearchAllPageHitSchema, SearchAllResponseSchema, SeedAppliedIdListSchema, SeedAppliedLandedSchema, SetPresenceRequestSchema, SetPresenceResponseSchema, UninstallPackageRequestSchema, UninstallPackageResponseSchema, UnregisterDeviceRequestSchema, UnregisterDeviceResponseSchema, UpdateAiConversationRequestSchema, UpdateDataRequestSchema, UpdateDataResponseSchema, UpdateManyDataRequestSchema, UpdateManyDataResponseSchema, UpdateNotificationPreferencesRequestSchema, UpdateNotificationPreferencesResponseSchema, ValidateDataIssueSchema, ValidateDataRequestSchema, ValidateDataResponseSchema } from '@objectstack/spec/api'; +import type { AiAgentCapabilities, AiAgentChatRequest, AiAgentSummary, AiAgentsResponse, AiChatRequest, AiChatResponse, AiCompleteRequest, AiConversation, AiMessage, AiModelsResponse, AiPendingAction, AiPendingActionStatus, AiStreamChunk, ApproveAiPendingActionResponse, AuditMetaItemRequest, AuditMetaItemResponse, AutomationActionsResponse, AutomationTriggerRequest, AutomationTriggerResponse, BatchDataRequest, BatchDataResponse, CheckPermissionRequest, CheckPermissionResponse, CloneDataResponse, CreateAiConversationRequest, CreateDataRequest, CreateDataResponse, CreateManyDataRequest, CreateManyDataResponse, DeleteDataRequest, DeleteDataResponse, DeleteManyDataRequest, DeleteManyDataResponse, DeleteMetaItemRequest, DeleteMetaItemResponse, DiffMetaItemResponse, DisablePackageRequest, DisablePackageResponse, EnablePackageRequest, EnablePackageResponse, FindDataRequest, FindDataResponse, FindReferencesToMetaResponse, FlowRegistration, FlowRegistrationRefusal, GetDataRequest, GetDataResponse, GetDiscoveryRequest, GetDiscoveryResponse, GetEffectivePermissionsRequest, GetEffectivePermissionsResponse, GetFieldLabelsRequest, GetFieldLabelsResponse, GetLocalesRequest, GetLocalesResponse, GetMetaDiagnosticsResponse, GetMetaItemCachedRequest, GetMetaItemCachedResponse, GetMetaItemLayeredRequest, GetMetaItemLayeredResponse, GetMetaItemRequest, GetMetaItemResponse, GetMetaItemsRequest, GetMetaItemsResponse, GetMetaTypesRequest, GetMetaTypesResponse, GetNotificationPreferencesRequest, GetNotificationPreferencesResponse, GetObjectPermissionsRequest, GetObjectPermissionsResponse, GetPackageRequest, GetPackageResponse, GetPresenceRequest, GetPresenceResponse, GetPublishedMetaItemResponse, GetRecordFieldAccessResponse, GetTranslationsRequest, GetTranslationsResponse, GetUiViewRequest, GetUiViewResponse, HistoryMetaItemRequest, HistoryMetaItemResponse, InstallPackageRequest, InstallPackageResponse, ListAiConversationsRequest, ListAiConversationsResponse, ListAiPendingActionsRequest, ListAiPendingActionsResponse, ListDraftsResponse, ListNotificationsRequest, ListNotificationsResponse, ListPackagesRequest, ListPackagesResponse, MarkAllNotificationsReadRequest, MarkAllNotificationsReadResponse, MarkNotificationsReadRequest, MarkNotificationsReadResponse, MetadataAuthoringClient, MetadataAuthoringSurface, MetadataConflictError, Notification, NotificationPreferences, PublicFormSubmitResponse, PublishMetaItemRequest, PublishMetaItemResponse, PublishPackageDraftsRequest, PublishPackageDraftsResponse, RealtimeConnectRequest, RealtimeConnectResponse, RealtimeDisconnectRequest, RealtimeDisconnectResponse, RealtimeSubscribeRequest, RealtimeSubscribeResponse, RealtimeUnsubscribeRequest, RealtimeUnsubscribeResponse, RegisterDeviceRequest, RegisterDeviceResponse, RejectAiPendingActionResponse, RollbackMetaItemRequest, RollbackMetaItemResponse, RuntimeAuthoringIssue, SaveMetaItemRequest, SaveMetaItemResponse, SearchAllHit, SearchAllPageHit, SearchAllResponse, SeedAppliedIdList, SeedAppliedLanded, SetPresenceRequest, SetPresenceResponse, UninstallPackageRequest, UninstallPackageResponse, UnregisterDeviceRequest, UnregisterDeviceResponse, UpdateAiConversationRequest, UpdateDataRequest, UpdateDataResponse, UpdateManyDataRequest, UpdateManyDataResponse, UpdateNotificationPreferencesRequest, UpdateNotificationPreferencesResponse, ValidateDataIssue, ValidateDataRequest, ValidateDataResponse } from '@objectstack/spec/api'; // Validate data const result = AiAgentCapabilitiesSchema.parse(data); @@ -2050,6 +2050,7 @@ The published metadata item body, opaque by ruling (1C). Shape is the item's own | **sinceSeq** | `number` | optional | Exclusive lower bound on `seq` for pagination: only events with `seq > sinceSeq` are returned. Absent means "from the beginning". | | **limit** | `number` | optional | Maximum events to return, oldest first. Forwarded to the repository unclamped and with NO default — absent means the full remaining change log. (Deliberately no declared bounds: unlike the audit twin's [1, 500] clamp, nothing on this path clamps or refuses, so declaring `.min()`/`.max()` here would refuse values the shipped verb accepts.) | | **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. | +| **packageId** | `string` | optional | Optional package ID (`?package=` on the REST door, the `/layers` spelling) — for a type stored per (package, name), the holder whose versions to address: the slot of the row a read naming the package serves (its own row, its `.custom` pair's declared override, or the package-less row that read falls back to), else the package's own empty slot when it ships the name; a package that neither holds nor ships the name is refused 409 `not-held-by-qualifier` (ADR-0150 D3/D4). Versions attributed to no package, or to the environment, are that slot's only while it is the name's sole slot. Absent, a name two holders hold (in stored rows or in code) is refused 409 naming every holder. Refused with 400 `VALIDATION_ERROR` on a type not stored per (package, name). | --- @@ -2828,6 +2829,22 @@ Answer to a device registration: the device id the client keeps | **id** | `string` | ✅ | The rejected action id | +--- + +## RollbackMetaItemRequest + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **type** | `string` | ✅ | Metadata type name | +| **name** | `string` | ✅ | Item name | +| **toVersion** | `integer` | ✅ | The history version whose body is restored as the new live row: a whole number of at least 1, as the history lists it. The rollback door reads this declaration and refuses anything else `400`. | +| **message** | `string` | optional | Rollback note, recorded on the new history row. | +| **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. | +| **packageId** | `string` | optional | Optional package ID (`?package=` on the REST door, the `/layers` spelling) — for a type stored per (package, name), the holder whose versions to address: the slot of the row a read naming the package serves (its own row, its `.custom` pair's declared override, or the package-less row that read falls back to), else the package's own empty slot when it ships the name; a package that neither holds nor ships the name is refused 409 `not-held-by-qualifier` (ADR-0150 D3/D4). Versions attributed to no package, or to the environment, are that slot's only while it is the name's sole slot. Absent, a name two holders hold (in stored rows or in code) is refused 409 naming every holder. Refused with 400 `VALIDATION_ERROR` on a type not stored per (package, name). | + + --- ## RollbackMetaItemResponse diff --git a/packages/spec/authorable-surface/api.json b/packages/spec/authorable-surface/api.json index c7b9470aa7d..5f43ca93e09 100644 --- a/packages/spec/authorable-surface/api.json +++ b/packages/spec/authorable-surface/api.json @@ -917,6 +917,7 @@ "api/HistoryMetaItemRequest:limit", "api/HistoryMetaItemRequest:member", "api/HistoryMetaItemRequest:name", + "api/HistoryMetaItemRequest:packageId", "api/HistoryMetaItemRequest:sinceSeq", "api/HistoryMetaItemRequest:type", "api/HistoryMetaItemResponse:events", @@ -1705,6 +1706,12 @@ "api/RevertPackageCommitResponse:reverted", "api/RevertPackageCommitResponse:revertedCount", "api/RevertPackageCommitResponse:success", + "api/RollbackMetaItemRequest:member", + "api/RollbackMetaItemRequest:message", + "api/RollbackMetaItemRequest:name", + "api/RollbackMetaItemRequest:packageId", + "api/RollbackMetaItemRequest:toVersion", + "api/RollbackMetaItemRequest:type", "api/RollbackMetaItemResponse:advisories", "api/RollbackMetaItemResponse:message", "api/RollbackMetaItemResponse:restoredFromVersion",