Repository navigation
Expand file tree
/
Copy pathaudit-writers.ts
More file actions
3486 lines (3375 loc) · 182 KB
/
Copy pathaudit-writers.ts
File metadata and controls
3486 lines (3375 loc) · 182 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import type { EnableLike, HookContext } from '@objectstack/spec/data';
import type { IDataEngine, WriteObservabilityOptions } from '@objectstack/spec/contracts';
// [#6656] The read-mask CONTRACT, imported rather than re-typed. `SECRET_MASK`
// is the exact string the engine's read path substitutes and
// `collectMaskedReadFields` is the exact predicate that picks the fields
// (`secret` always; `password` unless the object is `managedBy: 'better-auth'`
// — ADR-0100). A hand-copied `'••••••••'` or a re-typed "is it secret?" test
// here would be a second de-facto contract that drifts from the engine's by one
// character and leaks on the day it does; `secret-fields.ts` makes the same
// argument for its own single definition. The `/core` subpath is the
// engine-free surface of the same package.
//
// [#21197] `collectInternalReadFields` is the flag-keyed half of the same
// contract: a field declared `internal: true` is "never returned on the generic
// data path", and the engine's read path OMITS it. The ledger is a second exit
// for the same value, so it honours the same declaration the same way — the
// producer's declaration consumed, not a masking rule of this package's own.
import { SECRET_MASK, collectInternalReadFields, collectMaskedReadFields, platformSystemApi } from '@objectstack/objectql/core';
// [#24625] The mask of a mail-log row's body columns in a copy of it.
import { maskMailLogBodyCopy } from './mail-log-body-mask.js';
// The key-material columns no copy of a row carries (`key-material-copy.ts`).
import { keyMaterialColumnsOf, omitKeyMaterialFromCopy } from './key-material-copy.js';
import { omitSideCopyFromCopy } from './side-copy-columns.js';
// [#7230] ADR-0079's record display-name contract, imported rather than
// re-derived. `resolveDisplayField` IS the definition of "which field is this
// object's human title" (`nameField` → deprecated `displayNameField` alias →
// deterministic derivation). A local "try name, then title, then subject"
// heuristic here would be a second de-facto contract that disagrees with the
// picker, the search companion and the approval inbox the day an author sets
// `nameField` — the same argument the SECRET_MASK import above makes.
// [#22738] `canServeApiOperation` is the spec's one exposure decision (ADR-0049),
// asked of a referenced object before its title is read into a summary.
import { canServeApiOperation, resolveFieldHistory, referenceTargetOf, resolveDisplayField } from '@objectstack/spec/data';
// [#22510] The acting user's object, named by the registry constant rather
// than a literal — `sys_activity.actor_name` is resolved from its title.
import { SystemObjectName } from '@objectstack/spec/system';
// [#21120] The family-wide stored-metadata-body seam. `sys_metadata` /
// `sys_metadata_history` rows carry a serialized metadata BODY in their
// `metadata` column (a datasource body holds stored credential material), and
// this writer COPIES the whole audited row into `sys_audit_log.new_value` /
// `old_value` and `sys_activity.metadata` at write time — a second,
// admin-readable, at-rest copy. The copy is projected through the one shared
// redactor so the credential is withheld here exactly as it is on every read
// exit; `collectMaskedReadFields` cannot reach it, because the credential is
// nested inside the serialized column, not a top-level secret field of the
// stored-metadata table. ⛔ No second redaction dialect — the credential
// definition is `getMetadataTypeRedactor`'s, consumed through this seam.
import {
isStoredMetadataBodyObject,
redactStoredMetadataBody,
STORED_METADATA_BODY_COLUMN,
STORED_METADATA_TYPE_COLUMN,
} from '@objectstack/spec/kernel';
// [#21207] The same rows' stored content-hash columns — defined beside the
// at-rest rewrite that withholds the copies already written.
import {
METADATA_DECISION_AUDIT_OBJECT,
STORED_METADATA_HASH_COLUMNS,
STORED_METADATA_HASH_NOTE_COLUMN,
withheldStoredHashTokens,
} from './stored-metadata-body-migration.js';
// [commit 1408fe385 / #10101] The platform-row organization resolver, imported rather
// than owned. It started life in THIS file (commit 1408fe385, honouring #8287's ruling)
// and was promoted to `@objectstack/metadata-core` by the maintainer ruling
// recorded on cloud#1395: ONE shared resolver for all three platform-row
// writers (audit, approvals, automation runs) — a per-writer copy of the
// precedence is exactly the two-tables-disagree drift the promotion ends.
// `createFieldPresenceProbe` moved with it (same file, same criterion) and is
// re-exported below so this package's public surface is unchanged.
import {
createFieldPresenceProbe,
createRecordOrganizationResolver,
} from '@objectstack/metadata-core';
// [#15166] The repo's ONE vocabulary of "which driver failure is a missing
// table". The datasource remedy below is the remedy for that cause and no
// other, so deciding whether to print it is exactly this predicate's question.
// AGENTS.md -> "Degradation log levels": a hand-rolled `err.code === '42P01'`
// here would be a second de-facto vocabulary that disagrees with the shared one
// the day a driver is added -- the same argument the imports above make.
import { isMissingTableError } from '@objectstack/types';
// [#21081] The name the activity row declares its text provenance under, owned
// by the read side that redacts by it. [#22771] Likewise the `metadata.kind`
// slot (ADR-0052 §5) and the kind a fired milestone stamps there.
import {
ACTIVITY_KIND_KEY,
ACTIVITY_MILESTONE_KIND,
ACTIVITY_TEXT_SOURCES_KEY,
type ActivityTextSources,
} from './activity-field-redaction.js';
import type { LedgerRecordWriteAction } from './audit-log-field-redaction.js';
import { SIGN_IN_STAMP_EVENT, isSignInStamp } from './sign-in-stamp.js';
import { IMPERSONATED_BY_KEY, IMPERSONATED_BY_NAME_KEY, impersonatorOf } from './impersonation-attribution.js';
import { SCIM_CONNECTION_ID_KEY, scimConnectionOf } from './scim-connection-attribution.js';
import type { MentionGateInput } from './mention-recipient-gate.js';
import {
MENTION_EMAIL_CHANNEL,
MENTION_TOPIC,
REPLY_TOPIC,
mentionEmailDedupKey,
replyEmailDedupKey,
type MentionBuiltinTemplate,
} from './mention-email.js';
// [ADR-0139 E6] The ONE derivation of the two writer-stamped columns the
// withheld-row rule reads, shared with the before-insert hook and the backfill.
import {
declaredMilestoneWatchedFields,
declaresActivityStampColumns,
installActivityStampHook,
planActivityStamp,
} from './activity-changed-fields.js';
// [#26167] A summary's code, and the ONE composer of its text — the stored
// sentence here and each reader's on the read side.
import {
ACTIVITY_SUMMARY_MESSAGE_KEY,
composeStoredSummary,
englishBooleanWord,
milestoneTokenNames,
milestoneTokenRe,
withEnglishMessages,
type ActivitySummaryFieldChange,
type ActivitySummaryLocale,
type ActivitySummaryMessage,
type ActivitySummaryValue,
} from './activity-summary-message.js';
/**
* Minimal structural view of `NotificationService.emit` (ADR-0030). Declared
* locally so plugin-audit takes no runtime dependency on service-messaging — it
* resolves whatever object is registered under the `messaging` service at hook
* time and routes collaboration notifications through the single ingress.
*/
export interface MessagingEmitSurface {
emit(input: {
topic: string;
audience: string[];
payload?: Record<string, unknown>;
severity?: 'info' | 'warning' | 'critical';
dedupKey?: string;
source?: { object: string; id: string };
actorId?: string;
organizationId?: string;
/**
* The channels to fan out to; absent, messaging's `['inbox']` default.
* The mention e-mail names `['email']` (`mention-email.ts`).
*/
channels?: string[];
}): Promise<unknown>;
/**
* `MessagingService.registerBuiltinTemplates` — the code-declared template
* tier the mention e-mail's text is registered in (`mention-email.ts`).
* Optional: a messaging service without it renders the e-mail from the
* notification's title and body alone.
*/
registerBuiltinTemplates?(templates: readonly MentionBuiltinTemplate[]): void;
}
/**
* Minimal structural view of `II18nService.t`. Declared locally (same
* rationale as {@link MessagingEmitSurface}) so plugin-audit resolves whatever
* object is registered under the `i18n` service without a runtime dependency
* on service-i18n. The kernel always registers at least the in-memory
* fallback, and `t` returns the key verbatim on a miss.
*/
export interface AuditI18nSurface {
t(key: string, locale: string, params?: Record<string, unknown>): string;
}
/**
* A user's display identity as the platform holds it: the `sys_user` title
* column (the display name) and `sys_user.image` (the avatar URL), each `null`
* where it cannot be read. The rule is `resolveActorSnapshot`'s, inside
* {@link installAuditWriters}.
*/
export interface AuditActorSnapshot {
name: string | null;
avatarUrl: string | null;
}
/** What {@link installAuditWriters} hands back to the plugin that composes it. */
export interface AuditWritersHandle {
/**
* The display identity of `userId`, read from `sys_user` with the system's
* own read through `api` (a hook context's `api`) — the one resolution the
* `sys_activity` actor columns are written with, so every other platform
* writer of a user's display identity asks it rather than keeping a second
* one. It never rejects: an unreadable identity answers `null` for both.
*/
resolveActorSnapshot(api: unknown, userId: string): Promise<AuditActorSnapshot>;
}
/** Options for {@link installAuditWriters}. */
export interface AuditWriterOptions {
/**
* Lazily resolve the messaging service so collaboration `@mention` /
* assignment notifications go through the ADR-0030 single ingress rather than
* writing `sys_notification` directly. Returns `undefined` when messaging is
* not installed — those notifications are then skipped (no pipeline, no bell),
* matching the `notify` node's degradation.
*/
getMessaging?(): MessagingEmitSurface | undefined;
/**
* Lazily resolve the i18n service used to localize the collaboration
* notification titles (`messages.mentionedYou` …). [#26167] Activity
* summaries are stored in English and localized per READER on the read side
* (`installActivitySummaryLocale`).
*/
getI18n?(): AuditI18nSurface | undefined;
/**
* Resolve the workspace default locale (ADR-0053 `localization.locale`) for
* the write's tenant/user scope. Called per audited write but memoized here
* per scope, so implementations may hit the settings service directly. A
* held answer lasts until the next write to `sys_setting` or
* `sys_platform_setting` through this engine, or a short TTL, whichever
* comes first. Absent → notification titles stay English. [#26167] An
* activity summary asks for no locale at write time.
*/
getLocale?(tenantId?: string, userId?: string): Promise<string | undefined>;
/**
* [ADR-0131 D9] The organization an activity row carries when neither its
* record nor the acting session names one: the Default Organization under
* `single` (the only organization there is), `null` under a wall — the
* `tenancy` service's `defaultOrgId()`. Asked only for such a row, never
* for one whose organization is already known. Absent, `null`, or an answer
* that throws → no activity row is written; the ledger row still is
* (ruling 6257510973 item 3: activity is never a NULL row).
*/
getDefaultOrganizationId?(): Promise<string | null | undefined>;
/**
* The `@mention` recipient gate (`mention-recipient-gate.ts`): the mentioned
* users who may be notified about a comment — each resolved to a user id,
* minus the author, minus everyone who cannot READ the comment's record or
* the comment itself. AuditPlugin wires the real gate. Absent → no mention
* notification is emitted at all (fail closed, said once): the writer cannot
* tell on its own who may see the comment a notification would preview.
*/
admitMentionRecipients?(input: MentionGateInput): Promise<string[]>;
/**
* The absolute URL of a Console page — the auth service's `getConsoleUrl`
* (`${origin}${uiBasePath}${path}`), the one composer of Console page links
* in mail. The mention e-mail links the comment's record through it
* (`mention-email.ts`). Absent, or answering nothing, the link stays the
* app-relative `/{object}/{id}` the inbox notice carries.
*/
getConsoleUrl?(path: string): string | undefined;
}
/**
* Audit writer hook installer.
*
* Subscribes to the ObjectQL engine's wildcard `before*` / `after*` lifecycle
* events and writes:
*
* - `sys_audit_log` rows — compliance-grade entries with field-level
* `old_value` / `new_value` diffs. The platform writes them, and they are
* read-only through the data API and in Setup.
* - `sys_activity` rows — denormalized, human-readable summaries shown
* in the dashboard recent-activity feed and per-record timelines.
*
* Skip rules avoid recursion and noise:
* - Never audit the audit/activity tables themselves.
* - Never audit session/presence/auth tables (high-frequency, low value).
* - A user's own write to their own per-user UI-state row writes neither the
* ledger row nor the activity row (`PER_USER_UI_STATE_OWNER_FIELD`).
* - Read-only operations (`afterFind`) are not audited BY THIS WRITER. Since
* #8992 the `read` action has its own writer in `read-audit.ts`, installed
* separately and only over the objects a deployment opts in: record-detail
* views, batched off the request path. This writer stays write-only.
*
* All writes go through the platform's own system api over `ctx.api`
* (`platformSystemApi`, objectql) so they bypass record-level permissions and
* always succeed regardless of the calling user's RBAC — and so they are the
* platform's rows, never an insert of the automation whose write they record.
*/
/**
* Tables that are intentionally excluded from audit/activity writes.
*
* Two reasons an object lands here:
* 1. Recursion / auth noise — the audit & activity tables themselves, plus
* session/presence/auth tables (high-frequency, low value).
* 2. Operational telemetry / plumbing (ADR-0057) — platform-internal
* event/log/queue objects with a `telemetry`/`transient`/`event`
* lifecycle class. These are NOT user-attributable, compliance-relevant
* changes; mirroring every one of them into the audit ledger
* *and* the activity feed is the dominant source of unbounded growth (a
* single 20s scheduled flow fanned out to ~21 audit+activity rows/tick,
* ~76% of all row growth — see the lifecycle-retention ADR). Until the
* event-spine (ADR-0052 §P2) lands, exclude them at the writer seam.
*/
const SKIP_OBJECTS = new Set<string>([
// (1) recursion + auth/session noise
'sys_audit_log',
'sys_activity',
// NOT `sys_comment`: a comment is an act a person performed, so its insert,
// update and delete write the same ledger and activity rows as every other
// mirrored write, an impersonated one stamped like the rest (maintainer
// ruling on #30213's comments fork, 「A 评论也记审计和动态」). Its rows name
// `sys_comment` as their parent, so the record timeline (which reads the
// parent record's own pair) never draws them twice, and the parent-record
// read gates serve them only to a reader the comment's own read gate admits
// (`parent-record-read-gate.ts`: a parent narrowed by an object-scoped read
// middleware is read through the bounded probe, as the caller).
'sys_session',
'sys_presence',
'sys_account',
'sys_account_session',
'sys_account_verification',
'sys_account_account',
'sys_device_code',
// (2) operational telemetry / plumbing (ADR-0057 — telemetry/transient/event)
'sys_job', // schedule heartbeats (last_run_at churn)
'sys_job_run', // one row per scheduled execution
// [#5193, ADR-0057 D5 "stop the amplifier"] `sys_job_queue` is `sys_job_run`'s
// sibling — `lifecycle.class: 'transient'` since #5179 — and the highest-volume
// table of this family. It is engine-owned plumbing (`managedBy:
// 'engine-owned'`, `enable.apiMethods: ['get','list']`), written ONLY by
// `DbQueueAdapter` under SYSTEM_CTX, so no row here is a user-attributable,
// compliance-relevant change. Every message costs at least three writes —
// publish insert, lease `pending→running`, terminal `→completed` (plus a retry
// update per failure and the #5192 reaper's periodic DELETE of completed rows)
// — and each one mirrored into `sys_audit_log` AND `sys_activity`. Since #5160
// routes email through the queue, that is the amplifier on every single mail.
'sys_job_queue', // durable queue/DLQ messages (≥3 writes each)
'sys_automation_run', // one row per automation execution
'sys_notification', // messaging-owned (ADR-0030); its own lifecycle
'sys_notification_delivery',
'sys_notification_receipt',
'sys_inbox_message', // per-user fan-out of every notification
'sys_http_delivery', // webhook/outbound transport log
// [#5202, ADR-0057 D5 — the same gap as #5193, one table over] Also
// `lifecycle.class: 'transient'`, and its own object comment settles what the
// rows are worth: "an upload session is ephemeral state, **never business
// truth**" (ADR-0057 / #2970 item 4). `StorageMetadataStore` is its only
// writer — `createSession()` inserts, `updateSession()` runs ONCE PER CHUNK,
// and `deleteSession()` (plus the TTL/retention reaper) removes the row — so
// an N-chunk upload cost 2 × (1 + N) `sys_audit_log` + `sys_activity` rows,
// each with its own `beforeUpdate` snapshot read. Worse per row than the
// count suggests: `updateSession()` writes the MERGED FULL record, so every
// chunk's diff drags along the `parts` JSON blob that grows with each part.
// Deliberately NOT `sys_file`: those rows are mostly permanent business truth
// and keep their compliance value, so they stay audited (see #5202).
'sys_upload_session', // chunked-upload progress (1 write per chunk)
// [ADR-0148 D4, ADR-0057 §3.3] The recycle bin, `lifecycle.class:
// 'transient'` and engine-owned. Its entry is written raw by the delete that
// the ledger already records, so the generic writer only ever sees the
// bookkeeping: the lifecycle sweep's reap of an entry, the `set_null` of its
// `deleted_by` when the deleting user goes, and an organization delete's
// cascade into its entries. Each of those would copy the WHOLE entry into
// `sys_audit_log` and `sys_activity`, and the entry's `snapshot` holds every
// declared column of the deleted rows, `internal: true` ones included, which
// the ledger leaves out of the business row's own delete. The snapshot is
// read only through the bin's own doors, under the live object's field-level
// security; a purge by a person is an event-specific writer's to record.
'sys_recycle_bin', // deleted-record snapshots (reaped by TTL)
'ai_traces', // LLM trace telemetry
// [ADR-0057 §3.3] The lifecycle sweeper's own clock state (one row per
// datastore, `managedBy: 'engine-owned'`), written ONLY by objectql's
// `LifecycleService` under SYSTEM_CTX after every completed sweep. Audited,
// each sweep would feed `sys_audit_log` and `sys_activity` the very rows the
// next sweep archives or reaps: cleanup re-feeding the tables it drains.
// Not an act anyone performed; the ruling that created the object forbids
// an audit row per sweep.
'sys_lifecycle_state', // sweep watermark (1 write per sweep)
// [#31021] The seed loader's record of which seed rows landed in an
// organization (`managedBy: 'engine-owned'`, no data API), written ONLY by
// `SeedLoaderService` under the seed write context, one row per key it
// lands. Audited, every seed load would mirror its own bookkeeping into
// `sys_audit_log` and `sys_activity` row for row — the first replay after
// the upgrade, one per seeded row. The seeded rows themselves stay audited.
'sys_seed_landed_key', // landed seed keys (1 write per new key)
// [ADR-0154 D4] The ledger's own tamper evidence, written only by the sealer.
// Audited, every checkpoint, amendment or key would write a ledger row, which
// the next pass would seal into a new checkpoint, which would write a row
// again; and an expiry would write ledger rows about its own deletes. A key's
// creation and rotation are recorded instead as `audit_signing_key_change`.
'sys_audit_checkpoint',
'sys_audit_amendment',
'sys_audit_signing_key',
]);
/**
* [#5860] The same list, on the REGISTRATION face.
*
* `SKIP_OBJECTS` above is consulted inside the handlers, where it is invisible
* to the engine. That made every audit registration read as GLOBAL, so the
* per-object demand gates (#5284's single-id prior-row read on `update()`,
* #5038's bulk equivalents) had to answer "yes, a hook covers this object" for
* every one of these tables and buy a row read for a handler that returns on
* its first line. The knowledge existed; the contract had nowhere to put it
* until #5928 / commit 69787f07b added `excludeObjects`.
*
* Why the negative face and not `object: [...]` with the complement: the object
* universe is OPEN. `/meta` PUT registers new objects into a running engine and
* `SchemaRegistry.registerObject` emits no event, so an enumerated allow list
* would freeze at boot and silently stop auditing everything created after —
* for a compliance plugin, a regression that reports nothing. Subtraction has
* no such failure mode: an object nobody had heard of at install time is
* audited by default. Pinned in `audit-hook-object-scope.test.ts`.
*
* DERIVED, never re-typed: the registration face and the handlers' early return
* are one list, so neither can drift from the other. The early return stays as
* defence in depth — it is what protects every non-hook caller of these
* handlers, and it keeps audit behaviour bit-for-bit conserved by this change.
*
* [#8992] EXPORTED because the read/view writer (`read-audit.ts`) needs the same
* subtraction and must not keep a second copy of it. Every reason an object is
* excluded from write auditing — recursion, auth/session noise, ADR-0057
* telemetry plumbing — applies unchanged to auditing its READS, and two
* hand-kept lists would disagree the day either is fixed. Same rule this
* docblock already states one paragraph up, now across two files.
*/
export const AUDIT_EXCLUDED_OBJECTS: string[] = [...SKIP_OBJECTS];
/**
* [#22961, ruling record 6212163130] Per-user UI-state objects: the owning
* user's OWN write writes neither the `sys_audit_log` row nor the activity row.
*
* The rule: the ledger records acts (data, configuration, access and sharing
* changes), and what reaches a user's bell is another actor's act or something
* the user needs. A user's own UI state is neither. A per-user UI-state row is
* re-saved by the client as a side effect of using the interface (a column
* hidden, a sort toggled, a page visited), and RLS keeps it private to its
* user. Recorded, every click came back twice: as an `update` row on top of
* Setup's Audit Logs, burying the rows an administrator opens it for, and as
* `Updated User Preference "ui.recent"` in the user's own bell, where a fresh
* user saw nothing else.
*
* - CLOSED and DECLARED: an object is a member only by being listed here,
* mapped to the field that names its owning user. ⛔ Never a name heuristic.
* No spec key means "per-user UI state"; `enable.activities: false` mutes
* the activity row of every writer and never the ledger row, so it is not
* this rule.
* - OWN WRITES ONLY: the acting user (`userId`: the `user_id` the ledger row
* would record, and the `actor_id` the activity row would) must be the
* owner on every side of the row the write carries. Another actor's write
* keeps BOTH rows: an organization admin editing the row from Setup's User
* Preferences grid (`modifyAllRecords` passes the self-only RLS), a system
* write with no user, a write that moves the row to another owner.
* - LEDGER AND ACTIVITY, one test (ruling record 6212163130): judged once, at
* the top of `writeAudit`, before either row is built; a write it does not
* admit writes both rows exactly as before. It is still not `SKIP_OBJECTS`,
* which drops every writer's rows and is the `AUDIT_EXCLUDED_OBJECTS` list
* the hook registration and `read-audit.ts` share: another actor's write to
* the same object is an act. No spec key and no object-level flag either;
* `SKIP_OBJECTS` and this rule are the standing qualifications of the
* spec's "audit capture itself is always on" (`enable.trackHistory`). Rows
* already stored are kept.
*
* Membership as measured: the console keeps all of its per-user UI state
* (`ui.recent`, `ui.favorites`, `ui.flow.palette.recents`) on
* `sys_user_preference`, and no other per-user UI-state object exists. A new
* one joins by a line here, and that line takes its owners' own writes out of
* the compliance ledger: ⛔ never a business or security object.
*/
const PER_USER_UI_STATE_OWNER_FIELD: ReadonlyMap<string, string> = new Map([
['sys_user_preference', 'user_id'],
]);
/**
* Whether this write is a user's own write to their own per-user UI-state row
* ({@link PER_USER_UI_STATE_OWNER_FIELD}): the object is listed, an acting user
* is known, and every side of the row that names an owner names that user.
* A side without the owner field (a delete's result is often just `{ id }`) is
* not evidence either way; no side naming an owner at all answers `false`.
*/
function isOwnUiStateWrite(
object: string,
actorUserId: string | undefined,
before: unknown,
after: unknown,
): boolean {
const ownerField = PER_USER_UI_STATE_OWNER_FIELD.get(object);
if (!ownerField || !actorUserId) return false;
const owners: string[] = [];
for (const side of [before, after]) {
if (!side || typeof side !== 'object') continue;
const owner = (side as Record<string, unknown>)[ownerField];
if (owner !== undefined && owner !== null) owners.push(String(owner));
}
return owners.length > 0 && owners.every((owner) => owner === actorUserId);
}
/** Fields that are noise in diffs (always change, never user-meaningful). */
const NOISE_FIELDS = new Set<string>([
'updated_at',
'updated_by',
'created_at',
'created_by',
]);
/**
* [#8144 / commit 1408fe385 / #10101] `createFieldPresenceProbe` and
* `resolveRecordOrganizationField` were defined HERE until #10101 promoted
* them to `@objectstack/metadata-core` (the cloud#1395 ruling: one shared
* platform-row organization resolver for audit, approvals and automation
* runs). Re-exported from this original path so this package's public surface
* — and every existing import — is unchanged; the moved modules carry the
* full precedence documentation.
*/
export { createFieldPresenceProbe, resolveRecordOrganizationField } from '@objectstack/metadata-core';
/**
* [#33694] The `sys_audit_log.metadata` keys that ride beside `performed_by` /
* `on_behalf_of` when the in-product AI performed an operation for a person:
* the AI conversation it ran in, and the pending item the person's approval
* decided before it ran. Copied from `ExecutionContext.performedBy` (for a
* record write, through `HookContext.provenance`), never from the request.
*/
const PERFORMED_IN_CONVERSATION_KEY = 'conversation_id';
const PERFORMED_UNDER_CONFIRMATION_KEY = 'confirmation_id';
/**
* One server-stamped attribution mark, read only as a non-blank string
* (trimmed); anything else reads as absent.
*/
function attributionMark(value: unknown): string | undefined {
return typeof value === 'string' && value.trim() ? value.trim() : undefined;
}
/**
* The performer of one operation, in the shape of `ExecutionContext.performedBy`
* (`HookContext.provenance` carries the same four marks as
* `performedByClientId` / `performedByAgentId` / `performedByConversationId` /
* `performedByConfirmationId`). Each member is read only as a non-blank string.
*/
export interface AuditPerformerSource {
clientId?: unknown;
agentId?: unknown;
conversationId?: unknown;
confirmationId?: unknown;
}
/** The performer keys one `sys_audit_log.metadata` object carries. */
export interface AuditPerformerMetadata {
performed_by: string;
on_behalf_of: string | null;
conversation_id?: string;
confirmation_id?: string;
}
/**
* [ADR-0090 D10 rule 4; #33694, owner ruling on objectstack-ai/cloud#3826
* 「3826 照建议(征询版)」] The ONE rule every `sys_audit_log` writer applies to
* the performer of an operation — the record-write mirror below and the
* action-invocation, data-export and dataset-query rows alike — so the four row
* kinds can never disagree about what `performed_by` means.
*
* Two server-side producers name a performer, each only its own key: the /mcp
* OAuth door names its client in `clientId`; the server-constructed in-product
* AI path, which runs AS the signed-in person, names the agent it ran in
* `agentId`, the conversation it ran in and, when the person confirmed the
* call, the confirmation. The ruling reuses the existing `performed_by` /
* `on_behalf_of` pair and adds no actor vocabulary, so the agent lands in
* `performed_by` exactly where an OAuth client does; if one envelope ever
* carried both, the OAuth client keeps the column it has always held and the
* agent is dropped with its marks.
*
* The conversation and the confirmation are the in-product path's own marks,
* so they are written ONLY when the in-product agent is the performer the row
* records — never beside an OAuth client id. That is what the spec promises a
* reader of `performed_by`, which holds either kind. Each is present only when
* the producer stamped it: no confirmation key ⇒ the operation needed none.
*
* `onBehalfOf` is the row's own `user_id` value, so the two sides of rule 4
* come from one source and never disagree. Answers `undefined` when no
* performer is named: the principal acted for itself and the row carries none
* of these keys.
*/
export function auditPerformerMetadata(
performer: AuditPerformerSource | undefined,
onBehalfOf: string | null | undefined,
): AuditPerformerMetadata | undefined {
const performedByClientId = attributionMark(performer?.clientId);
const performedByAgentId = attributionMark(performer?.agentId);
const performedBy = performedByClientId ?? performedByAgentId;
if (performedBy === undefined) return undefined;
const agentIsRecordedPerformer: boolean = !performedByClientId && performedByAgentId !== undefined;
const performedInConversationId = agentIsRecordedPerformer
? attributionMark(performer?.conversationId)
: undefined;
const performedUnderConfirmationId = agentIsRecordedPerformer
? attributionMark(performer?.confirmationId)
: undefined;
return {
performed_by: performedBy,
on_behalf_of: onBehalfOf ?? null,
...(performedInConversationId ? { [PERFORMED_IN_CONVERSATION_KEY]: performedInConversationId } : {}),
...(performedUnderConfirmationId ? { [PERFORMED_UNDER_CONFIRMATION_KEY]: performedUnderConfirmationId } : {}),
};
}
/**
* Action name produced from a HookContext.event string.
*
* [#21155] Typed by the ledger's record-write vocabulary: these are the rows
* whose snapshots are a parent record's field map, and the read side
* (`audit-log-field-redaction.ts`) narrows exactly those. A new record-write
* action does not compile until that list names it.
*/
function actionFor(event: string): LedgerRecordWriteAction | null {
if (event === 'afterInsert') return 'create';
if (event === 'afterUpdate') return 'update';
if (event === 'afterDelete') return 'delete';
return null;
}
/** Activity type produced from an audit action. */
function activityTypeFor(action: 'create' | 'update' | 'delete'): 'created' | 'updated' | 'deleted' {
return action === 'create' ? 'created' : action === 'update' ? 'updated' : 'deleted';
}
/**
* The human-readable record label: the value of the object's TITLE field, with
* the record id as the floor.
*
* [#21878] Which field that is, is not decided here. The caller hands in the
* field ADR-0079's resolver answered for the object (`titleFieldOf` in the
* writer factory, the same answer referenced-record titles use), so the label
* an activity row records names the field every renderer titles the record by.
* An object titled by a field no fixed key list anticipated (`company_name`)
* gets its title rather than its id; an empty title value gets the id, never a
* guess at some other field.
*
* [#21081] Also answers WHICH field the label was read from (`null` for the id
* floor), so the activity row can declare it: the label is a field value, and
* the read side serves it only to a reader served that field.
*
* A title field that is a REFERENCE (an app's join object titled by its
* person: `nameField: 'person'`, a lookup to `sys_user`) stores a foreign key,
* which is no title. `titlesFor` is the pre-resolved id → title map of that
* field's target ({@link planLabelLookupRead} + `resolveLookupTitles`), so the
* label is the target record's own title, the one the record header shows. An
* id with no entry keeps the stored value it rendered before, so this can only
* replace an id with a title, never a title with an id; and the label is still
* a value of the reference field, which is the field it declares.
*/
function recordLabel(
record: any,
titleField: string | undefined,
id: string,
titlesFor?: Map<string, string>,
): { text: string; field: string | null } {
if (!titleField || !record || typeof record !== 'object') return { text: id, field: null };
const value = record[titleField];
if (titlesFor) {
const refs = referenceIdsOf(value);
if (refs.some((ref) => titlesFor.has(ref))) {
return { text: refs.map((ref) => titlesFor.get(ref) ?? ref).join(', '), field: titleField };
}
}
// A structured value has no text face; it floors to the id rather than
// rendering as a serialised object.
if (value === null || value === undefined || typeof value === 'object') return { text: id, field: null };
const text = String(value).trim();
return text ? { text, field: titleField } : { text: id, field: null };
}
/**
* Field types whose values the engine computes rather than storing (formula /
* summary / rollup / autonumber). Excluded from the audit diff because a
* DERIVED value's change is already implied by the source fields that produced
* it — recording both says the same thing twice.
*
* The original symptom was narrower: `before` came back through the query path
* (computed) while `after` (`ctx.result`) was the raw write result (formula
* key ABSENT), so every update recorded a phantom "value → null" change on the
* objectui record History tab. Since #5504 the write path hydrates formulas
* too, so that particular asymmetry is gone and the two sides now agree. The
* exclusion is kept on its own merit — the derived-is-implied reason above —
* and it is keyed on the field TYPE from `fieldDefs`, never on a key being
* missing, which is why the fix one layer down did not disturb it.
*
* [#6656] Since the pre-image became the engine's raw row, `before` no longer
* carries formula keys at all while `after` still does (#5504's write-path
* hydration) — so the asymmetry is back on the SNAPSHOT faces, which this set
* never reached. `ledgerView(..., { dropComputed: true })` now applies the same
* rule to create `new_value` and delete `old_value`; this set is the single
* definition both faces read.
*/
const COMPUTED_FIELD_TYPES = new Set<string>(['formula', 'summary', 'rollup', 'autonumber', 'auto_number']);
/**
* [#6656] Field types that are **virtual** — no driver ever returns a column
* for one. Dropped from the FULL SNAPSHOTS (create `new_value`, delete
* `old_value`), which is a different job from {@link COMPUTED_FIELD_TYPES}
* above, on a deliberately different set.
*
* Why a snapshot needs the rule at all: `ctx.result` hydrates formulas onto
* what a write hands back (#5504) while the pre-image is the engine's RAW row,
* which structurally cannot carry them. Left in, create `new_value` would
* describe formula fields and delete `old_value` could not — the two snapshot
* faces disagreeing about their own vocabulary.
*
* ⚠️ Why it is NARROWER than `COMPUTED_FIELD_TYPES`, and must stay so. Of that
* set only `formula` is virtual — "formulas are virtual: no driver ever returns
* a column for one" (`engine.ts`, #5504). The rest are ordinary **stored**
* columns the engine maintains: `autonumber` is seeded at insert
* (`seedAutonumber`), and a `summary` roll-up is written to the parent row by
* `recomputeSummaries` and seeded at create time (#5749/#6063). They are
* present on BOTH sides and symmetric, so dropping them from a snapshot would
* delete real ledger content — the record's human-facing number, and its
* roll-up values — to fix an asymmetry they never had.
*
* The wider set stays correct for `diff()`, whose rule is a different one: a
* derived value's CHANGE is already implied by the source fields that produced
* it. That is about change reporting; this is about what a snapshot can
* contain. Do not unify them.
*/
const VIRTUAL_FIELD_TYPES = new Set<string>(['formula']);
/**
* Compute a shallow JSON diff between two records. Returns only keys whose
* value changed (and ignores keys in `NOISE_FIELDS` plus computed field
* types per `fieldDefs`). Both sides are serialisable via `JSON.stringify` —
* values that fail to serialise are coerced to `String(value)`.
*/
function diff(
before: Record<string, any>,
after: Record<string, any>,
fieldDefs?: Record<string, any> | null,
): { old: Record<string, any>; next: Record<string, any> } {
const oldOut: Record<string, any> = {};
const newOut: Record<string, any> = {};
const keys = new Set<string>([...Object.keys(before || {}), ...Object.keys(after || {})]);
for (const k of keys) {
if (NOISE_FIELDS.has(k)) continue;
const type = fieldDefs?.[k]?.type;
if (typeof type === 'string' && COMPUTED_FIELD_TYPES.has(type)) continue;
// `?? null` BEFORE comparing: a key absent on one side (undefined) must
// compare equal to an explicit null on the other. JSON.stringify(undefined)
// returns undefined (not a string), so the raw comparison saw
// undefined ≠ 'null' and wrote a noise row with old=new=null.
const b = before?.[k] ?? null;
const a = after?.[k] ?? null;
if (safeStringify(b) !== safeStringify(a)) {
oldOut[k] = b;
newOut[k] = a;
}
}
return { old: oldOut, next: newOut };
}
function safeStringify(v: any): string {
try { return JSON.stringify(v); } catch { return String(v); }
}
/**
* [#7230] Field types whose stored value is a FOREIGN RECORD ID rather than
* something a human can read. `user` is on the list because it is "a lookup
* specialized to the `sys_user` system object — stored IDENTICALLY (FK string
* column → sys_user.id)" (`field.zod.ts`), which is exactly the field class the
* measured symptom came from (`Rating Owner: ∅ → oBK25…`). `tree` is NOT on the
* list: it carries no `reference`, so there is no target object to read.
*
* The same three types, for the same reason, are what `plugin-approvals`
* resolves for its inbox display (`resolveLookupFields`) — one vocabulary for
* "this value is a reference", not two.
*/
const REFERENCE_FIELD_TYPES: ReadonlySet<string> = new Set(['lookup', 'master_detail', 'user']);
/**
* [#19264] The TARGET OBJECT of a reference-typed field — the key both halves
* of a summary's title resolution are keyed on.
*
* Read through `referenceTargetOf`, the spec's SINGLE arbiter of "what does
* this field point at", and NOT through the materialized `reference` carrier
* this file used to read raw. For `user` the two differ, and
* `IMPLICIT_REFERENCE_TARGETS` (`@objectstack/spec/data`) is explicit about
* which one answers: the target of a `user` field is "a CONSTANT OF THE TYPE,
* so `reference` on a `user` field materializes that constant; it does not
* supply it. Metadata authored without it (hand-written JSON, an AI author, a
* Studio form) is fully specified, not under-specified."
*
* Gating on the carrier therefore dropped the spelling the contract calls
* COMPLETE, and dropped it SILENTLY: a `trackHistory`'d `{ type: 'user' }`
* field with no `reference` was planned for nobody, so the timeline rendered
* the raw 32-char id where every other reference field showed a name — no
* refusal, no diagnostic. `plugin-approvals` had the identical defect in
* `resolveLookupFields` and was moved to this same arbiter; the docblock on
* {@link REFERENCE_FIELD_TYPES} declares the two packages share one vocabulary
* for "this value is a reference", so they resolve the target one way too.
*
* ## Both halves, because the key has two ends
*
* The plan (`planTrackedLookupReads` / `planMilestoneTokenReads`) keys the read
* by target object and the renderers (`renderTrackedChangeSummary` /
* `renderMilestoneSummary`) look the resolved titles back up by the same key.
* Repairing only the plan would issue the read and then fail to find it again,
* so the timeline would still show the id — the symptom this fixes — while
* paying for the read. One function answers for all four, which is also why a
* padded carrier can no longer make the two ends disagree: the plan used to
* `trim()` and the renderers did not, so `reference: ' crm_account '` produced
* a key neither side could match.
*
* ## The type gate is unchanged, deliberately
*
* `tree` is the fourth member of `REFERENCE_VALUE_TYPES` and stays OUT: it
* carries an author-chosen target, so admitting it would WIDEN what the
* timeline tracks rather than repair what it silently dropped.
* {@link REFERENCE_FIELD_TYPES} remains the one gate, applied by the callers
* before they ask this.
*
* ## Why the throw is swallowed here rather than propagated
*
* `referenceTargetOf` reads the carrier through `referenceCarrierOf`, which
* THROWS for an object- or array-valued `reference` — a shape `safeParse`
* refuses at the contract door and only an unparsed literal can reach. Every
* caller below runs inside `writeAudit`'s summary composition, which is NOT
* inside the `try` that guards the audit row write: a `TypeError` escaping
* here would leave the hook, i.e. turn a display-enrichment miss into a
* failure on the audited write's own path. So an unreadable carrier keeps the
* answer it has always had on this path — absent, the field left out of the
* plan — and the audited write is untouched. Absence is not a new silence: it
* is byte-identical to what `typeof field.reference === 'string'` already
* answered for that shape, and this repair is about the target a `user` field
* legitimately declines to restate, not about unreadable metadata.
*
* Returns `''` — never `undefined` — so the callers' existing falsy gate reads
* exactly as it did.
*/
function referenceTargetForSummary(field: any): string {
let target: string | undefined;
try {
target = referenceTargetOf(field);
} catch {
return '';
}
return typeof target === 'string' ? target.trim() : '';
}
/** [#22738] What `objectName` declares: `getSchema()` on the engine. A throw is no answer. */
type DeclarationReader = (objectName: string) => { enable?: unknown } | null | undefined;
type WarnSink = { warn?: (message: string) => void };
/**
* [#22738] May an activity summary carry a title read from `target`, the object
* a tracked reference points at? Asked of the spec's one exposure decision
* (ADR-0049) for `get`, the read `GET /data/{target}/{id}` performs and the
* operation the data door's `$expand` and the dataset door's labels ask of the
* same target. It takes no caller: it judges the target's declaration, and
* the read that follows is in the WRITER's scope (see `resolveLookupTitles`),
* for a summary's titles and a record label alike.
*
* A refused target is not read, so the summary names its records by their
* stored ids, the answer an unresolvable reference already gets. A declaration
* that cannot be read withholds too (fail-closed, at `warn`). Only rows written
* from now on change; a written row is a snapshot and is never rewritten.
*/
function servesSummaryTitleTarget(target: string, readDeclaration: DeclarationReader, logger?: WarnSink): boolean {
let enable: EnableLike | null | undefined;
try {
enable = readDeclaration(target)?.enable as EnableLike | null | undefined;
} catch (err) {
logger?.warn?.(
`[audit] resolveLookupTitles: the API exposure declaration of "${target}" could not be read, so the ` +
`summary names its records by their stored ids (fail-closed): ${err instanceof Error ? err.message : String(err)}`,
);
return false;
}
return canServeApiOperation(enable, 'get');
}
/**
* [#7230] The referenced record ids carried by one lookup-field value.
*
* A single-value lookup stores one id; a `multiple: true` one stores an ARRAY
* (`field.zod.ts`: "Stores as Array/JSON"). Only the in-memory array shape is
* unpacked — a driver that hands the column back as an unparsed JSON string is
* left to the raw fallback rather than guessed at here, since parsing it would
* be this file inventing a storage contract it does not own.
*
* Objects are deliberately skipped: since #6656 both sides of the diff are raw
* driver rows, so an already-expanded `{id, name}` cannot reach here, and
* writing a limb for it would be consumer-side tolerance for a producer that
* does not exist (PD #12).
*/
function referenceIdsOf(value: any): string[] {
const one = (v: any): string | null => {
if (v === null || v === undefined || v === '') return null;
if (typeof v === 'string') return v.trim() ? v : null;
if (typeof v === 'number' || typeof v === 'bigint') return String(v);
return null;
};
if (Array.isArray(value)) return value.map(one).filter((v): v is string => v !== null);
const single = one(value);
return single === null ? [] : [single];
}
/**
* Resolve a field value to its display string, preferring a select/picklist
* option label — or, for a reference field, the referenced record's title —
* over the raw stored value. Empty/missing → "∅".
*
* [#7230] `titlesFor` is the pre-resolved id → title map for THIS field's
* target object (see `resolveLookupTitles`). It is a lookup into an
* already-batched result, never a read: this function stays synchronous, and a
* caller with nothing to resolve passes nothing and keeps today's behaviour
* exactly. [#7290] Both summary branches now feed it: the tracked-change diff
* (`renderTrackedChangeSummary`) and the fired-milestone template
* (`renderMilestoneSummary`), each from its own read plan.
*
* An id with no entry in the map — record deleted, object unregistered, title
* field unresolvable, or a record or title column the writer may not read —
* falls back to the raw id, which is what this function
* returned before the branch existed. The change is therefore restore-invariant:
* it can only replace an id with a title, never a title with an id.
*
* [#7289] `optionLabelFor` is the locale-bound lookup for THIS field's option
* labels — `objects.<object>.fields.<field>.options.<value>`, the key shape the
* shipped bundles actually carry (`translations/zh-CN.objects.generated.ts`:
* `sys_audit_log.fields.action.options.create = "创建"`). Like `titlesFor` it is an
* already-resolved lookup and never I/O, so this function stays SYNCHRONOUS;
* and like `titlesFor`, a caller with nothing to resolve passes nothing and
* keeps today's behaviour exactly. That opt-in shape is load-bearing rather
* than stylistic — see {@link renderMilestoneSummary}, which passes nothing on
* purpose and is documented there.
*
* The lookup is consulted only where a DECLARED OPTION MATCHED, so a value
* matching no option still renders `String(value)` as before. Bundles are
* generated FROM the declared options (`os i18n extract`), so a bundle key with
* no matching declared option cannot arise, and a miss falls straight back to
* the authored `label`. Same restore-invariance as the reference branch: it can
* only replace an authored label with that label's translation.
*/
function displayFieldValue(
field: any,
value: any,
titlesFor?: Map<string, string>,
optionLabelFor?: (optionValue: string) => string | undefined,
): string {
const shown = summaryValueOf(field, value, titlesFor);
// A milestone's sentence is composed in the author's language at write time;
// a reader's translation, when its locale carries one, is re-rendered from the
// `_milestones` key on the feed (`activity-summary-message.ts`). An English
// yes/no word interpolated here would be the very mixed-language sentence the
// field-change wording removes, so a boolean token keeps its stored value.
if (shown.boolean !== undefined) return String(value);
return shown.option !== undefined ? (optionLabelFor?.(shown.option) ?? shown.text) : shown.text;
}
/**
* [#26167] {@link displayFieldValue} before any option label is translated:
* the text it renders with no `optionLabelFor`, and the declared option the
* value matched, if any. A field-change summary stores this pair, so the
* option label is translated for each READER (`activity-summary-message.ts`).
*/
function summaryValueOf(field: any, value: any, titlesFor?: Map<string, string>): ActivitySummaryValue {
if (value === null || value === undefined || value === '') return { text: '∅' };
if (titlesFor && typeof field?.type === 'string' && REFERENCE_FIELD_TYPES.has(field.type)) {
const ids = referenceIdsOf(value);
if (ids.length > 0) return { text: ids.map((id) => titlesFor.get(id) ?? id).join(', ') };
}
const options = field?.options;
if (Array.isArray(options)) {
for (const o of options) {
const ov = o && typeof o === 'object' ? (o.value ?? o.name ?? o.label) : o;
if (ov === value) {
const ol = o && typeof o === 'object' ? (o.label ?? o.name ?? ov) : o;
return { text: String(ol), option: String(ov) };
}
}
}
// A boolean the field declares no words for is a yes/no, never the literal
// `true` / `false`: the value rides in the code itself, and the composer
// words it in the locale it composes in (`activity-summary-message.ts`). The
// writer's text is the English catalogue's word, so a locale with none still
// reads a word.
if (typeof value === 'boolean' && typeof field?.type === 'string' && BOOLEAN_FIELD_TYPES.has(field.type)) {
return { text: englishBooleanWord(value), boolean: value };
}
return { text: String(value) };
}
/** The field types whose value is a yes/no (`FieldType`: `boolean`, and its `toggle` face). */
const BOOLEAN_FIELD_TYPES: ReadonlySet<string> = new Set(['boolean', 'toggle']);
/**
* [#7230] Every tracked-change field of `fields` that is a reference, grouped
* by TARGET OBJECT — the tracked-change branch's read plan for
* {@link resolveLookupTitles}.
*
* Grouping by target object (not by field, and emphatically not by row) is what
* keeps this off the write hot path: N tracked reference fields pointing at one
* object cost ONE read, and a write that changes no tracked reference field
* produces an empty plan and therefore no read at all.
*/
function planTrackedLookupReads(
fields: Record<string, any> | undefined | null,
oldVals: Record<string, any> | null,
newVals: Record<string, any> | null,
showsValues: ChangeValuesShown,
): Map<string, Set<string>> {
const byObject = new Map<string, Set<string>>();
if (!fields || !newVals) return byObject;
for (const key of Object.keys(newVals)) {
const field = fields[key];
if (!field || !showsValues(key, field)) continue;
if (typeof field.type !== 'string' || !REFERENCE_FIELD_TYPES.has(field.type)) continue;