diff --git a/.changeset/31716-package-scoped-rule-lean.md b/.changeset/31716-package-scoped-rule-lean.md new file mode 100644 index 00000000000..871d034c0a7 --- /dev/null +++ b/.changeset/31716-package-scoped-rule-lean.md @@ -0,0 +1,22 @@ +--- +'@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. 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/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..3e3fba561be --- /dev/null +++ b/packages/core/src/package-scoped-resolution.test.ts @@ -0,0 +1,206 @@ +// 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, + RUNTIME_COMPATIBILITY_PACKAGE_ID, + 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); + }); +}); + +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 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' }); + }); +}); + +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 new file mode 100644 index 00000000000..8d5cf5e1ea6 --- /dev/null +++ b/packages/core/src/package-scoped-resolution.ts @@ -0,0 +1,590 @@ +// 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 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 counts it beside every + * package holder once no environment item answers (epic seat rulings on + * #31733, 6729484996 and 6730444942). + */ + +// --------------------------------------------------------------------------- +// 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' | 'tool'; + +/** + * 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', + // joined after the AI family, in its own change (#31414) + 'tool', +]); + +/** 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(), + tool: 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 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. +// --------------------------------------------------------------------------- + +/** + * Who holds a name under package addressing: a package (the vocabulary's own + * {@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: 'platform' }; + +/** How a refusal names a holder. */ +export function describePackageScopedHolder(holder: PackageScopedHolder): string { + 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). */ +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' + /** 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 = + /** 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`, `''`, the + * `sys_metadata` sentinel or {@link RUNTIME_COMPATIBILITY_PACKAGE_ID} 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; + /** + * 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, 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; +} + +/** + * 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('; '); + const platform = refusal.candidates.some((c) => c.kind === 'platform'); + switch (refusal.reason) { + case 'ambiguous-in-closure': + 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} ${platform ? 'holders' : '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' }; + } + // 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) { + 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)); + 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 !== RUNTIME_COMPATIBILITY_PACKAGE_ID + ? 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, the platform's + // item counted beside it (in every caller's reach, like `sys`). + const reach = closureOf(callerPackageId); + 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)); + + // 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.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 new file mode 100644 index 00000000000..50141a5bf16 --- /dev/null +++ b/packages/metadata-core/src/package-closure.ts @@ -0,0 +1,221 @@ +// 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-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, '*'])) } }; + }; +} + +/** + * [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). 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`. + * + * ⛔ 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 (!registry || typeof getPackage !== 'function') return undefined; + const closure = resolvePackageClosure(packageId, closurePackageReader(registry, getPackage)); + 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..8e00da848c1 --- /dev/null +++ b/packages/metadata-protocol/src/protocol-write-package-scope.test.ts @@ -0,0 +1,29 @@ +// 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'; +// 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'; +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 b9748e2b778..22d8e3e04a7 100644 --- a/packages/objectql/src/bare-name-one-holder.ts +++ b/packages/objectql/src/bare-name-one-holder.ts @@ -149,60 +149,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' | 'tool'; - -/** - * 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', - // joined after the AI family, in its own change - 'tool', -]); +// [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); @@ -260,44 +238,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(), - tool: 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:`). @@ -330,11 +270,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; @@ -454,13 +389,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-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-hooks-and-functions.ts b/packages/objectql/src/engine-hooks-and-functions.ts index 9ede9a1a32d..cc28836ab8f 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'; @@ -53,6 +53,7 @@ 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 { ObjectQL } from './engine.js'; /** @@ -71,6 +72,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 +247,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 +277,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 +286,35 @@ 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. 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. */ 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 07a6e2c0881..5e5bd44e56e 100644 --- a/packages/objectql/src/engine.ts +++ b/packages/objectql/src/engine.ts @@ -139,6 +139,8 @@ import { type EngineTransactionInfo, type EngineTransactionOptions, Logger, + type PackageScopedHolderSource, + RUNTIME_COMPATIBILITY_PACKAGE_ID, type RetryOptions, recordNotFoundError, } from '@objectstack/core'; @@ -646,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 + // (`resolvePackageScopedFunction` over `functionHoldersOf`). + private functionHolders = new Map>(); + // Realtime service for event publishing private realtimeService?: IRealtimeService; @@ -822,6 +832,21 @@ 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 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 + * 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`). @@ -9513,7 +9538,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`). @@ -9889,6 +9914,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/federated-injected-column-readers.test.ts b/packages/objectql/src/federated-injected-column-readers.test.ts index 2f87d551dd9..34a51415648 100644 --- a/packages/objectql/src/federated-injected-column-readers.test.ts +++ b/packages/objectql/src/federated-injected-column-readers.test.ts @@ -444,10 +444,6 @@ const READERS: Record = { why: 'names the `queue` metadata TYPE in the namespace name rule\'s type list (ADR-0150 D2); it reads no row and no column', }, '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/index.ts b/packages/objectql/src/index.ts index d58510ba5d4..2ea31946933 100644 --- a/packages/objectql/src/index.ts +++ b/packages/objectql/src/index.ts @@ -100,16 +100,24 @@ 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, packageScopedRefusalMessage, describePackageScopedHolder, isPackageScopedType, + isPackageScopedResolvableType, isPlatformRequestedBareName, + ENGINE_FUNCTION_TYPE, PACKAGE_SCOPED_TYPES, PLATFORM_REQUESTED_BARE_NAMES_BY_TYPE, KERNEL_NAMESPACE, @@ -118,6 +126,13 @@ export type { PackageScopedType, PackageScopedHolder, PackageScopedQuery, + PackageScopedHoldersQuery, + PackageScopedHolderSource, + PackageScopedResolvableType, + PackageClosureRegistry, + PackageResolutionClosureOf, + PackageScopedFunctionQuery, + PackageScopedFunctionEngine, PackageScopedRegistry, PackageScopedResolution, PackageScopedResolutionStep, 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 cb3e252d698..c7c992e78ea 100644 --- a/packages/objectql/src/package-scoped-resolver.test.ts +++ b/packages/objectql/src/package-scoped-resolver.test.ts @@ -19,6 +19,16 @@ * 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) 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'; @@ -26,12 +36,21 @@ import { SchemaRegistry } from './registry.js'; import { BARE_NAME_REGISTRY_TYPES, type BareNameRegistryType } from './bare-name-one-holder.js'; import { resolvePackageScopedName, + resolvePackageScopedFunction, + 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 * as metadataCore from '@objectstack/metadata-core'; +import * as core from '@objectstack/core'; import { packageDependencyClosure } from '@objectstack/metadata-protocol'; const A = 'com.acme.alpha'; @@ -431,3 +450,395 @@ 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 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', () => { + 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( + { 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'); + } + } + // 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 core 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({ type: 'email_template', name: 'welcome', callerPackageId: P }, source, (caller) => packageResolutionClosure(registry, caller))) + .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({ 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); + }); + + 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({ type: type as PackageScopedResolvableType, name: 'n' }, source, () => new Set())).toThrow(TypeError); + } + }); +}); + +describe('R2 — engine functions resolve in their referrer\'s package (ADR-0150 D4)', () => { + let engine: ObjectQL; + 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) => + 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 platform', () => { + 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}"`); + 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 }))); + engine.registerFunction('score', fn('host')); + 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 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' }], + }); + }); + }); + + 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]); + }); +}); + +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); + }); +}); + +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]) { + 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(`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', () => { + 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]); + }); +}); + +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); + }); +}); + +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/package-scoped-resolver.ts b/packages/objectql/src/package-scoped-resolver.ts index cc8fb7929a3..9ae4742b8ef 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. + * 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. * - * ⛔ 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. + * ## Where the rule is, and what this module adds (child R2, #31716) * - * ## The rule (ADR-0150 D3, as ruled) + * 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. * - * A caller that belongs to package P resolves a bare name to: + * 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: * - * 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). + * - {@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,39 +41,11 @@ * (`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. - * * ## 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. @@ -81,291 +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); -} - -/** - * 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: PackageScopedType; - 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. */ -export interface PackageScopedQuery { +// 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; - 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; /** For a bundled type (`email_template`): one member, as `getItem` takes it. */ readonly member?: string; } -/** 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: PackageScopedType, packageId: string): boolean { - return isBareNameOneHolderType(type) && isOverridableBaseline(type, packageId); -} - -/** Every installed package of the reserved kernel namespace. */ -function kernelPackages(registry: PackageScopedRegistry): 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: PackageScopedRegistry, 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: PackageScopedType): 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: PackageScopedQuery, - 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: PackageScopedType, - 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 the asked bundle member. */ -function packageItem( - registry: PackageScopedRegistry, - query: PackageScopedQuery, - packageId: string, - via: PackageScopedResolutionStep, -): PackageScopedResolution { - const item = registry.getPackageScopedItem(query.type, query.name, packageId, query.member); - 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, - callerPackageId: string | null, - holders: readonly string[], -): PackageScopedResolution { - const environmentItem = registry.getEnvironmentScopedItem(query.type, query.name, query.member); - 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'); - 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 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 @@ -378,32 +135,60 @@ export function resolvePackageScopedName( if (!isPackageScopedType(query.type)) { throw new TypeError( `[package-scoped-resolver] "${String(query.type)}" is not addressed by (package, name) (ADR-0150 D1); ` + - `positions are environment-scoped (D7) and objects keep their literal name (ADR-0129).`, + (query.type === ENGINE_FUNCTION_TYPE + ? '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 raw = query.callerPackageId; - const callerPackageId = typeof raw === 'string' && raw !== '' && raw !== OVERLAY_PROVENANCE_SENTINEL ? raw : null; - const holders = registry.packageScopedHoldersOf(query.type, query.name); - - if (callerPackageId === null || isPlatformRequestedBareName(query.type, query.name)) { - return resolveEnvironmentWide(registry, query, callerPackageId, holders); - } + const { type, name, member } = query; + return resolvePackageScopedHolders( + query, + { + // 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), + }, + (callerPackageId) => packageResolutionClosure(registry, callerPackageId), + ); +} - // Step 1 — the caller package's own item. - if (holders.includes(callerPackageId)) return packageItem(registry, query, callerPackageId, 'own'); +/** 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; +} - // 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 === 'several') return refuse(query, callerPackageId, 'ambiguous-in-closure', pick.packageIds.map(packageHolder)); +/** The engine slice the function adapter reads — every member of it, and no other. */ +export type PackageScopedFunctionEngine = Pick; - // 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 (candidates.length === 0) return { status: 'not-found' }; - return refuse(query, callerPackageId, 'outside-closure', candidates); +/** + * 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 platform's + * item — code a plugin or the host registers, never an item authored in the + * environment — so it is in every caller's reach, like `sys` (ADR-0150 D2): + * a package caller holding none itself counts it beside its closure's + * holders. 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), + ); } diff --git a/packages/objectql/src/plugin.ts b/packages/objectql/src/plugin.ts index 09cb8954fdc..79149e8c687 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 b9e7a7a01c5..8d88a0518cc 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 @@ -8368,8 +8371,23 @@ 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 `[]`. - */ - packageScopedHoldersOf(type: string, name: string): string[] { + * + * [#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). + * + * @param callerPackageId - The package a bare read is made from. Its own + * holding stays in the set even when it is an addition, so its step 1 + * (its own item, ADR-0150 D3) answers as before: the addition only stops + * counting toward OTHER callers' ambiguity (epic seat review 6729484996). + */ + packageScopedHoldersOf(type: string, name: string, callerPackageId?: string | null): string[] { const collection = this.metadata.get(type); if (!collection) return []; const composite = this.compositeHoldersOf(collection, name); @@ -8379,7 +8397,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) => id === callerPackageId || !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; } /** @@ -9280,6 +9333,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'); } @@ -9823,6 +9904,7 @@ export class SchemaRegistry { this.metadata.clear(); this.appNavContributions.clear(); this.picklistExtensionContributions.clear(); + this.residualOwnerDependencies.clear(); this._objectRevision += 1; this.log('[Registry] Reset complete'); } 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 });