From 48cd3c9ddcadbe8e5d92f6956d7e13b4ae08188d Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 00:20:56 +0000 Subject: [PATCH] fix(plugin-audit): a milestone row written before its template gained a token reads its stored sentence A fired milestone's summary code now stores every {token} name its template held. A reader composes the translated template only when each token it names has the row's stored value or was in the template and empty; otherwise the row keeps its stored sentence, which has no hole. Also: one exported {token} pattern (milestoneTokenRe) shared by the writer and the reader; a read answers each milestone once and reads each object's packaged base once; two stale doc comments (i18n-resolver's scalarOverridesPackagedBase, the audit-option-label-summary test header). Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L6bhgUpnvPnJ1hR74pUrVj --- .../37635-milestone-summary-token-names.md | 13 +++ ...lestone-summary-locale.integration.test.ts | 13 +++ .../src/activity-summary-message.test.ts | 54 +++++++++- .../src/activity-summary-message.ts | 99 +++++++++++++++---- .../src/audit-option-label-summary.test.ts | 11 ++- .../plugins/plugin-audit/src/audit-writers.ts | 16 +-- packages/spec/src/system/i18n-resolver.ts | 9 +- 7 files changed, 175 insertions(+), 40 deletions(-) create mode 100644 .changeset/37635-milestone-summary-token-names.md diff --git a/.changeset/37635-milestone-summary-token-names.md b/.changeset/37635-milestone-summary-token-names.md new file mode 100644 index 00000000000..0065da07e99 --- /dev/null +++ b/.changeset/37635-milestone-summary-token-names.md @@ -0,0 +1,13 @@ +--- +'@objectstack/plugin-audit': patch +'@objectstack/spec': patch +--- + +fix(plugin-audit): a milestone row written before its template gained a token reads its stored sentence, not a translation with a hole + +Clause-②: no +Metadata-protocol: none + +A fired milestone's activity row now also stores the names of every `{token}` its template held (`names` in the row's summary code). A reader whose language translates the milestone composes the translation only when each token it names either has the row's stored value or was in the template and empty; a token the app added to the template after the row was written, or one only the translation names, leaves the row's stored sentence in place, which has no hole. A row written before this change carries no names, so it composes only when every token of the translation has a stored value. + +Also: the `{token}` pattern has one exported definition (`milestoneTokenRe`, `activity-summary-message.ts`) that the writer and the reader share; a read answers each milestone's translation once and reads each object's packaged base once, instead of once per row; and two `@objectstack/spec` doc comments on `scalarOverridesPackagedBase` now name the five scalars it is asked about. diff --git a/packages/plugins/plugin-audit/src/activity-milestone-summary-locale.integration.test.ts b/packages/plugins/plugin-audit/src/activity-milestone-summary-locale.integration.test.ts index afc5896b450..2355f5d0c4d 100644 --- a/packages/plugins/plugin-audit/src/activity-milestone-summary-locale.integration.test.ts +++ b/packages/plugins/plugin-audit/src/activity-milestone-summary-locale.integration.test.ts @@ -156,6 +156,7 @@ describe('activity milestone summary — rendered in the reader\'s language (#37 field: 'stage', value: 'won', tokens: { name: { text: 'Acme' }, stage: { text: 'Won', option: 'won' } }, + names: ['name', 'stage'], }); const served = await rowOf('won', reader('zh-CN')); expect(JSON.parse(served!.metadata)).not.toHaveProperty('summary_message'); @@ -167,4 +168,16 @@ describe('activity milestone summary — rendered in the reader\'s language (#37 expect(hidden).toBeDefined(); expect(hidden).not.toHaveProperty('summary'); }); + + // Last: it changes the app's pack for the rest of the file. + it('[#37635] a row written before its template gained a token reads its stored sentence, not a hole', async () => { + // The app adds `{note}` to the won milestone, with its translation. The + // won row was written before: it holds no value for `note`. + kernel.getService('i18n').loadTranslations('zh-CN', { + objects: { [DEAL]: { _milestones: { stage: { won: { summary: '商机赢单:{name}({stage}),备注:{note}' } } } } }, + }); + expect((await rowOf('won', reader('zh-CN')))?.summary).toBe('Deal won: Acme (Won)'); + // CONTROL: the lost row's template held `{note}` when it was written, so it still composes. + expect((await rowOf('lost', reader('zh-CN')))?.summary).toBe('商机输单:Acme,budget cut'); + }); }); diff --git a/packages/plugins/plugin-audit/src/activity-summary-message.test.ts b/packages/plugins/plugin-audit/src/activity-summary-message.test.ts index bd310d2e095..deb243b5ae4 100644 --- a/packages/plugins/plugin-audit/src/activity-summary-message.test.ts +++ b/packages/plugins/plugin-audit/src/activity-summary-message.test.ts @@ -389,18 +389,58 @@ describe('composeActivitySummary — a fired milestone (#37524)', () => { field: 'stage', value: 'won', tokens: { name: { text: 'Acme' }, stage: { text: 'Won', option: 'won' } }, + names: ['name', 'stage'], }; - function milestoneI18n() { + function milestoneI18n(summary = '赢单:{name}({stage})') { const i18n = makeI18n(); i18n.loadTranslations('zh-CN', { - objects: { biz_deal: { _milestones: { stage: { won: { summary: '赢单:{name}({stage}){extra}' } } } } }, + objects: { biz_deal: { _milestones: { stage: { won: { summary } } } } }, }); return i18n; } + const zhLocale = (summary?: string) => + readerSummaryLocale(milestoneI18n(summary), 'zh-CN', (n) => MILESTONE_DEFS[n] ?? null)!; - it('composes the translated template, a select token by the reader\'s option label, an unstored token empty', () => { - const locale = readerSummaryLocale(milestoneI18n(), 'zh-CN', (n) => MILESTONE_DEFS[n] ?? null)!; - expect(composeActivitySummary(WON, locale)).toBe('赢单:Acme(赢单)'); + it('composes the translated template, a select token by the reader\'s option label', () => { + expect(composeActivitySummary(WON, zhLocale())).toBe('赢单:Acme(赢单)'); + }); + + it('[#37635] a token the fired template held whose value was empty renders empty, as in the stored sentence', () => { + // Written from `Deal won: {name} ({stage}) {note}` with `note` empty: the + // stored sentence has an empty there too, so the translation may. + const emptyNote: ActivitySummaryMessage = { ...WON, names: ['name', 'stage', 'note'] }; + expect(composeActivitySummary(emptyNote, zhLocale('赢单:{name}({stage}){note}'))).toBe('赢单:Acme(赢单)'); + }); + + it('[#37635] red first: a token the template gained after the row was written keeps the stored sentence', () => { + // The app added `{note}` to the template (and its translation) after this + // row was written from `Deal won: {name} ({stage})`: the row has no value + // for it, and its stored sentence is whole, so the reader reads that. + expect(composeActivitySummary(WON, zhLocale('赢单:{name}({stage}),备注:{note}'))).toBeUndefined(); + }); + + it('[#37635] a token only the translation names keeps the stored sentence', () => { + expect(composeActivitySummary(WON, zhLocale('赢单:{name}({stage}){extra}'))).toBeUndefined(); + }); + + it('[#37635] a row written before token names were stored composes only when every token has a value', () => { + const { names: _names, ...legacy } = WON; + expect(composeActivitySummary(legacy as ActivitySummaryMessage, zhLocale())).toBe('赢单:Acme(赢单)'); + expect(composeActivitySummary(legacy as ActivitySummaryMessage, zhLocale('赢单:{name}({stage}){note}'))).toBeUndefined(); + }); + + it('[#37635] answers each milestone once per read: one packaged-base read per object for many rows', () => { + let packagedReads = 0; + const packaged = (n: string) => { + packagedReads += 1; + return MILESTONE_DEFS[n]; + }; + const locale = readerSummaryLocale(milestoneI18n(), 'zh-CN', (n) => MILESTONE_DEFS[n] ?? null, packaged)!; + for (let i = 0; i < 5; i++) expect(composeActivitySummary(WON, locale)).toBe('赢单:Acme(赢单)'); + expect(packagedReads).toBe(1); + // A different milestone of the same object is its own answer, from the same base. + expect(composeActivitySummary({ ...WON, value: 'lost' }, locale)).toBeUndefined(); + expect(packagedReads).toBe(1); }); it('composes nothing — the stored sentence stands — for a locale with no entry, and on the writer\'s locale', () => { @@ -428,5 +468,9 @@ describe('composeActivitySummary — a fired milestone (#37524)', () => { expect(readActivitySummaryMessage(WON)).toEqual(WON); expect(readActivitySummaryMessage({ ...WON, tokens: { name: 'Acme' } })).toBeNull(); expect(readActivitySummaryMessage({ ...WON, value: 1 })).toBeNull(); + expect(readActivitySummaryMessage({ ...WON, names: 'name' })).toBeNull(); + expect(readActivitySummaryMessage({ ...WON, names: ['name', 1] })).toBeNull(); + const { names: _names, ...legacy } = WON; + expect(readActivitySummaryMessage(legacy)).toEqual(legacy); }); }); diff --git a/packages/plugins/plugin-audit/src/activity-summary-message.ts b/packages/plugins/plugin-audit/src/activity-summary-message.ts index 3f889aad30e..e2dd03e8b7b 100644 --- a/packages/plugins/plugin-audit/src/activity-summary-message.ts +++ b/packages/plugins/plugin-audit/src/activity-summary-message.ts @@ -141,6 +141,18 @@ export type ActivitySummaryMessage = value: string; /** Each `{token}` the authored template interpolated, by token name. */ tokens: Record; + /** + * [#37635] Every `{token}` name the fired template held when the row was + * written, interpolated or not ({@link milestoneTokenNames}). It is what + * tells a token whose value was empty (listed, no entry in `tokens`) + * from one the template gained after the row was written (not listed), + * which this row has no value for: a translation naming such a token + * cannot be composed whole, so the row keeps its stored sentence. A row + * written before #37635 carries no list, so no token missing from + * `tokens` can be told empty, and it keeps its stored sentence whenever + * its translation names one. + */ + names?: string[]; }; /** One language a summary is composed in. */ @@ -164,6 +176,24 @@ export interface ActivitySummaryLocale { milestoneSummary?(objectName: string, field: string, value: string): string | undefined; } +/** + * [#7290] The `{token}` pattern of an `activityMilestones` summary template — + * the ONE definition: the writer plans its reads and renders the stored + * sentence with it, and a reader composes a translated template with it. + * + * A FRESH instance per call, deliberately: a module-level `/g` regex carries + * `lastIndex` between callers, and a fired milestone reads this more than + * once. One definition, no shared cursor. + */ +export function milestoneTokenRe(): RegExp { + return /\{(\w+)\}/g; +} + +/** [#37635] The distinct `{token}` names of `template`, in the order they first appear. */ +export function milestoneTokenNames(template: string): string[] { + return [...new Set(Array.from(template.matchAll(milestoneTokenRe()), (match) => match[1]))]; +} + /** Interpolate one `{{param}}` template, the shared convention (`createMemoryI18n`, FileI18nAdapter). */ function interpolate(template: string, params: Record = {}): string { return template.replace(/\{\{(\w+)\}\}/g, (_, name: string) => String(params[name] ?? `{{${name}}}`)); @@ -295,14 +325,23 @@ export function composeActivitySummary( const template = locale.milestoneSummary?.(message.object, message.field, message.value); if (template === undefined) return undefined; const fields = locale.getObjectDef(message.object)?.fields; - // The authored template's tokens are the ones with a stored value; a - // token the translation adds, or one whose value was empty, renders - // empty, as an empty value does in the authored sentence. - return template.replace(/\{(\w+)\}/g, (_match: string, token: string) => { + // The tokens with a stored value render it. A token the fired template + // held whose value was empty renders empty, as it does in the stored + // sentence. [#37635] Any other token (one the template gained after + // the row was written, or one only the translation names) has no value + // this row could give it, so the row keeps its stored sentence rather + // than show a hole where that sentence has none. + const written = new Set(message.names ?? []); + let whole = true; + const text = template.replace(milestoneTokenRe(), (_match: string, token: string) => { const value = Object.prototype.hasOwnProperty.call(message.tokens, token) ? message.tokens[token] : undefined; - if (!value) return ''; + if (!value) { + if (!written.has(token)) whole = false; + return ''; + } return value.option !== undefined ? (optionLabelOn(fields?.[token], value.option) ?? value.text) : value.text; }); + return whole ? text : undefined; } } } @@ -336,7 +375,8 @@ export function readActivitySummaryMessage(value: unknown): ActivitySummaryMessa return typeof value.field === 'string' && typeof value.value === 'string' && isRecord(tokens) && - Object.values(tokens).every(isValue) + Object.values(tokens).every(isValue) && + (value.names === undefined || isStringList(value.names)) ? (value as ActivitySummaryMessage) : null; } @@ -450,6 +490,17 @@ export function readerSummaryLocale( const locale = negotiatedLocale(service, requested); let translation: { value: ReturnType } | undefined; const definitions = new Map(); + // [#37635] One answer per milestone for the read: a feed page holds many + // rows of the same milestone, and each answer walks the authored and the + // packaged definitions. + const milestoneTemplates = new Map(); + // The packaged base, read once per object for the read: the translated + // definition and every milestone answer ask it. + const packagedBases = new Map(); + const packagedBaseOf = (objectName: string): unknown => { + if (!packagedBases.has(objectName)) packagedBases.set(objectName, getPackagedObjectBase?.(objectName)); + return packagedBases.get(objectName); + }; const translatedObjectDef = (objectName: string): any => { if (definitions.has(objectName)) return definitions.get(objectName); const def = getObjectDef(objectName); @@ -458,7 +509,7 @@ export function readerSummaryLocale( try { translation ??= { value: labelTranslationOf(service, locale) }; if (translation.value) { - const packagedBase = getPackagedObjectBase?.(objectName); + const packagedBase = packagedBaseOf(objectName); served = translateObject({ ...def, name: objectName }, translation.value.bundle, { ...translation.value.options, ...(packagedBase && typeof packagedBase === 'object' ? { packagedBase } : {}), @@ -485,21 +536,35 @@ export function readerSummaryLocale( locale, getObjectDef: translatedObjectDef, milestoneSummary: (objectName, field, value) => { + // NUL cannot occur in an object, field or value name, so the key is unambiguous. + const cacheKey = `${objectName}\u0000${field}\u0000${value}`; + if (milestoneTemplates.has(cacheKey)) return milestoneTemplates.get(cacheKey); + let template: string | undefined; try { translation ??= { value: labelTranslationOf(service, locale) }; - if (!translation.value) return undefined; - // ADR-0029 D9.2a: a tenant's rewording of a packaged milestone is - // authored data and keeps its words, judged as a validation message - // is — the served milestone against the packaged one of the same pair, - // through the resolver's one predicate (never a copy of it). - const served = milestoneOn(getObjectDef(objectName), field, value); - const packaged = milestoneOn(getPackagedObjectBase?.(objectName), field, value); - if (scalarOverridesPackagedBase(packaged, 'summary', served?.summary)) return undefined; - return resolveObjectMilestoneSummary(translation.value.bundle, objectName, field, value, translation.value.options); + if (translation.value) { + // ADR-0029 D9.2a: a tenant's rewording of a packaged milestone is + // authored data and keeps its words, judged as a validation message + // is — the served milestone against the packaged one of the same pair, + // through the resolver's one predicate (never a copy of it). + const served = milestoneOn(getObjectDef(objectName), field, value); + const packaged = milestoneOn(packagedBaseOf(objectName), field, value); + if (!scalarOverridesPackagedBase(packaged, 'summary', served?.summary)) { + template = resolveObjectMilestoneSummary( + translation.value.bundle, + objectName, + field, + value, + translation.value.options, + ); + } + } } catch { // A misbehaving i18n service must not fail the read: the stored text stands. - return undefined; + template = undefined; } + milestoneTemplates.set(cacheKey, template); + return template; }, }; } diff --git a/packages/plugins/plugin-audit/src/audit-option-label-summary.test.ts b/packages/plugins/plugin-audit/src/audit-option-label-summary.test.ts index 9eceb9efa74..655f80d7ec2 100644 --- a/packages/plugins/plugin-audit/src/audit-option-label-summary.test.ts +++ b/packages/plugins/plugin-audit/src/audit-option-label-summary.test.ts @@ -25,10 +25,13 @@ * fully localized — verb template, object label, and since #7230 the field * label. The authored option value was the one untranslated token left in * it, so translating it makes the string uniformly localized. **Localized.** - * - `renderMilestoneSummary` (#7290) interpolates tokens into an author-written - * sentence that has no bundle key and is deliberately NOT translated (#7290 - * called that a contract decision and left it). #7290's own change — a - * reference id → the record's title — is locale-INDEPENDENT data, the same + * - `renderMilestoneSummary` (#7290) interpolates tokens into the author-written + * sentence the row STORES. #7290 left that sentence untranslated as a + * contract decision; since #37524 a reader whose language translates the + * milestone (`objects.._milestones...summary`) reads it + * composed from the row's code instead, and the stored sentence itself is + * still rendered untranslated, which is what this file pins. #7290's own + * change — a reference id → the record's title — is locale-INDEPENDENT data, the same * string in every locale, which is why it could be added to an untranslated * sentence. An option label is locale-DEPENDENT rendering: reading the bundle * there would guarantee a split sentence (`Deal moved to 已赢单`) in exactly diff --git a/packages/plugins/plugin-audit/src/audit-writers.ts b/packages/plugins/plugin-audit/src/audit-writers.ts index ee4d7151cff..77b09fde069 100644 --- a/packages/plugins/plugin-audit/src/audit-writers.ts +++ b/packages/plugins/plugin-audit/src/audit-writers.ts @@ -116,6 +116,8 @@ import { ACTIVITY_SUMMARY_MESSAGE_KEY, composeStoredSummary, englishBooleanWord, + milestoneTokenNames, + milestoneTokenRe, withEnglishMessages, type ActivitySummaryFieldChange, type ActivitySummaryLocale, @@ -1242,17 +1244,6 @@ function renderChangedFieldsSummary( return null; } -/** - * [#7290] The `{token}` pattern of an `activityMilestones` summary template. - * - * A FRESH instance per call, deliberately: a module-level `/g` regex carries - * `lastIndex` between callers, and this one is read twice per fired milestone - * (once to plan the reads, once to render). One definition, no shared cursor. - */ -function milestoneTokenRe(): RegExp { - return /\{(\w+)\}/g; -} - /** * ADR-0052 §5b.2 — declarative semantic milestones. If a watched field * transitioned INTO a configured `value` on this update (before ≠ value, after = @@ -2705,6 +2696,9 @@ export function installAuditWriters( field: milestone.field, value: milestone.value, tokens: rendered.tokens, + // [#37635] Every token the fired template held, so a reader can tell + // an empty one from one the template gains later. + names: milestoneTokenNames(milestone.template), }; if (milestone.type) activityType = milestone.type; // [#22771] `type` stays what the declaration names; the row says it is diff --git a/packages/spec/src/system/i18n-resolver.ts b/packages/spec/src/system/i18n-resolver.ts index d89c099ed14..088d9e77ac7 100644 --- a/packages/spec/src/system/i18n-resolver.ts +++ b/packages/spec/src/system/i18n-resolver.ts @@ -4937,8 +4937,10 @@ function builtinSystemFieldLabel( } /** - * [#8284] Whether one of an object document's three scalars has been - * EXPLICITLY set — i.e. it no longer carries the value the package shipped. + * [#8284] Whether a document scalar has been EXPLICITLY set — i.e. it no + * longer carries the value the package shipped. The scalars asked about are an + * object's three (`label`, `pluralLabel`, `description`), a validation rule's + * `message` and an activity milestone's `summary` (each section below). * * This is comparison-based provenance, and it is the whole mechanism: no flag * is carried through the fold, nothing is stamped on the document, and the @@ -5004,7 +5006,8 @@ export function scalarOverridesPackagedBase( /** * [#20680] The ONE comparison behind {@link scalarOverridesPackagedBase}, * keyed by any attribute name — the exported predicate's key union names the - * object scalars its two callers ask about, and the dashboard translator + * scalars its callers ask about (an object's three, a validation rule's + * `message`, an activity milestone's `summary`), and the dashboard translator * ({@link translateDashboard}) asks the same question of `title`, which that * union does not carry; the view translator ({@link translateView}, #20731) * asks it of a bulk-action def's `confirmText`, its params' `help`, a form