diff --git a/.changeset/35711-residual-extension-and-jobs.md b/.changeset/35711-residual-extension-and-jobs.md new file mode 100644 index 00000000000..864d81e411a --- /dev/null +++ b/.changeset/35711-residual-extension-and-jobs.md @@ -0,0 +1,24 @@ +--- +'@objectstack/spec': minor +'@objectstack/metadata': minor +'@objectstack/objectql': minor +--- + +fix(objectql)!: a composition's top-level `objectExtensions` entry that no package body carries is registered and served; composition refuses two such jobs of one name, and residual extensions that would share one package's slot + +Clause-②: no (narrowing) +Metadata-protocol: narrowed +Skills-docs: none — no skill teaches placing `objectExtensions` or `jobs` in a manifest-less input of a `'preserve'` composition; the refusal names both entries and prescribes the fix + + + +**BREAKING** accept-set narrowing, shipped as `minor`, beside a runtime fix. + +- **Fixed (`@objectstack/objectql`, `@objectstack/metadata`).** A composed artifact that carries `packages[]` keeps the entries no package body claims at its top level, and the boot registers that residual under the artifact's `manifest.id` (ADR-0130 D4). Under `composeStacks(stacks, { manifest: 'preserve' })` that is an input with no `manifest`; under `'first'`, `'last'` or an index it is also the own top-level entries of an input that is itself a multi-package artifact. Its `objectExtensions` entries were registered by no door: the target object was served without their fields (`INVALID_FIELD` on a write naming one) and nothing was logged, through `os serve` and through `os build`'s artifact alike. The residual rule (`unclaimedTopLevel`) now lists such an entry (type `object_extension`) when no package body carries an entry equal to it, and the engine registers it as an `extend` contribution under `manifest.id`, as a body's entry registers. An entry whose field names a picklist no package body declares is not registered and is named at boot, like a residual object. +- **Refused now, at composition (`STACK_CROSS_REFERENCE_INVALID`, 422), under every manifest strategy once the result carries `packages[]`.** Two residual jobs of one name: the boot's job binder schedules neither (`NOT SCHEDULED` at `error`). A residual `objectExtensions` entry for an object that the body carrying `manifest.id` also extends with other fields: one extension of an object registers per package, so only the last one's fields would be served; the finding names that body's entry first, then the residual's: `Object extension of 'crm_line' is declared twice in \`objectExtensions\`: 'com.example.billing' (stack #2) objectExtensions[0] and stack #1 objectExtensions[0]. …`. Two residual `objectExtensions` entries for one object, also when another package body extends that object: a residual entry is now told from a body's flattened copy by value, not by target, so the two are one package's pair (they used to count as that body's copies and compose). +- **Not refused (known gap).** A residual job that shares its name with a package body's job, with other content, still composes: it is read as that body's copy, and the boot holds two enabled jobs of the name and schedules neither. +- **Wording.** The `jobs` finding at every door now says what the runtime does with the pair: `The runtime keys jobs by name: the metadata keeps only the last of these entries, and the job scheduler refuses a name two enabled jobs share, so when both are enabled neither runs.` +- **Unchanged.** One residual extension for an object another package extends composes, and both register. A residual entry equal to a body's entry is that body's copy. Package-claimed extensions and a single residual job compose and boot as before. +- **Installed artifacts.** A residual extension sharing its package's slot registers, the last one served, with one `error` line per object naming the entries. A residual extension now passes the registry's `extend` door as a package body's entry does, so one that door refuses (reachable only through `strict: false` or a hand-built artifact) now fails a boot that used to load and drop it. + +One-line fix: declare each job name once; move a top-level extension into the package that owns it, or merge it into that package's own entry for the object. diff --git a/packages/metadata/src/plugin.ts b/packages/metadata/src/plugin.ts index 85eedd30463..9084b94c0b1 100644 --- a/packages/metadata/src/plugin.ts +++ b/packages/metadata/src/plugin.ts @@ -380,6 +380,52 @@ function claimedArtifactSlots(bodies: readonly unknown[]): (type: string, name: return (type, name) => owned.get(type)?.has(name) === true; } +/** + * Whether a top-level `objectExtensions` entry of a stack that carries + * `packages[]` is a package body's: a body carries an entry EQUAL to it by + * value. An extension has no slot of its own (it is keyed by `extend`, and its + * `name` spelling is a retired alias the schema refuses), so it is told from + * the residual by what it holds, never by its target: the flattened top level + * of a `composeStacks(…, { manifest: 'preserve' })` artifact repeats every + * body's entry, and a built artifact has lost the references, but each copy + * still holds exactly what its body's entry holds. An entry extending a target + * some body also extends, with other fields, is the residual's own. + * + * Equal by value is also the case where nothing is lost: the body's entry + * registers exactly what the copy holds. Keys set to `undefined` count as + * absent, as `deepEqualAuthored` (`@objectstack/spec`) and the composition + * door's mirror read them. + */ +function claimedArtifactExtensions(bodies: readonly unknown[]): (item: unknown) => boolean { + const declared: unknown[] = []; + for (const body of bodies) { + const items = (body as any)?.objectExtensions; + if (Array.isArray(items)) declared.push(...items); + } + return (item) => declared.some((entry) => entry === item || sameAuthoredValue(entry, item, 0)); +} + +/** Structural equality of two authored values; keys holding `undefined` count as absent. */ +function sameAuthoredValue(a: unknown, b: unknown, depth: number): boolean { + if (Object.is(a, b)) return true; + if (depth >= 32 || typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false; + if (Array.isArray(a) !== Array.isArray(b)) return false; + if (Array.isArray(a) && Array.isArray(b)) { + return a.length === b.length && a.every((v, i) => sameAuthoredValue(v, b[i], depth + 1)); + } + const left = a as Record; + const right = b as Record; + const keys = Object.keys(left).filter((k) => left[k] !== undefined); + if (keys.length !== Object.keys(right).filter((k) => right[k] !== undefined).length) return false; + return keys.every((k) => sameAuthoredValue(left[k], right[k], depth + 1)); +} + +/** The object an `objectExtensions` entry extends, or `undefined` when it names none. */ +function extensionTarget(item: unknown): string | undefined { + const target = (item as { extend?: unknown } | null | undefined)?.extend; + return typeof target === 'string' && target !== '' ? target : undefined; +} + /** One top-level item of a multi-package stack that none of its package bodies declares. */ export interface UnclaimedTopLevelItem { /** The stack collection the item sits in, e.g. `views`. */ @@ -419,7 +465,12 @@ export interface UnclaimedTopLevel { * An item is unclaimed when it occupies a registry slot (`artifactItemSlot`) * that no package body occupies (`claimedArtifactSlots`): a container is * compared on its own slot, every other item on its name. An item with no - * derivable slot is registered by no door, so it is not listed. + * derivable slot is registered by no door, so it is not listed — with one + * exception: an `objectExtensions` entry, which has no slot, is listed (type + * `object_extension`) when it names a target and no body carries an entry + * equal to it (`claimedArtifactExtensions`). The metadata door registers no + * extension, a body's or the residual's (it has no slot to file one under); + * the engine registers the residual's under this id, as it does a body's. * * @returns `undefined` for a stack without `packages[]`: its top level IS its * one package's body, so it has no residual. @@ -428,11 +479,16 @@ export function unclaimedTopLevel(stack: unknown): UnclaimedTopLevel | undefined if (!Array.isArray((stack as any)?.packages)) return undefined; const bodies = resolveArtifactPackageOrder(stack); const claimed = claimedArtifactSlots(bodies); + const claimedExtension = claimedArtifactExtensions(bodies); const items: UnclaimedTopLevelItem[] = []; for (const [field, metaType] of Object.entries(ARTIFACT_FIELD_TO_TYPE)) { const collection = (stack as any)[field]; if (!Array.isArray(collection)) continue; collection.forEach((item: unknown, index: number) => { + if (metaType === 'object_extension') { + if (extensionTarget(item) !== undefined && !claimedExtension(item)) items.push({ field, index, type: metaType, item }); + return; + } const slot = artifactItemSlot(metaType, item); if (!slot) return; if (claimed(metaType, slot.container ? slot.object : slot.name)) return; diff --git a/packages/metadata/src/unclaimed-top-level-residual-extension.test.ts b/packages/metadata/src/unclaimed-top-level-residual-extension.test.ts new file mode 100644 index 00000000000..62f327e4c42 --- /dev/null +++ b/packages/metadata/src/unclaimed-top-level-residual-extension.test.ts @@ -0,0 +1,74 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0130 D4] The residual rule (`unclaimedTopLevel`) lists a multi-package + * stack's residual `objectExtensions` entries, so the engine registers them + * under the stack's `manifest.id` as it registers the residual's objects. + * + * An extension has no slot (it is keyed by `extend`; its `name` is a retired + * alias), so the rule used to list none, and no door registered one: measured + * through `os serve` on main `c30ce97cd7`, a `composeStacks(…, { manifest: + * 'preserve' })` artifact with an input that has no manifest served the target + * without the extension's field (`INVALID_FIELD` on write) and logged nothing. + * + * It is told from a body's flattened copy by VALUE, never by target: the + * flattened top level repeats every body's entry, a built artifact has lost the + * references, and an entry extending a target some body also extends with other + * fields is the residual's own. + */ + +import { describe, it, expect } from 'vitest'; +// Paid at collection, not inside a case's clocked window: `plugin.ts` loads it lazily. +import '@objectstack/metadata-fs'; +import { composeStacks, defineStack } from '@objectstack/spec'; +import { unclaimedTopLevel } from './plugin.js'; + +const owner = { id: 'com.probe.owner', namespace: 'probe', name: 'probe', version: '1.0.0', type: 'module' as const }; +const other = { id: 'com.probe.other', namespace: 'probe', name: 'probe_other', version: '1.0.0', type: 'module' as const }; +const account = { name: 'probe_account', label: 'Account', sharingModel: 'private' as const, fields: { title: { type: 'text' as const, label: 'Title' } } }; +const extension = (field: string) => ({ extend: 'probe_account', fields: { [field]: { type: 'text' as const, label: field } } }); + +const residualExtensions = (stack: unknown) => + (unclaimedTopLevel(stack)?.items ?? []) + .filter((entry) => entry.type === 'object_extension') + .map((entry) => ({ field: entry.field, index: entry.index, target: (entry.item as { extend: string }).extend, fields: Object.keys((entry.item as { fields: object }).fields) })); + +describe('unclaimedTopLevel lists a residual objectExtensions entry', () => { + // `'preserve'` keeps the last manifest (owner's) as the residual's id, and + // owner does not extend the target: the residual's entry has a slot of its own. + const composed = () => composeStacks( + [ + defineStack({ manifest: other, objectExtensions: [extension('other_note')] }), + defineStack({ manifest: owner, objects: [account] }), + defineStack({ objectExtensions: [extension('residual_note')] }), + ], + { manifest: 'preserve' }, + ); + + it('the manifest-less input\'s entry, as composed and as built JSON; never the body\'s flattened copy', () => { + for (const [leg, stack] of [['composed', composed()], ['built', JSON.parse(JSON.stringify(composed()))]] as const) { + expect(residualExtensions(stack), leg).toEqual([ + { field: 'objectExtensions', index: 1, target: 'probe_account', fields: ['residual_note'] }, + ]); + expect(unclaimedTopLevel(stack)?.ownerId, leg).toBe(owner.id); + } + }); + + it('CONTROL: a stack whose every extension a body carries lists none', () => { + const stack = composeStacks( + [ + defineStack({ manifest: owner, objects: [account] }), + defineStack({ manifest: other, objectExtensions: [extension('other_note')] }), + defineStack({ pages: [{ name: 'probe_home', label: 'Home', type: 'app', regions: [] }] }), + ], + { manifest: 'preserve' }, + ); + expect((stack as unknown as { objectExtensions: unknown[] }).objectExtensions, 'anti-vacuity: the flattened copy is there').toHaveLength(1); + expect(residualExtensions(stack)).toEqual([]); + expect(residualExtensions(JSON.parse(JSON.stringify(stack)))).toEqual([]); + }); + + it('CONTROL: a stack without packages[] has no residual', () => { + expect(unclaimedTopLevel(defineStack({ manifest: owner, objects: [account], objectExtensions: [extension('x_note')] }))).toBeUndefined(); + }); +}); diff --git a/packages/objectql/src/engine-registration.ts b/packages/objectql/src/engine-registration.ts index 7707d899968..cbc7b4d3e62 100644 --- a/packages/objectql/src/engine-registration.ts +++ b/packages/objectql/src/engine-registration.ts @@ -125,8 +125,50 @@ function logSameTargetObjectExtensions( } } +/** + * The partial object definition an `objectExtensions` entry registers as an + * `extend` contribution to its target, and the priority it registers at — the + * ONE reading of an entry, taken by a package body's entries + * ({@link RegistrationFacet.registerApp} step 2b) and by a multi-package + * stack's RESIDUAL entries (`ObjectQLPlugin`, ADR-0130 D4) alike. + * + * ⛔ Never a second literal at either caller: a key added here reaches both, so + * a residual extension registers exactly what the same entry registers from a + * package body (pinned by `manifest-service-residual-object-extension.test.ts`, + * which compares the object both registrations serve). + */ +export function objectExtensionContribution(ext: any): { + definition: { + name: string; fields: unknown; fieldPatches: unknown; label: unknown; pluralLabel: unknown; + description: unknown; validations: unknown; indexes: unknown; place: unknown; + }; + priority: number; +} { + return { + definition: { + name: ext.extend, // Use the target FQN as name + fields: ext.fields, + // [ADR-0146 D10, second rule] The per-field display patches, + // the slot as `ObjectExtensionSchema.fieldPatches` declares + // it — applied by the registry's `mergeObjectDefinitions`, + // whose fold every object read shares. + fieldPatches: ext.fieldPatches, + label: ext.label, + pluralLabel: ext.pluralLabel, + description: ext.description, + validations: ext.validations, + indexes: ext.indexes, + // [#35901] Where its own fields, groups and child lists go — + // applied by the registry fold after every contributor's + // fields are merged (`applyExtensionPlacements`). + place: ext.place, + }, + priority: ext.priority ?? 200, + }; +} + /** Structural equality of two JSON-shaped values: same primitives, same arrays in order, same keys with equal values. */ -function equalByValue(a: unknown, b: unknown): boolean { +export function equalByValue(a: unknown, b: unknown): boolean { if (a === b) return true; if (a === null || b === null || typeof a !== 'object' || typeof b !== 'object') return false; if (Array.isArray(a) !== Array.isArray(b)) return false; @@ -395,30 +437,13 @@ export class RegistrationFacet { // outcome is unchanged. logSameTargetObjectExtensions(this.logger, id, manifest.objectExtensions); for (const ext of manifest.objectExtensions) { - const targetFqn = ext.extend; - const priority = ext.priority ?? 200; - // Create a partial object definition for the extension - const extDef = { - name: targetFqn, // Use the target FQN as name - fields: ext.fields, - // [ADR-0146 D10, second rule] The per-field display patches, - // the slot as `ObjectExtensionSchema.fieldPatches` declares - // it — applied by the registry's `mergeObjectDefinitions`, - // whose fold every object read shares. - fieldPatches: ext.fieldPatches, - label: ext.label, - pluralLabel: ext.pluralLabel, - description: ext.description, - validations: ext.validations, - indexes: ext.indexes, - // [#35901] Where its own fields, groups and child lists go — - // applied by the registry fold after every contributor's - // fields are merged (`applyExtensionPlacements`). - place: ext.place, - }; + // The partial object definition for the extension — the one + // reading of an entry, shared with the residual's + // ({@link objectExtensionContribution}). + const { definition: extDef, priority } = objectExtensionContribution(ext); // Register as extension (namespace is undefined since we're targeting by FQN) - this._registry.registerObject(stampPackage(extDef, id, version), id, undefined, 'extend', priority); - this.logger.debug('Registered Object Extension', { target: targetFqn, priority, from: id }); + this._registry.registerObject(stampPackage(extDef as any, id, version), id, undefined, 'extend', priority); + this.logger.debug('Registered Object Extension', { target: extDef.name, priority, from: id }); } } diff --git a/packages/objectql/src/manifest-service-residual-object-extension.test.ts b/packages/objectql/src/manifest-service-residual-object-extension.test.ts new file mode 100644 index 00000000000..b32004afdda --- /dev/null +++ b/packages/objectql/src/manifest-service-residual-object-extension.test.ts @@ -0,0 +1,188 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * ADR-0130 D4 — the engine's `manifest` service registers a multi-package + * stack's residual `objectExtensions` entries (top-level entries no package + * body carries, as `unclaimedTopLevel` lists them) under the residual's id, as + * `registerApp` step 2b registers a body's. + * + * ## The defect these pin + * + * No door registered a residual extension. Measured through `os serve` on main + * `c30ce97cd7`: `composeStacks([owner, other, noManifest], { manifest: + * 'preserve' })`, the input without a manifest extending `probe_account` with + * `residual_note` — `GET /api/v1/meta/object/probe_account` listed no + * `residual_note`, `POST /api/v1/data/probe_account` with it answered 400 + * `INVALID_FIELD`, and the boot logged nothing. `os build` emitted the entry + * (`1 Extensions`, exit 0), so a built artifact reached the same drop. + * + * ## What each pin is for + * + * - The residual extension's field is SERVED on its target, composed and as + * built JSON. + * - CONTROL: a package-claimed extension registers as before and logs nothing. + * - A residual entry for a target the body that carries the residual's id + * extends too (refused at authoring now; a hand-built or older artifact): + * one extension of a target registers per package, so the residual's — the + * last registered — is served, and the boot says so at `error` once. + * - A residual entry whose field names a picklist no body declares is not + * registered (the boot's picklist audit would refuse the field), and the + * boot names it — the residual objects' own rule. + */ + +import { describe, it, expect, afterEach } from 'vitest'; +import { ObjectKernel, type Plugin, type PluginContext } from '@objectstack/core'; +import { composeStacks, defineStack } from '@objectstack/spec'; +import { ObjectQLPlugin } from './plugin.js'; +import type { ObjectQL } from './engine.js'; + +type ManifestService = { register(m: unknown): void | Promise }; + +const engineOf = (kernel: ObjectKernel): ObjectQL => kernel.getService('objectql'); + +const OWNER_ID = 'com.probe.owner'; +const OTHER_ID = 'com.probe.other'; +const owner = { id: OWNER_ID, namespace: 'probe', name: 'probe', version: '1.0.0', type: 'module' as const }; +const other = { id: OTHER_ID, namespace: 'probe', name: 'probe_other', version: '1.0.0', type: 'module' as const }; +const account = () => ({ name: 'probe_account', label: 'Account', sharingModel: 'private' as const, fields: { title: { type: 'text' as const, label: 'Title' } } }); +const otherObj = () => ({ name: 'probe_other', label: 'Other', sharingModel: 'private' as const, fields: { title: { type: 'text' as const, label: 'Title' } } }); +const extension = (field: string, spec: Record = { type: 'text', label: field }) => + ({ extend: 'probe_account', fields: { [field]: spec } }); + +/** What `AppPlugin.init` hands the `manifest` service. */ +const payload = (bundle: Record) => ({ ...(bundle.manifest as object), ...bundle }); + +const fieldsOf = (ql: ObjectQL, name: string): string[] => Object.keys(ql.registry.getObject(name)?.fields ?? {}); + +/** Records every `warn` and `error` the kernel's one logger carries. */ +class LogRecorder implements Plugin { + name = 'test.residual-extension.log-recorder'; + version = '1.0.0'; + readonly warnings: string[] = []; + readonly errors: string[] = []; + init = async (ctx: PluginContext): Promise => { + const logger = ctx.logger as unknown as Record<'warn' | 'error', (message: string, ...rest: unknown[]) => void>; + for (const [level, sink] of [['warn', this.warnings], ['error', this.errors]] as const) { + const real = logger[level].bind(logger); + logger[level] = (message: string, ...rest: unknown[]) => { + sink.push(String(message)); + real(message, ...rest); + }; + } + }; +} + +function registering(artifact: unknown): Plugin { + return { + name: 'test.residual-extension.registering', + dependencies: ['com.objectstack.engine.objectql'], + init: async (ctx: PluginContext) => { + await ctx.getService('manifest').register(artifact); + }, + } as Plugin; +} + +const kernels: ObjectKernel[] = []; + +async function boot(artifact: unknown): Promise<{ ql: ObjectQL; log: LogRecorder }> { + const kernel = new ObjectKernel({ logger: { level: 'silent' }, gracefulShutdown: false }); + kernels.push(kernel); + const log = new LogRecorder(); + await kernel.use(log); + await kernel.use(new ObjectQLPlugin()); + await kernel.use(registering(artifact)); + await kernel.bootstrap(); + return { ql: engineOf(kernel), log }; +} + +afterEach(async () => { + while (kernels.length > 0) await kernels.pop()!.shutdown().catch(() => {}); +}); + +const composed = (residual: Record, otherExtra: Record = {}, ownerObject: Record = account()) => + composeStacks( + [ + defineStack({ manifest: owner, objects: [ownerObject as ReturnType] }), + defineStack({ manifest: other, objects: [otherObj()], ...otherExtra }), + defineStack(residual), + ], + { manifest: 'preserve' }, + ) as unknown as Record; + +describe('a residual objectExtensions entry registers under the residual\'s id', () => { + it('its field is served on the target, composed and as built JSON', async () => { + const artifact = composed({ objectExtensions: [extension('residual_note')] }); + expect((artifact.packages as unknown[]).length, 'anti-vacuity: an artifact with bodies').toBe(2); + for (const [leg, bundle] of [['composed', artifact], ['built', JSON.parse(JSON.stringify(artifact))]] as const) { + const { ql, log } = await boot(payload(bundle)); + expect(fieldsOf(ql, 'probe_account'), leg).toEqual(expect.arrayContaining(['title', 'residual_note'])); + expect(ql.registry.getObjectOwner('probe_account')?.packageId, leg).toBe(OWNER_ID); + expect(log.errors.filter((m) => m.includes('probe_account')), leg).toEqual([]); + } + }); + + it('serves what the same entry serves from a package body (one reading of an entry for both)', async () => { + const entry = { ...extension('parity_note'), label: 'Account (extended)', pluralLabel: 'Accounts (extended)', description: 'Extended' }; + const strip = (value: unknown): unknown => JSON.parse(JSON.stringify(value), (key, v) => (key.startsWith('_') ? undefined : v)); + const asBody = await boot(payload(composed({ pages: [{ name: 'probe_home', label: 'Home', type: 'app', regions: [] }] }, { objectExtensions: [entry] }))); + const asResidual = await boot(payload(composed({ objectExtensions: [entry] }))); + const served = (ql: ObjectQL) => strip(ql.registry.getObject('probe_account')); + expect(fieldsOf(asResidual.ql, 'probe_account'), 'anti-vacuity').toContain('parity_note'); + expect(served(asResidual.ql)).toEqual(served(asBody.ql)); + }); + + it('carries the entry\'s place as a body\'s entry does (one reading of an entry for both)', async () => { + const grouped = { ...account(), fieldGroups: [{ key: 'basic', label: 'Basic' }] }; + const placed = { ...extension('placed_note'), place: [{ field: 'placed_note', group: 'basic' }] }; + const strip = (value: unknown): unknown => JSON.parse(JSON.stringify(value), (key, v) => (key.startsWith('_') ? undefined : v)); + const served = (ql: ObjectQL) => strip(ql.registry.getObject('probe_account')); + const asBody = await boot(payload(composed({ pages: [{ name: 'probe_home', label: 'Home', type: 'app', regions: [] }] }, { objectExtensions: [placed] }, grouped))); + const asResidual = await boot(payload(composed({ objectExtensions: [placed] }, {}, grouped))); + const unplaced = await boot(payload(composed({ objectExtensions: [extension('placed_note')] }, {}, grouped))); + expect(fieldsOf(asResidual.ql, 'probe_account'), 'anti-vacuity').toContain('placed_note'); + expect(served(asResidual.ql), 'anti-vacuity: the placement changes what is served').not.toEqual(served(unplaced.ql)); + expect(served(asResidual.ql)).toEqual(served(asBody.ql)); + }); + + it('CONTROL: a package-claimed extension registers as before, nothing logged', async () => { + const artifact = composed( + { pages: [{ name: 'probe_home', label: 'Home', type: 'app', regions: [] }] }, + { objectExtensions: [extension('other_note')] }, + ); + expect((artifact.objectExtensions as unknown[]).length, 'anti-vacuity: the flattened copy is there').toBe(1); + const { ql, log } = await boot(payload(artifact)); + expect(fieldsOf(ql, 'probe_account')).toEqual(expect.arrayContaining(['title', 'other_note'])); + expect(log.errors.filter((m) => m.includes('probe_account'))).toEqual([]); + }); + + it('a residual entry sharing the slot of the body that carries its id: the last one\'s fields, said once at error', async () => { + // Hand-built: authoring refuses this pair now (composeStacks' residual door). + const artifact = payload({ + manifest: other, + objects: [account(), otherObj()], + objectExtensions: [extension('other_note'), extension('residual_note')], + packages: [ + { manifest: { ...owner, objects: [account()] } }, + { manifest: { ...other, objects: [otherObj()], objectExtensions: [extension('other_note')] } }, + ], + }); + const { ql, log } = await boot(artifact); + expect(fieldsOf(ql, 'probe_account')).toContain('residual_note'); + expect(fieldsOf(ql, 'probe_account')).not.toContain('other_note'); + const lines = log.errors.filter((m) => m.includes("extensions of object 'probe_account'")); + expect(lines).toHaveLength(1); + expect(lines[0]).toContain(`stack '${OTHER_ID}' registers 2 extensions of object 'probe_account' under that one id`); + expect(lines[0]).toContain(`package '${OTHER_ID}' objectExtensions[0] and the top-level objectExtensions[1] no package body declares`); + }); + + it('a residual entry whose field names a picklist no body declares: not registered, named at boot', async () => { + const artifact = composed({ + objectExtensions: [extension('residual_status', { type: 'select', label: 'Status', picklist: 'probe_nowhere' })], + }); + const { ql, log } = await boot(payload(artifact)); + expect(fieldsOf(ql, 'probe_account')).not.toContain('residual_status'); + const lines = log.warnings.filter((m) => m.includes('top-level object extension(s)')); + expect(lines).toHaveLength(1); + expect(lines[0]).toContain("field 'residual_status' names picklist 'probe_nowhere', which no package body declares"); + }); +}); diff --git a/packages/objectql/src/plugin.ts b/packages/objectql/src/plugin.ts index 161e6f23b09..f2f2235fdfa 100644 --- a/packages/objectql/src/plugin.ts +++ b/packages/objectql/src/plugin.ts @@ -32,6 +32,10 @@ import { viewContainerNameRefusal } from './view-container-name-refusal.js'; // [ADR-0150 D2, #31720] The residual as one holder of the stack's namespace, // for the namespace name rule (see the residual registration below). import { residualNamespacePackageOf } from './namespace-co-owner-names.js'; +// [ADR-0130 D4] The one reading of an `objectExtensions` entry, and the equality +// `registerApp`'s same-target line reads — the residual's extensions register +// and are judged as a body's are. +import { equalByValue, objectExtensionContribution } from './engine-registration.js'; import { StorageNameMapping } from '@objectstack/spec/system'; import { applyProtection } from '@objectstack/spec/shared'; // [#21777] The ONE "is this schema the remote's?" predicate, shared with `ObjectQL.syncSchemas`. @@ -197,6 +201,31 @@ function unclaimedTopLevelObjects( : undefined; } +/** + * The `objectExtensions` entries of a multi-package stack's residual, and the + * id they are owned by — the residual rule's answer (`unclaimedTopLevel`, which + * lists an entry no body carries an equal of), read the way + * {@link unclaimedTopLevelObjects} reads it. ⛔ Never re-derived here. + * + * Why the engine needs them: no door registered a residual extension, so a + * `composeStacks(…, { manifest: 'preserve' })` artifact with an input that has + * no `manifest` (and `os build`'s output of it) served the target without the + * extension's fields, and nothing said so. + * + * @returns `undefined` when the stack has no residual extension. + */ +function unclaimedTopLevelExtensions( + residual: UnclaimedTopLevel | undefined, +): { ownerId: string | undefined; ownerVersion: string | undefined; extensions: Array<{ index: number; item: Record }> } | undefined { + if (!residual) return undefined; + const extensions = residual.items + .filter((entry) => entry.type === 'object_extension') + .map((entry) => ({ index: entry.index, item: entry.item as Record })); + return extensions.length > 0 + ? { ownerId: residual.ownerId, ownerVersion: residual.ownerVersion, extensions } + : undefined; +} + /** * The residual types the engine does NOT register through * {@link unclaimedTopLevelItems}, each because it has a path of its own: @@ -210,9 +239,11 @@ function unclaimedTopLevelObjects( * would change which objects the data door serves. A residual list no * object field names is refused instead * ({@link unreferencedResidualPicklistRefusal}); - * - `object_extension`: an extension has no slot of its own (it is keyed by - * `extend`, and its `name` spelling is a retired alias the schema refuses), - * so the residual rule never lists one. + * - `object_extension`: {@link unclaimedTopLevelExtensions}, through the + * registry's `extend` verb a body's `objectExtensions` take — an extension + * is no item: it has no slot of its own (it is keyed by `extend`, and its + * `name` spelling is a retired alias the schema refuses), and it registers + * as a contribution to its target object. */ const RESIDUAL_TYPES_WITH_OWN_PATH: ReadonlySet = new Set(['object', 'picklist', 'object_extension']); @@ -956,13 +987,16 @@ export class ObjectQLPlugin implements Plugin { // which readers of the registry alone see only through this. See // {@link unclaimedTopLevelItems}. const residualItems = unclaimedTopLevelItems(residualAnswer); + // …and its `objectExtensions` entries, which register as `extend` + // contributions, not as items. See {@link unclaimedTopLevelExtensions}. + const residualExtensions = unclaimedTopLevelExtensions(residualAnswer); // …and its picklists, which neither of those registers: one that no // object field names is refused here, before anything registers. See // {@link unreferencedResidualPicklistRefusal}. const unreferencedPicklists = unreferencedResidualPicklistRefusal(residualAnswer, ordered); if (unreferencedPicklists) throw unreferencedPicklists; - if (ordered.length === 0 && residual === undefined && residualItems === undefined) { + if (ordered.length === 0 && residual === undefined && residualItems === undefined && residualExtensions === undefined) { // An artifact that declared `packages: []` registers nothing. Said out // loud rather than returning quietly: "the install did nothing" is not // a state anyone should have to infer from an absence. @@ -1075,6 +1109,10 @@ export class ObjectQLPlugin implements Plugin { // id, through the registration a body's own item of that type takes. // See {@link registerUnclaimedTopLevelItems}. if (residualItems) this.registerUnclaimedTopLevelItems(ctx, residualItems); + // [ADR-0130 D4] …and the residual's object extensions, last, under + // the same id, through the verb a body's `objectExtensions` take + // (`registerApp` step 2b). See {@link registerUnclaimedTopLevelExtensions}. + if (residualExtensions) this.registerUnclaimedTopLevelExtensions(ctx, residualExtensions, ordered); })); // [#28534] …and the door's statement of where the residual's owner // came from: no package row answers the id, and a reader of an item's @@ -1085,7 +1123,7 @@ export class ObjectQLPlugin implements Plugin { // it (the bridge below, every reader after the door answers). The // residual is not an artifact entry, so it states no source of its // own; the door's word, `code` when it states none, is its origin. - const residualOwnerId = residual?.ownerId ?? residualItems?.ownerId; + const residualOwnerId = residual?.ownerId ?? residualItems?.ownerId ?? residualExtensions?.ownerId; if (residualOwnerId !== undefined) ql.recordResidualOwner(residualOwnerId, options?.source ?? 'code'); // [ADR-0130 D4, epic #31527 R2] …and what the residual's owner // declares it depends on (the stack's own manifest): no package record @@ -3628,6 +3666,113 @@ export class ObjectQLPlugin implements Plugin { } } + /** + * [ADR-0130 D4] Register the `objectExtensions` entries of a stack's + * residual ({@link unclaimedTopLevelExtensions}) in the engine, the way + * `registerApp` step 2b registers a body's: each one an `extend` + * contribution to its target under the residual rule's id, with the stack's + * version stamped beside it ({@link objectExtensionContribution}, the one + * reading of an entry). Before this, no door registered one, so the target + * was served without its fields and nothing was said. + * + * The registry keeps one extension of a target per package (the extend + * splice replaces the package's earlier contribution, which a reload relies + * on). The residual's id is a package of its own only in name: under + * `manifest: 'preserve'` it is the last input's manifest id, which is also + * that input's body. So a residual entry for a target that body extends too, + * or two residual entries for one target, keep only the LAST one's fields — + * the residual registering after every body. Authoring refuses both shapes + * (`composeStacks`' residual door, the #22934 sentence); an artifact built + * before that still loads, and the outcome is said once per target at + * `error`, as `registerApp` says it of one body (#35228 ruling A, arm A1): + * the boot looks healthy while the earlier entries' fields are absent. + * + * One class is NOT registered, the residual objects' own rule: an entry + * whose field names a picklist none of the stack's package bodies declares, + * because the residual's own picklists are metadata only and the boot's + * picklist audit at `kernel:ready` would refuse the field. It is named at + * boot instead. Any refusal the registry's `extend` verb raises propagates, + * as a body's does. + */ + private registerUnclaimedTopLevelExtensions( + ctx: PluginContext, + residual: { ownerId: string | undefined; ownerVersion: string | undefined; extensions: Array<{ index: number; item: Record }> }, + bodies: unknown[], + ): void { + const ql = this.ql; + if (!ql) return; + const { ownerId, ownerVersion } = residual; + const bodyPicklists = new Set(); + for (const body of bodies) for (const name of collectManifestPicklistNames(body)) bodyPicklists.add(name); + const unserved: string[] = []; + const registered: Array<{ index: number; item: Record }> = []; + for (const entry of residual.extensions) { + const dangling = collectManifestPicklistReferences({ objectExtensions: [entry.item] }, ownerId) + .find((ref) => !bodyPicklists.has(ref.picklist)); + if (dangling) { + unserved.push( + `objectExtensions[${entry.index}] of '${String(entry.item.extend)}' (field '${dangling.field}' names picklist ` + + `'${dangling.picklist}', which no package body declares)`, + ); + continue; + } + registered.push(entry); + } + this.logResidualSameTargetExtensions(ctx, ownerId, registered, bodies); + for (const { item } of registered) { + const { definition, priority } = objectExtensionContribution(item); + if (ownerVersion !== undefined) applyProtection(definition as any, { packageId: ownerId, packageVersion: ownerVersion }); + ql.registry.registerObject(definition as any, ownerId as string, undefined, 'extend', priority); + ctx.logger.debug('Registered residual Object Extension', { target: definition.name, priority, from: ownerId }); + } + if (unserved.length === 0) return; + ctx.logger.warn( + `[ObjectQLPlugin] ${unserved.length} top-level object extension(s) of stack '${ownerId ?? ''}' that no ` + + `package body declares are NOT registered, so the target does not serve their fields: ${unserved.join(', ')}. ` + + 'Declare each one inside the `packages[]` entry of the package that owns it, together with every picklist ' + + 'its fields name.', + ); + } + + /** + * The one error line per target that the residual's extensions + * ({@link registerUnclaimedTopLevelExtensions}) owe when two or more + * contributions under the residual's id extend it — the body that carries + * that id first, then the residual, in registration order — and they are not + * all equal by value: only the last one's fields are served. + */ + private logResidualSameTargetExtensions( + ctx: PluginContext, + ownerId: string | undefined, + residual: ReadonlyArray<{ index: number; item: Record }>, + bodies: unknown[], + ): void { + const owner = ownerId === undefined ? undefined : bodies.find((body) => artifactPackageId(body) === ownerId); + const ownerEntries = (owner as { objectExtensions?: unknown } | undefined)?.objectExtensions; + const byTarget = new Map>(); + const add = (target: unknown, at: string, item: unknown): void => { + if (typeof target !== 'string' || target === '') return; + byTarget.set(target, [...(byTarget.get(target) ?? []), { at, item }]); + }; + if (Array.isArray(ownerEntries)) { + ownerEntries.forEach((item, i) => add((item as { extend?: unknown } | null)?.extend, `package '${ownerId}' objectExtensions[${i}]`, item)); + } + for (const { index, item } of residual) add(item.extend, `the top-level objectExtensions[${index}] no package body declares`, item); + for (const [target, entries] of byTarget) { + if (entries.length < 2) continue; + if (entries.every((e) => equalByValue(e.item, entries[0]!.item))) continue; + const named = `${entries.slice(0, -1).map((e) => e.at).join(', ')} and ${entries[entries.length - 1]!.at}`; + ctx.logger.error( + `[ObjectQLPlugin] stack '${ownerId ?? ''}' registers ${entries.length} extensions of object '${target}' under ` + + `that one id (${named}): one extension of an object registers per package, so only the last one's fields are ` + + 'served and the fields of the others are missing, while the stack keeps loading. Merge them into a single ' + + `objectExtensions entry for '${target}' inside the \`packages[]\` entry of the package that owns it.`, + undefined, + { package: ownerId, target }, + ); + } + } + /** * [ADR-0130 D5] Bridge each package of one artifact, in the SAME * dependency-topological order they registered in. diff --git a/packages/spec/src/migrations/entries/semantic/18.stack-residual-extension-registered-and-jobs-judged.ts b/packages/spec/src/migrations/entries/semantic/18.stack-residual-extension-registered-and-jobs-judged.ts new file mode 100644 index 00000000000..d8780c0d847 --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/18.stack-residual-extension-registered-and-jobs-judged.ts @@ -0,0 +1,51 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// An accept-set narrowing of composition, beside a runtime fix. A composed +// artifact that carries packages[] has a residual (top-level entries no package +// body claims, registered under manifest.id); its objectExtensions are now +// registered by the engine, where no door registered one, and the composition +// door judges what that registration makes one package. That holds under every +// manifest strategy: 'preserve' with an input that has no manifest, and +// 'first' / 'last' / an index with an input that is itself a multi-package +// artifact. No D2 conversion: which of two extensions or two jobs to keep is the +// author's call. +// +// Known gap, left to the job binder and not judged at composition: a residual +// job whose name a package body's job also carries (with other content) is read +// as that body's copy and composes, and the boot schedules neither of the two +// enabled jobs. #36431 carries the question. +export const entry: SemanticMigration = { + id: 'stack-residual-extension-registered-and-jobs-judged', + surface: + 'composeStacks(…) whose result carries packages[] beside top-level entries no package body claims (the residual): ' + + "under manifest 'preserve' the entries of inputs that carry no manifest, and under 'first', 'last' or an index " + + 'also every top-level entry an input that is itself a multi-package artifact carries of its own. Refused there ' + + 'now: two residual jobs of one name; a residual objectExtensions entry for an object that the body carrying ' + + 'manifest.id also extends with other fields; two residual objectExtensions entries for one object, also when a ' + + 'package body extends that object too (before this release they counted as that body\'s copies and composed).', + replacement: + 'Declare each job name once in the artifact. Put a top-level extension in the package that owns it, or merge it ' + + "into that package's own objectExtensions entry for the same object, and merge two top-level extensions of one " + + "object into one: the residual registers under the artifact's manifest id (under manifest preserve the last " + + 'input with a manifest, under first / last / an index the manifest that strategy keeps), and one extension of an ' + + 'object registers per package.', + reason: + 'A residual objectExtensions entry was registered by no door, so its fields were missing on the target and ' + + 'nothing was said; it now registers under manifest.id. A residual entry is told from a body\'s flattened copy by ' + + 'value, not by target, so two residual entries for one object are one package\'s pair whatever other packages ' + + 'extend, and only the last one\'s fields register. Under manifest preserve that id is also a package body, so a ' + + 'residual entry for an object that body extends too keeps only the last fields. Composition refuses each pair ' + + '(STACK_CROSS_REFERENCE_INVALID) with the one-package wording, a body entry first. Two residual jobs of one name ' + + 'composed and the boot then scheduled neither (NOT SCHEDULED at error); composition refuses them now, and the ' + + 'jobs wording at every door says that when both are enabled neither runs. The same holds under first, last or ' + + 'an index once an input carries packages[]. An artifact built before this keeps loading: a residual extension ' + + 'pair is registered (the last one served) with an error line naming both. One case is NOT refused: a residual ' + + 'job sharing its name with a package body\'s job composes, and the binder schedules neither (a known gap).', + acceptanceCriteria: + 'objectstack validate and objectstack build load the composed stack without a STACK_CROSS_REFERENCE_INVALID ' + + 'finding "Job \'NAME\' is declared twice in jobs" or "Object extension of \'OBJECT\' is declared twice in ' + + 'objectExtensions". The boot log carries no error saying a stack registers several extensions of one object ' + + 'under one id, and every field of the residual extension is served on its target object.', +}; diff --git a/packages/spec/src/stack-residual-extension-jobs.test.ts b/packages/spec/src/stack-residual-extension-jobs.test.ts new file mode 100644 index 00000000000..9fd0e753c37 --- /dev/null +++ b/packages/spec/src/stack-residual-extension-jobs.test.ts @@ -0,0 +1,220 @@ +/** + * The composition door for a `'preserve'` artifact's RESIDUAL — the top-level + * entries no package body claims, which the boot registers under the + * artifact's `manifest.id` — for the two collections it used to leave unjudged + * or misjudged: + * + * - `jobs`: two inputs without a manifest declaring one job name composed, and + * the boot's job binder then scheduled neither (measured through `os serve` + * on main `c30ce97cd7`: `NOT SCHEDULED` at `error`). They are refused here + * now, in the one-package wording, and the `jobs` row says what the runtime + * does with the pair. + * - `objectExtensions`: a residual entry registers under `manifest.id` + * (`@objectstack/objectql`), which under `'preserve'` is also the last + * input-with-a-manifest's body. The registry keeps one extension of a target + * per package, so a residual entry for a target that body extends too is + * refused with that body's entry, body first; a residual entry is told from + * a body's flattened copy by value, so one extending a target ANOTHER body + * extends composes, as two packages' extensions do. + * + * The engine half (the residual's fields are served) is pinned in + * `packages/objectql` (`manifest-service-residual-object-extension.test.ts`). + */ +import { describe, it, expect } from 'vitest'; +import { composeStacks, defineStack } from './stack.zod'; + +const sales = { id: 'com.example.sales', namespace: 'crm', name: 'sales', version: '1.0.0', type: 'app' as const }; +const billing = { id: 'com.example.billing', namespace: 'crm', name: 'billing', version: '1.0.0', type: 'module' as const }; + +const line = { name: 'crm_line', label: 'Line', sharingModel: 'private' as const, fields: { title: { type: 'text' as const, label: 'Title' } } }; +const extension = (field: string) => ({ extend: 'crm_line', fields: { [field]: { type: 'text' as const, label: field } } }); +const job = (label: string) => ({ + name: 'crm_nightly', + label, + schedule: { type: 'interval' as const, intervalMs: 60000 }, + body: { language: 'js' as const, source: 'return 1;', capabilities: [] }, +}); + +interface Refusal { name?: string; code?: string; status?: number; issues?: readonly string[]; message: string } + +function refusalOf(run: () => unknown): Refusal | null { + try { + run(); + return null; + } catch (e) { + return e as Refusal; + } +} + +function expectOneIssue(r: Refusal | null): asserts r is Refusal { + expect(r, 'refused').not.toBeNull(); + expect(r!.code).toBe('STACK_CROSS_REFERENCE_INVALID'); + expect(r!.status).toBe(422); + expect(r!.issues).toHaveLength(1); +} + +const JOB_CONSEQUENCE_AND_REMEDY = + 'The runtime keys jobs by name: the metadata keeps only the last of these entries, and the job scheduler ' + + 'refuses a name two enabled jobs share, so when both are enabled neither runs. Rename one of them, or merge them into a single entry.'; + +const EXTENSION_CONSEQUENCE_AND_REMEDY = + "The runtime applies one extension of a target object per package, so only the last of these entries' fields " + + "register and the others' are silently dropped. Merge them into a single `objectExtensions` entry for 'crm_line'."; + +describe('residual jobs under `preserve` are judged as one package', () => { + it('two manifest-less inputs declaring one job name: refused, naming both', () => { + const r = refusalOf(() => + composeStacks( + [ + defineStack({ manifest: sales, objects: [line] }), + defineStack({ manifest: billing }), + defineStack({ jobs: [job('First')] }), + defineStack({ jobs: [job('Second')] }), + ], + { manifest: 'preserve' }, + ), + ); + expectOneIssue(r); + expect(r.issues![0]).toBe( + "Job 'crm_nightly' is declared twice in `jobs`: stack #2 jobs[0] and stack #3 jobs[0]. " + JOB_CONSEQUENCE_AND_REMEDY, + ); + }); + + it('a single stack says the same of its pair: one row, every door', () => { + const r = refusalOf(() => defineStack({ jobs: [job('First'), job('Second')] })); + expect(r?.message).toContain( + "Job 'crm_nightly' is declared twice in `jobs`: stack.jobs[0] and stack.jobs[1]. " + JOB_CONSEQUENCE_AND_REMEDY, + ); + }); + + it('CONTROL: one residual job composes, carried at the top level', () => { + const composed = composeStacks( + [defineStack({ manifest: sales, objects: [line] }), defineStack({ manifest: billing }), defineStack({ jobs: [job('Only')] })], + { manifest: 'preserve' }, + ) as unknown as { packages: unknown[]; jobs: Array<{ name: string }> }; + expect(composed.packages).toHaveLength(2); + expect(composed.jobs.map((j) => j.name)).toEqual(['crm_nightly']); + }); + + it('CONTROL: a job each body declares stays each body\'s, not a residual pair', () => { + expect(refusalOf(() => + composeStacks( + [defineStack({ manifest: sales, objects: [line], jobs: [job('Sales')] }), defineStack({ manifest: billing, jobs: [job('Billing')] })], + { manifest: 'preserve' }, + ), + )).toBeNull(); + }); +}); + +describe('the residual door is not `preserve`-only: a multi-package input carries `packages[]` under every strategy', () => { + const nested = () => composeStacks( + [defineStack({ manifest: sales, objects: [line] }), defineStack({ manifest: billing })], + { manifest: 'preserve' }, + ); + + it.each(['first', 'last'] as const)('`%s`: two residual jobs of one name beside a nested artifact\'s packages[] are refused', (strategy) => { + const r = refusalOf(() => + composeStacks([nested(), defineStack({ jobs: [job('First')] }), defineStack({ jobs: [job('Second')] })], { manifest: strategy }), + ); + expectOneIssue(r); + expect(r.issues![0]).toMatch(/^Job 'crm_nightly' is declared twice in `jobs`: /); + expect(r.issues![0]).toContain(JOB_CONSEQUENCE_AND_REMEDY); + }); + + it('CONTROL: `last` with a nested artifact and one residual job composes, packages[] carried', () => { + const composed = composeStacks([nested(), defineStack({ jobs: [job('Only')] })], { manifest: 'last' }) as unknown as { packages?: unknown[] }; + expect(composed.packages, 'anti-vacuity: the artifact carries packages[]').toHaveLength(2); + }); +}); + +describe('a residual `objectExtensions` entry shares the slot of the body that carries `manifest.id`', () => { + it('a residual extension of a target that body extends too: refused, the body\'s entry first', () => { + // `'last'` keeps billing's manifest, so the residual registers as billing. + const r = refusalOf(() => + composeStacks( + [ + defineStack({ manifest: sales, objects: [line] }), + defineStack({ objectExtensions: [extension('cb_residual')] }), + defineStack({ manifest: billing, objectExtensions: [extension('cb_billing')] }), + ], + { manifest: 'preserve' }, + ), + ); + expectOneIssue(r); + expect(r.issues![0]).toBe( + "Object extension of 'crm_line' is declared twice in `objectExtensions`: 'com.example.billing' (stack #2) " + + `objectExtensions[0] and stack #1 objectExtensions[0]. ${EXTENSION_CONSEQUENCE_AND_REMEDY}`, + ); + }); + + it('a residual extension of a target ANOTHER body extends, with other fields: composes, carried at the top level', () => { + const composed = composeStacks( + [ + defineStack({ manifest: billing, objectExtensions: [extension('cb_billing')] }), + defineStack({ objectExtensions: [extension('cb_residual')] }), + defineStack({ manifest: sales, objects: [line] }), + ], + { manifest: 'preserve' }, + ) as unknown as { manifest: { id: string }; objectExtensions: Array<{ fields: Record }> }; + expect(composed.manifest.id).toBe(sales.id); + expect(composed.objectExtensions.map((e) => Object.keys(e.fields))).toEqual([['cb_billing'], ['cb_residual']]); + }); + + it('a residual entry EQUAL to the owning body\'s is that body\'s copy, not a pair', () => { + expect(refusalOf(() => + composeStacks( + [ + defineStack({ manifest: sales, objects: [line] }), + defineStack({ objectExtensions: [extension('cb_same')] }), + defineStack({ manifest: billing, objectExtensions: [extension('cb_same')] }), + ], + { manifest: 'preserve' }, + ), + )).toBeNull(); + }); + + it('two residual extensions of a target another body extends: refused as the residual\'s pair (claimed by value, not by target)', () => { + const r = refusalOf(() => + composeStacks( + [ + defineStack({ manifest: billing, objectExtensions: [extension('cb_billing')] }), + defineStack({ objectExtensions: [extension('cb_first')] }), + defineStack({ objectExtensions: [extension('cb_second')] }), + defineStack({ manifest: sales, objects: [line] }), + ], + { manifest: 'preserve' }, + ), + ); + expectOneIssue(r); + expect(r.issues![0]).toBe( + "Object extension of 'crm_line' is declared twice in `objectExtensions`: stack #1 objectExtensions[0] and " + + `stack #2 objectExtensions[0]. ${EXTENSION_CONSEQUENCE_AND_REMEDY}`, + ); + }); + + it('CONTROL: a package-claimed extension is unchanged — two packages each extending one target compose', () => { + const composed = composeStacks( + [ + defineStack({ manifest: sales, objects: [line], objectExtensions: [extension('cb_sales')] }), + defineStack({ manifest: billing, objectExtensions: [extension('cb_billing')] }), + ], + { manifest: 'preserve' }, + ) as unknown as { packages: Array<{ manifest: { objectExtensions?: unknown[] } }> }; + expect(composed.packages.map((p) => p.manifest.objectExtensions?.length)).toEqual([1, 1]); + }); + + it('CONTROL: the owning body\'s own pair is its own door\'s finding, reported once', () => { + const r = refusalOf(() => + composeStacks( + [ + defineStack({ manifest: sales, objects: [line] }), + defineStack({ pages: [{ name: 'crm_home', label: 'Home', type: 'app', regions: [] }] }), + defineStack({ manifest: billing, objectExtensions: [extension('cb_a'), extension('cb_b')] }, { strict: false }), + ], + { manifest: 'preserve' }, + ), + ); + expectOneIssue(r); + expect(r.issues![0]).toMatch(/^Object extension of 'crm_line' is declared twice in `objectExtensions`: '[a-z.]+' \(stack #2\) objectExtensions\[0\] and/); + }); +}); diff --git a/packages/spec/src/stack.zod.ts b/packages/spec/src/stack.zod.ts index 2fd398b6df3..1391b8a3946 100644 --- a/packages/spec/src/stack.zod.ts +++ b/packages/spec/src/stack.zod.ts @@ -383,6 +383,10 @@ function applyCollectionItemOwnerStampGate( * that no body declares is registered under `manifest.id` and its stamp is * judged at both doors, like every other residual item. * A package BODY's items of these collections are still judged, at both doors. + * This is the owner-stamp mirror only: the composition's duplicate-entry door + * still judges two top-level `jobs` no body declares as one package's + * ({@link residualEntryPredicate}), since the boot's job binder schedules + * neither of two enabled jobs of one name. * * Mirrored, because `@objectstack/spec` cannot import the rule it mirrors; a * `@objectstack/metadata` test holds the two equal, collection by collection. @@ -3285,6 +3289,12 @@ function collectDuplicateFunctionNameErrors(config: ObjectStackDefinition): stri * - `docs`: `os validate` and `os build` refused the pair (`docs/duplicate-name`) * while a source boot kept the last. * + * `jobs` left the first bullet since: the boot's job binder now refuses a name + * two enabled jobs share and schedules none of them (re-measured on main + * `c30ce97cd7` through `os serve`, two `'preserve'` inputs with no manifest: + * `NOT SCHEDULED` at `error`, neither job armed; a stack without `packages[]` + * takes the same binder judgement), so its row says that. + * * The identity is the string the registrars key an entry by: `name` for 26 * collections, the `(name, locale)` pair for `emailTemplates` (an i18n bundle * is one name across several locales), the extended object (`extend`) for @@ -3343,7 +3353,7 @@ function readEntryName(entry: unknown): string | undefined { const RENAME_OR_MERGE = (): string => 'Rename one of them, or merge them into a single entry.'; -/** The 23 collections whose boot keeps the last entry under a name, on both paths. */ +/** The 22 collections whose boot keeps the last entry under a name, on both paths. */ function lastWinsByName(noun: string, plural: string): SameStackEntryIdentity { return { identity: readEntryName, @@ -3371,7 +3381,14 @@ const SAME_STACK_ENTRY_IDENTITY = Object.freeze({ reports: lastWinsByName('Report', 'reports'), datasets: lastWinsByName('Dataset', 'datasets'), flows: lastWinsByName('Flow', 'flows'), - jobs: lastWinsByName('Job', 'jobs'), + jobs: { + identity: readEntryName, + subject: (name) => `Job '${name}'`, + consequence: () => + 'The runtime keys jobs by name: the metadata keeps only the last of these entries, and the job ' + + 'scheduler refuses a name two enabled jobs share, so when both are enabled neither runs.', + remedy: RENAME_OR_MERGE, + }, // An i18n bundle is one `name` across several `locale` tags, so the identity // is the pair — the registry's `ITEM_KEY_DISCRIMINATORS` entry, keyed as // `name@locale` with an untagged entry keyed as the floor tag (the schema's @@ -3564,7 +3581,16 @@ function collectPackageBodyDuplicateEntryErrors( * (ADR-0048 §3.4). What is left — a manifest-less input's entries, and the * own collections of an input that carries `packages[]` — is one package, * and two of its entries under one identity are refused with the one-stack - * wording. + * wording. That includes two of its `jobs` of one name: the boot reads jobs + * off the stack whole and its binder schedules neither. + * + * The residual registers under `manifest.id`, and under `'preserve'` that id + * is also a body's: the last input with a manifest. The registry keeps one + * extension of a target per package, so a residual `objectExtensions` entry + * for a target THAT body extends too shares its slot, and that body's entries + * for the target are judged here with the residual's, first, in the order the + * boot registers them ({@link ownerBodyExtensionEntries}): only the last + * entry's fields register, as the finding says. * * `objects` is skipped: two inputs declaring one object name is the * `objectConflict` strategy's to refuse or fold, and what that step composed @@ -3586,6 +3612,8 @@ function collectPackageBodyDuplicateEntryErrors( function collectComposedResidualDuplicateEntryErrors( stacks: readonly ObjectStackDefinition[], composedPackages: unknown, + ownerId: unknown, + preserve: boolean, ): string[] { const isResidual = residualEntryPredicate(composedPackages); return duplicateEntryFindings( @@ -3606,30 +3634,104 @@ function collectComposedResidualDuplicateEntryErrors( entries.push(item); } } + // An extension registers under its package id, and the residual's id is + // the body that carries `manifest.id` when one does: that body's entries + // for a target the residual extends too come first, as the boot + // registers that body before the residual. Only those: the body's own + // pairs are its own door's. + if (key === 'objectExtensions' && entries.length > 0) { + const identity = SAME_STACK_ENTRY_IDENTITY.objectExtensions.identity; + const targets = new Set(entries.map((e) => identity(e.entry))); + const owned = ownerBodyExtensionEntries(stacks, composedPackages, ownerId, preserve) + .filter((e) => identity(e.entry) !== undefined && targets.has(identity(e.entry))); + entries.unshift(...owned); + } return declared ? entries : undefined; }, new Set(['objects']), ); } +/** + * The `objectExtensions` entries of the package body that carries the composed + * artifact's `manifest.id` — the id the boot registers the residual under — + * labelled as the input that carries the body: a body a nested artifact + * carries at its `packages[p].manifest`, or, under `manifest: 'preserve'`, the + * body assembled from an input with that manifest and no `packages[]`. The + * registry keeps one extension of a target per package, so a residual entry + * for a target that body extends shares its slot. Empty when the artifact + * carries no body, or none under that id. + */ +function ownerBodyExtensionEntries( + stacks: readonly ObjectStackDefinition[], + composedPackages: unknown, + ownerId: unknown, + preserve: boolean, +): PackageCollectionEntry[] { + if (typeof ownerId !== 'string' || composedPackageBodies(composedPackages).length === 0) return []; + for (const [i, stack] of stacks.entries()) { + const label = stackLabel(stack, i); + const carried: unknown = (stack as Record).packages; + if (Array.isArray(carried)) { + for (const [p, entry] of carried.entries()) { + const body: unknown = isRecord(entry) ? entry.manifest : undefined; + if (isRecord(body) && body.id === ownerId) { + return labelledCollection(body, 'objectExtensions', `${label} packages[${p}].manifest.`) ?? []; + } + } + continue; + } + if (preserve && stack.manifest?.id === ownerId) { + return labelledCollection(stack as Record, 'objectExtensions', `${label} `) ?? []; + } + } + return []; +} + +/** The `packages[i].manifest` bodies a composed artifact carries, in order. */ +function composedPackageBodies(composedPackages: unknown): Record[] { + return Array.isArray(composedPackages) + ? composedPackages.flatMap((p: unknown) => (isRecord(p) && isRecord(p.manifest) ? [p.manifest] : [])) + : []; +} + /** * Whether a top-level entry of a composed artifact is in the package the boot * registers under the artifact's `manifest.id`. With no `packages[]` (or an * empty one) every entry is. With bodies, the boot's residual rule decides * ({@link isResidualTopLevelItem}, the mirror of `unclaimedTopLevel`), for the - * collections that rule walks by slot. The two table collections it does not - * walk by a slot of its own — `datasources` and `objectExtensions` (an - * extension is keyed by `extend`) — count an entry as claimed when a body - * carries one under the same identity ({@link SAME_STACK_ENTRY_IDENTITY}), so - * a body's flattened copy is never read as a second entry of the residual. + * collections that rule walks by slot. `objectExtensions` mirrors that rule's + * own reading of an extension, which has no slot: an entry is claimed when a + * body carries an entry EQUAL to it ({@link deepEqualAuthored}) — the copy a + * body's flattened top level repeats — so an entry extending a target some body + * also extends, with other fields, is the residual's own and registers under + * `manifest.id`. The two table collections judged here that the rule does not + * walk by a slot — `datasources`, and `jobs`, which it never files as residual + * ({@link TOP_LEVEL_COLLECTIONS_NEVER_RESIDUAL}) because the boot reads them off + * the stack whole — count an entry as claimed when a body carries one under the + * same identity ({@link SAME_STACK_ENTRY_IDENTITY}), so a body's flattened copy + * is never read as a second entry of the residual, while two entries that no + * body declares are judged as one package's: the boot's job binder schedules + * neither of two enabled jobs of one name. + * + * ⚠ Known gap, left to the binder and NOT judged here: the claim is by NAME, so + * a residual job whose name a package body's job also carries is read as that + * body's copy even when the two differ, and composes. The boot reads jobs off + * the stack whole, so it holds two enabled jobs of that name and its binder + * (`jobNameCollisions`, `@objectstack/runtime`) schedules neither — read from + * code, not driven. Two package bodies each declaring the name meet the same + * binder outcome and compose too (cross-package reuse, ADR-0048 §3.4). Whether + * composition should refuse a job name shared across packages is #36431's + * question, not this door's. */ function residualEntryPredicate(composedPackages: unknown): (key: string, entry: unknown) => boolean { - const bodies: Record[] = Array.isArray(composedPackages) - ? composedPackages.flatMap((p: unknown) => (isRecord(p) && isRecord(p.manifest) ? [p.manifest] : [])) - : []; + const bodies = composedPackageBodies(composedPackages); if (bodies.length === 0) return () => true; const bySlot = isResidualTopLevelItem(bodies); - const walkedBySlot: ReadonlySet = new Set(OWNER_STAMP_JUDGED_COLLECTIONS); + const walkedBySlot: ReadonlySet = new Set( + OWNER_STAMP_JUDGED_COLLECTIONS.filter((key) => !TOP_LEVEL_COLLECTIONS_NEVER_RESIDUAL.has(key)), + ); + const bodyExtensions = bodies.flatMap((body) => (Array.isArray(body.objectExtensions) ? body.objectExtensions : [])); const claimedByIdentity = new Map>(); const claimed = (key: keyof typeof SAME_STACK_ENTRY_IDENTITY): Set => { let set = claimedByIdentity.get(key); @@ -3648,6 +3750,7 @@ function residualEntryPredicate(composedPackages: unknown): (key: string, entry: }; return (key, entry) => { if (walkedBySlot.has(key)) return bySlot(key, entry); + if (key === 'objectExtensions') return !bodyExtensions.some((held) => held === entry || deepEqualAuthored(held, entry)); if (!(key in SAME_STACK_ENTRY_IDENTITY)) return true; const typed = key as keyof typeof SAME_STACK_ENTRY_IDENTITY; const identity = SAME_STACK_ENTRY_IDENTITY[typed].identity(entry); @@ -9735,7 +9838,7 @@ function composeBuiltStacks( ...collectComposedExternalBindingDatasourceErrors(stacks, objects), ...collectComposedDatasourceConnectorErrors(stacks, opts.manifest === 'preserve'), ...collectArtifactFlowClaimErrors(stacks), - ...collectComposedResidualDuplicateEntryErrors(stacks, composed.packages), + ...collectComposedResidualDuplicateEntryErrors(stacks, composed.packages, (composed.manifest as { id?: unknown } | undefined)?.id, opts.manifest === 'preserve'), ...collectComposedPackageBodyDuplicateEntryErrors(stacks, opts.manifest === 'preserve'), ]; if (artifactCrossRefErrors.length > 0) {