Skip to content

Commit e2d0dab

Browse files
fix(objectql): list a runtime-authored bound action on the object it names (#28388)
<!-- claude-projects-attribution: {"github_login":"os-zhuang"} --> _Requested by **Sam** · [project thread](https://claude.ai/code/project/chan_01LjZwNRFiG2fkp8SNf6rHNx?thread=cmsg_01LjZwNRFiG2fkp8SNf6rHNxQLLDJM47eag51AoZaxz8Ha)_ Fixes #28356 Clause-②: no Metadata-protocol: none ## 维护者速读 - **改了什么:** 运行时经元数据入口(`PUT /api/v1/meta/action/NAME`、Studio、AI)保存的、带 `objectName` 的独立 action,现在会挂到它所指对象的 `actions` 上;删除后立即从对象上撤下。 - **为什么改:** 之前注册表只把代码包发布的绑定 action 挂到对象上,运行时保存的 action 能执行却不出现在任何对象界面上,保存成功但用户找不到按钮。 - **风险与回滚:** 只改 `SchemaRegistry` 读时挂接的取数范围与两处删除时的缓存失效;启动期审计仍只看代码包 action。回滚即 revert 本 PR。 - **先看:** `packages/objectql/src/registry.ts` 的 `boundServedActions`(同名 bare key 遮蔽 composite key 的那一行);同文件 `removeOverlayEntry` / `removeRuntimeShadow` 新增的 `invalidateAll`;`packages/objectql/src/bound-action-foreign-object.test.ts` 新增 describe 块。 - **两分钟验证:** `pnpm --filter @objectstack/objectql exec vitest run src/bound-action-foreign-object.test.ts`,预期 23 passed;新块 5 条覆盖保存、重存、删除、无目标对象、overlay 替换。 - **需要你做的:** 无,席位落地。 ## What changes - `SchemaRegistry.attachBoundActions` now attaches every bound standalone `action` the registry serves (new private `boundServedActions`), not only code-shipped ones. A runtime row reaches the registry through the save door's write-through and the boot's `sys_metadata` hydration; it was dispatchable through the router's rung 2 but listed on no served object, so no client drew it. - One item per name, with `getItem`'s precedence: a bare-key entry (an ADR-0005 overlay) shadows the composite entries of its name, so the attached entry is the declaration rung 2 resolves. - The boot audits (`findUnboundActionTargets`, the bound-action collision audit) keep reading the code-only population, so a runtime action naming a missing object never fails a boot. - `removeOverlayEntry` and `removeRuntimeShadow` (the delete heal's tiers) now drop the cached object folds when they retire an `action` entry, as `unregisterItem` already did. Without it a deleted runtime action stayed listed on the cached object. - The registry holds no org-scoped row (the protocol's hydration declines one), so the attach crosses no organization. ## Tests - New describe block in `packages/objectql/src/bound-action-foreign-object.test.ts` (real `ObjectStackProtocolImplementation` + real registry): - saved action is listed by `getMetaItem` object, `getMetaItems` object and `registry.getObject`, after the owner's own actions; control object unchanged; - attached entry is the rung 2 declaration by reference; - re-save serves the new body; delete withdraws it from the cached object and from the served read; - a runtime action naming a missing object is listed nowhere and `findUnboundActionTargets()` stays empty; - a bare-key overlay of a packaged bound action is attached in its place, and lifting the shadow serves the packaged one again. - Ablations (each through `scripts/ablation-replace.mjs`, mutation landed on disk, restored to the HEAD blob, `git diff HEAD` empty): - attach population back to `boundCodeActions` ⇒ 4 of the new cases red; - invalidation removed from `removeOverlayEntry` ⇒ the delete case red; - invalidation removed from `removeRuntimeShadow` ⇒ the shadow-lift case red. - A first attempt at the second ablation was a no-op (replacement contained the anchor); the tool refused it before running, and it was redone with a marker. - `pnpm --filter @objectstack/objectql typecheck && pnpm --filter @objectstack/objectql test` at 0b2103f: 505 files / 9828 tests passed (lock VERDICT command-exit 0). ## Acceptance notes - Not measured: a restart that rehydrates the stored row from `sys_metadata` (the dev server's `--fresh` store dies with the process). The hydrated row registers under the bare key, which the new population includes; the unit cases drive the write-through path. - Out of scope, noted: `removeOverlayEntry` / `removeRuntimeShadow` also skip the fold invalidation for `picklist` entries, which `registerItem` / `unregisterItem` do invalidate. Not measured. - The console side needs no change: `useConsoleActionRuntime` reads `objectDef.actions`, which now carries the action. ## Verification <details><summary>Live: fresh todo server, before and after</summary> `examples/app-todo` with `pnpm dev -- --fresh`, signed in as the seeded admin, then `PUT /api/v1/meta/action/rt_probe_action` with `objectName: todo_task`, `type: url`. - origin/main 80b561b: PUT 200; `GET /meta/action` lists `rt_probe_action`; `GET /meta/object/todo_task` and `GET /meta/object` list the 8 packaged actions only. - This branch (objectql rebuilt): both object reads list the 8 actions then `rt_probe_action`; after `DELETE /meta/action/rt_probe_action` (200) the object lists the 8 again. </details> <details><summary>Derived gates at 0b2103f</summary> `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack`: 62 commands, all run, exit codes captured before any pipe. - 60 exit 0. - `node scripts/check-plugin-teardown-shape.mjs --self-test` exit 3 on the shallow clone (positive-control commit unreachable); after fetching that commit, exit 0 (48 cases pass). - `pnpm check:dual-build-cjs-loads` exit 3, PREREQUISITE NOT MET (workspace not fully built): NOT MEASURED locally, CI's Lint and Repo Gates runs it. - `--ran` reconciliation: 62 derived, 61 run, 1 NOT-MEASURED (the one above). - `eslint --no-inline-config` on the two changed source files: exit 0. Repo-wide `pnpm lint` is CI's. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01QUs3BsEVeiZG9ncdEjdtiu)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 8c8c5b5 commit e2d0dab

3 files changed

Lines changed: 194 additions & 21 deletions

File tree

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
---
2+
'@objectstack/objectql': patch
3+
---
4+
5+
fix(objectql): a standalone action saved at runtime with `objectName` is listed on the object it names
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
A standalone `action` saved through the metadata door (`PUT /api/v1/meta/action/NAME`, Studio, or an AI author) with `objectName` set was stored and could be run, but no served object listed it: `GET /api/v1/meta/object/OBJECT` and the object list left it out of `actions`, so no record header, list toolbar or other object surface showed it. The registry attached bound actions to their object only when a code package shipped them.
11+
12+
Now every bound action the registry serves is attached, whoever authored it:
13+
14+
- **Runtime-authored actions appear on their object.** After the save, the object's served `actions` list the object's own actions first, then the bound ones, ordered by `order`. A re-save serves the new body, and a delete takes it off the object at once.
15+
- **A customised action replaces the packaged one.** Where a stored row overlays a packaged bound action of the same name, the object lists the stored version, the one the action route already runs.
16+
- **Boot checks are unchanged.** A runtime action naming an object that does not exist is listed nowhere and does not fail the boot. Only code-shipped actions are checked against their target at boot.

‎packages/objectql/src/bound-action-foreign-object.test.ts‎

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -429,3 +429,93 @@ describe('a bound action is served as its ActionSchema parse', () => {
429429
expect(actionNames(host.engine.registry.getObject('ba_org'))).toEqual(['own_gated']);
430430
});
431431
});
432+
433+
// ── [#28356] A bound action a runtime author saves through the metadata door ──
434+
435+
describe('a bound action saved at runtime through the metadata door reaches its object as served', () => {
436+
/** The standalone action an author saves for the owner's object — no package ships it. */
437+
const RUNTIME = {
438+
name: 'rt_action', label: 'Runtime', objectName: 'ba_org', type: 'url',
439+
target: 'https://example.com/rt', locations: ['record_header'],
440+
};
441+
const save = (protocol: ObjectStackProtocolImplementation, item: any, extra: Record<string, unknown> = {}) =>
442+
protocol.saveMetaItem({ type: 'action', name: item.name, item: structuredClone(item), ...extra } as any);
443+
const listedActions = async (protocol: ObjectStackProtocolImplementation, name: string): Promise<string[]> => {
444+
const listed: any = await protocol.getMetaItems({ type: 'object' } as any);
445+
const items: any[] = Array.isArray(listed) ? listed : listed?.items ?? [];
446+
return actionNames(items.find((o) => o?.name === name));
447+
};
448+
449+
it('GET /meta/object/<target>, the object list and the registry object all list it after the owner\'s own actions', async () => {
450+
const { engine, protocol } = await hostWith([OWNER, CONTROL]);
451+
const saved: any = await save(protocol, RUNTIME);
452+
expect(saved).toMatchObject({ success: true, state: 'active' });
453+
454+
const served: any = await protocol.getMetaItem({ type: 'object', name: 'ba_org' } as any);
455+
expect(actionNames(served.item)).toEqual(['own_action', 'rt_action']);
456+
expect(await listedActions(protocol, 'ba_org')).toEqual(['own_action', 'rt_action']);
457+
expect(actionNames(engine.registry.getObject('ba_org'))).toEqual(['own_action', 'rt_action']);
458+
// Control: the object it is not bound to is served as declared.
459+
expect(actionNames(engine.registry.getObject('ba_control'))).toEqual([]);
460+
});
461+
462+
it('the served entry is the declaration the router\'s rung 2 resolves, by reference', async () => {
463+
const { engine, protocol } = await hostWith([OWNER]);
464+
await save(protocol, RUNTIME);
465+
const attached: any = engine.registry.getObject('ba_org')?.actions?.find((a: any) => a.name === 'rt_action');
466+
expect(attached).toBe(engine.registry.getItem('action', 'rt_action'));
467+
expect(attached).toMatchObject({ target: 'https://example.com/rt', objectName: 'ba_org' });
468+
});
469+
470+
it('a re-save serves the new body, and a delete withdraws it from the cached object', async () => {
471+
const { engine, protocol } = await hostWith([OWNER]);
472+
await save(protocol, RUNTIME);
473+
expect(actionNames(engine.registry.getObject('ba_org'))).toEqual(['own_action', 'rt_action']);
474+
475+
await save(protocol, { ...RUNTIME, label: 'Runtime v2' });
476+
const resaved: any = engine.registry.getObject('ba_org')?.actions?.find((a: any) => a.name === 'rt_action');
477+
expect(resaved?.label).toBe('Runtime v2');
478+
479+
const deleted: any = await protocol.deleteMetaItem({ type: 'action', name: 'rt_action' } as any);
480+
expect(deleted).toMatchObject({ success: true });
481+
expect(engine.registry.getItem('action', 'rt_action')).toBeUndefined();
482+
expect(actionNames(engine.registry.getObject('ba_org'))).toEqual(['own_action']);
483+
const served: any = await protocol.getMetaItem({ type: 'object', name: 'ba_org' } as any);
484+
expect(actionNames(served.item)).toEqual(['own_action']);
485+
});
486+
487+
it('the code layer (`getArtifactItem`) carries the code packages\' bound actions only, never the runtime one', async () => {
488+
// The authored-action re-sync reads this layer to decide that a code
489+
// package ships an action (and leaves its handler to AppPlugin); a
490+
// runtime action read there would never get its body bound.
491+
const { engine, protocol } = await hostWith([OWNER, BINDER]);
492+
await save(protocol, RUNTIME);
493+
expect(actionNames(engine.registry.getObject('ba_org'))).toEqual(['own_action', 'rename_org', 'rt_action']);
494+
expect(actionNames(engine.registry.getArtifactItem('object', 'ba_org'))).toEqual(['own_action', 'rename_org']);
495+
});
496+
497+
it('a runtime action naming an object no package registers is listed nowhere, and the boot audit stays code-only', async () => {
498+
const { engine, protocol } = await hostWith([OWNER]);
499+
await save(protocol, { ...RUNTIME, name: 'rt_orphan', objectName: 'ba_missing' });
500+
expect(engine.registry.getItem('action', 'rt_orphan')).toBeDefined();
501+
expect(actionNames(engine.registry.getObject('ba_org'))).toEqual(['own_action']);
502+
expect(engine.registry.findUnboundActionTargets()).toEqual([]);
503+
});
504+
505+
it('a bare-key overlay of a packaged bound action is attached in its place, as the router resolves it', async () => {
506+
const { engine } = await hostWith([OWNER, BINDER]);
507+
// A rehydrated row under the bare name — the ADR-0005 overlay tier
508+
// `getItem` answers first. The save door refuses an `action` overlay,
509+
// so the registration is direct: the shape a stored legacy row takes.
510+
engine.registry.registerItem('action', { ...BOUND, target: 'https://example.com/customised' }, 'name');
511+
const attached: any[] = (engine.registry.getObject('ba_org')?.actions ?? []).filter((a: any) => a.name === 'rename_org');
512+
expect(attached).toHaveLength(1);
513+
expect(attached[0]).toBe(engine.registry.getItem('action', 'rename_org'));
514+
expect(attached[0].target).toBe('https://example.com/customised');
515+
516+
// Lifting the shadow (the delete heal's first tier) serves the packaged declaration again.
517+
expect(engine.registry.removeRuntimeShadow('action', 'rename_org')).toBe(true);
518+
const restored: any = engine.registry.getObject('ba_org')?.actions?.find((a: any) => a.name === 'rename_org');
519+
expect(restored?.target).toBe('https://example.com/rename');
520+
});
521+
});

