From 93f72d6727af2dfbcc6faba8cdce3fdf6d97b34f Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 08:48:57 +0000 Subject: [PATCH 1/9] =?UTF-8?q?wip(audit):=20old=20=E2=86=92=20new=20value?= =?UTF-8?q?s=20show=20unless=20the=20object=20or=20field=20turns=20them=20?= =?UTF-8?q?off=20(#36290)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Claude-Session: https://claude.ai/code/session_01QsR2jRCdMrPNTumXfsr1mw Co-authored-by: Claude --- .../src/activity-field-redaction.test.ts | 63 ++++++++- .../src/activity-field-redaction.ts | 88 ++++++++++++- .../src/activity-summary-message.ts | 23 +++- .../plugins/plugin-audit/src/audit-plugin.ts | 12 +- .../plugin-audit/src/audit-writers.test.ts | 113 ++++++++++++++++ .../plugins/plugin-audit/src/audit-writers.ts | 124 ++++++++++++++++-- packages/spec/src/data/field.form.ts | 2 +- packages/spec/src/data/field.zod.ts | 2 +- packages/spec/src/data/object.form.ts | 2 +- packages/spec/src/data/object.test.ts | 6 +- packages/spec/src/data/object.zod.ts | 33 +++-- 11 files changed, 425 insertions(+), 43 deletions(-) diff --git a/packages/plugins/plugin-audit/src/activity-field-redaction.test.ts b/packages/plugins/plugin-audit/src/activity-field-redaction.test.ts index d3bf84e5b9f..3915315ae9b 100644 --- a/packages/plugins/plugin-audit/src/activity-field-redaction.test.ts +++ b/packages/plugins/plugin-audit/src/activity-field-redaction.test.ts @@ -235,9 +235,13 @@ describe('[#21081] sys_activity value-bearing columns are served through the sec expect(blob).not.toContain(V.masked2); }); - it('masked: a summary composed from that field is dropped, and one composed from served fields is kept', async () => { + it('masked: a milestone composed from that field is dropped, a field-change summary keeps only the served changes, and one composed from served fields is kept', async () => { const rows = byChange(await read(MASKED_READER)); - expect(rows.allTracked).not.toHaveProperty('summary'); + // [#36290] Re-composed from the changes this reader is served, never dropped whole. + expect(String(rows.allTracked?.summary)).toContain(V.open2); + expect(String(rows.allTracked?.summary)).toContain(V.unserved2); + expect(String(rows.allTracked?.summary)).not.toContain(V.masked2); + expect(String(rows.allTracked?.summary)).not.toContain('Masked'); expect(rows.milestone).not.toHaveProperty('summary'); expect(String(rows.openOnly?.summary)).toContain(V.open3); expect(String(rows.created?.summary)).toContain('item'); @@ -254,6 +258,49 @@ describe('[#21081] sys_activity value-bearing columns are served through the sec expect(tracked.new).toHaveProperty('f_open', V.open2); }); + // ── [#36290] the field-change code, served narrowed change by change ──── + + /** The served field-change code of a row, or `undefined`. */ + const codeOf = (row: Row | undefined) => + typeof row?.metadata === 'string' ? JSON.parse(row.metadata).summary_message : undefined; + + it('[#36290] at rest the field-change code names every changed field, with both values', async () => { + const code = codeOf(byChange(await read(SYS)).allTracked); + expect(code?.key).toBe('fieldChanges'); + expect(code.changes.map((c: Row) => c.field)).toEqual(['f_masked', 'f_unserved', 'f_open']); + expect(JSON.stringify(code)).toContain(V.masked2); + expect(JSON.stringify(code)).toContain(V.unserved2); + }); + + it('[#36290] masked: the code is served without the change of the field served masked', async () => { + const code = codeOf(byChange(await read(MASKED_READER)).allTracked); + expect(code?.key).toBe('fieldChanges'); + expect(code.changes.map((c: Row) => c.field)).toEqual(['f_unserved', 'f_open']); + expect(JSON.stringify(code)).not.toContain(V.masked1); + expect(JSON.stringify(code)).not.toContain(V.masked2); + }); + + it('[#36290] not served: the code and the summary are served without the change of the field not served', async () => { + const row = byChange(await read(UNSERVED_READER)).allTracked; + const code = codeOf(row); + expect(code.changes.map((c: Row) => c.field)).toEqual(['f_masked', 'f_open']); + expect(JSON.stringify(code)).not.toContain(V.unserved2); + expect(String(row?.summary)).toContain(V.masked2); + expect(String(row?.summary)).not.toContain(V.unserved2); + expect(String(row?.summary)).not.toContain('Unserved'); + }); + + it('[#36290] control: a reader served every field is served the whole code', async () => { + const code = codeOf(byChange(await read(CONTROL)).allTracked); + expect(code.changes.map((c: Row) => c.field)).toEqual(['f_masked', 'f_unserved', 'f_open']); + }); + + it('[#36290] a code other than a field-change code is still never served to a reader', async () => { + const rows = byChange(await read(CONTROL)); + expect(codeOf(rows.created)).toBeUndefined(); + expect(codeOf(byChange(await read(SYS)).created)?.key).toBe('activityCreated'); + }); + // ── a field not served ────────────────────────────────────────────────── it('not served: no row served to the reader carries a value of a field it may not read', async () => { @@ -433,7 +480,9 @@ const refObjects = [ fields: { title: { name: 'title', label: 'Title', type: 'text' as const } }, }, { - name: REF_TITLED, label: 'Reference Titled', nameField: 'target', + // [#36290] Values off, so its update is summarized by the record label — + // the text this scene judges — not by a field change. + name: REF_TITLED, label: 'Reference Titled', nameField: 'target', enable: { trackHistory: false }, fields: { name: { name: 'name', label: 'Name', type: 'text' as const }, target: refLookup(REF_TARGET) }, }, { @@ -623,8 +672,14 @@ describe('an activity text naming a referenced record by its title is served onl expect(String(control?.summary)).toContain(ids.unexposed); const withheld = await updatedAs(TITLE_WITHHELD); expect(withheld).toBeTruthy(); - expect(withheld).not.toHaveProperty('summary'); + // [#36290] Judged change by change: the change naming the exposed + // target's title is dropped, the one naming the unexposed target by its id + // (whose title field this reader IS served) is kept. + expect(String(withheld?.summary)).toContain(ids.unexposed); + expect(String(withheld?.summary)).not.toContain('Open'); expect(JSON.stringify(withheld)).not.toContain(T.one); + const code = JSON.parse(String(withheld?.metadata)).summary_message; + expect(code.changes.map((c: Row) => c.field)).toEqual(['hidden']); }); it('findOne: the by-id read is judged like the list', async () => { diff --git a/packages/plugins/plugin-audit/src/activity-field-redaction.ts b/packages/plugins/plugin-audit/src/activity-field-redaction.ts index 7441f1d1c3a..31edeea8b8b 100644 --- a/packages/plugins/plugin-audit/src/activity-field-redaction.ts +++ b/packages/plugins/plugin-audit/src/activity-field-redaction.ts @@ -40,6 +40,12 @@ * * - `metadata.old` / `metadata.new`: every key the reader is not served is * DROPPED, key by key — the approval snapshot's shape. + * - [#36290] `metadata.summary_message` of a field-change summary: every + * change of a field the reader is not served is DROPPED, change by change, + * by the same answer, and a reference field's change by the reference rule + * below; the summary is then re-composed from the changes kept instead of + * being dropped whole, so a reader reads the lines of the fields they may + * read and never a value of one they may not. * - `summary` / `record_label`: a text cannot be split back into fields, so * each one is served whole or DROPPED whole. The writer declares, in the * row's own `metadata`, which parent fields each was composed from @@ -223,6 +229,14 @@ import { */ export { resolveServedFields } from './served-fields.js'; import { omitSideCopyFromCopy, sideCopyColumnsOf } from './side-copy-columns.js'; +import { + ACTIVITY_SUMMARY_MESSAGE_KEY, + composeActivitySummary, + readActivitySummaryMessage, + type ActivitySummaryFieldChange, + type ActivitySummaryLocale, + type ActivitySummaryMessage, +} from './activity-summary-message.js'; const ACTIVITY_OBJECT = 'sys_activity'; const SYSTEM_CTX = { isSystem: true } as const; @@ -679,6 +693,10 @@ export async function redactActivityRows( * the middleware always hands it in; without it no source is judged as a * reference. */ referenceTitles?: ReferenceTitlesServedFor, + /** [#36290] The registered definition of a parent object, for the field + * labels a narrowed field-change summary is re-composed with; without it + * the summary names each field by its machine key. */ + getObjectDef?: (object: string) => unknown, ): Promise { const list = (Array.isArray(rows) ? rows : rows ? [rows] : []) as unknown[]; if (list.length === 0) return; @@ -733,12 +751,47 @@ export async function redactActivityRows( const servedWhole = (sources: string[] | 'unknown') => sourcesServed(sources, servedSet, () => restrictedOn(object, servedSet)); + /** [#36290] The field-change code, narrowed to this reader; `null` when the row has none to serve. */ + let narrowedChanges: Extract | null = null; if (metadata) { let changed = false; for (const side of ['old', 'new'] as const) { const snapshot = metadata[side]; if (isRecord(snapshot) && dropUnservedKeys(snapshot, servedSet)) changed = true; } + // [#36290, ruling 7076513167] The field-change code is served to a + // reader narrowed change by change, by the answer `old` / `new` are + // narrowed by: a change of a field this reader is not served is dropped, + // and a reference field's change is kept only for a reader served the + // referenced record's title ({@link referenceTitlesPerRead}), the rule + // the summary text is judged by. A code this version cannot read is + // dropped (fail closed). Every other code is left to the summary + // middleware, which strips it for every non-system reader. + if (ACTIVITY_SUMMARY_MESSAGE_KEY in metadata) { + const stored = metadata[ACTIVITY_SUMMARY_MESSAGE_KEY]; + const code = readActivitySummaryMessage(stored); + if (isRecord(stored) && stored.key === 'fieldChanges' && code?.key !== 'fieldChanges') { + delete metadata[ACTIVITY_SUMMARY_MESSAGE_KEY]; + changed = true; + } else if (code?.key === 'fieldChanges') { + const kept: ActivitySummaryFieldChange[] = []; + for (const change of code.changes) { + if (!servedSet.has(change.field)) continue; + if (referenceTitles && !(await referenceTitles(object, [change.field]))) continue; + kept.push(change); + } + if (kept.length === 0) { + delete metadata[ACTIVITY_SUMMARY_MESSAGE_KEY]; + changed = true; + } else { + narrowedChanges = { ...code, changes: kept }; + if (kept.length !== code.changes.length) { + metadata[ACTIVITY_SUMMARY_MESSAGE_KEY] = narrowedChanges; + changed = true; + } + } + } + } if (kindSources !== null && !(await servedWhole(kindSources))) { delete metadata[ACTIVITY_KIND_KEY]; changed = true; @@ -756,11 +809,40 @@ export async function redactActivityRows( const sources = provenance[col]; const served = (await servedWhole(sources)) && (!referenceTitles || sources === 'unknown' || (await referenceTitles(object, sources))); - if (!served) delete row[col]; + if (served) continue; + // [#36290] A field-change summary is not dropped whole when some of its + // changes are this reader's: it is re-composed from the narrowed code, + // so the reader reads the lines of the fields they may read. The text is + // composed from the served changes alone; the summary middleware then + // re-composes it in the reader's language from the same code. + if (col === 'summary' && narrowedChanges) { + row.summary = composeActivitySummary(narrowedChanges, authoredLabelsLocale(getObjectDef)) ?? ''; + continue; + } + delete row[col]; } } } +/** + * [#36290] The locale a narrowed field-change summary is composed in on this + * seam: no bundle (every key misses), so each field is named by its authored + * label, else its machine key, and each value by the text the writer stored. + */ +function authoredLabelsLocale(getObjectDef?: (object: string) => unknown): ActivitySummaryLocale { + return { + translate: () => undefined, + locale: undefined, + getObjectDef: (object) => { + try { + return getObjectDef?.(object) ?? null; + } catch { + return null; + } + }, + }; +} + /** * The text columns' provenance lives in `metadata`, and the parent in * `object_name`; a projection that names a value-bearing column without them @@ -816,7 +898,9 @@ export function installActivityFieldRedaction( servedFor, logger, ); - await redactActivityRows(list, security, ctx.context, logger, servedFor, restrictedFor, referenceTitles); + await redactActivityRows(list, security, ctx.context, logger, servedFor, restrictedFor, referenceTitles, (object) => + typeof engine.getSchema === 'function' ? engine.getSchema(object) : undefined, + ); } catch (err) { // A redaction failure must never fall open into a leak. logger.warn( diff --git a/packages/plugins/plugin-audit/src/activity-summary-message.ts b/packages/plugins/plugin-audit/src/activity-summary-message.ts index 18770b7a4fb..650bab5ec85 100644 --- a/packages/plugins/plugin-audit/src/activity-summary-message.ts +++ b/packages/plugins/plugin-audit/src/activity-summary-message.ts @@ -347,6 +347,12 @@ function parseMetadata(raw: unknown): Record | null { * `metadata`: its parameters are parent field values (the record label, a * changed value), and the field redaction judges the text columns, not this * slot. A row whose `summary` the projection did not ask for is not given one. + * + * [#36290] One code is served: a field-change code (`fieldChanges`), which the + * field redaction has already narrowed change by change for this reader + * (`activity-field-redaction.ts`), so the record page can draw one line per + * changed field. This middleware is registered OUTSIDE the redaction for that + * reason: it composes from the narrowed code, never from the stored one. */ export function localizeActivityRow( row: Record, @@ -366,12 +372,17 @@ export function localizeActivityRow( } } } - if (stripCode) { + if (stripCode && !isFieldChangeCode(metadata[ACTIVITY_SUMMARY_MESSAGE_KEY])) { delete metadata[ACTIVITY_SUMMARY_MESSAGE_KEY]; row.metadata = isRecord(row.metadata) ? metadata : JSON.stringify(metadata); } } +/** [#36290] A code this version reads as a field-change summary — the one code served to a reader. */ +function isFieldChangeCode(value: unknown): boolean { + return readActivitySummaryMessage(value)?.key === 'fieldChanges'; +} + /** The engine slice the summary middleware registers on. */ export interface ActivitySummaryEngine { registerMiddleware?( @@ -383,10 +394,12 @@ export interface ActivitySummaryEngine { /** * Install the `sys_activity` summary middleware. `getI18n` is resolved on every - * read: the i18n service may register after this plugin. Register it AFTER the - * field redaction (`installActivityFieldRedaction`), so it runs inside it: the - * summary is composed from the row as stored, and the redaction then judges - * the composed text by the same declared sources the stored one had. + * read: the i18n service may register after this plugin. Register it BEFORE the + * field redaction (`installActivityFieldRedaction`), so the redaction runs + * inside it [#36290]: the redaction judges the stored text by its declared + * sources and narrows the field-change code first, and this middleware then + * composes a kept summary in the reader's language from what the redaction + * left — a narrowed code composes only the changes this reader is served. */ export function installActivitySummaryLocale( engine: ActivitySummaryEngine, diff --git a/packages/plugins/plugin-audit/src/audit-plugin.ts b/packages/plugins/plugin-audit/src/audit-plugin.ts index 6f043bfbbb0..42527cdbeef 100644 --- a/packages/plugins/plugin-audit/src/audit-plugin.ts +++ b/packages/plugins/plugin-audit/src/audit-plugin.ts @@ -840,14 +840,16 @@ export class AuditPlugin implements Plugin { return undefined; } }; - installActivityFieldRedaction(engine as any, getSecurity, ctx.logger); - ctx.logger.info('AuditPlugin: sys_activity field redaction installed'); // [#26167] …and each kept row's summary is composed in the READER's - // language from the code the writer stored beside it. Registered after - // the redaction, so it runs inside it: the redaction judges the - // composed text by the same declared sources as the stored one. + // language from the code the writer stored beside it. [#36290] + // Registered BEFORE the redaction, so the redaction runs inside it: the + // redaction judges the stored text by its declared sources and narrows + // the field-change code to this reader first, and the summary is then + // composed from what it kept. installActivitySummaryLocale(engine as any, getI18n); ctx.logger.info('AuditPlugin: sys_activity reader-language summaries installed'); + installActivityFieldRedaction(engine as any, getSecurity, ctx.logger); + ctx.logger.info('AuditPlugin: sys_activity field redaction installed'); // [#21155] The compliance ledger's before/after snapshots take the same // narrowing, through the same answer and the same resolver: a ledger // reader is not field-unrestricted by default. An auditor who must see diff --git a/packages/plugins/plugin-audit/src/audit-writers.test.ts b/packages/plugins/plugin-audit/src/audit-writers.test.ts index 6324b43fa48..15fc63ff8e3 100644 --- a/packages/plugins/plugin-audit/src/audit-writers.test.ts +++ b/packages/plugins/plugin-audit/src/audit-writers.test.ts @@ -667,6 +667,119 @@ describe('audit writers — declarative trackHistory activity (ADR-0052 §5b)', }); }); +describe('[#36290] a changed field shows old → new unless the object or the field turns it off', () => { + const DEAL_FIELDS: Record = { + id: { type: 'text' }, + name: { type: 'text', label: 'Name' }, + amount: { type: 'currency', label: 'Amount' }, + note: { type: 'textarea', label: 'Note' }, + quiet: { type: 'text', label: 'Quiet', trackHistory: false }, + api_token: { type: 'secret', label: 'API Token' }, + payload: { type: 'json', label: 'Payload' }, + payload_opted: { type: 'json', label: 'Payload Opted', trackHistory: true }, + }; + const schemaWith = (summary: Record = { type: 'text' }) => ({ + sys_audit_log: SINGLE_TENANT.sys_audit_log, + sys_activity: { + ...Object.fromEntries(SINGLE_TENANT.sys_activity.map((f) => [f, { type: 'text' }])), + summary, + }, + deal: DEAL_FIELDS, + }); + + async function updateDeal( + previous: Record, + result: Record, + { objectDef = {}, summary }: { objectDef?: Record; summary?: Record } = {}, + ) { + const { engine, fire, created } = makeEngine(schemaWith(summary), { deal: { label: 'Deal', ...objectDef } }); + installAuditWriters(engine as any, 'test.audit'); + await fire('afterUpdate', { + object: 'deal', + input: { id: 'deal-1' }, + result: { id: 'deal-1', name: 'D-1', ...result }, + previous: { id: 'deal-1', name: 'D-1', ...previous }, + session: {}, + }); + const activity = created.find((c) => c.object === 'sys_activity'); + expect(activity).toBeDefined(); + return { summary: activity!.row.summary as string, metadata: JSON.parse(activity!.row.metadata) }; + } + + it('an object and a field that say nothing show the values', async () => { + const { summary, metadata } = await updateDeal({ amount: 100 }, { amount: 200 }); + expect(summary).toBe('Amount: 100 → 200'); + expect(metadata.summary_message).toEqual({ + key: 'fieldChanges', + object: 'deal', + changes: [{ field: 'amount', from: { text: '100' }, to: { text: '200' } }], + }); + }); + + it('an object that sets enable.trackHistory: false names the field, never its values', async () => { + const { summary, metadata } = await updateDeal({ amount: 100 }, { amount: 200 }, { objectDef: { enable: { trackHistory: false } } }); + expect(summary).toBe('Updated Deal "D-1": Amount'); + expect(metadata.summary_message.key).toBe('activityUpdatedFields'); + }); + + it('a field that sets trackHistory: false is named by label only, beside a field that shows its values', async () => { + const quietOnly = await updateDeal({ quiet: 'q-before' }, { quiet: 'q-after' }); + expect(quietOnly.summary).toBe('Updated Deal "D-1": Quiet'); + expect(quietOnly.summary).not.toContain('q-after'); + const mixed = await updateDeal({ quiet: 'q-before', amount: 1 }, { quiet: 'q-after', amount: 2 }); + expect(mixed.summary).toBe('Amount: 1 → 2'); + expect(JSON.stringify(mixed.metadata.summary_message)).not.toContain('q-after'); + }); + + it('a credential field is named by label only, never by its mask', async () => { + const { summary, metadata } = await updateDeal({ api_token: 'tok-before' }, { api_token: 'tok-after' }); + expect(summary).toBe('Updated Deal "D-1": API Token'); + expect(JSON.stringify(metadata.summary_message)).not.toContain('•'); + expect(JSON.stringify({ summary, metadata })).not.toContain('tok-after'); + }); + + it('a structured-JSON field shows values only when it opts in with trackHistory: true', async () => { + const plain = await updateDeal({ payload: { a: 1 } }, { payload: { a: 2 } }); + expect(plain.summary).toBe('Updated Deal "D-1": Payload'); + const opted = await updateDeal({ payload_opted: 'p1' }, { payload_opted: 'p2' }); + expect(opted.summary).toBe('Payload Opted: p1 → p2'); + }); + + it('a long value still fits a bounded summary column, and the code keeps a bounded copy of each side', async () => { + const before = 'b'.repeat(3000); + const after = 'a'.repeat(3000); + const { summary, metadata } = await updateDeal({ note: before }, { note: after }, { summary: { type: 'text', maxLength: 500 } }); + expect(summary.length).toBeLessThanOrEqual(500); + expect(summary.startsWith('Note: ')).toBe(true); + const [change] = metadata.summary_message.changes; + expect(change.field).toBe('note'); + expect(change.to.text.length).toBe(1000); + expect(change.to.text.endsWith('…')).toBe(true); + }); + + it('many changes fit a bounded summary column by leaving trailing changes out of the stored sentence only', async () => { + const fields = Object.fromEntries(Array.from({ length: 30 }, (_, i) => [`f${i}`, { type: 'text', label: `Field ${i}` }])); + const { engine, fire, created } = makeEngine( + { ...schemaWith({ type: 'text', maxLength: 500 }), many: { id: { type: 'text' }, name: { type: 'text' }, ...fields } }, + { many: { label: 'Many' } }, + ); + installAuditWriters(engine as any, 'test.audit'); + const prev = Object.fromEntries(Object.keys(fields).map((k) => [k, `old-value-of-${k}`])); + const next = Object.fromEntries(Object.keys(fields).map((k) => [k, `new-value-of-${k}`])); + await fire('afterUpdate', { + object: 'many', + input: { id: 'm-1' }, + result: { id: 'm-1', name: 'M', ...next }, + previous: { id: 'm-1', name: 'M', ...prev }, + session: {}, + }); + const row = created.find((c) => c.object === 'sys_activity')!.row; + expect(row.summary.length).toBeLessThanOrEqual(500); + expect(row.summary.endsWith('; …')).toBe(true); + expect(JSON.parse(row.metadata).summary_message.changes).toHaveLength(30); + }); +}); + describe('audit writers — the generic update summary names the changed fields (#25787)', () => { // A campaign whose roll-up counters a hook bumps once per enrolled member — // plain number fields, none `trackHistory`'d (the measured HotCRM shape). diff --git a/packages/plugins/plugin-audit/src/audit-writers.ts b/packages/plugins/plugin-audit/src/audit-writers.ts index 9a2d9c0a192..4346c4a302a 100644 --- a/packages/plugins/plugin-audit/src/audit-writers.ts +++ b/packages/plugins/plugin-audit/src/audit-writers.ts @@ -987,12 +987,13 @@ function planTrackedLookupReads( fields: Record | undefined | null, oldVals: Record | null, newVals: Record | null, + showsValues: ChangeValuesShown, ): Map> { const byObject = new Map>(); if (!fields || !newVals) return byObject; for (const key of Object.keys(newVals)) { const field = fields[key]; - if (!field || field.trackHistory !== true) continue; + if (!field || !showsValues(key, field)) continue; if (typeof field.type !== 'string' || !REFERENCE_FIELD_TYPES.has(field.type)) continue; const reference = referenceTargetForSummary(field); if (!reference) continue; @@ -1029,8 +1030,10 @@ function planLabelLookupRead( } /** - * ADR-0052 §5b — declarative activity. For fields declared `trackHistory: true`, - * render the diff the writer already captured as a human-readable timeline + * ADR-0052 §5b — declarative activity. For every changed field whose values + * are shown ({@link changeValuesShownFor}: on unless the object or the field + * turns them off, #36290), render the diff the writer already captured as a + * human-readable timeline * summary ("Stage: Proposal → Closed Won"; multiple changes joined by "; "), * using the field label, select option labels and referenced record titles. * Returns null when no tracked field changed, so the caller falls back to the @@ -1071,24 +1074,120 @@ function renderTrackedChangeSummary( oldVals: Record | null, newVals: Record | null, locale: ActivitySummaryLocale, + showsValues: ChangeValuesShown, lookupTitles?: Map>, + maxLength?: number, ): { text: string; fields: string[]; message: ActivitySummaryMessage } | null { if (!fields || !newVals) return null; const changes: ActivitySummaryFieldChange[] = []; for (const key of Object.keys(newVals)) { const field = fields[key]; - if (!field || field.trackHistory !== true) continue; + if (!field || !showsValues(key, field)) continue; const reference = referenceTargetForSummary(field); const titlesFor = reference ? lookupTitles?.get(reference) : undefined; changes.push({ field: key, - from: summaryValueOf(field, oldVals ? oldVals[key] : undefined, titlesFor), - to: summaryValueOf(field, newVals[key], titlesFor), + from: boundedChangeValue(summaryValueOf(field, oldVals ? oldVals[key] : undefined, titlesFor), MAX_CHANGE_VALUE_TEXT), + to: boundedChangeValue(summaryValueOf(field, newVals[key], titlesFor), MAX_CHANGE_VALUE_TEXT), }); } if (changes.length === 0) return null; const message: ActivitySummaryMessage = { key: 'fieldChanges', object: objectName, changes }; - return { text: composeStoredSummary(message, locale), fields: changes.map((c) => c.field), message }; + return { text: fitStoredChangeSummary(message, locale, maxLength), fields: changes.map((c) => c.field), message }; +} + +/** + * [#36290] Whether a changed field's old → new VALUES are rendered: the + * predicate {@link changeValuesShownFor} builds for one object. + */ +type ChangeValuesShown = (key: string, field: any) => boolean; + +/** + * [#36290] The field types whose value has no one-line text — media, embedded + * structured values, vectors, a signature. Their change is named by label + * only, unless the field itself declares `trackHistory: true`, which keeps the + * opt-in it always was. + */ +const NO_LINE_VALUE_TYPES: ReadonlySet = new Set([ + 'image', 'file', 'avatar', 'video', 'audio', 'signature', + 'composite', 'repeater', 'record', 'location', 'address', 'code', 'json', 'vector', +]); + +/** + * [#36290, ruling 7076513167] ADR-0052 §5b.1 with its default reversed: a + * changed field's old → new values render on the record's activity stream + * unless the object turns it off (`enable.trackHistory: false`) or the field + * does (`trackHistory: false`). An absent flag is on. Two classes never render + * values, whatever the flags say: + * + * - a credential field (`collectMaskedReadFields`): both sides are the same + * mask, so the change is named by label only, never `•••• → ••••`; + * - a type in {@link NO_LINE_VALUE_TYPES}, unless the field declares + * `trackHistory: true` itself. + * + * Who may READ the values is not decided here: the row is redacted per reader, + * field by field (`activity-field-redaction.ts`). + */ +function changeValuesShownFor(objectDef: any): ChangeValuesShown { + if (objectDef?.enable?.trackHistory === false) return () => false; + const credentials = new Set(collectMaskedReadFields(objectDef)); + return (key, field) => { + if (!field || field.trackHistory === false || credentials.has(key)) return false; + if (field.trackHistory === true) return true; + return !(typeof field.type === 'string' && NO_LINE_VALUE_TYPES.has(field.type)); + }; +} + +/** + * [#36290] The longest text one side of a field change keeps in the stored + * code. The code is what a reader's record page draws each change from, so a + * long text keeps enough to read; bounded so one edit of a long text field + * cannot grow the row without limit. + */ +const MAX_CHANGE_VALUE_TEXT = 1000; + +/** + * [#36290] How long one side of a change may be inside the STORED one-line + * summary when the full sentence does not fit `sys_activity.summary`'s + * `maxLength`. + */ +const FITTED_CHANGE_VALUE_TEXT = 60; + +/** `value` with its text cut to `max` characters (an ellipsis marks the cut). */ +function boundedChangeValue(value: ActivitySummaryValue, max: number): ActivitySummaryValue { + if (value.text.length <= max) return value; + return { ...value, text: `${value.text.slice(0, Math.max(0, max - 1))}…` }; +} + +/** + * [#36290] The stored sentence for a field-change code, fitted to + * `sys_activity.summary`'s `maxLength` (the SQL driver sizes the column + * `varchar(n)` from it, so an over-long text fails the whole activity insert). + * With values on by default one save can change many fields, or one long + * text, so the tracked branch is fitted as the changed-fields branch is: first + * each side is cut to {@link FITTED_CHANGE_VALUE_TEXT} characters, then + * trailing changes are left out, then the sentence itself is cut. The code + * keeps every change, so a reader's language re-composes the whole of it. + */ +function fitStoredChangeSummary( + message: Extract, + locale: ActivitySummaryLocale, + maxLength: number | undefined, +): string { + const full = composeStoredSummary(message, locale); + if (maxLength === undefined || full.length <= maxLength) return full; + const cut = message.changes.map((c) => ({ + field: c.field, + from: boundedChangeValue(c.from, FITTED_CHANGE_VALUE_TEXT), + to: boundedChangeValue(c.to, FITTED_CHANGE_VALUE_TEXT), + })); + for (let shown = cut.length; shown >= 1; shown -= 1) { + const text = composeStoredSummary({ ...message, changes: cut.slice(0, shown) }, locale); + const tail = shown < cut.length ? '; …' : ''; + if (text.length + tail.length <= maxLength) return `${text}${tail}`; + } + const one = composeStoredSummary({ ...message, changes: cut.slice(0, 1) }, locale); + return `${one.slice(0, Math.max(0, maxLength - 1))}…`; } /** @@ -1103,8 +1202,9 @@ const MAX_NAMED_CHANGED_FIELDS = 5; * changed: before this, the row said only `Updated "