diff --git a/.changeset/32714-registry-action-door-loose-ends.md b/.changeset/32714-registry-action-door-loose-ends.md new file mode 100644 index 00000000000..1c973f0fe65 --- /dev/null +++ b/.changeset/32714-registry-action-door-loose-ends.md @@ -0,0 +1,15 @@ +--- +'@objectstack/metadata': patch +--- + +fix(metadata): the in-memory store declares a view where it is made, and a refusal of a slot it does not hold names each holder once + +Clause-②: no +Metadata-protocol: none + +Loose ends of the per-member registry keys. No served answer changes. + +- **Views are declared, not inferred.** A read the registry cannot answer judges a view assembled from the registry's and the loaders' items. A bundled type's slot (`email_template`, one member per `locale`) answers that view's first member, the member its sources wrote last. The store used to infer "this is a view" from "no write was ever recorded on it". It now marks the view where it builds it, so a store that is not a view answers by its write order, as every other read of "written last" does. Every view the manager builds is marked, so each read answers as before. +- **One holder, one candidate.** The refusal of a write addressed to a package that holds no slot of the name (`not-held-by-qualifier`, `409`) lists each holder once. One package's two locales, or one package's action bound to two objects, is one candidate, as the other refusals already count it. Its one caller, `DatabaseLoader`'s rollback, keys one row per slot, so its refusals read the same. + +Pinned with them, unchanged: a second locale of a bundled item is announced `added` and a rewrite of a held locale `changed`, because an email template's identity is `(name, locale)`. A package's first item of a name whose bundle the environment holds takes over that member only, and leaves the environment's other locales the environment's, in the registry, the `MemoryLoader` and `DatabaseLoader` alike. On a host whose `protocol` serves no merged action listing, two packages' same-named action bound to one object is refused: the execution door answers `409` naming both packages and runs nothing, and the activation door writes no ledger row. MCP `list_actions` lists one row per package, and the bare `run_action` is refused naming both. diff --git a/packages/metadata/src/metadata-manager-email-template-slot.test.ts b/packages/metadata/src/metadata-manager-email-template-slot.test.ts index bdf5702f127..257e9f6a848 100644 --- a/packages/metadata/src/metadata-manager-email-template-slot.test.ts +++ b/packages/metadata/src/metadata-manager-email-template-slot.test.ts @@ -277,3 +277,120 @@ describe('[#32517] a bundled type keeps one item per (package, name, member) in } }); }); + +/** + * [#32714 item 1] Which watcher event a write of a bundled type's member + * announces. Decided by the governing text, not picked: an email template's + * identity is `(name, locale)` — `EmailTemplateDefinitionSchema.locale` is "the + * second half of the bundle key" and "multiple rows sharing one `name` form an + * i18n bundle" (`packages/spec/src/system/email-template.zod.ts`; the identity + * table `ITEM_KEY_DISCRIMINATORS` in `@objectstack/metadata-core` says the + * same) — and `register()` announces `added` for a first registration and + * `changed` for an overwrite (its own contract, matching the repository + * watch path's `create` / `update` split). A second locale is a new row of the + * bundle and overwrites nothing, so it is `added`; a rewrite of a locale the + * slot already holds is `changed`. `watchService` maps them to `registered` / + * `updated`. No realtime event is published for either: `email_template` has + * no declared `MetadataEventType`. + */ +describe('[#32714 item 1] a second locale of a bundled item is announced `added`, a rewrite of a held locale `changed`', () => { + const member = (packageId: string | undefined, locale: string, subject = `${packageId ?? 'env'}:${locale}`) => ({ + name: NAME, + locale, + subject, + bodyHtml: '

hi

', + ...(packageId === undefined ? {} : { _packageId: packageId, _provenance: 'package' }), + }); + + function watched(type = 'email_template') { + const manager = new MetadataManager({ formats: ['json'], loaders: [] }); + const raw: string[] = []; + const service: string[] = []; + const published: unknown[] = []; + manager.subscribe(type, (event) => { raw.push(event.type); }); + manager.watchService(type, (event) => { service.push(event.type); }); + manager.setRealtimeService({ + publish: async (event: unknown) => { published.push(event); }, + subscribe: async () => 'sub-1', + unsubscribe: async () => undefined, + } as never); + return { manager, raw, service, published }; + } + + it('one package: en-US added, fr-FR added (a new member of the bundle), fr-FR again and en-US again changed', async () => { + const { manager, raw, service, published } = watched(); + for (const item of [member(ALPHA, 'en-US'), member(ALPHA, 'fr-FR'), member(ALPHA, 'fr-FR', 'fr again'), member(ALPHA, 'en-US', 'en again')]) { + await manager.register('email_template', NAME, item); + } + expect(raw).toEqual(['added', 'added', 'changed', 'changed']); + expect(service).toEqual(['registered', 'registered', 'updated', 'updated']); + expect(published, 'no declared realtime event for the type').toEqual([]); + }); + + it('the environment\'s bundle: its second locale is added too, and a package taking over its canonical member is changed (it replaces that row)', async () => { + const { manager, raw } = watched(); + for (const item of [member(undefined, 'en-US'), member(undefined, 'fr-FR'), member(ALPHA, 'en-US')]) { + await manager.register('email_template', NAME, item); + } + expect(raw).toEqual(['added', 'added', 'changed']); + }); + + it('CONTROL — an unbundled by-package type keeps one item per slot: its second write is changed, whatever `locale` it carries', async () => { + const { manager, raw } = watched('agent'); + await manager.register('agent', NAME, { name: NAME, locale: 'en-US', _packageId: ALPHA }); + await manager.register('agent', NAME, { name: NAME, locale: 'fr-FR', _packageId: ALPHA }); + expect(raw).toEqual(['added', 'changed']); + }); +}); + +/** + * [#32714 item 2] The environment holds a bundle (`en-US`, `fr-FR`) of a name + * no package holds; then a package ships the name's canonical member. The + * package's write takes over the bare slot's SAME member only (its row, as + * `DatabaseLoader` binds the package-less row of the member it writes): the + * environment's `fr-FR` stays the environment's. Pinned as it stands — the + * registry and the door's `MemoryLoader` agree, and `DatabaseLoader` leaves + * that row package-less too — so no layer moves a member nobody wrote. + */ +describe('[#32714 item 2] a package taking over a bundled name moves only the member it writes', () => { + const member = (packageId: string | undefined, locale: string, subject = `${packageId ?? 'env'}:${locale}`) => ({ + name: NAME, + label: 'Welcome', + locale, + subject, + bodyHtml: '

hi

', + ...(packageId === undefined ? {} : { _packageId: packageId, _provenance: 'package' }), + }); + const subjects = (items: unknown[]) => (items as Array<{ subject: string }>).map((item) => item.subject).sort(); + const TAKEN_OVER = () => [member(undefined, 'en-US'), member(undefined, 'fr-FR'), member(ALPHA, 'en-US')]; + + async function shapes(): Promise> { + const registry = new MetadataManager({ formats: ['json'], loaders: [] }); + for (const item of TAKEN_OVER()) registry.registerInMemory('email_template', NAME, item); + const loader = new MemoryLoader(); + for (const item of TAKEN_OVER()) await loader.save('email_template', NAME, item); + return [['registry', registry], ['MemoryLoader', new MetadataManager({ formats: ['json'], loaders: [loader] })]]; + } + + it('list: the package\'s en-US and the environment\'s fr-FR, each once; reads answer the package\'s slot', async () => { + for (const [label, manager] of await shapes()) { + expect(subjects(await manager.list('email_template')), label).toEqual([`${ALPHA}:en-US`, 'env:fr-FR']); + expect(((await manager.get('email_template', NAME, ALPHA)) as any)?.subject, label).toBe(`${ALPHA}:en-US`); + expect(((await manager.get('email_template', NAME)) as any)?.subject, label).toBe(`${ALPHA}:en-US`); + } + }); + + it('a removal naming the package leaves the environment\'s fr-FR, which a read naming none then answers', async () => { + for (const [label, manager] of await shapes()) { + await manager.unregister('email_template', NAME, { packageId: ALPHA }); + expect(subjects(await manager.list('email_template')), label).toEqual(['env:fr-FR']); + expect(((await manager.get('email_template', NAME)) as any)?.subject, label).toBe('env:fr-FR'); + } + }); + + it('the package\'s own fr-FR then takes the environment\'s over in turn: one fr-FR, the package\'s', async () => { + const registry = new MetadataManager({ formats: ['json'], loaders: [] }); + for (const item of [...TAKEN_OVER(), member(ALPHA, 'fr-FR')]) registry.registerInMemory('email_template', NAME, item); + expect(subjects(await registry.list('email_template'))).toEqual([`${ALPHA}:en-US`, `${ALPHA}:fr-FR`]); + }); +}); diff --git a/packages/metadata/src/metadata-manager-match-endpoint.test.ts b/packages/metadata/src/metadata-manager-match-endpoint.test.ts index b2b66f90885..21fb14ce784 100644 --- a/packages/metadata/src/metadata-manager-match-endpoint.test.ts +++ b/packages/metadata/src/metadata-manager-match-endpoint.test.ts @@ -1117,7 +1117,28 @@ describe('per-package loader storage for every type stored per package (ADR-0150 expect(((await manager.list(type))[0] as any)?.subject).toBe('en again'); }); - it.each(UNBUNDLED)('%s: the loaders\' by-name reads still answer the item saved last; the plural reads answer every package\'s item, over the door\'s store [#32517] and over the stored rows (#32521; BEFORE: the database\'s one row per name, the one saved last)', async (type) => { + /** + * [#32714 item 2] The database half of the registry's take-over rule + * (`package-slotted-store.test.ts`): a package's first item of a name whose + * bundle the environment holds binds the package-less row of the member it + * writes, and leaves the other members' rows package-less, as the registry + * and the door's `MemoryLoader` leave their keys. + */ + it.each(BUNDLED)('%s: [#32714] a package\'s first member of an environment-held bundle binds that member\'s row only; the other member\'s row stays package-less', async (type) => { + const { driver, rows } = rowDriver(); + const db = new DatabaseLoader({ driver, tableName: 'sys_metadata' }); + const body = (packageId: string | undefined, locale: string) => ({ + name: nameOf(type), label: `${packageId ?? 'env'}:${locale}`, locale, + ...(packageId === undefined ? {} : { _packageId: packageId, _provenance: 'package' }), + }); + await db.save(type, nameOf(type), body(undefined, 'en-US')); + await db.save(type, nameOf(type), body(undefined, 'fr-FR')); + await db.save(type, nameOf(type), body(A, 'en-US')); + const stored = rows(type).map((row) => [row.package_id ?? null, row.bundle_member ?? null]).sort((x, y) => String(x[1]).localeCompare(String(y[1]))); + expect(stored).toEqual([[null, 'fr-FR'], [A, null]]); + }); + + it.each(UNBUNDLED)('%s: the loaders\' by-name reads still answer the item saved last; the plural reads answer every package\'s item, over the door\'s store ([#32517] under epic record 6818307202 on #32517: an unscoped plural read answers every package\'s slot) and over the stored rows (#32521; BEFORE: the database\'s one row per name, the one saved last)', async (type) => { const ctx = await boot(type); for (const peer of [ctx.peer(['database']), ctx.peer(['door'])]) { expect(((await peer.load(type, nameOf(type))) as any)?.label).toBe(label(type, B)); diff --git a/packages/metadata/src/metadata-manager.ts b/packages/metadata/src/metadata-manager.ts index 599a20ec8dd..c13c70fee24 100644 --- a/packages/metadata/src/metadata-manager.ts +++ b/packages/metadata/src/metadata-manager.ts @@ -103,6 +103,7 @@ import { slotPackageOf, slotOfKey, slotStoreOf, + newSlotView, storedItemPackageId as indexedItemPackageId, storedNameOf, storeKeysNamed, @@ -1550,7 +1551,9 @@ export class MetadataManager implements IMetadataService { loaderStore: ReadonlyMap, ): Map { const registryStore = this.registry.get(type); - const view = new Map(); + // [#32714] Declared a view where it is made (`newSlotView`), so + // `latestMemberOf` never infers it from a missing write order. + const view = newSlotView(); // [#32517] Each slot's member written last first: a slot no key of which // came from the registry answers its first member (`latestMemberOf`). if (registryStore) { diff --git a/packages/metadata/src/package-slotted-store.test.ts b/packages/metadata/src/package-slotted-store.test.ts new file mode 100644 index 00000000000..1af9c90861b --- /dev/null +++ b/packages/metadata/src/package-slotted-store.test.ts @@ -0,0 +1,179 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#32714] The package-slotted store's rules on their own (`package-slotted-store.ts`). + * + * The manager, the artifact door's `MemoryLoader` and `DatabaseLoader` all ask + * these rules; their suites pin what each layer serves. This file pins the + * rules themselves, over plain maps keyed the way those layers key them + * (`storeSlotKey`), so a rule that changes is red here first, whichever layer + * would have noticed. + */ + +import { describe, it, expect } from 'vitest'; +import { PackageScopedNameRefusedError } from '@objectstack/core'; +import { + inheritStoreWriteOrder, + lastWrittenKeyOf, + latestMemberOf, + newSlotView, + recordStoreWrite, + refuseSeveralSlots, + refuseSlotNotHeld, + slotOfKey, + storeSlotKey, + storeWriteKey, +} from './package-slotted-store.js'; + +const TYPE = 'email_template'; +const NAME = 'welcome'; +const ALPHA = 'com.alpha.app'; +const BETA = 'com.beta.app'; + +/** A member of the bundle: `packageId` undefined is the environment's own item. */ +const member = (packageId: string | undefined, locale: string, subject = `${packageId ?? 'env'}:${locale}`) => ({ + name: NAME, + locale, + subject, + ...(packageId === undefined ? {} : { _packageId: packageId, _provenance: 'package' }), +}); +type Member = ReturnType; + +const keyOf = (item: Member) => storeSlotKey(TYPE, NAME, (item as { _packageId?: string })._packageId, item); + +/** A store written the way the registry and the `MemoryLoader` write: the key the write rule picks, its write recorded. */ +function written(...items: Member[]): Map { + const store = new Map(); + for (const item of items) { + const { key, replaces } = storeWriteKey(store, TYPE, NAME, item); + for (const replaced of replaces) store.delete(replaced); + store.set(key, item); + recordStoreWrite(store, key); + } + return store; +} + +const subjects = (store: ReadonlyMap) => [...store.values()].map((item) => item.subject).sort(); + +describe('[#32714] a view is declared where it is made: `latestMemberOf` never infers one from a missing write order', () => { + const EN = member(ALPHA, 'en-US'); + const FR = member(ALPHA, 'fr-FR'); + const SLOT = slotOfKey(keyOf(EN)); + + it('the two members share one slot (the premise of every case below)', () => { + expect(slotOfKey(keyOf(FR))).toBe(SLOT); + expect(keyOf(FR)).not.toBe(keyOf(EN)); + }); + + it('a VIEW with no write order answers its first member of the slot: its sources hand the member written last first', () => { + const view = newSlotView(); + view.set(keyOf(FR), FR); + view.set(keyOf(EN), EN); + expect(latestMemberOf(view, SLOT)).toBe(keyOf(FR)); + }); + + it('a store that is NOT a view, with no write recorded, answers by its write order as `lastWrittenKeyOf` does: the last member in store order (BASE: read as a view, its first member)', () => { + const store = new Map([[keyOf(FR), FR], [keyOf(EN), EN]]); + expect(latestMemberOf(store, SLOT)).toBe(keyOf(EN)); + expect(latestMemberOf(store, SLOT)).toBe(lastWrittenKeyOf(store, [keyOf(FR), keyOf(EN)])); + }); + + it('a written store answers the member written last, whatever the store\'s order (the registry, the door\'s `MemoryLoader`)', () => { + const store = written(EN, FR, member(ALPHA, 'en-US', 'en again')); + expect([...store.keys()]).toEqual([keyOf(EN), keyOf(FR)]); + expect(store.get(latestMemberOf(store, SLOT))!.subject).toBe('en again'); + expect(store.get(latestMemberOf(written(EN, FR), SLOT))!.subject).toBe(`${ALPHA}:fr-FR`); + }); + + it('a view that inherited a store\'s write order answers by it for a slot that store holds, and its first member for a slot only the view holds', () => { + const registry = written(EN, FR, member(ALPHA, 'en-US', 'en again')); + const loaderOnly = [member(BETA, 'fr-FR'), member(BETA, 'en-US')]; + const view = newSlotView(); + for (const [key, item] of registry) view.set(key, item); + for (const item of loaderOnly) view.set(keyOf(item), item); + inheritStoreWriteOrder(view, registry); + expect(view.get(latestMemberOf(view, SLOT))!.subject).toBe('en again'); + expect(latestMemberOf(view, slotOfKey(keyOf(loaderOnly[0]!)))).toBe(keyOf(loaderOnly[0]!)); + }); +}); + +describe('[#32714] `refuseSlotNotHeld` names each holder once, as `packageSlotsOf` and `refuseSeveralSlots` count them', () => { + const refusalOf = (store: ReadonlyMap, packageId: string | null): PackageScopedNameRefusedError => { + try { + refuseSlotNotHeld(store, TYPE, NAME, packageId); + } catch (err) { + return err as PackageScopedNameRefusedError; + } + throw new Error('refuseSlotNotHeld returned'); + }; + + it('one package\'s two locales are ONE candidate, and the environment\'s two locales one more (BASE: one candidate per member)', () => { + const store = written(member(undefined, 'en-US'), member(undefined, 'fr-FR')); + for (const item of [member(ALPHA, 'en-US'), member(ALPHA, 'fr-FR')]) store.set(keyOf(item), item); + const err = refusalOf(store, BETA); + expect(err).toBeInstanceOf(PackageScopedNameRefusedError); + expect([err.code, err.status, err.refusal.reason]).toEqual(['RESOURCE_CONFLICT', 409, 'not-held-by-qualifier']); + expect(err.refusal.callerPackageId).toBe(BETA); + expect(err.refusal.candidates).toEqual([{ kind: 'package', packageId: ALPHA }, { kind: 'environment' }]); + }); + + it('one package\'s action bound to two objects is ONE candidate', () => { + const bound = (objectName: string) => ({ name: 'ping', objectName, _packageId: ALPHA }); + const store = new Map(); + for (const item of [bound('o1'), bound('o2')]) store.set(storeSlotKey('action', 'ping', ALPHA, item), item); + expect(store.size).toBe(2); + let err: PackageScopedNameRefusedError | undefined; + try { + refuseSlotNotHeld(store, 'action', 'ping', null); + } catch (e) { + err = e as PackageScopedNameRefusedError; + } + expect(err?.refusal.candidates).toEqual([{ kind: 'package', packageId: ALPHA }]); + }); + + it('CONTROL — `refuseSeveralSlots` counts slots, never members: one package\'s two locales are not refused, a package beside the environment is', () => { + expect(() => refuseSeveralSlots(written(member(ALPHA, 'en-US'), member(ALPHA, 'fr-FR')), TYPE, NAME)).not.toThrow(); + const both = new Map(); + for (const item of [member(undefined, 'en-US'), member(ALPHA, 'en-US'), member(ALPHA, 'fr-FR')]) both.set(keyOf(item), item); + let err: PackageScopedNameRefusedError | undefined; + try { + refuseSeveralSlots(both, TYPE, NAME); + } catch (e) { + err = e as PackageScopedNameRefusedError; + } + expect(err?.refusal.candidates).toEqual([{ kind: 'environment' }, { kind: 'package', packageId: ALPHA }]); + }); +}); + +/** + * [#32714 item 2] A package's first item of a bundled name the environment + * already holds takes over the bare slot's SAME member only. The bare slot's + * other members stay where they are, the environment's: no member moves + * without being written. `DatabaseLoader` leaves those members' package-less + * rows the same way (pinned beside its storage pins, + * `metadata-manager-match-endpoint.test.ts`). + */ +describe('[#32714 item 2] a package taking over a bundled name moves the member it writes, and no other', () => { + it('the package\'s canonical member replaces the bare canonical member; the bare `fr-FR` stays bare', () => { + const store = written(member(undefined, 'en-US'), member(undefined, 'fr-FR')); + const EN = member(ALPHA, 'en-US'); + const write = storeWriteKey(store, TYPE, NAME, EN); + expect(write).toEqual({ key: keyOf(EN), replaces: [keyOf(member(undefined, 'en-US'))] }); + const after = written(member(undefined, 'en-US'), member(undefined, 'fr-FR'), EN); + expect(subjects(after)).toEqual([`${ALPHA}:en-US`, 'env:fr-FR']); + expect([...after.keys()]).toEqual([keyOf(member(undefined, 'fr-FR')), keyOf(EN)]); + }); + + it('the package\'s write of that member later takes the bare member over in turn: nothing is left beside it', () => { + const FR = member(ALPHA, 'fr-FR'); + const before = written(member(undefined, 'en-US'), member(undefined, 'fr-FR'), member(ALPHA, 'en-US')); + expect(storeWriteKey(before, TYPE, NAME, FR)).toEqual({ key: keyOf(FR), replaces: [keyOf(member(undefined, 'fr-FR'))] }); + expect(subjects(written(member(undefined, 'en-US'), member(undefined, 'fr-FR'), member(ALPHA, 'en-US'), FR))) + .toEqual([`${ALPHA}:en-US`, `${ALPHA}:fr-FR`]); + }); + + it('CONTROL — beside a second package nothing is taken over: the bare members stay, each package fills its own slot', () => { + const store = written(member(undefined, 'en-US'), member(BETA, 'en-US')); + expect(storeWriteKey(store, TYPE, NAME, member(ALPHA, 'en-US')).replaces).toEqual([]); + }); +}); diff --git a/packages/metadata/src/package-slotted-store.ts b/packages/metadata/src/package-slotted-store.ts index cd51c0d4993..2b68ba5f28c 100644 --- a/packages/metadata/src/package-slotted-store.ts +++ b/packages/metadata/src/package-slotted-store.ts @@ -239,8 +239,27 @@ export function keyIdentityOf(key: string): string { */ const writeOrder = new WeakMap, Map>(); let writeSequence = 0; -/** [#32560, #32517] The views whose write order {@link inheritStoreWriteOrder} took from another store. */ -const inheritedViews = new WeakSet>(); +/** + * [#32517, #32714] The stores that are VIEWS: assembled from what other stores + * hold ({@link newSlotView}), never written through {@link recordStoreWrite}. + * {@link latestMemberOf} reads a view's first member of a slot where the view + * has no write order for it; every other store answers by its write order. + */ +const slotViews = new WeakSet>(); + +/** + * [#32714] A new, empty view: a store a reader assembles from other stores' + * items (the manager's view of a name over the registry and the loaders, + * {@link slotStoreOf}'s map of the loaders' stored items). It is declared a + * view here, where it is made, so {@link latestMemberOf} never has to infer it + * from a missing write order. Its sources hand each slot's member written last + * first, so the view's first member of a slot is that member. + */ +export function newSlotView(): Map { + const view = new Map(); + slotViews.add(view); + return view; +} /** Record that `key` of `store` was just written ({@link readStoreEntry}'s "written last"). */ export function recordStoreWrite(store: ReadonlyMap, key: string): void { @@ -272,11 +291,12 @@ function writtenLast(store: ReadonlyMap, keys: readonly string[ * does not hold counts as written before every key it does. */ export function inheritStoreWriteOrder(view: ReadonlyMap, from: ReadonlyMap | undefined): void { + // [#32517] A store that takes another's order is a view: a slot none of + // whose members came from `from` still answers its first member in it + // ({@link latestMemberOf}). + slotViews.add(view); const order = from ? writeOrder.get(from) : undefined; if (!order) return; - // [#32517] A slot none of whose members came from `from` still answers its - // first member in the view ({@link latestMemberOf}). - inheritedViews.add(view); const inherited = new Map(); for (const key of view.keys()) { const at = order.get(key); @@ -339,7 +359,7 @@ export function slotStoreOf( name: string, items: Iterable<{ readonly packageId?: string; readonly data: T }>, ): Map { - const store = new Map(); + const store = newSlotView(); for (const { packageId, data } of items) { const key = storeSlotKey(type, name, packageId, data); if (!store.has(key)) store.set(key, data); @@ -540,22 +560,25 @@ function holdsSlot(store: ReadonlyMap, slot: string): boolean { * ({@link writtenLast}) — the one item the slot held before a bundle's members * had keys of their own; the slot itself when none is held. * - * A store no write was recorded on is a VIEW assembled from what others hold - * (the manager's {@link slotStoreOf}-built view of a name the registry cannot - * answer): its first member of the slot answers, the item that view kept for - * the slot when one key held it. Its sources hand a slot's member written - * last first (the registry by its write order, the `MemoryLoader`'s - * `loadSlots`), so the view answers what they answer. [#32560] A view that - * inherited the registry's write order ({@link inheritStoreWriteOrder}) - * answers by it for a slot the registry holds, and its first member for a - * slot only a loader holds. + * A VIEW ({@link newSlotView}: a store assembled from what others hold, the + * manager's view of a name the registry cannot answer) answers its first + * member of the slot, the item that view kept for the slot when one key held + * it. Its sources hand a slot's member written last first (the registry by + * its write order, the `MemoryLoader`'s `loadSlots`), so the view answers what + * they answer. [#32560] A view that inherited the registry's write order + * ({@link inheritStoreWriteOrder}) answers by it for a slot the registry + * holds, and its first member for a slot only a loader holds. + * + * [#32714] A view is declared where it is made, never inferred from a store + * no write was recorded on: a store that is not a view answers by its write + * order, as {@link lastWrittenKeyOf} does (the last member in the store's + * order when none was recorded). */ export function latestMemberOf(store: ReadonlyMap, slot: string): string { const members = [...store.keys()].filter((key) => slotOfKey(key) === slot); if (members.length === 0) return slot; const order = writeOrder.get(store); - if (!order) return members[0]!; - if (inheritedViews.has(store) && !members.some((key) => order.has(key))) return members[0]!; + if (slotViews.has(store) && !members.some((key) => order?.has(key) === true)) return members[0]!; return writtenLast(store, members); } @@ -862,14 +885,17 @@ export function refuseSeveralSlots(store: ReadonlyMap | undefin * package a rollback names, or the package whose version it restores; `null` * for the environment's package-less slot) when `store` holds no slot of * `name` for it: no row is that holder's to write, and ⛔ never another - * holder's. The refusal names every slot the store holds, packages first, then - * the environment (the exact-qualifier door's order). The caller answers a + * holder's. The refusal names every holder of the name once, packages first, + * then the environment (the exact-qualifier door's order). The caller answers a * name with no slot at all as its own miss and never asks this. * * @throws {PackageScopedNameRefusedError} always (`not-held-by-qualifier`). */ export function refuseSlotNotHeld(store: ReadonlyMap | undefined, type: string, name: string, packageId: string | null): never { - const holders = storeKeysNamed(store, type, name).map(slotPackageOf); + // [#32714] Each holder once, as `packageSlotsOf` and `refuseSeveralSlots` + // count them: one package's two members of a bundle (or two bindings of an + // action) are one holder, never two candidates. + const holders = [...new Set(storeKeysNamed(store, type, name).map(slotPackageOf))]; const base: Omit = { status: 'refused', reason: 'not-held-by-qualifier', diff --git a/packages/runtime/src/domains/action-activation-unpackaged.test.ts b/packages/runtime/src/domains/action-activation-unpackaged.test.ts index f046c2d2b0c..2fc5791412f 100644 --- a/packages/runtime/src/domains/action-activation-unpackaged.test.ts +++ b/packages/runtime/src/domains/action-activation-unpackaged.test.ts @@ -121,7 +121,12 @@ interface Harness { * engine carries the REAL action activation projection over the REAL durable * store, and that store writes into {@link makeLedgerTable}. */ -function boot(opts: { writeError?: Error; metadata?: unknown } = {}): Harness { +function boot(opts: { + writeError?: Error; + metadata?: unknown; + /** [#32714] The engine's handler registry (`listRegisteredActions`), for the MCP bridge's listing probe. */ + handlers?: ReadonlyArray<{ objectName: string; actionName: string }>; +} = {}): Harness { const { rows, engine: ledger } = makeLedgerTable(opts.writeError); let executed = 0; const objectDef = { @@ -143,6 +148,7 @@ function boot(opts: { writeError?: Error; metadata?: unknown } = {}): Harness { isActionEnabled: (name: string) => projection.isEnabled(name), describeDisabledAction: (name: string) => projection.describeDisabled(name), setActionActive: (row: any, options?: any) => projection.setActive(row, options), + ...(opts.handlers ? { listRegisteredActions: () => [...opts.handlers!] } : {}), }; projection.attach(new ObjectStoreActionActivationStore(ql)); @@ -386,3 +392,111 @@ describe('[#32517] two packages\' same-named actions: the metadata-service-only expect(h.rows.map((r) => [r.name, r.package_id, r.active])).toEqual([['shared_ping', 'com.acme.alpha', false]]); }); }); + +/** + * [#32714 item 4] The rest of the metadata-service-only host's action doors, + * over the same real `MetadataManager` and `MemoryLoader`: two packages' + * same-named action bound to ONE object (the activation and execution doors), + * and the MCP doors PR #32687's changeset declared and left unpinned — + * `list_actions` (one row per package) and the bare `run_action` (the D3 + * refusal naming both packages, nothing run). Each case beside its one-holder + * CONTROL, which answers as before. + */ +describe('[#32714] the metadata-service-only host: two packages on one object, and the MCP doors', () => { + const OTHER = 'crm_contact'; + const ALPHA = 'com.acme.alpha'; + const BETA = 'com.acme.beta'; + const shipped = (packageId: string, objectName: string | undefined) => ({ + name: 'shared_ping', label: `ping ${packageId}`, type: 'script', target: 'shared_ping', + ai: { exposed: true, description: 'Ping.' }, + ...(objectName === undefined ? {} : { objectName }), + _packageId: packageId, _provenance: 'package', + }); + + async function host(holders: ReadonlyArray): Promise { + const door = new MemoryLoader(); + for (const [packageId, objectName] of holders) await door.save('action', 'shared_ping', shipped(packageId, objectName)); + const manager = new MetadataManager({ formats: ['json'], loaders: [door] }); + const objects = [ + { name: OBJECT, _packageId: PACKAGE, _provenance: 'package', actions: [] }, + { name: OTHER, _packageId: PACKAGE, _provenance: 'package', actions: [] }, + ]; + const metadata: any = { + load: (type: string, name: string) => manager.load(type, name), + loadDiagnosed: (type: string, name: string) => manager.loadDiagnosed(type, name), + loadMany: (type: string) => manager.loadMany(type), + listObjects: async () => objects, + getObject: async (name: string) => objects.find((o) => o.name === name), + }; + const handlers = [...new Set(holders.map(([, objectName]) => objectName ?? 'global'))] + .map((objectName) => ({ objectName, actionName: 'shared_ping' })); + return boot({ metadata, handlers }); + } + const bridgeOf = (h: Harness): any => (h.dispatcher as any).buildMcpBridge(ADMIN()); + const listedPings = async (h: Harness) => + ((await bridgeOf(h).listActions()) as any[]).filter((row) => row.name === 'shared_ping'); + + /** + * Refused, and no row: the flip of a name two packages hold on this object + * switches neither. It answers 404 "has no declaration", the answer the + * object-less pair gets above: the declaration read refuses the name + * (the execution door's 409 below) and the activation door drops that + * refusal for its "no declaration" branch. That door's 404 → 409 is + * #32689's, for every key; this pin moves with it. + */ + it('two packages bound to ONE object — the activation door: refused, 404 RESOURCE_NOT_FOUND, and no row', async () => { + const h = await host([[ALPHA, OTHER], [BETA, OTHER]]); + for (const enabled of [false, true]) { + const res = await flip(h, OTHER, 'shared_ping', enabled); + expect(statusOf(res), bodyOf(res)).toBe(404); + expect(codeOf(res)).toBe('RESOURCE_NOT_FOUND'); + } + expect(h.rows).toEqual([]); + }); + + it('two packages bound to ONE object — the execution door: 409 RESOURCE_CONFLICT naming both packages, nothing runs', async () => { + const h = await host([[ALPHA, OTHER], [BETA, OTHER]]); + const res = await h.dispatcher.handleActions(`/${OTHER}/shared_ping`, 'POST', {}, ADMIN()); + expect(statusOf(res), bodyOf(res)).toBe(409); + expect(codeOf(res)).toBe('RESOURCE_CONFLICT'); + expect(bodyOf(res)).toContain(ALPHA); + expect(bodyOf(res)).toContain(BETA); + expect(h.executed()).toBe(0); + }); + + it('CONTROL — one package on that object: the execution door runs it, the flip writes its row', async () => { + const h = await host([[ALPHA, OTHER]]); + const ran = await h.dispatcher.handleActions(`/${OTHER}/shared_ping`, 'POST', {}, ADMIN()); + expect(statusOf(ran), bodyOf(ran)).toBe(200); + expect(h.executed()).toBe(1); + const res = await flip(h, OTHER, 'shared_ping', false); + expect(statusOf(res), bodyOf(res)).toBe(200); + expect(h.rows.map((r) => [r.name, r.package_id, r.active])).toEqual([['shared_ping', ALPHA, false]]); + }); + + it('MCP `list_actions`, both object-less: one row per package (as the changeset declares)', async () => { + const rows = await listedPings(await host([[ALPHA, undefined], [BETA, undefined]])); + expect(rows.map((row) => row.label).sort()).toEqual([`ping ${ALPHA}`, `ping ${BETA}`]); + }); + + it('CONTROL — MCP `list_actions`, one package: one row', async () => { + const rows = await listedPings(await host([[ALPHA, undefined]])); + expect(rows.map((row) => row.label)).toEqual([`ping ${ALPHA}`]); + }); + + it('MCP bare `run_action`, both object-less: the D3 refusal naming both packages (409 RESOURCE_CONFLICT), nothing runs', async () => { + const h = await host([[ALPHA, undefined], [BETA, undefined]]); + const thrown: any = await bridgeOf(h).runAction('shared_ping', {}).catch((e: unknown) => e); + expect(thrown).toBeInstanceOf(Error); + expect([thrown?.code, thrown?.status]).toEqual(['RESOURCE_CONFLICT', 409]); + expect(String(thrown?.message)).toContain(ALPHA); + expect(String(thrown?.message)).toContain(BETA); + expect(h.executed()).toBe(0); + }); + + it('CONTROL — MCP bare `run_action`, one package: it runs', async () => { + const h = await host([[ALPHA, undefined]]); + await expect(bridgeOf(h).runAction('shared_ping', {})).resolves.toMatchObject({ ok: true }); + expect(h.executed()).toBe(1); + }); +});