Skip to content

Commit c1e3b08

Browse files
committed
refactor(metadata-protocol): generate the protocol.ts section split with a deterministic codemod (WIP)
scripts/codemod-split-protocol.mjs applies the E1 host split (packages/metadata-protocol/scripts/host-split.mjs) to whole sections of ObjectStackProtocolImplementation and proves the move: undoing it rebuilds the base protocol.ts and protocol-host.ts byte for byte, and host-split's own check passes for every moved member. Generated output, unedited. Claude-Session: https://claude.ai/code/session_01WGufzgddMBbTQd9yVo4Yuz Co-Authored-By: Claude <noreply@anthropic.com>
1 parent 9049be2 commit c1e3b08

12 files changed

Lines changed: 10964 additions & 8269 deletions

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

Lines changed: 296 additions & 0 deletions
Large diffs are not rendered by default.

‎packages/metadata-protocol/src/protocol-diff-delete-load.ts‎

Lines changed: 1653 additions & 0 deletions
Large diffs are not rendered by default.

‎packages/metadata-protocol/src/protocol-discovery-and-bases.ts‎

Lines changed: 339 additions & 0 deletions
Large diffs are not rendered by default.

‎packages/metadata-protocol/src/protocol-history-and-publish.ts‎

Lines changed: 1163 additions & 0 deletions
Large diffs are not rendered by default.

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

Lines changed: 135 additions & 0 deletions
Large diffs are not rendered by default.

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

Lines changed: 2154 additions & 0 deletions
Large diffs are not rendered by default.

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

Lines changed: 734 additions & 0 deletions
Large diffs are not rendered by default.

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

