Skip to content

Commit 6a2b1f4

Browse files
committed
fix(objectql, metadata-protocol, cloud-connection): close the declared action override's door and boot-order loose ends
- install door: judge a declared action override against the base's code artifact, not the listing that serves the armed override - protocol door: a declared action override's base is keyed <objectName>:<name>, as os validate and the install door key it - registerAction: only the declared base's handler slots beneath an armed override; any other registration replaces it and is warned Claude-Session: https://claude.ai/code/session_01Utp6CXTiQqG1Y4zdXMck85 Co-authored-by: Claude <noreply@anthropic.com>
1 parent db04e5c commit 6a2b1f4

8 files changed

Lines changed: 200 additions & 28 deletions

‎packages/cloud-connection/src/marketplace-install-local-override-gate.test.ts‎

Lines changed: 44 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,8 @@ const deps = (...ids: string[]) => Object.fromEntries(ids.map((id) => [id, '*'])
4444

4545
/** What each installed package holds, as the protocol's per-package listing answers it. */
4646
type Holdings = Record<string, Record<string, Array<Record<string, unknown>>>>;
47+
/** [#30542] The registry's code artifacts (`getArtifactItem`), each under its package's `_packageId`. */
48+
type Artifacts = Array<{ type: string; item: Record<string, unknown> }>;
4749

4850
function makeRawApp() {
4951
const routes = new Map<string, Handler>();
@@ -59,7 +61,7 @@ function makeRawApp() {
5961
* A kernel whose registry holds `installed` (BASE read-only — a code or
6062
* marketplace package is in `manifests`) and whose protocol lists `holdings`.
6163
*/
62-
function makeCtx(rawApp: any, installed: Array<{ id: string; dependencies?: Record<string, string> }>, holdings: Holdings) {
64+
function makeCtx(rawApp: any, installed: Array<{ id: string; dependencies?: Record<string, string> }>, holdings: Holdings, artifacts?: Artifacts) {
6365
const hooks = new Map<string, any>();
6466
const registered: any[] = [];
6567
const saved: Array<[string, string]> = [];
@@ -77,6 +79,11 @@ function makeCtx(rawApp: any, installed: Array<{ id: string; dependencies?: Reco
7779
registry: {
7880
getAllPackages: () => [...records, ...registered],
7981
getPackage: (id: string) => records.find((r) => r.manifest.id === id),
82+
// [#30542] The registry's code artifacts, when the case gives them.
83+
...(artifacts ? {
84+
getArtifactItem: (type: string, name: string, packageId?: string) => artifacts
85+
.find((a) => a.type === type && a.item.name === name && a.item._packageId === packageId)?.item,
86+
} : {}),
8087
},
8188
}),
8289
protocol: {
@@ -132,9 +139,10 @@ async function install(
132139
manifest: Record<string, unknown>,
133140
installed: Array<{ id: string; dependencies?: Record<string, string> }> = [{ id: BASE }],
134141
holdings: Holdings = BASE_HOLDINGS,
142+
artifacts?: Artifacts,
135143
) {
136144
const rawApp = makeRawApp();
137-
const k = makeCtx(rawApp, installed, holdings);
145+
const k = makeCtx(rawApp, installed, holdings, artifacts);
138146
const plugin = new MarketplaceInstallLocalPlugin({ controlPlaneUrl: 'off', storageDir: dir });
139147
await plugin.start(k.ctx as any);
140148
await k.fire();
@@ -299,3 +307,37 @@ describe('install-local 2d — the override write gate at the managed install (A
299307
expect(saved).toEqual([['email_template', 'crm_welcome'], ['email_template', 'crm_welcome']]);
300308
});
301309
});
310+
311+
/**
312+
* [#30542] A re-install of the pair is judged against the base's code
313+
* artifact, as the protocol door judges the save. Once the pair's declared
314+
* action override is armed, the protocol's listing of the base serves that
315+
* override under the base's envelope (measured on the real engine and
316+
* protocol); the registry still holds the base's own action.
317+
*/
318+
describe('[#30542] the install door judges a declared action override against the base\'s code artifact', () => {
319+
const overrides = { package: BASE, basedOn: '1.0.0' };
320+
const BASE_GATES = { requiredPermissions: ['crm_admin'], ai: { requiresConfirmation: true } };
321+
// v1, armed: it added a capability to the base's.
322+
const armed: Holdings = {
323+
[BASE]: { action: [{ name: 'crm_call', label: 'V1', overrides, ...BASE_GATES, requiredPermissions: ['crm_admin', 'crm_auditor'] }] },
324+
};
325+
const artifacts: Artifacts = [{ type: 'action', item: { name: 'crm_call', label: 'Call', ...BASE_GATES, _packageId: BASE } }];
326+
const pairOf = (action: Record<string, unknown>) =>
327+
({ id: PAIR, version: '2.0.0', namespace: 'crm_custom', dependencies: deps(BASE), actions: [action] });
328+
329+
it('a v2 that relaxes the v1 tightening back to the base\'s own gates installs', async () => {
330+
const { res, saved } = await install(pairOf({ name: 'crm_call', label: 'V2', overrides, ...BASE_GATES }), [{ id: BASE }], armed, artifacts);
331+
expect(res.status, JSON.stringify(res.payload)).toBe(200);
332+
expect(saved).toEqual([['action', 'crm_call']]);
333+
});
334+
335+
it('a v2 that drops a gate the base\'s own action carries is still refused 403, and nothing is written', async () => {
336+
const wider = { name: 'crm_call', label: 'V2', overrides, ...BASE_GATES, ai: {} };
337+
const { res, saved, ledger } = await install(pairOf(wider), [{ id: BASE }], armed, artifacts);
338+
expect(res.status, JSON.stringify(res.payload)).toBe(403);
339+
expect(res.payload?.error?.code).toBe('NOT_OVERRIDABLE');
340+
expect(refusedOf(res)).toEqual([['action', 'crm_call', 'declared_action_widens_access']]);
341+
expect([saved, ledger]).toEqual([[], []]);
342+
});
343+
});

‎packages/cloud-connection/src/marketplace-install-local-plugin.ts‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -568,6 +568,8 @@ type NamespaceHoldingEngine = PackageWritabilityEngine & {
568568
type OverrideGateEngine = PackageWritabilityEngine & {
569569
registry?: PackageWritabilityEngine['registry'] & {
570570
getAllPackages?(): unknown;
571+
/** [#30542] An installed package's code artifact (`SchemaRegistry#getArtifactItem`). */
572+
getArtifactItem?(type: string, name: string, currentPackageId?: string): unknown;
571573
};
572574
};
573575
type OverrideGateLister = {
@@ -3681,6 +3683,20 @@ export class MarketplaceInstallLocalPlugin implements Plugin {
36813683
return read;
36823684
};
36833685
const isBase = (id: string): boolean => delivered.has(id) || !isWritablePackage(ql, id);
3686+
// [#30542] An installed base's own item is its code artifact, the one
3687+
// the protocol door judges a declared action override against
3688+
// (`overrideWriteVerdict`'s `baseItemOf`). The listing is not: once
3689+
// the base's declared override is armed, it serves the override under
3690+
// the base's envelope, so a re-install of the pair was judged against
3691+
// its own previous version, and a v2 that relaxes a v1 tightening
3692+
// back to the base's own gates was refused. A registry that answers
3693+
// no artifact leaves the listed item.
3694+
const artifactOf = (item: OverrideWriteItem, base: string): unknown => {
3695+
const artifact = registry.getArtifactItem?.(item.type, item.name, base);
3696+
return isPlainObject(artifact) && artifact._packageId === base && listedIdentity(item.type, artifact) === item.identity
3697+
? artifact
3698+
: undefined;
3699+
};
36843700

36853701
const refusals: OverrideInstallRefusal[] = [];
36863702
for (const [packageId, pkg] of delivered) {
@@ -3693,7 +3709,10 @@ export class MarketplaceInstallLocalPlugin implements Plugin {
36933709
const shipped = new Map<string, unknown>();
36943710
for (const base of bases) {
36953711
const held = (await heldBy(item.type, base)).get(item.identity);
3696-
if (held !== undefined) { shippers.push(base); shipped.set(base, held); }
3712+
if (held !== undefined) {
3713+
shippers.push(base);
3714+
shipped.set(base, (delivered.has(base) ? undefined : artifactOf(item, base)) ?? held);
3715+
}
36973716
}
36983717
const verdict = judgeOverrideWrite(
36993718
{ type: item.type, name: item.name, packageId, item: item.item },

‎packages/metadata-protocol/src/protocol-packaged-base-refusal.ts‎

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -766,6 +766,17 @@ export function overrideWriteIdentityOf(type: string, identity: string, item: un
766766
return member === undefined ? identity : `${identity}\u0000${member}`;
767767
}
768768

769+
/**
770+
* [#30542] The object an `action` item is keyed on under the override write
771+
* gate — its `objectName`, `''` when it names none: the first half of the
772+
* `<objectName>:<name>` identity {@link overrideWriteItemsOf} gives it, and
773+
* what {@link overrideWriteVerdict} matches a declared override's base on.
774+
*/
775+
function overrideWriteActionObjectOf(item: unknown): string {
776+
const objectName = isPlainRecord(item) ? item.objectName : undefined;
777+
return typeof objectName === 'string' ? objectName : '';
778+
}
779+
769780
/** One item written into one package — what the override write gate judges. */
770781
export interface OverrideWriteSubject {
771782
/** The metadata type, either spelling (folded here). */
@@ -1112,9 +1123,8 @@ export function overrideWriteItemsOf(body: Record<string, unknown>, at = ''): Ov
11121123
}
11131124
continue;
11141125
}
1115-
const identity = type === 'action' && typeof item.objectName === 'string' && item.objectName !== ''
1116-
? `${item.objectName}:${declaredName}`
1117-
: declaredName;
1126+
const object = type === 'action' ? overrideWriteActionObjectOf(item) : '';
1127+
const identity = object !== '' ? `${object}:${declaredName}` : declaredName;
11181128
out.push({ type, name: declaredName, identity: overrideWriteIdentityOf(type, identity, item), item, path });
11191129
}
11201130
}
@@ -1171,11 +1181,19 @@ export function overrideWriteVerdict(
11711181
if (packageId !== undefined && scope === undefined) return NOT_CONCERNED;
11721182
const dependencies = scope?.dependencies.filter((id) => id !== packageId);
11731183
const member = overrideWriteMemberOf(request.type, request.item);
1184+
// [#30542] A declared action override names its base's action by the
1185+
// identity `os validate` and the install door key it on,
1186+
// `<objectName>:<name>` ({@link overrideWriteItemsOf}): the base's action
1187+
// of that name on another object is no shipper of it, so an override that
1188+
// moves the action to another object is refused here as it is there.
1189+
const onItsObject = (a: unknown): boolean => !declaration.present
1190+
|| (PLURAL_TO_SINGULAR[request.type] ?? request.type) !== 'action'
1191+
|| overrideWriteActionObjectOf(a) === overrideWriteActionObjectOf(request.item);
11741192
const shippers = dependencies === undefined || dependencies.length === 0
11751193
? []
11761194
: Array.from(new Set(
11771195
this.shippedArtifactsOf(request.type, request.name, undefined, member)
1178-
.filter((a) => overrideWriteMemberOf(request.type, a) === member)
1196+
.filter((a) => overrideWriteMemberOf(request.type, a) === member && onItsObject(a))
11791197
.map((a) => (a as { _packageId?: unknown } | null | undefined)?._packageId)
11801198
// An override replaces an item of an INSTALLED, read-only base
11811199
// (ADR-0146 D1): a writable package's item is edited in place
@@ -1188,7 +1206,7 @@ export function overrideWriteVerdict(
11881206
// [#30065] The base's own item, the one a declared action override is
11891207
// judged against: the shipping artifact under that base's envelope.
11901208
const baseItemOf = (basePackageId: string): unknown => this.shippedArtifactsOf(request.type, request.name, undefined, member)
1191-
.find((a) => overrideWriteMemberOf(request.type, a) === member
1209+
.find((a) => overrideWriteMemberOf(request.type, a) === member && onItsObject(a)
11921210
&& (a as { _packageId?: unknown } | null | undefined)?._packageId === basePackageId);
11931211
return judgeOverrideWrite(request, { dependencies, shippers, baseItemOf });
11941212
}

‎packages/objectql/src/engine-actions.ts‎

Lines changed: 39 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -33,17 +33,21 @@
3333

3434
import type { ActionActivationRow, ActionActivationStore, ActionActivationWriteOptions } from './action-activation.js';
3535
import type { ObjectQL } from './engine.js';
36+
import { standaloneActionOwnerKey } from './action-governance.js';
3637

3738
/**
3839
* One registered action handler. [#30065] `override` marks a declared action
3940
* override's handler ({@link ActionsFacet.registerActionOverride}); `beneath`
40-
* is the handler it was bound over, or one registered for the key after it,
41-
* kept so removing the override restores it.
41+
* is the handler it was bound over, or the declared base's registered for the
42+
* key after it, kept so removing the override restores it. [#30542] `base` is
43+
* the package the override declares (`overrides.package`): only a handler of
44+
* the action that package ships slots beneath it.
4245
*/
4346
export interface ActionHandlerEntry {
4447
handler: (ctx: any) => Promise<any> | any;
4548
package?: string;
4649
override?: true;
50+
base?: string;
4751
beneath?: ActionHandlerEntry;
4852
}
4953

@@ -58,21 +62,24 @@ export interface ActionsHost {
5862
readonly actionActivation: ObjectQL['actionActivation'];
5963
readonly actions: ObjectQL['actions'];
6064
readonly logger: ObjectQL['logger'];
65+
readonly registry: ObjectQL['registry'];
6166
}
6267

6368
/** The bodies of the "Action system and packaged-action activation" section of `ObjectQL`: a stateless facet, called by the class's stubs. */
6469
export class ActionsFacet {
6570
/** The body of `ObjectQL#registerAction`; the method's docblock there is its contract. */
66-
static registerAction(this: Pick<ActionsHost, 'actions' | 'logger'>, objectName: string, actionName: string, handler: (ctx: any) => Promise<any> | any, packageName?: string): void {
71+
static registerAction(this: Pick<ActionsHost, 'actions' | 'logger' | 'registry'>, objectName: string, actionName: string, handler: (ctx: any) => Promise<any> | any, packageName?: string): void {
6772
const key = `${objectName}:${actionName}`;
6873
const replaced = this.actions.get(key);
69-
// [#30065, ADR-0146 D9 `action`] Another package's handler arriving under
70-
// a key a declared override holds — a marketplace base's, bound by its
74+
// [#30065, ADR-0146 D9 `action`] The declared base's handler arriving
75+
// under a key the override holds — a marketplace base's, bound by its
7176
// `kernel:ready` rehydrate after the authored-action resync bound the
72-
// override, or a bundle's handlers re-bound — is the base's: it slots
73-
// beneath the override, which stays the one that runs, and is the one a
74-
// removal of the override binds again.
75-
if (replaced?.override === true && replaced.package !== packageName) {
77+
// override, or a bundle's handlers re-bound — slots beneath the override,
78+
// which stays the one that runs, and is the one a removal of the override
79+
// binds again. [#30542] Only the declared base's: any other registration
80+
// replaces it and is warned below, like every other collision.
81+
if (replaced?.override === true && replaced.package !== packageName
82+
&& ActionsFacet.arrivesAsDeclaredBase.call(this, replaced, objectName, actionName, packageName)) {
7683
this.actions.set(key, { ...replaced, beneath: { handler, package: packageName } });
7784
this.logger.debug('Registered action beneath an override', { objectName, actionName, package: packageName, override: replaced.package });
7885
return;
@@ -92,14 +99,35 @@ export class ActionsFacet {
9299
this.logger.debug('Registered action', { objectName, actionName, package: packageName });
93100
}
94101

102+
/**
103+
* [#30542] Whether a registration under a key a declared override holds is
104+
* the declared base's own handler: the registry's code artifact of the
105+
* action (`getArtifactItem`, which a package's items are registered in
106+
* before its handlers are bound) belongs to the package the override
107+
* declares, on this object — the judgement the authored-action resync
108+
* binds the override by once that artifact is registered. A registration
109+
* with no package is no package's. An override bound with no declared base
110+
* keeps taking any package's handler beneath it.
111+
*/
112+
static arrivesAsDeclaredBase(this: Pick<ActionsHost, 'registry'>, override: ActionHandlerEntry, objectName: string, actionName: string, packageName: string | undefined): boolean {
113+
if (packageName === undefined) return false;
114+
if (override.base === undefined) return true;
115+
const artifact: any = this.registry?.getArtifactItem?.('action', actionName);
116+
return artifact?._packageId === override.base && standaloneActionOwnerKey(artifact) === objectName;
117+
}
118+
95119
/** The body of `ObjectQL#registerActionOverride`; the method's docblock there is its contract. */
96-
static registerActionOverride(this: Pick<ActionsHost, 'actions' | 'logger'>, objectName: string, actionName: string, handler: (ctx: any) => Promise<any> | any, packageName: string): void {
120+
static registerActionOverride(this: Pick<ActionsHost, 'actions' | 'logger'>, objectName: string, actionName: string, handler: (ctx: any) => Promise<any> | any, packageName: string, base?: string): void {
97121
const key = `${objectName}:${actionName}`;
98122
const current = this.actions.get(key);
99123
// Re-binding the same package's override replaces it in place, over the
100124
// same handler beneath.
101125
const beneath = current?.package === packageName ? current.beneath : current;
102-
this.actions.set(key, { handler, package: packageName, override: true, ...(beneath !== undefined ? { beneath } : {}) });
126+
this.actions.set(key, {
127+
handler, package: packageName, override: true,
128+
...(base !== undefined ? { base } : {}),
129+
...(beneath !== undefined ? { beneath } : {}),
130+
});
103131
this.logger.debug('Registered action override', { objectName, actionName, package: packageName, beneath: beneath?.package });
104132
}
105133

‎packages/objectql/src/engine.ts‎

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1185,11 +1185,15 @@ export class ObjectQL implements IObjectQLEngine {
11851185
*
11861186
* [#30065, ADR-0146 D9 `action`] The one exception: a key a declared
11871187
* action override holds ({@link registerActionOverride}) keeps the
1188-
* override on top, and another package's registration takes the place
1189-
* beneath it, the handler a removal of the override binds again. A
1190-
* marketplace base's handlers are bound by its rehydrate after the
1191-
* authored-action resync bound the override, so the base's body arrives
1192-
* second and must not replace the override's.
1188+
* override on top when the declared base's handler arrives, and that
1189+
* handler takes the place beneath it, the one a removal of the override
1190+
* binds again. A marketplace base's handlers are bound by its rehydrate
1191+
* after the authored-action resync bound the override, so the base's body
1192+
* arrives second and must not replace the override's. [#30542] The
1193+
* declared base's handler is the one registered while the registry's code
1194+
* artifact of the action is that package's, on this object; any other
1195+
* registration under the key, one with no package included, replaces the
1196+
* override and is warned like every other.
11931197
*/
11941198
registerAction(objectName: string, actionName: string, handler: (ctx: any) => Promise<any> | any, packageName?: string): void {
11951199
// [#29986 codemod] The body moved to `engine-actions.ts` (see `ActionsHost`).
@@ -1210,9 +1214,13 @@ export class ObjectQL implements IObjectQLEngine {
12101214
* warned: the replacement is the declared one. The entry is marked as an
12111215
* override, so the base's handler registered after it (by
12121216
* {@link registerAction}) slots beneath it instead of replacing it.
1217+
*
1218+
* @param base [#30542] The package the override declares it overrides
1219+
* (`overrides.package`). Only that package's handler slots beneath the
1220+
* override; without it, any package's does.
12131221
*/
1214-
registerActionOverride(objectName: string, actionName: string, handler: (ctx: any) => Promise<any> | any, packageName: string): void {
1215-
return ActionsFacet.registerActionOverride.call(actionsHost.of(this), objectName, actionName, handler, packageName);
1222+
registerActionOverride(objectName: string, actionName: string, handler: (ctx: any) => Promise<any> | any, packageName: string, base?: string): void {
1223+
return ActionsFacet.registerActionOverride.call(actionsHost.of(this), objectName, actionName, handler, packageName, base);
12161224
}
12171225

12181226
/**
@@ -10431,6 +10439,7 @@ export class ObjectQL implements IObjectQLEngine {
1043110439
get actionActivation() { return engine.actionActivation; },
1043210440
get actions() { return engine.actions; },
1043310441
get logger() { return engine.logger; },
10442+
get registry() { return engine.registry; },
1043410443
}));
1043510444
cascadePlanningHost.install((engine) => ({
1043610445
get _registry() { return engine._registry; },

0 commit comments

Comments
 (0)