diff --git a/.changeset/31678-picklist-by-referrer-package.md b/.changeset/31678-picklist-by-referrer-package.md new file mode 100644 index 00000000000..f17456f383d --- /dev/null +++ b/.changeset/31678-picklist-by-referrer-package.md @@ -0,0 +1,22 @@ +--- +'@objectstack/objectql': patch +'@objectstack/metadata': patch +--- + +fix(objectql)!: a field's picklist resolves from the package that declares the field, and the api endpoint index keeps one item per package and name + +Clause-②: no (narrowing) +Metadata-protocol: none + + + +**BREAKING** for a field whose `picklist` names a list its own package cannot reach (`@objectstack/objectql`). A field's `picklist` now resolves from the package that declares the field: that package's own list, else the one package in its declared dependency closure (`manifest.dependencies`, plus the platform's `sys` packages) that holds the name, else nothing. Two kinds of reference that used to be served now are not: + +- a field of a package whose list only an environment-authored item holds (one created in this environment, bound to no package); +- a field of a package whose list another package holds, when the field's package does not declare a dependency on it. Two packages shipped in one artifact are no exception: a sibling's list needs a declared dependency too. + +Before, either field was served that list's options. After, it is served with no options and its values are refused, and the boot names each one in a warning instead of failing. A package installed after the boot that carries such a reference is refused at install, naming every holder. The fix is one line: add the package that holds the list to the field's package `manifest.dependencies`, or declare the list in the field's own package. + +Unchanged: a field whose package holds the list, or depends on the package that holds it, is served exactly as before; a field written only by an environment-authored body (a tenant overlay, an object created in Studio) resolves the name environment-wide, as before; and a `picklistExtensions` entry still adds its options to the one list its `extend` names in the environment, whether or not its package depends on that list's package. + +`@objectstack/metadata`: the api endpoint index reads its stored items one per package and name, so two packages' same-named api items are no longer collapsed into one before the matcher reads them. A package-less row under a name one package holds is that package's customization and keeps sharing its slot. While each api name has one package holder, every route answers as before. diff --git a/packages/cli/src/utils/picklist-references.boot-parity.test.ts b/packages/cli/src/utils/picklist-references.boot-parity.test.ts index 2109d6933ee..9c96720257c 100644 --- a/packages/cli/src/utils/picklist-references.boot-parity.test.ts +++ b/packages/cli/src/utils/picklist-references.boot-parity.test.ts @@ -138,11 +138,17 @@ describe('[#29898] picklist-reference-unknown — the author-time door and the m const boundCase = (picklist: string) => caseObj({ subject: { type: 'text', label: 'Subject' }, status: { type: 'select', label: 'Status', picklist } }); - /** One artifact: the core body carries the object, the app body declares `parity_status`. */ + /** + * One artifact: the core body carries the object, the app body declares + * `parity_status`. [ADR-0150 D3, child E6; N1 ruled on #31678: the declared + * dependency closure only] Forced edit: the core body declares its + * dependency on the app body — a sibling it does not depend on is outside + * its closure, and the boot refuses that reference. + */ const artifactWith = (picklist: string): AnyRec => ({ manifest: manifest(STACK_ID), packages: [ - { manifest: { ...manifest('com.example.parity.core'), objects: [boundCase(picklist)] } }, + { manifest: { ...manifest('com.example.parity.core'), dependencies: { 'com.example.parity.app': '^1.0.0' }, objects: [boundCase(picklist)] } }, { manifest: { ...manifest('com.example.parity.app'), picklists: [status] } }, ], }); diff --git a/packages/metadata/src/metadata-manager-match-endpoint.test.ts b/packages/metadata/src/metadata-manager-match-endpoint.test.ts index afa77d92cd4..44220474031 100644 --- a/packages/metadata/src/metadata-manager-match-endpoint.test.ts +++ b/packages/metadata/src/metadata-manager-match-endpoint.test.ts @@ -263,3 +263,53 @@ describe('#5089 — MetadataManager.matchEndpoint', () => { }); }); }); + +/** + * [ADR-0150 D4, child E6] The index's item list keeps one slot per + * `(package, name)`, not per bare name: a bare-name map let one package's + * stored `api` item overwrite another package's same-named item before the + * matcher ever saw it. A package-less row under a name one package holds is + * that holder's customization and shares its slot (D4). + */ +describe('the endpoint index keeps one slot per (package, name) (ADR-0150 D4)', () => { + /** A store whose keyed read answers the given rows, in order, the way `sys_metadata` does. */ + function storeOf(rows: Array<{ name: string; data: Record }>): MetadataLoader { + return { + contract: { name: 'rows', protocol: 'datasource:', capabilities: { read: true, write: false } }, + async load() { return { data: null }; }, + async loadMany(type: string) { return type === 'api' ? rows.map((r) => r.data) : []; }, + async loadManyKeyed(type: string) { return type === 'api' ? rows : []; }, + async exists() { return false; }, + async stat() { return null; }, + async list() { return []; }, + } as unknown as MetadataLoader; + } + const A_PATH = { method: 'GET', path: '/api/v1/apps/alpha/tasks' }; + const B_PATH = { method: 'GET', path: '/api/v1/apps/beta/tasks' }; + + it('serves two packages\' same-named api items, each on its own route', async () => { + const manager = new MetadataManager({ formats: ['json'], loaders: [] }); + manager.registerLoader(storeOf([ + { name: 'list_tasks', data: { ...endpoint({ path: A_PATH.path, target: 'a' }), packageId: 'com.acme.alpha' } }, + { name: 'list_tasks', data: { ...endpoint({ path: B_PATH.path, target: 'b' }), packageId: 'com.acme.beta' } }, + ])); + expect((await manager.matchEndpoint(A_PATH))?.endpoint.target).toBe('a'); + expect((await manager.matchEndpoint(B_PATH))?.endpoint.target).toBe('b'); + }); + + it('CONTROL — a package-less row under a name one package holds shares that holder\'s slot: the first one read keeps it', async () => { + const manager = new MetadataManager({ formats: ['json'], loaders: [] }); + manager.registerLoader(storeOf([ + { name: 'list_tasks', data: { ...endpoint({ path: A_PATH.path, target: 'customized' }) } }, + { name: 'list_tasks', data: { ...endpoint({ path: B_PATH.path, target: 'shipped' }), packageId: 'com.acme.alpha' } }, + ])); + expect((await manager.matchEndpoint(A_PATH))?.endpoint.target).toBe('customized'); + expect(await manager.matchEndpoint(B_PATH)).toBeUndefined(); + }); + + it('CONTROL — an environment-authored row whose name no package holds is served', async () => { + const manager = new MetadataManager({ formats: ['json'], loaders: [] }); + manager.registerLoader(storeOf([{ name: 'list_tasks', data: endpoint({ path: A_PATH.path, target: 'env' }) }])); + expect((await manager.matchEndpoint(A_PATH))?.endpoint.target).toBe('env'); + }); +}); diff --git a/packages/metadata/src/metadata-manager.ts b/packages/metadata/src/metadata-manager.ts index e86efc1b2f8..79e0f7a610a 100644 --- a/packages/metadata/src/metadata-manager.ts +++ b/packages/metadata/src/metadata-manager.ts @@ -365,6 +365,23 @@ function redactServedDocument( return peeled ? { ...result.item, ...bookkeeping } : result.item; } +/** + * [ADR-0150 D4, child E6] The package a stored or registered item carries: + * its stored envelope's `packageId` (flat or under the publish envelope), else + * the registry's `_packageId` stamp on the body; `undefined` for an item bound + * to no package (the `sys_metadata` provenance sentinel included). + */ +function indexedItemPackageId(item: unknown): string | undefined { + const peeled = peelStoredEnvelope(item); + const fromEnvelope = (peeled.envelope as { packageId?: unknown }).packageId; + const body = peeled.body as { _packageId?: unknown } | null | undefined; + const stamped = body && typeof body === 'object' ? body._packageId : undefined; + for (const candidate of [fromEnvelope, stamped]) { + if (typeof candidate === 'string' && candidate !== '' && candidate !== 'sys_metadata') return candidate; + } + return undefined; +} + /** * Main metadata manager class. * Implements IMetadataService contract for unified metadata management. @@ -612,7 +629,7 @@ export class MetadataManager implements IMetadataService { // `notifyWatchers` without a cache mutation of their own. // Double invalidation is idempotent, so the overlap is free. this.endpointMatcher = new EndpointMatcher({ - listApiItems: () => this.listForIndex(MetadataManager.ENDPOINT_METADATA_TYPE), + listApiItems: () => this.listForIndex(MetadataManager.ENDPOINT_METADATA_TYPE, { byPackage: true }), logger: this.logger, }); this.subscribe(MetadataManager.ENDPOINT_METADATA_TYPE, () => this.endpointMatcher.invalidate()); @@ -1186,23 +1203,33 @@ export class MetadataManager implements IMetadataService { type: string, items: Map ): Promise { + for (const entry of await this.loaderEntries(loader, type)) { + if (items.has(entry.name)) continue; + items.set(entry.name, entry.data); + } + } + + /** + * Every named item one loader holds for `type`, in the loader's order, each + * with its key: {@link MetadataLoader.loadManyKeyed} where the loader offers + * it, else `loadMany` keyed by each body's own `name` (the pre-#14205 + * reading, for loaders that cannot produce keys). An item with no key is + * left out, as {@link admitLoaderItems} always left it. + */ + private async loaderEntries(loader: MetadataLoader, type: string): Promise> { + const entries: Array<{ name: string; data: unknown }> = []; if (typeof loader.loadManyKeyed === 'function') { - const keyed = await loader.loadManyKeyed(type); - for (const entry of keyed) { + for (const entry of await loader.loadManyKeyed(type)) { if (!entry || typeof entry.name !== 'string' || entry.name === '') continue; - if (items.has(entry.name)) continue; - items.set(entry.name, entry.data); + entries.push({ name: entry.name, data: entry.data }); } - return; + return entries; } - - const loaderItems = await loader.loadMany(type); - for (const item of loaderItems) { + for (const item of await loader.loadMany(type)) { const itemAny = item as { name?: unknown } | null; - if (itemAny && typeof itemAny.name === 'string' && !items.has(itemAny.name)) { - items.set(itemAny.name, item); - } + if (itemAny && typeof itemAny.name === 'string' && itemAny.name !== '') entries.push({ name: itemAny.name, data: item }); } + return entries; } private async readListUncached(type: string): Promise { @@ -1403,7 +1430,8 @@ export class MetadataManager implements IMetadataService { * driver behind a real `DatabaseLoader` makes `matchEndpoint` reject rather * than answer a 404-shaped `undefined`.) */ - private async listForIndex(type: string): Promise { + private async listForIndex(type: string, options?: { byPackage?: boolean }): Promise { + if (options?.byPackage) return this.listForPackageScopedIndex(type); const items = new Map(); const typeStore = this.registry.get(type); @@ -1421,6 +1449,60 @@ export class MetadataManager implements IMetadataService { return Array.from(items.values()); } + /** + * [ADR-0150 D4, child E6] {@link listForIndex} for an index whose items are + * addressed by `(package, name)` — the `api` endpoint index. Same sources, + * same precedence (the in-memory registry first, then each loader in turn, + * the first entry of a slot kept) and the same refusal to swallow a failed + * read; what changes is the SLOT. A bare-name `Map` lets one package's item + * overwrite another package's same-named item before the matcher ever sees + * it, so each slot is `(package, name)` instead: + * + * - an item that carries its package (`packageId` on its stored envelope, or + * the registry's `_packageId` stamp) fills that package's slot; + * - an item that carries none, under a name exactly one package holds here, + * is that holder's customization (ADR-0150 D4: a package-less row bearing + * a package-held name is never a second item), so it shares the holder's + * slot and the precedence above decides between them, as the bare-name + * map did; + * - an item that carries none, under a name no package holds, is the + * environment's own (D1 bucket 4) and fills the environment's slot. + * + * While phase 1 keeps one package holder per `api` name, every slot holds + * what the bare-name map held, so the index answers what it answered. No + * name is resolved here: a request carries no caller package, and the + * matcher keys its routes by METHOD + path (bucket 1). + */ + private async listForPackageScopedIndex(type: string): Promise { + const entries: Array<{ name: string; data: unknown }> = []; + const typeStore = this.registry.get(type); + if (typeStore) { + for (const [name, data] of typeStore) entries.push({ name, data }); + } + for (const loader of this.loaders.values()) { + // No try/catch, on purpose — see {@link listForIndex}. + entries.push(...(await this.loaderEntries(loader, type))); + } + + const holders = new Map>(); + for (const { name, data } of entries) { + const packageId = indexedItemPackageId(data); + if (packageId === undefined) continue; + let held = holders.get(name); + if (!held) holders.set(name, (held = new Set())); + held.add(packageId); + } + + const slots = new Map(); + for (const { name, data } of entries) { + const held = holders.get(name); + const slotPackage = indexedItemPackageId(data) ?? (held?.size === 1 ? [...held][0] : ''); + const slot = `${slotPackage}\u0000${name}`; + if (!slots.has(slot)) slots.set(slot, data); + } + return Array.from(slots.values()); + } + /** * Unregister/remove a metadata item by type and name. * Deletes from database-backed loaders only (same rationale as register()). @@ -2197,7 +2279,9 @@ export class MetadataManager implements IMetadataService { if (packageEndpointNames.size === 0 && packageFlowNames.size === 0) return []; const bodies = (items: unknown[]) => items.map((item) => peelStoredEnvelope(item).body); - const endpoints = bodies(await this.listForIndex(MetadataManager.ENDPOINT_METADATA_TYPE)) as AnonymousFlowDoorCandidate[]; + const endpoints = bodies( + await this.listForIndex(MetadataManager.ENDPOINT_METADATA_TYPE, { byPackage: true }), + ) as AnonymousFlowDoorCandidate[]; const flows = bodies(await this.listForIndex(MetadataManager.FLOW_METADATA_TYPE)) as ElevatedFlowCandidate[]; const errors: Array<{ type: string; name: string; message: string }> = []; diff --git a/packages/objectql/src/engine-picklist.test.ts b/packages/objectql/src/engine-picklist.test.ts index b23a5f33100..17c46336216 100644 --- a/packages/objectql/src/engine-picklist.test.ts +++ b/packages/objectql/src/engine-picklist.test.ts @@ -100,10 +100,16 @@ const CORE = { objects: [account], }; -/** A second package: adds a value to the list and binds a second object to it. */ +/** + * A second package: adds a value to the list and binds a second object to it. + * It declares its dependency on CORE: a field's `picklist` resolves from its + * package's declared closure (ADR-0150 D3), so binding a field to another + * package's list takes the dependency. + */ const HEALTH = { id: 'com.test.picklist.health', name: 'health', + dependencies: { 'com.test.picklist.core': '^1.0.0' }, picklistExtensions: [HEALTHCARE_EXTENSION], objects: [lead], }; @@ -169,7 +175,10 @@ describe('picklist — the served shape', () => { describe('picklist — load order', () => { it('an object registered BEFORE its list still resolves once the list arrives', async () => { const engine = await bootEngine(); - engine.registry.registerObject(account as any, 'com.test.early'); + // The object is the list's own package's (a field's `picklist` resolves + // from its package's declared closure, ADR-0150 D3); only the ORDER is + // under test. + engine.registry.registerObject(account as any, 'com.test.core'); // Read before the list exists: nothing to serve yet … expect((engine.registry.getObject('pk_account')!.fields.industry as any).options).toBeUndefined(); // … then the list and an extension land, in the "wrong" order. @@ -360,3 +369,115 @@ describe('picklist — a stale served copy never stands in for the list', () => expect(folded.fields[1]).toBe(body.fields[1]); }); }); + +/** + * [ADR-0150 D3/D4, child E6] A field's `picklist` resolves through the + * package-scoped resolver from the package that WROTE the reference: its own + * list, else the unique holder in its declared dependency closure (plus + * `sys`), else a refusal naming every candidate. Phase 1 keeps one holder per + * name, so what moves is the declared narrowing alone. + */ +describe('picklist — resolved from the package that writes the reference (ADR-0150 D3)', () => { + const ENV_LIST = { name: 'env_tier', label: 'Tier', options: [{ label: 'Gold', value: 'gold' }] }; + const member = (picklist: string) => ({ + name: 'pk_member', + label: 'Member', + fields: { + name: { name: 'name', label: 'Name', type: 'text' as const }, + tier: { name: 'tier', label: 'Tier', type: 'select' as const, picklist }, + }, + }); + + it('D3 (a): a package field whose list only the environment holds is served with no options, and its values are refused', async () => { + const engine = await bootEngine(); + // An environment-authored list: bound to no package (the bare slot). + engine.registry.registerItem('picklist', { ...ENV_LIST }, 'name'); + engine.registerApp({ id: 'com.test.pkg', name: 'pkg', objects: [member('env_tier')] }); + + const field: any = engine.registry.getObject('pk_member')!.fields.tier; + expect(field.picklist).toBe('env_tier'); + expect(field.options).toBeUndefined(); + const verdict = engine.registry.picklistReferenceVerdict('env_tier', 'com.test.pkg'); + expect(verdict).toMatchObject({ status: 'refused', reason: 'outside-closure', candidates: [{ kind: 'environment' }] }); + const err = await refusal(engine.insert('pk_member', { name: 'M', tier: 'gold' }, sys)); + expect(err.fields[0]).toMatchObject({ field: 'tier' }); + // Named for the boot's warning (never a boot refusal), not as an unresolved reference. + expect(engine.registry.findUnresolvedPicklistReferences()).toEqual([]); + expect(engine.registry.findOutsideClosurePicklistReferences()).toEqual([ + expect.objectContaining({ object: 'pk_member', field: 'tier', picklist: 'env_tier', packageId: 'com.test.pkg' }), + ]); + }); + + it('a package field whose list a package OUTSIDE its declared closure holds is refused, naming that package', async () => { + const engine = await bootEngine(); + engine.registerApp({ id: 'com.test.lists', name: 'lists', picklists: [{ ...ENV_LIST }] }); + engine.registerApp({ id: 'com.test.pkg', name: 'pkg', objects: [member('env_tier')] }); + + expect((engine.registry.getObject('pk_member')!.fields.tier as any).options).toBeUndefined(); + // A refused reference, named for the boot's warning — never a boot refusal (N2). + expect(engine.registry.findUnresolvedPicklistReferences()).toEqual([]); + const [outside] = engine.registry.findOutsideClosurePicklistReferences(); + expect(outside).toMatchObject({ object: 'pk_member', field: 'tier', packageId: 'com.test.pkg' }); + expect(outside.refusal).toContain('package "com.test.lists"'); + }); + + it('CONTROL — the same field, its package declaring the holder as a dependency, is served the list', async () => { + const engine = await bootEngine(); + engine.registerApp({ id: 'com.test.lists', name: 'lists', picklists: [{ ...ENV_LIST }] }); + engine.registerApp({ + id: 'com.test.pkg', name: 'pkg', dependencies: { 'com.test.lists': '^1.0.0' }, objects: [member('env_tier')], + }); + expect(values(engine.registry.getObject('pk_member')!.fields.tier)).toEqual(['gold']); + expect(engine.registry.findUnresolvedPicklistReferences()).toEqual([]); + }); + + it('CONTROL — a referrer with no package (a body only the environment writes) is served the environment\'s list, as before', async () => { + const engine = await bootEngine(); + engine.registry.registerItem('picklist', { ...ENV_LIST }, 'name'); + const body = member('env_tier'); + // A body this registry never saw: no packaged layer wrote its reference. + const folded: any = engine.registry.foldObjectExtendersOnto('pk_member', body); + expect(values(folded.fields.tier)).toEqual(['gold']); + expect(engine.registry.resolvePicklistOptions('env_tier')!.map((o) => o.value)).toEqual(['gold']); + }); + + // [epic seat review on #31731] An owner and an extender in different + // packages both write the field's reference: neither is picked by fold + // order. The field is served only when every referrer reaches the same list. + it('two packages writing one field\'s reference: served no options unless BOTH reach the list (no fold-order pick)', async () => { + const engine = await bootEngine(); + engine.registerApp({ id: 'com.test.lists', name: 'lists', picklists: [{ ...ENV_LIST }] }); + // The owner does not depend on the list's package; the extender (folded LAST) does. + engine.registerApp({ id: 'com.test.pkg', name: 'pkg', objects: [member('env_tier')] }); + engine.registerApp({ + id: 'com.test.ext', name: 'ext', dependencies: { 'com.test.lists': '^1.0.0' }, + objectExtensions: [{ extend: 'pk_member', fields: { tier: { name: 'tier', type: 'select', picklist: 'env_tier' } } }], + }); + expect((engine.registry.getObject('pk_member')!.fields.tier as any).options).toBeUndefined(); + expect(engine.registry.findOutsideClosurePicklistReferences()).toEqual([ + expect.objectContaining({ object: 'pk_member', field: 'tier', packageId: 'com.test.pkg' }), + ]); + }); + + it('CONTROL — the same owner and extender, both depending on the list\'s package, are served the list', async () => { + const engine = await bootEngine(); + engine.registerApp({ id: 'com.test.lists', name: 'lists', picklists: [{ ...ENV_LIST }] }); + engine.registerApp({ + id: 'com.test.pkg', name: 'pkg', dependencies: { 'com.test.lists': '^1.0.0' }, objects: [member('env_tier')], + }); + engine.registerApp({ + id: 'com.test.ext', name: 'ext', dependencies: { 'com.test.lists': '^1.0.0' }, + objectExtensions: [{ extend: 'pk_member', fields: { tier: { name: 'tier', type: 'select', picklist: 'env_tier' } } }], + }); + expect(values(engine.registry.getObject('pk_member')!.fields.tier)).toEqual(['gold']); + expect(engine.registry.findUnresolvedPicklistReferences()).toEqual([]); + }); + + it('a package\'s `picklistExtensions` target resolves caller-less: it extends the one holder\'s list, dependency or not', async () => { + const engine = await bootEngine(); + engine.registerApp(CORE); + engine.registerApp({ id: 'com.test.addon', name: 'addon', picklistExtensions: [HEALTHCARE_EXTENSION] }); + expect(values(engine.registry.getObject('pk_account')!.fields.industry)).toEqual(['technology', 'finance', 'healthcare']); + expect(engine.registry.findOrphanPicklistExtensions()).toEqual([]); + }); +}); diff --git a/packages/objectql/src/manifest-service-residual-objects.test.ts b/packages/objectql/src/manifest-service-residual-objects.test.ts index 52d0db388e0..ad760f358c6 100644 --- a/packages/objectql/src/manifest-service-residual-objects.test.ts +++ b/packages/objectql/src/manifest-service-residual-objects.test.ts @@ -216,9 +216,13 @@ describe('ADR-0130 D4 — the manifest service registers the residual\'s objects expect(acmePackageIds(ql)).toEqual([]); }); + // [ADR-0150 D3, child E6; N1 ruled on #31678: the declared dependency + // closure only] The residual names the body that holds the list among its + // dependencies — forced edit: a same-artifact sibling it does not depend on + // is outside its closure, and its list is refused. it('a residual object whose field names a picklist a BODY declares is served with that list', async () => { const { kernel } = await boot(registering('app', [ - residualStack(noteObj(statusField), {}, { picklists: [statusList()] }), + residualStack(noteObj(statusField), { manifest: { ...app, id: RELEASE_ID, dependencies: { [SERVICE_ID]: '^2.4.0' } } }, { picklists: [statusList()] }), ])); const ql = engineOf(kernel); expect(ql.registry.getObjectOwner('acme_note')?.packageId).toBe(RELEASE_ID); @@ -736,4 +740,22 @@ describe('[ADR-0130 D4, epic #31527 R2] the residual owner\'s declared dependenc expect(acmePackageIds(ql)).not.toContain(RELEASE_ID); expect(packageResolutionClosure(ql.registry, RELEASE_ID).has(SERVICE_ID)).toBe(true); }); + + // [ADR-0150 D3] The install judge reads the closure through a view that + // overlays the pending artifact's manifests; that view must hand the walk the + // registered residual owner's dependencies too, or a package that reaches a + // list only THROUGH the residual owner is refused at install. + it('after start(), a package depending on the residual owner reaches the list its dependency holds', async () => { + const stack = residualStack(noteObj(), {}, { picklists: [statusList()] }); + (stack as { manifest: Record }).manifest.dependencies = { [SERVICE_ID]: '^2.0.0' }; + const { kernel } = await boot(registering('test.residual-deps', [stack])); + const late = payload({ + manifest: { id: 'com.example.late', name: 'late', namespace: 'late', version: '1.0.0', type: 'app', dependencies: { [RELEASE_ID]: '^1.0.0' } }, + objects: [{ name: 'late_ticket', label: 'Ticket', sharingModel: 'private', fields: statusField }], + }); + await (kernel.getService('manifest') as ManifestService).register(late); + const ql = engineOf(kernel); + expect(ql.registry.getObjectOwner('late_ticket')?.packageId).toBe('com.example.late'); + expect(ql.registry.resolvePicklistOptions('acme_status', 'com.example.late')?.map((o) => o.value)).toEqual(['open']); + }); }); diff --git a/packages/objectql/src/picklist-resolution.ts b/packages/objectql/src/picklist-resolution.ts index f011ed0c574..086e1f31b70 100644 --- a/packages/objectql/src/picklist-resolution.ts +++ b/packages/objectql/src/picklist-resolution.ts @@ -138,11 +138,28 @@ export function mergePicklistOptions(contributions: readonly PicklistContributio return merged; } -function resolveField(field: unknown, resolve: (picklist: string) => readonly PicklistOptionLike[] | undefined): unknown { +/** + * How a served body asks for one field's list: the picklist name, and the + * field that names it (its key in a name-keyed `fields`, or an array entry's + * `name`). The field is what tells the registry WHO wrote the reference, so + * the name resolves from that author's package (ADR-0150 D3, child E6). + */ +export type PicklistFieldResolver = ( + picklist: string, + field: string | undefined, +) => readonly PicklistOptionLike[] | undefined; + +/** An array-spelled field's `name`, when it carries one. */ +function fieldNameOf(field: unknown): string | undefined { + const name = field && typeof field === 'object' ? (field as { name?: unknown }).name : undefined; + return typeof name === 'string' && name !== '' ? name : undefined; +} + +function resolveField(field: unknown, fieldName: string | undefined, resolve: PicklistFieldResolver): unknown { if (!field || typeof field !== 'object') return field; const picklist = (field as { picklist?: unknown }).picklist; if (typeof picklist !== 'string' || picklist.length === 0) return field; - const options = resolve(picklist); + const options = resolve(picklist, fieldName); if (options) { const resolved = options.map((o) => ({ ...o })); // Marked as derived unless the body brought `options` of its own: a field @@ -169,7 +186,7 @@ function resolveField(field: unknown, resolve: (picklist: string) => readonly Pi */ export function resolvePicklistFieldsOnto( body: T, - resolve: (picklist: string) => readonly PicklistOptionLike[] | undefined, + resolve: PicklistFieldResolver, ): T { if (!body || typeof body !== 'object') return body; const fields = (body as { fields?: unknown }).fields; @@ -178,15 +195,33 @@ export function resolvePicklistFieldsOnto( !!f && typeof f === 'object' && typeof (f as { picklist?: unknown }).picklist === 'string'; if (Array.isArray(fields)) { if (!fields.some(bound)) return body; - return { ...(body as object), fields: fields.map((f) => resolveField(f, resolve)) } as T; + return { + ...(body as object), + fields: fields.map((f) => resolveField(f, fieldNameOf(f), resolve)), + } as T; } const entries = Object.entries(fields as Record); if (!entries.some(([, f]) => bound(f))) return body; const next: Record = {}; - for (const [name, f] of entries) next[name] = resolveField(f, resolve); + for (const [name, f] of entries) next[name] = resolveField(f, name, resolve); return { ...(body as object), fields: next } as T; } +/** + * A field's picklist reference that resolves to no list from its package — + * nothing holds the name, or the package-scoped resolver refused it + * (ADR-0150 D3: `refusal` is that refusal's own sentence, every candidate + * named, carried verbatim). + */ +export type UnresolvedPicklistReference = PicklistReference & { readonly refusal?: string }; + +/** A `picklistExtensions` entry whose target resolves to no list from its package (as above). */ +export type UnresolvedPicklistExtension = OrphanPicklistExtension & { readonly refusal?: string }; + +function refusalSuffix(refusal: string | undefined): string { + return refusal ? ` (${refusal})` : ''; +} + /** * The load-time refusal for picklist names nothing declares — every field * that references one, and every `picklistExtensions` entry that extends one, @@ -198,16 +233,18 @@ export function resolvePicklistFieldsOnto( * arrives, and the values an author added would silently go nowhere. */ export function describeUnresolvedPicklistReferences( - unresolved: readonly PicklistReference[], - orphanExtensions: readonly OrphanPicklistExtension[] = [], + unresolved: readonly UnresolvedPicklistReference[], + orphanExtensions: readonly UnresolvedPicklistExtension[] = [], ): PicklistMetadataError | undefined { if (unresolved.length === 0 && orphanExtensions.length === 0) return undefined; const lines = [ ...unresolved.map( - (r) => `field '${r.object}.${r.field}' (${describePackage(r.packageId)}) references picklist '${r.picklist}'`, + (r) => `field '${r.object}.${r.field}' (${describePackage(r.packageId)}) references picklist '${r.picklist}'` + + refusalSuffix(r.refusal), ), ...orphanExtensions.map( - (e) => `a \`picklistExtensions\` entry (${describePackage(e.packageId)}) extends picklist '${e.picklist}'`, + (e) => `a \`picklistExtensions\` entry (${describePackage(e.packageId)}) extends picklist '${e.picklist}'` + + refusalSuffix(e.refusal), ), ]; return picklistMetadataError( diff --git a/packages/objectql/src/plugin-picklist-boot-audit.test.ts b/packages/objectql/src/plugin-picklist-boot-audit.test.ts index 937a65b1798..e136d7ddb55 100644 --- a/packages/objectql/src/plugin-picklist-boot-audit.test.ts +++ b/packages/objectql/src/plugin-picklist-boot-audit.test.ts @@ -82,7 +82,10 @@ describe('the picklist boot audit', () => { it('boots when the list arrives from a package registered LATER in the same boot', async () => { const { kernel, use } = kernelWith( new ObjectQLPlugin(), - registering('app', [{ id: 'com.test.boot.app', name: 'app', objects: [ACCOUNT] }]), + // The app declares its dependency on the package whose list its field + // names: a field's `picklist` resolves from its package's declared + // closure (ADR-0150 D3). + registering('app', [{ id: 'com.test.boot.app', name: 'app', dependencies: { 'com.test.boot.lists': '^1.0.0' }, objects: [ACCOUNT] }]), registering('lists', [{ id: 'com.test.boot.lists', name: 'lists', picklists: [INDUSTRY] }]), ); await use(); @@ -118,7 +121,8 @@ describe('the picklist boot audit', () => { await use(); await kernel.bootstrap(); const manifest = kernel.getService('manifest'); - await manifest.register({ id: 'com.test.late', name: 'late', objects: [ACCOUNT] }); + // Naming a registered list of another package takes the dependency (ADR-0150 D3). + await manifest.register({ id: 'com.test.late', name: 'late', dependencies: { 'com.test.boot.lists': '^1.0.0' }, objects: [ACCOUNT] }); await manifest.register({ id: 'com.test.late2', name: 'late2', picklists: [{ name: 'tier', label: 'Tier', options: [{ label: 'Gold', value: 'gold' }] }], @@ -129,3 +133,114 @@ describe('the picklist boot audit', () => { expect(servedValues(ql, 'pb_member', 'tier')).toEqual(['gold']); }); }); + +/** + * [ADR-0150 D3 (a), child E6] A packaged field whose list only an + * environment-authored item holds: the package-scoped resolver refuses it, and + * that refusal is a refused REFERENCE (no options served, every value refused), + * never a refused boot. An artifact arriving after the seal with such a + * reference is refused by the install door, naming the environment. + */ +describe('the picklist boot audit — a list only the environment holds (ADR-0150 D3 (a))', () => { + const ENV_LIST = { name: 'industry', label: 'Industry', options: [{ label: 'Technology', value: 'technology' }] }; + /** Registers the environment's own list (no package) during init, as a stored row's hydration does. */ + const environmentList = { + name: 'env-list', + dependencies: ['com.objectstack.engine.objectql'], + init: async (ctx: PluginContext) => { + ctx.getService('objectql').registry.registerItem('picklist', { ...ENV_LIST }, 'name'); + }, + }; + + it('boots, serving the package field with no options', async () => { + const { kernel, use } = kernelWith( + new ObjectQLPlugin(), + environmentList, + registering('app', [{ id: 'com.test.boot.app', name: 'app', objects: [ACCOUNT] }]), + ); + await use(); + await kernel.bootstrap(); + const ql = kernel.getService('objectql'); + expect(servedValues(ql, 'pb_account', 'industry')).toEqual([]); + expect(ql.registry.findOutsideClosurePicklistReferences()).toEqual([ + expect.objectContaining({ object: 'pb_account', field: 'industry', packageId: 'com.test.boot.app' }), + ]); + }); + + it('after the boot, an artifact naming it is refused before ANY of it registers, naming the environment', async () => { + const { kernel, use } = kernelWith(new ObjectQLPlugin(), environmentList); + await use(); + await kernel.bootstrap(); + const manifest = kernel.getService('manifest'); + expect(() => manifest.register({ id: 'com.test.late', name: 'late', objects: [ACCOUNT] })) + .toThrow(/references picklist 'industry' \(The picklist "industry" is held outside the declared dependency closure of package "com\.test\.late": the environment/); + expect(kernel.getService('objectql').registry.getObject('pb_account')).toBeUndefined(); + }); + + it('CONTROL — an artifact naming a list a package it depends on holds registers after the boot', async () => { + const { kernel, use } = kernelWith(new ObjectQLPlugin(), registering('lists', [{ id: 'com.test.boot.lists', name: 'lists', picklists: [ENV_LIST] }])); + await use(); + await kernel.bootstrap(); + const manifest = kernel.getService('manifest'); + await manifest.register({ id: 'com.test.late', name: 'late', dependencies: { 'com.test.boot.lists': '^1.0.0' }, objects: [ACCOUNT] }); + expect(servedValues(kernel.getService('objectql'), 'pb_account', 'industry')).toEqual(['technology']); + }); + + // [N1 ruled on #31678; ruling N2] A package holder outside the declared + // closure is refused the same way: the boot warns, it never fails. + it('boots when the list is held by a package the field\'s package does not depend on, serving no options', async () => { + const { kernel, use } = kernelWith( + new ObjectQLPlugin(), + registering('lists', [{ id: 'com.test.boot.lists', name: 'lists', picklists: [ENV_LIST] }]), + registering('app', [{ id: 'com.test.boot.app', name: 'app', objects: [ACCOUNT] }]), + ); + await use(); + await kernel.bootstrap(); + const ql = kernel.getService('objectql'); + expect(servedValues(ql, 'pb_account', 'industry')).toEqual([]); + expect(ql.registry.findUnresolvedPicklistReferences()).toEqual([]); + expect(ql.registry.findOutsideClosurePicklistReferences()).toEqual([ + expect.objectContaining({ object: 'pb_account', field: 'industry', packageId: 'com.test.boot.app' }), + ]); + }); +}); + +/** + * [ADR-0150 D3, child E6; epic seat review on #31731] After the seal, the + * install door judges each reference of a multi-package artifact from the + * package that writes it: a list its OWN manifest declares is its own, and a + * list a SIBLING manifest declares is reached only the way R reaches any + * holder — through the referrer's declared dependency closure. No + * artifact-wide "some member declares it" pass. ⛔ The refusal pin below is the + * N1 arm (a same-artifact sibling with no declared dependency), pending the + * maintainer's ruling on #31678. + */ +describe('the picklist install door — a sibling in the same artifact (ADR-0150 D3)', () => { + const suite = (app: Record) => ({ + id: 'com.test.suite', + version: '1.0.0', + packages: [ + { manifest: { id: 'com.test.suite.lists', name: 'lists', version: '1.0.0', type: 'module', picklists: [INDUSTRY] } }, + { manifest: { id: 'com.test.suite.app', name: 'app', version: '1.0.0', type: 'module', objects: [ACCOUNT], ...app } }, + ], + }); + + it('refuses a reference to a list only a sibling it does not depend on declares, naming that sibling', async () => { + const { kernel, use } = kernelWith(new ObjectQLPlugin()); + await use(); + await kernel.bootstrap(); + const manifest = kernel.getService('manifest'); + await expect(Promise.resolve().then(() => manifest.register(suite({})))) + .rejects.toThrow(/references picklist 'industry' \(The picklist "industry" is held outside the declared dependency closure of package "com\.test\.suite\.app": package "com\.test\.suite\.lists"/); + expect(kernel.getService('objectql').registry.getObject('pb_account')).toBeUndefined(); + }); + + it('CONTROL — the same artifact registers when the app depends on its sibling', async () => { + const { kernel, use } = kernelWith(new ObjectQLPlugin()); + await use(); + await kernel.bootstrap(); + const manifest = kernel.getService('manifest'); + await manifest.register(suite({ dependencies: { 'com.test.suite.lists': '^1.0.0' } })); + expect(servedValues(kernel.getService('objectql'), 'pb_account', 'industry')).toEqual(['technology']); + }); +}); diff --git a/packages/objectql/src/plugin.ts b/packages/objectql/src/plugin.ts index b152ad5270a..c78d6f2961b 100644 --- a/packages/objectql/src/plugin.ts +++ b/packages/objectql/src/plugin.ts @@ -951,15 +951,38 @@ export class ObjectQLPlugin implements Plugin { // against the registry or against a list the artifact itself declares. // A refused install registers nothing. if (this.picklistVocabularySealed) { - const declared = new Set(); - for (const manifest of ordered) for (const name of collectManifestPicklistNames(manifest)) declared.add(name); - const known = (name: string) => declared.has(name) || ql.registry.resolvePicklistOptions(name) !== undefined; - const unresolved = ordered - .flatMap((manifest) => collectManifestPicklistReferences(manifest, artifactPackageId(manifest))) - .filter((ref) => !known(ref.picklist)); - const orphans = ordered - .flatMap((manifest) => collectManifestPicklistExtensions(manifest, artifactPackageId(manifest))) - .filter((ext) => !known(ext.picklist)); + // [ADR-0150 D3, child E6] A reference is reached the way the served + // field will reach it: from the package that writes it, through the + // package-scoped resolver, against a registry view holding the + // artifact's manifests — their declared dependencies and the lists + // each one declares. A list the reference's OWN manifest declares is + // its own; every other list, a sibling's in this artifact included, + // is R's to answer (epic seat review on #31731: no artifact-wide + // "declared somewhere" pass). A reference R refuses — the + // environment's own list included (D3 (a)) — is refused here, + // loudly, naming every candidate. An extension's target is a + // contribution, judged caller-less (epic seat ruling X on #31678; + // `SchemaRegistry.picklistContributions`). + const judge = ( + ref: R, + own: ReadonlySet, + caller: string | null | undefined, + ): R & { refusal?: string } | undefined => { + if (own.has(ref.picklist)) return undefined; + const verdict = ql.registry.picklistReferenceVerdict(ref.picklist, caller, ordered); + if (verdict.status === 'resolved') return undefined; + return verdict.status === 'refused' ? { ...ref, refusal: verdict.message } : ref; + }; + const unresolved = ordered.flatMap((manifest) => { + const own = collectManifestPicklistNames(manifest); + return collectManifestPicklistReferences(manifest, artifactPackageId(manifest)) + .flatMap((ref) => judge(ref, own, ref.packageId) ?? []); + }); + const orphans = ordered.flatMap((manifest) => { + const own = collectManifestPicklistNames(manifest); + return collectManifestPicklistExtensions(manifest, artifactPackageId(manifest)) + .flatMap((ext) => judge(ext, own, null) ?? []); + }); const refusal = describeUnresolvedPicklistReferences(unresolved, orphans); if (refusal) throw refusal; } @@ -1209,6 +1232,22 @@ export class ObjectQLPlugin implements Plugin { this.ql?.registry.findOrphanPicklistExtensions() ?? [], ); if (unresolvedPicklists) throw unresolvedPicklists; + // [ADR-0150 D3, child E6] A packaged reference whose every holder is + // outside its package's declared dependency closure — an + // environment-authored list (D3 (a)) or a package it does not depend + // on, a same-artifact sibling included (N1, ruled on #31678) — is + // refused by the package-scoped resolver: the field is served with no + // options and the record validator refuses its values. A refused + // REFERENCE, never a refused boot (ruling N2), so it is named here, + // once per reference, in the resolver's own words, and the boot goes on. + for (const ref of this.ql?.registry.findOutsideClosurePicklistReferences() ?? []) { + ctx.logger.warn( + `[ObjectQLPlugin] Field '${ref.object}.${ref.field}' of package '${ref.packageId}' is served with no ` + + `options and refuses every value: ${ref.refusal}`, + { object: ref.object, field: ref.field, packageId: ref.packageId, picklist: ref.picklist }, + ); + } + this.picklistVocabularySealed = true; // [#24400] A top-level action bound by `objectName` to an object no // package registers fails the boot, naming the action, its package and diff --git a/packages/objectql/src/registry.ts b/packages/objectql/src/registry.ts index 8d88a0518cc..cd02a893c3c 100644 --- a/packages/objectql/src/registry.ts +++ b/packages/objectql/src/registry.ts @@ -141,6 +141,7 @@ import { // pure, so the registry and the engine plugin's load-time audit read one // spelling of each. See the module header. import { + collectManifestPicklistNames, collectPicklistReferences, duplicatePicklistValueError, findDuplicatePicklistValue, @@ -148,8 +149,19 @@ import { resolvePicklistFieldsOnto, type PicklistContribution, type PicklistOptionLike, - type PicklistReference, + type UnresolvedPicklistExtension, + type UnresolvedPicklistReference, } from './picklist-resolution.js'; +// [ADR-0150 D3, child E6] The ONE answer to "which package's list does this +// bare picklist name mean, for this referrer" — R's. ⛔ No second closure walk +// and no first-registered fallback here: every picklist read below asks it. +import { + resolvePackageScopedName, + type PackageScopedHolder, + type PackageScopedRefusal, + type PackageScopedRegistry, + type PackageScopedResolution, +} from './package-scoped-resolver.js'; import { standaloneActionOwnerKey, isObjectLessActionKey } from './action-governance.js'; import { recordCurrencySummaryRefusal } from './record-currency-aggregate-door.js'; @@ -571,6 +583,67 @@ function fieldPatchYieldKey(field: string, key: string, option?: string): string return option === undefined ? `${field}\u0000${key}` : `${field}\u0000options\u0000${option}\u0000${key}`; } +/** A picklist item as the registry stores it: the two keys the merge reads. */ +type PicklistItemLike = { options?: PicklistOptionLike[]; _packageId?: string }; + +/** + * [ADR-0150 D3, child E6] Who wrote one field's picklist reference: every + * package whose own layer declares it, in fold order, or `[null]` — one caller + * with no package — when no packaged layer does. + */ +type PicklistReferrer = (field: string | undefined, picklist: string) => readonly (string | null)[]; + +/** Every reference is the environment's: a body no packaged layer declares. */ +const NO_PACKAGE_REFERRER: PicklistReferrer = () => [null]; + +/** Are two package-scoped holders the same one? */ +function sameHolder(a: PackageScopedHolder, b: PackageScopedHolder): boolean { + if (a.kind === 'package') return b.kind === 'package' && a.packageId === b.packageId; + return a.kind === b.kind; +} + +/** The `picklist` a body's field declares (name-keyed or array-spelled), when it declares one. */ +function declaredPicklistOf(body: unknown, field: string): string | undefined { + const fields = isPlainRecord(body) ? body.fields : undefined; + let declared: unknown; + if (Array.isArray(fields)) { + declared = fields.find((f) => isPlainRecord(f) && f.name === field); + } else if (isPlainRecord(fields) && Object.prototype.hasOwnProperty.call(fields, field)) { + declared = fields[field]; + } + const picklist = isPlainRecord(declared) ? declared.picklist : undefined; + return typeof picklist === 'string' && picklist !== '' ? picklist : undefined; +} + +/** + * [ADR-0150 D3, child E6] The referrers of each picklist reference a served + * body carries, read from the contributors that fold into it: EVERY packaged + * layer (the owner, then each extension) whose own declaration names that same + * list on that field, each package once. Several layers can write one + * reference; none of them is picked over the others (epic seat review on + * #31731): the field is served a list only when every one of them reaches the + * same holder ({@link SchemaRegistry.resolvePicklistFields}). A reference no + * packaged layer writes came from an environment-authored body — a tenant + * overlay, a stored row, an object created in this environment — and resolves + * as the environment's (`null`), never from the package that body customizes + * (D3). + */ +function picklistReferrerOf(contributors: readonly ObjectContributor[] | undefined): PicklistReferrer { + if (!contributors || contributors.length === 0) return NO_PACKAGE_REFERRER; + const packaged = [ + ...contributors.filter((c) => c.ownership === 'own'), + ...contributors.filter((c) => c.ownership === 'extend'), + ].filter((c) => !isTenantAuthored(c.definition)); + return (field, picklist) => { + if (field === undefined) return [null]; + const referrers = new Set(); + for (const c of packaged) { + if (declaredPicklistOf(c.definition, field) === picklist) referrers.add(c.packageId ?? null); + } + return referrers.size > 0 ? [...referrers] : [null]; + }; +} + /** A field of an object body's name-keyed `fields`, when it is a record. */ function recordFieldOf(body: unknown, name: string): Record | undefined { const fields = isPlainRecord(body) ? body.fields : undefined; @@ -5630,7 +5703,7 @@ export class SchemaRegistry { // A picklist-bound field is served with its list's options resolved onto // it — here, in the fold every object read and the write door share, so // the set a client is offered and the set a write is judged by are one. - return this.finishServedObject(merged, layer); + return this.finishServedObject(merged, layer, picklistReferrerOf(contributors)); } /** @@ -5792,8 +5865,12 @@ export class SchemaRegistry { * packages' alone: a tenant's action is not something a code package * ships, and `getArtifactItem('object')` answers exactly that question. */ - private finishServedObject(body: T, layer: ServedObjectLayer = 'served'): T { - return this.attachBoundActions(this.resolvePicklistFields(body), layer); + private finishServedObject( + body: T, + layer: ServedObjectLayer = 'served', + referrerOf: PicklistReferrer = NO_PACKAGE_REFERRER, + ): T { + return this.attachBoundActions(this.resolvePicklistFields(body, referrerOf), layer); } /** @@ -6348,7 +6425,7 @@ export class SchemaRegistry { const contributors = withheld?.kept ?? listed; const served = withheld ? withoutWithheldMembers(base as unknown as ServiceObject, withheld) : base as unknown as ServiceObject; if (!contributors || !contributors.some((c) => c.ownership === 'extend')) { - return this.finishServedObject(served as unknown as T); + return this.finishServedObject(served as unknown as T, 'served', picklistReferrerOf(contributors)); } return this.foldExtendersOntoDefinition( contributors, @@ -9758,19 +9835,94 @@ export class SchemaRegistry { /** * The resolved options of a picklist — its own, then every extension's, in - * registration order — or `undefined` when no picklist of that name is - * registered. Extensions held for an unregistered list resolve nothing on - * their own: a list exists only once its owner declares it. - */ - resolvePicklistOptions(name: string): PicklistOptionLike[] | undefined { - const contributions = this.picklistContributions(name); + * registration order — or `undefined` when the name reaches no list. + * Extensions held for an unregistered list resolve nothing on their own: a + * list exists only once its owner declares it. + * + * [ADR-0150 D3/D4, child E6] The name is resolved by R's package-scoped + * resolver from `callerPackageId`, the package that WROTE the reference: its + * own list, else the unique holder in its declared dependency closure (plus + * `sys`), else nothing — a refusal ({@link picklistReferenceVerdict} says + * which). Omitted, `null` or `''` is a caller with no package (an + * environment-authored body, a context-free door): the environment's own + * list first, else the unique package holder. That is what the bare read + * answered while phase 1 keeps one holder per name, so every caller-less + * reader keeps its answer. + */ + resolvePicklistOptions(name: string, callerPackageId?: string | null): PicklistOptionLike[] | undefined { + const contributions = this.picklistContributions(name, callerPackageId); if (!contributions.some((c) => c.kind === 'picklist')) return undefined; return mergePicklistOptions(contributions); } /** - * Every field of every packaged object that names a picklist no registered - * package declares — the load-time audit's input. + * [ADR-0150 D3, child E6] R's verdict on one picklist reference: `resolved`, + * `not-found` (nothing holds the name) or `refused` (holders exist and none + * is reachable from `callerPackageId`, or more than one is). The audits + * below read it, so the boot, the install door and the served field share + * one answer. + */ + picklistReferenceVerdict( + name: string, + callerPackageId?: string | null, + pendingManifests?: readonly unknown[], + ): PackageScopedResolution { + const registry = pendingManifests && pendingManifests.length > 0 ? this.withPendingManifests(pendingManifests) : this; + return resolvePackageScopedName(registry, { type: 'picklist', name, callerPackageId }); + } + + /** + * The registry as R reads it once `manifests` (an artifact the install door + * is judging, not yet registered) are installed: each manifest answers + * `getPackage` for its own id — its `dependencies` and `namespace`, which is + * all the closure reads — ahead of an installed version of it, and each + * `picklist` a manifest declares is held by that manifest's package, next + * to the registry's holders. So a reference to a list a sibling in the + * artifact declares is judged by R's one rule — reached through the + * referrer's declared closure, else refused naming every holder — exactly as + * the served field will be once the artifact registers (epic seat review on + * #31731). ⛔ No closure is computed here; R computes it from this view. + */ + private withPendingManifests(manifests: readonly unknown[]): PackageScopedRegistry { + const pending = new Map(); + const pendingLists = new Map>(); + for (const manifest of manifests) { + const id = artifactPackageId(manifest); + if (id === undefined) continue; + pending.set(id, { manifest } as unknown as InstalledPackage); + for (const name of collectManifestPicklistNames(manifest)) { + let holders = pendingLists.get(name); + if (!holders) pendingLists.set(name, holders = new Set()); + holders.add(id); + } + } + const pendingHolders = (type: string, name: string): ReadonlySet => + (type === 'picklist' ? pendingLists.get(name) : undefined) ?? new Set(); + // A residual owner's declared dependencies (ADR-0130 D4) are read by the + // one closure walk through the registry it is handed — this view too. + const view: PackageScopedRegistry & Pick = { + residualOwnerDependenciesOf: (id) => this.residualOwnerDependenciesOf(id), + getPackage: (id) => pending.get(id) ?? this.getPackage(id), + getAllPackages: () => [ + ...this.getAllPackages().filter((row) => !pending.has(artifactPackageId(row.manifest) ?? '')), + ...pending.values(), + ], + packageScopedHoldersOf: (type, name) => [ + ...new Set([...this.packageScopedHoldersOf(type, name), ...pendingHolders(type, name)]), + ], + getPackageScopedItem: (type: string, name: string, packageId: string, member?: string): T | undefined => + pendingHolders(type, name).has(packageId) + ? ({ name, _packageId: packageId } as unknown as T) + : this.getPackageScopedItem(type, name, packageId, member), + getEnvironmentScopedItem: (type, name, member) => this.getEnvironmentScopedItem(type, name, member), + }; + return view; + } + + /** + * Every field of every packaged object whose picklist reference reaches no + * list from the package that declares the field — the load-time audit's + * input, with the resolver's refusal sentence where it refused. * * Judged over the PACKAGED contributors only (`own` and `extend`), never an * `overlay` and never a tenant-authored body: those come out of @@ -9778,42 +9930,120 @@ export class SchemaRegistry { * tenant field naming an unknown list is still never served options and * never accepts a value — the fold drops whatever options it carried and * the record validator refuses the field. + * + * ⛔ Leaves out a reference the resolver refuses as held OUTSIDE the + * declaring package's dependency closure (ADR-0150 D3 (a), and a package + * holder it does not depend on — N1, ruled on #31678): + * {@link findOutsideClosurePicklistReferences} names those, and the boot + * warns instead of refusing (ruling N2 on the E6 card): the narrowing is a + * refused reference, not a refused boot. A name nothing holds, or one the + * closure holds more than once, still refuses the boot here. */ - findUnresolvedPicklistReferences(): PicklistReference[] { - const unresolved: PicklistReference[] = []; + findUnresolvedPicklistReferences(): UnresolvedPicklistReference[] { + return this.auditPicklistReferences().unresolved; + } + + /** + * Every `picklistExtensions` entry whose target names no list — the second + * half of the load-time audit. Held extensions are legal while the boot + * fills; once it is sealed, one still held adds its options to nothing. + * The target is judged caller-less ({@link picklistContributions} says + * why), so a refusal here is only ever an ambiguity, every holder named. + */ + findOrphanPicklistExtensions(): UnresolvedPicklistExtension[] { + const orphans: UnresolvedPicklistExtension[] = []; + for (const [target, byPackage] of this.picklistExtensionContributions) { + const verdict = this.picklistReferenceVerdict(target, null); + if (verdict.status === 'resolved') continue; + for (const entry of byPackage.values()) { + orphans.push(verdict.status === 'refused' + ? { picklist: target, packageId: entry.packageId, refusal: verdict.message } + : { picklist: target, packageId: entry.packageId }); + } + } + return orphans; + } + + /** + * [ADR-0150 D3, child E6] The packaged fields whose picklist is held only + * OUTSIDE the declaring package's declared dependency closure: by an + * environment-authored list (D3 (a)), or by a package it does not depend + * on — a same-artifact sibling included (N1, ruled on #31678: the declared + * closure only). The resolver refuses them (`outside-closure`, naming every + * holder): the field is served with no options and the record validator + * refuses its values. The boot names each one (a warning carrying the + * refusal's sentence) and the D10 upgrade report lists them; it does not + * refuse the boot (ruling N2 on the E6 card: a refused reference, not a + * refused boot). The fix is the refusal's own: declare the dependency. + */ + findOutsideClosurePicklistReferences(): UnresolvedPicklistReference[] { + return this.auditPicklistReferences().outsideClosure; + } + + /** The field half of the audit, split by the resolver's verdict (above). */ + private auditPicklistReferences(): { + unresolved: UnresolvedPicklistReference[]; + outsideClosure: UnresolvedPicklistReference[]; + } { + const unresolved: UnresolvedPicklistReference[] = []; + const outsideClosure: UnresolvedPicklistReference[] = []; for (const [fqn, contributors] of this.objectContributors) { for (const contributor of contributors) { if (contributor.ownership === 'overlay' || isTenantAuthored(contributor.definition)) continue; for (const ref of collectPicklistReferences(fqn, contributor.definition, contributor.packageId)) { - if (this.resolvePicklistOptions(ref.picklist) === undefined) unresolved.push(ref); + const judged = this.judgePicklistReference(ref.picklist, ref.packageId); + if (judged === 'resolved') continue; + const entry = judged.refusal ? { ...ref, refusal: judged.refusal.message } : ref; + (judged.outsideClosure ? outsideClosure : unresolved).push(entry); } } } - return unresolved; + return { unresolved, outsideClosure }; } /** - * Every `picklistExtensions` entry whose target list no registered package - * declares — the second half of the load-time audit. Held extensions are - * legal while the boot fills; once it is sealed, one still held adds its - * options to nothing. + * One reference, judged: `'resolved'` when the name reaches a list from + * `callerPackageId`, else what it is — the refusal (when the resolver + * refused) and whether it refused because every holder is outside the + * caller's declared closure. */ - findOrphanPicklistExtensions(): Array<{ picklist: string; packageId: string | undefined }> { - const orphans: Array<{ picklist: string; packageId: string | undefined }> = []; - for (const [target, byPackage] of this.picklistExtensionContributions) { - if (this.resolvePicklistOptions(target) !== undefined) continue; - for (const entry of byPackage.values()) orphans.push({ picklist: target, packageId: entry.packageId }); - } - return orphans; + private judgePicklistReference( + name: string, + callerPackageId: string | undefined, + ): 'resolved' | { refusal?: PackageScopedRefusal; outsideClosure: boolean } { + const verdict = this.picklistReferenceVerdict(name, callerPackageId); + if (verdict.status === 'resolved') return 'resolved'; + if (verdict.status !== 'refused') return { outsideClosure: false }; + return { refusal: verdict, outsideClosure: verdict.reason === 'outside-closure' }; } - /** The owning list's options (when registered) followed by every extension's. */ - private picklistContributions(name: string): PicklistContribution[] { + /** + * The list `name` reaches from `callerPackageId` (its options, when that is + * one), followed by every extension of the SAME list. + * + * [ADR-0150 D3, child E6; epic seat ruling X on the E6 card, #31678] A + * `picklistExtensions` entry's `extend` is a CONTRIBUTION to another + * package's item, not a reference its package reads: it resolves + * caller-less through R — the environment's own list, else the unique + * package holder, else a refusal naming every holder — the treatment D3 + * gives an environment overlay. So an extension adds to the list its target + * names environment-wide, and to a field's list only when that is the same + * list. Loosens nothing (no first match is picked) and guesses nothing. + */ + private picklistContributions(name: string, callerPackageId?: string | null): PicklistContribution[] { const contributions: PicklistContribution[] = []; - const base = this.getItem<{ options?: PicklistOptionLike[]; _packageId?: string }>('picklist', name); + const resolution = this.picklistReferenceVerdict(name, callerPackageId); + const base = resolution.status === 'resolved' ? resolution : undefined; if (base) { - contributions.push({ packageId: base._packageId, kind: 'picklist', options: Array.isArray(base.options) ? base.options : [] }); + const item = base.item; + contributions.push({ + packageId: item?._packageId, + kind: 'picklist', + options: Array.isArray(item?.options) ? item.options : [], + }); } + const extended = base ? this.picklistReferenceVerdict(name, null) : undefined; + if (base && !(extended?.status === 'resolved' && sameHolder(extended.holder, base.holder))) return contributions; for (const entry of this.picklistExtensionContributions.get(name)?.values() ?? []) { contributions.push({ packageId: entry.packageId, kind: 'extension', options: [...entry.options.values()] }); } @@ -9830,7 +10060,10 @@ export class SchemaRegistry { picklist: { options?: PicklistOptionLike[] }, packageId: string | undefined, ): void { - const extensions = this.picklistContributions(name).filter((c) => c.kind === 'extension'); + // The list is not registered yet, so no resolution reaches it: judged + // against every extension held for the name, as the additive rule reads. + const extensions: PicklistContribution[] = [...(this.picklistExtensionContributions.get(name)?.values() ?? [])] + .map((entry) => ({ packageId: entry.packageId, kind: 'extension' as const, options: [...entry.options.values()] })); const duplicate = findDuplicatePicklistValue([ { packageId, kind: 'picklist', options: Array.isArray(picklist?.options) ? picklist.options : [] }, ...extensions, @@ -9838,9 +10071,42 @@ export class SchemaRegistry { if (duplicate) throw duplicatePicklistValueError(name, duplicate); } - /** Resolve every picklist-bound field of a body (by reference when there is none). */ - private resolvePicklistFields(body: T): T { - return resolvePicklistFieldsOnto(body, (picklist) => this.resolvePicklistOptions(picklist)); + /** + * Resolve every picklist-bound field of a body (by reference when there is + * none). [ADR-0150 D3, child E6] Each field's list is resolved from the + * package that WROTE that field's reference (`referrerOf`): the packaged + * layer whose own declaration carries it, else no package — a reference + * only an environment-authored body (a tenant overlay, a stored row) writes + * is the environment's reference, never the package's it customizes (D3). + */ + private resolvePicklistFields(body: T, referrerOf: PicklistReferrer = NO_PACKAGE_REFERRER): T { + return resolvePicklistFieldsOnto(body, (picklist, field) => + this.resolveFieldPicklistOptions(picklist, referrerOf(field, picklist))); + } + + /** + * [ADR-0150 D3, child E6; epic seat review on #31731] One field's list, when + * several packaged layers write its reference: each referrer's resolution + * is R's, and the field is served only when every one of them resolves to + * the SAME holder. Any other answer — one of them refused or reaching + * nothing, or two reaching different holders — serves no options, so the + * record validator refuses the field's values; the boot audit names each + * referrer whose own resolution refuses, with R's sentence + * ({@link findUnresolvedPicklistReferences}). ⛔ No referrer is preferred by + * fold order. + */ + private resolveFieldPicklistOptions( + picklist: string, + referrers: readonly (string | null)[], + ): PicklistOptionLike[] | undefined { + const [first, ...others] = referrers; + if (others.length > 0) { + const verdicts = referrers.map((referrer) => this.picklistReferenceVerdict(picklist, referrer)); + const [head] = verdicts; + if (head.status !== 'resolved') return undefined; + if (!verdicts.every((v) => v.status === 'resolved' && sameHolder(v.holder, head.holder))) return undefined; + } + return this.resolvePicklistOptions(picklist, first ?? null); } /** Drop a package's `picklistExtensions`; `true` when it had any. */