Lines changed: 2511 additions & 0 deletions
Large diffs are not rendered by default.
Lines changed: 161 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,161 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#29985 codemod] The "Global search and the metadata cache" section of
5+
* `ObjectStackProtocolImplementation`: the bodies of `getMetaItemCached` moved
6+
* out of `protocol.ts` whole by `scripts/codemod-split-protocol.mjs`.
7+
*
8+
* A MOVE, not a redesign. Each function below is the body of the class method
9+
* of the same name as `packages/metadata-protocol/scripts/host-split.mjs` moves
10+
* one (ruling E, item E1): re-indented one level, with `this.<member>` read as
11+
* `host.<member>` and nothing else changed. Each method stays on the class
12+
* with its docblock and signature, which the published `.d.ts` prints, and
13+
* hands its body the host (`protocol-host.ts`); the docblock there is the
14+
* contract.
15+
*
16+
* What a body reads from elsewhere, it imports from where `protocol.ts`
17+
* imports it. Nothing re-exports this module, so the published surface does
18+
* not move.
19+
*/
20+
21+
import type { FlowRegistration, MetadataCacheRequest, MetadataCacheResponse } from '@objectstack/spec/api';
22+
import { canonicalizeMetaRequestType } from './protocol-meta-type-schema.js';
23+
import { simpleHash } from './protocol-version-tokens.js';
24+
import { metadataItemNotFoundError } from './protocol-client-failures.js';
25+
import type { ProtocolHost } from './protocol-host.js';
26+
27+
/** The body of `ObjectStackProtocolImplementation#getMetaItemCached`; the method's docblock there is its contract. */
28+
export async function getMetaItemCached(host: Pick<ProtocolHost, 'getMetaItem'>, request: { type: string, name: string, cacheRequest?: MetadataCacheRequest, locale?: string }): Promise<MetadataCacheResponse & { registration?: FlowRegistration; disabledActions?: string[]; cascadeDeleteObjects?: string[] }> {
29+
// #4432 — CANONICAL TYPE KEY. See {@link canonicalMetaType}. The ETag
30+
// and the cache entry are keyed by type, so two spellings would cache
31+
// the same item twice and invalidate only one of them.
32+
request = canonicalizeMetaRequestType(request);
33+
try {
34+
// Delegate to getMetaItem so the customization-overlay read order
35+
// (sys_metadata → registry → MetadataService) is honoured here too
36+
// (ADR-0005). Without this, cached reads silently bypass overlays.
37+
const result = await host.getMetaItem({
38+
type: request.type,
39+
name: request.name,
40+
});
41+
const item = (result as any)?.item;
42+
// [#23316] The automation engine's verdict on a flow, as the
43+
// delegate read above just resolved it — live, on every call. It
44+
// rides beside `data` for the REST layer's default door, and is
45+
// never hashed into the ETag below (see the 304 note there).
46+
const registration = (result as { registration?: FlowRegistration } | undefined)?.registration;
47+
// [#27842] …and, for an object, the packaged actions the activation
48+
// ledger switches off, on exactly those terms: live, beside `data`,
49+
// never hashed (see the 304 note below).
50+
const disabledActions = (result as { disabledActions?: string[] } | undefined)?.disabledActions;
51+
// [#28001] …and the objects a delete of one of its records can
52+
// cascade into, on the same terms.
53+
const cascadeDeleteObjects = (result as { cascadeDeleteObjects?: string[] } | undefined)?.cascadeDeleteObjects;
54+
55+
if (!item) {
56+
// [#5532] Structured: 404 + the catalog's `RESOURCE_NOT_FOUND`.
57+
// Reaching here now means a real miss — `getMetaItem` throws
58+
// 503 rather than answering `undefined` when the store could
59+
// not be read (see
60+
// {@link rethrowUnlessMetadataStoreUnprovisioned}) — so the
61+
// 404 is a claim this layer is finally entitled to make.
62+
//
63+
// [#5840] That entitlement was only three-quarters earned when
64+
// it was written: it held for the `sys_metadata` overlay read,
65+
// whose failure arrives as a throw, and NOT for the
66+
// MetadataService read, whose failure `MetadataManager`
67+
// warn-logs and skips — so a loader outage still reached this
68+
// line as a plain missing `item` and was answered 404. Both
69+
// halves now refuse to guess (see
70+
// {@link readItemFromMetadataService}).
71+
throw metadataItemNotFoundError(request.type, request.name);
72+
}
73+
74+
// Calculate ETag (simple hash of the stringified metadata).
75+
//
76+
// The ETag MUST vary by locale. The REST layer translates the
77+
// response body *after* this validator check, so an ETag computed
78+
// only from the (untranslated) content would let a language switch
79+
// match the prior `If-None-Match` and return `304 Not Modified`
80+
// carrying a stale-locale body — labels/headers stuck in the old
81+
// language until a hard refresh (issue #1319). Folding the resolved
82+
// locale into the hash gives each locale a distinct validator.
83+
//
84+
// [ADR-0131 D6] No organization is part of the validator: the
85+
// read is the environment's for every caller, so the document
86+
// hashed below is the whole scope. An org-less caller's validator
87+
// is byte-for-byte the one it was issued before.
88+
//
89+
// ⛔ The ONE invariant this block depends on: `content` — the bytes
90+
// actually being sent — is inside the hash below. A 304 is answered
91+
// only on an exact match over those bytes, so a caller is only ever
92+
// pinned to the representation IT received. Hashing anything
93+
// cheaper than the document — a version marker — destroys that
94+
// silently.
95+
const content = JSON.stringify(item);
96+
const scope = [
97+
request.locale || undefined,
98+
].filter((part): part is string => part !== undefined);
99+
const hash = simpleHash(
100+
scope.length > 0
101+
? `${scope.join('\u0000')}\u0000${content}`
102+
: content,
103+
);
104+
const etag = { value: hash, weak: false };
105+
106+
// Check If-None-Match header
107+
//
108+
// [#23316] …except for a read that carries `registration`: the
109+
// served body holds the engine's verdict and this validator does
110+
// not (it hashes the document alone, and the verdict stays out of
111+
// it), so a 304 here would pin the caller to the verdict it was
112+
// served before — after the engine re-registered or refused the
113+
// flow under an unchanged body. Such a read is always answered in
114+
// full; the work is the same either way, since this method always
115+
// performs the delegate read.
116+
//
117+
// [#27842] The same holds for `disabledActions`: an administrator's
118+
// switch moves no byte of the object document, so a 304 would keep
119+
// the caller on the switched-off list it was served before.
120+
// [#28001] So does `cascadeDeleteObjects`: an object registered
121+
// later that cascades into this one moves no byte of it either.
122+
if (
123+
request.cacheRequest?.ifNoneMatch
124+
&& registration === undefined && disabledActions === undefined && cascadeDeleteObjects === undefined
125+
) {
126+
const clientEtag = request.cacheRequest.ifNoneMatch.replace(/^"(.*)"$/, '$1').replace(/^W\/"(.*)"$/, '$1');
127+
if (clientEtag === hash) {
128+
// Return 304 Not Modified
129+
return {
130+
notModified: true,
131+
etag,
132+
};
133+
}
134+
}
135+
136+
// Return full metadata with cache headers
137+
return {
138+
data: item,
139+
...(registration !== undefined ? { registration } : {}),
140+
...(disabledActions !== undefined ? { disabledActions } : {}),
141+
...(cascadeDeleteObjects !== undefined ? { cascadeDeleteObjects } : {}),
142+
etag,
143+
lastModified: new Date().toISOString(),
144+
cacheControl: {
145+
// Metadata is invalidated by publish, so freshness must be
146+
// gated by the ETag validator — not a TTL. `no-cache` lets
147+
// clients store the body but forces an `If-None-Match`
148+
// revalidation on every use: a cheap 304 when unchanged,
149+
// fresh fields the instant a publish bumps the ETag. The old
150+
// `max-age=3600` pinned the schema for up to an hour, so the
151+
// AI-build "New" form kept rendering pre-publish fields until
152+
// the TTL lapsed (no revalidation in between). `private` also
153+
// keeps per-tenant metadata out of shared CDN/proxy caches.
154+
directives: ['private', 'no-cache'],
155+
},
156+
notModified: false,
157+
};
158+
} catch (error: any) {
159+
throw error;
160+
}
161+
}
Lines changed: 156 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,156 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#29985 codemod] The "Write gates: overlay, code-only, organization, sealed
5+
* and packaged-base refusals, locks, version tokens, conflict audit" section of
6+
* `ObjectStackProtocolImplementation`: the bodies of `isArtifactBacked`,
7+
* `isNestedArtifactField`, `packagedBaseRefusal`, `packagedArtifactOwner`,
8+
* `storedFlowBindingAgrees`, `refusePackagedBaseRemoval`,
9+
* `baseServesBundleMember`, `pairOfAddedMember`, `findPairAddedMemberRow`,
10+
* `registryMemberServedAt` moved out of `protocol.ts` whole by
11+
* `scripts/codemod-split-protocol.mjs`.
12+
*
13+
* A MOVE, not a redesign. Each function below is the body of the class method
14+
* of the same name as `packages/metadata-protocol/scripts/host-split.mjs` moves
15+
* one (ruling E, item E1): re-indented one level, with `this.<member>` read as
16+
* `host.<member>` and nothing else changed. Each method stays on the class
17+
* with its docblock and signature, which the published `.d.ts` prints, and
18+
* hands its body the host (`protocol-host.ts`); the docblock there is the
19+
* contract.
20+
*
21+
* What a body reads from elsewhere, it imports from where `protocol.ts`
22+
* imports it. Nothing re-exports this module, so the published surface does
23+
* not move.
24+
*/
25+
26+
import { managedItemSealedSentence } from './packaged-base-regime.js';
27+
import type { StoredOverlayRow } from './item-lock.js';
28+
import { itemDiscriminator } from '@objectstack/metadata-core';
29+
import { PLURAL_TO_SINGULAR } from '@objectstack/spec/shared';
30+
import { customizationPackageId } from '@objectstack/spec/kernel';
31+
import { baseAddressServesMember, shippingPackageIds } from './protocol-environment-rows.js';
32+
import { canonicalMetaType, canonicalizeMetaRequestType } from './protocol-meta-type-schema.js';
33+
import { boundPackageOf } from './protocol-package-bindings.js';
34+
import type { ShippingPackages } from './protocol-package-bindings.js';
35+
import { memberOption } from './protocol-bundle-members.js';
36+
import type { ProtocolHost } from './protocol-host.js';
37+
38+
/** The body of `ObjectStackProtocolImplementation#isArtifactBacked`; the method's docblock there is its contract. */
39+
export function isArtifactBacked(host: Pick<ProtocolHost, 'isDeclaredCodeDatasource' | 'isNestedArtifactField' | 'lookupArtifactItem'>, type: string, name: string): boolean {
40+
// `lookupArtifactItem` only returns items whose `_packageId` marks a
41+
// genuine code package (the `'sys_metadata'` rehydration sentinel is
42+
// excluded), and — via `SchemaRegistry.getArtifactItem` — is immune
43+
// to plain-key shadows hydrated from overlay rows.
44+
if (host.lookupArtifactItem(type, name) !== undefined) return true;
45+
return host.isNestedArtifactField(type, name) || host.isDeclaredCodeDatasource(type, name);
46+
}
47+
48+
/** The body of `ObjectStackProtocolImplementation#isNestedArtifactField`; the method's docblock there is its contract. */
49+
export function isNestedArtifactField(host: Pick<ProtocolHost, 'lookupArtifactItem'>, type: string, name: string): boolean {
50+
if ((PLURAL_TO_SINGULAR[type] ?? type) !== 'field') return false;
51+
// `<object>.<field>` — both halves are snake_case and carry no dot of
52+
// their own, so the FIRST separator is the only one.
53+
const sep = name.indexOf('.');
54+
if (sep <= 0 || sep === name.length - 1) return false;
55+
const objectArtifact = host.lookupArtifactItem('object', name.slice(0, sep)) as
56+
{ fields?: Record<string, unknown> } | undefined;
57+
const fields = objectArtifact?.fields;
58+
if (!fields || typeof fields !== 'object') return false;
59+
return Object.prototype.hasOwnProperty.call(fields, name.slice(sep + 1));
60+
}
61+
62+
/** The body of `ObjectStackProtocolImplementation#packagedBaseRefusal`; the method's docblock there is its contract. */
63+
export function packagedBaseRefusal(host: Pick<ProtocolHost, 'isPackagedBaseRefusal' | 'refusePackagedBaseOverride' | 'refusePackagedBaseRemoval'>, request: { type: string; name: string; operation: 'save' | 'delete'; packageId?: string | null }): Error | null {
64+
// [#9009] Folded HERE, at the producer of the verdict, so a caller that
65+
// arrives with a plural spelling cannot address around the lock.
66+
const folded = canonicalizeMetaRequestType(request);
67+
try {
68+
if (folded.operation === 'delete') host.refusePackagedBaseRemoval(folded);
69+
else {
70+
host.refusePackagedBaseOverride({
71+
type: folded.type,
72+
name: folded.name,
73+
...(folded.packageId ? { packageId: folded.packageId } : {}),
74+
});
75+
}
76+
} catch (err) {
77+
if (host.isPackagedBaseRefusal(err)) return err;
78+
throw err;
79+
}
80+
return null;
81+
}
82+
83+
/** The body of `ObjectStackProtocolImplementation#packagedArtifactOwner`; the method's docblock there is its contract. */
84+
export function packagedArtifactOwner(host: Pick<ProtocolHost, 'lookupArtifactItem'>, request: { type: string; name: string }): string | undefined {
85+
const folded = canonicalizeMetaRequestType(request);
86+
const artifact = host.lookupArtifactItem(folded.type, folded.name) as { _packageId?: unknown } | undefined;
87+
const packageId = artifact?._packageId;
88+
return typeof packageId === 'string' && packageId !== '' ? packageId : undefined;
89+
}
90+
91+
/** The body of `ObjectStackProtocolImplementation#storedFlowBindingAgrees`; the method's docblock there is its contract. */
92+
export async function storedFlowBindingAgrees(host: Pick<ProtocolHost, 'findEnvironmentRow' | 'rethrowUnlessMetadataStoreUnprovisioned'>, name: string, packageId: string): Promise<boolean> {
93+
try {
94+
// [#21911] The explicit system opt-in — see findServedOverlayRow.
95+
const row = await host.findEnvironmentRow('sys_metadata', {
96+
where: { type: 'flow', name, package_id: packageId },
97+
context: { isSystem: true },
98+
});
99+
return row != null;
100+
} catch (error) {
101+
host.rethrowUnlessMetadataStoreUnprovisioned(error, 'sys_metadata');
102+
return false;
103+
}
104+
}
105+
106+
/** The body of `ObjectStackProtocolImplementation#refusePackagedBaseRemoval`; the method's docblock there is its contract. */
107+
export function refusePackagedBaseRemoval(host: Pick<ProtocolHost, 'isSealedManagedItem' | 'mergesOverlayAtRead'>, request: { type: string; name: string }): void {
108+
const legacyOverlayRemoval = host
109+
.mergesOverlayAtRead(request.type);
110+
if (host.isSealedManagedItem(request.type, request.name) && !legacyOverlayRemoval) {
111+
// [#20819, ADR-0131 D6] Sentence per ADR-0126 regime, as in the save door.
112+
const err = new Error(managedItemSealedSentence(request.type, request.name, 'delete'));
113+
(err as any).code = 'NOT_OVERRIDABLE';
114+
(err as any).status = 403;
115+
throw err;
116+
}
117+
}
118+
119+
/** The body of `ObjectStackProtocolImplementation#baseServesBundleMember`; the method's docblock there is its contract. */
120+
export function baseServesBundleMember(host: Pick<ProtocolHost, 'shippedArtifactsOf'>, type: string, name: string, base: string, item: unknown, shipping: ShippingPackages): boolean {
121+
const member = itemDiscriminator(canonicalMetaType(type), item);
122+
const baseShipsMember = shippingPackageIds(host.shippedArtifactsOf(type, name, shipping, member)).has(base);
123+
return baseAddressServesMember(base, boundPackageOf((item as { _packageId?: unknown } | null | undefined)?._packageId), baseShipsMember);
124+
}
125+
126+
/** The body of `ObjectStackProtocolImplementation#pairOfAddedMember`; the method's docblock there is its contract. */
127+
export function pairOfAddedMember(host: Pick<ProtocolHost, 'shippedArtifactsOf' | 'shippingPackagesOf' | 'shipsBundleName'>, type: string, name: string, base: string, member: string): string | undefined {
128+
const shipping = host.shippingPackagesOf(type);
129+
if (!host.shipsBundleName(type, name, base, shipping)) return undefined;
130+
if (shippingPackageIds(host.shippedArtifactsOf(type, name, shipping, member)).has(base)) return undefined;
131+
const pair = customizationPackageId(base);
132+
return pair.ok ? pair.value : undefined;
133+
}
134+
135+
/** The body of `ObjectStackProtocolImplementation#findPairAddedMemberRow`; the method's docblock there is its contract. */
136+
export async function findPairAddedMemberRow(host: Pick<ProtocolHost, 'findServedOverlayRow' | 'pairOfAddedMember'>, type: string, name: string, base: string, member: string | undefined, wantedMember: string,
137+
activeRows?: readonly StoredOverlayRow[],): Promise<any> {
138+
const pairOfAddition = host.pairOfAddedMember(type, name, base, wantedMember);
139+
if (pairOfAddition === undefined) return undefined;
140+
return (await host.findServedOverlayRow({
141+
type, name, state: 'active', packageId: pairOfAddition, ...memberOption(member),
142+
}, activeRows))?.row;
143+
}
144+
145+
/** The body of `ObjectStackProtocolImplementation#registryMemberServedAt`; the method's docblock there is its contract. */
146+
export function registryMemberServedAt(host: Pick<ProtocolHost, 'baseServesBundleMember' | 'engine' | 'shippedArtifactsOf' | 'shippingPackagesOf' | 'shipsBundleName'>, type: string, name: string, base: string, item: unknown, member: string | undefined): unknown {
147+
const shipping = host.shippingPackagesOf(type);
148+
if (!host.shipsBundleName(type, name, base, shipping)) return item;
149+
if (host.baseServesBundleMember(type, name, base, item, shipping)) return item;
150+
if (member !== undefined) return undefined;
151+
const own = host.shippedArtifactsOf(type, name, shipping)
152+
.find((artifact) => (artifact as { _packageId?: unknown } | null)?._packageId === base);
153+
if (own === undefined) return undefined;
154+
const candidate = host.engine.registry.getItem(type, name, base, itemDiscriminator(canonicalMetaType(type), own));
155+
return candidate !== undefined && host.baseServesBundleMember(type, name, base, candidate, shipping) ? candidate : undefined;
156+
}

0 commit comments

Comments
 (0)