From f0a972147422ddb96a0e136d9e29b825fb769267 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 07:07:17 +0000 Subject: [PATCH 1/6] fix(metadata-protocol): publish judges an object draft by the current ObjectSchema The draft promotion re-ran the save door's refusals on a stored draft but never its spec parse, so an object draft saved before a narrowing ObjectSchema refinement landed went live unjudged by it. The promotion now asks the parse of the draft as the publish serves it (ADR-0087 chain applied), with the save door's 422 INVALID_METADATA envelope, before anything is written; judge-only batches raise it too. Claude-Session: https://claude.ai/code/session_017xRBcRoJWF7MQr6HoRgBeC Co-authored-by: Claude --- .../src/protocol-history-and-publish.ts | 12 + .../protocol-promoted-draft-spec-refusal.ts | 70 +++++ ...tocol.publish-draft-schema-reparse.test.ts | 283 ++++++++++++++++++ 3 files changed, 365 insertions(+) create mode 100644 packages/metadata-protocol/src/protocol-promoted-draft-spec-refusal.ts create mode 100644 packages/metadata-protocol/src/protocol.publish-draft-schema-reparse.test.ts diff --git a/packages/metadata-protocol/src/protocol-history-and-publish.ts b/packages/metadata-protocol/src/protocol-history-and-publish.ts index 13a159fd7d9..9f79c4ba1d1 100644 --- a/packages/metadata-protocol/src/protocol-history-and-publish.ts +++ b/packages/metadata-protocol/src/protocol-history-and-publish.ts @@ -69,6 +69,7 @@ import { historySlotOf, refusePackageSelectorOutsideSlottedTypes } from './proto import { captureStoredExpressionChange, fillStoredExpressionChange, type StoredExpressionFillCapture } from './protocol-stored-expression-fill.js'; import { OBJECT_REGISTRY_REFUSED, reportObjectRegistryRefusal } from './protocol-registry-hydration.js'; import { OBJECT_EXTENSION_TYPE, registrableObjectExtension } from './protocol-object-extension-item.js'; +import { promotedObjectDraftSpecRefusal } from './protocol-promoted-draft-spec-refusal.js'; import { retireOverlayCacheOnRollback } from './meta-overlay-cache.js'; /** @@ -1098,6 +1099,17 @@ export class ProtocolHistoryAndPublishFacet { }, ); } + // [#35924] …and the save door's spec parse, asked of the draft + // this promotion makes live: a draft stored before a narrowing + // `ObjectSchema` refinement landed was never judged by it, and was + // promoted unjudged. Judged as the publish serves it (the ADR-0087 + // chain applied), with the save door's `422 INVALID_METADATA` and + // `issues[]`, before `repo.promoteDraft` writes; a judge-only call + // raises it too. Asked ahead of the registry's refusal, as the save + // door orders them, so a body both refuse keeps the structured + // `issues[]` (#5364). See {@link promotedObjectDraftSpecRefusal}. + const specRefusal = promotedObjectDraftSpecRefusal(request.name, draftForGate.body); + if (specRefusal) throw specRefusal; // [#29673] …and the registry's refusal of the body this promotion // makes live, on the same row and for the D9.9 refusal's reason: // the write-through runs after the row is active, where a refusal diff --git a/packages/metadata-protocol/src/protocol-promoted-draft-spec-refusal.ts b/packages/metadata-protocol/src/protocol-promoted-draft-spec-refusal.ts new file mode 100644 index 00000000000..3528de18409 --- /dev/null +++ b/packages/metadata-protocol/src/protocol-promoted-draft-spec-refusal.ts @@ -0,0 +1,70 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#35924] The save door's spec parse, asked again of an object draft at its + * promotion. + * + * `saveMetaItem` parses every object body against the current `ObjectSchema` + * (`resolveOverlaySchema` → `getMetadataTypeSchema('object')`) and refuses a + * body it rejects `422 INVALID_METADATA`. `promoteDraftForPublish` re-runs the + * save door's other refusals on the stored draft, because a draft stored + * before a rule landed was never judged by it (#4463 D1), but it did not ask + * the parse. So an object draft saved before a narrowing `ObjectSchema` + * refinement landed was promoted live at publish, unjudged by that refinement + * — the ADR-0154 D10 chain-column rule's sealed object without `tenant_id` + * is the first measured case. This is the parse, asked of the draft the + * promotion reads, with the save door's envelope: the same code and status, + * the same `issues[]` (registered refusal params included, #36594) and the + * same sentence on the default face. + * + * ## The body judged is the body the publish serves + * + * A stored row is read through the ADR-0087 conversion chain + * (`applyConversionsToStoredItem`, replayed with its retired entries by the + * protocol's read and by the database loader that registers the row), so a + * draft stored in a spelling a later release retired is served — and + * registered — in today's canonical shape. The parse judges that converted + * body ({@link convertStoredItemDetailed}, no notice logged here: the read + * warns once when it serves the row), not the stored bytes, so a draft the + * chain converts keeps publishing exactly as before. What is still refused + * after the chain is what the publish would make live while the current + * schema refuses it. + * + * `object` only: the type the card measured. The save door parses every type + * with a registered schema; whether the promotion should ask every one of + * them is a separate question (each type's stored-draft population differs — + * a `flow` is judged through `storedFlowVerdictBody`, a `view` stores its + * parsed projection), and is not answered here. + */ + +import { resolveOverlaySchema } from './protocol-meta-type-schema.js'; +import { zodIssuesToMetadataIssues, type MetadataIssueEntry } from './protocol-metadata-issues.js'; +import { convertStoredItemDetailed } from './protocol-stored-item-conversion.js'; +import { specValidationFindings } from './protocol-write-face.js'; + +/** The refusal {@link promotedObjectDraftSpecRefusal} answers: the save door's spec-validation 422. */ +export type PromotedDraftSpecRefusal = Error & { code: 'INVALID_METADATA'; status: 422; issues: MetadataIssueEntry[] }; + +/** + * The save door's spec-validation refusal of the object draft `body` the + * promotion of `object/name` reads, judged as the publish would serve it; + * `undefined` when the current `ObjectSchema` admits it (or no schema is + * registered for `object`, as the save door then parses nothing). + */ +export function promotedObjectDraftSpecRefusal(name: string, body: unknown): PromotedDraftSpecRefusal | undefined { + const schema = resolveOverlaySchema('object', body); + if (!schema) return undefined; + const served = convertStoredItemDetailed('object', body).item; + const parsed = schema.safeParse(served); + if (parsed.success) return undefined; + const issues = zodIssuesToMetadataIssues(parsed.error.issues, { refusalParams: true }); + // No write face: the publish doors declare none, so the sentence carries + // the findings in full, as every undeclared face of the save door does. + const err = new Error( + `object/${name} failed spec validation: ${specValidationFindings(undefined, issues)}`, + ) as PromotedDraftSpecRefusal; + err.code = 'INVALID_METADATA'; + err.status = 422; + err.issues = issues; + return err; +} diff --git a/packages/metadata-protocol/src/protocol.publish-draft-schema-reparse.test.ts b/packages/metadata-protocol/src/protocol.publish-draft-schema-reparse.test.ts new file mode 100644 index 00000000000..836c55abccc --- /dev/null +++ b/packages/metadata-protocol/src/protocol.publish-draft-schema-reparse.test.ts @@ -0,0 +1,283 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { describe, expect, it } from 'vitest'; +// The producer's OWN write-verb dispatch decisions, so the fake engine below +// cannot accept a call ObjectQL refuses (`check:engine-double-contract`). +import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFindOnePredicate, hashSpec } from '@objectstack/metadata-core'; +import { ObjectSchema } from '@objectstack/spec/data'; +// The draft verdict reaches `import('@objectstack/lint')`; paid at collection, +// never inside a case's clock (`check:test-source-alias`). +import '@objectstack/lint'; +import { ObjectStackProtocolImplementation } from './protocol.js'; + +interface Row { + id: string; + type: string; + name: string; + organization_id: string | null; + package_id: string | null; + state: string; + metadata: string; + checksum?: string; + version?: number; +} + +function keyOf(w: Record) { + return `${w.type}|${w.name}|${w.organization_id ?? '__env__'}|${w.state ?? 'active'}|${w.package_id ?? '__nopkg__'}`; +} + +/** Does row `r` satisfy `where` (top-level eq + `$or`)? */ +function matchesMetadataWhere(r: Row, where: Record): boolean { + for (const [k, v] of Object.entries(where)) { + if (k === '$or') { + const clauses = v as Array>; + if (!clauses.some((c) => matchesMetadataWhere(r, c))) return false; + continue; + } + // `undefined` = "dimension not constrained"; `null` = "must be NULL". + if (v === undefined) continue; + if (v !== null && typeof v === 'object' && !Array.isArray(v)) { + const op = v as Record; + if ('$in' in op) { + if (!(op.$in as unknown[]).includes((r as any)[k])) return false; + continue; + } + if ('$ne' in op) { + if ((r as any)[k] === op.$ne) return false; + continue; + } + } + if ((r as any)[k] !== v) return false; + } + return true; +} + +/** The package whose objects are saved and published here. */ +const PKG = 'com.acme.alpha'; +const NS = 'crm'; + +function makeStubEngine() { + const rows = new Map(); + let nextId = 0; + + const findRow = (w: Record): { key: string; row: Row } | null => { + if (w.id !== undefined) { + for (const [k, r] of rows) if (r.id === w.id) return { key: k, row: r }; + return null; + } + for (const [k, r] of rows) if (matchesMetadataWhere(r, w)) return { key: k, row: r }; + return null; + }; + + const manifests: Record> = { + [PKG]: { id: PKG, namespace: NS }, + }; + + const engine: any = { + async findOne(table: string, opts: { where: Record }) { + assertEngineFindOnePredicate(table, opts); + if (table !== 'sys_metadata') return null; + return findRow(opts.where)?.row ?? null; + }, + async find(table: string, opts: { where: Record; limit?: number }) { + if (table !== 'sys_metadata') return []; + const matched = Array.from(rows.values()).filter((r) => matchesMetadataWhere(r, opts.where ?? {})); + // The caller's bound, after the filter, by presence (`check:objectql-double-limit`). + return typeof opts?.limit === 'number' ? matched.slice(0, opts.limit) : matched; + }, + async insert(table: string, data: Record) { + nextId += 1; + if (table !== 'sys_metadata') return { id: `x_${nextId}` }; + const row = { id: `r_${nextId}`, ...(data as any) } as Row; + rows.set(keyOf(data), row); + return { id: row.id }; + }, + async update(table: string, data: Record, opts: { where: Record }) { + assertEngineUpdateDispatch(data, opts); + if (table !== 'sys_metadata') return { id: null }; + const found = findRow(opts.where); + if (!found) return { id: null }; + const merged = { ...found.row, ...(data as any) }; + rows.delete(found.key); + rows.set(keyOf(merged), merged); + return { id: found.row.id }; + }, + async delete(table: string, opts: { where: Record }) { + assertEngineDeleteDispatch(opts); + if (table !== 'sys_metadata') return { deleted: 0 }; + const found = findRow(opts.where); + if (!found) return { deleted: 0 }; + rows.delete(found.key); + return { deleted: 1 }; + }, + async transaction(cb: (ctx: any, info: { owned: boolean }) => Promise): Promise { + return cb(undefined, { owned: true }); + }, + registry: { + registerItem: () => {}, + registerObject: () => {}, + getPackage: (id: string) => (manifests[id] ? { manifest: manifests[id] } : undefined), + getAllPackages: () => Object.values(manifests).map((manifest) => ({ manifest })), + }, + }; + return { engine, rows }; +} + +/** + * A sealed audit-class object whose default chain column `tenant_id` is a + * declared lookup — the body the ADR-0154 D10 chain-column refinement admits. + */ +const sealedLedger = (name: string) => ({ + name, + label: `Ledger ${name}`, + sharingModel: 'private', + fields: { + action: { type: 'text', label: 'Action' }, + old_value: { type: 'textarea', label: 'Old Value' }, + tenant_id: { type: 'lookup', reference: 'sys_organization', label: 'Organization' }, + }, + lifecycle: { class: 'audit', retention: { maxAge: '90d' }, seal: { valueFields: ['old_value'] } }, +}); + +/** + * The same object as stored before that refinement landed: no `tenant_id`, so + * the current `ObjectSchema` refuses it. + */ +const preRefinementLedger = (name: string) => { + const body = sealedLedger(name); + const { tenant_id: _dropped, ...fields } = body.fields; + return { ...body, fields }; +}; + +/** + * Overwrites the stored draft row's body in place: the draft a save wrote + * before the refinement that now refuses it, with the checksum the store + * would have written for it. + */ +function rewriteStoredDraft(rows: Map, name: string, body: unknown) { + const row = [...rows.values()].find((r) => r.type === 'object' && r.name === name && r.state === 'draft'); + if (!row) throw new Error(`no stored draft of object/${name}`); + row.metadata = JSON.stringify(body); + row.checksum = hashSpec(body, 'object'); +} + +const rowsFor = (rows: Map, name: string) => + Array.from(rows.values()) + .filter((r) => r.type === 'object' && r.name === name) + .map((r) => ({ state: r.state, package_id: r.package_id })); + +/** The ADR-0154 D10 default-chain-column refusal, located as the spec raises it. */ +const defaultChainIssue = (outcome: unknown) => + ((outcome as { issues?: Array<{ path: string }> }).issues ?? []).filter((i) => i.path.startsWith('lifecycle.seal')); + +/** Saves a valid draft, then rewrites its stored body as `stored`. */ +async function stagePreRefinementDraft(protocol: ObjectStackProtocolImplementation, rows: Map, name: string, stored: unknown) { + await protocol.saveMetaItem({ type: 'object', name, item: sealedLedger(name), packageId: PKG, mode: 'draft' }); + rewriteStoredDraft(rows, name, stored); +} + +/** + * [#35924] An object draft stored before a narrowing `ObjectSchema` + * refinement landed is judged by it at publish. + * + * Measured on `origin/main` before the fix (this file's pins, unfixed): the + * per-item publish of the pre-refinement draft answered `success: true` and + * the package publish `outcome: 'published'`, each writing the active row — + * while the save door refuses the same body `422 INVALID_METADATA`. The + * promotion re-ran the save door's other refusals on the stored draft and + * never the schema parse. + * + * The "draft saved before the refinement" is made by saving a body the + * current schema admits and rewriting the stored row to the body a store + * held from before ADR-0154 D10's chain-column rule (no `tenant_id`); the + * row's checksum is the one the store would have written for it. + * + * Harness: the real save, publish and repository paths over a stub engine + * whose write verbs are held to ObjectQL's own dispatch decisions. + */ +describe('[#35924] the publish judges an object draft by the current ObjectSchema', () => { + it('PREMISE — the fixtures straddle the refinement: one parses, the other is refused', () => { + expect(ObjectSchema.safeParse(sealedLedger('crm_ledger')).success).toBe(true); + expect(ObjectSchema.safeParse(preRefinementLedger('crm_ledger')).success).toBe(false); + }); + + it('the save door refuses the pre-refinement body — INVALID_METADATA / 422, nothing stored', async () => { + const { engine, rows } = makeStubEngine(); + const protocol = new ObjectStackProtocolImplementation(engine); + const name = 'crm_ledger'; + const outcome = await protocol.saveMetaItem({ type: 'object', name, item: preRefinementLedger(name), packageId: PKG, mode: 'draft' }) + .then(() => 'saved', (e: unknown) => e); + expect(outcome).toMatchObject({ code: 'INVALID_METADATA', status: 422 }); + expect(defaultChainIssue(outcome)).not.toEqual([]); + expect(rowsFor(rows, name)).toEqual([]); + }); + + it('the per-item publish refuses that draft with the save door\'s envelope; the draft stays a draft', async () => { + const { engine, rows } = makeStubEngine(); + const protocol = new ObjectStackProtocolImplementation(engine); + const name = 'crm_ledger'; + await stagePreRefinementDraft(protocol, rows, name, preRefinementLedger(name)); + + const saved = await protocol.saveMetaItem({ type: 'object', name, item: preRefinementLedger(name), packageId: PKG, mode: 'draft' }) + .then(() => 'saved', (e: unknown) => e); + const outcome = await protocol.publishMetaItem({ type: 'object', name, packageId: PKG }) + .then(() => 'published', (e: unknown) => e); + + expect(outcome).toMatchObject({ code: 'INVALID_METADATA', status: 422 }); + // The same findings the save door raises for the same body. + expect(defaultChainIssue(outcome)).toEqual(defaultChainIssue(saved)); + expect(defaultChainIssue(outcome)).not.toEqual([]); + expect(rowsFor(rows, name)).toEqual([{ state: 'draft', package_id: PKG }]); + }); + + it('the package publish refuses it into failed[] with nothing promoted', async () => { + const { engine, rows } = makeStubEngine(); + const protocol = new ObjectStackProtocolImplementation(engine); + const name = 'crm_ledger'; + await stagePreRefinementDraft(protocol, rows, name, preRefinementLedger(name)); + + const res: any = await protocol.publishPackageDrafts({ packageId: PKG } as any); + + expect(res).toMatchObject({ success: false, outcome: 'refused', publishedCount: 0, failedCount: 1 }); + expect(res.failed[0]).toMatchObject({ type: 'object', name, code: 'INVALID_METADATA' }); + expect(rowsFor(rows, name)).toEqual([{ state: 'draft', package_id: PKG }]); + }); +}); + +describe('[#35924] what the publish still promotes', () => { + it('CONTROL — a fresh valid draft publishes per item, as before', async () => { + const { engine, rows } = makeStubEngine(); + const protocol = new ObjectStackProtocolImplementation(engine); + const name = 'crm_ledger'; + await protocol.saveMetaItem({ type: 'object', name, item: sealedLedger(name), packageId: PKG, mode: 'draft' }); + + expect(await protocol.publishMetaItem({ type: 'object', name, packageId: PKG })).toMatchObject({ success: true }); + expect(rowsFor(rows, name)).toEqual([{ state: 'active', package_id: PKG }]); + }); + + it('CONTROL — a fresh valid draft publishes with its package, as before', async () => { + const { engine, rows } = makeStubEngine(); + const protocol = new ObjectStackProtocolImplementation(engine); + const name = 'crm_ledger'; + await protocol.saveMetaItem({ type: 'object', name, item: sealedLedger(name), packageId: PKG, mode: 'draft' }); + + expect(await protocol.publishPackageDrafts({ packageId: PKG } as any)) + .toMatchObject({ success: true, outcome: 'published', publishedCount: 1, failedCount: 0 }); + expect(rowsFor(rows, name)).toEqual([{ state: 'active', package_id: PKG }]); + }); + + it('CONTROL — a draft stored in a spelling the ADR-0087 chain converts still publishes: it is judged as served', async () => { + const { engine, rows } = makeStubEngine(); + const protocol = new ObjectStackProtocolImplementation(engine); + const name = 'crm_ledger'; + // `externalSharingModel` is tombstoned on the object shape (a live + // author is refused at parse) and stripped from a stored row by the + // chain (`object-external-sharing-model-removed`). + const legacy = { ...sealedLedger(name), externalSharingModel: 'private' }; + expect(ObjectSchema.safeParse(legacy).success).toBe(false); + await stagePreRefinementDraft(protocol, rows, name, legacy); + + expect(await protocol.publishMetaItem({ type: 'object', name, packageId: PKG })).toMatchObject({ success: true }); + expect(rowsFor(rows, name)).toEqual([{ state: 'active', package_id: PKG }]); + }); +}); From 9d3ff84b969af0e654c6a3c28cc7d31bdd29d79b Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 07:08:34 +0000 Subject: [PATCH 2/6] test(metadata-protocol): pin the judge-only package publish of a pre-refinement object draft Claude-Session: https://claude.ai/code/session_017xRBcRoJWF7MQr6HoRgBeC Co-authored-by: Claude --- ...tocol.publish-draft-schema-reparse.test.ts | 40 ++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/packages/metadata-protocol/src/protocol.publish-draft-schema-reparse.test.ts b/packages/metadata-protocol/src/protocol.publish-draft-schema-reparse.test.ts index 836c55abccc..ec3feca22e8 100644 --- a/packages/metadata-protocol/src/protocol.publish-draft-schema-reparse.test.ts +++ b/packages/metadata-protocol/src/protocol.publish-draft-schema-reparse.test.ts @@ -56,7 +56,12 @@ function matchesMetadataWhere(r: Row, where: Record): boolean { const PKG = 'com.acme.alpha'; const NS = 'crm'; -function makeStubEngine() { +/** + * `rollback: false` gives the engine a default driver that declares no + * transactions, so `engineCanRollBack` answers false and a package publish + * judges its whole batch (`judgeOnly`) before it promotes any of it. + */ +function makeStubEngine(options: { rollback?: boolean } = {}) { const rows = new Map(); let nextId = 0; @@ -113,6 +118,12 @@ function makeStubEngine() { async transaction(cb: (ctx: any, info: { owned: boolean }) => Promise): Promise { return cb(undefined, { owned: true }); }, + ...(options.rollback === false + ? { + getDefaultDriverName: () => 'stub', + getDriverByName: () => ({ supports: { transactionsUnsupported: true } }), + } + : {}), registry: { registerItem: () => {}, registerObject: () => {}, @@ -242,6 +253,22 @@ describe('[#35924] the publish judges an object draft by the current ObjectSchem expect(res.failed[0]).toMatchObject({ type: 'object', name, code: 'INVALID_METADATA' }); expect(rowsFor(rows, name)).toEqual([{ state: 'draft', package_id: PKG }]); }); + + it('a package publish that judges before it writes (no rollback) refuses it in the judge pass: no draft of the batch goes live', async () => { + const { engine, rows } = makeStubEngine({ rollback: false }); + const protocol = new ObjectStackProtocolImplementation(engine); + const name = 'crm_ledger'; + const sibling = 'crm_journal'; + await protocol.saveMetaItem({ type: 'object', name: sibling, item: sealedLedger(sibling), packageId: PKG, mode: 'draft' }); + await stagePreRefinementDraft(protocol, rows, name, preRefinementLedger(name)); + + const res: any = await protocol.publishPackageDrafts({ packageId: PKG } as any); + + expect(res).toMatchObject({ success: false, outcome: 'refused', publishedCount: 0 }); + expect(res.failed.find((f: any) => f.name === name)).toMatchObject({ type: 'object', code: 'INVALID_METADATA' }); + expect(rowsFor(rows, name)).toEqual([{ state: 'draft', package_id: PKG }]); + expect(rowsFor(rows, sibling)).toEqual([{ state: 'draft', package_id: PKG }]); + }); }); describe('[#35924] what the publish still promotes', () => { @@ -266,6 +293,17 @@ describe('[#35924] what the publish still promotes', () => { expect(rowsFor(rows, name)).toEqual([{ state: 'active', package_id: PKG }]); }); + it('CONTROL — a fresh valid draft publishes with its package where the batch is judged first (no rollback), as before', async () => { + const { engine, rows } = makeStubEngine({ rollback: false }); + const protocol = new ObjectStackProtocolImplementation(engine); + const name = 'crm_ledger'; + await protocol.saveMetaItem({ type: 'object', name, item: sealedLedger(name), packageId: PKG, mode: 'draft' }); + + expect(await protocol.publishPackageDrafts({ packageId: PKG } as any)) + .toMatchObject({ success: true, outcome: 'published', publishedCount: 1, failedCount: 0 }); + expect(rowsFor(rows, name)).toEqual([{ state: 'active', package_id: PKG }]); + }); + it('CONTROL — a draft stored in a spelling the ADR-0087 chain converts still publishes: it is judged as served', async () => { const { engine, rows } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine); From c3c5411fb91f0c0b18737075ef56217c6048d214 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 07:08:59 +0000 Subject: [PATCH 3/6] chore(changeset): metadata-protocol publish re-parses an object draft Claude-Session: https://claude.ai/code/session_017xRBcRoJWF7MQr6HoRgBeC Co-authored-by: Claude --- .changeset/35924-publish-reparses-object-draft.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 .changeset/35924-publish-reparses-object-draft.md diff --git a/.changeset/35924-publish-reparses-object-draft.md b/.changeset/35924-publish-reparses-object-draft.md new file mode 100644 index 00000000000..86f910f3d4e --- /dev/null +++ b/.changeset/35924-publish-reparses-object-draft.md @@ -0,0 +1,14 @@ +--- +'@objectstack/metadata-protocol': patch +--- + +fix(metadata-protocol): publishing an object draft judges it by the current ObjectSchema + +Clause-②: no +Metadata-protocol: none + +A save checks an object body against the current `ObjectSchema` and refuses it with `422 INVALID_METADATA`. Publishing a draft did not repeat that check. So an object draft saved before a stricter `ObjectSchema` rule landed went live at publish, even though that rule refuses it. One example is a sealed object with no `tenant_id` chain column (ADR-0154 D10). + +Both publishes, per item and per package (including the pass that judges a batch before it writes on a store that cannot roll back), now check the draft the same way a save does. They refuse it with the same `422 INVALID_METADATA` and the same `issues[]`, before anything is written. The draft is checked as the publish would serve it, after the stored-row conversions are applied. So a draft stored in a spelling a later release retired, which those conversions rewrite, still publishes as before. + +A refused draft stays a draft. To publish it, fix the keys the issues name and save it again, the same fix a save of that body asks for. Every body this refuses is one a save of the same body already refuses. From 502a4a7dbf52cbd52191b1de8113a57d02c73af3 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 07:29:21 +0000 Subject: [PATCH 4/6] test(engine-double-contract): record the publish re-parse pins in the pinned ledger Claude-Session: https://claude.ai/code/session_017xRBcRoJWF7MQr6HoRgBeC Co-authored-by: Claude --- scripts/engine-double-contract.pinned.json | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/scripts/engine-double-contract.pinned.json b/scripts/engine-double-contract.pinned.json index 26ec3022c81..63734d4631f 100644 --- a/scripts/engine-double-contract.pinned.json +++ b/scripts/engine-double-contract.pinned.json @@ -1806,6 +1806,21 @@ "verb": "update", "pinned": 1 }, + { + "file": "packages/metadata-protocol/src/protocol.publish-draft-schema-reparse.test.ts", + "verb": "delete", + "pinned": 1 + }, + { + "file": "packages/metadata-protocol/src/protocol.publish-draft-schema-reparse.test.ts", + "verb": "findOne", + "pinned": 1 + }, + { + "file": "packages/metadata-protocol/src/protocol.publish-draft-schema-reparse.test.ts", + "verb": "update", + "pinned": 1 + }, { "file": "packages/metadata-protocol/src/protocol.publish-item-draft-org-scope.test.ts", "verb": "delete", From f7534a6467da1e531d2d3871481ae5c62bedaaa1 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 10:01:54 +0000 Subject: [PATCH 5/6] chore(changeset): declare the publish re-parse a narrowing, with its upgrade-guide entry Claude-Session: https://claude.ai/code/session_017xRBcRoJWF7MQr6HoRgBeC Co-authored-by: Claude --- .../35924-publish-reparses-object-draft.md | 19 +++++++++---- ...object-draft-the-current-schema-refuses.ts | 28 +++++++++++++++++++ 2 files changed, 42 insertions(+), 5 deletions(-) create mode 100644 packages/spec/src/migrations/entries/semantic/19.publish-refuses-object-draft-the-current-schema-refuses.ts diff --git a/.changeset/35924-publish-reparses-object-draft.md b/.changeset/35924-publish-reparses-object-draft.md index 86f910f3d4e..c1d0ae6e995 100644 --- a/.changeset/35924-publish-reparses-object-draft.md +++ b/.changeset/35924-publish-reparses-object-draft.md @@ -1,14 +1,23 @@ --- -'@objectstack/metadata-protocol': patch +'@objectstack/metadata-protocol': minor +'@objectstack/spec': patch --- -fix(metadata-protocol): publishing an object draft judges it by the current ObjectSchema +fix(metadata-protocol)!: publishing an object draft judges it by the current ObjectSchema Clause-②: no -Metadata-protocol: none +Metadata-protocol: narrowed + + + +**BREAKING** for an object draft the current `ObjectSchema` refuses. Before this change it published; now it is refused at publish, and the refusal names the fix. Stored metadata is not rewritten or refused at boot, and an active row is unchanged. The refusal comes at the next publish of such a draft. A save checks an object body against the current `ObjectSchema` and refuses it with `422 INVALID_METADATA`. Publishing a draft did not repeat that check. So an object draft saved before a stricter `ObjectSchema` rule landed went live at publish, even though that rule refuses it. One example is a sealed object with no `tenant_id` chain column (ADR-0154 D10). -Both publishes, per item and per package (including the pass that judges a batch before it writes on a store that cannot roll back), now check the draft the same way a save does. They refuse it with the same `422 INVALID_METADATA` and the same `issues[]`, before anything is written. The draft is checked as the publish would serve it, after the stored-row conversions are applied. So a draft stored in a spelling a later release retired, which those conversions rewrite, still publishes as before. +Both publishes now check the draft the same way a save does: per item (`POST /api/v1/meta/object/:name/publish`) and per package (`POST /api/v1/packages/:id/publish-drafts`), including the pass that judges a batch before it writes on a store that cannot roll back. They refuse it with the same `422 INVALID_METADATA` and the same `issues[]` before anything is written. The draft stays a draft, and a package publish refuses its whole batch with nothing promoted. The draft is checked as the publish would serve it, after the stored-row conversions are applied. So a draft stored in a spelling a later release retired, which those conversions rewrite, still publishes as before. + +## FROM → TO + +- A pending object draft the current schema refuses, for example a sealed audit object (`lifecycle.seal`) with no `chainField` and no `tenant_id` field. That draft is refused at publish. The fix: declare the chain column, `fields: { tenant_id: { type: 'lookup', reference: 'sys_organization' } }`, or name one, `lifecycle: { seal: { valueFields: [...], chainField: 'organization_id' } }`. Then save the draft again and publish. Whatever the refusal's `issues[]` names, the fix is the one a save of the same body asks for. To find such drafts before upgrading, read each pending object draft: those whose `_diagnostics.valid` is `false` are the ones a publish will refuse. -A refused draft stays a draft. To publish it, fix the keys the issues name and save it again, the same fix a save of that body asks for. Every body this refuses is one a save of the same body already refuses. +`@objectstack/spec` adds only the upgrade-guide entry `publish-refuses-object-draft-the-current-schema-refuses`. diff --git a/packages/spec/src/migrations/entries/semantic/19.publish-refuses-object-draft-the-current-schema-refuses.ts b/packages/spec/src/migrations/entries/semantic/19.publish-refuses-object-draft-the-current-schema-refuses.ts new file mode 100644 index 00000000000..50983afe168 --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/19.publish-refuses-object-draft-the-current-schema-refuses.ts @@ -0,0 +1,28 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// The upgrade-guide entry of the publish door's object re-parse (#35924): the +// per-item and package publish now judge a stored object draft by the current +// `ObjectSchema`, as the save door judges the same body. Notice only: no key +// is removed and no D2 conversion exists. A draft the ADR-0087 chain converts +// is judged as served and keeps publishing; what is refused is a draft the +// current schema refuses after the chain, and its fix is the author's. +export const entry: SemanticMigration = { + id: 'publish-refuses-object-draft-the-current-schema-refuses', + surface: + 'The per-item publish (`POST /api/v1/meta/object/:name/publish`) and the package publish (`POST /api/v1/packages/:id/publish-drafts`) of an ' + + '`object` draft: the draft is parsed against the current `ObjectSchema`, as served (the stored-row conversion ' + + 'chain applied), before it is promoted, and refused `422 INVALID_METADATA` with the save door\'s `issues[]`', + replacement: + 'Fix the keys the refusal\'s `issues[]` names, save the draft again (the save answers the same refusal until ' + + 'the body parses), then publish', + reason: + 'A draft saved before a stricter `ObjectSchema` rule landed (for example a sealed audit object with no ' + + '`tenant_id` chain column, ADR-0154 D10) was promoted live at publish, unjudged by that rule, while a save of ' + + 'the same body is refused. Stored metadata is not rewritten or refused at boot; an active row is unchanged. ' + + 'The next publish of such a draft is refused, the draft stays a draft, and a package publish refuses its ' + + 'whole batch with nothing promoted.', + acceptanceCriteria: + 'Every pending object draft reads `_diagnostics.valid: true`; a publish of every object draft the package carries succeeds.', +}; From 8627792974c5ca88f4c6e1682ed3feec7a5cd66b Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 12:49:00 +0000 Subject: [PATCH 6/6] fix(changeset): declare the narrowing arm; source the legacy spelling from the retirement kit's fixture Claude-Session: https://claude.ai/code/session_017xRBcRoJWF7MQr6HoRgBeC Co-authored-by: Claude --- .../35924-publish-reparses-object-draft.md | 2 +- ...tocol.publish-draft-schema-reparse.test.ts | 29 ++++++++++++++++--- 2 files changed, 26 insertions(+), 5 deletions(-) diff --git a/.changeset/35924-publish-reparses-object-draft.md b/.changeset/35924-publish-reparses-object-draft.md index c1d0ae6e995..690061a1d74 100644 --- a/.changeset/35924-publish-reparses-object-draft.md +++ b/.changeset/35924-publish-reparses-object-draft.md @@ -5,7 +5,7 @@ fix(metadata-protocol)!: publishing an object draft judges it by the current ObjectSchema -Clause-②: no +Clause-②: no (narrowing) Metadata-protocol: narrowed diff --git a/packages/metadata-protocol/src/protocol.publish-draft-schema-reparse.test.ts b/packages/metadata-protocol/src/protocol.publish-draft-schema-reparse.test.ts index ec3feca22e8..7533c96544f 100644 --- a/packages/metadata-protocol/src/protocol.publish-draft-schema-reparse.test.ts +++ b/packages/metadata-protocol/src/protocol.publish-draft-schema-reparse.test.ts @@ -5,6 +5,7 @@ import { describe, expect, it } from 'vitest'; // cannot accept a call ObjectQL refuses (`check:engine-double-contract`). import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFindOnePredicate, hashSpec } from '@objectstack/metadata-core'; import { ObjectSchema } from '@objectstack/spec/data'; +import { ALL_CONVERSIONS } from '@objectstack/spec'; // The draft verdict reaches `import('@objectstack/lint')`; paid at collection, // never inside a case's clock (`check:test-source-alias`). import '@objectstack/lint'; @@ -172,6 +173,22 @@ function rewriteStoredDraft(rows: Map, name: string, body: unknown) row.checksum = hashSpec(body, 'object'); } +/** The ADR-0087 conversion whose retired object key the legacy-spelling CONTROL stores. */ +const LEGACY_SPELLING_CONVERSION = 'object-external-sharing-model-removed'; + +/** + * The object keys conversion `id` strips, with the values its own fixture + * stores: the keys of the fixture's first `before` object that the matching + * `after` object no longer carries. + */ +function retiredObjectKeysOf(id: string): Record { + const conversion = ALL_CONVERSIONS.find((c) => c.id === id); + if (!conversion) throw new Error(`no ADR-0087 conversion '${id}'`); + const [before] = (conversion.fixture.before as { objects: Array> }).objects; + const [after] = (conversion.fixture.after as { objects: Array> }).objects; + return Object.fromEntries(Object.entries(before ?? {}).filter(([key]) => !(after && key in after))); +} + const rowsFor = (rows: Map, name: string) => Array.from(rows.values()) .filter((r) => r.type === 'object' && r.name === name) @@ -308,10 +325,14 @@ describe('[#35924] what the publish still promotes', () => { const { engine, rows } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine); const name = 'crm_ledger'; - // `externalSharingModel` is tombstoned on the object shape (a live - // author is refused at parse) and stripped from a stored row by the - // chain (`object-external-sharing-model-removed`). - const legacy = { ...sealedLedger(name), externalSharingModel: 'private' }; + // The retired spelling comes from the retirement kit's own fixture, + // never authored here: the keys the conversion's `before` object + // carries and its `after` object does not. This file authors no + // retired key, so the kit's tree-scoped absence pin keeps its radius. + // Its key is tombstoned on the object shape (a live author is refused + // at parse) and stripped from a stored row by the chain. + const legacy = { ...sealedLedger(name), ...retiredObjectKeysOf(LEGACY_SPELLING_CONVERSION) }; + expect(Object.keys(retiredObjectKeysOf(LEGACY_SPELLING_CONVERSION))).not.toEqual([]); expect(ObjectSchema.safeParse(legacy).success).toBe(false); await stagePreRefinementDraft(protocol, rows, name, legacy);