‎packages/objectql/src/registry.ts‎

Lines changed: 88 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -495,6 +495,14 @@ const OBJECT_FOLD_SCALAR_KEYS = ['label', 'pluralLabel', 'description'] as const
495495

496496
type ObjectFoldScalarKey = (typeof OBJECT_FOLD_SCALAR_KEYS)[number];
497497

498+
/**
499+
* [#28356] Which layer an object fold serves: `'served'`, what every read
500+
* answers (the bound actions the registry serves, runtime-authored included),
501+
* or `'code'`, the code-layer resolution {@link SchemaRegistry.getArtifactItem}
502+
* answers (the code packages' bound actions alone).
503+
*/
504+
type ServedObjectLayer = 'served' | 'code';
505+
498506
/**
499507
* Deep merge two ServiceObject definitions.
500508
*
@@ -3913,8 +3921,12 @@ export class SchemaRegistry {
39133921
* code-layer resolution ({@link resolveOwnerLayer}) folds extenders exactly
39143922
* the same way rather than growing a second, drifting copy.
39153923
*/
3916-
private foldExtenders(contributors: ObjectContributor[], base: ObjectContributor): ServiceObject {
3917-
return this.foldExtendersOntoDefinition(contributors, base.definition);
3924+
private foldExtenders(
3925+
contributors: ObjectContributor[],
3926+
base: ObjectContributor,
3927+
layer: ServedObjectLayer = 'served',
3928+
): ServiceObject {
3929+
return this.foldExtendersOntoDefinition(contributors, base.definition, layer);
39183930
}
39193931

39203932
/**
@@ -3925,6 +3937,7 @@ export class SchemaRegistry {
39253937
private foldExtendersOntoDefinition(
39263938
contributors: ObjectContributor[],
39273939
baseDefinition: ServiceObject,
3940+
layer: ServedObjectLayer = 'served',
39283941
): ServiceObject {
39293942
// [ADR-0029 D9.2a] Computed ONCE, over the base the fold starts from — never
39303943
// re-derived from the running `merged`, which would make an extender's own
@@ -3955,7 +3968,7 @@ export class SchemaRegistry {
39553968
// A picklist-bound field is served with its list's options resolved onto
39563969
// it — here, in the fold every object read and the write door share, so
39573970
// the set a client is offered and the set a write is judged by are one.
3958-
return this.finishServedObject(merged);
3971+
return this.finishServedObject(merged, layer);
39593972
}
39603973

39613974
/**
@@ -3997,11 +4010,15 @@ export class SchemaRegistry {
39974010
* MetadataService layers run. A step added here reaches every one of them.
39984011
*
39994012
* 1. picklist-bound fields get their list's options resolved onto them;
4000-
* 2. [#24400] the code packages' bound top-level actions are attached
4001-
* ({@link attachBoundActions}).
4013+
* 2. [#24400] the bound top-level actions are attached — the code
4014+
* packages' and, [#28356], the runtime-authored ones
4015+
* ({@link attachBoundActions}). The CODE layer
4016+
* ({@link resolveOwnerLayer}, `layer: 'code'`) attaches the code
4017+
* packages' alone: a tenant's action is not something a code package
4018+
* ships, and `getArtifactItem('object')` answers exactly that question.
40024019
*/
4003-
private finishServedObject<T>(body: T): T {
4004-
return this.attachBoundActions(this.resolvePicklistFields(body));
4020+
private finishServedObject<T>(body: T, layer: ServedObjectLayer = 'served'): T {
4021+
return this.attachBoundActions(this.resolvePicklistFields(body), layer);
40054022
}
40064023

40074024
/**
@@ -4020,14 +4037,16 @@ export class SchemaRegistry {
40204037
* the action may register in either order, and the cached fold is dropped
40214038
* when an action registers ({@link registerItem}) or leaves.
40224039
*
4023-
* What attaches: a standalone `action` item a CODE package shipped
4024-
* (`isCodeArtifactBody` — never a tenant-authored row), whose owner key
4025-
* ({@link standaloneActionOwnerKey}, the router's own test) is this object's
4026-
* name, and whose package is not disabled. Attached BY REFERENCE, so the
4027-
* served entry is the very declaration rung 2 resolves: its
4028-
* `requiredPermissions`, `requiresMembershipReach` and execution identity
4029-
* travel with it unchanged, and nothing about the object's own write policy
4030-
* moves.
4040+
* What attaches: a standalone `action` item this registry serves
4041+
* ({@link boundServedActions}) — one a code package shipped, or [#28356] one
4042+
* a runtime author saved through the metadata door, which the save's
4043+
* write-through and the boot's `sys_metadata` hydration register here —
4044+
* whose owner key ({@link standaloneActionOwnerKey}, the router's own test)
4045+
* is this object's name, and whose package is not disabled. Attached BY
4046+
* REFERENCE, so the served entry is the very declaration rung 2 resolves:
4047+
* its `requiredPermissions`, `requiresMembershipReach` and execution
4048+
* identity travel with it unchanged, and nothing about the object's own
4049+
* write policy moves.
40314050
*
40324051
* Deduplicated by NAME, which is also what makes the step idempotent over a
40334052
* body that already carries the action — the same-stack merge's copy, a
@@ -4046,7 +4065,7 @@ export class SchemaRegistry {
40464065
*
40474066
* Returns `body` by reference when nothing attaches.
40484067
*/
4049-
private attachBoundActions<T>(body: T): T {
4068+
private attachBoundActions<T>(body: T, layer: ServedObjectLayer = 'served'): T {
40504069
if (body === null || typeof body !== 'object') return body;
40514070
const objectName = (body as { name?: unknown }).name;
40524071
if (typeof objectName !== 'string' || objectName === '') return body;
@@ -4056,7 +4075,7 @@ export class SchemaRegistry {
40564075
const base: any[] = Array.isArray(declared) ? declared : [];
40574076
const present = new Set<unknown>(base.map((action) => action?.name));
40584077
const fresh: any[] = [];
4059-
for (const action of this.boundCodeActions()) {
4078+
for (const action of layer === 'code' ? this.boundCodeActions() : this.boundServedActions()) {
40604079
if (standaloneActionOwnerKey(action) !== objectName || present.has(action.name)) continue;
40614080
present.add(action.name);
40624081
fresh.push(action);
@@ -4067,11 +4086,52 @@ export class SchemaRegistry {
40674086
return { ...body, actions: [...base, ...sortActionsByOrder(fresh)] };
40684087
}
40694088

4089+
/**
4090+
* [#28356] The standalone `action` items bound to an object that this
4091+
* registry SERVES — the population {@link attachBoundActions} attaches.
4092+
*
4093+
* Every bound item in the collection, whoever authored it: a code package's
4094+
* (under its `<packageId>:<name>` key) and a runtime author's, which the
4095+
* save door's write-through and the boot's `sys_metadata` hydration register
4096+
* (under the bare name, or a bound package's key with `_provenance: 'org'`).
4097+
* Leaving the runtime rows out made a bound action saved through the
4098+
* metadata door dispatchable (rung 2 reads {@link getItem}) yet listed by no
4099+
* served object, so no client drew it.
4100+
*
4101+
* One item per name where {@link getItem} would pick one: a bare-key entry
4102+
* (an ADR-0005 overlay) shadows the composite entries of its name, so a
4103+
* customised bound action is attached as customised — the declaration rung 2
4104+
* resolves — and never as the packaged default under it.
4105+
*
4106+
* The registry holds no org-scoped row (the protocol's hydration declines
4107+
* one), so nothing here crosses an organization. A disabled package's items
4108+
* are left out, as the rest of its items are withheld.
4109+
*
4110+
* ⛔ Not the boot audits' population: a runtime row naming an object no
4111+
* package registers must not fail a boot, so {@link findUnboundActionTargets}
4112+
* and {@link FIND_BOUND_ACTION_COLLISIONS} keep reading
4113+
* {@link boundCodeActions}.
4114+
*/
4115+
private boundServedActions(): any[] {
4116+
const collection = this.metadata.get('action');
4117+
if (!collection) return [];
4118+
const out: any[] = [];
4119+
for (const [key, action] of collection) {
4120+
if (!action || typeof action !== 'object' || typeof (action as any).name !== 'string') continue;
4121+
const name: string = (action as any).name;
4122+
if (key !== name && collection.has(name)) continue;
4123+
if (isObjectLessActionKey(standaloneActionOwnerKey(action))) continue;
4124+
if (this.isPackageDisabled((action as any)._packageId)) continue;
4125+
out.push(action);
4126+
}
4127+
return out;
4128+
}
4129+
40704130
/**
40714131
* [#24400] The standalone `action` items code packages ship that are bound
4072-
* to an object — the population {@link attachBoundActions} attaches and
4073-
* {@link findUnboundActionTargets} audits. A disabled package's actions are
4074-
* left out, as the rest of its items are withheld.
4132+
* to an object — the population {@link findUnboundActionTargets} and
4133+
* {@link FIND_BOUND_ACTION_COLLISIONS} audit. A disabled package's actions
4134+
* are left out, as the rest of its items are withheld.
40754135
*/
40764136
private boundCodeActions(): any[] {
40774137
const out: any[] = [];
@@ -4940,7 +5000,7 @@ export class SchemaRegistry {
49405000
if (!contributors || contributors.length === 0) return undefined;
49415001
const ownerContrib = contributors.find(c => c.ownership === 'own');
49425002
if (!ownerContrib) return undefined;
4943-
return this.foldExtenders(contributors, ownerContrib);
5003+
return this.foldExtenders(contributors, ownerContrib, 'code');
49445004
}
49455005

49465006
/**
@@ -6151,6 +6211,9 @@ export class SchemaRegistry {
61516211
const it = item as any;
61526212
if (it && it._packageId && it._packageId !== 'sys_metadata') {
61536213
collection.delete(name);
6214+
// [#28356] An object may carry the shadow as a bound action; the
6215+
// artifact it uncovers may bind elsewhere ({@link attachBoundActions}).
6216+
if (type === 'action') this.invalidateAll();
61546217
this.log(`[Registry] Removed runtime shadow ${type}: ${name} (artifact ${it._packageId} restored)`);
61556218
return true;
61566219
}
@@ -6227,6 +6290,10 @@ export class SchemaRegistry {
62276290
return false;
62286291
}
62296292
collection.delete(name);
6293+
// [#28356] …and an object may carry the retired entry as a bound action
6294+
// ({@link attachBoundActions}): drop the cached folds, as
6295+
// {@link unregisterItem} does, or a deleted runtime action stays listed.
6296+
if (type === 'action') this.invalidateAll();
62306297
this.log(`[Registry] Removed overlay entry ${type}: ${name} (no layer serves it any more)`);
62316298
return true;
62326299
}

0 commit comments

Comments
 (0)