Skip to content

Commit 5c135f4

Browse files
committed
wip(spec,objectql): one owner-stamp judge for a collection item's _packageId
Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017ihL2fi9zfJhUTubyJYb6V
1 parent f23e051 commit 5c135f4

4 files changed

Lines changed: 248 additions & 12 deletions

File tree

‎packages/objectql/src/engine.ts‎

Lines changed: 18 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,7 @@ import { buildDriverOptions, driverReadScope, driverWriteTarget, engineLayer0Ver
157157
// methods of the same names below hand each body the members it reads (`MigrationFlagsHost`).
158158
import { announceOpenMigrationGates, isOrganizationOwnershipCertified, isValueShapesMigrationVerified, noteAdmittedValueShapeViolation, readFileReferencesFlagRow, readMigrationFlagVerified, supplyTenantKeyCertifiedResolver, wasDatastoreCreatedFromEmpty } from './engine-migration-flags.js';
159159
import { ExecutionContext, ExecutionContextSchema, type InstalledPackageSource } from '@objectstack/spec/kernel';
160-
import { isStoredMetadataBodyObject } from '@objectstack/spec/kernel';
160+
import { isStoredMetadataBodyObject, judgeCollectionItemOwnerStamp } from '@objectstack/spec/kernel';
161161
// [#27884] The stored-row read gate, registered on the family's tables below.
162162
import { STORED_METADATA_TYPE_READ_GATE_OBJECTS, storedMetadataTypeReadGate } from './stored-metadata-type-read-gate.js';
163163
import type { FlowFunctionEffect } from '@objectstack/spec/automation';
@@ -4859,6 +4859,15 @@ function noteRegistrationStamp(item: unknown, stampBefore: unknown): void {
48594859
* neither is overwritten by `applyProtection`, so either would survive as an
48604860
* owner no row answers.
48614861
*
4862+
* The judgement and its words are the one judge both doors of the rule call,
4863+
* `judgeCollectionItemOwnerStamp` (`@objectstack/spec/kernel`, whose header
4864+
* holds the verdict table and the collections): the stack schema runs it at
4865+
* the build door (`defineStack`, `os validate`, `os build`, the artifact door's
4866+
* parse), so this seam is the door for a body no schema parse judged — an
4867+
* installed body, a programmatic `registerApp`, a nested plugin, a
4868+
* `strict: false` stack. ⛔ Never a second comparison here. What stays here is
4869+
* the exemption below, which is this process's state, not a body rule.
4870+
*
48624871
* `VALIDATION_ERROR` / 400, `issues[]` at `_packageId`: the envelope of
48634872
* {@link permissionSetOwnerRegistrationRefusal}. Exported for the stack's
48644873
* RESIDUAL registration (`registerUnclaimedTopLevelItems` in `plugin.ts`),
@@ -4884,16 +4893,14 @@ export function collectionItemOwnerStampRefusal(
48844893
name: string,
48854894
ownerId: string | undefined,
48864895
): (Error & { code: 'VALIDATION_ERROR'; status: 400; httpStatus: 400; issues: Array<{ path: string; message: string; code: string }> }) | undefined {
4887-
if (!item || typeof item !== 'object') return undefined;
4888-
const stamped = (item as { _packageId?: unknown })._packageId;
4889-
if (stamped === undefined || stamped === ownerId) return undefined;
4890-
if (REGISTRATION_WRITTEN_STAMPS.get(item) === stamped) return undefined;
4891-
const owner = ownerId === undefined ? 'no package' : `package '${ownerId}'`;
4892-
const issueMessage = `carries _packageId ${JSON.stringify(stamped)}, but it is registered under ${owner}`;
4893-
const err = new Error(
4894-
`Drop \`_packageId\` from ${type} '${name}': it ${issueMessage}. The package an item belongs to is the one `
4895-
+ 'that registers it, stamped by the registration; a body never names its own owner.',
4896-
) as Error & {
4896+
if (item && typeof item === 'object') {
4897+
const stamped = (item as { _packageId?: unknown })._packageId;
4898+
if (stamped !== undefined && REGISTRATION_WRITTEN_STAMPS.get(item) === stamped) return undefined;
4899+
}
4900+
const refusal = judgeCollectionItemOwnerStamp(item, type, name, ownerId, 'register');
4901+
if (!refusal) return undefined;
4902+
const issueMessage = refusal.issueMessage;
4903+
const err = new Error(refusal.message) as Error & {
48974904
code: 'VALIDATION_ERROR'; status: 400; httpStatus: 400; issues: Array<{ path: string; message: string; code: string }>;
48984905
};
48994906
err.code = 'VALIDATION_ERROR';
Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,144 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [ADR-0010] The owner-stamp judge for a collection item's `_packageId`: ONE
5+
* comparison and ONE set of words, called by every door that files a
6+
* collection item under a package.
7+
*
8+
* ## The rule
9+
*
10+
* `_packageId` is the ADR-0010 envelope stamp: the package that REGISTERS the
11+
* item, written by the registration (`applyProtection`, which writes the key
12+
* only while it is unset). Every item schema that spreads
13+
* `MetadataProtectionFields` declares the key, so a body could arrive wearing
14+
* another package's id, or an id no package holds, and keep it: every reader
15+
* that asks an item's owner (whose package root a connector's file ref
16+
* resolves against, the disabled-package filter, the artifact gates) then read
17+
* a stamp the body wrote about itself. A body never names its own owner, so
18+
* the stamp is refused, with a prescription.
19+
*
20+
* | body `_packageId` | the owner | verdict |
21+
* |:--|:--|:--|
22+
* | absent (`undefined`) | anything | accepted: an absent key declares nothing |
23+
* | `'P'` | `'P'` | accepted: what an item re-registered under its own package carries |
24+
* | `'Q'` | `'P'` | refused |
25+
* | any value, `null` and `''` included | none | refused |
26+
* | `null` or `''` | `'P'` | refused: `applyProtection` overwrites neither, so either would survive as an owner no row answers |
27+
*
28+
* The comparison is strict equality against the owner as the door passes it:
29+
* the registration door's own normalisation (`id || name`) is the door's, and
30+
* a stamp of another type than string is judged like any other foreign value
31+
* (the build door's item schemas refuse it first, with their own located
32+
* issue, since `_packageId` is declared `z.string()`).
33+
*
34+
* ## The doors, and why the judge lives in this package
35+
*
36+
* | door | caller | the owner it passes |
37+
* |:--|:--|:--|
38+
* | `build` | the stack schema's refinement (`ObjectStackDefinitionSchema`, `stack.zod.ts`): `defineStack`, `os validate`, `os build`, the artifact door's parse | the stack's `manifest.id` (none without a manifest); each `packages[]` body's own `id` |
39+
* | `register` | `ObjectQL.registerApp`'s collection loop, its seed datasets and its `viewItems:` channel, and the `manifest` service's residual registration (`@objectstack/objectql`) | the package id it registers under |
40+
*
41+
* `@objectstack/spec` is the one layer both callers already depend on, so the
42+
* judge lives here and nowhere else. ⛔ Do not write a second comparison at a
43+
* door: two doors spelling one rule differently is how one comes to accept
44+
* what the other refuses. What stays at the registration door is process
45+
* state, not a body rule: a stamp a registration of this process wrote onto
46+
* the caller's own object is exempt there, because no body wrote it.
47+
*
48+
* ## Which collections
49+
*
50+
* {@link OWNER_STAMP_JUDGED_COLLECTIONS}: the stack collections whose items the
51+
* registration door files through `registerItem` and judges, the seed `data`
52+
* datasets included. The build door judges exactly these, so it refuses what
53+
* the boot refuses and nothing the boot accepts. An objectql test holds the
54+
* list equal to what `registerApp` refuses, key by key.
55+
*
56+
* ## The words
57+
*
58+
* Pure: it builds no error and throws nothing. Each door wraps
59+
* {@link CollectionItemOwnerStampRefusal} in its own envelope: the build door
60+
* as a schema issue at the item's `_packageId`, the registration door as
61+
* ADR-0112's `VALIDATION_ERROR` / 400 with `issues[]` at `_packageId`. The
62+
* message prescribes first, because a 4xx message crosses the REST boundary
63+
* bounded at 500 characters with its tail truncated. The two doors' words
64+
* differ only in the clause that names where the owner comes from. Runtime
65+
* words carry no tracker number.
66+
*/
67+
68+
/** The door judging the item: where its owner comes from. */
69+
export type CollectionItemOwnerStampDoor = 'build' | 'register';
70+
71+
/** A disagreement, in the words every door shows it with. */
72+
export interface CollectionItemOwnerStampRefusal {
73+
/** The body's `_packageId`, as it arrived (never `undefined`). */
74+
readonly stamped: unknown;
75+
/** The owner judged against: `undefined` is no package. */
76+
readonly owner: string | undefined;
77+
/** The refusal sentence: the prescription first, then both values, then the rule. */
78+
readonly message: string;
79+
/** The located sentence a door's issue at `_packageId` carries. */
80+
readonly issueMessage: string;
81+
}
82+
83+
/**
84+
* The stack collections whose items the registration door files under their
85+
* package and judges by {@link judgeCollectionItemOwnerStamp}, in the stack
86+
* schema's spelling.
87+
*
88+
* Not judged, because the registration door files them through a path of its
89+
* own and does not judge their stamp: `objects` and `objectExtensions` (the
90+
* object-merge path), `apps` (registered by their own verb),
91+
* `picklistExtensions` (merged into the list they name, not filed as items),
92+
* and `datasources`, `datasourceMapping` and `translations` (configuration,
93+
* not registry items).
94+
*/
95+
export const OWNER_STAMP_JUDGED_COLLECTIONS = Object.freeze([
96+
'picklists',
97+
'actions', 'views', 'pages', 'dashboards', 'reports', 'datasets',
98+
'flows', 'webhooks', 'jobs',
99+
'positions', 'permissions', 'capabilities', 'sharingRules',
100+
'queues', 'assignmentRules',
101+
'agents', 'tools', 'skills',
102+
'apis',
103+
'hooks', 'mappings', 'analyticsCubes',
104+
'connectors',
105+
'emailTemplates', 'docs', 'books',
106+
'data',
107+
] as const);
108+
109+
/** One member of {@link OWNER_STAMP_JUDGED_COLLECTIONS}. */
110+
export type OwnerStampJudgedCollection = (typeof OWNER_STAMP_JUDGED_COLLECTIONS)[number];
111+
112+
/**
113+
* Judge one collection item's body `_packageId` against the owner of the door
114+
* that files it.
115+
*
116+
* @param item The item's body, as it arrived (anything: a non-object is not judged).
117+
* @param type The item's metadata type, as the words show it (`connector`, `data`, …).
118+
* @param name The item's name, as the words show it.
119+
* @param owner The package the door files the item under: `undefined` for none.
120+
* @param door Which door is asking (see the module header).
121+
* @returns The refusal when the stamp disagrees with the owner, else `undefined`.
122+
*/
123+
export function judgeCollectionItemOwnerStamp(
124+
item: unknown,
125+
type: string,
126+
name: string,
127+
owner: string | undefined,
128+
door: CollectionItemOwnerStampDoor,
129+
): CollectionItemOwnerStampRefusal | undefined {
130+
if (!item || typeof item !== 'object') return undefined;
131+
const stamped = (item as { _packageId?: unknown })._packageId;
132+
if (stamped === undefined || stamped === owner) return undefined;
133+
const where = door === 'register'
134+
? `it is registered under ${owner === undefined ? 'no package' : `package '${owner}'`}`
135+
: `this stack ships it from ${owner === undefined ? 'no package (the stack declares no `manifest`)' : `package '${owner}'`}`;
136+
const issueMessage = `carries _packageId ${JSON.stringify(stamped)}, but ${where}`;
137+
return {
138+
stamped,
139+
owner,
140+
message: `Drop \`_packageId\` from ${type} '${name}': it ${issueMessage}. The package an item belongs to is the one `
141+
+ 'that registers it, stamped by the registration; a body never names its own owner.',
142+
issueMessage,
143+
};
144+
}

‎packages/spec/src/kernel/index.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,9 @@ export * from './platform-capabilities';
3636
export * from './metadata-loader.zod';
3737
export * from './metadata-plugin.zod';
3838
export * from './metadata-protection.zod';
39+
// [ADR-0010] The one judge of a collection item's body `_packageId` against the
40+
// package that files it, read by the stack schema and the registration door.
41+
export * from './collection-item-owner-stamp';
3942
// [ADR-0146 D2, D3] The override declaration every overridable type spreads,
4043
// and the paired `<base>.custom` package's identity rules and the closed
4144
// overridable-type list the doors read.

‎packages/spec/src/stack.zod.ts‎

Lines changed: 83 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import {
1010
UNMANAGED_INSTALL_REFUSING_DISPOSITIONS,
1111
unmanagedInstallValueCarries,
1212
} from './kernel/unmanaged-install';
13-
import { PLURAL_TO_SINGULAR } from './meta-spelling/manifest-collection-spelling';
13+
import { PLURAL_TO_SINGULAR, pluralToSingular } from './meta-spelling/manifest-collection-spelling';
1414
import { validateObjectNamespacePrefix } from './kernel/namespace-prefix';
1515
import { PLATFORM_CAPABILITY_TOKENS, RETIRED_PLATFORM_CAPABILITY_GUIDANCE } from './kernel/platform-capabilities';
1616
import { DatasourceSchema } from './data/datasource.zod';
@@ -66,6 +66,7 @@ import { JobSchema } from './system/job.zod';
6666
import { PositionSchema } from './identity/position.zod';
6767
import { PermissionSetSchema, findHierarchyScopeGrants } from './security/permission.zod';
6868
import { judgePermissionSetOwnerBinding } from './security/permission-set-owner-binding';
69+
import { judgeCollectionItemOwnerStamp, OWNER_STAMP_JUDGED_COLLECTIONS } from './kernel/collection-item-owner-stamp';
6970
import { CapabilityDeclarationSchema } from './security/capabilities';
7071
import { SharingRuleSchema } from './security/sharing.zod';
7172
import { QueueSchema } from './security/queue.zod';
@@ -277,6 +278,86 @@ function applyPermissionSetOwnerBindingGate(
277278
});
278279
}
279280

281+
/**
282+
* [ADR-0010] Raise every collection item whose body carries a `_packageId`
283+
* other than the package that ships it as a Zod issue at that key: the BUILD
284+
* door of the owner-stamp judge ({@link judgeCollectionItemOwnerStamp},
285+
* `kernel/collection-item-owner-stamp.ts`, whose header holds the rule, the
286+
* collections and the other door). The registration door refuses the same
287+
* stamp at boot or install; judged here too, an author hears it where they
288+
* wrote it.
289+
*
290+
* On the SCHEMA rather than inside `defineStack`, for the reason
291+
* {@link applyApiEndpointGates} gives: `defineStack`, `os validate`, `os build`,
292+
* the lint scorer and the metadata plugin's artifact ingestion all run this one
293+
* parse. It reads the PARSED stack, and every item schema of a judged
294+
* collection declares `_packageId` (`MetadataProtectionFields`), so the parse
295+
* keeps the key for the judge. The owner is the id each item is registered
296+
* under, read the way {@link applyPermissionSetOwnerBindingGate} reads a
297+
* permission set's:
298+
*
299+
* - **no `packages[]`**: every top-level item ships from `manifest.id`, and
300+
* from no package when there is no `manifest`;
301+
* - **`packages[]`** (ADR-0130 D4): a body's items ship from that body's own
302+
* `id`. A top-level item that no body declares in the same collection under
303+
* the same name is the stack's residual, registered under `manifest.id`; a
304+
* top-level item a body declares is a copy of that body's item, never
305+
* registered from the top level, so the top level does not judge it.
306+
*
307+
* A stack's `plugins` are runtime plugin instances (`z.unknown()`), not bodies
308+
* this parse can read; the registration door judges a nested plugin's items
309+
* when it registers them.
310+
*/
311+
function applyCollectionItemOwnerStampGate(
312+
config: Record<string, unknown> & { manifest?: { id?: unknown } | undefined; packages?: unknown },
313+
ctx: z.RefinementCtx,
314+
): void {
315+
const nameOf = (key: string, item: unknown): string => {
316+
const it = (item ?? {}) as { name?: unknown; id?: unknown; object?: unknown };
317+
const name = key === 'data' ? it.object : (it.name ?? it.id ?? (key === 'views' ? it.object : undefined));
318+
return typeof name === 'string' && name !== '' ? name : '(unnamed)';
319+
};
320+
const judgeBody = (
321+
body: Record<string, unknown>,
322+
owner: unknown,
323+
path: (string | number)[],
324+
skip?: (key: string, name: string) => boolean,
325+
): void => {
326+
for (const key of OWNER_STAMP_JUDGED_COLLECTIONS) {
327+
const items = body[key];
328+
if (!Array.isArray(items)) continue;
329+
items.forEach((item: unknown, i: number) => {
330+
const name = nameOf(key, item);
331+
if (skip?.(key, name)) return;
332+
const refusal = judgeCollectionItemOwnerStamp(
333+
item,
334+
pluralToSingular(key),
335+
name,
336+
typeof owner === 'string' ? owner : undefined,
337+
'build',
338+
);
339+
if (refusal) ctx.addIssue({ code: 'custom', path: [...path, key, i, '_packageId'], message: refusal.message });
340+
});
341+
}
342+
};
343+
if (!Array.isArray(config.packages)) {
344+
judgeBody(config, config.manifest?.id, []);
345+
return;
346+
}
347+
// `<collection>:<name>`: no collection key carries a `:`, so the pair is unambiguous.
348+
const claimed = new Set<string>();
349+
config.packages.forEach((entry: unknown, j: number) => {
350+
const body = (entry as { manifest?: Record<string, unknown> } | null | undefined)?.manifest;
351+
if (!body || typeof body !== 'object') return;
352+
for (const key of OWNER_STAMP_JUDGED_COLLECTIONS) {
353+
const items = body[key];
354+
if (Array.isArray(items)) for (const item of items) claimed.add(`${key}:${nameOf(key, item)}`);
355+
}
356+
judgeBody(body, body.id, ['packages', j, 'manifest']);
357+
});
358+
judgeBody(config, config.manifest?.id, [], (key, name) => claimed.has(`${key}:${name}`));
359+
}
360+
280361
/** One `objectExtensions` entry as the registry registers it, with where it sits in the stack. */
281362
interface VisibleObjectExtension {
282363
/** The position of the package that ships it: registration order across packages. */
@@ -2183,6 +2264,7 @@ export const ObjectStackDefinitionSchema = lazySchema(() => strictObject({
21832264
...STACK_DEFINITION_COLLECTIONS_SHAPE,
21842265
}).superRefine(applyApiEndpointGates)
21852266
.superRefine(applyPermissionSetOwnerBindingGate)
2267+
.superRefine(applyCollectionItemOwnerStampGate)
21862268
.superRefine(applyControlledByParentExtensionGate));
21872269

21882270
export type ObjectStackDefinition = z.input<typeof ObjectStackDefinitionSchema>;

0 commit comments

Comments
 (0)