From 3c8f2d3129b96ceb6ad15f3abb6f7980f974473c Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 8 Nov 2026 23:19:30 +0000 Subject: [PATCH 01/11] feat(objectql): resolve a bare name by package over a caller-supplied holder set, and keep engine functions per package The package-scoped resolver's D3 steps now run over a holder source the caller supplies (resolvePackageScopedHolders); resolvePackageScopedName is that call over the registry's holders. The engine keeps every function registration by its package beside the bare name map (functionHoldersOf). No reader is wired. Claude-Session: https://claude.ai/code/session_01ADHkmQ5eMDSpkq6rYGLbBU Co-authored-by: Claude --- .../src/engine-hooks-and-functions.ts | 40 +++- packages/objectql/src/engine.ts | 24 +++ .../objectql/src/package-scoped-resolver.ts | 196 ++++++++++++++---- 3 files changed, 219 insertions(+), 41 deletions(-) diff --git a/packages/objectql/src/engine-hooks-and-functions.ts b/packages/objectql/src/engine-hooks-and-functions.ts index 9ede9a1a32d..31d72f0127d 100644 --- a/packages/objectql/src/engine-hooks-and-functions.ts +++ b/packages/objectql/src/engine-hooks-and-functions.ts @@ -53,6 +53,8 @@ import { assertValidHookExcludeObjects, assertValidHookObject, assertValidUnscopedMultiWriteFlag, hookMatchesObject, } from './engine-top-level.js'; import type { FunctionEntry, FunctionRegistrationOptions, HookEntry, HookHandler } from './engine-top-level.js'; +import { handlerOwnerPackageId } from './bare-name-one-holder.js'; +import type { PackageScopedHolderSource } from './package-scoped-resolver.js'; import type { ObjectQL } from './engine.js'; /** @@ -71,6 +73,7 @@ export interface HooksAndFunctionsHost { /** The engine itself: a moved body reads `this.facade` where the method read a bare `this` (#30020). */ readonly facade: ObjectQL; readonly functions: ObjectQL['functions']; + readonly functionHolders: ObjectQL['functionHolders']; getDriver: ObjectQL['getDriver']; readonly hooks: ObjectQL['hooks']; isClosedUnitHandle: ObjectQL['isClosedUnitHandle']; @@ -245,12 +248,22 @@ export class HooksAndFunctionsFacet { } /** The body of `ObjectQL#registerFunction`; the method's docblock there is its contract. */ - static registerFunction(this: Pick, name: string, handler: HookHandler, packageIdOrOptions?: string | FunctionRegistrationOptions): void { + static registerFunction(this: Pick, name: string, handler: HookHandler, packageIdOrOptions?: string | FunctionRegistrationOptions): void { if (!name || typeof handler !== 'function') return; const opts: FunctionRegistrationOptions = typeof packageIdOrOptions === 'string' ? { packageId: packageIdOrOptions } : (packageIdOrOptions ?? {}); const { packageId, effect } = opts; - this.functions.set(name, { handler, packageId, ...(effect ? { effect } : {}) }); + const entry: FunctionEntry = { handler, packageId, ...(effect ? { effect } : {}) }; + this.functions.set(name, entry); + // [ADR-0150 D4, #31716] The holder set beside the bare map: the entry + // under its package (the owner `app:` read as the id, as phase 1's + // claims read it), or under `null` for an owner-less registration. A + // second package's function of the same name is a second holder here, + // never a replacement; the bare map above still keeps the last one. + const holder = packageId ? handlerOwnerPackageId(packageId) : null; + let holders = this.functionHolders.get(name); + if (!holders) this.functionHolders.set(name, holders = new Map()); + holders.set(holder, entry); this.logger.debug('Registered function', { name, packageId, effect }); } @@ -265,7 +278,7 @@ export class HooksAndFunctionsFacet { } /** The body of `ObjectQL#unregisterFunctionsByPackage`; the method's docblock there is its contract. */ - static unregisterFunctionsByPackage(this: Pick, packageId: string): number { + static unregisterFunctionsByPackage(this: Pick, packageId: string): number { if (!packageId) return 0; let removed = 0; for (const [name, entry] of this.functions.entries()) { @@ -274,12 +287,33 @@ export class HooksAndFunctionsFacet { removed += 1; } } + // [ADR-0150 D4, #31716] The same registrations leave the holder set, + // including one the bare map had already replaced with another + // package's. The count stays the bare map's. + for (const [name, holders] of this.functionHolders) { + for (const [holder, entry] of holders) if (entry.packageId === packageId) holders.delete(holder); + if (holders.size === 0) this.functionHolders.delete(name); + } if (removed > 0) { this.logger.debug('Unregistered functions by package', { packageId, removed }); } return removed; } + /** The body of `ObjectQL#functionHoldersOf`; the method's docblock there is its contract. */ + static functionHoldersOf(this: Pick, name: string): PackageScopedHolderSource> { + // A snapshot: a registration after this call is not in it. Built here, not + // by the resolver module's `packageScopedHolderSource`, because this + // module is in the lean `./core` entry and the resolver module is not + // (it reads `@objectstack/metadata-protocol`, ADR-0076 D2). + const holders = new Map(this.functionHolders.get(name) ?? []); + return Object.freeze({ + packageHolders: Object.freeze([...holders.keys()].filter((id): id is string => id !== null)), + packageItem: (packageId: string) => holders.get(packageId), + environmentItem: () => holders.get(null), + }); + } + /** The body of `ObjectQL#bindHooks`; the method's docblock there is its contract. */ static bindHooks(this: Pick, hooks: any[] | undefined, opts?: { packageId?: string; diff --git a/packages/objectql/src/engine.ts b/packages/objectql/src/engine.ts index 0680e90390d..89f303fa973 100644 --- a/packages/objectql/src/engine.ts +++ b/packages/objectql/src/engine.ts @@ -383,6 +383,7 @@ export { } from './engine-top-level.js'; // [#29986 codemod] Class head: units, hooks, functions, body runners, hook dispatch: the methods of the same names below hand the bodies what they read (`HooksAndFunctionsHost`). import { HooksAndFunctionsFacet } from './engine-hooks-and-functions.js'; +import type { PackageScopedHolderSource } from './package-scoped-resolver.js'; // [#29986 codemod] Action system and packaged-action activation: the methods of the same names below hand the bodies what they read (`ActionsHost`). import { ActionsFacet, type ActionHandlerEntry } from './engine-actions.js'; // [#29986 codemod] Registration seams, readable-ids security, formula and default permissions: the methods of the same names below hand the bodies what they read (`SecurityResolversHost`). @@ -647,6 +648,14 @@ export class ObjectQL implements IObjectQLEngine { // `AppPlugin`, or directly via `engine.registerFunction(...)`. private functions = new Map(); + // [ADR-0150 D4, #31716] The same registrations by holder: function name → + // registering package (the owner read as its package id; `null` for an + // owner-less registration) → that package's entry. `functions` above keeps + // one entry per name, the last-registered; this keeps every holder, so a + // referrer's function can be resolved in its package + // (`resolvePackageScopedHolders` over `functionHoldersOf`). + private functionHolders = new Map>(); + // Realtime service for event publishing private realtimeService?: IRealtimeService; @@ -823,6 +832,20 @@ export class ObjectQL implements IObjectQLEngine { return HooksAndFunctionsFacet.resolveFunctionEntry.call(hooksAndFunctionsHost.of(this), name); } + /** + * Every holder of the function `name` (ADR-0150 D4): each package that + * registered one under that name, with its own entry, and an owner-less + * registration as the environment's own item — the holder set + * `resolvePackageScopedHolders` resolves a flow's or an action's function + * over, in the referrer's package. A snapshot, taken at the call. + * `resolveFunction` and `resolveFunctionEntry` keep answering the one + * last-registered entry per name. + */ + functionHoldersOf(name: string): PackageScopedHolderSource> { + // [#31716] The body lives in `engine-hooks-and-functions.ts` (see `HooksAndFunctionsHost`). + return HooksAndFunctionsFacet.functionHoldersOf.call(hooksAndFunctionsHost.of(this), name); + } + /** Remove all functions registered under a given `packageId`. */ unregisterFunctionsByPackage(packageId: string): number { // [#29986 codemod] The body moved to `engine-hooks-and-functions.ts` (see `HooksAndFunctionsHost`). @@ -9884,6 +9907,7 @@ export class ObjectQL implements IObjectQLEngine { get drivers() { return engine.drivers; }, facade: engine, get functions() { return engine.functions; }, + get functionHolders() { return engine.functionHolders; }, getDriver: (...a) => engine.getDriver(...a), get hooks() { return engine.hooks; }, isClosedUnitHandle: (...a) => engine.isClosedUnitHandle(...a), diff --git a/packages/objectql/src/package-scoped-resolver.ts b/packages/objectql/src/package-scoped-resolver.ts index cc8fb7929a3..d95d8cfdad9 100644 --- a/packages/objectql/src/package-scoped-resolver.ts +++ b/packages/objectql/src/package-scoped-resolver.ts @@ -70,10 +70,24 @@ * reachable package holds the name — the vocabulary's own reading — and * answers only when no other candidate of that step does. * + * ## Holders from a store other than the registry (child R2, #31716) + * + * The rule reads three things about a name: which packages hold it, one + * holder's item, and the environment's own item + * ({@link PackageScopedHolderSource}). {@link resolvePackageScopedHolders} + * runs the steps over a source the caller supplies, and + * {@link resolvePackageScopedName} is that call over the registry's holders, + * so the rule is written once. The other source is the engine's function + * registry: a function is not a metadata type, so it resolves in the package + * of the flow or action that names it (ADR-0150 D4's last row), over the + * `(package, function)` pairs the engine keeps (`ObjectQL#functionHoldersOf`). + * Same closure, same refusal, same baseline rule. + * * ## What it deliberately does not do * * - ⛔ Wire any reader, retire or narrow any phase-1 refusal, or change any - * spec (child R's scope). + * spec (child R's scope, and R2's: the function callers are a later + * child's). * - ⛔ Address an object-bound action by `(package, objectName, name)`: it * resolves the registry's `(type, name)` key, which is the object-less * action's whole identity; the object-bound key is child E2's. @@ -133,6 +147,22 @@ export function isPackageScopedType(type: unknown): type is PackageScopedType { return typeof type === 'string' && (PACKAGE_SCOPED_TYPES as readonly string[]).includes(type); } +/** + * The engine's function registry, as the resolver names its holders: not a + * metadata type (so not in {@link PACKAGE_SCOPED_TYPES}), and resolved in its + * referrer's package (ADR-0150 D4). Phase 1 spells the same registry the + * same way (`BARE_NAME_ONE_HOLDER_TYPES`). + */ +export const ENGINE_FUNCTION_TYPE = 'function'; + +/** What the resolver resolves: a type addressed by `(package, name)`, or the engine's functions. */ +export type PackageScopedResolvableType = PackageScopedType | typeof ENGINE_FUNCTION_TYPE; + +/** Does the resolver resolve `type` ({@link PackageScopedResolvableType})? */ +export function isPackageScopedResolvableType(type: unknown): type is PackageScopedResolvableType { + return type === ENGINE_FUNCTION_TYPE || isPackageScopedType(type); +} + /** * Names the PLATFORM requests by spelling, per type (ADR-0150 D3 Exceptions): * they resolve environment-wide whatever the caller's package, and keep one @@ -212,7 +242,7 @@ export type PackageScopedResolution = export interface PackageScopedRefusal { readonly status: 'refused'; readonly reason: PackageScopedRefusalReason; - readonly type: PackageScopedType; + readonly type: PackageScopedResolvableType; readonly name: string; /** The caller's package, or `null` for a caller with no package. */ readonly callerPackageId: string | null; @@ -222,19 +252,78 @@ export interface PackageScopedRefusal { readonly message: string; } -/** What the resolver is asked. */ -export interface PackageScopedQuery { - readonly type: PackageScopedType; +/** What the resolver is asked, over any holder source ({@link resolvePackageScopedHolders}). */ +export interface PackageScopedHoldersQuery { + readonly type: PackageScopedResolvableType; readonly name: string; /** * The package the caller belongs to; omitted, `null`, `''` or the * `sys_metadata` sentinel is a caller with no package. */ readonly callerPackageId?: string | null; +} + +/** What the resolver is asked, over the registry's holders ({@link resolvePackageScopedName}). */ +export interface PackageScopedQuery extends PackageScopedHoldersQuery { + readonly type: PackageScopedType; /** For a bundled type (`email_template`): one member, as `getItem` takes it. */ readonly member?: string; } +/** + * Who holds a name, and their items: the three things ADR-0150 D3's steps + * read, from whichever store keeps them — the registry + * ({@link resolvePackageScopedName}), or a store the caller supplies (the + * engine's function registry). Read only when a step needs it. + */ +export interface PackageScopedHolderSource { + /** Every package holding the name, each once, in the store's order. */ + readonly packageHolders: readonly string[]; + /** + * A package holder's item: its own, with whatever binds to it. `undefined` + * when it lacks what was asked (a bundle member), which answers not-found. + */ + packageItem(packageId: string): T | undefined; + /** + * The environment's own item of the name — bound to no package — or + * `undefined`. In the registry that is a package-less row under a name no + * package holds (D4: over a held name, the row is the holder's overlay). + */ + environmentItem(): T | undefined; +} + +/** + * A holder source over `(package, item)` pairs, a `null` package being the + * environment's own item. The order of the pairs is the store's order, which + * is the order every refusal names its candidates in. + * + * @throws {TypeError} when two pairs name one holder: a holder set holds each + * holder once, and the resolver never picks between two items of one holder. + */ +export function packageScopedHolderSource( + holdings: Iterable, +): PackageScopedHolderSource { + const items = new Map(); + for (const [packageId, item] of holdings) { + if (items.has(packageId)) { + throw new TypeError( + `[package-scoped-resolver] the holder set names ${packageId === null ? 'the environment' : `package "${packageId}"`} twice; ` + + `a holder holds a name once (ADR-0150 D3).`, + ); + } + items.set(packageId, item); + } + const packageHolders = [...items.keys()].filter((id): id is string => id !== null); + return Object.freeze({ + packageHolders: Object.freeze(packageHolders), + packageItem: (packageId: string) => items.get(packageId), + environmentItem: () => items.get(null), + }); +} + +/** The registry slice the closure reads ({@link packageResolutionClosure}). */ +export type PackageResolutionClosureRegistry = Pick; + /** The registry slice the resolver reads — every member of it, and no other. */ export type PackageScopedRegistry = Pick< SchemaRegistry, @@ -242,12 +331,12 @@ export type PackageScopedRegistry = Pick< >; /** Is `packageId`'s item of `type` an overridable baseline (the vocabulary's predicate)? */ -function isBaseline(type: PackageScopedType, packageId: string): boolean { +function isBaseline(type: PackageScopedResolvableType, packageId: string): boolean { return isBareNameOneHolderType(type) && isOverridableBaseline(type, packageId); } /** Every installed package of the reserved kernel namespace. */ -function kernelPackages(registry: PackageScopedRegistry): string[] { +function kernelPackages(registry: PackageResolutionClosureRegistry): string[] { const ids: string[] = []; for (const row of registry.getAllPackages()) { const manifest = (row as { manifest?: { id?: unknown; namespace?: unknown } } | undefined)?.manifest; @@ -263,7 +352,7 @@ function kernelPackages(registry: PackageScopedRegistry): string[] { * package the registry cannot produce declares nothing, so it reaches `sys` * only. */ -export function packageResolutionClosure(registry: PackageScopedRegistry, callerPackageId: string): ReadonlySet { +export function packageResolutionClosure(registry: PackageResolutionClosureRegistry, callerPackageId: string): ReadonlySet { const reach = new Set(packageDependencyClosure(callerPackageId, registry)?.dependencies ?? []); for (const id of kernelPackages(registry)) reach.add(id); reach.delete(callerPackageId); @@ -272,7 +361,7 @@ export function packageResolutionClosure(registry: PackageScopedRegistry, caller const packageHolder = (packageId: string): PackageScopedHolder => ({ kind: 'package', packageId }); -function typeLabel(type: PackageScopedType): string { +function typeLabel(type: PackageScopedResolvableType): string { switch (type) { case 'api': return 'API'; case 'email_template': return 'email template'; @@ -305,7 +394,7 @@ export function packageScopedRefusalMessage(refusal: Omit !isBaseline(type, id)); @@ -333,77 +422,108 @@ function pickUnique( return { kind: 'none' }; } -/** A package's item, as a resolution — or not-found when it lacks the asked bundle member. */ +/** A package's item, as a resolution — or not-found when it lacks what was asked. */ function packageItem( - registry: PackageScopedRegistry, - query: PackageScopedQuery, + source: PackageScopedHolderSource, packageId: string, via: PackageScopedResolutionStep, ): PackageScopedResolution { - const item = registry.getPackageScopedItem(query.type, query.name, packageId, query.member); + const item = source.packageItem(packageId); return item === undefined ? { status: 'not-found' } : { status: 'resolved', item, holder: packageHolder(packageId), via }; } /** A caller with no package, or a platform-requested name: the whole environment (ADR-0150 D3). */ function resolveEnvironmentWide( - registry: PackageScopedRegistry, - query: PackageScopedQuery, + query: PackageScopedHoldersQuery, callerPackageId: string | null, - holders: readonly string[], + source: PackageScopedHolderSource, ): PackageScopedResolution { - const environmentItem = registry.getEnvironmentScopedItem(query.type, query.name, query.member); + const environmentItem = source.environmentItem(); if (environmentItem !== undefined) { return { status: 'resolved', item: environmentItem, holder: { kind: 'environment' }, via: 'environment' }; } - const pick = pickUnique(query.type, holders); - if (pick.kind === 'one') return packageItem(registry, query, pick.packageId, pick.baseline ? 'baseline' : 'unique-holder'); + const pick = pickUnique(query.type, source.packageHolders); + if (pick.kind === 'one') return packageItem(source, pick.packageId, pick.baseline ? 'baseline' : 'unique-holder'); if (pick.kind === 'several') return refuse(query, callerPackageId, 'ambiguous-in-environment', pick.packageIds.map(packageHolder)); return { status: 'not-found' }; } /** - * Resolve a bare name by ADR-0150 D3 (module doc). Reads the registry, writes - * nothing, and never throws for a name — only for a type that is not - * addressed by package ({@link PACKAGE_SCOPED_TYPES}), which is a caller's - * programming error. + * Resolve a bare name by ADR-0150 D3 (module doc) over a holder set the + * caller supplies — the engine's function registry, or any store that keeps + * `(package, item)` pairs outside the registry. The closure is the registry's + * ({@link packageResolutionClosure}); the holders and their items are the + * source's. Writes nothing, and never throws for a name — only for a type the + * resolver does not resolve ({@link PackageScopedResolvableType}), which is a + * caller's programming error. * * @returns `resolved` with the item, its holder and the step that reached it; * `not-found` when nothing holds the name; `refused` naming every candidate * of the step that could not pick one. */ -export function resolvePackageScopedName( - registry: PackageScopedRegistry, - query: PackageScopedQuery, +export function resolvePackageScopedHolders( + registry: PackageResolutionClosureRegistry, + query: PackageScopedHoldersQuery, + source: PackageScopedHolderSource, ): PackageScopedResolution { - if (!isPackageScopedType(query.type)) { + if (!isPackageScopedResolvableType(query.type)) { throw new TypeError( - `[package-scoped-resolver] "${String(query.type)}" is not addressed by (package, name) (ADR-0150 D1); ` + + `[package-scoped-resolver] "${String(query.type)}" is not resolved by package (ADR-0150 D1, D4); ` + `positions are environment-scoped (D7) and objects keep their literal name (ADR-0129).`, ); } const raw = query.callerPackageId; const callerPackageId = typeof raw === 'string' && raw !== '' && raw !== OVERLAY_PROVENANCE_SENTINEL ? raw : null; - const holders = registry.packageScopedHoldersOf(query.type, query.name); + const holders = source.packageHolders; - if (callerPackageId === null || isPlatformRequestedBareName(query.type, query.name)) { - return resolveEnvironmentWide(registry, query, callerPackageId, holders); + if (callerPackageId === null || (query.type !== ENGINE_FUNCTION_TYPE && isPlatformRequestedBareName(query.type, query.name))) { + return resolveEnvironmentWide(query, callerPackageId, source); } // Step 1 — the caller package's own item. - if (holders.includes(callerPackageId)) return packageItem(registry, query, callerPackageId, 'own'); + if (holders.includes(callerPackageId)) return packageItem(source, callerPackageId, 'own'); // Step 2 — the unique holder in its declared closure, plus `sys`. const reach = packageResolutionClosure(registry, callerPackageId); const pick = pickUnique(query.type, holders.filter((id) => reach.has(id))); - if (pick.kind === 'one') return packageItem(registry, query, pick.packageId, pick.baseline ? 'baseline' : 'closure'); + if (pick.kind === 'one') return packageItem(source, pick.packageId, pick.baseline ? 'baseline' : 'closure'); if (pick.kind === 'several') return refuse(query, callerPackageId, 'ambiguous-in-closure', pick.packageIds.map(packageHolder)); // Step 3 — nothing reachable: a refusal naming every holder there is, or // not-found when there is none. ⛔ Never an environment-wide guess. const candidates: PackageScopedHolder[] = holders.map(packageHolder); - if (registry.getEnvironmentScopedItem(query.type, query.name, query.member) !== undefined) { - candidates.push({ kind: 'environment' }); - } + if (source.environmentItem() !== undefined) candidates.push({ kind: 'environment' }); if (candidates.length === 0) return { status: 'not-found' }; return refuse(query, callerPackageId, 'outside-closure', candidates); } + +/** + * Resolve a bare name by ADR-0150 D3 (module doc) over the registry's + * holders: {@link resolvePackageScopedHolders} with the registry as the + * source. Reads the registry, writes nothing, and never throws for a name — + * only for a type that is not addressed by package + * ({@link PACKAGE_SCOPED_TYPES}), which is a caller's programming error. + * + * @returns `resolved` with the item, its holder and the step that reached it; + * `not-found` when nothing holds the name; `refused` naming every candidate + * of the step that could not pick one. + */ +export function resolvePackageScopedName( + registry: PackageScopedRegistry, + query: PackageScopedQuery, +): PackageScopedResolution { + if (!isPackageScopedType(query.type)) { + throw new TypeError( + `[package-scoped-resolver] "${String(query.type)}" is not addressed by (package, name) (ADR-0150 D1); ` + + (query.type === ENGINE_FUNCTION_TYPE + ? 'the registry holds no function: resolve one over the engine\'s holders (resolvePackageScopedHolders, ADR-0150 D4).' + : 'positions are environment-scoped (D7) and objects keep their literal name (ADR-0129).'), + ); + } + const { type, name, member } = query; + return resolvePackageScopedHolders(registry, query, { + packageHolders: registry.packageScopedHoldersOf(type, name), + packageItem: (packageId) => registry.getPackageScopedItem(type, name, packageId, member), + environmentItem: () => registry.getEnvironmentScopedItem(type, name, member), + }); +} From 5e1dd2eb73689f7c90e4419cdc0742411bdb244e Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 8 Nov 2026 23:20:58 +0000 Subject: [PATCH 02/11] test(objectql): pin the holder-set entry's parity, the function holders and the red lines; export the entry Claude-Session: https://claude.ai/code/session_01ADHkmQ5eMDSpkq6rYGLbBU Co-authored-by: Claude --- .changeset/31716-function-holders-resolver.md | 13 + packages/objectql/src/index.ts | 8 + .../src/package-scoped-resolver.test.ts | 241 ++++++++++++++++++ 3 files changed, 262 insertions(+) create mode 100644 .changeset/31716-function-holders-resolver.md diff --git a/.changeset/31716-function-holders-resolver.md b/.changeset/31716-function-holders-resolver.md new file mode 100644 index 00000000000..68fee583379 --- /dev/null +++ b/.changeset/31716-function-holders-resolver.md @@ -0,0 +1,13 @@ +--- +'@objectstack/objectql': patch +--- + +feat(objectql): the package-scoped resolver takes holders from a source other than the registry, and the engine keeps each function's registering package (ADR-0150 D3/D4) + +Clause-②: no +Metadata-protocol: none + +- **`resolvePackageScopedHolders`** runs the ADR-0150 D3 rule over a holder set the caller supplies (`PackageScopedHolderSource`: the package holders, one holder's item, the environment's own item), with the same declared closure, the same refusals and the same baseline rule as `resolvePackageScopedName`, which is now that call over the registry's holders. `packageScopedHolderSource` builds a source from `(package, item)` pairs, a `null` package being the environment's own item. `ENGINE_FUNCTION_TYPE` (`'function'`) is the one type it resolves beside `PACKAGE_SCOPED_TYPES`: a function is not a metadata type, so it resolves in the package of the flow or action that names it (ADR-0150 D4). +- **`ObjectQL#functionHoldersOf(name)`** answers every holder of a function name: each package that registered one (the owner `app:PACKAGE_ID` read as the package id), with its own entry, and an owner-less registration as the environment's own item. + +Nothing changes for a running deployment: no reader calls either yet, `resolveFunction` and `resolveFunctionEntry` keep answering the one last-registered function per name, and phase 1's one-holder refusal stays in force. diff --git a/packages/objectql/src/index.ts b/packages/objectql/src/index.ts index 2212d1a622b..9780747433d 100644 --- a/packages/objectql/src/index.ts +++ b/packages/objectql/src/index.ts @@ -105,11 +105,15 @@ export { findPackageHeldSecurityCatalogNames } from './registry.js'; // the lean `./core` entry never imports (ADR-0076 D2). export { resolvePackageScopedName, + resolvePackageScopedHolders, + packageScopedHolderSource, packageResolutionClosure, packageScopedRefusalMessage, describePackageScopedHolder, isPackageScopedType, + isPackageScopedResolvableType, isPlatformRequestedBareName, + ENGINE_FUNCTION_TYPE, PACKAGE_SCOPED_TYPES, PLATFORM_REQUESTED_BARE_NAMES_BY_TYPE, KERNEL_NAMESPACE, @@ -118,6 +122,10 @@ export type { PackageScopedType, PackageScopedHolder, PackageScopedQuery, + PackageScopedHoldersQuery, + PackageScopedHolderSource, + PackageScopedResolvableType, + PackageResolutionClosureRegistry, PackageScopedRegistry, PackageScopedResolution, PackageScopedResolutionStep, diff --git a/packages/objectql/src/package-scoped-resolver.test.ts b/packages/objectql/src/package-scoped-resolver.test.ts index cb3e252d698..c2a39fbf697 100644 --- a/packages/objectql/src/package-scoped-resolver.test.ts +++ b/packages/objectql/src/package-scoped-resolver.test.ts @@ -19,6 +19,13 @@ * phase 1's one-holder rule (the registry sealed), the resolver answers every * covered type exactly as `getItem` does, so wiring a reader to it later * changes no answer a release gives today. + * + * Child R2 (#31716) adds the entry over a caller-supplied holder set + * (`resolvePackageScopedHolders`) and the engine's function holders + * (`ObjectQL#functionHoldersOf`): the `R2` blocks at the end. Their parity + * block holds the new entry, over the registry's holders, to exactly + * `resolvePackageScopedName`'s answer; their red-line pins were ablated the + * same way, readings in the PR body. */ import { describe, it, expect, beforeEach } from 'vitest'; @@ -26,12 +33,18 @@ import { SchemaRegistry } from './registry.js'; import { BARE_NAME_REGISTRY_TYPES, type BareNameRegistryType } from './bare-name-one-holder.js'; import { resolvePackageScopedName, + resolvePackageScopedHolders, + packageScopedHolderSource, packageResolutionClosure, + ENGINE_FUNCTION_TYPE, PACKAGE_SCOPED_TYPES, PLATFORM_REQUESTED_BARE_NAMES_BY_TYPE, + type PackageScopedHolderSource, type PackageScopedResolution, + type PackageScopedResolvableType, type PackageScopedType, } from './package-scoped-resolver.js'; +import { ObjectQL } from './engine.js'; import { packageDependencyClosure } from '@objectstack/metadata-protocol'; const A = 'com.acme.alpha'; @@ -431,3 +444,231 @@ describe('phase 1 parity — under the one-holder rule the resolver answers as ` expect(() => ship('flow', NAME, B)).toThrow(); }); }); + +// --------------------------------------------------------------------------- +// Child R2 (#31716): the rule over a holder set the caller supplies. +// --------------------------------------------------------------------------- + +/** The registry's holders of `(type, name)`, as `(package, item)` pairs. */ +const registryPairs = (type: PackageScopedType, name: string): Array<[string | null, unknown]> => { + const pairs: Array<[string | null, unknown]> = registry + .packageScopedHoldersOf(type, name) + .map((id) => [id, registry.getPackageScopedItem(type, name, id)]); + const environment = registry.getEnvironmentScopedItem(type, name); + if (environment !== undefined) pairs.push([null, environment]); + return pairs; +}; + +describe('R2 parity — the holder-set entry over the registry\'s holders answers as `resolvePackageScopedName`', () => { + const CALLERS = [undefined, null, '', 'sys_metadata', A, B, C, MID, P, SYS, 'com.acme.not_installed']; + + it('every caller, every arm: own, closure, unique holder, environment, baseline, platform-requested, ambiguous, outside, not-found', () => { + install(SYS, [], 'sys'); + install(EMAIL_BASELINE, [], 'sys'); + install(A); + install(B); + install(C); + install(MID, [A]); + install(P, [MID, B]); + ship('flow', 'own_and_closure', P); + ship('flow', 'own_and_closure', A); + ship('flow', 'closure_only', A); + ship('flow', 'two_in_closure', A); + ship('flow', 'two_in_closure', B); + ship('flow', 'outside_only', C); + ship('page', 'kernel_page', SYS, 'kernel'); + overlay('dataset', 'env_only', undefined, 'env'); + overlay('page', 'held_and_customized', undefined, 'env-custom'); + ship('page', 'held_and_customized', C); + ship('email_template', 'auth.password_reset', EMAIL_BASELINE, 'builtin'); + ship('email_template', 'baseline_beside_holder', EMAIL_BASELINE, 'builtin'); + ship('email_template', 'baseline_beside_holder', A); + ship('permission', 'guest_portal', C); + const names: Array<[PackageScopedType, string]> = [ + ['flow', 'own_and_closure'], ['flow', 'closure_only'], ['flow', 'two_in_closure'], ['flow', 'outside_only'], + ['page', 'kernel_page'], ['dataset', 'env_only'], ['page', 'held_and_customized'], + ['email_template', 'auth.password_reset'], ['email_template', 'baseline_beside_holder'], + ['permission', 'guest_portal'], ['flow', 'nothing_here'], + ]; + const seen = new Set(); + for (const [type, name] of names) { + for (const callerPackageId of CALLERS) { + const expected = resolvePackageScopedName(registry, { type, name, callerPackageId }); + const actual = resolvePackageScopedHolders(registry, { type, name, callerPackageId }, packageScopedHolderSource(registryPairs(type, name))); + expect(actual, `${type} ${name} for ${String(callerPackageId)}`).toEqual(expected); + seen.add(expected.status === 'resolved' ? expected.via : expected.status === 'refused' ? expected.reason : 'not-found'); + } + } + // The matrix reaches every arm of the rule, so the equality above is about all of them. + expect([...seen].sort()).toEqual([ + 'ambiguous-in-closure', 'ambiguous-in-environment', 'baseline', 'closure', 'environment', + 'not-found', 'outside-closure', 'own', 'unique-holder', + ]); + }); + + it('a bundled type: the holder-set entry answers the member the source serves', () => { + install(A); + install(P, [A]); + ship('email_template', 'welcome', A); + registry.registerItem('email_template', { ...body('email_template', 'welcome', 'alpha-zh'), locale: 'zh-CN' }, 'name' as never, A); + for (const member of ['zh-CN', undefined, 'fr-FR']) { + const source: PackageScopedHolderSource = { + packageHolders: registry.packageScopedHoldersOf('email_template', 'welcome'), + packageItem: (id) => registry.getPackageScopedItem('email_template', 'welcome', id, member), + environmentItem: () => registry.getEnvironmentScopedItem('email_template', 'welcome', member), + }; + expect(resolvePackageScopedHolders(registry, { type: 'email_template', name: 'welcome', callerPackageId: P }, source)) + .toEqual(resolvePackageScopedName(registry, { type: 'email_template', name: 'welcome', callerPackageId: P, member })); + } + }); +}); + +describe('R2 — the holder source and the types the entry resolves', () => { + it('builds a source from `(package, item)` pairs: package holders in order, `null` as the environment', () => { + const source = packageScopedHolderSource([[B, 'b'], [null, 'env'], [A, 'a']]); + expect(source.packageHolders).toEqual([B, A]); + expect(source.packageItem(A)).toBe('a'); + expect(source.packageItem(C)).toBeUndefined(); + expect(source.environmentItem()).toBe('env'); + expect(packageScopedHolderSource([[A, 'a']]).environmentItem()).toBeUndefined(); + }); + + it('refuses a holder set that names one holder twice: nothing picks between its two items', () => { + expect(() => packageScopedHolderSource([[A, 1], [A, 2]])).toThrow(TypeError); + expect(() => packageScopedHolderSource([[null, 1], [null, 2]])).toThrow(TypeError); + }); + + it('resolves `function` over a supplied source, and the registry entry refuses it: the registry holds no function', () => { + install(A); + install(P, [A]); + const source = packageScopedHolderSource([[A, 'alpha fn']]); + expect(resolvePackageScopedHolders(registry, { type: ENGINE_FUNCTION_TYPE, name: 'score', callerPackageId: P }, source)) + .toMatchObject({ status: 'resolved', item: 'alpha fn', via: 'closure', holder: { kind: 'package', packageId: A } }); + expect(() => resolve('function' as PackageScopedType, 'score', P)).toThrow(TypeError); + }); + + it('positions and objects are not resolved over a supplied source either', () => { + const source = packageScopedHolderSource([[A, 'x']]); + for (const type of ['position', 'object']) { + expect(() => resolvePackageScopedHolders(registry, { type: type as PackageScopedResolvableType, name: 'n' }, source)).toThrow(TypeError); + } + }); +}); + +describe('R2 — engine functions resolve in their referrer\'s package (ADR-0150 D4)', () => { + let engine: ObjectQL; + const fn = (tag: string) => Object.assign(() => tag, { tag }); + const installOn = (id: string, deps: string[] = [], namespace?: string) => engine.registry.installPackage(manifest(id, deps, namespace), 'code'); + const resolveFn = (name: string, callerPackageId?: string | null) => + resolvePackageScopedHolders(engine.registry, { type: ENGINE_FUNCTION_TYPE, name, callerPackageId }, engine.functionHoldersOf(name)); + const tagOf = (r: PackageScopedResolution) => + r.status === 'resolved' ? ((r.item as { handler: { tag?: string } }).handler.tag) : undefined; + + beforeEach(() => { + engine = new ObjectQL(); + engine.registry.logLevel = 'silent'; + }); + + it('keeps every package\'s function of one name, the owner `app:ID` read as the package; the bare map still keeps the last', () => { + engine.registerFunction('score', fn('alpha'), `app:${A}`); + engine.registerFunction('score', fn('beta'), { packageId: B, effect: 'writes' }); + expect((engine.resolveFunction('score') as unknown as { tag: string }).tag).toBe('beta'); + const holders = engine.functionHoldersOf('score'); + expect(holders.packageHolders).toEqual([A, B]); + expect((holders.packageItem(A)?.handler as unknown as { tag: string }).tag).toBe('alpha'); + expect(holders.packageItem(B)).toMatchObject({ packageId: B, effect: 'writes' }); + expect(holders.environmentItem()).toBeUndefined(); + expect(engine.functionHoldersOf('nothing_here').packageHolders).toEqual([]); + }); + + it('a package re-registering its function replaces its own entry, never adds a holder', () => { + engine.registerFunction('score', fn('alpha-1'), `app:${A}`); + engine.registerFunction('score', fn('alpha-2'), `app:${A}`); + expect(engine.functionHoldersOf('score').packageHolders).toEqual([A]); + expect((engine.functionHoldersOf('score').packageItem(A)?.handler as unknown as { tag: string }).tag).toBe('alpha-2'); + }); + + it('own, then the closure: a flow of P resolves its dependency\'s function, each holder its own', () => { + installOn(A); + installOn(B); + installOn(P, [A]); + engine.registerFunction('score', fn('alpha'), `app:${A}`); + engine.registerFunction('score', fn('beta'), `app:${B}`); + expect(resolveFn('score', P)).toMatchObject({ status: 'resolved', via: 'closure', holder: { packageId: A } }); + expect(tagOf(resolveFn('score', P))).toBe('alpha'); + expect(tagOf(resolveFn('score', A))).toBe('alpha'); + expect(tagOf(resolveFn('score', B))).toBe('beta'); + engine.registerFunction('score', fn('caller'), `app:${P}`); + expect(resolveFn('score', P)).toMatchObject({ status: 'resolved', via: 'own' }); + expect(tagOf(resolveFn('score', P))).toBe('caller'); + }); + + it('red line 1: two holders in the closure refuse — no first- or last-registered pick', () => { + installOn(A); + installOn(B); + installOn(P, [A, B]); + engine.registerFunction('score', fn('alpha'), `app:${A}`); + engine.registerFunction('score', fn('beta'), `app:${B}`); + expect(resolveFn('score', P)).toMatchObject({ status: 'refused', reason: 'ambiguous-in-closure', type: 'function', callerPackageId: P }); + expect(resolveFn('score')).toMatchObject({ status: 'refused', reason: 'ambiguous-in-environment', callerPackageId: null }); + }); + + it('red line 1: a function held only outside the closure is refused, never served', () => { + installOn(C); + installOn(P); + engine.registerFunction('score', fn('gamma'), `app:${C}`); + const r = resolveFn('score', P); + expect(r).toMatchObject({ status: 'refused', reason: 'outside-closure', candidates: [{ kind: 'package', packageId: C }] }); + expect(r.status === 'refused' && r.message).toContain('The function "score"'); + }); + + it('red line 2: every refusal names every holder, and the environment', () => { + for (const id of [A, B, C]) installOn(id); + installOn(P, [A, B, C]); + installOn(MID); + for (const id of [A, B, C]) engine.registerFunction('score', fn(id), `app:${id}`); + const inClosure = resolveFn('score', P); + if (inClosure.status !== 'refused') throw new Error(`expected a refusal, got ${inClosure.status}`); + expect(inClosure.candidates).toEqual([A, B, C].map((packageId) => ({ kind: 'package', packageId }))); + for (const id of [A, B, C]) expect(inClosure.message).toContain(`package "${id}"`); + engine.registerFunction('score', fn('host')); + const outside = resolveFn('score', MID); + if (outside.status !== 'refused') throw new Error(`expected a refusal, got ${outside.status}`); + expect(outside.reason).toBe('outside-closure'); + expect(outside.candidates).toEqual([...[A, B, C].map((packageId) => ({ kind: 'package', packageId })), { kind: 'environment' }]); + }); + + it('an owner-less registration is the environment\'s own: a caller with no package gets it, a package caller is refused (D3 (a))', () => { + installOn(P); + engine.registerFunction('score', fn('host')); + expect(engine.functionHoldersOf('score').packageHolders).toEqual([]); + expect(resolveFn('score')).toMatchObject({ status: 'resolved', via: 'environment', holder: { kind: 'environment' } }); + expect(resolveFn('score', P)).toMatchObject({ status: 'refused', reason: 'outside-closure', candidates: [{ kind: 'environment' }] }); + }); + + it('a `sys` package\'s function is in every caller\'s closure', () => { + installOn(SYS, [], 'sys'); + installOn(P); + engine.registerFunction('now_utc', fn('kernel'), `app:${SYS}`); + expect(resolveFn('now_utc', P)).toMatchObject({ status: 'resolved', via: 'closure', holder: { packageId: SYS } }); + }); + + it('unregistering a package removes its holder, even one the bare map had already replaced', () => { + installOn(A); + installOn(B); + engine.registerFunction('score', fn('alpha'), `app:${A}`); + engine.registerFunction('score', fn('beta'), `app:${B}`); + expect(engine.unregisterFunctionsByPackage(`app:${A}`)).toBe(0); // the bare map holds B's: its count is unchanged + expect(engine.functionHoldersOf('score').packageHolders).toEqual([B]); + expect(engine.unregisterFunctionsByPackage(`app:${B}`)).toBe(1); + expect(engine.functionHoldersOf('score').packageHolders).toEqual([]); + expect(resolveFn('score')).toEqual({ status: 'not-found' }); + }); + + it('a holder set is a snapshot: a later registration is not in it', () => { + engine.registerFunction('score', fn('alpha'), `app:${A}`); + const holders = engine.functionHoldersOf('score'); + engine.registerFunction('score', fn('beta'), `app:${B}`); + expect(holders.packageHolders).toEqual([A]); + }); +}); From 3ddac4b74bf92f1774557c79bc4bb11145de3dab Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 8 Nov 2026 23:28:30 +0000 Subject: [PATCH 03/11] refactor(core, metadata-core): host the package-scoped resolution rule and its closure walk where lean readers reach them The D3 rule moves into @objectstack/core as a pure function over a caller-supplied holder set and closure, with its refusal vocabulary. The closure walk (resolvePackageClosure, the App-pair widening, the declared closure and the resolution closure with sys) moves into @objectstack/metadata-core. lint, metadata-protocol and objectql re-export every moved name unchanged; objectql keeps two adapters, the registry's and the engine functions'. Claude-Session: https://claude.ai/code/session_01ADHkmQ5eMDSpkq6rYGLbBU Co-authored-by: Claude --- .changeset/31716-function-holders-resolver.md | 13 - .changeset/31716-package-scoped-rule-lean.md | 19 + packages/core/src/index.ts | 6 + .../src/package-scoped-resolution.test.ts | 154 +++++ .../core/src/package-scoped-resolution.ts | 536 ++++++++++++++++ ...ntime-gate.resolve-package-closure.test.ts | 8 + packages/lint/src/runtime-gate.ts | 48 +- packages/metadata-core/src/index.ts | 9 + packages/metadata-core/src/package-closure.ts | 192 ++++++ .../src/protocol-write-package-scope.test.ts | 26 + .../src/protocol-write-package-scope.ts | 97 +-- packages/objectql/src/bare-name-one-holder.ts | 117 +--- .../src/engine-hooks-and-functions.ts | 15 +- packages/objectql/src/engine.ts | 6 +- packages/objectql/src/index.ts | 15 +- .../src/package-scoped-resolver.test.ts | 52 +- .../objectql/src/package-scoped-resolver.ts | 599 ++++-------------- 17 files changed, 1181 insertions(+), 731 deletions(-) delete mode 100644 .changeset/31716-function-holders-resolver.md create mode 100644 .changeset/31716-package-scoped-rule-lean.md create mode 100644 packages/core/src/package-scoped-resolution.test.ts create mode 100644 packages/core/src/package-scoped-resolution.ts create mode 100644 packages/metadata-core/src/package-closure.ts create mode 100644 packages/metadata-protocol/src/protocol-write-package-scope.test.ts diff --git a/.changeset/31716-function-holders-resolver.md b/.changeset/31716-function-holders-resolver.md deleted file mode 100644 index 68fee583379..00000000000 --- a/.changeset/31716-function-holders-resolver.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -'@objectstack/objectql': patch ---- - -feat(objectql): the package-scoped resolver takes holders from a source other than the registry, and the engine keeps each function's registering package (ADR-0150 D3/D4) - -Clause-②: no -Metadata-protocol: none - -- **`resolvePackageScopedHolders`** runs the ADR-0150 D3 rule over a holder set the caller supplies (`PackageScopedHolderSource`: the package holders, one holder's item, the environment's own item), with the same declared closure, the same refusals and the same baseline rule as `resolvePackageScopedName`, which is now that call over the registry's holders. `packageScopedHolderSource` builds a source from `(package, item)` pairs, a `null` package being the environment's own item. `ENGINE_FUNCTION_TYPE` (`'function'`) is the one type it resolves beside `PACKAGE_SCOPED_TYPES`: a function is not a metadata type, so it resolves in the package of the flow or action that names it (ADR-0150 D4). -- **`ObjectQL#functionHoldersOf(name)`** answers every holder of a function name: each package that registered one (the owner `app:PACKAGE_ID` read as the package id), with its own entry, and an owner-less registration as the environment's own item. - -Nothing changes for a running deployment: no reader calls either yet, `resolveFunction` and `resolveFunctionEntry` keep answering the one last-registered function per name, and phase 1's one-holder refusal stays in force. diff --git a/.changeset/31716-package-scoped-rule-lean.md b/.changeset/31716-package-scoped-rule-lean.md new file mode 100644 index 00000000000..0a928127946 --- /dev/null +++ b/.changeset/31716-package-scoped-rule-lean.md @@ -0,0 +1,19 @@ +--- +'@objectstack/core': patch +'@objectstack/metadata-core': patch +'@objectstack/lint': patch +'@objectstack/metadata-protocol': patch +'@objectstack/objectql': patch +--- + +feat(core, metadata-core, objectql): the package-scoped resolution rule and its closure walk move where every reader reaches them, and engine functions resolve in their referrer's package (ADR-0150 D3/D4) + +Clause-②: no +Metadata-protocol: none + +- **`@objectstack/core`** exports `resolvePackageScopedHolders`, the ADR-0150 D3 rule as a pure function: a caller of package P is answered P's own item, else the unique holder in P's resolution closure, else a refusal naming every candidate; a caller with no package the environment's own item, else the unique package holder, else the refusal. The holders come from a `PackageScopedHolderSource` the caller supplies (`packageScopedHolderSource` builds one from `(package, item)` pairs, a `null` package being the environment's own item), and the closure from a function the caller supplies. The refusal vocabulary moves with it: `PACKAGE_SCOPED_TYPES`, `ENGINE_FUNCTION_TYPE`, `PLATFORM_REQUESTED_BARE_NAMES_BY_TYPE`, `OVERRIDABLE_BASELINE_PACKAGES`, `BARE_NAME_ONE_HOLDER_TYPES`, `describeBareNameHolder` and the refusal and resolution types. +- **`@objectstack/metadata-core`** exports the one closure walk: `resolvePackageClosure` (moved from `@objectstack/lint`), `widenPairClosureToAppMembers` and `packageDependencyClosure` (moved from `@objectstack/metadata-protocol`), and `packageResolutionClosure` with `KERNEL_NAMESPACE` (moved from `@objectstack/objectql`): the declared dependency closure plus every `sys` package. +- **`@objectstack/lint`**, **`@objectstack/metadata-protocol`** and **`@objectstack/objectql`** re-export every moved name under the name they published, so no import changes. objectql's `resolvePackageScopedName` keeps its signature and answers, now as the rule's call over the registry's holders. +- **`@objectstack/objectql`** adds `resolvePackageScopedFunction`, the rule's call over the engine's function holders, and `ObjectQL#functionHoldersOf(name)`: every package that registered a function of that name (the owner `app:PACKAGE_ID` read as the package id), with its own entry, and an owner-less registration as the environment's own item. + +Nothing changes for a running deployment: no reader calls the rule yet, `resolveFunction` and `resolveFunctionEntry` keep answering the one last-registered function per name, the save door admits and refuses exactly what it did, and phase 1's one-holder refusal stays in force. diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 03aace854e0..fe2fa96faf0 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -22,6 +22,12 @@ export * from './artifact-packages.js'; // `@objectstack/cloud-connection`'s ledger rehydrate), and it sorts with // `resolvePluginOrder` above. export * from './hydration-order.js'; +// [ADR-0150 D3, epic #31527 child R2] The one rule for which package's item a +// bare name means: D3's steps over a holder set and a closure the caller +// supplies, and the refusal vocabulary. Here because its readers sit inside +// objectql's lean entry, below it (the security catalog) and above it; every +// one of them already depends on this package. +export * from './package-scoped-resolution.js'; // [#22301] The two halves of resolving an app's `requires` that `os serve` // (`@objectstack/cli`) and the verification handle (`@objectstack/verify`) both // read — the package-owned collection reader (ADR-0130 D4) and the token → diff --git a/packages/core/src/package-scoped-resolution.test.ts b/packages/core/src/package-scoped-resolution.test.ts new file mode 100644 index 00000000000..8cf7740946b --- /dev/null +++ b/packages/core/src/package-scoped-resolution.test.ts @@ -0,0 +1,154 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The package-scoped resolution rule (ADR-0150 D3) as a pure function of a + * holder set and a closure — epic #31527 child R2 (#31716). No registry: the + * holders are plain `(package, item)` pairs and the closure a plain map, so + * every arm is pinned on the rule alone. objectql's two adapters (the + * registry's holders, the engine's function holders) are pinned against this + * in `packages/objectql/src/package-scoped-resolver.test.ts`. + * + * The `red line` cases are negative pins: each was ablated once (the loosened + * behaviour put back, the pin read red, restored), readings in the PR body. + */ + +import { describe, expect, it } from 'vitest'; +import { + ENGINE_FUNCTION_TYPE, + OVERRIDABLE_BASELINE_PACKAGES, + packageScopedHolderSource, + resolvePackageScopedHolders, + type PackageResolutionClosureOf, + type PackageScopedResolvableType, +} from './package-scoped-resolution.js'; + +const A = 'com.acme.alpha'; +const B = 'com.acme.beta'; +const C = 'com.acme.gamma'; +const P = 'com.acme.caller'; +const EMAIL = [...OVERRIDABLE_BASELINE_PACKAGES.email_template][0]; + +/** A closure where `P` reaches `reach`, and every other caller reaches nothing. */ +const closure = (reach: readonly string[]): PackageResolutionClosureOf => (caller) => new Set(caller === P ? reach : []); + +const resolve = ( + pairs: Array<[string | null, string]>, + reach: readonly string[], + callerPackageId?: string | null, + type: PackageScopedResolvableType = 'flow', + name = 'send_email', +) => resolvePackageScopedHolders({ type, name, callerPackageId }, packageScopedHolderSource(pairs), closure(reach)); + +describe('ADR-0150 D3 over a supplied holder set — a caller that belongs to a package', () => { + it("answers the caller's own item before a closure holder", () => { + expect(resolve([[A, 'a'], [P, 'p']], [A], P)).toEqual({ status: 'resolved', item: 'p', holder: { kind: 'package', packageId: P }, via: 'own' }); + }); + + it('answers the unique holder in the closure; a holder outside it is no candidate', () => { + expect(resolve([[C, 'c'], [A, 'a']], [A], P)).toEqual({ status: 'resolved', item: 'a', holder: { kind: 'package', packageId: A }, via: 'closure' }); + }); + + it('asks the closure only when the caller holds no item itself', () => { + let asked = 0; + const counting: PackageResolutionClosureOf = () => { asked += 1; return new Set(); }; + resolvePackageScopedHolders({ type: 'flow', name: 'n', callerPackageId: P }, packageScopedHolderSource([[P, 'p']]), counting); + expect(asked).toBe(0); + resolvePackageScopedHolders({ type: 'flow', name: 'n', callerPackageId: P }, packageScopedHolderSource([[A, 'a']]), counting); + expect(asked).toBe(1); + }); + + it('zero holders is not-found', () => { + expect(resolve([], [A], P)).toEqual({ status: 'not-found' }); + }); + + it('a holder that lacks what was asked answers not-found, never another holder', () => { + const source = { packageHolders: [A], packageItem: () => undefined, environmentItem: () => undefined }; + expect(resolvePackageScopedHolders({ type: 'email_template', name: 'welcome', callerPackageId: P }, source, closure([A]))).toEqual({ status: 'not-found' }); + }); +}); + +describe('ADR-0150 D3 over a supplied holder set — a caller with no package', () => { + it("answers the environment's own item first, then the unique package holder", () => { + expect(resolve([[A, 'a'], [null, 'env']], [])).toMatchObject({ status: 'resolved', item: 'env', via: 'environment', holder: { kind: 'environment' } }); + expect(resolve([[A, 'a']], [])).toMatchObject({ status: 'resolved', item: 'a', via: 'unique-holder' }); + }); + + it('reads `null`, `""` and the `sys_metadata` sentinel as no caller package, and never asks the closure', () => { + const never: PackageResolutionClosureOf = () => { throw new Error('asked'); }; + for (const caller of [undefined, null, '', 'sys_metadata']) { + expect(resolvePackageScopedHolders({ type: 'flow', name: 'n', callerPackageId: caller }, packageScopedHolderSource([[A, 'a']]), never)) + .toMatchObject({ status: 'resolved', via: 'unique-holder' }); + } + }); +}); + +describe('red line 1 — the rule never loosens', () => { + it('two holders in the closure refuse: no first- or last-listed pick', () => { + expect(resolve([[A, 'a'], [B, 'b']], [A, B], P)).toMatchObject({ status: 'refused', reason: 'ambiguous-in-closure', callerPackageId: P }); + }); + + it('two package holders refuse a caller with no package', () => { + expect(resolve([[A, 'a'], [B, 'b']], [])).toMatchObject({ status: 'refused', reason: 'ambiguous-in-environment', callerPackageId: null }); + }); + + it('a name held only outside the closure is refused, never an environment-wide guess', () => { + expect(resolve([[C, 'c']], [A], P)).toMatchObject({ status: 'refused', reason: 'outside-closure', candidates: [{ kind: 'package', packageId: C }] }); + }); + + it("a package caller is refused the environment's own item (D3 (a))", () => { + expect(resolve([[null, 'env']], [A], P)).toMatchObject({ status: 'refused', reason: 'outside-closure', candidates: [{ kind: 'environment' }] }); + }); +}); + +describe('red line 2 — every refusal names every candidate', () => { + it('in the closure, in the environment and outside the closure', () => { + const three: Array<[string | null, string]> = [[A, 'a'], [B, 'b'], [C, 'c']]; + const packages = [A, B, C].map((packageId) => ({ kind: 'package', packageId })); + for (const [reach, caller] of [[[A, B, C], P], [[], undefined]] as const) { + const r = resolve(three, reach, caller); + if (r.status !== 'refused') throw new Error(`expected a refusal, got ${r.status}`); + expect(r.candidates).toEqual(packages); + for (const id of [A, B, C]) expect(r.message).toContain(`package "${id}"`); + } + const outside = resolve([...three, [null, 'env']], [], P); + if (outside.status !== 'refused') throw new Error(`expected a refusal, got ${outside.status}`); + expect(outside.candidates).toEqual([...packages, { kind: 'environment' }]); + expect(outside.message).toContain('the environment'); + }); +}); + +describe('ADR-0150 D3 exceptions over a supplied holder set', () => { + it('a platform-requested name resolves environment-wide whatever the caller', () => { + expect(resolve([[C, 'c']], [], P, 'permission', 'guest_portal')).toMatchObject({ status: 'resolved', via: 'unique-holder' }); + expect(resolve([[C, 'c']], [], P, 'permission', 'sales_rep')).toMatchObject({ status: 'refused', reason: 'outside-closure' }); + }); + + it('an overridable baseline yields to another holder of the step, and answers when it is the only one', () => { + expect(resolve([[EMAIL, 'builtin']], [EMAIL], P, 'email_template', 'auth.password_reset')).toMatchObject({ status: 'resolved', via: 'baseline' }); + expect(resolve([[EMAIL, 'builtin'], [A, 'a']], [EMAIL, A], P, 'email_template', 'auth.password_reset')).toMatchObject({ status: 'resolved', item: 'a', via: 'closure' }); + expect(resolve([[EMAIL, 'builtin'], [A, 'a']], [], undefined, 'email_template', 'auth.password_reset')).toMatchObject({ status: 'resolved', item: 'a', via: 'unique-holder' }); + }); + + it('resolves the engine\'s functions, and refuses positions and objects', () => { + expect(resolve([[A, 'fn']], [A], P, ENGINE_FUNCTION_TYPE, 'score')).toMatchObject({ status: 'resolved', via: 'closure' }); + for (const type of ['position', 'object']) { + expect(() => resolve([[A, 'x']], [A], P, type as PackageScopedResolvableType)).toThrow(TypeError); + } + }); +}); + +describe('the holder source', () => { + it('keeps the pairs\' order, `null` as the environment, and is a snapshot', () => { + const pairs: Array<[string | null, string]> = [[B, 'b'], [null, 'env'], [A, 'a']]; + const source = packageScopedHolderSource(pairs); + pairs.push([C, 'c']); + expect(source.packageHolders).toEqual([B, A]); + expect(source.packageItem(A)).toBe('a'); + expect(source.environmentItem()).toBe('env'); + }); + + it('refuses a holder named twice: nothing picks between its two items', () => { + expect(() => packageScopedHolderSource([[A, 1], [A, 2]])).toThrow(TypeError); + expect(() => packageScopedHolderSource([[null, 1], [null, 2]])).toThrow(TypeError); + }); +}); diff --git a/packages/core/src/package-scoped-resolution.ts b/packages/core/src/package-scoped-resolution.ts new file mode 100644 index 00000000000..8481b6c9613 --- /dev/null +++ b/packages/core/src/package-scoped-resolution.ts @@ -0,0 +1,536 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * # The one rule for "which package's item does this bare name mean" (ADR-0150 D3) + * + * The pure core of the package-scoped resolver: D3's three steps over a holder + * set and a dependency closure the CALLER supplies, the refusal it answers and + * the vocabulary that refusal is written in. It reads no registry and imports + * nothing, so every reader can call it, wherever it sits. + * + * ## Why this lives in `@objectstack/core` (epic #31527, child R2) + * + * The readers epic #31527 wires sit at three depths: inside objectql's lean + * `./core` entry (`SchemaRegistry`, the engine's action and function + * registries), below objectql (`@objectstack/core`'s security catalog), and + * above it (the automation service, the plugins). ADR-0076 D2 keeps + * `@objectstack/metadata-protocol` out of the lean entry, and objectql's first + * resolver read its closure there, so the first two depths could not call it. + * A second, local copy of the rule at either depth is the drift child R exists + * to prevent. `@objectstack/core` is a dependency of every one of them and is + * in the lean entry's admitted set, so hosting the rule here adds no package + * edge. Its two inputs come from the caller: + * + * - **the holders** ({@link PackageScopedHolderSource}): objectql's + * `resolvePackageScopedName` builds them from `SchemaRegistry` (the + * per-package overlay slot of D4), and the engine's function registry + * from its per-package function map (D4's last row); + * - **the closure** of the caller package: its declared dependencies plus + * every `sys` package — `packageResolutionClosure` in + * `@objectstack/metadata-core`, the save door's own walk. + * + * ## The rule (ADR-0150 D3, as ruled) + * + * A caller that belongs to package P resolves a bare name to: + * + * 1. **P's own item**; + * 2. else **the unique holder in P's resolution closure** — its declared + * dependency closure (ADR-0141) plus every package of the reserved kernel + * namespace `sys` (D2); + * 3. else a **refusal that names every candidate**. + * + * A caller with no package (an environment item, a context-free door, an MCP + * client) resolves against the whole environment: the environment's own item + * first (ADR-0005 overlay precedence), else the unique package holder, else + * the refusal naming every candidate (the doors map it to `409`, D5). + * + * **Zero holders is not-found, never a refusal.** + * + * ## The two red lines (epic #31527) + * + * - **It never loosens.** No first-registered fallback, no environment-wide + * guess for a caller with a package (a holder outside P's closure is + * refused, never served), and no silent pick between two candidates of + * one step. + * - **Ambiguity is reported, never guessed.** Every refusal carries every + * candidate of the step that refused. + * + * ## The exceptions (ADR-0150 D3, ruled) + * + * - **Names the platform requests by spelling** + * ({@link PLATFORM_REQUESTED_BARE_NAMES_BY_TYPE}): environment-wide whatever + * the caller, one holder. + * - **Positions** are one environment-wide slot (D7), and objects keep their + * literal name (ADR-0129): neither is a {@link PackageScopedResolvableType}, + * and asking for one throws. + * - **An overridable baseline** ({@link OVERRIDABLE_BASELINE_PACKAGES}) answers + * only when no other candidate of that step does. + */ + +// --------------------------------------------------------------------------- +// The holder vocabulary (phase 1's, ADR-0048 §3.4 as narrowed; objectql's +// `bare-name-one-holder.ts` holds the rule it is written for and re-exports +// these, so there is one copy of each). +// --------------------------------------------------------------------------- + +/** + * A type phase 1's one-holder rule covers that the registry stores — its items + * reach the engine's package door and the registry's item seam. + */ +export type BareNameRegistryType = + | 'picklist' | 'mapping' | 'dataset' + | 'api' | 'action' + | 'flow' | 'webhook' | 'connector' | 'email_template' + | 'agent' | 'skill'; + +/** + * A type phase 1 covers: a registry type, or `function` — the engine's + * function registry, which a package reaches through the hook binder's bind + * alone. + */ +export type BareNameOneHolderType = BareNameRegistryType | 'function'; + +/** + * Every type phase 1 covers, in the order a refusal and a cold boot list them: + * one family after another, each in the order its change named them. + */ +export const BARE_NAME_ONE_HOLDER_TYPES: readonly BareNameOneHolderType[] = Object.freeze([ + // the data family + 'picklist', + 'mapping', + 'dataset', + // the request family + 'api', + 'action', + 'function', + // the flow family + 'flow', + 'webhook', + 'connector', + 'email_template', + // the AI family + 'agent', + 'skill', +]); + +/** Is `type` one of the types phase 1 covers? */ +export function isBareNameOneHolderType(type: unknown): type is BareNameOneHolderType { + return typeof type === 'string' && (BARE_NAME_ONE_HOLDER_TYPES as readonly string[]).includes(type); +} + +/** + * Per covered type, the packages whose items are an OVERRIDABLE BASELINE: the + * platform's copies, which that type's one consumer serves any other package's + * same-named item over, by contract. Such a package neither holds a name of + * that type nor is refused one under phase 1, and under ADR-0150 D3 (b) it + * ranks below every other holder of a step. + * + * `email_template`: the email service declares the built-in auth templates + * under its own package id (`EmailServicePlugin.init`, `@objectstack/plugin-email`), + * and its template loader picks any other package's `(name, locale)` member + * before the built-in's (`BUILTIN_EMAIL_TEMPLATES_PACKAGE_ID` there — the + * same spelling, held together by the flow family's booted dogfood pin: an + * app overriding a built-in template installs only while the two agree). + */ +export const OVERRIDABLE_BASELINE_PACKAGES: Readonly>> = Object.freeze({ + picklist: new Set(), + mapping: new Set(), + dataset: new Set(), + api: new Set(), + action: new Set(), + function: new Set(), + flow: new Set(), + webhook: new Set(), + connector: new Set(), + email_template: new Set(['com.objectstack.service.email']), + agent: new Set(), + skill: new Set(), +}); + +/** + * Is `packageId`'s item of `type` an overridable baseline + * ({@link OVERRIDABLE_BASELINE_PACKAGES}) — never a holder, never judged? + */ +export function isOverridableBaseline(type: BareNameOneHolderType, packageId: string | undefined): boolean { + return packageId !== undefined && OVERRIDABLE_BASELINE_PACKAGES[type].has(packageId); +} + +/** Who holds a covered name under phase 1: a package, or the platform as a built-in. */ +export type BareNameHolder = + | { readonly kind: 'package'; readonly packageId: string } + | { readonly kind: 'built-in' }; + +/** How a refusal names a holder. */ +export function describeBareNameHolder(holder: BareNameHolder): string { + return holder.kind === 'package' + ? `package "${holder.packageId}"` + : 'the platform, as a built-in name no package can declare'; +} + +// --------------------------------------------------------------------------- +// What the rule resolves. +// --------------------------------------------------------------------------- + +/** + * The metadata types addressed by `(package, name)` — ADR-0150 D1 buckets 2 + * and 3, as the registry spells them. `rag_pipeline` (bucket 3 in D1) has no + * registry type since ADR-0049 retired the collection, so it is not listed; + * `position` is environment-scoped (D7) and is not listed either. + */ +export const PACKAGE_SCOPED_TYPES = Object.freeze([ + // bucket 2 + 'flow', + 'action', + 'hook', + 'job', + 'webhook', + 'mapping', + 'connector', + 'permission', + 'sharing_rule', + 'queue', + 'assignment_rule', + 'app', + 'page', + 'dashboard', + 'report', + 'dataset', + 'analytics_cube', + 'picklist', + 'email_template', + 'book', + 'api', + // bucket 3 + 'tool', + 'skill', + 'agent', +] as const); + +/** A type addressed by `(package, name)` ({@link PACKAGE_SCOPED_TYPES}). */ +export type PackageScopedType = (typeof PACKAGE_SCOPED_TYPES)[number]; + +/** Is `type` addressed by `(package, name)`? */ +export function isPackageScopedType(type: unknown): type is PackageScopedType { + return typeof type === 'string' && (PACKAGE_SCOPED_TYPES as readonly string[]).includes(type); +} + +/** + * The engine's function registry, as the rule names its holders: not a + * metadata type (so not in {@link PACKAGE_SCOPED_TYPES}), and resolved in the + * package of the flow or action that names it (ADR-0150 D4's last row). + * Phase 1 spells the same registry the same way ({@link BARE_NAME_ONE_HOLDER_TYPES}). + */ +export const ENGINE_FUNCTION_TYPE = 'function'; + +/** What the rule resolves: a type addressed by `(package, name)`, or the engine's functions. */ +export type PackageScopedResolvableType = PackageScopedType | typeof ENGINE_FUNCTION_TYPE; + +/** Does the rule resolve `type` ({@link PackageScopedResolvableType})? */ +export function isPackageScopedResolvableType(type: unknown): type is PackageScopedResolvableType { + return type === ENGINE_FUNCTION_TYPE || isPackageScopedType(type); +} + +/** + * Names the PLATFORM requests by spelling, per type (ADR-0150 D3 Exceptions): + * they resolve environment-wide whatever the caller's package, and keep one + * holder. The same list as `@objectstack/cli`'s `PLATFORM_REQUESTED_BARE_NAMES`, + * keyed by registry type instead of stack collection: the public form doors' + * submit context requests the permission set `guest_portal` by name + * (`packages/rest/src/form-routes.ts`). + */ +export const PLATFORM_REQUESTED_BARE_NAMES_BY_TYPE: Readonly>> = Object.freeze({ + permission: Object.freeze(['guest_portal']), +}); + +/** Is `(type, name)` one the platform requests by spelling? */ +export function isPlatformRequestedBareName(type: PackageScopedType, name: string): boolean { + return PLATFORM_REQUESTED_BARE_NAMES_BY_TYPE[type]?.includes(name) ?? false; +} + +/** The value `_packageId` carries for a row rehydrated from `sys_metadata`: not a package. */ +const OVERLAY_PROVENANCE_SENTINEL = 'sys_metadata'; + +// --------------------------------------------------------------------------- +// The answer. +// --------------------------------------------------------------------------- + +/** + * Who holds a name under package addressing: a package (the vocabulary's own + * {@link BareNameHolder}), or the environment's own item — an item authored in + * this environment, in the implicit environment package (ADR-0150 D1 bucket 4). + */ +export type PackageScopedHolder = + | Extract + | { readonly kind: 'environment' }; + +/** How a refusal names a holder. */ +export function describePackageScopedHolder(holder: PackageScopedHolder): string { + return holder.kind === 'environment' + ? 'the environment (an item authored in this environment, bound to no package)' + : describeBareNameHolder(holder); +} + +/** How the resolved item was reached (ADR-0150 D3's steps). */ +export type PackageScopedResolutionStep = + /** the caller package's own item */ + | 'own' + /** the unique holder in the caller's declared dependency closure (plus `sys`) */ + | 'closure' + /** the environment's own item (a caller with no package) */ + | 'environment' + /** the unique package holder in the environment (a caller with no package) */ + | 'unique-holder' + /** an overridable baseline, reached because no other candidate of the step holds the name */ + | 'baseline'; + +/** Why a resolution refused. */ +export type PackageScopedRefusalReason = + /** two or more holders in the caller package's declared closure (plus `sys`) */ + | 'ambiguous-in-closure' + /** two or more package holders in the environment, and the caller names no package */ + | 'ambiguous-in-environment' + /** holders exist, and none is in the caller package's declared closure (plus `sys`) */ + | 'outside-closure'; + +/** A resolution's answer. */ +export type PackageScopedResolution = + | { + readonly status: 'resolved'; + readonly item: T; + readonly holder: PackageScopedHolder; + readonly via: PackageScopedResolutionStep; + } + | { readonly status: 'not-found' } + | PackageScopedRefusal; + +/** A refusal: every candidate named, and nothing picked. */ +export interface PackageScopedRefusal { + readonly status: 'refused'; + readonly reason: PackageScopedRefusalReason; + readonly type: PackageScopedResolvableType; + readonly name: string; + /** The caller's package, or `null` for a caller with no package. */ + readonly callerPackageId: string | null; + /** Every candidate of the step that refused, in the item store's order. */ + readonly candidates: readonly PackageScopedHolder[]; + /** One sentence naming the item, every candidate and what to do. */ + readonly message: string; +} + +// --------------------------------------------------------------------------- +// The inputs. +// --------------------------------------------------------------------------- + +/** What the rule is asked. */ +export interface PackageScopedHoldersQuery { + readonly type: PackageScopedResolvableType; + readonly name: string; + /** + * The package the caller belongs to; omitted, `null`, `''` or the + * `sys_metadata` sentinel is a caller with no package. + */ + readonly callerPackageId?: string | null; +} + +/** + * Who holds a name, and their items: the three things the rule reads, from + * whichever store keeps them. Read only when a step needs it. + */ +export interface PackageScopedHolderSource { + /** Every package holding the name, each once, in the store's order. */ + readonly packageHolders: readonly string[]; + /** + * A package holder's item: its own, with whatever binds to it. `undefined` + * when it lacks what was asked (a bundle member), which answers not-found. + */ + packageItem(packageId: string): T | undefined; + /** + * The environment's own item of the name — bound to no package — or + * `undefined`. In the registry that is a package-less row under a name no + * package holds (ADR-0150 D4: over a held name, the row is the holder's + * overlay). + */ + environmentItem(): T | undefined; +} + +/** + * A caller package's resolution closure (ADR-0150 D3 step 2): the packages + * other than itself whose items it may resolve a bare name to — its declared + * dependency closure plus every `sys` package. Asked only for a caller with a + * package that holds no item of the name itself. + */ +export type PackageResolutionClosureOf = (callerPackageId: string) => ReadonlySet; + +/** + * A holder source over `(package, item)` pairs, a `null` package being the + * environment's own item. The order of the pairs is the store's order, which + * is the order every refusal names its candidates in. A snapshot: the pairs + * are read once, here. + * + * @throws {TypeError} when two pairs name one holder: a holder set holds each + * holder once, and the rule never picks between two items of one holder. + */ +export function packageScopedHolderSource( + holdings: Iterable, +): PackageScopedHolderSource { + const items = new Map(); + for (const [packageId, item] of holdings) { + if (items.has(packageId)) { + throw new TypeError( + `[package-scoped-resolution] the holder set names ${packageId === null ? 'the environment' : `package "${packageId}"`} twice; ` + + 'a holder holds a name once (ADR-0150 D3).', + ); + } + items.set(packageId, item); + } + const packageHolders = Object.freeze([...items.keys()].filter((id): id is string => id !== null)); + return Object.freeze({ + packageHolders, + packageItem: (packageId: string) => items.get(packageId), + environmentItem: () => items.get(null), + }); +} + +// --------------------------------------------------------------------------- +// The rule. +// --------------------------------------------------------------------------- + +/** Is `packageId`'s item of `type` an overridable baseline (the vocabulary's predicate)? */ +function isBaseline(type: PackageScopedResolvableType, packageId: string): boolean { + return isBareNameOneHolderType(type) && isOverridableBaseline(type, packageId); +} + +const packageHolder = (packageId: string): PackageScopedHolder => ({ kind: 'package', packageId }); + +function typeLabel(type: PackageScopedResolvableType): string { + switch (type) { + case 'api': return 'API'; + case 'email_template': return 'email template'; + case 'sharing_rule': return 'sharing rule'; + case 'assignment_rule': return 'assignment rule'; + case 'analytics_cube': return 'analytics cube'; + case 'permission': return 'permission set'; + default: return type; + } +} + +/** + * The sentence a refusal carries: the item, why it refused, every candidate + * (in the vocabulary's words) and the one thing a caller can do about it. + */ +export function packageScopedRefusalMessage(refusal: Omit): string { + const subject = `The ${typeLabel(refusal.type)} "${refusal.name}"`; + const named = refusal.candidates.map(describePackageScopedHolder).join('; '); + switch (refusal.reason) { + case 'ambiguous-in-closure': + return `${subject} is held by ${refusal.candidates.length} packages in the declared dependency closure of ` + + `package "${refusal.callerPackageId}": ${named}. Nothing picks one of them: address it by its package.`; + case 'ambiguous-in-environment': + return `${subject} is held by ${refusal.candidates.length} packages in this environment and the caller names ` + + `no package: ${named}. Nothing picks one of them: address it by its package.`; + case 'outside-closure': + return `${subject} is held outside the declared dependency closure of package "${refusal.callerPackageId}": ` + + `${named}. Declare a dependency on the package that holds it (ADR-0141).`; + } +} + +function refuse( + query: PackageScopedHoldersQuery, + callerPackageId: string | null, + reason: PackageScopedRefusalReason, + candidates: readonly PackageScopedHolder[], +): PackageScopedRefusal { + const base = { status: 'refused' as const, reason, type: query.type, name: query.name, callerPackageId, candidates }; + return { ...base, message: packageScopedRefusalMessage(base) }; +} + +/** + * The one step of ADR-0150 D3 that picks among package holders: exactly one + * candidate other than an overridable baseline answers; two or more refuse, + * naming every one; none falls to the baselines by the same rule; `none` when + * no candidate holds the name at all. + */ +function pickUnique( + type: PackageScopedResolvableType, + candidates: readonly string[], +): { kind: 'one'; packageId: string; baseline: boolean } | { kind: 'several'; packageIds: string[] } | { kind: 'none' } { + const primary = candidates.filter((id) => !isBaseline(type, id)); + if (primary.length === 1) return { kind: 'one', packageId: primary[0], baseline: false }; + if (primary.length > 1) return { kind: 'several', packageIds: primary }; + const baselines = candidates.filter((id) => isBaseline(type, id)); + if (baselines.length === 1) return { kind: 'one', packageId: baselines[0], baseline: true }; + if (baselines.length > 1) return { kind: 'several', packageIds: baselines }; + return { kind: 'none' }; +} + +/** A package's item, as a resolution — or not-found when it lacks what was asked. */ +function packageItem( + source: PackageScopedHolderSource, + packageId: string, + via: PackageScopedResolutionStep, +): PackageScopedResolution { + const item = source.packageItem(packageId); + return item === undefined ? { status: 'not-found' } : { status: 'resolved', item, holder: packageHolder(packageId), via }; +} + +/** A caller with no package, or a platform-requested name: the whole environment (ADR-0150 D3). */ +function resolveEnvironmentWide( + query: PackageScopedHoldersQuery, + callerPackageId: string | null, + source: PackageScopedHolderSource, +): PackageScopedResolution { + const environmentItem = source.environmentItem(); + if (environmentItem !== undefined) { + return { status: 'resolved', item: environmentItem, holder: { kind: 'environment' }, via: 'environment' }; + } + const pick = pickUnique(query.type, source.packageHolders); + if (pick.kind === 'one') return packageItem(source, pick.packageId, pick.baseline ? 'baseline' : 'unique-holder'); + if (pick.kind === 'several') return refuse(query, callerPackageId, 'ambiguous-in-environment', pick.packageIds.map(packageHolder)); + return { status: 'not-found' }; +} + +/** + * Resolve a bare name by ADR-0150 D3 (module doc) over the holders `source` + * supplies and the closure `closureOf` supplies. Writes nothing, and never + * throws for a name — only for a type the rule does not resolve + * ({@link PackageScopedResolvableType}), which is a caller's programming error. + * + * @returns `resolved` with the item, its holder and the step that reached it; + * `not-found` when nothing holds the name; `refused` naming every candidate + * of the step that could not pick one. + */ +export function resolvePackageScopedHolders( + query: PackageScopedHoldersQuery, + source: PackageScopedHolderSource, + closureOf: PackageResolutionClosureOf, +): PackageScopedResolution { + if (!isPackageScopedResolvableType(query.type)) { + throw new TypeError( + `[package-scoped-resolution] "${String(query.type)}" is not resolved by package (ADR-0150 D1, D4); ` + + 'positions are environment-scoped (D7) and objects keep their literal name (ADR-0129).', + ); + } + const raw = query.callerPackageId; + const callerPackageId = typeof raw === 'string' && raw !== '' && raw !== OVERLAY_PROVENANCE_SENTINEL ? raw : null; + const holders = source.packageHolders; + + if (callerPackageId === null || (query.type !== ENGINE_FUNCTION_TYPE && isPlatformRequestedBareName(query.type, query.name))) { + return resolveEnvironmentWide(query, callerPackageId, source); + } + + // Step 1 — the caller package's own item. + if (holders.includes(callerPackageId)) return packageItem(source, callerPackageId, 'own'); + + // Step 2 — the unique holder in its resolution closure. + const reach = closureOf(callerPackageId); + const pick = pickUnique(query.type, holders.filter((id) => reach.has(id))); + if (pick.kind === 'one') return packageItem(source, pick.packageId, pick.baseline ? 'baseline' : 'closure'); + if (pick.kind === 'several') return refuse(query, callerPackageId, 'ambiguous-in-closure', pick.packageIds.map(packageHolder)); + + // Step 3 — nothing reachable: a refusal naming every holder there is, or + // not-found when there is none. ⛔ Never an environment-wide guess. + const candidates: PackageScopedHolder[] = holders.map(packageHolder); + if (source.environmentItem() !== undefined) candidates.push({ kind: 'environment' }); + if (candidates.length === 0) return { status: 'not-found' }; + return refuse(query, callerPackageId, 'outside-closure', candidates); +} diff --git a/packages/lint/src/runtime-gate.resolve-package-closure.test.ts b/packages/lint/src/runtime-gate.resolve-package-closure.test.ts index 270561a7c98..d72412bcfbc 100644 --- a/packages/lint/src/runtime-gate.resolve-package-closure.test.ts +++ b/packages/lint/src/runtime-gate.resolve-package-closure.test.ts @@ -9,6 +9,7 @@ import { describe, expect, it } from 'vitest'; import { resolvePackageClosure } from './runtime-gate.js'; import * as runtimeEntry from './runtime.js'; +import * as metadataCore from '@objectstack/metadata-core'; type Pkg = { manifest?: unknown }; @@ -63,3 +64,10 @@ describe('resolvePackageClosure (#28240)', () => { expect(runtimeEntry.resolvePackageClosure).toBe(resolvePackageClosure); }); }); + +describe('resolvePackageClosure is the one walk (epic #31527 child R2)', () => { + it('is `@objectstack/metadata-core`\'s own function, re-exported: lint computes no second closure', () => { + expect(resolvePackageClosure).toBe(metadataCore.resolvePackageClosure); + expect(runtimeEntry.resolvePackageClosure).toBe(metadataCore.resolvePackageClosure); + }); +}); diff --git a/packages/lint/src/runtime-gate.ts b/packages/lint/src/runtime-gate.ts index c6fdac31637..4d26ce0bf18 100644 --- a/packages/lint/src/runtime-gate.ts +++ b/packages/lint/src/runtime-gate.ts @@ -570,46 +570,16 @@ const OVERLAY_PROVENANCE_SENTINEL = 'sys_metadata'; /** * The package closure a write by `packageId` is judged against (#9612): the * package and the transitive closure of the `dependencies` its manifest - * declares, read through `getPackage` — the host's package registry on the - * server (`resolveWritePackageScope` in `@objectstack/metadata-protocol`), the - * served package list in Studio, whose object pickers offer what this closure - * admits. ONE walk for both, so the picker and the publish gate cannot - * disagree about what a package may reference. - * - * Answers `undefined` — narrow nothing — for no package id, the - * `sys_metadata` sentinel (an overlay row, not a package), and a package - * `getPackage` cannot produce: its manifest is the only declaration of what it - * may reference, and narrowing without it would be narrowing on nothing. - * - * A declared dependency `getPackage` cannot produce is still IN the closure: - * the package declared it, so an object stamped with it is reachable by - * declaration. Only the transitive walk stops there. - * - * Pure. A `getPackage` that throws propagates; the caller decides what an - * unreadable registry means (the server answers `undefined`). + * declares. ONE walk for the server's publish gate and Studio's object + * pickers, so the two cannot disagree about what a package may reference. + * + * [epic #31527 child R2] The walk lives in `@objectstack/metadata-core` + * (`package-closure.ts`, its docblock is the contract), beside the App-pair + * widening and the package-scoped resolution closure that read it, so the + * readers inside objectql's lean entry read the same walk. Re-exported here + * under its name, so this package's surface is unchanged. */ -export function resolvePackageClosure( - packageId: string | null | undefined, - getPackage: (id: string) => { manifest?: unknown } | undefined, -): { packageId: string; dependencies: string[] } | undefined { - if (typeof packageId !== 'string' || packageId === '' || packageId === OVERLAY_PROVENANCE_SENTINEL) return undefined; - if (!getPackage(packageId)) return undefined; - - const dependencies = new Set(); - const frontier = [packageId]; - while (frontier.length > 0) { - const current = frontier.pop() as string; - const manifest = getPackage(current)?.manifest as { dependencies?: Record } | undefined; - const declared = manifest?.dependencies; - if (!declared || typeof declared !== 'object') continue; - for (const dep of Object.keys(declared)) { - if (dep === packageId || dependencies.has(dep)) continue; - dependencies.add(dep); - frontier.push(dep); - } - } - return { packageId, dependencies: [...dependencies] }; -} +export { resolvePackageClosure } from '@objectstack/metadata-core'; /** * The context collections the snapshot carries, in stack-key order — DERIVED diff --git a/packages/metadata-core/src/index.ts b/packages/metadata-core/src/index.ts index aafb62b4986..261b52a1090 100644 --- a/packages/metadata-core/src/index.ts +++ b/packages/metadata-core/src/index.ts @@ -177,3 +177,12 @@ export * from './package-upgrade-verdict.js'; // this is the one package all four declare; the id rule stays in // `@objectstack/spec/kernel`. export * from './customization-pair-lookup.js'; + +// [ADR-0141, ADR-0150 D3 · epic #31527 child R2] A package's declared +// dependency closure — the one walk the save door, the runtime authoring gate, +// Studio's object pickers and the package-scoped resolution rule all read +// (`resolvePackageClosure`, `packageDependencyClosure`, +// `packageResolutionClosure`). Here because the rule's readers sit inside +// objectql's lean entry, which `@objectstack/metadata-protocol` stays out of, +// and every one of them already depends on this package. +export * from './package-closure.js'; diff --git a/packages/metadata-core/src/package-closure.ts b/packages/metadata-core/src/package-closure.ts new file mode 100644 index 00000000000..6385f762a30 --- /dev/null +++ b/packages/metadata-core/src/package-closure.ts @@ -0,0 +1,192 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * # A package's declared dependency closure — the one walk (ADR-0141, ADR-0150 D3) + * + * Every reader that asks "which packages may package P reach" reads this + * module, so no two can disagree: + * + * - the save door's write scope (`resolveWritePackageScope` in + * `@objectstack/metadata-protocol`) and the runtime authoring gate + * (`@objectstack/lint` `runtime`), which judge what a write by P may + * reference ({@link packageDependencyClosure}, {@link resolvePackageClosure}); + * - Studio's object pickers, which offer what the gate admits + * ({@link resolvePackageClosure} over the served package list); + * - the package-scoped resolution rule (`resolvePackageScopedHolders` in + * `@objectstack/core`, ADR-0150 D3 step 2), which resolves a bare name in + * P's closure plus the `sys` packages ({@link packageResolutionClosure}). + * + * ## Why it lives here (epic #31527, child R2) + * + * The walk started in `@objectstack/lint` and the App-pair widening in + * `@objectstack/metadata-protocol`. ADR-0076 D2 keeps metadata-protocol out + * of objectql's lean `./core` entry, where the resolution rule's first readers + * sit (the registry, the engine's action and function registries), so they + * could not read the closure. This package is already a dependency of lint, + * metadata-protocol and objectql, is in the lean entry's admitted set, holds + * the pair lookup the widening reads, and depends on nothing but + * `@objectstack/spec`, so hosting the walk here adds no package edge. Lint and + * metadata-protocol re-export what moved, under the same names. + */ + +import { customizationBasePackageId } from '@objectstack/spec/kernel'; +import { installedManifestsOf, pairOf } from './customization-pair-lookup.js'; + +/** + * The value `_packageId` carries for a row rehydrated from `sys_metadata` + * rather than delivered by a package — not a package id, so the walk reads it + * as "unpackaged" rather than as a package nobody declared a dependency on. + */ +const OVERLAY_PROVENANCE_SENTINEL = 'sys_metadata'; + +/** + * The package closure a write by `packageId` is judged against (#9612): the + * package and the transitive closure of the `dependencies` its manifest + * declares, read through `getPackage` — the host's package registry on the + * server (`resolveWritePackageScope` in `@objectstack/metadata-protocol`), the + * served package list in Studio, whose object pickers offer what this closure + * admits. ONE walk for both, so the picker and the publish gate cannot + * disagree about what a package may reference. + * + * Answers `undefined` — narrow nothing — for no package id, the + * `sys_metadata` sentinel (an overlay row, not a package), and a package + * `getPackage` cannot produce: its manifest is the only declaration of what it + * may reference, and narrowing without it would be narrowing on nothing. + * + * A declared dependency `getPackage` cannot produce is still IN the closure: + * the package declared it, so an object stamped with it is reachable by + * declaration. Only the transitive walk stops there. + * + * Pure. A `getPackage` that throws propagates; the caller decides what an + * unreadable registry means (the server answers `undefined`). + */ +export function resolvePackageClosure( + packageId: string | null | undefined, + getPackage: (id: string) => { manifest?: unknown } | undefined, +): { packageId: string; dependencies: string[] } | undefined { + if (typeof packageId !== 'string' || packageId === '' || packageId === OVERLAY_PROVENANCE_SENTINEL) return undefined; + if (!getPackage(packageId)) return undefined; + + const dependencies = new Set(); + const frontier = [packageId]; + while (frontier.length > 0) { + const current = frontier.pop() as string; + const manifest = getPackage(current)?.manifest as { dependencies?: Record } | undefined; + const declared = manifest?.dependencies; + if (!declared || typeof declared !== 'object') continue; + for (const dep of Object.keys(declared)) { + if (dep === packageId || dependencies.has(dep)) continue; + dependencies.add(dep); + frontier.push(dep); + } + } + return { packageId, dependencies: [...dependencies] }; +} + +/** The registry slice the closure reads: a package by id, and every installed package. */ +export interface PackageClosureRegistry { + getPackage?: (id: string) => { manifest?: unknown } | undefined; + getAllPackages?: () => ReadonlyArray<{ manifest?: unknown }>; +} + +/** + * [ADR-0146 D3, ruling record 6691022506] The write closure of an App's pair: + * `closure` — the pair and what it declares, the App — widened, when it + * declares its App, by every other installed package whose pair it is (`pairOf`) + * and their own declared closures. A customization of any package of the App + * lands in the App's pair, and the pair declares only the App (its range is + * the App's), so the members it overrides and extends are reached through the + * App's membership, not through a dependency the pair would have to restate + * for every module the App delivers. Any other package's closure is returned + * as it is. + */ +export function widenPairClosureToAppMembers( + closure: { packageId: string; dependencies: string[] }, + registry: PackageClosureRegistry | undefined, +): { packageId: string; dependencies: string[] } { + const pairId = closure.packageId; + const appId = customizationBasePackageId(pairId); + // Members are reached THROUGH the App: a pair that does not declare its + // App (an installed copy that dropped the dependency) is widened by + // nothing, and the App itself is only ever in the closure by declaration. + if (appId === null || !closure.dependencies.includes(appId)) return closure; + if (!registry || typeof registry.getPackage !== 'function' || typeof registry.getAllPackages !== 'function') return closure; + const installed = installedManifestsOf(registry as { getPackage(id: string): { manifest?: unknown } | undefined }); + const getPackage = (id: string) => registry.getPackage!.call(registry, id); + const dependencies = new Set(closure.dependencies); + for (const row of registry.getAllPackages.call(registry)) { + const id = (row?.manifest as { id?: unknown } | undefined)?.id; + if (typeof id !== 'string' || id === pairId || id === appId || dependencies.has(id)) continue; + const pair = pairOf(id, installed); + if (!pair.ok || pair.value !== pairId) continue; + dependencies.add(id); + for (const dep of resolvePackageClosure(id, getPackage)?.dependencies ?? []) { + if (dep !== pairId) dependencies.add(dep); + } + } + return { packageId: pairId, dependencies: [...dependencies] }; +} + +/** + * [#31575, ADR-0150 D3, ADR-0141] Package `packageId`'s DECLARED dependency + * closure, read from `registry`: the package itself and every package its + * manifest's `dependencies` name, transitively ({@link resolvePackageClosure}), + * with an App's pair widened by the App's members + * ({@link widenPairClosureToAppMembers}). The one implementation: the save + * door's write scope is this call inside a silent `catch`, and the + * package-scoped resolution rule's closure is this plus the `sys` packages + * ({@link packageResolutionClosure}). + * + * Answers `undefined` exactly where the walk does — no package id, the + * `sys_metadata` sentinel, a package `registry` cannot produce — and for a + * registry with no `getPackage` (a metadata-only test double). Each reader + * decides what `undefined` means for it: the save door narrows nothing, the + * resolver reaches nothing beyond the caller's own items and `sys`. + * + * ⛔ It does NOT add the `sys` kernel namespace ADR-0150 D3 puts in a + * resolution closure: the save door's scope stays as it was. + * + * A `getPackage` that throws propagates; the caller decides what an unreadable + * registry means. + */ +export function packageDependencyClosure( + packageId: string | null | undefined, + registry: PackageClosureRegistry | undefined, +): { packageId: string; dependencies: string[] } | undefined { + const getPackage = registry?.getPackage; + if (typeof getPackage !== 'function') return undefined; + const closure = resolvePackageClosure(packageId, (id) => getPackage.call(registry, id)); + return closure === undefined ? undefined : widenPairClosureToAppMembers(closure, registry); +} + +/** + * The reserved kernel namespace (ADR-0150 D2; ADR-0028 TL;DR 5): every package + * declaring it is in every caller's resolution closure (D3). + */ +export const KERNEL_NAMESPACE = 'sys'; + +/** Every installed package of the reserved kernel namespace. */ +function kernelPackages(registry: PackageClosureRegistry): string[] { + const ids: string[] = []; + if (typeof registry.getAllPackages !== 'function') return ids; + for (const row of registry.getAllPackages.call(registry)) { + const manifest = (row as { manifest?: { id?: unknown; namespace?: unknown } } | undefined)?.manifest; + if (manifest?.namespace === KERNEL_NAMESPACE && typeof manifest.id === 'string' && manifest.id !== '') ids.push(manifest.id); + } + return ids; +} + +/** + * The packages a caller of package `callerPackageId` may resolve a bare name + * in (ADR-0150 D3 step 2): its declared dependency closure — the save door's + * own ({@link packageDependencyClosure}) — plus every `sys` package, the + * caller itself excluded. A caller package the registry cannot produce + * declares nothing, so it reaches `sys` only. Every host of the resolution + * rule (`resolvePackageScopedHolders`) supplies its closure from this one call. + */ +export function packageResolutionClosure(registry: PackageClosureRegistry, callerPackageId: string): ReadonlySet { + const reach = new Set(packageDependencyClosure(callerPackageId, registry)?.dependencies ?? []); + for (const id of kernelPackages(registry)) reach.add(id); + reach.delete(callerPackageId); + return reach; +} diff --git a/packages/metadata-protocol/src/protocol-write-package-scope.test.ts b/packages/metadata-protocol/src/protocol-write-package-scope.test.ts new file mode 100644 index 00000000000..5f2b6eec701 --- /dev/null +++ b/packages/metadata-protocol/src/protocol-write-package-scope.test.ts @@ -0,0 +1,26 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The save door's declared dependency closure is the one walk (epic #31527, + * child R2): `packageDependencyClosure` and the App-pair widening live in + * `@objectstack/metadata-core` beside the resolution closure the + * package-scoped rule reads, and this package re-exports them. Pinned by + * identity, so no second closure can be computed here and still read green. + */ +import { describe, expect, it } from 'vitest'; +import * as metadataCore from '@objectstack/metadata-core'; +import * as lintRuntime from '@objectstack/lint/runtime'; +import { packageDependencyClosure, widenPairClosureToAppMembers } from './protocol-write-package-scope.js'; +import * as packageRoot from './index.js'; + +describe('the save door reads the one closure walk (epic #31527 child R2)', () => { + it('re-exports `@objectstack/metadata-core`\'s closure and widening, from this module and the package root', () => { + expect(packageDependencyClosure).toBe(metadataCore.packageDependencyClosure); + expect(widenPairClosureToAppMembers).toBe(metadataCore.widenPairClosureToAppMembers); + expect(packageRoot.packageDependencyClosure).toBe(metadataCore.packageDependencyClosure); + }); + + it('the walk under it is the one the runtime authoring gate re-exports', () => { + expect(lintRuntime.resolvePackageClosure).toBe(metadataCore.resolvePackageClosure); + }); +}); diff --git a/packages/metadata-protocol/src/protocol-write-package-scope.ts b/packages/metadata-protocol/src/protocol-write-package-scope.ts index 10b47ff84a6..d15eb303e8f 100644 --- a/packages/metadata-protocol/src/protocol-write-package-scope.ts +++ b/packages/metadata-protocol/src/protocol-write-package-scope.ts @@ -26,7 +26,7 @@ * gate's host (cut 8, `protocol-authoring-gate.ts`), whose closure calls it. * * The body reads no module-level declaration of `protocol.ts`; it imports the - * class type and the shared walk (`resolvePackageClosure`, below). + * class type and the shared walk ({@link packageDependencyClosure}). * * ## One declared dependency closure for every reader (#31575, ADR-0150 D3) * @@ -36,56 +36,18 @@ * resolver (`resolvePackageScopedName`) both ask it, so the closure a write is * judged against and the closure a bare name resolves in can never disagree. * It is the one export of this module the package root re-exports. + * + * [epic #31527 child R2] The walk, the App-pair widening and this closure live + * in `@objectstack/metadata-core` (`package-closure.ts`), so the resolution + * rule's readers inside objectql's lean entry, which this package stays out + * of (ADR-0076 D2), read the same one. Re-exported here under their names, so + * this package's surface is unchanged. */ -import { resolvePackageClosure } from '@objectstack/lint/runtime'; -import { installedManifestsOf, pairOf } from '@objectstack/metadata-core'; -import { customizationBasePackageId } from '@objectstack/spec/kernel'; +import { packageDependencyClosure, widenPairClosureToAppMembers, type PackageClosureRegistry } from '@objectstack/metadata-core'; import type { ObjectStackProtocolImplementation } from './protocol.js'; -/** The registry slice {@link widenPairClosureToAppMembers} reads. */ -interface MemberRegistry { - getPackage?: (id: string) => { manifest?: unknown } | undefined; - getAllPackages?: () => ReadonlyArray<{ manifest?: unknown }>; -} - -/** - * [ADR-0146 D3, ruling record 6691022506] The write closure of an App's pair: - * `closure` — the pair and what it declares, the App — widened, when it - * declares its App, by every other installed package whose pair it is (`pairOf`, `@objectstack/metadata-core`) - * and their own declared closures. A customization of any package of the App - * lands in the App's pair, and the pair declares only the App (its range is - * the App's), so the members it overrides and extends are reached through the - * App's membership, not through a dependency the pair would have to restate - * for every module the App delivers. Any other package's closure is returned - * as it is. - */ -export function widenPairClosureToAppMembers( - closure: { packageId: string; dependencies: string[] }, - registry: MemberRegistry | undefined, -): { packageId: string; dependencies: string[] } { - const pairId = closure.packageId; - const appId = customizationBasePackageId(pairId); - // Members are reached THROUGH the App: a pair that does not declare its - // App (an installed copy that dropped the dependency) is widened by - // nothing, and the App itself is only ever in the closure by declaration. - if (appId === null || !closure.dependencies.includes(appId)) return closure; - if (!registry || typeof registry.getPackage !== 'function' || typeof registry.getAllPackages !== 'function') return closure; - const installed = installedManifestsOf(registry as { getPackage(id: string): { manifest?: unknown } | undefined }); - const getPackage = (id: string) => registry.getPackage!.call(registry, id); - const dependencies = new Set(closure.dependencies); - for (const row of registry.getAllPackages.call(registry)) { - const id = (row?.manifest as { id?: unknown } | undefined)?.id; - if (typeof id !== 'string' || id === pairId || id === appId || dependencies.has(id)) continue; - const pair = pairOf(id, installed); - if (!pair.ok || pair.value !== pairId) continue; - dependencies.add(id); - for (const dep of resolvePackageClosure(id, getPackage)?.dependencies ?? []) { - if (dep !== pairId) dependencies.add(dep); - } - } - return { packageId: pairId, dependencies: [...dependencies] }; -} +export { packageDependencyClosure, widenPairClosureToAppMembers }; /** * The `ObjectStackProtocolImplementation` members the function below reads — @@ -101,8 +63,9 @@ export interface WritePackageScopeHost { /** * The body of `ObjectStackProtocolImplementation#resolveWritePackageScope`; the method's docblock there is its contract. * - * [#28240] The dependency walk itself is `resolvePackageClosure` in - * `@objectstack/lint`, the same function Studio's object pickers call over + * [#28240] The dependency walk itself is `resolvePackageClosure` (in + * `@objectstack/metadata-core` since epic #31527 child R2, re-exported by + * `@objectstack/lint`), the same function Studio's object pickers call over * the served package list, so the picker offers exactly what this gate * admits. This body keeps the two host guards: a registry with no * `getPackage`, and the silent `catch` answering `undefined`. An App's pair's @@ -113,7 +76,7 @@ export function resolveWritePackageScope( packageId: string | null | undefined, ): { packageId: string; dependencies: string[] } | undefined { try { - return packageDependencyClosure(packageId, this.engine.registry as MemberRegistry | undefined); + return packageDependencyClosure(packageId, this.engine.registry as PackageClosureRegistry | undefined); } catch { // Context gathering must never fail a write (the same contract // `listCollection` above holds). An unreadable registry means an @@ -121,37 +84,3 @@ export function resolveWritePackageScope( return undefined; } } - -/** - * [#31575, ADR-0150 D3, ADR-0141] Package `packageId`'s DECLARED dependency - * closure, read from `registry`: the package itself and every package its - * manifest's `dependencies` name, transitively (`resolvePackageClosure`, the - * walk Studio's object pickers share), with an App's pair widened by the App's - * members ({@link widenPairClosureToAppMembers}). The one implementation: the - * save door's write scope ({@link resolveWritePackageScope}) is this call - * inside a silent `catch`, and objectql's package-scoped name resolver asks it - * for the closure a bare name resolves in. - * - * Answers `undefined` exactly where the walk does — no package id, the - * `sys_metadata` sentinel, a package `registry` cannot produce — and for a - * registry with no `getPackage` (a metadata-only test double). Each reader - * decides what `undefined` means for it: the save door narrows nothing, the - * resolver reaches nothing beyond the caller's own items and `sys`. - * - * Not a widening of anything: it adds no package the walk and the pair - * widening did not already add. ⛔ It does NOT add the `sys` kernel namespace - * ADR-0150 D3 puts in a resolution closure: the save door's scope stays as it - * was, so the resolver adds `sys` itself. - * - * A `getPackage` that throws propagates; the caller decides what an unreadable - * registry means. - */ -export function packageDependencyClosure( - packageId: string | null | undefined, - registry: MemberRegistry | undefined, -): { packageId: string; dependencies: string[] } | undefined { - const getPackage = registry?.getPackage; - if (typeof getPackage !== 'function') return undefined; - const closure = resolvePackageClosure(packageId, (id) => getPackage.call(registry, id)); - return closure === undefined ? undefined : widenPairClosureToAppMembers(closure, registry); -} diff --git a/packages/objectql/src/bare-name-one-holder.ts b/packages/objectql/src/bare-name-one-holder.ts index a88c66768e9..7f67e7bca84 100644 --- a/packages/objectql/src/bare-name-one-holder.ts +++ b/packages/objectql/src/bare-name-one-holder.ts @@ -143,58 +143,38 @@ */ import type { ObjectStackManifest } from '@objectstack/spec/kernel'; -import { artifactPackageId } from '@objectstack/core'; +import { + artifactPackageId, + BARE_NAME_ONE_HOLDER_TYPES, + OVERRIDABLE_BASELINE_PACKAGES, + isBareNameOneHolderType, + isOverridableBaseline, + describeBareNameHolder, + type BareNameHolder, + type BareNameOneHolderType, + type BareNameRegistryType, +} from '@objectstack/core'; import { isObjectLessActionKey, standaloneActionOwnerKey } from './action-governance.js'; -/** - * A covered type the registry stores — its items reach the engine's package - * door and the registry's item seam, keyed as the registry keys them. - */ -export type BareNameRegistryType = - | 'picklist' | 'mapping' | 'dataset' - | 'api' | 'action' - | 'flow' | 'webhook' | 'connector' | 'email_template' - | 'agent' | 'skill'; - -/** - * A covered type: a registry type, or `function` — the engine's function - * registry, which a package reaches through the hook binder's bind alone. - */ -export type BareNameOneHolderType = BareNameRegistryType | 'function'; - -/** - * Every covered type, in the order a refusal and a cold boot list them: one - * family after another, each in the order its change named them. - */ -export const BARE_NAME_ONE_HOLDER_TYPES: readonly BareNameOneHolderType[] = Object.freeze([ - // the data family - 'picklist', - 'mapping', - 'dataset', - // the request family - 'api', - 'action', - 'function', - // the flow family - 'flow', - 'webhook', - 'connector', - 'email_template', - // the AI family - 'agent', - 'skill', -]); +// [epic #31527 child R2] The holder vocabulary — the covered types, the +// overridable baselines and the holder spelling — lives in `@objectstack/core` +// (`package-scoped-resolution.ts`) beside the package-scoped resolution rule +// that is written in it, so every reader of either reads one copy. Re-exported +// here under the same names; the rule it serves is this module's. +export type { BareNameRegistryType, BareNameOneHolderType, BareNameHolder } from '@objectstack/core'; +export { + BARE_NAME_ONE_HOLDER_TYPES, + OVERRIDABLE_BASELINE_PACKAGES, + isBareNameOneHolderType, + isOverridableBaseline, + describeBareNameHolder, +}; /** The covered registry types, in the order a refusal lists them. */ export const BARE_NAME_REGISTRY_TYPES: readonly BareNameRegistryType[] = Object.freeze( BARE_NAME_ONE_HOLDER_TYPES.filter((type): type is BareNameRegistryType => type !== 'function'), ); -/** Is `type` one of the covered types? */ -export function isBareNameOneHolderType(type: unknown): type is BareNameOneHolderType { - return typeof type === 'string' && (BARE_NAME_ONE_HOLDER_TYPES as readonly string[]).includes(type); -} - /** Is `type` a covered type the registry stores (as the registry keys it)? */ export function isBareNameRegistryType(type: unknown): type is BareNameRegistryType { return typeof type === 'string' && (BARE_NAME_REGISTRY_TYPES as readonly string[]).includes(type); @@ -250,43 +230,6 @@ export const BUILT_IN_BARE_NAMES: Readonly(), }); -/** - * Per covered type, the packages whose items are an OVERRIDABLE BASELINE - * (module doc, "The holders"): the platform's copies, which that type's one - * consumer serves any other package's same-named item over, by contract. Such - * a package neither holds a name of that type nor is refused one — at the - * package door, the item seam and the cold boot alike. - * - * `email_template`: the email service declares the built-in auth templates - * under its own package id (`EmailServicePlugin.init`, `@objectstack/plugin-email`), - * and its template loader picks any other package's `(name, locale)` member - * before the built-in's (`BUILTIN_EMAIL_TEMPLATES_PACKAGE_ID` there — the - * same spelling, held together by the flow family's booted dogfood pin: an - * app overriding a built-in template installs only while the two agree). - */ -export const OVERRIDABLE_BASELINE_PACKAGES: Readonly>> = Object.freeze({ - picklist: new Set(), - mapping: new Set(), - dataset: new Set(), - api: new Set(), - action: new Set(), - function: new Set(), - flow: new Set(), - webhook: new Set(), - connector: new Set(), - email_template: new Set(['com.objectstack.service.email']), - agent: new Set(), - skill: new Set(), -}); - -/** - * Is `packageId`'s item of `type` an overridable baseline - * ({@link OVERRIDABLE_BASELINE_PACKAGES}) — never a holder, never judged? - */ -export function isOverridableBaseline(type: BareNameOneHolderType, packageId: string | undefined): boolean { - return packageId !== undefined && OVERRIDABLE_BASELINE_PACKAGES[type].has(packageId); -} - /** * The prefix the runtime binds a package's handlers under * (`appArtifactHandlerOwner` in `@objectstack/runtime`: `app:`). @@ -319,11 +262,6 @@ export type BareNameColdBootMode = 'warn' | 'refuse'; */ export const BARE_NAME_COLD_BOOT_MODE: BareNameColdBootMode = 'warn'; -/** Who holds a covered name (module doc, "The holders"). */ -export type BareNameHolder = - | { readonly kind: 'package'; readonly packageId: string } - | { readonly kind: 'built-in' }; - /** One `(type, name)` a package declares. */ export interface DeclaredBareName { readonly type: BareNameRegistryType; @@ -441,13 +379,6 @@ export function bareNameReason(types: readonly BareNameOneHolderType[] = BARE_NA ); } -/** How a refusal names a holder. */ -export function describeBareNameHolder(holder: BareNameHolder): string { - return holder.kind === 'package' - ? `package "${holder.packageId}"` - : 'the platform, as a built-in name no package can declare'; -} - /** A stable identity for de-duplicating holders. */ export function bareNameHolderKey(holder: BareNameHolder): string { return holder.kind === 'package' ? `package:${holder.packageId}` : holder.kind; diff --git a/packages/objectql/src/engine-hooks-and-functions.ts b/packages/objectql/src/engine-hooks-and-functions.ts index 31d72f0127d..619ea509213 100644 --- a/packages/objectql/src/engine-hooks-and-functions.ts +++ b/packages/objectql/src/engine-hooks-and-functions.ts @@ -39,7 +39,7 @@ import { driverSupportsTransactions } from '@objectstack/spec/data'; import type { HookContext } from '@objectstack/spec/data'; import type { ExecutionContext } from '@objectstack/spec/kernel'; import { STORED_METADATA_TYPE_READ_GATE_OBJECTS, storedMetadataTypeReadGate } from './stored-metadata-type-read-gate.js'; -import { createLogger } from '@objectstack/core'; +import { createLogger, packageScopedHolderSource, type PackageScopedHolderSource } from '@objectstack/core'; import { hookStoppedRefusal } from './summary-errors.js'; import { startSummaryRefreshOnEnable } from './summary-enable-refresh.js'; import { HookTargetRebindError } from './hook-target-rebind-errors.js'; @@ -54,7 +54,6 @@ import { } from './engine-top-level.js'; import type { FunctionEntry, FunctionRegistrationOptions, HookEntry, HookHandler } from './engine-top-level.js'; import { handlerOwnerPackageId } from './bare-name-one-holder.js'; -import type { PackageScopedHolderSource } from './package-scoped-resolver.js'; import type { ObjectQL } from './engine.js'; /** @@ -302,16 +301,8 @@ export class HooksAndFunctionsFacet { /** The body of `ObjectQL#functionHoldersOf`; the method's docblock there is its contract. */ static functionHoldersOf(this: Pick, name: string): PackageScopedHolderSource> { - // A snapshot: a registration after this call is not in it. Built here, not - // by the resolver module's `packageScopedHolderSource`, because this - // module is in the lean `./core` entry and the resolver module is not - // (it reads `@objectstack/metadata-protocol`, ADR-0076 D2). - const holders = new Map(this.functionHolders.get(name) ?? []); - return Object.freeze({ - packageHolders: Object.freeze([...holders.keys()].filter((id): id is string => id !== null)), - packageItem: (packageId: string) => holders.get(packageId), - environmentItem: () => holders.get(null), - }); + // A snapshot: a registration after this call is not in it. + return packageScopedHolderSource>(this.functionHolders.get(name) ?? []); } /** The body of `ObjectQL#bindHooks`; the method's docblock there is its contract. */ diff --git a/packages/objectql/src/engine.ts b/packages/objectql/src/engine.ts index 89f303fa973..ef19540a57f 100644 --- a/packages/objectql/src/engine.ts +++ b/packages/objectql/src/engine.ts @@ -139,6 +139,7 @@ import { type EngineTransactionInfo, type EngineTransactionOptions, Logger, + type PackageScopedHolderSource, type RetryOptions, recordNotFoundError, resolveUserAuthzGrants, @@ -383,7 +384,6 @@ export { } from './engine-top-level.js'; // [#29986 codemod] Class head: units, hooks, functions, body runners, hook dispatch: the methods of the same names below hand the bodies what they read (`HooksAndFunctionsHost`). import { HooksAndFunctionsFacet } from './engine-hooks-and-functions.js'; -import type { PackageScopedHolderSource } from './package-scoped-resolver.js'; // [#29986 codemod] Action system and packaged-action activation: the methods of the same names below hand the bodies what they read (`ActionsHost`). import { ActionsFacet, type ActionHandlerEntry } from './engine-actions.js'; // [#29986 codemod] Registration seams, readable-ids security, formula and default permissions: the methods of the same names below hand the bodies what they read (`SecurityResolversHost`). @@ -653,7 +653,7 @@ export class ObjectQL implements IObjectQLEngine { // owner-less registration) → that package's entry. `functions` above keeps // one entry per name, the last-registered; this keeps every holder, so a // referrer's function can be resolved in its package - // (`resolvePackageScopedHolders` over `functionHoldersOf`). + // (`resolvePackageScopedFunction` over `functionHoldersOf`). private functionHolders = new Map>(); // Realtime service for event publishing @@ -836,7 +836,7 @@ export class ObjectQL implements IObjectQLEngine { * Every holder of the function `name` (ADR-0150 D4): each package that * registered one under that name, with its own entry, and an owner-less * registration as the environment's own item — the holder set - * `resolvePackageScopedHolders` resolves a flow's or an action's function + * `resolvePackageScopedFunction` resolves a flow's or an action's function * over, in the referrer's package. A snapshot, taken at the call. * `resolveFunction` and `resolveFunctionEntry` keep answering the one * last-registered entry per name. diff --git a/packages/objectql/src/index.ts b/packages/objectql/src/index.ts index 9780747433d..357ed3dd8d4 100644 --- a/packages/objectql/src/index.ts +++ b/packages/objectql/src/index.ts @@ -100,11 +100,15 @@ export { findPackageHeldSecurityCatalogNames } from './registry.js'; // metadata: the caller package's own item, else the unique holder in its // declared dependency closure (plus `sys`), else a refusal naming every // candidate. Exported for the readers epic #31527's later children switch to -// it (runtime indexes, doors, stored references); no reader calls it yet. On -// this barrel only: it reads `@objectstack/metadata-protocol`'s closure, which -// the lean `./core` entry never imports (ADR-0076 D2). +// it (runtime indexes, doors, stored references); no reader calls it yet. +// [#31716, child R2] The rule is `@objectstack/core`'s and the closure walk +// `@objectstack/metadata-core`'s, both inside the lean `./core` entry's +// admitted set (ADR-0076 D2); this module is objectql's two adapters over +// them (the registry's holders, the engine's function holders) and re-exports +// the rest under the names R published. export { resolvePackageScopedName, + resolvePackageScopedFunction, resolvePackageScopedHolders, packageScopedHolderSource, packageResolutionClosure, @@ -125,7 +129,10 @@ export type { PackageScopedHoldersQuery, PackageScopedHolderSource, PackageScopedResolvableType, - PackageResolutionClosureRegistry, + PackageClosureRegistry, + PackageResolutionClosureOf, + PackageScopedFunctionQuery, + PackageScopedFunctionEngine, PackageScopedRegistry, PackageScopedResolution, PackageScopedResolutionStep, diff --git a/packages/objectql/src/package-scoped-resolver.test.ts b/packages/objectql/src/package-scoped-resolver.test.ts index c2a39fbf697..91c8ffced16 100644 --- a/packages/objectql/src/package-scoped-resolver.test.ts +++ b/packages/objectql/src/package-scoped-resolver.test.ts @@ -20,12 +20,15 @@ * covered type exactly as `getItem` does, so wiring a reader to it later * changes no answer a release gives today. * - * Child R2 (#31716) adds the entry over a caller-supplied holder set - * (`resolvePackageScopedHolders`) and the engine's function holders - * (`ObjectQL#functionHoldersOf`): the `R2` blocks at the end. Their parity - * block holds the new entry, over the registry's holders, to exactly - * `resolvePackageScopedName`'s answer; their red-line pins were ablated the - * same way, readings in the PR body. + * Child R2 (#31716) moved the rule into `@objectstack/core` + * (`resolvePackageScopedHolders`, over a holder set and a closure the caller + * supplies) and the closure walk into `@objectstack/metadata-core`, so this + * module is two adapters: the registry's (`resolvePackageScopedName`, every + * case above unchanged) and the engine functions' (`resolvePackageScopedFunction` + * over `ObjectQL#functionHoldersOf`): the `R2` blocks at the end. Their parity + * block holds the core, over the registry's holders and the one walk, to + * exactly the adapter's answer; their red-line pins were ablated the same + * way, readings in the PR body. */ import { describe, it, expect, beforeEach } from 'vitest'; @@ -33,6 +36,7 @@ import { SchemaRegistry } from './registry.js'; import { BARE_NAME_REGISTRY_TYPES, type BareNameRegistryType } from './bare-name-one-holder.js'; import { resolvePackageScopedName, + resolvePackageScopedFunction, resolvePackageScopedHolders, packageScopedHolderSource, packageResolutionClosure, @@ -45,6 +49,8 @@ import { type PackageScopedType, } from './package-scoped-resolver.js'; import { ObjectQL } from './engine.js'; +import * as metadataCore from '@objectstack/metadata-core'; +import * as core from '@objectstack/core'; import { packageDependencyClosure } from '@objectstack/metadata-protocol'; const A = 'com.acme.alpha'; @@ -459,7 +465,7 @@ const registryPairs = (type: PackageScopedType, name: string): Array<[string | n return pairs; }; -describe('R2 parity — the holder-set entry over the registry\'s holders answers as `resolvePackageScopedName`', () => { +describe('R2 parity — the core rule over the registry\'s holders and the one walk answers as `resolvePackageScopedName`', () => { const CALLERS = [undefined, null, '', 'sys_metadata', A, B, C, MID, P, SYS, 'com.acme.not_installed']; it('every caller, every arm: own, closure, unique holder, environment, baseline, platform-requested, ambiguous, outside, not-found', () => { @@ -494,7 +500,11 @@ describe('R2 parity — the holder-set entry over the registry\'s holders answer for (const [type, name] of names) { for (const callerPackageId of CALLERS) { const expected = resolvePackageScopedName(registry, { type, name, callerPackageId }); - const actual = resolvePackageScopedHolders(registry, { type, name, callerPackageId }, packageScopedHolderSource(registryPairs(type, name))); + const actual = resolvePackageScopedHolders( + { type, name, callerPackageId }, + packageScopedHolderSource(registryPairs(type, name)), + (caller) => metadataCore.packageResolutionClosure(registry, caller), + ); expect(actual, `${type} ${name} for ${String(callerPackageId)}`).toEqual(expected); seen.add(expected.status === 'resolved' ? expected.via : expected.status === 'refused' ? expected.reason : 'not-found'); } @@ -506,7 +516,7 @@ describe('R2 parity — the holder-set entry over the registry\'s holders answer ]); }); - it('a bundled type: the holder-set entry answers the member the source serves', () => { + it('a bundled type: the core answers the member the source serves', () => { install(A); install(P, [A]); ship('email_template', 'welcome', A); @@ -517,7 +527,7 @@ describe('R2 parity — the holder-set entry over the registry\'s holders answer packageItem: (id) => registry.getPackageScopedItem('email_template', 'welcome', id, member), environmentItem: () => registry.getEnvironmentScopedItem('email_template', 'welcome', member), }; - expect(resolvePackageScopedHolders(registry, { type: 'email_template', name: 'welcome', callerPackageId: P }, source)) + expect(resolvePackageScopedHolders({ type: 'email_template', name: 'welcome', callerPackageId: P }, source, (caller) => packageResolutionClosure(registry, caller))) .toEqual(resolvePackageScopedName(registry, { type: 'email_template', name: 'welcome', callerPackageId: P, member })); } }); @@ -542,7 +552,7 @@ describe('R2 — the holder source and the types the entry resolves', () => { install(A); install(P, [A]); const source = packageScopedHolderSource([[A, 'alpha fn']]); - expect(resolvePackageScopedHolders(registry, { type: ENGINE_FUNCTION_TYPE, name: 'score', callerPackageId: P }, source)) + expect(resolvePackageScopedHolders({ type: ENGINE_FUNCTION_TYPE, name: 'score', callerPackageId: P }, source, (caller) => packageResolutionClosure(registry, caller))) .toMatchObject({ status: 'resolved', item: 'alpha fn', via: 'closure', holder: { kind: 'package', packageId: A } }); expect(() => resolve('function' as PackageScopedType, 'score', P)).toThrow(TypeError); }); @@ -550,7 +560,7 @@ describe('R2 — the holder source and the types the entry resolves', () => { it('positions and objects are not resolved over a supplied source either', () => { const source = packageScopedHolderSource([[A, 'x']]); for (const type of ['position', 'object']) { - expect(() => resolvePackageScopedHolders(registry, { type: type as PackageScopedResolvableType, name: 'n' }, source)).toThrow(TypeError); + expect(() => resolvePackageScopedHolders({ type: type as PackageScopedResolvableType, name: 'n' }, source, () => new Set())).toThrow(TypeError); } }); }); @@ -559,8 +569,7 @@ describe('R2 — engine functions resolve in their referrer\'s package (ADR-0150 let engine: ObjectQL; const fn = (tag: string) => Object.assign(() => tag, { tag }); const installOn = (id: string, deps: string[] = [], namespace?: string) => engine.registry.installPackage(manifest(id, deps, namespace), 'code'); - const resolveFn = (name: string, callerPackageId?: string | null) => - resolvePackageScopedHolders(engine.registry, { type: ENGINE_FUNCTION_TYPE, name, callerPackageId }, engine.functionHoldersOf(name)); + const resolveFn = (name: string, callerPackageId?: string | null) => resolvePackageScopedFunction(engine, { name, callerPackageId }); const tagOf = (r: PackageScopedResolution) => r.status === 'resolved' ? ((r.item as { handler: { tag?: string } }).handler.tag) : undefined; @@ -672,3 +681,18 @@ describe('R2 — engine functions resolve in their referrer\'s package (ADR-0150 expect(holders.packageHolders).toEqual([A]); }); }); + +describe('R2 — one rule, one walk: objectql re-exports them, it computes neither', () => { + it('the rule and its vocabulary are `@objectstack/core`\'s own', () => { + expect(resolvePackageScopedHolders).toBe(core.resolvePackageScopedHolders); + expect(packageScopedHolderSource).toBe(core.packageScopedHolderSource); + expect(PACKAGE_SCOPED_TYPES).toBe(core.PACKAGE_SCOPED_TYPES); + expect(PLATFORM_REQUESTED_BARE_NAMES_BY_TYPE).toBe(core.PLATFORM_REQUESTED_BARE_NAMES_BY_TYPE); + expect(BARE_NAME_REGISTRY_TYPES.every((type) => core.BARE_NAME_ONE_HOLDER_TYPES.includes(type))).toBe(true); + }); + + it('the closure is `@objectstack/metadata-core`\'s one walk', () => { + expect(packageResolutionClosure).toBe(metadataCore.packageResolutionClosure); + expect(packageDependencyClosure).toBe(metadataCore.packageDependencyClosure); + }); +}); diff --git a/packages/objectql/src/package-scoped-resolver.ts b/packages/objectql/src/package-scoped-resolver.ts index d95d8cfdad9..6e7303823c5 100644 --- a/packages/objectql/src/package-scoped-resolver.ts +++ b/packages/objectql/src/package-scoped-resolver.ts @@ -1,39 +1,39 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. /** - * # One answer to "which package's item does this bare name mean" (ADR-0150 D3) + * # One answer to "which package's item does this bare name mean" (ADR-0150 D3) — objectql's adapters * * Behavioural and presentation metadata (ADR-0150 D1 buckets 2 and 3: flows, * actions, permission sets, pages, skills, …) is identified by * `(package, name)`. Every reader that later carries the package — the runtime * indexes (epic #31527 children E), the by-name doors (G), the stored - * references (S) — resolves a bare name through THIS function, so no two - * readers can drift into two rules. That drift is what phase 1 (#30803) - * measured: first-registered wins in some readers, refusal in others. - * - * ⛔ Additive (child R, #31575): no reader calls it yet, phase 1's one-holder - * refusal (`bare-name-one-holder.ts`) stays in force, and while it does no two - * package holders of a covered name exist, so wiring a reader to this changes - * no answer it gives today. - * - * ## The rule (ADR-0150 D3, as ruled) - * - * A caller that belongs to package P resolves a bare name to: - * - * 1. **P's own item** — its ADR-0005 overlay when one binds to it, else its - * composite slot (`SchemaRegistry.getPackageScopedItem`, the per-package - * overlay slot of D4); - * 2. else **the unique holder in P's declared dependency closure** — P's - * `manifest.dependencies`, transitively (ADR-0141; the save door's own - * closure, `packageDependencyClosure` in `@objectstack/metadata-protocol`), - * plus every package of the reserved kernel namespace `sys` (D2), which - * this resolver adds itself: the save door's closure does not; - * 3. else a **refusal that names every candidate**. - * - * A caller with no package (an environment item, a context-free door, an MCP - * client) resolves against the whole environment: the environment's own item - * first (ADR-0005 overlay precedence), else the unique package holder, else the - * refusal naming every candidate (the doors map it to `409`, D5). + * references (S) — resolves a bare name through ONE rule, so no two readers + * can drift into two rules. That drift is what phase 1 (#30803) measured: + * first-registered wins in some readers, refusal in others. + * + * ## Where the rule is, and what this module adds (child R2, #31716) + * + * The rule itself — D3's three steps over a holder set and a closure the + * caller supplies, its refusal and the vocabulary that refusal is written in — + * is `resolvePackageScopedHolders` in `@objectstack/core` + * (`package-scoped-resolution.ts`; its module doc states the rule, the two red + * lines and the exceptions). The closure is `packageResolutionClosure` in + * `@objectstack/metadata-core`: the caller's declared dependency closure, the + * save door's own walk, plus every `sys` package. Both sit where every reader + * reaches them, objectql's lean `./core` entry included (ADR-0076 D2), and + * this module re-exports both under the names child R published. + * + * This module is the two objectql adapters over that rule, each the rule's + * call with the holders of one store and the closure from that one walk: + * + * - {@link resolvePackageScopedName} — the registry's holders: a package's + * item in its composite slot with its ADR-0005 overlay when one binds to + * it (`SchemaRegistry.getPackageScopedItem`, the per-package overlay slot of + * D4), and the environment's own item (`getEnvironmentScopedItem`); + * - {@link resolvePackageScopedFunction} — the engine's function registry: a + * function is not a metadata type, so it resolves in the package of the + * flow or action that names it (D4's last row), over the per-package + * function holders the engine keeps (`ObjectQL#functionHoldersOf`). * * **A package-less row that bears a package-held name is a customization, * never a second item** (ADR-0150 D3): it is the overlay of the one holder, @@ -41,48 +41,6 @@ * (`SchemaRegistry.getEnvironmentScopedItem`). So it never makes a name * ambiguous, and it is never served beside the item it customizes. * - * **Zero holders is not-found, never a refusal.** A refusal says "this name - * means more than one thing here, or nothing you may reach"; not-found says the - * name means nothing at all. - * - * ## The two red lines (epic #31527) - * - * - **It never loosens.** There is no first-registered fallback, no - * environment-wide guess for a caller with a package (a holder outside P's - * closure is refused, never served), and no silent pick between two - * candidates of one step. - * - **Ambiguity is reported, never guessed.** Every refusal carries every - * candidate of the step that refused, in the holder vocabulary - * `bare-name-one-holder.ts` defines ({@link BareNameHolder}, - * {@link describeBareNameHolder}), plus one holder kind this rule needs: the - * environment's own item. - * - * ## The exceptions (ADR-0150 D3, ruled) - * - * - **Names the platform requests by spelling** - * ({@link PLATFORM_REQUESTED_BARE_NAMES_BY_TYPE}; today the permission set - * `guest_portal`): the platform declares no dependency, so they resolve - * environment-wide whatever the caller, and keep ONE holder. - * - **Positions** are one environment-wide slot (D7, open question Q2). The - * type is not in {@link PACKAGE_SCOPED_TYPES}, and asking for it throws. - * - **An overridable baseline** (`OVERRIDABLE_BASELINE_PACKAGES`: the email - * service's built-in templates, ADR-0131 D6/D10) holds nothing while another - * reachable package holds the name — the vocabulary's own reading — and - * answers only when no other candidate of that step does. - * - * ## Holders from a store other than the registry (child R2, #31716) - * - * The rule reads three things about a name: which packages hold it, one - * holder's item, and the environment's own item - * ({@link PackageScopedHolderSource}). {@link resolvePackageScopedHolders} - * runs the steps over a source the caller supplies, and - * {@link resolvePackageScopedName} is that call over the registry's holders, - * so the rule is written once. The other source is the engine's function - * registry: a function is not a metadata type, so it resolves in the package - * of the flow or action that names it (ADR-0150 D4's last row), over the - * `(package, function)` pairs the engine keeps (`ObjectQL#functionHoldersOf`). - * Same closure, same refusal, same baseline rule. - * * ## What it deliberately does not do * * - ⛔ Wire any reader, retire or narrow any phase-1 refusal, or change any @@ -95,414 +53,76 @@ * and global (ADR-0129). */ -import { packageDependencyClosure } from '@objectstack/metadata-protocol'; import { - describeBareNameHolder, - isBareNameOneHolderType, - isOverridableBaseline, - type BareNameHolder, -} from './bare-name-one-holder.js'; + ENGINE_FUNCTION_TYPE, + PACKAGE_SCOPED_TYPES, + PLATFORM_REQUESTED_BARE_NAMES_BY_TYPE, + describePackageScopedHolder, + isPackageScopedResolvableType, + isPackageScopedType, + isPlatformRequestedBareName, + packageScopedHolderSource, + packageScopedRefusalMessage, + resolvePackageScopedHolders, + type PackageScopedHoldersQuery, + type PackageScopedResolution, + type PackageScopedType, +} from '@objectstack/core'; +import { KERNEL_NAMESPACE, packageResolutionClosure } from '@objectstack/metadata-core'; +import type { ObjectQL } from './engine.js'; +import type { FunctionEntry } from './engine-top-level.js'; import type { SchemaRegistry } from './registry.js'; -/** - * The metadata types addressed by `(package, name)` — ADR-0150 D1 buckets 2 - * and 3, as the registry spells them. `rag_pipeline` (bucket 3 in D1) has no - * registry type since ADR-0049 retired the collection, so it is not listed; - * `position` is environment-scoped (D7) and is not listed either. - */ -export const PACKAGE_SCOPED_TYPES = Object.freeze([ - // bucket 2 - 'flow', - 'action', - 'hook', - 'job', - 'webhook', - 'mapping', - 'connector', - 'permission', - 'sharing_rule', - 'queue', - 'assignment_rule', - 'app', - 'page', - 'dashboard', - 'report', - 'dataset', - 'analytics_cube', - 'picklist', - 'email_template', - 'book', - 'api', - // bucket 3 - 'tool', - 'skill', - 'agent', -] as const); - -/** A type addressed by `(package, name)` ({@link PACKAGE_SCOPED_TYPES}). */ -export type PackageScopedType = (typeof PACKAGE_SCOPED_TYPES)[number]; - -/** Is `type` addressed by `(package, name)`? */ -export function isPackageScopedType(type: unknown): type is PackageScopedType { - return typeof type === 'string' && (PACKAGE_SCOPED_TYPES as readonly string[]).includes(type); -} - -/** - * The engine's function registry, as the resolver names its holders: not a - * metadata type (so not in {@link PACKAGE_SCOPED_TYPES}), and resolved in its - * referrer's package (ADR-0150 D4). Phase 1 spells the same registry the - * same way (`BARE_NAME_ONE_HOLDER_TYPES`). - */ -export const ENGINE_FUNCTION_TYPE = 'function'; - -/** What the resolver resolves: a type addressed by `(package, name)`, or the engine's functions. */ -export type PackageScopedResolvableType = PackageScopedType | typeof ENGINE_FUNCTION_TYPE; - -/** Does the resolver resolve `type` ({@link PackageScopedResolvableType})? */ -export function isPackageScopedResolvableType(type: unknown): type is PackageScopedResolvableType { - return type === ENGINE_FUNCTION_TYPE || isPackageScopedType(type); -} - -/** - * Names the PLATFORM requests by spelling, per type (ADR-0150 D3 Exceptions): - * they resolve environment-wide whatever the caller's package, and keep one - * holder. The same list as `@objectstack/cli`'s `PLATFORM_REQUESTED_BARE_NAMES`, - * keyed by registry type instead of stack collection: the public form doors' - * submit context requests the permission set `guest_portal` by name - * (`packages/rest/src/form-routes.ts`). - */ -export const PLATFORM_REQUESTED_BARE_NAMES_BY_TYPE: Readonly>> = Object.freeze({ - permission: Object.freeze(['guest_portal']), -}); - -/** Is `(type, name)` one the platform requests by spelling? */ -export function isPlatformRequestedBareName(type: PackageScopedType, name: string): boolean { - return PLATFORM_REQUESTED_BARE_NAMES_BY_TYPE[type]?.includes(name) ?? false; -} - -/** - * The reserved kernel namespace (ADR-0150 D2; ADR-0028 TL;DR 5): every package - * declaring it is in every caller's resolution closure (D3). - */ -export const KERNEL_NAMESPACE = 'sys'; - -/** The value `_packageId` carries for a row rehydrated from `sys_metadata`: not a package. */ -const OVERLAY_PROVENANCE_SENTINEL = 'sys_metadata'; - -/** - * Who holds a name under package addressing: a package (the vocabulary's own - * {@link BareNameHolder}), or the environment's own item — an item authored in - * this environment, in the implicit environment package (ADR-0150 D1 bucket 4). - */ -export type PackageScopedHolder = - | Extract - | { readonly kind: 'environment' }; - -/** How a refusal names a holder. */ -export function describePackageScopedHolder(holder: PackageScopedHolder): string { - return holder.kind === 'environment' - ? 'the environment (an item authored in this environment, bound to no package)' - : describeBareNameHolder(holder); -} - -/** How the resolved item was reached (ADR-0150 D3's steps). */ -export type PackageScopedResolutionStep = - /** the caller package's own item */ - | 'own' - /** the unique holder in the caller's declared dependency closure (plus `sys`) */ - | 'closure' - /** the environment's own item (a caller with no package) */ - | 'environment' - /** the unique package holder in the environment (a caller with no package) */ - | 'unique-holder' - /** an overridable baseline, reached because no other candidate of the step holds the name */ - | 'baseline'; - -/** Why a resolution refused. */ -export type PackageScopedRefusalReason = - /** two or more holders in the caller package's declared closure (plus `sys`) */ - | 'ambiguous-in-closure' - /** two or more package holders in the environment, and the caller names no package */ - | 'ambiguous-in-environment' - /** holders exist, and none is in the caller package's declared closure (plus `sys`) */ - | 'outside-closure'; - -/** A resolution's answer. */ -export type PackageScopedResolution = - | { - readonly status: 'resolved'; - readonly item: T; - readonly holder: PackageScopedHolder; - readonly via: PackageScopedResolutionStep; - } - | { readonly status: 'not-found' } - | PackageScopedRefusal; - -/** A refusal: every candidate named, and nothing picked. */ -export interface PackageScopedRefusal { - readonly status: 'refused'; - readonly reason: PackageScopedRefusalReason; - readonly type: PackageScopedResolvableType; - readonly name: string; - /** The caller's package, or `null` for a caller with no package. */ - readonly callerPackageId: string | null; - /** Every candidate of the step that refused, in the item store's order. */ - readonly candidates: readonly PackageScopedHolder[]; - /** One sentence naming the item, every candidate and what to do. */ - readonly message: string; -} - -/** What the resolver is asked, over any holder source ({@link resolvePackageScopedHolders}). */ -export interface PackageScopedHoldersQuery { - readonly type: PackageScopedResolvableType; - readonly name: string; - /** - * The package the caller belongs to; omitted, `null`, `''` or the - * `sys_metadata` sentinel is a caller with no package. - */ - readonly callerPackageId?: string | null; -} - -/** What the resolver is asked, over the registry's holders ({@link resolvePackageScopedName}). */ +// Child R's published names — now the rule's (`@objectstack/core`) and the +// walk's (`@objectstack/metadata-core`) own — and R2's additions to them. +export { + ENGINE_FUNCTION_TYPE, + KERNEL_NAMESPACE, + PACKAGE_SCOPED_TYPES, + PLATFORM_REQUESTED_BARE_NAMES_BY_TYPE, + describePackageScopedHolder, + isPackageScopedResolvableType, + isPackageScopedType, + isPlatformRequestedBareName, + packageResolutionClosure, + packageScopedHolderSource, + packageScopedRefusalMessage, + resolvePackageScopedHolders, +}; +export type { + PackageResolutionClosureOf, + PackageScopedHolder, + PackageScopedHolderSource, + PackageScopedHoldersQuery, + PackageScopedRefusal, + PackageScopedRefusalReason, + PackageScopedResolution, + PackageScopedResolutionStep, + PackageScopedResolvableType, + PackageScopedType, +} from '@objectstack/core'; +export type { PackageClosureRegistry } from '@objectstack/metadata-core'; + +/** What {@link resolvePackageScopedName} is asked. */ export interface PackageScopedQuery extends PackageScopedHoldersQuery { readonly type: PackageScopedType; /** For a bundled type (`email_template`): one member, as `getItem` takes it. */ readonly member?: string; } -/** - * Who holds a name, and their items: the three things ADR-0150 D3's steps - * read, from whichever store keeps them — the registry - * ({@link resolvePackageScopedName}), or a store the caller supplies (the - * engine's function registry). Read only when a step needs it. - */ -export interface PackageScopedHolderSource { - /** Every package holding the name, each once, in the store's order. */ - readonly packageHolders: readonly string[]; - /** - * A package holder's item: its own, with whatever binds to it. `undefined` - * when it lacks what was asked (a bundle member), which answers not-found. - */ - packageItem(packageId: string): T | undefined; - /** - * The environment's own item of the name — bound to no package — or - * `undefined`. In the registry that is a package-less row under a name no - * package holds (D4: over a held name, the row is the holder's overlay). - */ - environmentItem(): T | undefined; -} - -/** - * A holder source over `(package, item)` pairs, a `null` package being the - * environment's own item. The order of the pairs is the store's order, which - * is the order every refusal names its candidates in. - * - * @throws {TypeError} when two pairs name one holder: a holder set holds each - * holder once, and the resolver never picks between two items of one holder. - */ -export function packageScopedHolderSource( - holdings: Iterable, -): PackageScopedHolderSource { - const items = new Map(); - for (const [packageId, item] of holdings) { - if (items.has(packageId)) { - throw new TypeError( - `[package-scoped-resolver] the holder set names ${packageId === null ? 'the environment' : `package "${packageId}"`} twice; ` + - `a holder holds a name once (ADR-0150 D3).`, - ); - } - items.set(packageId, item); - } - const packageHolders = [...items.keys()].filter((id): id is string => id !== null); - return Object.freeze({ - packageHolders: Object.freeze(packageHolders), - packageItem: (packageId: string) => items.get(packageId), - environmentItem: () => items.get(null), - }); -} - -/** The registry slice the closure reads ({@link packageResolutionClosure}). */ -export type PackageResolutionClosureRegistry = Pick; - -/** The registry slice the resolver reads — every member of it, and no other. */ +/** The registry slice the registry adapter reads — every member of it, and no other. */ export type PackageScopedRegistry = Pick< SchemaRegistry, 'getPackage' | 'getAllPackages' | 'packageScopedHoldersOf' | 'getPackageScopedItem' | 'getEnvironmentScopedItem' >; -/** Is `packageId`'s item of `type` an overridable baseline (the vocabulary's predicate)? */ -function isBaseline(type: PackageScopedResolvableType, packageId: string): boolean { - return isBareNameOneHolderType(type) && isOverridableBaseline(type, packageId); -} - -/** Every installed package of the reserved kernel namespace. */ -function kernelPackages(registry: PackageResolutionClosureRegistry): string[] { - const ids: string[] = []; - for (const row of registry.getAllPackages()) { - const manifest = (row as { manifest?: { id?: unknown; namespace?: unknown } } | undefined)?.manifest; - if (manifest?.namespace === KERNEL_NAMESPACE && typeof manifest.id === 'string' && manifest.id !== '') ids.push(manifest.id); - } - return ids; -} - /** - * The packages a caller of package `callerPackageId` may resolve a bare name - * in (ADR-0150 D3 step 2): its declared dependency closure — the save door's - * own ({@link packageDependencyClosure}) — plus every `sys` package. A caller - * package the registry cannot produce declares nothing, so it reaches `sys` - * only. - */ -export function packageResolutionClosure(registry: PackageResolutionClosureRegistry, callerPackageId: string): ReadonlySet { - const reach = new Set(packageDependencyClosure(callerPackageId, registry)?.dependencies ?? []); - for (const id of kernelPackages(registry)) reach.add(id); - reach.delete(callerPackageId); - return reach; -} - -const packageHolder = (packageId: string): PackageScopedHolder => ({ kind: 'package', packageId }); - -function typeLabel(type: PackageScopedResolvableType): string { - switch (type) { - case 'api': return 'API'; - case 'email_template': return 'email template'; - case 'sharing_rule': return 'sharing rule'; - case 'assignment_rule': return 'assignment rule'; - case 'analytics_cube': return 'analytics cube'; - case 'permission': return 'permission set'; - default: return type; - } -} - -/** - * The sentence a refusal carries: the item, why it refused, every candidate - * (in the vocabulary's words) and the one thing a caller can do about it. - */ -export function packageScopedRefusalMessage(refusal: Omit): string { - const subject = `The ${typeLabel(refusal.type)} "${refusal.name}"`; - const named = refusal.candidates.map(describePackageScopedHolder).join('; '); - switch (refusal.reason) { - case 'ambiguous-in-closure': - return `${subject} is held by ${refusal.candidates.length} packages in the declared dependency closure of ` + - `package "${refusal.callerPackageId}": ${named}. Nothing picks one of them: address it by its package.`; - case 'ambiguous-in-environment': - return `${subject} is held by ${refusal.candidates.length} packages in this environment and the caller names ` + - `no package: ${named}. Nothing picks one of them: address it by its package.`; - case 'outside-closure': - return `${subject} is held outside the declared dependency closure of package "${refusal.callerPackageId}": ` + - `${named}. Declare a dependency on the package that holds it (ADR-0141).`; - } -} - -function refuse( - query: PackageScopedHoldersQuery, - callerPackageId: string | null, - reason: PackageScopedRefusalReason, - candidates: readonly PackageScopedHolder[], -): PackageScopedRefusal { - const base = { status: 'refused' as const, reason, type: query.type, name: query.name, callerPackageId, candidates }; - return { ...base, message: packageScopedRefusalMessage(base) }; -} - -/** - * The one step of ADR-0150 D3 that picks among package holders: exactly one - * candidate other than an overridable baseline answers; two or more refuse, - * naming every one; none falls to the baselines by the same rule; `none` when - * no candidate holds the name at all. - */ -function pickUnique( - type: PackageScopedResolvableType, - candidates: readonly string[], -): { kind: 'one'; packageId: string; baseline: boolean } | { kind: 'several'; packageIds: string[] } | { kind: 'none' } { - const primary = candidates.filter((id) => !isBaseline(type, id)); - if (primary.length === 1) return { kind: 'one', packageId: primary[0], baseline: false }; - if (primary.length > 1) return { kind: 'several', packageIds: primary }; - const baselines = candidates.filter((id) => isBaseline(type, id)); - if (baselines.length === 1) return { kind: 'one', packageId: baselines[0], baseline: true }; - if (baselines.length > 1) return { kind: 'several', packageIds: baselines }; - return { kind: 'none' }; -} - -/** A package's item, as a resolution — or not-found when it lacks what was asked. */ -function packageItem( - source: PackageScopedHolderSource, - packageId: string, - via: PackageScopedResolutionStep, -): PackageScopedResolution { - const item = source.packageItem(packageId); - return item === undefined ? { status: 'not-found' } : { status: 'resolved', item, holder: packageHolder(packageId), via }; -} - -/** A caller with no package, or a platform-requested name: the whole environment (ADR-0150 D3). */ -function resolveEnvironmentWide( - query: PackageScopedHoldersQuery, - callerPackageId: string | null, - source: PackageScopedHolderSource, -): PackageScopedResolution { - const environmentItem = source.environmentItem(); - if (environmentItem !== undefined) { - return { status: 'resolved', item: environmentItem, holder: { kind: 'environment' }, via: 'environment' }; - } - const pick = pickUnique(query.type, source.packageHolders); - if (pick.kind === 'one') return packageItem(source, pick.packageId, pick.baseline ? 'baseline' : 'unique-holder'); - if (pick.kind === 'several') return refuse(query, callerPackageId, 'ambiguous-in-environment', pick.packageIds.map(packageHolder)); - return { status: 'not-found' }; -} - -/** - * Resolve a bare name by ADR-0150 D3 (module doc) over a holder set the - * caller supplies — the engine's function registry, or any store that keeps - * `(package, item)` pairs outside the registry. The closure is the registry's - * ({@link packageResolutionClosure}); the holders and their items are the - * source's. Writes nothing, and never throws for a name — only for a type the - * resolver does not resolve ({@link PackageScopedResolvableType}), which is a - * caller's programming error. - * - * @returns `resolved` with the item, its holder and the step that reached it; - * `not-found` when nothing holds the name; `refused` naming every candidate - * of the step that could not pick one. - */ -export function resolvePackageScopedHolders( - registry: PackageResolutionClosureRegistry, - query: PackageScopedHoldersQuery, - source: PackageScopedHolderSource, -): PackageScopedResolution { - if (!isPackageScopedResolvableType(query.type)) { - throw new TypeError( - `[package-scoped-resolver] "${String(query.type)}" is not resolved by package (ADR-0150 D1, D4); ` + - `positions are environment-scoped (D7) and objects keep their literal name (ADR-0129).`, - ); - } - const raw = query.callerPackageId; - const callerPackageId = typeof raw === 'string' && raw !== '' && raw !== OVERLAY_PROVENANCE_SENTINEL ? raw : null; - const holders = source.packageHolders; - - if (callerPackageId === null || (query.type !== ENGINE_FUNCTION_TYPE && isPlatformRequestedBareName(query.type, query.name))) { - return resolveEnvironmentWide(query, callerPackageId, source); - } - - // Step 1 — the caller package's own item. - if (holders.includes(callerPackageId)) return packageItem(source, callerPackageId, 'own'); - - // Step 2 — the unique holder in its declared closure, plus `sys`. - const reach = packageResolutionClosure(registry, callerPackageId); - const pick = pickUnique(query.type, holders.filter((id) => reach.has(id))); - if (pick.kind === 'one') return packageItem(source, pick.packageId, pick.baseline ? 'baseline' : 'closure'); - if (pick.kind === 'several') return refuse(query, callerPackageId, 'ambiguous-in-closure', pick.packageIds.map(packageHolder)); - - // Step 3 — nothing reachable: a refusal naming every holder there is, or - // not-found when there is none. ⛔ Never an environment-wide guess. - const candidates: PackageScopedHolder[] = holders.map(packageHolder); - if (source.environmentItem() !== undefined) candidates.push({ kind: 'environment' }); - if (candidates.length === 0) return { status: 'not-found' }; - return refuse(query, callerPackageId, 'outside-closure', candidates); -} - -/** - * Resolve a bare name by ADR-0150 D3 (module doc) over the registry's - * holders: {@link resolvePackageScopedHolders} with the registry as the - * source. Reads the registry, writes nothing, and never throws for a name — - * only for a type that is not addressed by package - * ({@link PACKAGE_SCOPED_TYPES}), which is a caller's programming error. + * Resolve a bare name by ADR-0150 D3 over the registry's holders: the rule + * (`resolvePackageScopedHolders`) with the registry as the holder source and + * the caller's closure from the one walk ({@link packageResolutionClosure}). + * Reads the registry, writes nothing, and never throws for a name — only for + * a type that is not addressed by package ({@link PACKAGE_SCOPED_TYPES}), + * which is a caller's programming error. * * @returns `resolved` with the item, its holder and the step that reached it; * `not-found` when nothing holds the name; `refused` naming every candidate @@ -516,14 +136,55 @@ export function resolvePackageScopedName( throw new TypeError( `[package-scoped-resolver] "${String(query.type)}" is not addressed by (package, name) (ADR-0150 D1); ` + (query.type === ENGINE_FUNCTION_TYPE - ? 'the registry holds no function: resolve one over the engine\'s holders (resolvePackageScopedHolders, ADR-0150 D4).' + ? 'the registry holds no function: resolvePackageScopedFunction resolves one over the engine\'s holders (ADR-0150 D4).' : 'positions are environment-scoped (D7) and objects keep their literal name (ADR-0129).'), ); } const { type, name, member } = query; - return resolvePackageScopedHolders(registry, query, { - packageHolders: registry.packageScopedHoldersOf(type, name), - packageItem: (packageId) => registry.getPackageScopedItem(type, name, packageId, member), - environmentItem: () => registry.getEnvironmentScopedItem(type, name, member), - }); + return resolvePackageScopedHolders( + query, + { + packageHolders: registry.packageScopedHoldersOf(type, name), + packageItem: (packageId) => registry.getPackageScopedItem(type, name, packageId, member), + environmentItem: () => registry.getEnvironmentScopedItem(type, name, member), + }, + (callerPackageId) => packageResolutionClosure(registry, callerPackageId), + ); +} + +/** What {@link resolvePackageScopedFunction} is asked: a function's name, and the package of the flow or action naming it. */ +export interface PackageScopedFunctionQuery { + readonly name: string; + /** + * The package of the flow or action that names the function; omitted, + * `null`, `''` or the `sys_metadata` sentinel is a caller with no package. + */ + readonly callerPackageId?: string | null; +} + +/** The engine slice the function adapter reads — every member of it, and no other. */ +export type PackageScopedFunctionEngine = Pick; + +/** + * Resolve the function a flow or an action names, in the package of that + * referrer (ADR-0150 D4's last row): the rule (`resolvePackageScopedHolders`) + * with the engine's per-package function holders (`ObjectQL#functionHoldersOf`) + * and the caller's closure from the one walk ({@link packageResolutionClosure} + * over the engine's registry). An owner-less registration is the + * environment's own item. Writes nothing, never throws for a name. + * + * ⛔ No caller reads it yet: `resolveFunction` / `resolveFunctionEntry` keep + * answering the one last-registered function per name until a later child + * wires the flow `script` node and the action `target` to this. + */ +export function resolvePackageScopedFunction( + engine: PackageScopedFunctionEngine, + query: PackageScopedFunctionQuery, +): PackageScopedResolution> { + const registry = engine.registry; + return resolvePackageScopedHolders( + { type: ENGINE_FUNCTION_TYPE, name: query.name, callerPackageId: query.callerPackageId }, + engine.functionHoldersOf(query.name), + (callerPackageId) => packageResolutionClosure(registry, callerPackageId), + ); } From cfd7688b8d12a1b3c363689a432827f72845f95b Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 8 Nov 2026 23:44:51 +0000 Subject: [PATCH 04/11] test(objectql): retire the federated-reader row for the moved type list, and type the function-holder fixtures Claude-Session: https://claude.ai/code/session_01ADHkmQ5eMDSpkq6rYGLbBU Co-authored-by: Claude --- .../objectql/src/federated-injected-column-readers.test.ts | 4 ---- packages/objectql/src/package-scoped-resolver.test.ts | 2 +- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/packages/objectql/src/federated-injected-column-readers.test.ts b/packages/objectql/src/federated-injected-column-readers.test.ts index 59677016e0a..684e8a11dfa 100644 --- a/packages/objectql/src/federated-injected-column-readers.test.ts +++ b/packages/objectql/src/federated-injected-column-readers.test.ts @@ -440,10 +440,6 @@ const READERS: Record = { }, 'assignment-rules.ts# :: owner_id': { disposition: 'not-a-read', why: VOCABULARY }, 'assignment-rules.ts# :: queue': { disposition: 'not-a-read', why: VOCABULARY }, - 'package-scoped-resolver.ts# :: queue': { - disposition: 'not-a-read', - why: 'the metadata TYPE `queue` (ADR-0150 D1 bucket 2) in the list of types addressed by package, not the column; it reads no row', - }, 'assignment-rules.ts#carriesQueueColumn :: resolveInjectedColumnProvenance()': { disposition: 'excludes', why: 'an object whose queue column is unprovisioned (federated) evaluates no assignment rule', diff --git a/packages/objectql/src/package-scoped-resolver.test.ts b/packages/objectql/src/package-scoped-resolver.test.ts index 91c8ffced16..e44cde1e78d 100644 --- a/packages/objectql/src/package-scoped-resolver.test.ts +++ b/packages/objectql/src/package-scoped-resolver.test.ts @@ -567,7 +567,7 @@ describe('R2 — the holder source and the types the entry resolves', () => { describe('R2 — engine functions resolve in their referrer\'s package (ADR-0150 D4)', () => { let engine: ObjectQL; - const fn = (tag: string) => Object.assign(() => tag, { tag }); + const fn = (tag: string) => Object.assign((): void => undefined, { tag }); const installOn = (id: string, deps: string[] = [], namespace?: string) => engine.registry.installPackage(manifest(id, deps, namespace), 'code'); const resolveFn = (name: string, callerPackageId?: string | null) => resolvePackageScopedFunction(engine, { name, callerPackageId }); const tagOf = (r: PackageScopedResolution) => From 532f3be4068faac3edc54f43940626bf52e77ee4 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 8 Nov 2026 23:59:19 +0000 Subject: [PATCH 05/11] fix(objectql): a bundle addition holds no name for a package-scoped bare read A dependent package's email template locale its base does not ship stays under the dependent (#28802), so the registry no longer counts it as a second holder of the base's name; a member read naming the dependent still reaches it. A dependent holding a member its base holds, or a package outside the holder's declaring closure, is still a holder. Claude-Session: https://claude.ai/code/session_01ADHkmQ5eMDSpkq6rYGLbBU Co-authored-by: Claude --- .../src/protocol-write-package-scope.test.ts | 3 ++ .../src/package-scoped-resolver.test.ts | 52 +++++++++++++++++++ packages/objectql/src/registry.ts | 50 +++++++++++++++++- ...dent-unshipped-locale-read.dogfood.test.ts | 30 ++++++++++- 4 files changed, 133 insertions(+), 2 deletions(-) diff --git a/packages/metadata-protocol/src/protocol-write-package-scope.test.ts b/packages/metadata-protocol/src/protocol-write-package-scope.test.ts index 5f2b6eec701..8e00da848c1 100644 --- a/packages/metadata-protocol/src/protocol-write-package-scope.test.ts +++ b/packages/metadata-protocol/src/protocol-write-package-scope.test.ts @@ -8,6 +8,9 @@ * identity, so no second closure can be computed here and still read green. */ import { describe, expect, it } from 'vitest'; +// The package root reaches `@objectstack/lint` by a dynamic import; pay its load +// at collection, never inside a case's clocked window (`check:test-source-alias`). +import '@objectstack/lint'; import * as metadataCore from '@objectstack/metadata-core'; import * as lintRuntime from '@objectstack/lint/runtime'; import { packageDependencyClosure, widenPairClosureToAppMembers } from './protocol-write-package-scope.js'; diff --git a/packages/objectql/src/package-scoped-resolver.test.ts b/packages/objectql/src/package-scoped-resolver.test.ts index e44cde1e78d..f65ceee98b3 100644 --- a/packages/objectql/src/package-scoped-resolver.test.ts +++ b/packages/objectql/src/package-scoped-resolver.test.ts @@ -696,3 +696,55 @@ describe('R2 — one rule, one walk: objectql re-exports them, it computes neith expect(packageDependencyClosure).toBe(metadataCore.packageDependencyClosure); }); }); + +describe('R2 — a bundle addition is no holder of its base\'s name for a bare read (#28802)', () => { + const D = 'com.acme.addon'; + const member = (packageId: string, locale: string, tag: string) => + registry.registerItem('email_template', { ...body('email_template', 'welcome', tag), locale }, 'name' as never, packageId); + /** A dependent's stored row, as the save door hydrates it: the bare slot, stamped with the dependent. */ + const storedMember = (packageId: string, locale: string, tag: string) => + registry.registerItem('email_template', { ...body('email_template', 'welcome', tag), locale, _packageId: packageId, _provenance: 'org' }, 'name' as never); + + beforeEach(() => { + install(A); + install(D, [A]); + install(P, [A]); + ship('email_template', 'welcome', A); + }); + + for (const [how, add] of [['in its composite slot', member], ['as a stored row', storedMember]] as const) { + it(`a dependent's locale its base does not ship (${how}) adds no holder: the base's name still resolves`, () => { + add(D, 'fr-FR', 'addon-fr'); + expect(registry.packageScopedHoldersOf('email_template', 'welcome')).toEqual([A]); + for (const caller of [undefined, P, D]) { + expect(label(resolve('email_template', 'welcome', caller))).toBe('alpha template'); + } + // The addition is still the dependent's member, read naming the dependent. + expect(registry.getPackageScopedItem<{ label: string }>('email_template', 'welcome', D, 'fr-FR')?.label).toBe('addon-fr template'); + // The base's address does not serve it. + expect(resolve('email_template', 'welcome', undefined, 'fr-FR')).toEqual({ status: 'not-found' }); + }); + } + + it('red line 1: a dependent holding a member its base holds is a holder, and the bare read refuses', () => { + member(D, 'en-US', 'addon-en'); + expect(registry.packageScopedHoldersOf('email_template', 'welcome')).toEqual([A, D]); + expect(resolve('email_template', 'welcome')).toMatchObject({ + status: 'refused', reason: 'ambiguous-in-environment', + candidates: [{ kind: 'package', packageId: A }, { kind: 'package', packageId: D }], + }); + }); + + it('red line 1: a package that does not declare the holder is a holder, whatever members it adds', () => { + install(B); + member(B, 'fr-FR', 'beta-fr'); + expect(registry.packageScopedHoldersOf('email_template', 'welcome')).toEqual([A, B]); + expect(resolve('email_template', 'welcome')).toMatchObject({ status: 'refused', reason: 'ambiguous-in-environment' }); + }); + + it('only a bundled type has additions: a dependent\'s same-named flow is a holder', () => { + ship('flow', 'send_email', A); + ship('flow', 'send_email', D); + expect(registry.packageScopedHoldersOf('flow', 'send_email')).toEqual([A, D]); + }); +}); diff --git a/packages/objectql/src/registry.ts b/packages/objectql/src/registry.ts index c13d3e12d03..636a70a8a9a 100644 --- a/packages/objectql/src/registry.ts +++ b/packages/objectql/src/registry.ts @@ -47,6 +47,9 @@ import { // installed?" asks it, over this registry's installed manifests. pairsOf, installedManifestsOf, + // [ADR-0150 D3, #28802] The one closure walk: a dependent's bundle addition + // under a dependency's name is no holder of that name for a bare read. + packageDependencyClosure, } from '@objectstack/metadata-core'; // [ADR-0029 D9.2a] `scalarOverridesPackagedBase` is the #8284 comparison, imported rather // than re-spelled: the object FOLD asks the same question one layer down (has @@ -8305,6 +8308,16 @@ export class SchemaRegistry { * Every package, overridable baselines included: the resolver ranks them * (`package-scoped-resolver.ts`). An object is not addressed by package * (ADR-0150 D1 bucket 1) and answers `[]`. + * + * [#28802, epic #31527 child R2] A bundle ADDITION holds no name: a + * package whose members of a bundled type's name are all members another + * holder in its declared dependency closure does not hold (a dependent's + * locale its base does not ship, which the write gate admits and which + * stays under the dependent) adds to that holder's bundle, so it is no + * second holder of the name for a bare read. The addition is still the + * dependent's member: {@link getPackageScopedItem} naming the dependent + * reads it. A package holding a member its dependency also holds is a + * holder (a clash, refused by the resolver, never folded away). */ packageScopedHoldersOf(type: string, name: string): string[] { const collection = this.metadata.get(type); @@ -8316,7 +8329,42 @@ export class SchemaRegistry { const bound = this.overlaySlotBinding(item, name, collection, compositeSet); if (typeof bound === 'string') holders.add(bound); } - return [...holders]; + const disc = ITEM_KEY_DISCRIMINATORS[type]; + if (!disc || holders.size < 2) return [...holders]; + const membersOf = new Map>(); + for (const id of holders) membersOf.set(id, this.bundleMembersHeldBy(type, collection, name, id, compositeSet, disc)); + return [...holders].filter((id) => !this.isBundleAddition(id, membersOf)); + } + + /** + * [#28802] The members (discriminator values) of `name`'s bundle that + * `packageId` holds: its composite group's, and the bare-slot entries that + * bind to it ({@link overlaySlotBinding}). + */ + private bundleMembersHeldBy(type: string, collection: Map, name: string, packageId: string, + holders: ReadonlySet, disc: { field: string; canonical: string }): Set { + const { local } = collectBundle(collection, name, disc, packageId); + const bound = this.bareSlotEntriesOf(type, collection, name) + .filter(({ item }) => this.overlaySlotBinding(item, name, collection, holders) === packageId); + return new Set([...local, ...bound].map((e) => discriminatorValue(e.item, disc.field) || disc.canonical)); + } + + /** + * [#28802] Whether `packageId`'s holding of a bundle's name is an addition + * to another holder's bundle: some other holder is in `packageId`'s declared + * dependency closure (the save door's walk), `packageId` is not in that + * holder's, and none of `packageId`'s members is one that holder holds. + */ + private isBundleAddition(packageId: string, membersOf: ReadonlyMap>): boolean { + const own = membersOf.get(packageId)!; + const reach = new Set(packageDependencyClosure(packageId, this)?.dependencies ?? []); + for (const [base, baseMembers] of membersOf) { + if (base === packageId || !reach.has(base)) continue; + if (packageDependencyClosure(base, this)?.dependencies.includes(packageId)) continue; + if ([...own].some((m) => baseMembers.has(m))) continue; + return true; + } + return false; } /** diff --git a/packages/qa/dogfood/test/email-template-dependent-unshipped-locale-read.dogfood.test.ts b/packages/qa/dogfood/test/email-template-dependent-unshipped-locale-read.dogfood.test.ts index fd389b2be8a..d1df50b667d 100644 --- a/packages/qa/dogfood/test/email-template-dependent-unshipped-locale-read.dogfood.test.ts +++ b/packages/qa/dogfood/test/email-template-dependent-unshipped-locale-read.dogfood.test.ts @@ -35,6 +35,7 @@ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { type VerifyStack } from '@objectstack/verify'; +import { resolvePackageScopedName } from '@objectstack/objectql'; import { bootShowcase } from './showcase-boot.js'; const BASE = 'com.example.showcase'; @@ -104,6 +105,23 @@ function showcaseRig() { const email: any = await rig.stack!.kernel.getServiceAsync('email'); return (await email.renderTemplate({ template: NAME, locale, data: { title: 'T' } }))?.subject; }; + /** + * [ADR-0150 D3, epic #31527 child R2] The package-scoped resolver over the + * served registry, for a caller with no package (a package-less send): the + * holder it answers and the subject, or the status. + */ + const resolved = async (member?: string) => { + const ql: any = await rig.stack!.kernel.getServiceAsync('objectql'); + const r = resolvePackageScopedName<{ subject?: unknown }>(ql.registry, { type: 'email_template', name: NAME, member }); + return r.status === 'resolved' + ? { status: r.status, holder: r.holder, subject: r.item?.subject } + : { status: r.status, ...(r.status === 'refused' ? { candidates: r.candidates } : {}) }; + }; + /** The dependent's own member, read naming the dependent. */ + const dependentMember = async (member: string) => { + const ql: any = await rig.stack!.kernel.getServiceAsync('objectql'); + return (ql.registry.getPackageScopedItem('email_template', NAME, DEPENDENT, member) as { subject?: unknown } | undefined)?.subject; + }; const body = (locale: string, subject: string, extra: Record = {}) => { const out: Record = {}; for (const [k, v] of Object.entries(rig.shipped)) if (!k.startsWith('_')) out[k] = v; @@ -141,7 +159,7 @@ function showcaseRig() { const doc = read.json?.data ?? read.json?.item ?? read.json; rig.shipped = doc?.item ?? doc; }; - return { rig, boot, byName, layers, listed, executing, rendered, body, saveInto, publishInto, createDependent, ensurePair }; + return { rig, boot, byName, layers, listed, executing, rendered, resolved, dependentMember, body, saveInto, publishInto, createDependent, ensurePair }; } const BASE_EN = { status: 200, subject: SHIPPED_SUBJECT, locale: 'en-US', _packageId: BASE }; @@ -187,6 +205,16 @@ describe('[#28802] a dependent\'s email template locale the base does not ship s expect(await r.byName('en-US')).toEqual(BASE_EN); }); + it('[ADR-0150 D3, R2] the dependent\'s `fr-FR` is an addition, no second holder: a package-less resolve of the name answers the base', async () => { + const BASE_HOLDER = { kind: 'package', packageId: BASE }; + expect(await r.resolved()).toEqual({ status: 'resolved', holder: BASE_HOLDER, subject: SHIPPED_SUBJECT }); + expect(await r.resolved('en-US')).toEqual({ status: 'resolved', holder: BASE_HOLDER, subject: SHIPPED_SUBJECT }); + // The base's address serves no `fr-FR`, as the by-name read answers 404. + expect(await r.resolved('fr-FR')).toEqual({ status: 'not-found' }); + // A member read naming the dependent still reaches the addition. + expect(await r.dependentMember('fr-FR')).toBe(DEPENDENT_SUBJECT); + }); + it('[#28830] the layered read naming the base or no package stays 404 for the dependent\'s `fr-FR`; naming the dependent it answers', async () => { expect(await r.layers('fr-FR', BASE)).toEqual({ status: 404 }); expect(await r.layers('fr-FR')).toEqual({ status: 404 }); From 77a49d7fdfab6db99ea851ae81907a46fcb6c287 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 00:04:30 +0000 Subject: [PATCH 06/11] chore: changeset names the bundle-addition holder change Claude-Session: https://claude.ai/code/session_01ADHkmQ5eMDSpkq6rYGLbBU Co-authored-by: Claude --- .changeset/31716-package-scoped-rule-lean.md | 1 + 1 file changed, 1 insertion(+) diff --git a/.changeset/31716-package-scoped-rule-lean.md b/.changeset/31716-package-scoped-rule-lean.md index 0a928127946..b842267cdf6 100644 --- a/.changeset/31716-package-scoped-rule-lean.md +++ b/.changeset/31716-package-scoped-rule-lean.md @@ -15,5 +15,6 @@ Metadata-protocol: none - **`@objectstack/metadata-core`** exports the one closure walk: `resolvePackageClosure` (moved from `@objectstack/lint`), `widenPairClosureToAppMembers` and `packageDependencyClosure` (moved from `@objectstack/metadata-protocol`), and `packageResolutionClosure` with `KERNEL_NAMESPACE` (moved from `@objectstack/objectql`): the declared dependency closure plus every `sys` package. - **`@objectstack/lint`**, **`@objectstack/metadata-protocol`** and **`@objectstack/objectql`** re-export every moved name under the name they published, so no import changes. objectql's `resolvePackageScopedName` keeps its signature and answers, now as the rule's call over the registry's holders. - **`@objectstack/objectql`** adds `resolvePackageScopedFunction`, the rule's call over the engine's function holders, and `ObjectQL#functionHoldersOf(name)`: every package that registered a function of that name (the owner `app:PACKAGE_ID` read as the package id), with its own entry, and an owner-less registration as the environment's own item. +- **`@objectstack/objectql`**: `SchemaRegistry#packageScopedHoldersOf` no longer counts a bundle addition as a holder (#28802). A dependent package's email template locale its base does not ship stays under the dependent, so it is no second holder of the base's name for a bare read, and a package-less resolve of the base's template answers the base. A read naming the dependent (`getPackageScopedItem`) still reaches the addition. A dependent holding a member its base also holds, and a package that does not declare the holder, are still holders, and the bare read refuses them. Nothing changes for a running deployment: no reader calls the rule yet, `resolveFunction` and `resolveFunctionEntry` keep answering the one last-registered function per name, the save door admits and refuses exactly what it did, and phase 1's one-holder refusal stays in force. From cc8a8ba5bd280722b1a1ce31b51156dc9791ad81 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 00:42:36 +0000 Subject: [PATCH 07/11] fix(core, objectql): keep a caller's own bundle addition at step 1, and an owner-less function is the platform's A dependent's bare read of its own added member answers its own item at step 1 again: the addition only stops counting toward other callers' ambiguity. An owner-less engine function is code a plugin or the host registers, so it is the platform's item, in every caller's reach like a sys package: a package caller holding none counts it beside its closure's holders, and two or more refuse naming each. Claude-Session: https://claude.ai/code/session_01ADHkmQ5eMDSpkq6rYGLbBU Co-authored-by: Claude --- .../src/package-scoped-resolution.test.ts | 31 ++++++++ .../core/src/package-scoped-resolution.ts | 53 +++++++++++--- .../src/engine-hooks-and-functions.ts | 14 +++- packages/objectql/src/engine.ts | 3 +- .../src/package-scoped-resolver.test.ts | 71 ++++++++++++++++--- .../objectql/src/package-scoped-resolver.ts | 10 ++- packages/objectql/src/registry.ts | 9 ++- 7 files changed, 161 insertions(+), 30 deletions(-) diff --git a/packages/core/src/package-scoped-resolution.test.ts b/packages/core/src/package-scoped-resolution.test.ts index 8cf7740946b..3ebad196362 100644 --- a/packages/core/src/package-scoped-resolution.test.ts +++ b/packages/core/src/package-scoped-resolution.test.ts @@ -152,3 +152,34 @@ describe('the holder source', () => { expect(() => packageScopedHolderSource([[null, 1], [null, 2]])).toThrow(TypeError); }); }); + +describe('the platform\'s item — in every caller\'s reach, like `sys` (epic seat ruling 6729484996)', () => { + const withPlatform = (pairs: Array<[string, string]>, platform: string | undefined) => { + const packages = packageScopedHolderSource(pairs); + return { ...packages, platformItem: () => platform }; + }; + const ask = (pairs: Array<[string, string]>, platform: string | undefined, reach: readonly string[], callerPackageId?: string) => + resolvePackageScopedHolders({ type: ENGINE_FUNCTION_TYPE, name: 'score', callerPackageId }, withPlatform(pairs, platform), closure(reach)); + + it('a package caller whose only reachable candidate it is resolves to it; a holder outside the closure is no candidate', () => { + expect(ask([], 'host', [], P)).toEqual({ status: 'resolved', item: 'host', holder: { kind: 'platform' }, via: 'platform' }); + expect(ask([[C, 'c']], 'host', [], P)).toMatchObject({ status: 'resolved', item: 'host', via: 'platform' }); + }); + + it('the caller\'s own item comes first', () => { + expect(ask([[P, 'p']], 'host', [], P)).toMatchObject({ status: 'resolved', item: 'p', via: 'own' }); + }); + + it('red line 1: beside a closure holder it refuses, naming each', () => { + const r = ask([[A, 'a']], 'host', [A], P); + expect(r).toMatchObject({ status: 'refused', reason: 'ambiguous-in-closure', candidates: [{ kind: 'package', packageId: A }, { kind: 'platform' }] }); + expect(r.status === 'refused' && r.message).toContain('the platform'); + }); + + it('a caller with no package: the environment\'s own item, then the platform\'s, then the unique package holder', () => { + expect(ask([[A, 'a']], 'host', [])).toMatchObject({ status: 'resolved', item: 'host', via: 'platform' }); + const env = { ...withPlatform([[A, 'a']], 'host'), environmentItem: () => 'env' }; + expect(resolvePackageScopedHolders({ type: ENGINE_FUNCTION_TYPE, name: 'score' }, env, closure([]))).toMatchObject({ item: 'env', via: 'environment' }); + expect(ask([[A, 'a']], undefined, [])).toMatchObject({ item: 'a', via: 'unique-holder' }); + }); +}); diff --git a/packages/core/src/package-scoped-resolution.ts b/packages/core/src/package-scoped-resolution.ts index 8481b6c9613..d1e85bad2cf 100644 --- a/packages/core/src/package-scoped-resolution.ts +++ b/packages/core/src/package-scoped-resolution.ts @@ -65,6 +65,11 @@ * and asking for one throws. * - **An overridable baseline** ({@link OVERRIDABLE_BASELINE_PACKAGES}) answers * only when no other candidate of that step does. + * - **The platform's item** ({@link PackageScopedHolderSource.platformItem}: + * an engine function a plugin or the host registers under no package) is + * in every caller's reach, like `sys` (D2): step 2 counts it beside the + * closure's holders, and a caller with no package reaches it after the + * environment's own item (epic seat ruling on #31733, 6729484996). */ // --------------------------------------------------------------------------- @@ -256,18 +261,22 @@ const OVERLAY_PROVENANCE_SENTINEL = 'sys_metadata'; /** * Who holds a name under package addressing: a package (the vocabulary's own - * {@link BareNameHolder}), or the environment's own item — an item authored in - * this environment, in the implicit environment package (ADR-0150 D1 bucket 4). + * {@link BareNameHolder}), the environment's own item — an item authored in + * this environment, in the implicit environment package (ADR-0150 D1 bucket 4) + * — or the platform: code a plugin or the host registers under no package (an + * owner-less engine function), reachable from every caller like `sys` (D2; + * epic seat ruling on #31733, 6729484996). */ export type PackageScopedHolder = | Extract - | { readonly kind: 'environment' }; + | { readonly kind: 'environment' } + | { readonly kind: 'platform' }; /** How a refusal names a holder. */ export function describePackageScopedHolder(holder: PackageScopedHolder): string { - return holder.kind === 'environment' - ? 'the environment (an item authored in this environment, bound to no package)' - : describeBareNameHolder(holder); + if (holder.kind === 'environment') return 'the environment (an item authored in this environment, bound to no package)'; + if (holder.kind === 'platform') return 'the platform (registered by a plugin or the host, owned by no package)'; + return describeBareNameHolder(holder); } /** How the resolved item was reached (ADR-0150 D3's steps). */ @@ -281,7 +290,9 @@ export type PackageScopedResolutionStep = /** the unique package holder in the environment (a caller with no package) */ | 'unique-holder' /** an overridable baseline, reached because no other candidate of the step holds the name */ - | 'baseline'; + | 'baseline' + /** the platform's item (owned by no package, in every caller's reach), the step's only candidate */ + | 'platform'; /** Why a resolution refused. */ export type PackageScopedRefusalReason = @@ -351,6 +362,16 @@ export interface PackageScopedHolderSource { * overlay). */ environmentItem(): T | undefined; + /** + * The platform's item of the name — code a plugin or the host registered + * under no package (an owner-less engine function) — or `undefined`. + * Omitted, there is none. Like a `sys` package (ADR-0150 D2) it is in every + * caller's reach: a package caller that holds no item itself counts it + * beside its closure's holders (one answers, two or more refuse naming + * each), and a caller with no package reaches it after the environment's + * own item and before the package holders. + */ + platformItem?(): T | undefined; } /** @@ -421,10 +442,11 @@ function typeLabel(type: PackageScopedResolvableType): string { export function packageScopedRefusalMessage(refusal: Omit): string { const subject = `The ${typeLabel(refusal.type)} "${refusal.name}"`; const named = refusal.candidates.map(describePackageScopedHolder).join('; '); + const platform = refusal.candidates.some((c) => c.kind === 'platform'); switch (refusal.reason) { case 'ambiguous-in-closure': - return `${subject} is held by ${refusal.candidates.length} packages in the declared dependency closure of ` + - `package "${refusal.callerPackageId}": ${named}. Nothing picks one of them: address it by its package.`; + return `${subject} is held by ${refusal.candidates.length} ${platform ? 'holders' : 'packages'} in the declared dependency closure of ` + + `package "${refusal.callerPackageId}"${platform ? ' and the platform' : ''}: ${named}. Nothing picks one of them: address it by its package.`; case 'ambiguous-in-environment': return `${subject} is held by ${refusal.candidates.length} packages in this environment and the caller names ` + `no package: ${named}. Nothing picks one of them: address it by its package.`; @@ -483,6 +505,8 @@ function resolveEnvironmentWide( if (environmentItem !== undefined) { return { status: 'resolved', item: environmentItem, holder: { kind: 'environment' }, via: 'environment' }; } + const platformItem = source.platformItem?.(); + if (platformItem !== undefined) return { status: 'resolved', item: platformItem, holder: { kind: 'platform' }, via: 'platform' }; const pick = pickUnique(query.type, source.packageHolders); if (pick.kind === 'one') return packageItem(source, pick.packageId, pick.baseline ? 'baseline' : 'unique-holder'); if (pick.kind === 'several') return refuse(query, callerPackageId, 'ambiguous-in-environment', pick.packageIds.map(packageHolder)); @@ -521,9 +545,16 @@ export function resolvePackageScopedHolders( // Step 1 — the caller package's own item. if (holders.includes(callerPackageId)) return packageItem(source, callerPackageId, 'own'); - // Step 2 — the unique holder in its resolution closure. + // Step 2 — the unique holder in its resolution closure, the platform's + // item counted beside it (in every caller's reach, like `sys`). const reach = closureOf(callerPackageId); - const pick = pickUnique(query.type, holders.filter((id) => reach.has(id))); + const reachable = holders.filter((id) => reach.has(id)); + const platformItem = source.platformItem?.(); + if (platformItem !== undefined) { + if (reachable.length === 0) return { status: 'resolved', item: platformItem, holder: { kind: 'platform' }, via: 'platform' }; + return refuse(query, callerPackageId, 'ambiguous-in-closure', [...reachable.map(packageHolder), { kind: 'platform' }]); + } + const pick = pickUnique(query.type, reachable); if (pick.kind === 'one') return packageItem(source, pick.packageId, pick.baseline ? 'baseline' : 'closure'); if (pick.kind === 'several') return refuse(query, callerPackageId, 'ambiguous-in-closure', pick.packageIds.map(packageHolder)); diff --git a/packages/objectql/src/engine-hooks-and-functions.ts b/packages/objectql/src/engine-hooks-and-functions.ts index 619ea509213..cc28836ab8f 100644 --- a/packages/objectql/src/engine-hooks-and-functions.ts +++ b/packages/objectql/src/engine-hooks-and-functions.ts @@ -301,8 +301,18 @@ export class HooksAndFunctionsFacet { /** The body of `ObjectQL#functionHoldersOf`; the method's docblock there is its contract. */ static functionHoldersOf(this: Pick, name: string): PackageScopedHolderSource> { - // A snapshot: a registration after this call is not in it. - return packageScopedHolderSource>(this.functionHolders.get(name) ?? []); + // A snapshot: a registration after this call is not in it. An owner-less + // registration is the platform's (code a plugin or the host registers), + // never an item authored in the environment (epic seat ruling 6729484996). + const holdings = [...(this.functionHolders.get(name) ?? [])]; + const platform = holdings.find(([packageId]) => packageId === null)?.[1]; + const packages = packageScopedHolderSource>(holdings.filter(([packageId]) => packageId !== null)); + return Object.freeze({ + packageHolders: packages.packageHolders, + packageItem: packages.packageItem, + environmentItem: () => undefined, + platformItem: () => platform, + }); } /** The body of `ObjectQL#bindHooks`; the method's docblock there is its contract. */ diff --git a/packages/objectql/src/engine.ts b/packages/objectql/src/engine.ts index ef19540a57f..bc916c6c12b 100644 --- a/packages/objectql/src/engine.ts +++ b/packages/objectql/src/engine.ts @@ -835,7 +835,8 @@ export class ObjectQL implements IObjectQLEngine { /** * Every holder of the function `name` (ADR-0150 D4): each package that * registered one under that name, with its own entry, and an owner-less - * registration as the environment's own item — the holder set + * registration as the platform's item (`platformItem`: code a plugin or + * the host registers, in every caller's reach like `sys`) — the holder set * `resolvePackageScopedFunction` resolves a flow's or an action's function * over, in the referrer's package. A snapshot, taken at the call. * `resolveFunction` and `resolveFunctionEntry` keep answering the one diff --git a/packages/objectql/src/package-scoped-resolver.test.ts b/packages/objectql/src/package-scoped-resolver.test.ts index f65ceee98b3..e0e6ff0e97b 100644 --- a/packages/objectql/src/package-scoped-resolver.test.ts +++ b/packages/objectql/src/package-scoped-resolver.test.ts @@ -631,7 +631,7 @@ describe('R2 — engine functions resolve in their referrer\'s package (ADR-0150 expect(r.status === 'refused' && r.message).toContain('The function "score"'); }); - it('red line 2: every refusal names every holder, and the environment', () => { + it('red line 2: every refusal names every holder, and the platform', () => { for (const id of [A, B, C]) installOn(id); installOn(P, [A, B, C]); installOn(MID); @@ -640,19 +640,58 @@ describe('R2 — engine functions resolve in their referrer\'s package (ADR-0150 if (inClosure.status !== 'refused') throw new Error(`expected a refusal, got ${inClosure.status}`); expect(inClosure.candidates).toEqual([A, B, C].map((packageId) => ({ kind: 'package', packageId }))); for (const id of [A, B, C]) expect(inClosure.message).toContain(`package "${id}"`); - engine.registerFunction('score', fn('host')); const outside = resolveFn('score', MID); if (outside.status !== 'refused') throw new Error(`expected a refusal, got ${outside.status}`); expect(outside.reason).toBe('outside-closure'); - expect(outside.candidates).toEqual([...[A, B, C].map((packageId) => ({ kind: 'package', packageId })), { kind: 'environment' }]); - }); - - it('an owner-less registration is the environment\'s own: a caller with no package gets it, a package caller is refused (D3 (a))', () => { - installOn(P); + expect(outside.candidates).toEqual([A, B, C].map((packageId) => ({ kind: 'package', packageId }))); engine.registerFunction('score', fn('host')); - expect(engine.functionHoldersOf('score').packageHolders).toEqual([]); - expect(resolveFn('score')).toMatchObject({ status: 'resolved', via: 'environment', holder: { kind: 'environment' } }); - expect(resolveFn('score', P)).toMatchObject({ status: 'refused', reason: 'outside-closure', candidates: [{ kind: 'environment' }] }); + const withPlatform = resolveFn('score', P); + if (withPlatform.status !== 'refused') throw new Error(`expected a refusal, got ${withPlatform.status}`); + expect(withPlatform.reason).toBe('ambiguous-in-closure'); + expect(withPlatform.candidates).toEqual([...[A, B, C].map((packageId) => ({ kind: 'package', packageId })), { kind: 'platform' }]); + expect(withPlatform.message).toContain('the platform'); + }); + + describe('an owner-less registration is the platform\'s, in every caller\'s reach like `sys` (ruling 6729484996)', () => { + it('a caller with no package and a package caller whose only holder it is both resolve to it', () => { + installOn(P); + engine.registerFunction('score', fn('host')); + expect(engine.functionHoldersOf('score').packageHolders).toEqual([]); + expect(engine.functionHoldersOf('score').environmentItem()).toBeUndefined(); + for (const caller of [undefined, P]) { + expect(resolveFn('score', caller)).toMatchObject({ status: 'resolved', via: 'platform', holder: { kind: 'platform' } }); + expect(tagOf(resolveFn('score', caller))).toBe('host'); + } + }); + + it('a holder outside the closure is no candidate beside it', () => { + installOn(C); + installOn(P); + engine.registerFunction('score', fn('gamma'), `app:${C}`); + engine.registerFunction('score', fn('host')); + expect(tagOf(resolveFn('score', P))).toBe('host'); + }); + + it('the caller\'s own function still comes first', () => { + installOn(P); + engine.registerFunction('score', fn('host')); + engine.registerFunction('score', fn('caller'), `app:${P}`); + expect(resolveFn('score', P)).toMatchObject({ status: 'resolved', via: 'own' }); + expect(tagOf(resolveFn('score', P))).toBe('caller'); + }); + + it('red line 1: beside a closure holder it refuses, naming both', () => { + installOn(A); + installOn(P, [A]); + engine.registerFunction('score', fn('alpha'), `app:${A}`); + engine.registerFunction('score', fn('host')); + expect(resolveFn('score', P)).toMatchObject({ + status: 'refused', reason: 'ambiguous-in-closure', + candidates: [{ kind: 'package', packageId: A }, { kind: 'platform' }], + }); + // A caller with no package keeps the environment-wide order: the platform's first. + expect(tagOf(resolveFn('score'))).toBe('host'); + }); }); it('a `sys` package\'s function is in every caller\'s closure', () => { @@ -716,7 +755,7 @@ describe('R2 — a bundle addition is no holder of its base\'s name for a bare r it(`a dependent's locale its base does not ship (${how}) adds no holder: the base's name still resolves`, () => { add(D, 'fr-FR', 'addon-fr'); expect(registry.packageScopedHoldersOf('email_template', 'welcome')).toEqual([A]); - for (const caller of [undefined, P, D]) { + for (const caller of [undefined, P]) { expect(label(resolve('email_template', 'welcome', caller))).toBe('alpha template'); } // The addition is still the dependent's member, read naming the dependent. @@ -724,6 +763,16 @@ describe('R2 — a bundle addition is no holder of its base\'s name for a bare r // The base's address does not serve it. expect(resolve('email_template', 'welcome', undefined, 'fr-FR')).toEqual({ status: 'not-found' }); }); + + it(`the dependent's own bare read (${how}) still answers its own item at step 1, as before the addition rule`, () => { + add(D, 'fr-FR', 'addon-fr'); + expect(registry.packageScopedHoldersOf('email_template', 'welcome', D)).toEqual([A, D]); + expect(resolve('email_template', 'welcome', D, 'fr-FR')).toMatchObject({ status: 'resolved', via: 'own', holder: { kind: 'package', packageId: D } }); + expect(label(resolve('email_template', 'welcome', D, 'fr-FR'))).toBe('addon-fr template'); + expect(label(resolve('email_template', 'welcome', D))).toBe('addon-fr template'); + // A member only the base holds: unchanged — the caller's own holding answers, and it lacks it. + expect(resolve('email_template', 'welcome', D, 'en-US')).toEqual({ status: 'not-found' }); + }); } it('red line 1: a dependent holding a member its base holds is a holder, and the bare read refuses', () => { diff --git a/packages/objectql/src/package-scoped-resolver.ts b/packages/objectql/src/package-scoped-resolver.ts index 6e7303823c5..9ae4742b8ef 100644 --- a/packages/objectql/src/package-scoped-resolver.ts +++ b/packages/objectql/src/package-scoped-resolver.ts @@ -144,7 +144,8 @@ export function resolvePackageScopedName( return resolvePackageScopedHolders( query, { - packageHolders: registry.packageScopedHoldersOf(type, name), + // The caller's own holding counts for its step 1 even as a bundle addition. + packageHolders: registry.packageScopedHoldersOf(type, name, query.callerPackageId), packageItem: (packageId) => registry.getPackageScopedItem(type, name, packageId, member), environmentItem: () => registry.getEnvironmentScopedItem(type, name, member), }, @@ -170,8 +171,11 @@ export type PackageScopedFunctionEngine = Pick>(); for (const id of holders) membersOf.set(id, this.bundleMembersHeldBy(type, collection, name, id, compositeSet, disc)); - return [...holders].filter((id) => !this.isBundleAddition(id, membersOf)); + return [...holders].filter((id) => id === callerPackageId || !this.isBundleAddition(id, membersOf)); } /** From 6860f06bbe1f2087628ccd1c1b5b6ecfd8764508 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 00:43:03 +0000 Subject: [PATCH 08/11] chore: changeset names the platform holder and the caller's own addition Claude-Session: https://claude.ai/code/session_01ADHkmQ5eMDSpkq6rYGLbBU Co-authored-by: Claude --- .changeset/31716-package-scoped-rule-lean.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.changeset/31716-package-scoped-rule-lean.md b/.changeset/31716-package-scoped-rule-lean.md index b842267cdf6..ef1e491a64d 100644 --- a/.changeset/31716-package-scoped-rule-lean.md +++ b/.changeset/31716-package-scoped-rule-lean.md @@ -14,7 +14,7 @@ Metadata-protocol: none - **`@objectstack/core`** exports `resolvePackageScopedHolders`, the ADR-0150 D3 rule as a pure function: a caller of package P is answered P's own item, else the unique holder in P's resolution closure, else a refusal naming every candidate; a caller with no package the environment's own item, else the unique package holder, else the refusal. The holders come from a `PackageScopedHolderSource` the caller supplies (`packageScopedHolderSource` builds one from `(package, item)` pairs, a `null` package being the environment's own item), and the closure from a function the caller supplies. The refusal vocabulary moves with it: `PACKAGE_SCOPED_TYPES`, `ENGINE_FUNCTION_TYPE`, `PLATFORM_REQUESTED_BARE_NAMES_BY_TYPE`, `OVERRIDABLE_BASELINE_PACKAGES`, `BARE_NAME_ONE_HOLDER_TYPES`, `describeBareNameHolder` and the refusal and resolution types. - **`@objectstack/metadata-core`** exports the one closure walk: `resolvePackageClosure` (moved from `@objectstack/lint`), `widenPairClosureToAppMembers` and `packageDependencyClosure` (moved from `@objectstack/metadata-protocol`), and `packageResolutionClosure` with `KERNEL_NAMESPACE` (moved from `@objectstack/objectql`): the declared dependency closure plus every `sys` package. - **`@objectstack/lint`**, **`@objectstack/metadata-protocol`** and **`@objectstack/objectql`** re-export every moved name under the name they published, so no import changes. objectql's `resolvePackageScopedName` keeps its signature and answers, now as the rule's call over the registry's holders. -- **`@objectstack/objectql`** adds `resolvePackageScopedFunction`, the rule's call over the engine's function holders, and `ObjectQL#functionHoldersOf(name)`: every package that registered a function of that name (the owner `app:PACKAGE_ID` read as the package id), with its own entry, and an owner-less registration as the environment's own item. -- **`@objectstack/objectql`**: `SchemaRegistry#packageScopedHoldersOf` no longer counts a bundle addition as a holder (#28802). A dependent package's email template locale its base does not ship stays under the dependent, so it is no second holder of the base's name for a bare read, and a package-less resolve of the base's template answers the base. A read naming the dependent (`getPackageScopedItem`) still reaches the addition. A dependent holding a member its base also holds, and a package that does not declare the holder, are still holders, and the bare read refuses them. +- **`@objectstack/objectql`** adds `resolvePackageScopedFunction`, the rule's call over the engine's function holders, and `ObjectQL#functionHoldersOf(name)`: every package that registered a function of that name (the owner `app:PACKAGE_ID` read as the package id), with its own entry. An owner-less registration is the platform's item (`platformItem`, holder kind `platform`, step `platform`): code a plugin or the host registers, in every caller's reach like a `sys` package, so a package caller holding none counts it beside its closure's holders and two or more refuse naming each. +- **`@objectstack/objectql`**: `SchemaRegistry#packageScopedHoldersOf` no longer counts a bundle addition as a holder (#28802). A dependent package's email template locale its base does not ship stays under the dependent, so it is no second holder of the base's name for a bare read, and a package-less resolve of the base's template answers the base. The dependent's own bare read still answers its own item (step 1, `packageScopedHoldersOf(type, name, callerPackageId)`), and a read naming the dependent (`getPackageScopedItem`) still reaches the addition. A dependent holding a member its base also holds, and a package that does not declare the holder, are still holders, and the bare read refuses them. Nothing changes for a running deployment: no reader calls the rule yet, `resolveFunction` and `resolveFunctionEntry` keep answering the one last-registered function per name, the save door admits and refuses exactly what it did, and phase 1's one-holder refusal stays in force. From 2bec106d17d8d5394ba9b21c7ded31ccc8c82f76 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 01:06:13 +0000 Subject: [PATCH 09/11] fix(core, objectql): a caller carrying the compatibility API's default package id is a caller with no package ObjectQL#registerObject stamps '__runtime__' when its caller gives no package id. That names no installed package, so the rule now reads such a caller as one with no package, beside the sys_metadata sentinel, instead of refusing it every environment item. The compatibility API takes its default from the one exported spelling. Claude-Session: https://claude.ai/code/session_01ADHkmQ5eMDSpkq6rYGLbBU Co-authored-by: Claude --- .changeset/31716-package-scoped-rule-lean.md | 1 + .../src/package-scoped-resolution.test.ts | 15 ++++++++++++++ .../core/src/package-scoped-resolution.ts | 20 ++++++++++++++++--- .../objectql/src/engine-compatibility-api.ts | 3 ++- packages/objectql/src/engine.ts | 3 ++- .../src/package-scoped-resolver.test.ts | 13 ++++++++++++ 6 files changed, 50 insertions(+), 5 deletions(-) diff --git a/.changeset/31716-package-scoped-rule-lean.md b/.changeset/31716-package-scoped-rule-lean.md index ef1e491a64d..fca7d386794 100644 --- a/.changeset/31716-package-scoped-rule-lean.md +++ b/.changeset/31716-package-scoped-rule-lean.md @@ -16,5 +16,6 @@ Metadata-protocol: none - **`@objectstack/lint`**, **`@objectstack/metadata-protocol`** and **`@objectstack/objectql`** re-export every moved name under the name they published, so no import changes. objectql's `resolvePackageScopedName` keeps its signature and answers, now as the rule's call over the registry's holders. - **`@objectstack/objectql`** adds `resolvePackageScopedFunction`, the rule's call over the engine's function holders, and `ObjectQL#functionHoldersOf(name)`: every package that registered a function of that name (the owner `app:PACKAGE_ID` read as the package id), with its own entry. An owner-less registration is the platform's item (`platformItem`, holder kind `platform`, step `platform`): code a plugin or the host registers, in every caller's reach like a `sys` package, so a package caller holding none counts it beside its closure's holders and two or more refuse naming each. - **`@objectstack/objectql`**: `SchemaRegistry#packageScopedHoldersOf` no longer counts a bundle addition as a holder (#28802). A dependent package's email template locale its base does not ship stays under the dependent, so it is no second holder of the base's name for a bare read, and a package-less resolve of the base's template answers the base. The dependent's own bare read still answers its own item (step 1, `packageScopedHoldersOf(type, name, callerPackageId)`), and a read naming the dependent (`getPackageScopedItem`) still reaches the addition. A dependent holding a member its base also holds, and a package that does not declare the holder, are still holders, and the bare read refuses them. +- **`@objectstack/core`** exports `RUNTIME_COMPATIBILITY_PACKAGE_ID` (`'__runtime__'`), the package id `ObjectQL#registerObject` stamps when its caller gives none, and reads a caller carrying it as a caller with no package (beside the `sys_metadata` sentinel), so it is not refused environment items. How an item stamped with it counts as a holder is unchanged. objectql's compatibility API takes its default from this one spelling. Nothing changes for a running deployment: no reader calls the rule yet, `resolveFunction` and `resolveFunctionEntry` keep answering the one last-registered function per name, the save door admits and refuses exactly what it did, and phase 1's one-holder refusal stays in force. diff --git a/packages/core/src/package-scoped-resolution.test.ts b/packages/core/src/package-scoped-resolution.test.ts index 3ebad196362..0714f1b0aae 100644 --- a/packages/core/src/package-scoped-resolution.test.ts +++ b/packages/core/src/package-scoped-resolution.test.ts @@ -16,6 +16,7 @@ import { describe, expect, it } from 'vitest'; import { ENGINE_FUNCTION_TYPE, OVERRIDABLE_BASELINE_PACKAGES, + RUNTIME_COMPATIBILITY_PACKAGE_ID, packageScopedHolderSource, resolvePackageScopedHolders, type PackageResolutionClosureOf, @@ -183,3 +184,17 @@ describe('the platform\'s item — in every caller\'s reach, like `sys` (epic se expect(ask([[A, 'a']], undefined, [])).toMatchObject({ item: 'a', via: 'unique-holder' }); }); }); + +describe('the compatibility API\'s default package id is a caller with no package (epic seat ruling from E6)', () => { + it('a `__runtime__` caller reaches an environment-only item, as a caller with no package does', () => { + expect(RUNTIME_COMPATIBILITY_PACKAGE_ID).toBe('__runtime__'); + const envOnly = packageScopedHolderSource([[null, 'env']]); + const never: PackageResolutionClosureOf = () => { throw new Error('asked'); }; + expect(resolvePackageScopedHolders({ type: 'flow', name: 'n', callerPackageId: RUNTIME_COMPATIBILITY_PACKAGE_ID }, envOnly, never)) + .toEqual({ status: 'resolved', item: 'env', holder: { kind: 'environment' }, via: 'environment' }); + }); + + it('only the caller side: an item stamped `__runtime__` is still a package holder', () => { + expect(resolve([['__runtime__', 'r'], [A, 'a']], [])).toMatchObject({ status: 'refused', reason: 'ambiguous-in-environment' }); + }); +}); diff --git a/packages/core/src/package-scoped-resolution.ts b/packages/core/src/package-scoped-resolution.ts index d1e85bad2cf..42a707ba7cf 100644 --- a/packages/core/src/package-scoped-resolution.ts +++ b/packages/core/src/package-scoped-resolution.ts @@ -255,6 +255,17 @@ export function isPlatformRequestedBareName(type: PackageScopedType, name: strin /** The value `_packageId` carries for a row rehydrated from `sys_metadata`: not a package. */ const OVERLAY_PROVENANCE_SENTINEL = 'sys_metadata'; +/** + * The package id `ObjectQL#registerObject` stamps when its caller gives none + * (the legacy compatibility API's default). It names no installed package, so + * a caller carrying it is a caller with no package: the rule reads it as one, + * beside the `sys_metadata` sentinel, rather than as a package whose closure + * is empty (which would refuse it every environment item, D3 (a)). Only the + * caller side: how an item stamped with it counts as a holder is unchanged. + * The one spelling; the compatibility API reads it from here. + */ +export const RUNTIME_COMPATIBILITY_PACKAGE_ID = '__runtime__'; + // --------------------------------------------------------------------------- // The answer. // --------------------------------------------------------------------------- @@ -337,8 +348,9 @@ export interface PackageScopedHoldersQuery { readonly type: PackageScopedResolvableType; readonly name: string; /** - * The package the caller belongs to; omitted, `null`, `''` or the - * `sys_metadata` sentinel is a caller with no package. + * The package the caller belongs to; omitted, `null`, `''`, the + * `sys_metadata` sentinel or {@link RUNTIME_COMPATIBILITY_PACKAGE_ID} is a + * caller with no package. */ readonly callerPackageId?: string | null; } @@ -535,7 +547,9 @@ export function resolvePackageScopedHolders( ); } const raw = query.callerPackageId; - const callerPackageId = typeof raw === 'string' && raw !== '' && raw !== OVERLAY_PROVENANCE_SENTINEL ? raw : null; + const callerPackageId = typeof raw === 'string' && raw !== '' && raw !== OVERLAY_PROVENANCE_SENTINEL && raw !== RUNTIME_COMPATIBILITY_PACKAGE_ID + ? raw + : null; const holders = source.packageHolders; if (callerPackageId === null || (query.type !== ENGINE_FUNCTION_TYPE && isPlatformRequestedBareName(query.type, query.name))) { diff --git a/packages/objectql/src/engine-compatibility-api.ts b/packages/objectql/src/engine-compatibility-api.ts index d19ea8f032e..156d278a33c 100644 --- a/packages/objectql/src/engine-compatibility-api.ts +++ b/packages/objectql/src/engine-compatibility-api.ts @@ -48,6 +48,7 @@ import type { ServiceObject } from '@objectstack/spec/data'; import type { IntrospectedSchema as SpecIntrospectedSchema } from '@objectstack/spec/contracts'; import { StorageNameMapping } from '@objectstack/spec/system'; +import { RUNTIME_COMPATIBILITY_PACKAGE_ID } from '@objectstack/core'; import { isFederatedObject } from './federated-object.js'; import type { ObjectQL } from './engine.js'; @@ -72,7 +73,7 @@ export interface CompatibilityApiHost { export function registerObject( this: Pick, schema: ServiceObject, - packageId: string = '__runtime__', + packageId: string = RUNTIME_COMPATIBILITY_PACKAGE_ID, namespace?: string, ): string { // Auto-assign field names from keys diff --git a/packages/objectql/src/engine.ts b/packages/objectql/src/engine.ts index bc916c6c12b..164e4a26aab 100644 --- a/packages/objectql/src/engine.ts +++ b/packages/objectql/src/engine.ts @@ -140,6 +140,7 @@ import { type EngineTransactionOptions, Logger, type PackageScopedHolderSource, + RUNTIME_COMPATIBILITY_PACKAGE_ID, type RetryOptions, recordNotFoundError, resolveUserAuthzGrants, @@ -9532,7 +9533,7 @@ export class ObjectQL implements IObjectQLEngine { */ registerObject( schema: ServiceObject, - packageId: string = '__runtime__', + packageId: string = RUNTIME_COMPATIBILITY_PACKAGE_ID, namespace?: string ): string { // [#25522 cut 8] The body moved to `engine-compatibility-api.ts` (see `CompatibilityApiHost`). diff --git a/packages/objectql/src/package-scoped-resolver.test.ts b/packages/objectql/src/package-scoped-resolver.test.ts index e0e6ff0e97b..38b85cd962d 100644 --- a/packages/objectql/src/package-scoped-resolver.test.ts +++ b/packages/objectql/src/package-scoped-resolver.test.ts @@ -797,3 +797,16 @@ describe('R2 — a bundle addition is no holder of its base\'s name for a bare r expect(registry.packageScopedHoldersOf('flow', 'send_email')).toEqual([A, D]); }); }); + +describe('R2 — an object registered with no package id is a caller with no package (`__runtime__`)', () => { + it('a `__runtime__` caller reaches an environment-only item over the registry', () => { + registry.registerItem('flow', body('flow', 'env_only', 'env'), 'name' as never); + expect(label(resolve('flow', 'env_only', core.RUNTIME_COMPATIBILITY_PACKAGE_ID))).toBe('env flow'); + }); + + it('the compatibility API stamps that one spelling', () => { + const ql = new ObjectQL(); + expect(ql.registerObject({ name: 'rt_probe', fields: {} } as never)).toBeDefined(); + expect((ql.registry.getObject('rt_probe') as { _packageId?: unknown } | undefined)?._packageId).toBe(core.RUNTIME_COMPATIBILITY_PACKAGE_ID); + }); +}); From cde2d586641e02ba7f3e51aeb95c056e5fcfd933 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 01:20:31 +0000 Subject: [PATCH 10/11] fix(metadata-core, objectql): a residual owner's declared dependencies reach the one closure walk A multi-package stack's residual owner has no package record, so the walk read its declared closure as empty and it could reach no dependency whatever it declared. The registry now keeps what the stack's manifest declares beside the package records, and the walk reads it for an id getPackage cannot produce, so every reader sees one closure for it. Claude-Session: https://claude.ai/code/session_01ADHkmQ5eMDSpkq6rYGLbBU Co-authored-by: Claude --- .changeset/31716-package-scoped-rule-lean.md | 1 + .../metadata-core/src/package-closure.test.ts | 45 +++++++++++++++++++ packages/metadata-core/src/package-closure.ts | 35 +++++++++++++-- .../manifest-service-residual-objects.test.ts | 14 ++++++ .../src/package-scoped-resolver.test.ts | 29 ++++++++++++ packages/objectql/src/plugin.ts | 9 +++- packages/objectql/src/registry.ts | 29 ++++++++++++ 7 files changed, 158 insertions(+), 4 deletions(-) create mode 100644 packages/metadata-core/src/package-closure.test.ts diff --git a/.changeset/31716-package-scoped-rule-lean.md b/.changeset/31716-package-scoped-rule-lean.md index fca7d386794..871d034c0a7 100644 --- a/.changeset/31716-package-scoped-rule-lean.md +++ b/.changeset/31716-package-scoped-rule-lean.md @@ -17,5 +17,6 @@ Metadata-protocol: none - **`@objectstack/objectql`** adds `resolvePackageScopedFunction`, the rule's call over the engine's function holders, and `ObjectQL#functionHoldersOf(name)`: every package that registered a function of that name (the owner `app:PACKAGE_ID` read as the package id), with its own entry. An owner-less registration is the platform's item (`platformItem`, holder kind `platform`, step `platform`): code a plugin or the host registers, in every caller's reach like a `sys` package, so a package caller holding none counts it beside its closure's holders and two or more refuse naming each. - **`@objectstack/objectql`**: `SchemaRegistry#packageScopedHoldersOf` no longer counts a bundle addition as a holder (#28802). A dependent package's email template locale its base does not ship stays under the dependent, so it is no second holder of the base's name for a bare read, and a package-less resolve of the base's template answers the base. The dependent's own bare read still answers its own item (step 1, `packageScopedHoldersOf(type, name, callerPackageId)`), and a read naming the dependent (`getPackageScopedItem`) still reaches the addition. A dependent holding a member its base also holds, and a package that does not declare the holder, are still holders, and the bare read refuses them. - **`@objectstack/core`** exports `RUNTIME_COMPATIBILITY_PACKAGE_ID` (`'__runtime__'`), the package id `ObjectQL#registerObject` stamps when its caller gives none, and reads a caller carrying it as a caller with no package (beside the `sys_metadata` sentinel), so it is not refused environment items. How an item stamped with it counts as a holder is unchanged. objectql's compatibility API takes its default from this one spelling. +- **`@objectstack/metadata-core`**: the one closure walk reads a residual owner (ADR-0130 D4, the id a multi-package stack's top-level items are owned by, which has no package record) through the dependencies it declared, via the optional `PackageClosureRegistry#residualOwnerDependenciesOf`. **`@objectstack/objectql`** records them when the manifest service registers a stack's residual (`SchemaRegistry#recordResidualOwnerDependencies` / `residualOwnerDependenciesOf`), with no package record added. A residual then reaches what it declares through every reader of the walk, and the save door's write scope for a residual owner is that declared closure, where before it narrowed nothing. Nothing changes for a running deployment: no reader calls the rule yet, `resolveFunction` and `resolveFunctionEntry` keep answering the one last-registered function per name, the save door admits and refuses exactly what it did, and phase 1's one-holder refusal stays in force. diff --git a/packages/metadata-core/src/package-closure.test.ts b/packages/metadata-core/src/package-closure.test.ts new file mode 100644 index 00000000000..c5c13f511c7 --- /dev/null +++ b/packages/metadata-core/src/package-closure.test.ts @@ -0,0 +1,45 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The one closure walk reads a residual owner (ADR-0130 D4: no package + * record) through the dependencies it declared — epic #31527 child R2, ruled + * from E6's finding. Every reader of the walk (the save door's write scope, + * the resolution rule's closure) then sees one closure for it. + */ + +import { describe, expect, it } from 'vitest'; +import { packageDependencyClosure, packageResolutionClosure, type PackageClosureRegistry } from './package-closure.js'; + +const A = 'com.acme.alpha'; +const B = 'com.acme.beta'; +const R = 'com.acme.release'; +const manifest = (id: string, deps: string[] = []) => ({ manifest: { id, dependencies: Object.fromEntries(deps.map((d) => [d, '*'])) } }); + +const registryOf = (rows: Array<{ manifest: { id: string } }>, residuals: Record = {}): PackageClosureRegistry => ({ + getPackage: (id) => rows.find((r) => r.manifest.id === id), + getAllPackages: () => rows, + residualOwnerDependenciesOf: (id) => residuals[id], +}); + +describe('a residual owner\'s declared closure', () => { + it('is walked like a package\'s, transitively, by both the save door\'s walk and the resolution closure', () => { + const registry = registryOf([manifest(A, [B]), manifest(B)], { [R]: [A] }); + expect(packageDependencyClosure(R, registry)).toEqual({ packageId: R, dependencies: [A, B] }); + expect([...packageResolutionClosure(registry, R)].sort()).toEqual([A, B]); + }); + + it('an id that is neither a package nor a residual owner still narrows nothing', () => { + expect(packageDependencyClosure(R, registryOf([manifest(A)]))).toBeUndefined(); + expect(packageResolutionClosure(registryOf([manifest(A)]), R).size).toBe(0); + }); + + it('a package record wins over a residual record of the same id', () => { + const registry = registryOf([manifest(A)], { [A]: [B] }); + expect(packageDependencyClosure(A, registry)).toEqual({ packageId: A, dependencies: [] }); + }); + + it('a registry without the member reads as before', () => { + const registry: PackageClosureRegistry = { getPackage: () => undefined, getAllPackages: () => [] }; + expect(packageDependencyClosure(R, registry)).toBeUndefined(); + }); +}); diff --git a/packages/metadata-core/src/package-closure.ts b/packages/metadata-core/src/package-closure.ts index 6385f762a30..50141a5bf16 100644 --- a/packages/metadata-core/src/package-closure.ts +++ b/packages/metadata-core/src/package-closure.ts @@ -87,6 +87,31 @@ export function resolvePackageClosure( export interface PackageClosureRegistry { getPackage?: (id: string) => { manifest?: unknown } | undefined; getAllPackages?: () => ReadonlyArray<{ manifest?: unknown }>; + /** + * [ADR-0130 D4] The dependencies a residual owner declared — the id a + * multi-package stack's top-level items are owned by, which has no package + * record — or `undefined` for an id that is no residual owner. Read only + * for an id `getPackage` cannot produce, so a residual's declared closure is + * walked like a package's, by every reader of this walk. + */ + residualOwnerDependenciesOf?: (id: string) => readonly string[] | undefined; +} + +/** + * `registry.getPackage`, answering a residual owner (ADR-0130 D4) that has no + * package record with a manifest of the dependencies it declared, so the walk + * reads it as it reads a package. A package record always wins. + */ +function closurePackageReader(registry: PackageClosureRegistry, getPackage: NonNullable) { + const residual = registry.residualOwnerDependenciesOf; + return (id: string): { manifest?: unknown } | undefined => { + const row = getPackage.call(registry, id); + if (row || typeof residual !== 'function') return row; + const dependencies = residual.call(registry, id); + return dependencies === undefined + ? undefined + : { manifest: { id, dependencies: Object.fromEntries(dependencies.map((dep) => [dep, '*'])) } }; + }; } /** @@ -139,7 +164,11 @@ export function widenPairClosureToAppMembers( * * Answers `undefined` exactly where the walk does — no package id, the * `sys_metadata` sentinel, a package `registry` cannot produce — and for a - * registry with no `getPackage` (a metadata-only test double). Each reader + * registry with no `getPackage` (a metadata-only test double). A residual + * owner (ADR-0130 D4: no package record) is walked through the dependencies + * it declared ({@link PackageClosureRegistry.residualOwnerDependenciesOf}), + * so every reader — the save door and the resolution rule alike — sees one + * closure for it (epic #31527 R2, ruled from E6's finding). Each reader * decides what `undefined` means for it: the save door narrows nothing, the * resolver reaches nothing beyond the caller's own items and `sys`. * @@ -154,8 +183,8 @@ export function packageDependencyClosure( registry: PackageClosureRegistry | undefined, ): { packageId: string; dependencies: string[] } | undefined { const getPackage = registry?.getPackage; - if (typeof getPackage !== 'function') return undefined; - const closure = resolvePackageClosure(packageId, (id) => getPackage.call(registry, id)); + if (!registry || typeof getPackage !== 'function') return undefined; + const closure = resolvePackageClosure(packageId, closurePackageReader(registry, getPackage)); return closure === undefined ? undefined : widenPairClosureToAppMembers(closure, registry); } diff --git a/packages/objectql/src/manifest-service-residual-objects.test.ts b/packages/objectql/src/manifest-service-residual-objects.test.ts index c15d7f197b7..52d0db388e0 100644 --- a/packages/objectql/src/manifest-service-residual-objects.test.ts +++ b/packages/objectql/src/manifest-service-residual-objects.test.ts @@ -41,6 +41,7 @@ import { OWNERSHIP_QUEUE_SERVICE, type IMetadataService } from '@objectstack/spe import { ObjectQLPlugin } from './plugin.js'; import type { ObjectQL } from './engine.js'; import { viewContainerNameRefusal } from './view-container-name-refusal.js'; +import { packageResolutionClosure } from '@objectstack/metadata-core'; type ManifestService = { register(m: unknown): void | Promise }; @@ -723,3 +724,16 @@ describe('ADR-0130 D4 — a residual picklist that no object field names', () => expect(engineOf(kernel).registry.resolvePicklistOptions('acme_unused')?.map((o) => o.value)).toEqual(['a']); }); }); + +describe('[ADR-0130 D4, epic #31527 R2] the residual owner\'s declared dependencies reach the one closure walk', () => { + it('records what the stack\'s manifest declares, adds no package record, and the walk reads it', async () => { + const stack = residualStack(); + (stack as { manifest: Record }).manifest.dependencies = { [SERVICE_ID]: '^2.0.0' }; + const { kernel } = await boot(registering('test.residual-deps', [stack])); + const ql = engineOf(kernel); + expect(ql.registry.residualOwnerDependenciesOf(RELEASE_ID)).toEqual([SERVICE_ID]); + expect(ql.registry.getPackage(RELEASE_ID)).toBeUndefined(); + expect(acmePackageIds(ql)).not.toContain(RELEASE_ID); + expect(packageResolutionClosure(ql.registry, RELEASE_ID).has(SERVICE_ID)).toBe(true); + }); +}); diff --git a/packages/objectql/src/package-scoped-resolver.test.ts b/packages/objectql/src/package-scoped-resolver.test.ts index 38b85cd962d..daabb4466de 100644 --- a/packages/objectql/src/package-scoped-resolver.test.ts +++ b/packages/objectql/src/package-scoped-resolver.test.ts @@ -810,3 +810,32 @@ describe('R2 — an object registered with no package id is a caller with no pac expect((ql.registry.getObject('rt_probe') as { _packageId?: unknown } | undefined)?._packageId).toBe(core.RUNTIME_COMPATIBILITY_PACKAGE_ID); }); }); + +describe('R2 — a residual owner (ADR-0130 D4) reaches what it declares through the one walk', () => { + const RESIDUAL = 'com.acme.release'; + + it('a residual declaring a dependency reaches that dependency\'s item; declaring none, it is refused outside-closure', () => { + install(A); + ship('flow', 'send_email', A); + expect(registry.getPackage(RESIDUAL)).toBeUndefined(); + expect(resolve('flow', 'send_email', RESIDUAL)).toMatchObject({ + status: 'refused', reason: 'outside-closure', candidates: [{ kind: 'package', packageId: A }], + }); + registry.recordResidualOwnerDependencies(RESIDUAL, [A]); + expect(resolve('flow', 'send_email', RESIDUAL)).toMatchObject({ status: 'resolved', via: 'closure', holder: { kind: 'package', packageId: A } }); + expect(packageDependencyClosure(RESIDUAL, registry)).toEqual({ packageId: RESIDUAL, dependencies: [A] }); + // No package record appears for it. + expect(registry.getPackage(RESIDUAL)).toBeUndefined(); + expect(registry.getAllPackages().map((p) => p.manifest?.id)).not.toContain(RESIDUAL); + }); + + it('a residual declaring none reaches nothing beyond `sys`, and a package record always wins over a residual record', () => { + install(A); + ship('flow', 'send_email', A); + registry.recordResidualOwnerDependencies(RESIDUAL, []); + expect(resolve('flow', 'send_email', RESIDUAL)).toMatchObject({ status: 'refused', reason: 'outside-closure' }); + install(P); + registry.recordResidualOwnerDependencies(P, [A]); + expect(resolve('flow', 'send_email', P)).toMatchObject({ status: 'refused', reason: 'outside-closure' }); + }); +}); diff --git a/packages/objectql/src/plugin.ts b/packages/objectql/src/plugin.ts index 424ce9bac86..3022fe8d923 100644 --- a/packages/objectql/src/plugin.ts +++ b/packages/objectql/src/plugin.ts @@ -14,7 +14,7 @@ import { assembleMetadataProtocol, isServedOverrideRowOf } from '@objectstack/me import { installedManifestsOf, isTenantAuthored, readLegacyOrganizationRows } from '@objectstack/metadata-core'; import type { MetadataAuthoringChannel } from '@objectstack/metadata-protocol'; import { Plugin, PluginContext } from '@objectstack/core'; -import { resolveArtifactPackageEntries, artifactPackageId, readDeploymentOrgScopingEntitlement } from '@objectstack/core'; +import { resolveArtifactPackageEntries, artifactPackageId, declaredDependencyIds, readDeploymentOrgScopingEntitlement } from '@objectstack/core'; // [ADR-0130 D4] The residual rule's decision half — which top-level items of a // multi-package stack no body declares, and the id they take. See // `unclaimedTopLevelObjects` below. @@ -1024,6 +1024,13 @@ export class ObjectQLPlugin implements Plugin { // own; the door's word, `code` when it states none, is its origin. const residualOwnerId = residual?.ownerId ?? residualItems?.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 + // carries it, so the one closure walk reads it here, and a residual + // reaches its declared dependencies through every reader of the walk. + if (residualOwnerId !== undefined) { + ql.registry.recordResidualOwnerDependencies(residualOwnerId, declaredDependencyIds((artifact as { manifest?: unknown })?.manifest ?? artifact)); + } // [#24472] The boot reported every same-name pair it found // (`kernel:ready`, below); an artifact arriving later is judged once it // has registered, for the pairs naming one of its packages on either diff --git a/packages/objectql/src/registry.ts b/packages/objectql/src/registry.ts index 9bfea78cd38..4550e9ffc50 100644 --- a/packages/objectql/src/registry.ts +++ b/packages/objectql/src/registry.ts @@ -9234,6 +9234,34 @@ export class SchemaRegistry { return this.metadata.get('package')?.get(id) as InstalledPackage | undefined; } + /** + * [ADR-0130 D4, epic #31527 R2] The dependencies each residual owner + * declared — the id a multi-package stack's top-level items are owned by, + * which has no package record. Kept beside the package records, never as + * one: `getPackage` / `getAllPackages` do not see it. + */ + private readonly residualOwnerDependencies = new Map(); + + /** + * Record the dependencies residual owner `ownerId` declares on its stack's + * manifest, as the artifact door registers its residual. The latest record + * wins (a reinstall of the stack restates them). + */ + recordResidualOwnerDependencies(ownerId: string, dependencies: readonly string[]): void { + this.residualOwnerDependencies.set(ownerId, Object.freeze([...dependencies])); + } + + /** + * The dependencies residual owner `id` declared, or `undefined` for an id + * that is no recorded residual owner. The one closure walk + * (`packageDependencyClosure` in `@objectstack/metadata-core`) reads it for + * an id {@link getPackage} cannot produce, so a residual reaches what it + * declares through every reader of that walk. + */ + residualOwnerDependenciesOf(id: string): readonly string[] | undefined { + return this.residualOwnerDependencies.get(id); + } + getAllPackages(): InstalledPackage[] { return this.listItems('package'); } @@ -9777,6 +9805,7 @@ export class SchemaRegistry { this.metadata.clear(); this.appNavContributions.clear(); this.picklistExtensionContributions.clear(); + this.residualOwnerDependencies.clear(); this._objectRevision += 1; this.log('[Registry] Reset complete'); } From bc895c41e0a441dfd0915be3cc3c0f2434810f0c Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 02:01:15 +0000 Subject: [PATCH 11/11] fix(core): a caller with no package counts the platform's item as one more holder After the environment's own item, the platform's item stands beside the package holders: the only one answers, and beside any package holder the name refuses ambiguous-in-environment, naming each, rather than the platform silently answering. Claude-Session: https://claude.ai/code/session_01ADHkmQ5eMDSpkq6rYGLbBU Co-authored-by: Claude --- .../src/package-scoped-resolution.test.ts | 10 ++++++++-- .../core/src/package-scoped-resolution.ts | 20 ++++++++++++------- .../src/package-scoped-resolver.test.ts | 7 +++++-- 3 files changed, 26 insertions(+), 11 deletions(-) diff --git a/packages/core/src/package-scoped-resolution.test.ts b/packages/core/src/package-scoped-resolution.test.ts index 0714f1b0aae..3e3fba561be 100644 --- a/packages/core/src/package-scoped-resolution.test.ts +++ b/packages/core/src/package-scoped-resolution.test.ts @@ -177,8 +177,14 @@ describe('the platform\'s item — in every caller\'s reach, like `sys` (epic se expect(r.status === 'refused' && r.message).toContain('the platform'); }); - it('a caller with no package: the environment\'s own item, then the platform\'s, then the unique package holder', () => { - expect(ask([[A, 'a']], 'host', [])).toMatchObject({ status: 'resolved', item: 'host', via: 'platform' }); + it('a caller with no package: the environment\'s own item first, then the platform counted as one more holder', () => { + expect(ask([], 'host', [])).toEqual({ status: 'resolved', item: 'host', holder: { kind: 'platform' }, via: 'platform' }); + const both = ask([[A, 'a']], 'host', []); + expect(both).toMatchObject({ + status: 'refused', reason: 'ambiguous-in-environment', callerPackageId: null, + candidates: [{ kind: 'package', packageId: A }, { kind: 'platform' }], + }); + expect(both.status === 'refused' && both.message).toContain('the platform'); const env = { ...withPlatform([[A, 'a']], 'host'), environmentItem: () => 'env' }; expect(resolvePackageScopedHolders({ type: ENGINE_FUNCTION_TYPE, name: 'score' }, env, closure([]))).toMatchObject({ item: 'env', via: 'environment' }); expect(ask([[A, 'a']], undefined, [])).toMatchObject({ item: 'a', via: 'unique-holder' }); diff --git a/packages/core/src/package-scoped-resolution.ts b/packages/core/src/package-scoped-resolution.ts index 42a707ba7cf..3360af10197 100644 --- a/packages/core/src/package-scoped-resolution.ts +++ b/packages/core/src/package-scoped-resolution.ts @@ -68,8 +68,9 @@ * - **The platform's item** ({@link PackageScopedHolderSource.platformItem}: * an engine function a plugin or the host registers under no package) is * in every caller's reach, like `sys` (D2): step 2 counts it beside the - * closure's holders, and a caller with no package reaches it after the - * environment's own item (epic seat ruling on #31733, 6729484996). + * closure's holders, and a caller with no package counts it beside every + * package holder once no environment item answers (epic seat rulings on + * #31733, 6729484996 and 6730444942). */ // --------------------------------------------------------------------------- @@ -379,9 +380,9 @@ export interface PackageScopedHolderSource { * under no package (an owner-less engine function) — or `undefined`. * Omitted, there is none. Like a `sys` package (ADR-0150 D2) it is in every * caller's reach: a package caller that holds no item itself counts it - * beside its closure's holders (one answers, two or more refuse naming - * each), and a caller with no package reaches it after the environment's - * own item and before the package holders. + * beside its closure's holders, and a caller with no package counts it + * beside every package holder once no environment item answers. Either + * way the only candidate answers, and two or more refuse naming each. */ platformItem?(): T | undefined; } @@ -460,7 +461,7 @@ export function packageScopedRefusalMessage(refusal: Omit( if (environmentItem !== undefined) { return { status: 'resolved', item: environmentItem, holder: { kind: 'environment' }, via: 'environment' }; } + // The platform's item is one more holder beside the packages: the only one + // answers, and beside any package holder the name refuses, naming each. const platformItem = source.platformItem?.(); - if (platformItem !== undefined) return { status: 'resolved', item: platformItem, holder: { kind: 'platform' }, via: 'platform' }; + if (platformItem !== undefined) { + if (source.packageHolders.length === 0) return { status: 'resolved', item: platformItem, holder: { kind: 'platform' }, via: 'platform' }; + return refuse(query, callerPackageId, 'ambiguous-in-environment', [...source.packageHolders.map(packageHolder), { kind: 'platform' }]); + } const pick = pickUnique(query.type, source.packageHolders); if (pick.kind === 'one') return packageItem(source, pick.packageId, pick.baseline ? 'baseline' : 'unique-holder'); if (pick.kind === 'several') return refuse(query, callerPackageId, 'ambiguous-in-environment', pick.packageIds.map(packageHolder)); diff --git a/packages/objectql/src/package-scoped-resolver.test.ts b/packages/objectql/src/package-scoped-resolver.test.ts index daabb4466de..c7c992e78ea 100644 --- a/packages/objectql/src/package-scoped-resolver.test.ts +++ b/packages/objectql/src/package-scoped-resolver.test.ts @@ -689,8 +689,11 @@ describe('R2 — engine functions resolve in their referrer\'s package (ADR-0150 status: 'refused', reason: 'ambiguous-in-closure', candidates: [{ kind: 'package', packageId: A }, { kind: 'platform' }], }); - // A caller with no package keeps the environment-wide order: the platform's first. - expect(tagOf(resolveFn('score'))).toBe('host'); + // A caller with no package counts it as one more holder: beside a package's, it refuses (6730444942). + expect(resolveFn('score')).toMatchObject({ + status: 'refused', reason: 'ambiguous-in-environment', callerPackageId: null, + candidates: [{ kind: 'package', packageId: A }, { kind: 'platform' }], + }); }); });