Skip to content

Commit cedc094

Browse files
fix(objectql)!: register a preserve composition’s residual objectExtensions entry; judge residual jobs at composition (#36338)
<!-- claude-projects-attribution: {"github_login":"zhuangjianguo"} --> _Requested by **Steedos** · [project thread](https://claude.ai/code/project/chan_018ETKaNwMZCNRYD7D8Q9Ubb?thread=cmsg_018ETKaNwMZCNRYD7D8Q9UbbCxiFE11rsKwyNffJZKYqJs)_ Fixes #35711 Clause-②: no (narrowing) Metadata-protocol: narrowed Skills-docs: none — no skill teaches placing `objectExtensions` or `jobs` in a manifest-less input of a `'preserve'` composition; the refusal names both entries and prescribes the fix ## 维护者速读 - 用户能看到什么变化:应用作者把几个包拼成一个产物时,若某个没有包标识的部分给别人的对象加了字段,这些字段现在能正常使用;以前字段直接消失,写入时报字段不存在,启动日志也一句不提。 - 为什么做:拼包产物里不属于任何包的"剩余部分"的对象扩展没有任何环节去登记,属于同一组拼包问题的最后一个漏洞;同时两个没有包标识的部分声明同名定时任务时,拼包不拦、启动时两个都不运行。 - 出错会怎样:拼包时新拦下三种写法(剩余部分里的同名定时任务;剩余部分和持有产物标识的那个包给同一对象各加一段扩展;剩余部分给同一对象加两段扩展,即使别的包也扩展了这个对象),不论选哪种拼包方式,只要产物里带有多个包就会拦;作者会在校验时看到点名两处的报错;已构建的产物照常启动,只多一条错误日志;撤回本次合并即可恢复原状,不涉及数据迁移。 - 要你做什么:无。本次虽然收紧拼包规则,但不在受管范围,座位会在完整回归测试对准最终版本之后自行合入。 ## What changes Measured first, on main `c30ce97cd7`, through the real `os serve` (`packages/cli/bin/run-dev.js serve`, SQLite in memory), on `composeStacks([owner, other, noManifest], { manifest: 'preserve' })`: - **Residual extension.** The input without a manifest extends `probe_account` with `residual_note`. `GET /api/v1/meta/object/probe_account` listed no `residual_note`; `POST /api/v1/data/probe_account` with it answered `400 INVALID_FIELD`; the boot logged nothing about it. `os build` of the same config exits 0 and carries the entry at the artifact's top level (`1 Extensions`), so a built artifact reaches the same drop. Producers: a composition yields `packages[]` beside a residual under `'preserve'` with an input that has no manifest, and under any strategy (`'preserve'`, `'first'`, `'last'`, an index) once an input is itself a multi-package artifact, whose own top-level collections are then residual; a flat composition of inputs that carry no `packages[]` is one package with no residual. - **Residual jobs.** Two inputs without a manifest declaring job `probe_nightly`: `composeStacks` accepted them; the boot (with scheduled work on) logged `NOT SCHEDULED` at `error` and armed neither. The fix, REGISTER rather than refuse, because the residual already has an owner: ADR-0130 D4 registers every residual item under `manifest.id`, and the engine already registers the residual's objects and items there; an extension was the one residual entry no door registered. - **`packages/metadata/src/plugin.ts`.** The residual rule `unclaimedTopLevel` (the one copy every door reads) now lists a top-level `objectExtensions` entry (type `object_extension`) when it names a target and no package body carries an entry EQUAL to it by value. Not by target: the flattened top level repeats each body's entry and a built artifact loses the references, but each copy still holds what its body's entry holds; an equal entry is also the case where nothing is lost. The metadata door still registers no extension (it never registered a body's either). - **`packages/objectql/src/plugin.ts`.** The `manifest` service registers those entries after every body, under the residual's id, through the registry's `extend` verb with the same contribution a body's entry builds: `objectExtensionContribution` (`engine-registration.ts`) is the one reading of an `objectExtensions` entry, and `registerApp` step 2b now builds a body's contribution through it too, so the two cannot drift (it carries `place`, which #36236 added to step 2b on main). Two follow-ons of registering: - Under `'preserve'` the residual's id is the last input-with-a-manifest's body too, and the registry keeps one extension of a target per package. A residual entry for a target that body also extends (or two residual entries for one target) keeps only the last one's fields; the boot says so once per target at `error`, like the #35228 arm A1 line for one body. - An entry whose field names a picklist no package body declares is not registered and is named at boot (`warn`), the residual objects' own rule (the boot's picklist audit would refuse the field). - **`packages/spec/src/stack.zod.ts`, the composition door.** The residual door now mirrors that reading: an `objectExtensions` entry is claimed by a body only when a body carries an equal entry; the owner body's entries for a target the residual also extends are judged with the residual's, body first (the boot's registration order), so the #22934 sentence ("only the last of these entries' fields register") is now true at that door. `jobs` is judged there by name (a body's job name claims the slot), where `TOP_LEVEL_COLLECTIONS_NEVER_RESIDUAL` used to drop it (that set is the owner-stamp mirror and is unchanged). - **The `jobs` row's wording, at every door.** It said only the last entry is kept; the binder schedules none. Now: `The runtime keys jobs by name: the metadata keeps only the last of these entries, and the job scheduler refuses a name two enabled jobs share, so when both are enabled neither runs.` (exact only for two enabled jobs; a disabled one counts no collision). One row, so it stays byte-identical across doors. - ADR-0087 semantic entry `stack-residual-extension-registered-and-jobs-judged`, changeset `minor` for spec, metadata and objectql. Newly refused at composition (`STACK_CROSS_REFERENCE_INVALID`, 422), under every manifest strategy once the result carries `packages[]` (`'preserve'`, and `'first'`/`'last'`/an index with a multi-package input): 1. two residual jobs of one name; 2. a residual extension for an object the body carrying `manifest.id` extends with other fields; 3. two residual extensions of one object, also when another package body extends that object (the claim is by value now; it was by target, so both counted as that body's copies and composed). Unchanged: one residual extension for an object ANOTHER package extends (both register), a residual entry equal to a body's, every package-claimed extension, one residual job. Not refused, a known gap left to the binder (stated in `residualEntryPredicate`'s docblock and the migration entry): a residual job that shares its name with a package body's job, with other content, composes as that body's copy, and the boot schedules neither of the two enabled jobs. Read from code, not driven. ## Tests New pins, named after the card: - `packages/spec/src/stack-residual-extension-jobs.test.ts` — residual job pair refused (code `STACK_CROSS_REFERENCE_INVALID`, status 422, exact sentence); the single-stack door says the same row; residual extension sharing the owner body's slot refused, body entry first; residual extension of a target another body extends composes; two residual extensions of a target another body extends refused (shape 3); `'first'` and `'last'` with a nested multi-package input refuse a residual job pair (with a CONTROL that the artifact carries `packages[]`); an equal entry is a copy; CONTROLS: one residual job composes, each body's own job name, two packages each extending one target, the owner body's own pair reported once. - `packages/metadata/src/unclaimed-top-level-residual-extension.test.ts` — `unclaimedTopLevel` lists the residual entry, composed and as built JSON, never the body's flattened copy; CONTROLS: nothing listed when every extension is a body's, no residual without `packages[]`. - `packages/objectql/src/manifest-service-residual-object-extension.test.ts` — on a kernel through the `manifest` service: the residual field is served (composed and built JSON); it serves exactly what the same entry serves from a body (parity), and a `place`d entry too (anti-vacuity: the placement changes what is served); CONTROL a package-claimed extension unchanged, nothing logged; the owner-slot pair serves the last fields with one `error` line; a dangling-picklist entry is not registered and is named at `warn`. <details><summary>Package suites and typecheck</summary> Head `058d5c2815`. Since f4e83b0 the change is docblocks, the migration entry, the changeset, the `jobs` row's last clause (now "so when both are enabled neither runs") and two spec pins (contract review S1, S2, N3, N4); the spec pin file re-ran here: 13 passed. The objectql and metadata readings below are from f4e83b0 (`origin/main` d8599c2 merged in, then the one-reading unification); neither package changed since. The spec suite's last full run is seat 4's at 5a41a05 (870/870 files, 27886 tests); since then `packages/spec` changed only by the main merge and a type cast, and its pin was re-run here. - `pnpm --filter @objectstack/objectql exec vitest run --project local --maxWorkers=2` — Test Files 628 passed (628), Tests 14272 passed - `pnpm --filter @objectstack/metadata exec vitest run --maxWorkers=2` — Test Files 82 passed (82), Tests 2638 passed - `src/stack-residual-extension-jobs.test.ts` (spec) — 13 passed at 058d5c2 (9 at f4e83b0); `src/unclaimed-top-level-residual-extension.test.ts` (metadata) — 3 passed; `src/manifest-service-residual-object-extension.test.ts` (objectql) — 6 passed - typecheck: `pnpm --filter @objectstack/spec typecheck` exit 0 (tsc, `check:scripts-typecheck`, `check:test-typecheck` OK), re-run at 8f58c38 (058d5c2 adds comments only); `@objectstack/metadata` exit 0; `@objectstack/objectql` exit 0 (`check:test-typecheck` OK). The first objectql run after the unification found TS2345 at step 2b (the shared definition is typed `unknown` per key); fixed in f4e83b0 by handing it to the registry as the residual caller does. - These ran outside the verify lock (declared narrowing): the lock was held by two sibling dogfood batteries for about 100 minutes; the battery below ran under it. </details> <details><summary>Ablation (each fix reverted after commit, through scripts/ablation-replace.mjs; every restore proven blob == HEAD, `git diff HEAD` empty)</summary> - A, metadata listing removed: the metadata pin turns red (1 failed of 3). - B, objectql registration call deleted: the objectql pin turns red (3 failed of 4 at that time). - C, spec `jobs` judged by slot again: the spec jobs pin turns red (1 failed of 9). - D, spec owner-body pairing removed: the owner-slot pin turns red (1 failed of 9). - E (seat 7, at f4e83b0), `place: ext.place` replaced by `place: undefined` in `objectExtensionContribution`: the objectql pin turns red (1 failed of 6, the placement anti-vacuity); restore proven blob == HEAD (cbc7b4d), `git diff HEAD` empty. </details> <details><summary>Real boot (os serve) after the fix</summary> Same probe as the measure-first reading, at 5957d21: `GET /api/v1/meta/object/probe_account` lists `residual_note`; `POST /api/v1/data/probe_account` with it answers a created record. </details> ## Acceptance notes - Measure-first, step 2 (producers): `packages[]` beside a residual comes from `'preserve'` with an input that has no manifest, and from any strategy once an input is itself a multi-package artifact (its own top-level collections are residual); `'first'`/`'last'`/an index over inputs that carry no `packages[]` compose one flat package with no residual. `os build` carries the composed top level as is (`1 Extensions`, exit 0). This corrects the first version of this note, which said `'preserve'` only; the composition door's docblock always said every strategy. - #36236 landed on main with `place` in `registerApp` step 2b's extension literal. Merging main here, the residual builder would have registered a residual entry without its placement; the two are now one call (`objectExtensionContribution`), `place` included, and the parity pin covers a placed entry. - The residual extension's dangling-picklist judgement reads the stack's own bodies, like the residual objects' rule; a field naming a picklist an already-installed package declares is treated as dangling (not registered, named at boot): conservative, not silent. - The `jobs` row's sentence changed at every door (it said the last entry is kept; the binder schedules none). The #22934 rows stay one table, byte-identical across doors. - `defineStack` on a hand-built `packages[]` stack judges its whole top level as one package (`stack.KEY[i]`), unchanged here. ## Open items (follow-up cards) - #36431: a residual job sharing its name with a package body's job (other content) composes and the boot schedules neither (contract review S2, L1). Whether composition should refuse a job name shared across packages is for the maintainer to rule. - #36432: a residual picklist named only by a residual extension is still refused as unreferenced at validate, build and boot (L1); `packages/metadata/src/picklist-references.ts` still tells authors a composed stack's top-level `objectExtensions` entry is not registered, which after this PR holds only for an entry naming a picklist no body declares (review N1); `sameAuthoredValue` (metadata) hand-copies the spec's `deepEqualAuthored` and no test holds them equal (review N5). - Not carried by either card: `logResidualSameTargetExtensions` also reports an owner-body pair for a target the residual does not extend, a second line beside `registerApp`'s (review N2). ## Verification First files to read (by risk): `packages/spec/src/stack.zod.ts` (`residualEntryPredicate`, `ownerBodyExtensionEntries`, the `jobs` row), `packages/objectql/src/plugin.ts` (`registerUnclaimedTopLevelExtensions`), `packages/metadata/src/unclaimed-top-level-residual-extension.test.ts`. Two-minute check: `pnpm --filter @objectstack/objectql exec vitest run --project local --maxWorkers=2 src/manifest-service-residual-object-extension.test.ts` (after building the objectql closure) — 6 passed. Local gates at 058d5c2: 100 derived families (`dispatch-gates --commands`), reconciled with `--ran` (exit codes recorded): 100 run, 0 NOT MEASURED. Seven first exited on a prerequisite (five spec `dist/` gates: `dist` predated the last comment commit; `check:dual-build-cjs-loads`: not every package built; the cli test: `MODULE_NOT_FOUND`) and were re-run after the full closure build: exit 0 each. `check:type-check-debt` exit 0 (its full re-measure, 0 raw tsc errors). `check:nul-bytes` exit 0. `overlap-check` clean before each push. PR check-runs at 058d5c2: Lint & Repo Gates, TypeScript Type Check, Test Core, Build Core, Governed Surface Queue Guard, Type Check UI, Test UI, Build & E2E UI, Live E2E UI, Dogfood Regression Gate and Check Changeset success; Lint UI skipped (no `ui/` path). Dogfood battery at 058d5c2: `os-verify-lock: VERDICT command-exit 0` (closure build exit 0, then `pnpm --filter @objectstack/dogfood test`): Test Files 484 passed, 3 skipped (487); Tests 4107 passed, 68 skipped (4175). The same counts at f4e83b0. Clause-② reading (seat 7): the diff refuses at composition three shapes that compose today (listed under What changes), under every manifest strategy once the result carries `packages[]`, so it is a narrowing, declared `no (narrowing)` as the claim's conditional names. The contract review at f4e83b0 named the third shape and the reach beyond `'preserve'`, which the first version of this body left out. No governed path is in the diff: the seat lands it with `--land` once the dogfood battery is pinned to the head. Registering the residual extension is the REGISTER judgement stated under What changes. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- signed: repo:objectstack#7 · zhuangjianguo · session_01QsR2jTeURPvEm465RcoYEC --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 36873ee commit cedc094

9 files changed

Lines changed: 929 additions & 43 deletions
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
---
2+
'@objectstack/spec': minor
3+
'@objectstack/metadata': minor
4+
'@objectstack/objectql': minor
5+
---
6+
7+
fix(objectql)!: a composition's top-level `objectExtensions` entry that no package body carries is registered and served; composition refuses two such jobs of one name, and residual extensions that would share one package's slot
8+
9+
Clause-②: no (narrowing)
10+
Metadata-protocol: narrowed
11+
Skills-docs: none — no skill teaches placing `objectExtensions` or `jobs` in a manifest-less input of a `'preserve'` composition; the refusal names both entries and prescribes the fix
12+
13+
<!-- adr-0087: registered stack-residual-extension-registered-and-jobs-judged -->
14+
15+
**BREAKING** accept-set narrowing, shipped as `minor`, beside a runtime fix.
16+
17+
- **Fixed (`@objectstack/objectql`, `@objectstack/metadata`).** A composed artifact that carries `packages[]` keeps the entries no package body claims at its top level, and the boot registers that residual under the artifact's `manifest.id` (ADR-0130 D4). Under `composeStacks(stacks, { manifest: 'preserve' })` that is an input with no `manifest`; under `'first'`, `'last'` or an index it is also the own top-level entries of an input that is itself a multi-package artifact. Its `objectExtensions` entries were registered by no door: the target object was served without their fields (`INVALID_FIELD` on a write naming one) and nothing was logged, through `os serve` and through `os build`'s artifact alike. The residual rule (`unclaimedTopLevel`) now lists such an entry (type `object_extension`) when no package body carries an entry equal to it, and the engine registers it as an `extend` contribution under `manifest.id`, as a body's entry registers. An entry whose field names a picklist no package body declares is not registered and is named at boot, like a residual object.
18+
- **Refused now, at composition (`STACK_CROSS_REFERENCE_INVALID`, 422), under every manifest strategy once the result carries `packages[]`.** Two residual jobs of one name: the boot's job binder schedules neither (`NOT SCHEDULED` at `error`). A residual `objectExtensions` entry for an object that the body carrying `manifest.id` also extends with other fields: one extension of an object registers per package, so only the last one's fields would be served; the finding names that body's entry first, then the residual's: `Object extension of 'crm_line' is declared twice in \`objectExtensions\`: 'com.example.billing' (stack #2) objectExtensions[0] and stack #1 objectExtensions[0]. …`. Two residual `objectExtensions` entries for one object, also when another package body extends that object: a residual entry is now told from a body's flattened copy by value, not by target, so the two are one package's pair (they used to count as that body's copies and compose).
19+
- **Not refused (known gap).** A residual job that shares its name with a package body's job, with other content, still composes: it is read as that body's copy, and the boot holds two enabled jobs of the name and schedules neither.
20+
- **Wording.** The `jobs` finding at every door now says what the runtime does with the pair: `The runtime keys jobs by name: the metadata keeps only the last of these entries, and the job scheduler refuses a name two enabled jobs share, so when both are enabled neither runs.`
21+
- **Unchanged.** One residual extension for an object another package extends composes, and both register. A residual entry equal to a body's entry is that body's copy. Package-claimed extensions and a single residual job compose and boot as before.
22+
- **Installed artifacts.** A residual extension sharing its package's slot registers, the last one served, with one `error` line per object naming the entries. A residual extension now passes the registry's `extend` door as a package body's entry does, so one that door refuses (reachable only through `strict: false` or a hand-built artifact) now fails a boot that used to load and drop it.
23+
24+
One-line fix: declare each job name once; move a top-level extension into the package that owns it, or merge it into that package's own entry for the object.

‎packages/metadata/src/plugin.ts‎

Lines changed: 57 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -380,6 +380,52 @@ function claimedArtifactSlots(bodies: readonly unknown[]): (type: string, name:
380380
return (type, name) => owned.get(type)?.has(name) === true;
381381
}
382382

383+
/**
384+
* Whether a top-level `objectExtensions` entry of a stack that carries
385+
* `packages[]` is a package body's: a body carries an entry EQUAL to it by
386+
* value. An extension has no slot of its own (it is keyed by `extend`, and its
387+
* `name` spelling is a retired alias the schema refuses), so it is told from
388+
* the residual by what it holds, never by its target: the flattened top level
389+
* of a `composeStacks(…, { manifest: 'preserve' })` artifact repeats every
390+
* body's entry, and a built artifact has lost the references, but each copy
391+
* still holds exactly what its body's entry holds. An entry extending a target
392+
* some body also extends, with other fields, is the residual's own.
393+
*
394+
* Equal by value is also the case where nothing is lost: the body's entry
395+
* registers exactly what the copy holds. Keys set to `undefined` count as
396+
* absent, as `deepEqualAuthored` (`@objectstack/spec`) and the composition
397+
* door's mirror read them.
398+
*/
399+
function claimedArtifactExtensions(bodies: readonly unknown[]): (item: unknown) => boolean {
400+
const declared: unknown[] = [];
401+
for (const body of bodies) {
402+
const items = (body as any)?.objectExtensions;
403+
if (Array.isArray(items)) declared.push(...items);
404+
}
405+
return (item) => declared.some((entry) => entry === item || sameAuthoredValue(entry, item, 0));
406+
}
407+
408+
/** Structural equality of two authored values; keys holding `undefined` count as absent. */
409+
function sameAuthoredValue(a: unknown, b: unknown, depth: number): boolean {
410+
if (Object.is(a, b)) return true;
411+
if (depth >= 32 || typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false;
412+
if (Array.isArray(a) !== Array.isArray(b)) return false;
413+
if (Array.isArray(a) && Array.isArray(b)) {
414+
return a.length === b.length && a.every((v, i) => sameAuthoredValue(v, b[i], depth + 1));
415+
}
416+
const left = a as Record<string, unknown>;
417+
const right = b as Record<string, unknown>;
418+
const keys = Object.keys(left).filter((k) => left[k] !== undefined);
419+
if (keys.length !== Object.keys(right).filter((k) => right[k] !== undefined).length) return false;
420+
return keys.every((k) => sameAuthoredValue(left[k], right[k], depth + 1));
421+
}
422+
423+
/** The object an `objectExtensions` entry extends, or `undefined` when it names none. */
424+
function extensionTarget(item: unknown): string | undefined {
425+
const target = (item as { extend?: unknown } | null | undefined)?.extend;
426+
return typeof target === 'string' && target !== '' ? target : undefined;
427+
}
428+
383429
/** One top-level item of a multi-package stack that none of its package bodies declares. */
384430
export interface UnclaimedTopLevelItem {
385431
/** The stack collection the item sits in, e.g. `views`. */
@@ -419,7 +465,12 @@ export interface UnclaimedTopLevel {
419465
* An item is unclaimed when it occupies a registry slot (`artifactItemSlot`)
420466
* that no package body occupies (`claimedArtifactSlots`): a container is
421467
* compared on its own slot, every other item on its name. An item with no
422-
* derivable slot is registered by no door, so it is not listed.
468+
* derivable slot is registered by no door, so it is not listed — with one
469+
* exception: an `objectExtensions` entry, which has no slot, is listed (type
470+
* `object_extension`) when it names a target and no body carries an entry
471+
* equal to it (`claimedArtifactExtensions`). The metadata door registers no
472+
* extension, a body's or the residual's (it has no slot to file one under);
473+
* the engine registers the residual's under this id, as it does a body's.
423474
*
424475
* @returns `undefined` for a stack without `packages[]`: its top level IS its
425476
* one package's body, so it has no residual.
@@ -428,11 +479,16 @@ export function unclaimedTopLevel(stack: unknown): UnclaimedTopLevel | undefined
428479
if (!Array.isArray((stack as any)?.packages)) return undefined;
429480
const bodies = resolveArtifactPackageOrder(stack);
430481
const claimed = claimedArtifactSlots(bodies);
482+
const claimedExtension = claimedArtifactExtensions(bodies);
431483
const items: UnclaimedTopLevelItem[] = [];
432484
for (const [field, metaType] of Object.entries(ARTIFACT_FIELD_TO_TYPE)) {
433485
const collection = (stack as any)[field];
434486
if (!Array.isArray(collection)) continue;
435487
collection.forEach((item: unknown, index: number) => {
488+
if (metaType === 'object_extension') {
489+
if (extensionTarget(item) !== undefined && !claimedExtension(item)) items.push({ field, index, type: metaType, item });
490+
return;
491+
}
436492
const slot = artifactItemSlot(metaType, item);
437493
if (!slot) return;
438494
if (claimed(metaType, slot.container ? slot.object : slot.name)) return;
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [ADR-0130 D4] The residual rule (`unclaimedTopLevel`) lists a multi-package
5+
* stack's residual `objectExtensions` entries, so the engine registers them
6+
* under the stack's `manifest.id` as it registers the residual's objects.
7+
*
8+
* An extension has no slot (it is keyed by `extend`; its `name` is a retired
9+
* alias), so the rule used to list none, and no door registered one: measured
10+
* through `os serve` on main `c30ce97cd7`, a `composeStacks(…, { manifest:
11+
* 'preserve' })` artifact with an input that has no manifest served the target
12+
* without the extension's field (`INVALID_FIELD` on write) and logged nothing.
13+
*
14+
* It is told from a body's flattened copy by VALUE, never by target: the
15+
* flattened top level repeats every body's entry, a built artifact has lost the
16+
* references, and an entry extending a target some body also extends with other
17+
* fields is the residual's own.
18+
*/
19+
20+
import { describe, it, expect } from 'vitest';
21+
// Paid at collection, not inside a case's clocked window: `plugin.ts` loads it lazily.
22+
import '@objectstack/metadata-fs';
23+
import { composeStacks, defineStack } from '@objectstack/spec';
24+
import { unclaimedTopLevel } from './plugin.js';
25+
26+
const owner = { id: 'com.probe.owner', namespace: 'probe', name: 'probe', version: '1.0.0', type: 'module' as const };
27+
const other = { id: 'com.probe.other', namespace: 'probe', name: 'probe_other', version: '1.0.0', type: 'module' as const };
28+
const account = { name: 'probe_account', label: 'Account', sharingModel: 'private' as const, fields: { title: { type: 'text' as const, label: 'Title' } } };
29+
const extension = (field: string) => ({ extend: 'probe_account', fields: { [field]: { type: 'text' as const, label: field } } });
30+
31+
const residualExtensions = (stack: unknown) =>
32+
(unclaimedTopLevel(stack)?.items ?? [])
33+
.filter((entry) => entry.type === 'object_extension')
34+
.map((entry) => ({ field: entry.field, index: entry.index, target: (entry.item as { extend: string }).extend, fields: Object.keys((entry.item as { fields: object }).fields) }));
35+
36+
describe('unclaimedTopLevel lists a residual objectExtensions entry', () => {
37+
// `'preserve'` keeps the last manifest (owner's) as the residual's id, and
38+
// owner does not extend the target: the residual's entry has a slot of its own.
39+
const composed = () => composeStacks(
40+
[
41+
defineStack({ manifest: other, objectExtensions: [extension('other_note')] }),
42+
defineStack({ manifest: owner, objects: [account] }),
43+
defineStack({ objectExtensions: [extension('residual_note')] }),
44+
],
45+
{ manifest: 'preserve' },
46+
);
47+
48+
it('the manifest-less input\'s entry, as composed and as built JSON; never the body\'s flattened copy', () => {
49+
for (const [leg, stack] of [['composed', composed()], ['built', JSON.parse(JSON.stringify(composed()))]] as const) {
50+
expect(residualExtensions(stack), leg).toEqual([
51+
{ field: 'objectExtensions', index: 1, target: 'probe_account', fields: ['residual_note'] },
52+
]);
53+
expect(unclaimedTopLevel(stack)?.ownerId, leg).toBe(owner.id);
54+
}
55+
});
56+
57+
it('CONTROL: a stack whose every extension a body carries lists none', () => {
58+
const stack = composeStacks(
59+
[
60+
defineStack({ manifest: owner, objects: [account] }),
61+
defineStack({ manifest: other, objectExtensions: [extension('other_note')] }),
62+
defineStack({ pages: [{ name: 'probe_home', label: 'Home', type: 'app', regions: [] }] }),
63+
],
64+
{ manifest: 'preserve' },
65+
);
66+
expect((stack as unknown as { objectExtensions: unknown[] }).objectExtensions, 'anti-vacuity: the flattened copy is there').toHaveLength(1);
67+
expect(residualExtensions(stack)).toEqual([]);
68+
expect(residualExtensions(JSON.parse(JSON.stringify(stack)))).toEqual([]);
69+
});
70+
71+
it('CONTROL: a stack without packages[] has no residual', () => {
72+
expect(unclaimedTopLevel(defineStack({ manifest: owner, objects: [account], objectExtensions: [extension('x_note')] }))).toBeUndefined();
73+
});
74+
});

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

Lines changed: 49 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -125,8 +125,50 @@ function logSameTargetObjectExtensions(
125125
}
126126
}
127127

128+
/**
129+
* The partial object definition an `objectExtensions` entry registers as an
130+
* `extend` contribution to its target, and the priority it registers at — the
131+
* ONE reading of an entry, taken by a package body's entries
132+
* ({@link RegistrationFacet.registerApp} step 2b) and by a multi-package
133+
* stack's RESIDUAL entries (`ObjectQLPlugin`, ADR-0130 D4) alike.
134+
*
135+
* ⛔ Never a second literal at either caller: a key added here reaches both, so
136+
* a residual extension registers exactly what the same entry registers from a
137+
* package body (pinned by `manifest-service-residual-object-extension.test.ts`,
138+
* which compares the object both registrations serve).
139+
*/
140+
export function objectExtensionContribution(ext: any): {
141+
definition: {
142+
name: string; fields: unknown; fieldPatches: unknown; label: unknown; pluralLabel: unknown;
143+
description: unknown; validations: unknown; indexes: unknown; place: unknown;
144+
};
145+
priority: number;
146+
} {
147+
return {
148+
definition: {
149+
name: ext.extend, // Use the target FQN as name
150+
fields: ext.fields,
151+
// [ADR-0146 D10, second rule] The per-field display patches,
152+
// the slot as `ObjectExtensionSchema.fieldPatches` declares
153+
// it — applied by the registry's `mergeObjectDefinitions`,
154+
// whose fold every object read shares.
155+
fieldPatches: ext.fieldPatches,
156+
label: ext.label,
157+
pluralLabel: ext.pluralLabel,
158+
description: ext.description,
159+
validations: ext.validations,
160+
indexes: ext.indexes,
161+
// [#35901] Where its own fields, groups and child lists go —
162+
// applied by the registry fold after every contributor's
163+
// fields are merged (`applyExtensionPlacements`).
164+
place: ext.place,
165+
},
166+
priority: ext.priority ?? 200,
167+
};
168+
}
169+
128170
/** Structural equality of two JSON-shaped values: same primitives, same arrays in order, same keys with equal values. */
129-
function equalByValue(a: unknown, b: unknown): boolean {
171+
export function equalByValue(a: unknown, b: unknown): boolean {
130172
if (a === b) return true;
131173
if (a === null || b === null || typeof a !== 'object' || typeof b !== 'object') return false;
132174
if (Array.isArray(a) !== Array.isArray(b)) return false;
@@ -395,30 +437,13 @@ export class RegistrationFacet {
395437
// outcome is unchanged.
396438
logSameTargetObjectExtensions(this.logger, id, manifest.objectExtensions);
397439
for (const ext of manifest.objectExtensions) {
398-
const targetFqn = ext.extend;
399-
const priority = ext.priority ?? 200;
400-
// Create a partial object definition for the extension
401-
const extDef = {
402-
name: targetFqn, // Use the target FQN as name
403-
fields: ext.fields,
404-
// [ADR-0146 D10, second rule] The per-field display patches,
405-
// the slot as `ObjectExtensionSchema.fieldPatches` declares
406-
// it — applied by the registry's `mergeObjectDefinitions`,
407-
// whose fold every object read shares.
408-
fieldPatches: ext.fieldPatches,
409-
label: ext.label,
410-
pluralLabel: ext.pluralLabel,
411-
description: ext.description,
412-
validations: ext.validations,
413-
indexes: ext.indexes,
414-
// [#35901] Where its own fields, groups and child lists go —
415-
// applied by the registry fold after every contributor's
416-
// fields are merged (`applyExtensionPlacements`).
417-
place: ext.place,
418-
};
440+
// The partial object definition for the extension — the one
441+
// reading of an entry, shared with the residual's
442+
// ({@link objectExtensionContribution}).
443+
const { definition: extDef, priority } = objectExtensionContribution(ext);
419444
// Register as extension (namespace is undefined since we're targeting by FQN)
420-
this._registry.registerObject(stampPackage(extDef, id, version), id, undefined, 'extend', priority);
421-
this.logger.debug('Registered Object Extension', { target: targetFqn, priority, from: id });
445+
this._registry.registerObject(stampPackage(extDef as any, id, version), id, undefined, 'extend', priority);
446+
this.logger.debug('Registered Object Extension', { target: extDef.name, priority, from: id });
422447
}
423448
}
424449

0 commit comments

Comments
 (0)