Skip to content

Commit d0cde39

Browse files
committed
wip: build-door gate and tests
Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017ihL2fi9zfJhUTubyJYb6V
1 parent 5c135f4 commit d0cde39

3 files changed

Lines changed: 368 additions & 0 deletions

File tree

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [ADR-0010] The registration door and the build door judge a collection
5+
* item's body `_packageId` with ONE judge (`judgeCollectionItemOwnerStamp`,
6+
* `@objectstack/spec/kernel`), so the two cannot disagree. This file holds
7+
* them equal from the registration side:
8+
*
9+
* - the same stamp gets the same verdict at both doors — `registerApp`
10+
* (boot / install) and the stack schema's parse (`defineStack`,
11+
* `os validate`, `os build`) — and each door's words are the judge's own;
12+
* - the build door judges exactly the collections `registerApp` refuses a
13+
* foreign stamp in (`OWNER_STAMP_JUDGED_COLLECTIONS`), key by key over the
14+
* stack schema's whole key set, so the build door neither misses a
15+
* collection the boot refuses nor refuses one the boot accepts.
16+
*
17+
* The registration door's envelope and its exemption for a stamp a
18+
* registration wrote stay pinned in `collection-item-owner-stamp.test.ts`.
19+
*/
20+
21+
import { describe, it, expect } from 'vitest';
22+
import { ObjectStackDefinitionSchema, STACK_DEFINITION_KEYS } from '@objectstack/spec';
23+
import { judgeCollectionItemOwnerStamp, OWNER_STAMP_JUDGED_COLLECTIONS } from '@objectstack/spec/kernel';
24+
import { ObjectQL } from './engine.js';
25+
26+
const PKG = 'com.probe.pkg';
27+
const FOREIGN = 'com.probe.host';
28+
29+
const connector = (stamp?: unknown) => ({
30+
name: 'probe_conn',
31+
label: 'Probe',
32+
type: 'api',
33+
provider: 'openapi',
34+
providerConfig: { spec: './specs/billing.json' },
35+
...(stamp === undefined ? {} : { _packageId: stamp }),
36+
});
37+
38+
/** The registration door's answer: the thrown error, or `undefined`. */
39+
function boot(body: Record<string, unknown>): any {
40+
try {
41+
new ObjectQL().registerApp(body as any);
42+
return undefined;
43+
} catch (e) {
44+
return e;
45+
}
46+
}
47+
48+
/** The build door's answer: the parse's issues at a `_packageId`. */
49+
function build(stack: Record<string, unknown>) {
50+
const result = ObjectStackDefinitionSchema.safeParse(stack);
51+
return result.success ? [] : result.error.issues.filter((i) => i.path[i.path.length - 1] === '_packageId');
52+
}
53+
54+
describe('[ADR-0010] one verdict at the registration door and the build door', () => {
55+
const manifest = { id: PKG, name: 'probe', namespace: 'probe', version: '1.0.0', type: 'app' };
56+
57+
it('a foreign stamp, `\'\'`, an equal stamp and no stamp: refused at both or accepted at both', () => {
58+
const cases: Array<[unknown, boolean]> = [[FOREIGN, true], ['', true], [PKG, false], [undefined, false]];
59+
for (const [stamp, refused] of cases) {
60+
const atBoot = boot({ ...manifest, connectors: [connector(stamp)] });
61+
const atBuild = build({ manifest, connectors: [connector(stamp)] });
62+
const label = `stamp ${JSON.stringify(stamp)}`;
63+
if (!refused) {
64+
expect(atBoot, label).toBeUndefined();
65+
expect(atBuild, label).toEqual([]);
66+
continue;
67+
}
68+
expect(atBoot, label).toMatchObject({ code: 'VALIDATION_ERROR', status: 400 });
69+
expect(atBoot.issues, label).toEqual([{ path: '_packageId', code: 'custom', message: expect.any(String) }]);
70+
expect(atBuild.map((i) => [i.path.join('.'), i.code]), label).toEqual([['connectors.0._packageId', 'custom']]);
71+
// Each door's words are the one judge's, for its own door.
72+
const judged = (door: 'build' | 'register') => judgeCollectionItemOwnerStamp(connector(stamp), 'connector', 'probe_conn', PKG, door)!;
73+
expect(atBoot.message, label).toBe(judged('register').message);
74+
expect(atBoot.issues[0].message, label).toBe(judged('register').issueMessage);
75+
expect(atBuild[0].message, label).toBe(judged('build').message);
76+
}
77+
});
78+
79+
it('`null`: refused at both — by the judge at boot, by the item schema\'s type check at build, both at `_packageId`', () => {
80+
expect(boot({ ...manifest, connectors: [connector(null)] })).toMatchObject({ code: 'VALIDATION_ERROR', status: 400 });
81+
expect(build({ manifest, connectors: [connector(null)] }).map((i) => [i.path.join('.'), i.code]))
82+
.toEqual([['connectors.0._packageId', 'invalid_type']]);
83+
});
84+
});
85+
86+
describe('[ADR-0010] the build door judges exactly the collections the registration door refuses a foreign stamp in', () => {
87+
it('key by key over the stack schema\'s whole key set', () => {
88+
const refusedAtBoot: string[] = [];
89+
for (const key of STACK_DEFINITION_KEYS) {
90+
const probe = { name: 'probe_item', object: 'probe_item', records: [], _packageId: FOREIGN };
91+
const error = boot({ id: PKG, name: 'probe', [key]: [probe] });
92+
const atStamp = error?.code === 'VALIDATION_ERROR'
93+
&& Array.isArray(error.issues) && error.issues.some((i: any) => i?.path === '_packageId');
94+
if (atStamp) refusedAtBoot.push(key);
95+
}
96+
expect(refusedAtBoot.sort()).toEqual([...OWNER_STAMP_JUDGED_COLLECTIONS].sort());
97+
});
98+
});
Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [ADR-0010] The owner-stamp judge, on its own: the verdict table of
5+
* `collection-item-owner-stamp.ts`'s header, row by row, and the two doors'
6+
* words. The doors that call it are pinned where they live: the build door in
7+
* `stack-collection-item-owner-stamp.test.ts`, the registration door in
8+
* `@objectstack/objectql`'s `collection-item-owner-stamp.test.ts`.
9+
*/
10+
import { describe, it, expect } from 'vitest';
11+
import {
12+
judgeCollectionItemOwnerStamp,
13+
OWNER_STAMP_JUDGED_COLLECTIONS,
14+
type CollectionItemOwnerStampDoor,
15+
} from './collection-item-owner-stamp';
16+
import { PLURAL_TO_SINGULAR } from '../meta-spelling/manifest-collection-spelling';
17+
18+
const PKG = 'com.acme.crm';
19+
const OTHER = 'com.acme.other';
20+
const DOORS: CollectionItemOwnerStampDoor[] = ['build', 'register'];
21+
22+
const judge = (stamp: unknown, owner: string | undefined, door: CollectionItemOwnerStampDoor) =>
23+
judgeCollectionItemOwnerStamp(
24+
stamp === undefined ? { name: 'probe_conn' } : { name: 'probe_conn', _packageId: stamp },
25+
'connector',
26+
'probe_conn',
27+
owner,
28+
door,
29+
);
30+
31+
describe('[ADR-0010] judgeCollectionItemOwnerStamp: the verdict table', () => {
32+
it('an absent stamp is accepted, whatever the owner, at both doors', () => {
33+
for (const door of DOORS) {
34+
expect(judge(undefined, PKG, door)).toBeUndefined();
35+
expect(judge(undefined, undefined, door)).toBeUndefined();
36+
}
37+
});
38+
39+
it('a stamp equal to the owner is accepted at both doors', () => {
40+
for (const door of DOORS) expect(judge(PKG, PKG, door)).toBeUndefined();
41+
});
42+
43+
it('a foreign stamp, and `null` and `\'\'` under an owner, are refused at both doors', () => {
44+
for (const door of DOORS) {
45+
for (const stamp of [OTHER, null, '']) {
46+
const refusal = judge(stamp, PKG, door);
47+
expect(refusal, `${door} · ${JSON.stringify(stamp)}`).toMatchObject({ stamped: stamp, owner: PKG });
48+
}
49+
}
50+
});
51+
52+
it('any stamp under no owner is refused at both doors', () => {
53+
for (const door of DOORS) {
54+
for (const stamp of [OTHER, PKG, null, '']) {
55+
expect(judge(stamp, undefined, door), `${door} · ${JSON.stringify(stamp)}`).toMatchObject({ owner: undefined });
56+
}
57+
}
58+
});
59+
60+
it('a non-object item is not judged', () => {
61+
for (const item of [undefined, null, 'probe', 42]) {
62+
expect(judgeCollectionItemOwnerStamp(item, 'connector', 'probe_conn', PKG, 'build')).toBeUndefined();
63+
}
64+
});
65+
});
66+
67+
describe('[ADR-0010] judgeCollectionItemOwnerStamp: the words', () => {
68+
it('both doors prescribe first and name both values; only the clause naming the owner differs', () => {
69+
const register = judge(OTHER, PKG, 'register')!;
70+
const build = judge(OTHER, PKG, 'build')!;
71+
for (const refusal of [register, build]) {
72+
expect(refusal.message.indexOf("Drop `_packageId` from connector 'probe_conn': it carries _packageId \"com.acme.other\", but ")).toBe(0);
73+
expect(refusal.message.endsWith('; a body never names its own owner.')).toBe(true);
74+
expect(refusal.message).toContain(refusal.issueMessage);
75+
}
76+
expect(register.issueMessage).toBe(`carries _packageId "${OTHER}", but it is registered under package '${PKG}'`);
77+
expect(build.issueMessage).toBe(`carries _packageId "${OTHER}", but this stack ships it from package '${PKG}'`);
78+
expect(register.message.replace(register.issueMessage, '')).toBe(build.message.replace(build.issueMessage, ''));
79+
});
80+
81+
it('no owner reads as no package, and the build door names the missing `manifest`', () => {
82+
expect(judge(OTHER, undefined, 'register')!.issueMessage).toBe(`carries _packageId "${OTHER}", but it is registered under no package`);
83+
expect(judge(OTHER, undefined, 'build')!.issueMessage)
84+
.toBe(`carries _packageId "${OTHER}", but this stack ships it from no package (the stack declares no \`manifest\`)`);
85+
});
86+
});
87+
88+
describe('[ADR-0010] OWNER_STAMP_JUDGED_COLLECTIONS', () => {
89+
it('names each collection once, and every one but the seed `data` folds to a registry type', () => {
90+
expect(new Set(OWNER_STAMP_JUDGED_COLLECTIONS).size).toBe(OWNER_STAMP_JUDGED_COLLECTIONS.length);
91+
for (const key of OWNER_STAMP_JUDGED_COLLECTIONS) {
92+
if (key === 'data') continue;
93+
expect(Object.prototype.hasOwnProperty.call(PLURAL_TO_SINGULAR, key), key).toBe(true);
94+
}
95+
});
96+
97+
it('is frozen', () => {
98+
expect(Object.isFrozen(OWNER_STAMP_JUDGED_COLLECTIONS)).toBe(true);
99+
});
100+
});
Lines changed: 170 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,170 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [ADR-0010] The BUILD door of the collection-item owner-stamp rule: the stack
5+
* schema refuses an item whose body carries a `_packageId` other than the
6+
* package that ships it (`applyCollectionItemOwnerStampGate`, `stack.zod.ts`,
7+
* calling `judgeCollectionItemOwnerStamp`).
8+
*
9+
* Before this gate such a stack parsed, and only the registration door refused
10+
* it, at boot or install. `defineStack`, `os validate`, `os build` and the
11+
* artifact door all run this one parse, so it is pinned here on the parse and
12+
* through `defineStack`, with the envelope each answers: the issue's `code` and
13+
* path at the parse, `STACK_SCHEMA_INVALID` / 422 from `defineStack`.
14+
*
15+
* The judge reads the PARSED stack, so a key the parse dropped would make it
16+
* unreachable: every judged collection's item schema declares `_packageId`
17+
* (`MetadataProtectionFields`, held by the authorable-surface ratchet), and the
18+
* last suite drives one item of each shape class (a plain item, a transformed
19+
* action, a seed dataset, a view container) through the parse to the judge.
20+
*/
21+
import { describe, it, expect } from 'vitest';
22+
import { composeStacks, defineStack, ObjectStackDefinitionSchema } from './stack.zod';
23+
import { judgeCollectionItemOwnerStamp } from './kernel/collection-item-owner-stamp';
24+
25+
type Envelope = Error & { code?: string; status?: number; issues?: Array<{ code?: string; path?: PropertyKey[]; message?: string }> };
26+
27+
const CRM = 'com.acme.crm';
28+
const OTHER = 'com.acme.other';
29+
30+
const connector = (name: string, stamp?: unknown) => ({
31+
name,
32+
label: 'Probe',
33+
type: 'api',
34+
provider: 'openapi',
35+
providerConfig: { spec: './specs/billing.json' },
36+
...(stamp === undefined ? {} : { _packageId: stamp }),
37+
});
38+
39+
const manifest = (id: string, extra: Record<string, unknown> = {}) => ({
40+
id,
41+
name: id,
42+
namespace: 'crm',
43+
version: '1.0.0',
44+
type: 'app' as const,
45+
...extra,
46+
});
47+
48+
function refusal(config: unknown): Envelope | null {
49+
try {
50+
defineStack(config as never);
51+
return null;
52+
} catch (e) {
53+
return e as Envelope;
54+
}
55+
}
56+
57+
/** Every issue the parse raises at a `_packageId`, as `[path, code, message]`. */
58+
function stampIssues(config: unknown): Array<[string, string, string]> {
59+
const result = ObjectStackDefinitionSchema.safeParse(config);
60+
if (result.success) return [];
61+
return result.error.issues
62+
.filter((i) => i.path[i.path.length - 1] === '_packageId')
63+
.map((i) => [i.path.join('.'), i.code, i.message]);
64+
}
65+
66+
describe('[ADR-0010] defineStack refuses a collection item whose body `_packageId` is not the stack\'s package', () => {
67+
it('a connector naming another package: STACK_SCHEMA_INVALID / 422, the issue at its `_packageId`, in the judge\'s build words', () => {
68+
const error = refusal({ manifest: manifest(CRM), connectors: [connector('probe_conn', OTHER)] });
69+
expect(error, 'the stack must be refused').not.toBeNull();
70+
expect(error).toMatchObject({ code: 'STACK_SCHEMA_INVALID', status: 422 });
71+
const issue = error!.issues!.find((i) => i.path?.join('.') === 'connectors.0._packageId');
72+
expect(issue, 'located at the item\'s key').toMatchObject({ code: 'custom' });
73+
expect(issue!.message).toBe(
74+
judgeCollectionItemOwnerStamp({ _packageId: OTHER }, 'connector', 'probe_conn', CRM, 'build')!.message,
75+
);
76+
expect(issue!.message.indexOf("Drop `_packageId` from connector 'probe_conn'")).toBe(0);
77+
});
78+
79+
it('CONTROL: the same stack without the stamp, and with a stamp equal to `manifest.id`, is accepted', () => {
80+
expect(refusal({ manifest: manifest(CRM), connectors: [connector('probe_conn')] })).toBeNull();
81+
expect(refusal({ manifest: manifest(CRM), connectors: [connector('probe_conn', CRM)] })).toBeNull();
82+
});
83+
84+
it('`\'\'` is a stamp: refused by the judge; `null` is a stamp too, refused first by the item schema at the same key', () => {
85+
expect(stampIssues({ manifest: manifest(CRM), connectors: [connector('probe_conn', '')] }))
86+
.toEqual([['connectors.0._packageId', 'custom', expect.stringContaining('carries _packageId "", but this stack ships it')]]);
87+
expect(stampIssues({ manifest: manifest(CRM), connectors: [connector('probe_conn', null)] }))
88+
.toEqual([['connectors.0._packageId', 'invalid_type', expect.any(String)]]);
89+
});
90+
91+
it('a stack with no `manifest` ships its items from no package: any stamp is refused', () => {
92+
for (const stamp of [OTHER, CRM]) {
93+
expect(stampIssues({ connectors: [connector('probe_conn', stamp)] }), stamp)
94+
.toEqual([['connectors.0._packageId', 'custom', expect.stringContaining('from no package (the stack declares no `manifest`)')]]);
95+
}
96+
expect(stampIssues({ connectors: [connector('probe_conn')] })).toEqual([]);
97+
});
98+
99+
it('a map-format collection is judged on the array it normalises to', () => {
100+
const error = refusal({
101+
manifest: manifest(CRM),
102+
connectors: { probe_conn: { label: 'Probe', type: 'api', provider: 'openapi', providerConfig: { spec: './s.json' }, _packageId: OTHER } },
103+
});
104+
expect(error).toMatchObject({ code: 'STACK_SCHEMA_INVALID', status: 422 });
105+
expect(error!.issues!.map((i) => i.path?.join('.'))).toContain('connectors.0._packageId');
106+
});
107+
});
108+
109+
describe('[ADR-0010] the parse keeps the stamp for the judge, across shape classes', () => {
110+
const stack = (extra: Record<string, unknown>) => ({ manifest: manifest(CRM), ...extra });
111+
112+
it('an action (a transformed item schema) is judged at its `_packageId`', () => {
113+
const action = { name: 'crm_go', label: 'Go', type: 'script', target: 'go' };
114+
expect(stampIssues(stack({ actions: [{ ...action, _packageId: OTHER }] })).map(([p, c]) => [p, c]))
115+
.toEqual([['actions.0._packageId', 'custom']]);
116+
expect(stampIssues(stack({ actions: [action] }))).toEqual([]);
117+
});
118+
119+
it('a seed dataset is judged under the type word `data`, named by its object', () => {
120+
const data = { object: 'crm_task', records: [] };
121+
expect(stampIssues(stack({ data: [{ ...data, _packageId: OTHER }] })))
122+
.toEqual([['data.0._packageId', 'custom', expect.stringContaining("Drop `_packageId` from data 'crm_task'")]]);
123+
expect(stampIssues(stack({ data: [data] }))).toEqual([]);
124+
});
125+
126+
it('a view container is judged, named by the object it binds to', () => {
127+
const view = { object: 'crm_task', list: { type: 'grid', columns: ['name'] } };
128+
expect(stampIssues(stack({ views: [{ ...view, _packageId: OTHER }] })))
129+
.toEqual([['views.0._packageId', 'custom', expect.stringContaining("Drop `_packageId` from view 'crm_task'")]]);
130+
expect(stampIssues(stack({ views: [view] }))).toEqual([]);
131+
});
132+
});
133+
134+
describe('[ADR-0010] a release artifact\'s items are judged against the package that registers each one', () => {
135+
/** Two packages composed as `os build` does (ADR-0130 D4), the crm connector's stamp as the variable. */
136+
// The artifact's own manifest is the LAST input's (`'preserve'` keeps the
137+
// `'last'` pick), so it is the orders module's, never the package under test.
138+
const twoPackages = (crmStamp?: string) => composeStacks([
139+
defineStack({ manifest: manifest(CRM), connectors: [connector('crm_conn', crmStamp)] } as never, { strict: false }),
140+
defineStack({ manifest: manifest('com.acme.orders', { type: 'module' }), connectors: [connector('orders_conn')] } as never),
141+
], { manifest: 'preserve' }) as unknown as {
142+
manifest: { id: string };
143+
packages: Array<{ manifest: Record<string, unknown> }>;
144+
[key: string]: unknown;
145+
};
146+
147+
it('a body\'s item is judged against that body\'s own id', () => {
148+
const artifact = twoPackages(OTHER);
149+
const at = artifact.packages.findIndex((p) => p.manifest.id === CRM);
150+
expect(stampIssues(artifact).map(([path]) => path)).toEqual([`packages.${at}.manifest.connectors.0._packageId`]);
151+
// CONTROL: the stamp naming the body that ships it, and no stamp.
152+
expect(stampIssues(twoPackages(CRM))).toEqual([]);
153+
expect(stampIssues(twoPackages())).toEqual([]);
154+
});
155+
156+
it('a top-level item no body declares is the residual, judged against the artifact\'s `manifest.id`', () => {
157+
const artifact = { ...twoPackages(), connectors: [connector('stray_conn', OTHER)] };
158+
const owner = artifact.manifest.id;
159+
expect(stampIssues(artifact)).toEqual([['connectors.0._packageId', 'custom', expect.stringContaining(`from package '${owner}'`)]]);
160+
// CONTROL: the residual stamped with the artifact's own id.
161+
expect(stampIssues({ ...twoPackages(), connectors: [connector('stray_conn', owner)] })).toEqual([]);
162+
});
163+
164+
it('CONTROL: a top-level COPY of a body\'s item is not judged against the artifact\'s id', () => {
165+
const artifact = twoPackages(CRM);
166+
const flattened = { ...artifact, connectors: [connector('crm_conn', CRM), connector('orders_conn')] };
167+
expect(flattened.manifest.id).not.toBe(CRM);
168+
expect(stampIssues(flattened)).toEqual([]);
169+
});
170+
});

0 commit comments

Comments
 (0)