Skip to content

Commit e566e4c

Browse files
committed
feat(objectql): carry an object extension's fieldPatches and apply it in mergeObjectDefinitions
ADR-0146 D10 second rule: whitelisted display keys and option labels by stored value, after the additive merges; ADR-0029 D9.2a yield; priority order; a patch naming a missing target is skipped and named once at the fold. Claude-Session: https://claude.ai/code/session_01FEkQ5nSMgkteiemkoN31vf Co-authored-by: Claude <noreply@anthropic.com>
1 parent d850be1 commit e566e4c

2 files changed

Lines changed: 247 additions & 5 deletions

File tree

‎packages/objectql/src/engine.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8986,6 +8986,11 @@ export class ObjectQL implements IObjectQLEngine {
89868986
const extDef = {
89878987
name: targetFqn, // Use the target FQN as name
89888988
fields: ext.fields,
8989+
// [ADR-0146 D10, second rule] The per-field display patches,
8990+
// the slot as `ObjectExtensionSchema.fieldPatches` declares
8991+
// it — applied by the registry's `mergeObjectDefinitions`,
8992+
// whose fold every object read shares.
8993+
fieldPatches: ext.fieldPatches,
89898994
label: ext.label,
89908995
pluralLabel: ext.pluralLabel,
89918996
description: ext.description,

‎packages/objectql/src/registry.ts‎

Lines changed: 242 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
22

3-
import { ServiceObject, ObjectSchema, ObjectOwnership, provisionPrimary, resolveInjectedSystemColumns, resolveInjectedColumnProvenance as injectedColumnProvenance, isInjectedColumnDefinition, isTenancyDisabled, checkManagedApiMethodAffordances, LEGACY_API_METHODS, AUDIT_PROVENANCE_FIELDS, materializeTreeSelfReferences } from '@objectstack/spec/data';
3+
import { ServiceObject, ObjectSchema, ObjectOwnership, provisionPrimary, resolveInjectedSystemColumns, resolveInjectedColumnProvenance as injectedColumnProvenance, isInjectedColumnDefinition, isTenancyDisabled, checkManagedApiMethodAffordances, LEGACY_API_METHODS, AUDIT_PROVENANCE_FIELDS, materializeTreeSelfReferences, BASE_FIELD_DISPLAY_WHITELIST, type ObjectExtensionParsed } from '@objectstack/spec/data';
44
// [#4513] The audit-family governance table, and [#6562] the injected-column
55
// DEFINITION tables it governs — see the re-exports below for why both live in a
66
// package `objectql` and `metadata-protocol` both depend on.
@@ -37,6 +37,10 @@ import {
3737
OBJECT_FIELD_TYPE_REFUSED_ERROR_NAME,
3838
type ObjectFieldTypeRefusal,
3939
type ObjectFieldTypeViolation,
40+
// [ADR-0146 D10, second rule] The field-patch target check — the install
41+
// door's and `os validate`'s judge, asked here so the fold names a patch it
42+
// cannot apply by the same verdict those doors refuse it by.
43+
fieldPatchTargetMisses,
4044
} from '@objectstack/metadata-core';
4145
// [ADR-0029 D9.2a] `scalarOverridesPackagedBase` is the #8284 comparison, imported rather
4246
// than re-spelled: the object FOLD asks the same question one layer down (has
@@ -495,6 +499,129 @@ const OBJECT_FOLD_SCALAR_KEYS = ['label', 'pluralLabel', 'description'] as const
495499

496500
type ObjectFoldScalarKey = (typeof OBJECT_FOLD_SCALAR_KEYS)[number];
497501

502+
/**
503+
* [ADR-0146 D10, second rule] An object extension's per-field display patches:
504+
* the slot `ObjectExtensionSchema.fieldPatches` declares, carried onto the
505+
* extension def by the manifest loop (`engine.ts`) and applied by
506+
* {@link mergeObjectDefinitions}. ⛔ No second shape: the type IS the spec's,
507+
* and the keys applied are read from `BASE_FIELD_DISPLAY_WHITELIST`, so a
508+
* widened whitelist widens what the merge applies too.
509+
*/
510+
type ObjectFieldPatches = NonNullable<ObjectExtensionParsed['fieldPatches']>;
511+
512+
/** An `extend` contributor's body: a partial object that may carry {@link ObjectFieldPatches}. */
513+
type ObjectExtensionBody = Partial<ServiceObject> & { fieldPatches?: ObjectFieldPatches };
514+
515+
const isPlainRecord = (v: unknown): v is Record<string, unknown> =>
516+
v !== null && typeof v === 'object' && !Array.isArray(v);
517+
518+
/**
519+
* The address of one patched display key in a fold's D9.2a yield set
520+
* ({@link SchemaRegistry.tenantPatchedDisplayKeys}): a field key, or one key of
521+
* the option addressed by its stored value.
522+
*/
523+
function fieldPatchYieldKey(field: string, key: string, option?: string): string {
524+
return option === undefined ? `${field}\u0000${key}` : `${field}\u0000options\u0000${option}\u0000${key}`;
525+
}
526+
527+
/** A field of an object body's name-keyed `fields`, when it is a record. */
528+
function recordFieldOf(body: unknown, name: string): Record<string, unknown> | undefined {
529+
const fields = isPlainRecord(body) ? body.fields : undefined;
530+
if (!isPlainRecord(fields) || !Object.prototype.hasOwnProperty.call(fields, name)) return undefined;
531+
const field = fields[name];
532+
return isPlainRecord(field) ? field : undefined;
533+
}
534+
535+
/** The option of a field's own `options` whose stored `value` is `value`. */
536+
function optionByValue(field: Record<string, unknown>, value: string): Record<string, unknown> | undefined {
537+
const options = field.options;
538+
if (!Array.isArray(options)) return undefined;
539+
const found = options.find((o) => isPlainRecord(o) && o.value === value);
540+
return isPlainRecord(found) ? found : undefined;
541+
}
542+
543+
/**
544+
* [ADR-0029 D9.2a] The scalar yield's comparison, asked of one display key of a
545+
* field or of one of its options. It IS {@link scalarOverridesPackagedBase} —
546+
* the one comparison behind every D9.2a yield, keyed by any attribute (its own
547+
* docblock: the exported key union names the keys its callers ask about, and
548+
* the implementation underneath reads any) — ⛔ never a second copy of it.
549+
*/
550+
function displayKeyOverridesPackagedBase(packaged: unknown, key: string, value: unknown): boolean {
551+
return scalarOverridesPackagedBase(packaged, key as Parameters<typeof scalarOverridesPackagedBase>[1], value);
552+
}
553+
554+
/**
555+
* [ADR-0146 D10, second rule] One base field with an extension's patch applied:
556+
* the whitelisted field keys, then each option the patch addresses by its
557+
* stored `value`. A key the tenant authored on the fold's base yields
558+
* (`tenantPatched`, ADR-0029 D9.2a). Returns `field` BY REFERENCE when nothing
559+
* applies.
560+
*
561+
* A field bound to a picklist is left alone under `options`: the served options
562+
* are the picklist's, written over the field after the fold
563+
* ({@link SchemaRegistry.finishServedObject}), so an option label written here
564+
* would never be served. The target check names that patch instead.
565+
*/
566+
function patchedField(
567+
name: string,
568+
field: Record<string, unknown>,
569+
patch: ObjectFieldPatches[string],
570+
tenantPatched: ReadonlySet<string> | undefined,
571+
): Record<string, unknown> {
572+
let next: Record<string, unknown> | undefined;
573+
const patchKeys = patch as Record<string, unknown>;
574+
for (const key of BASE_FIELD_DISPLAY_WHITELIST.field) {
575+
const value = patchKeys[key];
576+
if (value === undefined || tenantPatched?.has(fieldPatchYieldKey(name, key))) continue;
577+
(next ??= { ...field })[key] = value;
578+
}
579+
const optionPatches = patch.options;
580+
const options = field.options;
581+
const picklistBound = typeof field.picklist === 'string' && field.picklist !== '';
582+
if (optionPatches && Array.isArray(options) && !picklistBound) {
583+
let patchedOptions: unknown[] | undefined;
584+
options.forEach((option, index) => {
585+
if (!isPlainRecord(option) || typeof option.value !== 'string') return;
586+
if (!Object.prototype.hasOwnProperty.call(optionPatches, option.value)) return;
587+
const optionPatch = optionPatches[option.value] as Record<string, unknown> | undefined;
588+
if (!optionPatch) return;
589+
let patchedOption: Record<string, unknown> | undefined;
590+
for (const key of BASE_FIELD_DISPLAY_WHITELIST.option) {
591+
const value = optionPatch[key];
592+
if (value === undefined || tenantPatched?.has(fieldPatchYieldKey(name, key, option.value))) continue;
593+
(patchedOption ??= { ...option })[key] = value;
594+
}
595+
if (patchedOption) (patchedOptions ??= [...options])[index] = patchedOption;
596+
});
597+
if (patchedOptions) (next ??= { ...field }).options = patchedOptions;
598+
}
599+
return next ?? field;
600+
}
601+
602+
/**
603+
* [ADR-0146 D10, second rule] `fields` with every patch of `patches` applied
604+
* that names a field `fields` has. A patch naming a field the object lacks is
605+
* skipped here, and named by the fold ({@link SchemaRegistry.reportFieldPatchMisses}).
606+
* Returns `fields` BY REFERENCE when nothing applies.
607+
*/
608+
function applyFieldPatches(
609+
fields: ServiceObject['fields'],
610+
patches: ObjectFieldPatches,
611+
tenantPatched: ReadonlySet<string> | undefined,
612+
): ServiceObject['fields'] {
613+
if (!isPlainRecord(fields)) return fields;
614+
let out: Record<string, unknown> | undefined;
615+
for (const [name, patch] of Object.entries(patches)) {
616+
if (!patch) continue;
617+
const field = recordFieldOf({ fields: out ?? fields }, name);
618+
if (!field) continue;
619+
const next = patchedField(name, field, patch, tenantPatched);
620+
if (next !== field) (out ??= { ...fields })[name] = next;
621+
}
622+
return (out ?? fields) as ServiceObject['fields'];
623+
}
624+
498625
/**
499626
* [#28356] Which layer an object fold serves: `'served'`, what every read
500627
* answers (the bound actions the registry serves, runtime-authored included),
@@ -516,6 +643,12 @@ type ServedObjectLayer = 'served' | 'code';
516643
* - The three {@link OBJECT_FOLD_SCALAR_KEYS} (`label`, `pluralLabel`,
517644
* `description`) are overridden last-writer-wins, subject to the
518645
* `tenantAuthored` yield rule below.
646+
* - `fieldPatches` [ADR-0146 D10, second rule] is APPLIED, never carried:
647+
* after the merges above, each patch writes its `BASE_FIELD_DISPLAY_WHITELIST`
648+
* keys onto the named field and its option labels onto the options whose
649+
* stored `value` it names, each key yielding where `tenantPatched` says the
650+
* tenant authored it — the same D9.2a rule as the scalars. A patch naming a
651+
* field the merged object lacks is skipped here; the fold names it.
519652
*
520653
* **Every other top-level prop on `extension` is silently discarded.**
521654
* `merged` starts as `{ ...base }` and nothing outside the list above is ever
@@ -527,8 +660,8 @@ type ServedObjectLayer = 'served' | 'code';
527660
*
528661
* Declarative authors never reach that silence, though: `ObjectExtensionSchema`
529662
* (`packages/spec/src/data/object.zod.ts`) is `.strict()` — its shape is
530-
* exactly `extend` / `fields` / `label` / `pluralLabel` / `description` /
531-
* `validations` / `indexes` / `priority`, so an `objectExtensions` entry
663+
* exactly `extend` / `fields` / `fieldPatches` / `label` / `pluralLabel` /
664+
* `description` / `validations` / `indexes` / `priority`, so an `objectExtensions` entry
532665
* naming `tenancy`, `permissions`, or any other key outside that list fails
533666
* LOUDLY at authoring time with a prescription (#4001; the same rule is
534667
* documented at `content/docs/data-modeling/object-extensions.mdx`). This
@@ -558,9 +691,10 @@ type ServedObjectLayer = 'served' | 'code';
558691
*/
559692
function mergeObjectDefinitions(
560693
base: ServiceObject,
561-
extension: Partial<ServiceObject>,
694+
extension: ObjectExtensionBody,
562695
tenantAuthored?: ReadonlySet<ObjectFoldScalarKey>,
563696
tenantRules?: ReadonlyMap<string, TenantRuleSettings>,
697+
tenantPatched?: ReadonlySet<string>,
564698
): ServiceObject {
565699
const merged = { ...base };
566700

@@ -594,6 +728,16 @@ function mergeObjectDefinitions(
594728
merged.description = extension.description;
595729
}
596730

731+
// [ADR-0146 D10, second rule] The extension's display patches of the base's
732+
// fields — AFTER the additive merges, so a patch reaches a field a
733+
// lower-priority extender added, and with each key yielding where the tenant
734+
// authored it (`tenantPatched`, ADR-0029 D9.2a), as the scalars above yield.
735+
// Two extenders patching one key resolve as the scalars do: the fold applies
736+
// contributors in ascending `priority`, so the higher one is written last.
737+
if (extension.fieldPatches) {
738+
merged.fields = applyFieldPatches(merged.fields, extension.fieldPatches, tenantPatched);
739+
}
740+
597741
return merged;
598742
}
599743

@@ -4160,14 +4304,19 @@ export class SchemaRegistry {
41604304
// tenant's `message` and `active`. Computed once, over the base, as the
41614305
// scalars above are.
41624306
const tenantRules = this.tenantRuleSettings(contributors, baseDefinition);
4307+
// [ADR-0146 D10, second rule; ADR-0029 D9.2a] The display keys the tenant
4308+
// authored on the fields the extenders patch — computed once, over the
4309+
// base, for the scalars' reason above.
4310+
const tenantPatched = this.tenantPatchedDisplayKeys(contributors, baseDefinition);
41634311
let merged = tenantRules
41644312
? this.withPackagedOwnerRules(contributors, baseDefinition, tenantRules)
41654313
: { ...baseDefinition };
41664314
for (const contrib of contributors) {
41674315
if (contrib.ownership === 'extend') {
41684316
let extension = governAudit ? applyAuditFieldGovernance(contrib.definition) : contrib.definition;
41694317
if (governQueue) extension = this.withoutExtensionQueueField(extension, contrib.packageId);
4170-
merged = mergeObjectDefinitions(merged, extension, tenantAuthored, tenantRules);
4318+
merged = mergeObjectDefinitions(merged, extension, tenantAuthored, tenantRules, tenantPatched);
4319+
this.reportFieldPatchMisses(merged, extension, contrib.packageId);
41714320
}
41724321
}
41734322
if (tenantRules) this.reportChangedRuleCopies(contributors, baseDefinition);
@@ -4177,6 +4326,45 @@ export class SchemaRegistry {
41774326
return this.finishServedObject(merged, layer);
41784327
}
41794328

4329+
/**
4330+
* [ADR-0146 D10, second rule] Field-patch targets already named, keyed
4331+
* `object|package|field|option`. Per registry, for the reason
4332+
* {@link shadowedExtensionQueueWarned} gives.
4333+
*/
4334+
private fieldPatchMissesWarned = new Set<string>();
4335+
4336+
/**
4337+
* [ADR-0146 D10, second rule] Name, once, each patch of `extension` the fold
4338+
* could not apply: a field the object does not have, an option value its
4339+
* field does not have, or an option of a picklist-bound field. The verdict
4340+
* is the install door's and `os validate`'s own judge
4341+
* (`fieldPatchTargetMisses`), so the boot names exactly what those doors
4342+
* refuse.
4343+
*
4344+
* ⛔ Never a refusal, and worded as the state it observes: the fold runs on
4345+
* every read while a boot is still registering packages, so a field another
4346+
* extender adds later makes the patch apply on the next read, with nothing
4347+
* recorded to undo (AGENTS.md *Startup registry reads*). At `warn`: the
4348+
* object is visibly unpatched, and nothing durable is lost.
4349+
*/
4350+
private reportFieldPatchMisses(
4351+
target: ServiceObject,
4352+
extension: ObjectExtensionBody,
4353+
packageId: string | undefined,
4354+
): void {
4355+
if (!extension.fieldPatches) return;
4356+
const object = String(target.name ?? extension.name ?? '');
4357+
for (const miss of fieldPatchTargetMisses(object, extension.fieldPatches, target)) {
4358+
const key = `${object}|${packageId ?? ''}|${miss.field}|${miss.option ?? ''}`;
4359+
if (this.fieldPatchMissesWarned.has(key)) continue;
4360+
this.fieldPatchMissesWarned.add(key);
4361+
console.warn(
4362+
`[Registry] An extension of object "${object}"${packageId ? ` from package "${packageId}"` : ''} ` +
4363+
`carries a field patch that is not applied while the object has no such target: ${miss.message}`,
4364+
);
4365+
}
4366+
}
4367+
41804368
/**
41814369
* Extension `queue` declarations already named, keyed `object|package`. Per
41824370
* registry, not module-level, for the reason {@link navGroupDiagnostics}
@@ -4483,6 +4671,55 @@ export class SchemaRegistry {
44834671
return authored;
44844672
}
44854673

4674+
/**
4675+
* [ADR-0146 D10, second rule; ADR-0029 D9.2a] The display keys a fold's base
4676+
* has authored away from the packaged owner's value, on the fields and
4677+
* options the `extend` contributors patch — each a {@link fieldPatchYieldKey}.
4678+
* A patch yields on those keys, as an extender's scalar yields on
4679+
* {@link tenantAuthoredScalars}, and by the same comparison
4680+
* ({@link displayKeyOverridesPackagedBase}).
4681+
*
4682+
* The same two "no opinion" edges as {@link tenantAuthoredScalars}, for its
4683+
* reasons: no `own` contributor, or a base that IS the owner's body (by
4684+
* reference). Idempotent over a folded base for its reason too: a base that
4685+
* already carries a patch's text reads as authored, so the patch yields and
4686+
* the value stays what the first fold produced.
4687+
*/
4688+
private tenantPatchedDisplayKeys(
4689+
contributors: ObjectContributor[],
4690+
baseDefinition: ServiceObject,
4691+
): ReadonlySet<string> | undefined {
4692+
const owner = contributors.find((c) => c.ownership === 'own')?.definition;
4693+
if (!owner || owner === baseDefinition) return undefined;
4694+
let authored: Set<string> | undefined;
4695+
for (const contrib of contributors) {
4696+
if (contrib.ownership !== 'extend') continue;
4697+
const patches = (contrib.definition as ObjectExtensionBody).fieldPatches;
4698+
if (!patches) continue;
4699+
for (const [name, patch] of Object.entries(patches)) {
4700+
const packagedField = recordFieldOf(owner, name);
4701+
const baseField = recordFieldOf(baseDefinition, name);
4702+
if (!patch || !packagedField || !baseField) continue;
4703+
for (const key of BASE_FIELD_DISPLAY_WHITELIST.field) {
4704+
if (displayKeyOverridesPackagedBase(packagedField, key, baseField[key])) {
4705+
(authored ??= new Set()).add(fieldPatchYieldKey(name, key));
4706+
}
4707+
}
4708+
for (const value of Object.keys(patch.options ?? {})) {
4709+
const packagedOption = optionByValue(packagedField, value);
4710+
const baseOption = optionByValue(baseField, value);
4711+
if (!packagedOption || !baseOption) continue;
4712+
for (const key of BASE_FIELD_DISPLAY_WHITELIST.option) {
4713+
if (displayKeyOverridesPackagedBase(packagedOption, key, baseOption[key])) {
4714+
(authored ??= new Set()).add(fieldPatchYieldKey(name, key, value));
4715+
}
4716+
}
4717+
}
4718+
}
4719+
}
4720+
return authored;
4721+
}
4722+
44864723
/**
44874724
* [ADR-0029 D9.2a, 2026-10-30 note] The `message` / `active` a TENANT base
44884725
* sets on its rules, by name — `undefined` when the fold's base is a code

0 commit comments

Comments
 (0)