Skip to content

Commit 69c9f7c

Browse files
fix(metadata-protocol): the per-package layer stamps a row with its own package's envelope, never another package's (#28831) (#28857)
<!-- claude-projects-attribution: {"github_login":"os-project-manager"} --> _Requested by **Leehom** · [project thread](https://claude.ai/code/project/chan_01TenzsRopZj4jMbvjX8uz1X?thread=cmsg_01TenzsRopZj4jMbvjX8uz1XUSbzmMRfCQ13hL4Jffkmqp)_ Fixes #28831 Clause-②: no Metadata-protocol: none Skills-docs: none — no file under `skills/**` teaches the per-package layer or its envelope (0 hits for `getMetaItemsPerPackage` and `per-package layer`). ## 维护者速读 - **改了什么**:「按包分层」读取(`getMetaItemsPerPackage`,包导出和匿名表单撤回层用它)里,一个包存在基础包条目名下的行,不再借用基础包的 `_packageId` / `_packageVersion` / `_provenance`。依赖包的行、`.custom` 配对包未声明覆盖的行,现在都标自己的包;配对包**声明了**覆盖的行照旧标基础包。 - **为什么改**:信封嫁接(#22024)在该包没有同名制品时,制品查找会退回到第一个发布该名字的代码包,于是把别人的行标成基础包的(#28828 合同审查发现)。 - **风险与回滚**:低。实测 CRM、showcase 新启动 0 行,`packages/qa/**` 0 行;导出会去掉所有 `_` 开头的键,表单撤回按视图名判断,两个读者都不读这个标记,所以没有公开门的答复变化。共享的制品查找(`registry.getArtifactItem` 的回退)对其它调用者不变。回滚即 revert。 - **先看**:`packages/metadata-protocol/src/protocol.ts` 的 `perPackageLayerEnvelope` 和 `readFlattenedMetaItems` 里 `[#28831]` 那一处;`packages/objectql/src/protocol-per-package-layer-provenance.test.ts`。 - **两分钟验证**:先 `pnpm --filter @objectstack/metadata-protocol build`,再 `pnpm --filter @objectstack/objectql exec vitest run src/protocol-per-package-layer-provenance.test.ts`,预期 `Tests 4 passed (4)`(main 上 2 红,2 条对照两边都绿)。 - **需要你做的**:无,席位落地。 ## What changes - **The graft on the per-package layer** (`readFlattenedMetaItems`, `layer: 'per-package'`). After the artifact is looked up at the item's package (`envelopePackageId`, unchanged), `perPackageLayerEnvelope` keeps it only when it is that package's OWN artifact (`_packageId` equal to the item's bound package). Otherwise the item wears no artifact envelope and keeps its own binding. - **The one exception keeps today's stamp:** a stored row of the item's package that is the served override of the artifact's package. It is judged by `isServedOverrideRowOf` on the row's own `package_id` (never a body `_packageId`), at the item's bundle member, over the active rows the read already holds for the lock (`lockRowsByName`). - **An item bound to no package** keeps the lookup's answer, as before (a package-less row standing in for a base's slot is seated with the base's id by the merge, so it matches its own package anyway). - **Not touched:** `lookupArtifactItem` / `registry.getArtifactItem` and their fallback for every other caller; the effective list, the by-name read and the execution list (the new call is inside `layer === 'per-package'` only); the two readers. No new error code, no `packages/spec/**`, no new gate. - **Changeset** `.changeset/28831-per-package-layer-own-envelope.md`: `patch` on `@objectstack/metadata-protocol`, both declaration lines. **Why `Clause-②: no`.** Measured through the real doors (step 1 below): the package export drops every `_`-prefixed key before it answers, and the anonymous form doors' withdrawal judgement (`anonymousFormIntakeWithdrawnIn`) matches by view name and reads no stamp. So the stamp this changes is on an internal layer only, and no public door's served answer moves. ## Tests New `packages/objectql/src/protocol-per-package-layer-provenance.test.ts`, 4 tests, on the real protocol over the real `ObjectQL` engine and an in-memory driver (the harness of #28828's `protocol-bundle-member-base-address.test.ts`, whose view control it sits beside). Legacy rows are laid down as stored before the override write gate, the way that control does. Each case asserts `[columns, _packageId, _packageVersion, _provenance]` row by row. - **The withdrawal layer's read (unscoped):** the base's view reads `com.example.showcase · 1.0.0 · package`; a dependent's row under the same name reads its own package with no artifact envelope; the pair's undeclared row reads the pair. - **CONTROL:** the pair's declared override keeps the base's envelope, beside the base's own view. - **The export's read (scoped to each package):** the dependent's layer reads the dependent, the pair's reads the pair, the base's reads the base. - **CONTROL:** the pair's scoped layer keeps the base's envelope on its declared override. - **The form withdrawal leg at the door** is not pinned separately: the door reaches the layer (step 1: a dependent's withdrawal closes `/forms/contact-us`, 200 → 404), but its answer reads no stamp, so no door assertion can be red on base. The layer read it asks is the first case. <details><summary>Red on base, green on head; ablation</summary> - **Base** (`protocol.ts` from `1920e480`, the new file at head, metadata-protocol rebuilt): `Tests 2 failed | 2 passed (4)`. Both reds are the dependent's and the pair's rows reading `com.example.showcase · 1.0.0 · package`. The two declared-override controls are green both ways. Restored with `git checkout HEAD -- protocol.ts`, `git diff HEAD` empty, rebuilt. - **Head:** `Tests 4 passed (4)`. - **Ablation** via `node scripts/ablation-replace.mjs` from committed HEAD: the graft's condition `if (layer === 'per-package') {` replaced with `if (layer === 'per-package' && (globalThis as any).ABLATE_28831 === 1) {` (the fallback restored), anchor 1 → 0, blob `17bb3db36eed` → `393a0475ef93`; metadata-protocol rebuilt; `Tests 2 failed | 2 passed (4)`, the same two. Restored: blob == HEAD `17bb3db36eed`, `git diff HEAD` empty. </details> ## Acceptance notes - **Step 1 measurement:** `pm-orders/server/28831-step1-measurement.md` in the project files. A temporary census probe at the graft (never committed), run over the full dogfood battery and the objectql, rest, runtime and metadata-protocol suites: fresh CRM and showcase boots 0 rows, `packages/qa/**` seed sites 0 rows, and 3 unit-test fixtures that lay legacy rows down on purpose. No `object` item reached it. No reader depends on the base's stamp, so the order's stop condition did not hold. - **The export leg is pinned at the read the export asks** (`getMetaItemsPerPackage({ type, packageId })`), not at the door: the door's manifest carries no `_` key, so its body is the same on base and head. - **A draft preview** (`previewDrafts`) on the per-package layer is not covered: the exception reads active rows. Neither reader asks for drafts. ## Verification All readings at head `c7b62f42` (the fix `b7f9b13e`, changeset `533db7df`, merged once with `origin/main` `7f4cbc9d`, a clean merge). Full `pnpm turbo run build --concurrency=2` at the head: 118/118. <details><summary>Package suites, typecheck, lint</summary> - `@objectstack/metadata-protocol` test: `Tests 22093 passed | 26 skipped`, lock VERDICT command-exit 0. - `@objectstack/objectql` test: `Tests 10015 passed`, command-exit 0. - `@objectstack/rest` test: `Tests 6920 passed | 332 skipped`, command-exit 0. - `@objectstack/runtime` test: `Tests 8252 passed | 19 skipped`, command-exit 0. - `typecheck` of metadata-protocol and objectql (objectql's test layer included): exit 0. - `eslint --no-inline-config` on the two touched source files: exit 0; the repo's `pnpm lint` command scoped to `packages/metadata-protocol` and `packages/objectql`: exit 0. </details> <details><summary>Derived gates (`dispatch-gates.mjs --commands`, 62 families)</summary> - All 62 exit 0 at `c7b62f42`; `dispatch-gates --ran`: `62 derived, 62 run, 0 NOT-MEASURED, 0 UNRUN`. Record: `pm-orders/server/28831-gates-ran.txt`. - `check:type-check-debt`: OK, `--re-measure: OK`. - Repo-wide `pnpm lint` and the CI-only families are CI's; see the PR's check-runs. </details> <details><summary>Full dogfood battery (not owed: no `!` and no narrowing arm; run anyway)</summary> - Head `c7b62f42`: `Test Files 4 failed | 376 passed | 3 skipped (383)`, `Tests 4 failed | 3123 passed | 28 skipped (3155)`. - **The 4 failures are main's, not this PR's.** They are the 18.0 upgrade-harness files `audit-key-material`, `audit-mail-bodies`, `identity-mail-read-gate` and `upgrade-18x-harness`. Re-run alone on the head: the same 4 red. Re-run with `protocol.ts` checked out from `origin/main` and metadata-protocol rebuilt: the same 4 red (restored, `git diff HEAD` empty). `main`'s own push run at `7f4cbc9d` (CI run `41366661242`) has every Dogfood Regression Gate shard red, with `identity-mail-read-gate` named in shard 2's log. - The battery was green (3121 passed, 0 failed) at the pre-merge base `1920e480` during the step 1 census run. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01FEkQ5mTYb1BTJNRqf3bdJ8)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 45efba2 commit 69c9f7c

3 files changed

Lines changed: 355 additions & 1 deletion

File tree

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
'@objectstack/metadata-protocol': patch
3+
---
4+
5+
fix(metadata-protocol): the per-package layer stamps a row with its own package's envelope, never another package's (#28831)
6+
7+
Clause-②: no — the stamp is on the per-package layer (`getMetaItemsPerPackage`), which no door serves as it is: the package export drops every `_`-prefixed key, and the anonymous form doors' withdrawal judgement matches by view name. No accept set, export or served answer moves.
8+
Metadata-protocol: none
9+
10+
`getMetaItemsPerPackage` seats each stored row under its own package, and the #22024 envelope graft looked up the item's artifact at that package. When the package ships no artifact of the name, the artifact lookup falls back to the first code package that does, so a dependent package's row, or a `.custom` pair's undeclared row, under a base item's name read the base's `_packageId`, `_packageVersion` and `_provenance`.
11+
12+
- **Now.** On the per-package layer an item bound to a package wears its own package's artifact envelope, or none.
13+
- **Kept.** A `.custom` pair's declared override keeps the base's envelope it is served under, judged by `isServedOverrideRowOf` on the row's own `package_id` at the item's bundle member. An item bound to no package keeps the lookup's answer.
14+
- **Unchanged.** The artifact lookup (`registry.getArtifactItem` and its fallback) for every other caller, and every other read: the effective list, the by-name read and the execution list.

‎packages/metadata-protocol/src/protocol.ts‎

Lines changed: 59 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2595,6 +2595,56 @@ function envelopePackageId(requestedPackageId: string | undefined, served: unkno
25952595
return requestedPackageId ?? (served as { _packageId?: string } | null | undefined)?._packageId;
25962596
}
25972597

2598+
/**
2599+
* [#28831, #22024, ADR-0146 D8] The artifact envelope an item of the
2600+
* per-package layer ({@link ObjectStackProtocolImplementation.getMetaItemsPerPackage})
2601+
* wears: the artifact the read looked up at the item's package
2602+
* ({@link envelopePackageId}) when it is that package's OWN, else none.
2603+
*
2604+
* The artifact lookup falls back to the first code package that ships the
2605+
* name when the item's package ships none (`registry.getArtifactItem`'s
2606+
* any-composite tier). On the effective read that is how a package-less row
2607+
* standing in for a base wears the base's envelope. On the per-package layer
2608+
* every row is seated under its own package, so the fallback stamped a
2609+
* dependent package's row, or a `.custom` pair's undeclared row, under a base
2610+
* item's name with the BASE's `_packageId`, `_packageVersion` and
2611+
* `_provenance`: the export and the anonymous form doors' withdrawal layer
2612+
* read it as the base's.
2613+
*
2614+
* One exception keeps today's stamp: a stored row of the item's package that
2615+
* is the served override of the artifact's package, judged by
2616+
* {@link isServedOverrideRowOf} on the row's own `package_id` (never a body
2617+
* `_packageId`) at the item's own bundle member. It is served as its base's
2618+
* item, under its base's envelope.
2619+
*
2620+
* An item bound to no package (`boundPackageOf` answers `undefined`) keeps
2621+
* the lookup's answer, as before. ⛔ The lookup itself is not narrowed: its
2622+
* other callers rely on the fallback.
2623+
*/
2624+
function perPackageLayerEnvelope(
2625+
type: string,
2626+
item: unknown,
2627+
itemPackageId: string | undefined,
2628+
artifact: unknown,
2629+
rowsOfName: readonly any[],
2630+
): unknown {
2631+
if (artifact === undefined || artifact === null || typeof artifact !== 'object') return artifact;
2632+
const own = boundPackageOf(itemPackageId);
2633+
if (own === undefined) return artifact;
2634+
const lender = (artifact as { _packageId?: unknown })._packageId;
2635+
if (lender === own) return artifact;
2636+
const member = bundleMemberOf(type, item);
2637+
const declared = rowsOfName.some((row) => {
2638+
if (row?.package_id !== own || !isServedOverrideRowOf(row, lender)) return false;
2639+
try {
2640+
return bundleMemberOf(type, storedRowDocument(row)) === member;
2641+
} catch {
2642+
return false;
2643+
}
2644+
});
2645+
return declared ? artifact : undefined;
2646+
}
2647+
25982648
/**
25992649
* [#22057] The package a body is bound to, when it is bound to one: a
26002650
* non-empty id that is not the `'sys_metadata'` sentinel a package-less row
@@ -10793,7 +10843,15 @@ export class ObjectStackProtocolImplementation implements
1079310843
const itemPackageId = envelopePackageId(packageId, it);
1079410844
// [#23074] …and to the item's own bundle member, whose artifact
1079510845
// alone may lend it an envelope ({@link mergeArtifactProtection}).
10796-
const a = this.lookupArtifactItem(request.type, itemName, itemPackageId, bundleMemberOf(request.type, it));
10846+
let a = this.lookupArtifactItem(request.type, itemName, itemPackageId, bundleMemberOf(request.type, it));
10847+
// [#28831] …and on the per-package layer, an item bound to a
10848+
// package wears ITS OWN package's artifact envelope, or none
10849+
// ({@link perPackageLayerEnvelope}): never another package's, which
10850+
// the lookup falls back to when the item's package ships no
10851+
// artifact of the name.
10852+
if (layer === 'per-package') {
10853+
a = perPackageLayerEnvelope(request.type, it, itemPackageId, a, lockRowsByName.get(String(itemName)) ?? []);
10854+
}
1079710855
let itemLock: ItemLock | undefined;
1079810856
if (typeof itemName === 'string' && (it as any)?._draft !== true) {
1079910857
const address: ItemAddress = {
Lines changed: 282 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,282 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#28831, #22024, ADR-0146 D8] The per-package layer
5+
* (`getMetaItemsPerPackage`) stamps each item with ITS OWN package's
6+
* envelope, or with none: a stored row bound to a package that ships no
7+
* artifact of the name never takes another package's `_packageId`,
8+
* `_packageVersion` or `_provenance` through the artifact lookup's fallback
9+
* to the first code package that ships the name. A `.custom` pair's declared
10+
* override keeps the stamp it is served under (its base's), judged by
11+
* `isServedOverrideRowOf` on the row's own `package_id`.
12+
*
13+
* Two readers ask this layer: the anonymous form doors' withdrawal layer
14+
* (unscoped) and the package export (scoped to the exported package). Both
15+
* reads are pinned here, row by row, beside PR #28828's view control in
16+
* `protocol-bundle-member-base-address.test.ts`. The doors themselves read no
17+
* stamp (the withdrawal judgement matches by name, and the export drops every
18+
* `_` key), so the layer is where the stamp is pinned.
19+
*
20+
* Harness: the real protocol over the real `ObjectQL` engine and an in-memory
21+
* driver (copied from `protocol-bundle-member-base-address.test.ts`). Rows the
22+
* override write gate refuses today are laid down as stored before it: the
23+
* same door with the gate's verdict held at `not_concerned` for that write.
24+
*
25+
* Test-path resolution: the protocol is `@objectstack/metadata-protocol`'s
26+
* `dist/`, so a change there is read here after that package is rebuilt.
27+
*/
28+
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
29+
import type { ServiceObject } from '@objectstack/spec/data';
30+
import { ObjectStackProtocolImplementation, resetEnvWritableMetadataTypes } from '@objectstack/metadata-protocol';
31+
import { SysMetadataAuditObject, SysMetadataCommitObject, SysMetadataHistoryObject } from '@objectstack/metadata-core';
32+
import { ObjectQL } from './engine.js';
33+
34+
const BASE = 'com.example.showcase';
35+
const PAIR = 'com.example.showcase.custom';
36+
const DEPENDENT = 'com.default.acme-addon';
37+
/** A view item the base ships (its container expands it). */
38+
const VIEW = 'showcase_task.default';
39+
const BASE_COLUMNS = ['title', 'status'];
40+
const DECLARATION = { package: BASE, basedOn: '1.0.0' };
41+
/** The base's artifact envelope: `_packageId`, `_packageVersion`, `_provenance`. */
42+
const BASE_ENVELOPE = [BASE, '1.0.0', 'package'] as const;
43+
44+
const sysMetadataObject: ServiceObject = {
45+
name: 'sys_metadata',
46+
label: 'System Metadata',
47+
fields: {
48+
id: { name: 'id', label: 'ID', type: 'text' as const },
49+
type: { name: 'type', label: 'Type', type: 'text' as const, required: true },
50+
name: { name: 'name', label: 'Name', type: 'text' as const, required: true },
51+
organization_id: { name: 'organization_id', label: 'Org', type: 'text' as const },
52+
package_id: { name: 'package_id', label: 'Package', type: 'text' as const },
53+
bundle_member: { name: 'bundle_member', label: 'Bundle Member', type: 'text' as const, maxLength: 100 },
54+
metadata: { name: 'metadata', label: 'Body', type: 'textarea' as const },
55+
draft_changes: { name: 'draft_changes', label: 'Draft Changes', type: 'textarea' as const },
56+
checksum: { name: 'checksum', label: 'Checksum', type: 'text' as const, maxLength: 71 },
57+
state: { name: 'state', label: 'State', type: 'text' as const },
58+
version: { name: 'version', label: 'Version', type: 'number' as const },
59+
created_at: { name: 'created_at', label: 'Created', type: 'datetime' as const },
60+
updated_at: { name: 'updated_at', label: 'Updated', type: 'datetime' as const },
61+
},
62+
};
63+
64+
function makeMemoryDriver() {
65+
const stores = new Map<string, Map<string, Record<string, unknown>>>();
66+
const storeFor = (obj: string) => {
67+
let s = stores.get(obj);
68+
if (!s) { s = new Map(); stores.set(obj, s); }
69+
return s;
70+
};
71+
let nextId = 0;
72+
const matchesWhere = (row: Record<string, unknown>, where: any): boolean => {
73+
if (!where || typeof where !== 'object') return true;
74+
for (const [k, v] of Object.entries(where)) {
75+
if (k === '$and' && Array.isArray(v)) {
76+
if (!v.every((w: any) => matchesWhere(row, w))) return false;
77+
continue;
78+
}
79+
if (k === '$or' && Array.isArray(v)) {
80+
if (!v.some((w: any) => matchesWhere(row, w))) return false;
81+
continue;
82+
}
83+
if (k.startsWith('$')) continue;
84+
const rowVal = row[k];
85+
if (v && typeof v === 'object' && Array.isArray((v as any).$in)) {
86+
if (!(v as any).$in.includes(rowVal === undefined ? null : rowVal)) return false;
87+
continue;
88+
}
89+
const expected = (v && typeof v === 'object' && '$eq' in (v as any)) ? (v as any).$eq : v;
90+
const a = rowVal === undefined ? null : rowVal;
91+
const b = expected === undefined ? null : expected;
92+
if (a !== b) return false;
93+
}
94+
return true;
95+
};
96+
const driver: any = {
97+
name: 'memory', version: '0.0.0', supports: {} as any,
98+
async connect() {}, async disconnect() {}, async checkHealth() { return true; },
99+
async execute() { return null; },
100+
async find(object: string, ast: any) {
101+
const rows = Array.from(storeFor(object).values()).filter((r) => matchesWhere(r, ast?.where));
102+
return typeof ast?.limit === 'number' ? rows.slice(0, ast.limit) : rows;
103+
},
104+
async findOne(object: string, ast: any) {
105+
for (const r of storeFor(object).values()) if (matchesWhere(r, ast?.where)) return r;
106+
return null;
107+
},
108+
async create(object: string, data: Record<string, unknown>) {
109+
nextId += 1;
110+
const id = (data.id as string) ?? `r_${nextId}`;
111+
const row = { ...data, id };
112+
storeFor(object).set(id, row);
113+
return row;
114+
},
115+
async update(object: string, id: string, data: Record<string, unknown>) {
116+
const s = storeFor(object);
117+
const cur = s.get(id);
118+
if (!cur) throw new Error(`not found: ${object}/${id}`);
119+
const updated = { ...cur, ...data, id };
120+
s.set(id, updated);
121+
return updated;
122+
},
123+
async upsert(object: string, data: Record<string, unknown>) {
124+
const id = data.id as string | undefined;
125+
if (id && storeFor(object).has(id)) return this.update(object, id, data);
126+
return this.create(object, data);
127+
},
128+
async delete(object: string, id: string) { return storeFor(object).delete(id); },
129+
async count(object: string, ast: any) { return (await this.find(object, ast)).length; },
130+
async bulkCreate(object: string, rows: Record<string, unknown>[]) {
131+
return Promise.all(rows.map((r) => this.create(object, r)));
132+
},
133+
async bulkUpdate() { return []; }, async bulkDelete() {},
134+
async beginTransaction() { return { commit: async () => {}, rollback: async () => {} }; },
135+
async commit() {}, async rollback() {},
136+
};
137+
return { driver, stores };
138+
}
139+
140+
function baseManifest(): Record<string, unknown> {
141+
return {
142+
id: BASE,
143+
name: 'showcase',
144+
version: '1.0.0',
145+
namespace: 'showcase',
146+
objects: [{
147+
name: 'showcase_task',
148+
label: 'Task',
149+
sharingModel: 'private',
150+
fields: Object.fromEntries(BASE_COLUMNS.map((f) => [f, { name: f, label: f, type: 'text' }])),
151+
}],
152+
views: [{
153+
object: 'showcase_task',
154+
list: {
155+
label: 'All Tasks',
156+
type: 'grid',
157+
data: { provider: 'object', object: 'showcase_task' },
158+
columns: BASE_COLUMNS.map((field) => ({ field })),
159+
},
160+
}],
161+
};
162+
}
163+
164+
async function boot() {
165+
const engine = new ObjectQL();
166+
const { driver } = makeMemoryDriver();
167+
engine.registerDriver(driver, true);
168+
await engine.init();
169+
engine.registry.registerObject(sysMetadataObject, 'test-package');
170+
for (const o of [SysMetadataHistoryObject, SysMetadataAuditObject, SysMetadataCommitObject]) {
171+
engine.registry.registerObject(o as any, 'test-package');
172+
}
173+
engine.registerApp(baseManifest());
174+
const protocol = new ObjectStackProtocolImplementation(engine, () => new Map());
175+
return { engine, protocol };
176+
}
177+
178+
const savedWritable = process.env.OS_METADATA_WRITABLE;
179+
beforeEach(() => {
180+
delete process.env.OS_METADATA_WRITABLE;
181+
ObjectStackProtocolImplementation.resetEnvWritableCache();
182+
resetEnvWritableMetadataTypes();
183+
});
184+
afterEach(() => {
185+
if (savedWritable === undefined) delete process.env.OS_METADATA_WRITABLE;
186+
else process.env.OS_METADATA_WRITABLE = savedWritable;
187+
ObjectStackProtocolImplementation.resetEnvWritableCache();
188+
resetEnvWritableMetadataTypes();
189+
});
190+
191+
/** Installs a writable package through the package door (the pair as its ensure door writes it). */
192+
async function install(protocol: ObjectStackProtocolImplementation, id: string): Promise<void> {
193+
await (protocol as any).installPackage({
194+
manifest: {
195+
id, name: id.split('.').join('-'), version: '0.1.0', type: 'app',
196+
...(id === PAIR
197+
? { namespace: 'showcase_custom', dependencies: { [BASE]: '^1' } }
198+
: { dependencies: { [BASE]: '*' } }),
199+
},
200+
});
201+
}
202+
203+
const viewBody = (columns: readonly string[], extra: Record<string, unknown> = {}) => ({
204+
name: VIEW, object: 'showcase_task', viewKind: 'list', label: 'All Tasks',
205+
config: { type: 'grid', data: { provider: 'object', object: 'showcase_task' }, columns: columns.map((field) => ({ field })) },
206+
...extra,
207+
});
208+
209+
/** A draft save naming the package, then the per-item publish, the override write gate held for a legacy row. */
210+
async function store(
211+
protocol: ObjectStackProtocolImplementation, packageId: string, item: Record<string, unknown>, legacy: boolean,
212+
): Promise<void> {
213+
const gated = protocol as any;
214+
if (legacy) gated.overrideWriteVerdict = () => ({ verdict: 'not_concerned' });
215+
try {
216+
await protocol.saveMetaItem({ type: 'view', name: VIEW, item, mode: 'draft', packageId } as any);
217+
await protocol.publishMetaItem({ type: 'view', name: VIEW, packageId } as any);
218+
} finally {
219+
if (legacy) delete gated.overrideWriteVerdict;
220+
}
221+
}
222+
223+
/**
224+
* The per-package layer's items of `VIEW`, as `[columns, _packageId, _packageVersion, _provenance]`,
225+
* by columns. Unscoped: the anonymous form doors' withdrawal layer. Scoped: the package export's read.
226+
*/
227+
const layer = async (protocol: ObjectStackProtocolImplementation, packageId?: string) =>
228+
(((await (protocol as any).getMetaItemsPerPackage({ type: 'view', ...(packageId ? { packageId } : {}) })) as any).items as any[])
229+
.filter((i) => i?.name === VIEW)
230+
.map((i) => [
231+
(i?.config?.columns ?? i?.columns ?? []).map((c: any) => c?.field ?? c).join(','),
232+
i._packageId ?? null, i._packageVersion ?? null, i._provenance ?? null,
233+
])
234+
.sort((a, b) => String(a[0]).localeCompare(String(b[0])));
235+
236+
describe('[#28831] the per-package layer stamps each row with its own package', () => {
237+
it('a dependent\'s and a pair\'s undeclared row under a base view name read their own package; the base\'s view reads the base', async () => {
238+
const { protocol } = await boot();
239+
await install(protocol, PAIR);
240+
await install(protocol, DEPENDENT);
241+
await store(protocol, PAIR, viewBody(['title']), true);
242+
await store(protocol, DEPENDENT, viewBody(['status']), true);
243+
244+
const rows = await layer(protocol);
245+
expect(rows).toEqual([
246+
['status', DEPENDENT, null, null],
247+
['title', PAIR, null, null],
248+
['title,status', ...BASE_ENVELOPE],
249+
]);
250+
});
251+
252+
it('control: the pair\'s declared override keeps the stamp it is served under, the base\'s', async () => {
253+
const { protocol } = await boot();
254+
await install(protocol, PAIR);
255+
await store(protocol, PAIR, viewBody(['title'], { overrides: DECLARATION }), false);
256+
257+
const rows = await layer(protocol);
258+
expect(rows).toEqual([
259+
['title', ...BASE_ENVELOPE],
260+
['title,status', ...BASE_ENVELOPE],
261+
]);
262+
});
263+
264+
it('the export\'s read: each package\'s scoped layer carries its own provenance, never the base\'s', async () => {
265+
const { protocol } = await boot();
266+
await install(protocol, PAIR);
267+
await install(protocol, DEPENDENT);
268+
await store(protocol, PAIR, viewBody(['title']), true);
269+
await store(protocol, DEPENDENT, viewBody(['status']), true);
270+
expect(await layer(protocol, DEPENDENT)).toEqual([['status', DEPENDENT, null, null]]);
271+
expect(await layer(protocol, PAIR)).toEqual([['title', PAIR, null, null]]);
272+
expect(await layer(protocol, BASE)).toEqual([['title,status', ...BASE_ENVELOPE]]);
273+
});
274+
275+
it('control: the pair\'s scoped layer keeps the base\'s stamp on its declared override', async () => {
276+
const { protocol } = await boot();
277+
await install(protocol, PAIR);
278+
await store(protocol, PAIR, viewBody(['title'], { overrides: DECLARATION }), false);
279+
280+
expect(await layer(protocol, PAIR)).toEqual([['title', ...BASE_ENVELOPE]]);
281+
});
282+
});

0 commit comments

Comments
 (0)