From 1896afa32a6eae1a0d0789a00161e5456a75541c Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 13:57:24 +0000 Subject: [PATCH 1/9] test(rest): measure the draft window inside Save to this view (WIP measurement, M1 red on main) Measurement only, for a needs_decision report: M1 shows the publish door's active-row If-Match does not see a draft written between Save to this view's draft write and its publish; M2 shows a client-side pin on updateView's draft write does not either; M0 and M3 record the tokens and the active-save door's answer. Not for landing. Claude-Session: https://claude.ai/code/session_012MmDsSBHy5paNUz6zke9Re Co-authored-by: Claude --- ...tem-publish-draft-interleave-36350.test.ts | 189 ++++++++++++++++++ 1 file changed, 189 insertions(+) create mode 100644 packages/rest/src/meta-item-publish-draft-interleave-36350.test.ts diff --git a/packages/rest/src/meta-item-publish-draft-interleave-36350.test.ts b/packages/rest/src/meta-item-publish-draft-interleave-36350.test.ts new file mode 100644 index 00000000000..074bcef9cfe --- /dev/null +++ b/packages/rest/src/meta-item-publish-draft-interleave-36350.test.ts @@ -0,0 +1,189 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * MEASUREMENT (objectstack#36350) — does anything on the publish door today + * see a draft that moved between "Save to this view"'s draft write and its + * publish? Driven at the HTTP door on the real stack, as the sibling + * `meta-item-publish-version-pin.test.ts` is. + */ + +import { describe, it, expect, afterEach } from 'vitest'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; +import { SysMetadata, SysMetadataHistoryObject, SysMetadataAuditObject } from '@objectstack/platform-objects/metadata'; +import { RestServer } from './rest-server.js'; + +const TEST_PACKAGE_ID = 'objectstack-test'; +const META = '/api/v1/meta'; + +const TASK = { + name: 'task', + label: 'Task', + fields: { + id: { name: 'id', type: 'text' as const, primaryKey: true, label: 'ID' }, + name: { name: 'name', type: 'text' as const, label: 'Name' }, + }, +}; + +const view = (label: string, extra: Record = {}) => ({ + name: 'case_grid', + label, + object: 'task', + viewKind: 'list', + columns: [{ field: 'name', label: 'Name' }], + ...extra, +}); + +const liveEngines: ObjectQL[] = []; +afterEach(async () => { + while (liveEngines.length) { + try { await liveEngines.pop()?.destroy(); } catch { /* noop */ } + } +}); + +function createMockServer() { + const noop = () => {}; + return { get: noop, post: noop, put: noop, delete: noop, patch: noop, use: noop, listen: async () => {}, close: async () => {} }; +} + +function makeRes() { + const res: any = { statusCode: 200, body: undefined, headers: {} as Record }; + res.status = (code: number) => { res.statusCode = code; return res; }; + res.json = (body: any) => { res.body = body; return res; }; + res.send = () => res; + res.end = () => res; + res.header = (k: string, v: string) => { res.headers[k] = v; return res; }; + res.setHeader = () => {}; + res.write = () => true; + return res; +} + +async function boot() { + const engine = new ObjectQL(); + liveEngines.push(engine); + engine.registerDriver(new SqlDriver({ + client: 'better-sqlite3', + connection: { filename: ':memory:' }, + useNullAsDefault: true, + }), true); + await engine.init(); + engine.registry.registerObject(TASK as any, TEST_PACKAGE_ID); + engine.registry.registerObject(SysMetadata as any, TEST_PACKAGE_ID); + engine.registry.registerObject(SysMetadataHistoryObject as any, TEST_PACKAGE_ID); + engine.registry.registerObject(SysMetadataAuditObject as any, TEST_PACKAGE_ID); + await engine.syncSchemas(); + + const protocol = new ObjectStackProtocolImplementation(engine as any); + const rest: any = new RestServer( + createMockServer() as any, + protocol as any, + { api: { requireAuth: false }, metadata: { enableCache: false } } as any, + ); + rest.resolveExecCtx = async () => ({ userId: 'u_author', systemPermissions: ['manage_metadata'] }); + rest.registerRoutes(); + + const route = (method: string, path: string) => { + const found = rest.getRoutes().find((r: any) => r.method === method && r.path === path); + if (!found) throw new Error(`${method} ${path} is not registered`); + return found; + }; + const call = async (method: string, routePath: string, req: Record) => { + const res = makeRes(); + await route(method, routePath).handler({ method, headers: {}, query: {}, params: {}, ...req }, res); + return res; + }; + const item = { type: 'view', name: 'case_grid' }; + const path = `${META}/view/case_grid`; + const layers = () => + call('GET', `${META}/:type/:name/layers`, { path: `${path}/layers`, params: item }); + const readDraft = () => call('GET', `${META}/:type/:name`, { path, params: item, query: { state: 'draft' } }); + const save = (body: unknown, query: Record = {}, headers: Record = {}) => + call('PUT', `${META}/:type/:name`, { path, params: item, query, headers, body }); + const publish = (headers: Record = {}) => + call('POST', `${META}/:type/:name/publish`, { path: `${path}/publish`, params: item, headers, body: {} }); + const stored = async (state: 'active' | 'draft') => { + const rows = await engine.find('sys_metadata', { where: { type: 'view', name: 'case_grid', state } }); + return (rows ?? []).map((r: any) => JSON.parse(String(r.metadata))); + }; + return { layers, readDraft, save, publish, stored }; +} + +const ok = (res: any) => { + expect(res.statusCode, JSON.stringify(res.body)).toBe(200); + return res.body; +}; + +describe('[#36350 measurement] a draft that moves inside "Save to this view"', () => { + it('M0 the tokens: the draft receipt token, the draft read token and the active overlayVersion', async () => { + const h = await boot(); + const live = ok(await h.save(view('live'))); + const loaded = ok(await h.layers()).overlayVersion; + const saveDraft = ok(await h.save(view('save to this view'), { mode: 'draft' }, { 'if-none-match': '*' })); + const draftRead = ok(await h.readDraft()); + // eslint-disable-next-line no-console + console.log('M0', JSON.stringify({ + activeReceipt: live.version, overlayVersion: loaded, + draftReceipt: saveDraft.version, draftReadVersion: draftRead.version, + layersAfterDraft: ok(await h.layers()).overlayVersion, + })); + // A publish pinned with the DRAFT's token, under today's meaning of If-Match: + const pinnedToDraft = await h.publish({ 'if-match': saveDraft.version }); + // eslint-disable-next-line no-console + console.log('M0 publish If-Match=', pinnedToDraft.statusCode, JSON.stringify(pinnedToDraft.body)); + }, 60_000); + + it('M1 acceptance shape on main: Save pins the publish with the strongest pin main offers (active If-Match) — an interleaved updateView draft write must be refused', async () => { + const h = await boot(); + ok(await h.save(view('live'))); + const loaded = ok(await h.layers()).overlayVersion; + // "Save to this view": the draft over no draft. + ok(await h.save(view('save to this view'), { mode: 'draft' }, { 'if-none-match': '*' })); + // updateView's draft branch (rename / pin / set default): read the draft, merge, write back unpinned. + const draft = ok(await h.layers()).draft; + ok(await h.save({ ...draft, label: 'renamed, meant as a draft' }, { mode: 'draft' })); + // "Save to this view"'s publish, pinned to the active row it loaded. + const res = await h.publish({ 'if-match': loaded }); + // eslint-disable-next-line no-console + console.log('M1 publish', res.statusCode, JSON.stringify(res.body).slice(0, 300)); + // eslint-disable-next-line no-console + console.log('M1 active after', JSON.stringify((await h.stored('active')).map((r: any) => r.label))); + expect(res.statusCode).toBe(409); + expect(res.body.code).toBe('METADATA_CONFLICT'); + expect((await h.stored('active')).map((r: any) => r.label)).toEqual(['live']); + }, 60_000); + + it('M2 direction B extended: updateView pinned to the draft version it read inside the window — does the pin refuse it?', async () => { + const h = await boot(); + ok(await h.save(view('live'))); + ok(await h.save(view('save to this view'), { mode: 'draft' }, { 'if-none-match': '*' })); + // updateView reads INSIDE the window: the draft it reads is Save's own. + const read = ok(await h.readDraft()); + const draft = ok(await h.layers()).draft; + const write = await h.save({ ...draft, label: 'renamed, meant as a draft' }, { mode: 'draft' }, { 'if-match': read.version }); + const res = await h.publish(); + // eslint-disable-next-line no-console + console.log('M2 pinned updateView write', write.statusCode, '· publish', res.statusCode, + '· active after', JSON.stringify((await h.stored('active')).map((r: any) => r.label))); + }, 60_000); + + it('M3 no draft window at all: an ACTIVE save pinned to the loaded active row, with and without a pending draft', async () => { + const h = await boot(); + ok(await h.save(view('live'))); + const loaded = ok(await h.layers()).overlayVersion; + // Someone's unpublished draft is pending. + ok(await h.save(view('someone else, unreviewed'), { mode: 'draft' }, { 'if-none-match': '*' })); + const res = await h.save(view('save to this view, active'), {}, { 'if-match': loaded }); + // eslint-disable-next-line no-console + console.log('M3 active PUT over pending draft', res.statusCode, JSON.stringify(res.body).slice(0, 300), + '· active', JSON.stringify((await h.stored('active')).map((r: any) => r.label)), + '· draft', JSON.stringify((await h.stored('draft')).map((r: any) => r.label))); + // The other author's later publish, pinned to what THEY loaded. + const theirs = await h.publish({ 'if-match': loaded }); + // eslint-disable-next-line no-console + console.log('M3 their pinned publish afterwards', theirs.statusCode, JSON.stringify(theirs.body).slice(0, 200)); + const stale = await h.save(view('stale active'), {}, { 'if-match': loaded }); + // eslint-disable-next-line no-console + console.log('M3 stale active PUT', stale.statusCode, JSON.stringify(stale.body).slice(0, 200)); + }, 60_000); +}); From 186d0bd644b15963217adcdfbf533543cc92f451 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 23:00:08 +0000 Subject: [PATCH 2/9] feat(rest,metadata-protocol,spec): the per-item publish takes a draft-version pin (draftVersion) The publish door refuses a draft that moved since the caller wrote or read it, 409 METADATA_CONFLICT naming the draft's current token, beside the active-row If-Match pin. Ruling 7168616260 (A1). Claude-Session: https://claude.ai/code/session_012MmDsSpwtcn5gbWrBDA3Jm Co-authored-by: Claude --- .../src/protocol-history-and-publish.ts | 95 ++++++--- packages/metadata-protocol/src/protocol.ts | 2 + packages/rest/src/meta-item-history-routes.ts | 21 ++ ...tem-publish-draft-interleave-36350.test.ts | 189 ------------------ .../src/meta-item-publish-version-pin.test.ts | 121 ++++++++++- packages/spec/src/api/protocol.test.ts | 18 ++ packages/spec/src/api/protocol.zod.ts | 18 +- 7 files changed, 242 insertions(+), 222 deletions(-) delete mode 100644 packages/rest/src/meta-item-publish-draft-interleave-36350.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 d986866a4ca..83b0ed27024 100644 --- a/packages/metadata-protocol/src/protocol-history-and-publish.ts +++ b/packages/metadata-protocol/src/protocol-history-and-publish.ts @@ -736,6 +736,13 @@ export class ProtocolHistoryAndPublishFacet { * nothing. */ parentVersion?: string | null; + /** + * [#36350] `PublishMetaItemRequestSchema.draftVersion`: the + * caller's pin on the draft this promotion reads — a token, absent + * for unpinned. Stated by the per-item publish only; a package + * publish pins nothing. + */ + draftVersion?: string; /** * [ADR-0144 D2 and D6, amended] The registry question this * promotion asks before the row goes live, stated by every producer @@ -908,10 +915,69 @@ export class ProtocolHistoryAndPublishFacet { { verb: 'publish' }, ); if (unboundBase) throw unboundBase; + // [#21207] A conflict refused at this door, keyed values or none in + // the text and attributes, carrying its audit row. `draft-pin` is the + // caller's `draftVersion` refused; `promotion` is the store's own + // refusal at `repo.promoteDraft` (the judged draft moved, or the + // caller's `parentVersion` on the active row did not hold). + const publishConflictRefusal = async (err: ConflictError, at: 'draft-pin' | 'promotion'): Promise => { + const subject = `${request.type}/${request.name}`; + const conflict = await host.metadataConflictRefusal( + err, + subject, + at === 'draft-pin' + ? `${subject} draft changed since the version this publish pinned (draftVersion), so nothing was ` + + `published. Re-read the draft and publish again to promote what it holds now.` + : err instanceof DraftConflictError + ? `${subject} draft changed after this publish judged it, so nothing was ` + + `published. Publish again to judge and promote the current draft.` + : `${subject} published row advanced while you held the draft.`, + // [#36601] A publish pinned "no active row here" is told so, as the save door's first-write pin is. + at === 'promotion' && request.parentVersion === null && !(err instanceof DraftConflictError) ? 'active' : undefined, + ); + // [#8594] Attached, not written — same reason as the lock gate + // above. The repository's own transaction has already unwound by + // the time the caller's `catch` runs, but the BATCH caller's has not. + return withPendingAudit( + conflict, + host.optimisticConflictAuditEntry({ + type: request.type, + name: request.name, + operation: 'publish', + ...(request.actor ? { actor: request.actor } : {}), + source: 'protocol.publishMetaItem', + expectedParent: err.expectedParent, + actualHead: err.actualHead, + }), + ); + }; const draftForGate = await repo.get( { type: singularType, name: request.name, org: 'env' } as Parameters[0], { state: 'draft', packageId: draftKey, ...memberOption(request.member) }, ); + // [ruling 7168616260 on #36350] The caller's pin on the DRAFT this + // promotion reads (`PublishMetaItemRequestSchema.draftVersion`), + // judged before any rule judges the draft: a token is matched in keyed + // form against the draft row just read ({@link storedParentForToken}, + // the save door's comparison), and a draft that moved since the + // caller wrote or read it — or is no longer pending — is refused 409 + // `METADATA_CONFLICT` naming the draft's current token, with nothing + // promoted. Held through the write by `expectedDraftHash` below, which + // locks the promotion to this same row. `parentVersion` pins the + // active row; the two judge different rows and may be sent together. + // Absent, any pending draft is promoted, as before. + if (request.draftVersion !== undefined) { + try { + await host.storedParentForToken( + { type: singularType, name: request.name, org: 'env' }, + request.draftVersion, + draftForGate?.hash ?? null, + ); + } catch (err: unknown) { + if (err instanceof ConflictError) throw await publishConflictRefusal(err, 'draft-pin'); + throw err; + } + } // [ADR-0150 D4, ruling 6902014292] The environment's own action // draft is promoted into the one package-unbound active row of the // name: when that row is a holder's customization, the publish would @@ -1397,34 +1463,7 @@ export class ProtocolHistoryAndPublishFacet { ...(draftForGate ? { promotedDraft: { body: draftForGate.body, hash: draftForGate.hash } } : {}), }; } catch (err: any) { - if (err instanceof ConflictError) { - // [#21207] Keyed values or none in the text and attributes. - const conflict = await host.metadataConflictRefusal( - err, - `${request.type}/${request.name}`, - err instanceof DraftConflictError - ? `${request.type}/${request.name} draft changed after this publish judged it, so nothing was ` - + `published. Publish again to judge and promote the current draft.` - : `${request.type}/${request.name} published row advanced while you held the draft.`, - // [#36601] A publish pinned "no active row here" is told so, as the save door's first-write pin is. - request.parentVersion === null && !(err instanceof DraftConflictError) ? 'active' : undefined, - ); - // [#8594] Attached, not written — same reason as the lock gate - // above. The repository's own transaction has already unwound by - // the time this `catch` runs, but the BATCH caller's has not. - throw withPendingAudit( - conflict, - host.optimisticConflictAuditEntry({ - type: request.type, - name: request.name, - operation: 'publish', - ...(request.actor ? { actor: request.actor } : {}), - source: 'protocol.publishMetaItem', - expectedParent: err.expectedParent, - actualHead: err.actualHead, - }), - ); - } + if (err instanceof ConflictError) throw await publishConflictRefusal(err, 'promotion'); throw err; } } diff --git a/packages/metadata-protocol/src/protocol.ts b/packages/metadata-protocol/src/protocol.ts index c672534b9fe..f6903727c6f 100644 --- a/packages/metadata-protocol/src/protocol.ts +++ b/packages/metadata-protocol/src/protocol.ts @@ -9780,6 +9780,8 @@ export class ObjectStackProtocolImplementation implements userTextLocales?: readonly (string | undefined)[]; /** [#36601] The caller's pin on the active row this promotion replaces (`PublishMetaItemRequestSchema.parentVersion`). */ parentVersion?: string | null; + /** [#36350] The caller's pin on the draft this promotion reads (`PublishMetaItemRequestSchema.draftVersion`). */ + draftVersion?: string; /** The registry question this promotion asks (`registry-question.ts`). */ registryQuestion: RegistryQuestion; /** [#32396] Judge every refusal, write nothing: the answer then carries no `result`. */ diff --git a/packages/rest/src/meta-item-history-routes.ts b/packages/rest/src/meta-item-history-routes.ts index c63185dfe97..f2515823b83 100644 --- a/packages/rest/src/meta-item-history-routes.ts +++ b/packages/rest/src/meta-item-history-routes.ts @@ -698,6 +698,25 @@ export function registerMetaItemHistoryRoutes(this: MetaItemHistoryRouteHost, sc return; } const parentVersion = precondition.request.parentVersion; + // [ruling 7168616260 on #36350] The pin on the DRAFT this + // promotion reads (`PublishMetaItemRequestSchema.draftVersion`), + // a body member beside `message`: `If-Match` above keeps its + // shipped meaning (the active row's token). A present member + // that is not a string is refused `400`, never read as absent — + // dropped, it would publish unpinned exactly the draft the + // caller meant to guard. + const draftVersion: unknown = (body as Record).draftVersion; + if (draftVersion !== undefined && typeof draftVersion !== 'string') { + res.status(400).json({ + error: { + code: 'VALIDATION_ERROR', + message: 'draftVersion must be a string: the version token of the draft this publish ' + + 'promotes (a draft save\'s receipt version, or the draft read\'s version). ' + + 'Leave it out to publish whichever draft is pending.', + }, + }); + return; + } // [ADR-0131 D6] No organization, as on the `PUT` twin: a // draft is saved environment-wide, so the promotion looks in @@ -742,6 +761,8 @@ export function registerMetaItemHistoryRoutes(this: MetaItemHistoryRouteHost, sc ...(packageId ? { packageId } : {}), // [#36601] Present only when the caller pinned the active row. ...(parentVersion !== undefined ? { parentVersion } : {}), + // [#36350] Present only when the caller pinned the draft. + ...(typeof draftVersion === 'string' ? { draftVersion } : {}), // [#22877] Publishes ONE member's draft of a bundled type. ...metaMemberSelector(req.query), // [#32656] The languages the findings' `userMessage` is diff --git a/packages/rest/src/meta-item-publish-draft-interleave-36350.test.ts b/packages/rest/src/meta-item-publish-draft-interleave-36350.test.ts deleted file mode 100644 index 074bcef9cfe..00000000000 --- a/packages/rest/src/meta-item-publish-draft-interleave-36350.test.ts +++ /dev/null @@ -1,189 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * MEASUREMENT (objectstack#36350) — does anything on the publish door today - * see a draft that moved between "Save to this view"'s draft write and its - * publish? Driven at the HTTP door on the real stack, as the sibling - * `meta-item-publish-version-pin.test.ts` is. - */ - -import { describe, it, expect, afterEach } from 'vitest'; -import { ObjectQL } from '@objectstack/objectql'; -import { SqlDriver } from '@objectstack/driver-sql'; -import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; -import { SysMetadata, SysMetadataHistoryObject, SysMetadataAuditObject } from '@objectstack/platform-objects/metadata'; -import { RestServer } from './rest-server.js'; - -const TEST_PACKAGE_ID = 'objectstack-test'; -const META = '/api/v1/meta'; - -const TASK = { - name: 'task', - label: 'Task', - fields: { - id: { name: 'id', type: 'text' as const, primaryKey: true, label: 'ID' }, - name: { name: 'name', type: 'text' as const, label: 'Name' }, - }, -}; - -const view = (label: string, extra: Record = {}) => ({ - name: 'case_grid', - label, - object: 'task', - viewKind: 'list', - columns: [{ field: 'name', label: 'Name' }], - ...extra, -}); - -const liveEngines: ObjectQL[] = []; -afterEach(async () => { - while (liveEngines.length) { - try { await liveEngines.pop()?.destroy(); } catch { /* noop */ } - } -}); - -function createMockServer() { - const noop = () => {}; - return { get: noop, post: noop, put: noop, delete: noop, patch: noop, use: noop, listen: async () => {}, close: async () => {} }; -} - -function makeRes() { - const res: any = { statusCode: 200, body: undefined, headers: {} as Record }; - res.status = (code: number) => { res.statusCode = code; return res; }; - res.json = (body: any) => { res.body = body; return res; }; - res.send = () => res; - res.end = () => res; - res.header = (k: string, v: string) => { res.headers[k] = v; return res; }; - res.setHeader = () => {}; - res.write = () => true; - return res; -} - -async function boot() { - const engine = new ObjectQL(); - liveEngines.push(engine); - engine.registerDriver(new SqlDriver({ - client: 'better-sqlite3', - connection: { filename: ':memory:' }, - useNullAsDefault: true, - }), true); - await engine.init(); - engine.registry.registerObject(TASK as any, TEST_PACKAGE_ID); - engine.registry.registerObject(SysMetadata as any, TEST_PACKAGE_ID); - engine.registry.registerObject(SysMetadataHistoryObject as any, TEST_PACKAGE_ID); - engine.registry.registerObject(SysMetadataAuditObject as any, TEST_PACKAGE_ID); - await engine.syncSchemas(); - - const protocol = new ObjectStackProtocolImplementation(engine as any); - const rest: any = new RestServer( - createMockServer() as any, - protocol as any, - { api: { requireAuth: false }, metadata: { enableCache: false } } as any, - ); - rest.resolveExecCtx = async () => ({ userId: 'u_author', systemPermissions: ['manage_metadata'] }); - rest.registerRoutes(); - - const route = (method: string, path: string) => { - const found = rest.getRoutes().find((r: any) => r.method === method && r.path === path); - if (!found) throw new Error(`${method} ${path} is not registered`); - return found; - }; - const call = async (method: string, routePath: string, req: Record) => { - const res = makeRes(); - await route(method, routePath).handler({ method, headers: {}, query: {}, params: {}, ...req }, res); - return res; - }; - const item = { type: 'view', name: 'case_grid' }; - const path = `${META}/view/case_grid`; - const layers = () => - call('GET', `${META}/:type/:name/layers`, { path: `${path}/layers`, params: item }); - const readDraft = () => call('GET', `${META}/:type/:name`, { path, params: item, query: { state: 'draft' } }); - const save = (body: unknown, query: Record = {}, headers: Record = {}) => - call('PUT', `${META}/:type/:name`, { path, params: item, query, headers, body }); - const publish = (headers: Record = {}) => - call('POST', `${META}/:type/:name/publish`, { path: `${path}/publish`, params: item, headers, body: {} }); - const stored = async (state: 'active' | 'draft') => { - const rows = await engine.find('sys_metadata', { where: { type: 'view', name: 'case_grid', state } }); - return (rows ?? []).map((r: any) => JSON.parse(String(r.metadata))); - }; - return { layers, readDraft, save, publish, stored }; -} - -const ok = (res: any) => { - expect(res.statusCode, JSON.stringify(res.body)).toBe(200); - return res.body; -}; - -describe('[#36350 measurement] a draft that moves inside "Save to this view"', () => { - it('M0 the tokens: the draft receipt token, the draft read token and the active overlayVersion', async () => { - const h = await boot(); - const live = ok(await h.save(view('live'))); - const loaded = ok(await h.layers()).overlayVersion; - const saveDraft = ok(await h.save(view('save to this view'), { mode: 'draft' }, { 'if-none-match': '*' })); - const draftRead = ok(await h.readDraft()); - // eslint-disable-next-line no-console - console.log('M0', JSON.stringify({ - activeReceipt: live.version, overlayVersion: loaded, - draftReceipt: saveDraft.version, draftReadVersion: draftRead.version, - layersAfterDraft: ok(await h.layers()).overlayVersion, - })); - // A publish pinned with the DRAFT's token, under today's meaning of If-Match: - const pinnedToDraft = await h.publish({ 'if-match': saveDraft.version }); - // eslint-disable-next-line no-console - console.log('M0 publish If-Match=', pinnedToDraft.statusCode, JSON.stringify(pinnedToDraft.body)); - }, 60_000); - - it('M1 acceptance shape on main: Save pins the publish with the strongest pin main offers (active If-Match) — an interleaved updateView draft write must be refused', async () => { - const h = await boot(); - ok(await h.save(view('live'))); - const loaded = ok(await h.layers()).overlayVersion; - // "Save to this view": the draft over no draft. - ok(await h.save(view('save to this view'), { mode: 'draft' }, { 'if-none-match': '*' })); - // updateView's draft branch (rename / pin / set default): read the draft, merge, write back unpinned. - const draft = ok(await h.layers()).draft; - ok(await h.save({ ...draft, label: 'renamed, meant as a draft' }, { mode: 'draft' })); - // "Save to this view"'s publish, pinned to the active row it loaded. - const res = await h.publish({ 'if-match': loaded }); - // eslint-disable-next-line no-console - console.log('M1 publish', res.statusCode, JSON.stringify(res.body).slice(0, 300)); - // eslint-disable-next-line no-console - console.log('M1 active after', JSON.stringify((await h.stored('active')).map((r: any) => r.label))); - expect(res.statusCode).toBe(409); - expect(res.body.code).toBe('METADATA_CONFLICT'); - expect((await h.stored('active')).map((r: any) => r.label)).toEqual(['live']); - }, 60_000); - - it('M2 direction B extended: updateView pinned to the draft version it read inside the window — does the pin refuse it?', async () => { - const h = await boot(); - ok(await h.save(view('live'))); - ok(await h.save(view('save to this view'), { mode: 'draft' }, { 'if-none-match': '*' })); - // updateView reads INSIDE the window: the draft it reads is Save's own. - const read = ok(await h.readDraft()); - const draft = ok(await h.layers()).draft; - const write = await h.save({ ...draft, label: 'renamed, meant as a draft' }, { mode: 'draft' }, { 'if-match': read.version }); - const res = await h.publish(); - // eslint-disable-next-line no-console - console.log('M2 pinned updateView write', write.statusCode, '· publish', res.statusCode, - '· active after', JSON.stringify((await h.stored('active')).map((r: any) => r.label))); - }, 60_000); - - it('M3 no draft window at all: an ACTIVE save pinned to the loaded active row, with and without a pending draft', async () => { - const h = await boot(); - ok(await h.save(view('live'))); - const loaded = ok(await h.layers()).overlayVersion; - // Someone's unpublished draft is pending. - ok(await h.save(view('someone else, unreviewed'), { mode: 'draft' }, { 'if-none-match': '*' })); - const res = await h.save(view('save to this view, active'), {}, { 'if-match': loaded }); - // eslint-disable-next-line no-console - console.log('M3 active PUT over pending draft', res.statusCode, JSON.stringify(res.body).slice(0, 300), - '· active', JSON.stringify((await h.stored('active')).map((r: any) => r.label)), - '· draft', JSON.stringify((await h.stored('draft')).map((r: any) => r.label))); - // The other author's later publish, pinned to what THEY loaded. - const theirs = await h.publish({ 'if-match': loaded }); - // eslint-disable-next-line no-console - console.log('M3 their pinned publish afterwards', theirs.statusCode, JSON.stringify(theirs.body).slice(0, 200)); - const stale = await h.save(view('stale active'), {}, { 'if-match': loaded }); - // eslint-disable-next-line no-console - console.log('M3 stale active PUT', stale.statusCode, JSON.stringify(stale.body).slice(0, 200)); - }, 60_000); -}); diff --git a/packages/rest/src/meta-item-publish-version-pin.test.ts b/packages/rest/src/meta-item-publish-version-pin.test.ts index adfad7b924d..448ccfddd7c 100644 --- a/packages/rest/src/meta-item-publish-version-pin.test.ts +++ b/packages/rest/src/meta-item-publish-version-pin.test.ts @@ -124,9 +124,11 @@ async function boot() { /** `PUT /meta/view/case_grid` — active unless `mode: 'draft'`. */ const save = (body: unknown, query: Record = {}, headers: Record = {}) => call('PUT', `${META}/:type/:name`, { path, params: item, query, headers, body }); - /** `POST /meta/view/case_grid/publish`. */ - const publish = (headers: Record = {}) => - call('POST', `${META}/:type/:name/publish`, { path: `${path}/publish`, params: item, headers, body: {} }); + /** `GET /meta/view/case_grid?state=draft` — the strict draft read. */ + const readDraft = () => call('GET', `${META}/:type/:name`, { path, params: item, query: { state: 'draft' } }); + /** `POST /meta/view/case_grid/publish`, with the body given (`{}` when none). */ + const publish = (headers: Record = {}, body: Record = {}) => + call('POST', `${META}/:type/:name/publish`, { path: `${path}/publish`, params: item, headers, body }); /** One Studio Save: the draft over "no draft", then that item's publish, pinned as given. */ const studioSave = async (label: string, publishHeaders: Record = {}) => { ok(await save(view(label), { mode: 'draft' }, { 'if-none-match': '*' })); @@ -139,7 +141,7 @@ async function boot() { return (rows ?? []).map((r: any) => JSON.parse(String(r.metadata)).label as string); }; - return { protocol, layers, read, save, publish, studioSave, stored }; + return { protocol, layers, read, readDraft, save, publish, studioSave, stored }; } const ok = (res: any) => { @@ -282,3 +284,114 @@ describe('[#36601] the publish door\'s precondition headers, as the save door re } }); + +/** + * [#36350, ruling 7168616260] The per-item publish takes a pin on the DRAFT + * it promotes: `draftVersion` in the publish body, beside `message`. "Save to + * this view" writes a draft and then publishes it; a draft write by someone + * else landing in between (the view's rename / pin / set-default, which is + * `ObjectStackAdapter.updateView`'s draft branch) is refused at the publish + * instead of going live under Save's name: an unpublished draft is never + * published on someone else's behalf (ruling 7058616478). `If-Match` keeps its + * shipped meaning, the active row's token, and the two are sent together. + */ +describe('[#36350] the publish door\'s draft pin (`draftVersion`)', () => { + /** "Save to this view" up to its publish: the draft over "no draft", and the active token it loaded. */ + const saveToThisViewDraft = async (h: Awaited>, label: string) => { + const loaded = ok(await h.layers()).overlayVersion as string; + const receipt = ok(await h.save(view(label), { mode: 'draft' }, { 'if-none-match': '*' })); + return { loaded, draftVersion: receipt.version as string }; + }; + + it('acceptance: an updateView draft write inside the window is refused at Save\'s publish — 409, nothing unreviewed is published', async () => { + const h = await boot(); + ok(await h.save(view('live'))); + const saved = await saveToThisViewDraft(h, 'save to this view'); + expect(saved.draftVersion).toMatch(KEYED); + + // updateView's draft branch, inside the window: it reads the pending + // draft (Save's own), merges, and writes it back pinned to what it read. + const read = ok(await h.readDraft()); + expect(read.version).toBe(saved.draftVersion); + const renamed = ok(await h.save( + { ...view('save to this view'), label: 'renamed, meant as a draft' }, + { mode: 'draft' }, + { 'if-match': read.version }, + )); + + // Save's publish, pinned to both rows it knows. + const refused = refusedConflict(await h.publish({ 'if-match': saved.loaded }, { draftVersion: saved.draftVersion })); + // The refusal names the DRAFT's current token, which the draft read serves. + expect(refused.currentVersion).toBe(renamed.version); + expect(ok(await h.readDraft()).version).toBe(refused.currentVersion); + expect(MetadataConflictErrorSchema.parse(refused).currentVersion).toBe(renamed.version); + // Nothing promoted: the live row is untouched and the rename stays a pending draft. + expect(await h.stored('active')).toEqual(['live']); + expect(await h.stored('draft')).toEqual(['renamed, meant as a draft']); + }, 60_000); + + it('acceptance: an UNPINNED updateView draft write inside the window is refused the same way', async () => { + const h = await boot(); + ok(await h.save(view('live'))); + const saved = await saveToThisViewDraft(h, 'save to this view'); + ok(await h.save({ ...view('save to this view'), label: 'renamed, meant as a draft' }, { mode: 'draft' })); + + refusedConflict(await h.publish({ 'if-match': saved.loaded }, { draftVersion: saved.draftVersion })); + expect(await h.stored('active')).toEqual(['live']); + expect(await h.stored('draft')).toEqual(['renamed, meant as a draft']); + }, 60_000); + + it('control: with no write in the window the pinned publish promotes Save\'s draft', async () => { + const h = await boot(); + ok(await h.save(view('live'))); + const saved = await saveToThisViewDraft(h, 'save to this view'); + const published = ok(await h.publish({ 'if-match': saved.loaded }, { draftVersion: saved.draftVersion })); + expect(await h.stored('active')).toEqual(['save to this view']); + expect(await h.stored('draft')).toEqual([]); + expect(ok(await h.layers()).overlayVersion).toBe(published.version); + }, 60_000); + + it('absent `draftVersion` is unpinned, as before: the publish promotes whichever draft is pending', async () => { + const h = await boot(); + ok(await h.save(view('live'))); + const saved = await saveToThisViewDraft(h, 'save to this view'); + ok(await h.save({ ...view('save to this view'), label: 'renamed, meant as a draft' }, { mode: 'draft' })); + ok(await h.publish({ 'if-match': saved.loaded })); + expect(await h.stored('active')).toEqual(['renamed, meant as a draft']); + }, 60_000); + + it('a pinned draft no longer pending is refused 409 with `currentVersion: null`, promoting nothing', async () => { + const h = await boot(); + ok(await h.save(view('live'))); + const saved = await saveToThisViewDraft(h, 'save to this view'); + // Someone else publishes the draft first; it is no longer pending. + const theirs = ok(await h.publish()); + const refused = refusedConflict(await h.publish({}, { draftVersion: saved.draftVersion })); + expect(refused.currentVersion).toBeNull(); + expect(ok(await h.layers()).overlayVersion).toBe(theirs.version); + }, 60_000); + + it('the draft pin and the active pin judge different rows: a draft token sent as `If-Match` still answers the active row\'s refusal', async () => { + const h = await boot(); + ok(await h.save(view('live'))); + const saved = await saveToThisViewDraft(h, 'save to this view'); + // If-Match keeps its shipped meaning (ruling 7168616260, item 2). + const refused = refusedConflict(await h.publish({ 'if-match': saved.draftVersion }, { draftVersion: saved.draftVersion })); + expect(refused.currentVersion).toBe(saved.loaded); + expect(await h.stored('active')).toEqual(['live']); + expect(await h.stored('draft')).toEqual(['save to this view']); + }, 60_000); + + for (const [label, draftVersion] of Object.entries({ 'a number': 42, 'null': null, 'an object': { v: 'x' } })) { + it(`a \`draftVersion\` that is ${label} is refused 400 VALIDATION_ERROR, never read as unpinned`, async () => { + const h = await boot(); + ok(await h.save(view('live'))); + ok(await h.save(view('pending'), { mode: 'draft' })); + const res = await h.publish({}, { draftVersion }); + expect(res.statusCode, JSON.stringify(res.body)).toBe(400); + expect(res.body.error.code).toBe('VALIDATION_ERROR'); + expect(await h.stored('active')).toEqual(['live']); + expect(await h.stored('draft')).toEqual(['pending']); + }, 60_000); + } +}); diff --git a/packages/spec/src/api/protocol.test.ts b/packages/spec/src/api/protocol.test.ts index 34d7d547cc9..0bec6d30d6d 100644 --- a/packages/spec/src/api/protocol.test.ts +++ b/packages/spec/src/api/protocol.test.ts @@ -2281,6 +2281,24 @@ describe('PublishMetaItemRequestSchema mirrors the implementation parameter type } }); + it('draftVersion is an optional string, PRESERVED through parse, absent stays absent — the draft pin', () => { + // Ruling 7168616260 (A1): the publish door's own pin on the DRAFT it + // promotes, beside `parentVersion` (the active row's). Absent is unpinned, + // so the parse must keep absent apart from any value. + const pinned = PublishMetaItemRequestSchema.safeParse({ ...base, draftVersion: 'hmac-sha256:abc', parentVersion: 'hmac-sha256:def' }); + expect(pinned.success).toBe(true); + if (pinned.success) { + expect(pinned.data).toEqual({ ...base, draftVersion: 'hmac-sha256:abc', parentVersion: 'hmac-sha256:def' }); + } + const absent = PublishMetaItemRequestSchema.safeParse(base); + expect(absent.success).toBe(true); + if (absent.success) { + expect('draftVersion' in (absent.data as object)).toBe(false); + } + expect(PublishMetaItemRequestSchema.safeParse({ ...base, draftVersion: null }).success).toBe(false); + expect(PublishMetaItemRequestSchema.safeParse({ ...base, draftVersion: 42 }).success).toBe(false); + }); + it('does not declare environmentId — transport-level by ruling, stripped and shape-absent', () => { // Same regression guard as the meta-read block above: if someone declares // the member, the parse stops stripping it and this test names the ruling diff --git a/packages/spec/src/api/protocol.zod.ts b/packages/spec/src/api/protocol.zod.ts index cd41aed5a28..276221171d8 100644 --- a/packages/spec/src/api/protocol.zod.ts +++ b/packages/spec/src/api/protocol.zod.ts @@ -1636,7 +1636,23 @@ export const PublishMetaItemRequestSchema = lazySchema(() => z.object({ + '`If-None-Match: *`, which takes `*` alone and never beside `If-Match`), ' + 'refused 409 when one exists; an ABSENT key is unpinned and promotes over ' + 'whatever is live, as before. It pins the active row only — which draft is ' - + 'promoted is the address\'s, as without it.', + + 'promoted is the address\'s, as without it; the draft\'s own pin is ' + + '`draftVersion`.', + ), + draftVersion: z.string().optional().describe( + 'ADR-0008 optimistic-concurrency pin on the DRAFT this publish promotes: ' + + 'the version token of the pending draft row the caller wrote or loaded ' + + 'and means to publish (on the REST door, the `draftVersion` member of the ' + + 'publish body, beside `message`; a draft save\'s receipt `version` and the ' + + 'draft read\'s `version` serve it). A token that is not the current draft ' + + 'row\'s at the address the promotion reads is refused 409 ' + + '`METADATA_CONFLICT`, whose `currentVersion` names the draft\'s current ' + + 'token (`null` when no draft is pending), and nothing is promoted: a draft ' + + 'another writer changed after the caller wrote or read it is never ' + + 'published on that writer\'s behalf. ABSENT is unpinned and promotes ' + + 'whichever draft is pending, as before. It pins the draft only — the active ' + + 'row the promotion replaces is `parentVersion`\'s (`If-Match`), and the two ' + + 'may be sent together.', ), userTextLocales: userTextLocalesMember(), })); From 4ed08ef2ca1ab760da7f82cdba628717707d6964 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 23:03:32 +0000 Subject: [PATCH 3/9] wip(ui): pin Save to this view's publish and the draft bar's publish to the draft version Claude-Session: https://claude.ai/code/session_012MmDsSpwtcn5gbWrBDA3Jm Co-authored-by: Claude --- packages/spec/authorable-surface/api.json | 1 + .../src/views/runtime-metadata-persistence.ts | 44 +++++++++++++++++-- .../data-objectstack/src/metadata-client.ts | 16 ++++++- 3 files changed, 55 insertions(+), 6 deletions(-) diff --git a/packages/spec/authorable-surface/api.json b/packages/spec/authorable-surface/api.json index d8822b72614..50addb40d4f 100644 --- a/packages/spec/authorable-surface/api.json +++ b/packages/spec/authorable-surface/api.json @@ -1520,6 +1520,7 @@ "api/PublicFormSubmitResponse:fields", "api/PublicFormSubmitResponse:id", "api/PublishMetaItemRequest:actor", + "api/PublishMetaItemRequest:draftVersion", "api/PublishMetaItemRequest:member", "api/PublishMetaItemRequest:message", "api/PublishMetaItemRequest:name", diff --git a/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts b/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts index 55f90e5435f..ef95f6ec314 100644 --- a/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts +++ b/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts @@ -535,12 +535,26 @@ export async function publishRuntimeMetadata( type: RuntimeArtifactType, name: string, ctx: RuntimePersistCtx, + draftVersion?: string, ): Promise { - await ctx.metadataClient.publish(type, name); + // objectstack#36350 — pinned to the draft the bar showed when its caller + // has that draft's version: a draft another writer changed since is refused + // `409 METADATA_CONFLICT` and nothing is published. Without one, whichever + // draft is pending is published, as before. + await ctx.metadataClient.publish(type, name, draftVersion ? { draftVersion } : {}); invalidateViewCaches(type, name, ctx); announceDraftLedgerWrite(); } +/** + * The version token a draft save's receipt carries (`version`), or + * `undefined` when it carries none: the publish is then unpinned, as before. + */ +function receiptVersion(receipt: unknown): string | undefined { + const version = (receipt as { version?: unknown } | null | undefined)?.version; + return typeof version === 'string' && version.length > 0 ? version : undefined; +} + /** What {@link saveAndPublishRuntimeMetadata} did. */ export type SaveAndPublishOutcome = 'published' | 'pending-draft'; @@ -555,7 +569,13 @@ export type SaveAndPublishOutcome = 'published' | 'pending-draft'; * door does not say who did — and nothing is written: resolves * `'pending-draft'`. That draft is never published on its saver's behalf. * - * A publish the server refuses leaves no draft of this call behind: the draft + * objectstack#36350 — the publish is pinned to the draft this call wrote (its + * receipt's version, `draftVersion`). When another writer's draft write lands + * between the two, the server refuses the publish `409 METADATA_CONFLICT` and + * publishes nothing; the moved draft is left pending, never discarded, and + * this resolves `'pending-draft'`. + * + * Any other publish refusal leaves no draft of this call behind: the draft * it wrote is discarded (it was the only one, by the pin) and the refusal is * rethrown. Any other refusal is rethrown as it came. * @@ -575,13 +595,15 @@ export async function saveAndPublishRuntimeMetadata( ): Promise { const app = type === 'view' ? ctx.app : null; const packageId = app?.packageId ? await resolveRuntimeCreatePackage(app.packageId, type) : null; + let draftVersion: string | undefined; try { - await ctx.metadataClient.save( + const receipt = await ctx.metadataClient.save( type, name, body, packageId ? { mode: 'draft', ifNoneMatch: '*', packageId } : { mode: 'draft', ifNoneMatch: '*' }, ); + draftVersion = receiptVersion(receipt); } catch (err) { if (isDraftVersionConflict(err)) { return 'pending-draft'; @@ -589,8 +611,22 @@ export async function saveAndPublishRuntimeMetadata( throw err; } try { - await ctx.metadataClient.publish(type, name); + // objectstack#36350 — the publish is pinned to the draft this call wrote + // (`draftVersion`, its receipt's version). Another writer's draft write + // landing in between (a rename, pin or set-default on the same view) moves + // the draft, and the server refuses the publish `409 METADATA_CONFLICT` + // rather than publishing that writer's unreviewed change on their behalf. + await ctx.metadataClient.publish(type, name, draftVersion ? { draftVersion } : {}); } catch (err) { + if (isDraftVersionConflict(err)) { + // The draft moved: it now holds the other writer's change on top of + // this call's body, so it is no longer this call's own — ⛔ never + // discarded here. It stays pending for the draft bar's review, exactly + // as a draft found pending before the write does. + invalidateViewCaches(type, name, ctx); + announceDraftLedgerWrite(); + return 'pending-draft'; + } try { await ctx.metadataClient.reset(type, name, { state: 'draft' }); } catch (discardErr) { diff --git a/ui/packages/data-objectstack/src/metadata-client.ts b/ui/packages/data-objectstack/src/metadata-client.ts index 365df7fa1aa..98c6814d6a7 100644 --- a/ui/packages/data-objectstack/src/metadata-client.ts +++ b/ui/packages/data-objectstack/src/metadata-client.ts @@ -2040,11 +2040,20 @@ export class MetadataClient { * A stale pin is refused `409 METADATA_CONFLICT` with the current version as * `currentVersion`, and nothing is promoted. Neither, the publish is * unpinned, as before. ⛔ Never both: refused before any request. + * + * objectstack#36350 — `draftVersion` pins the DRAFT this publish promotes: + * the version a draft save's receipt returned (or the draft read's + * `version`), sent as the `draftVersion` body member beside `message`. A + * draft another writer changed since is refused `409 METADATA_CONFLICT` + * with the draft's current version as `currentVersion` (`null` when no + * draft is pending any more), and nothing is promoted. It pins the draft + * only and is sent beside `ifMatch`, which keeps pinning the active row. + * Omitted, whichever draft is pending is promoted, as before. */ async publish( type: string, name: string, - options: { message?: string; packageId?: string; member?: string; ifMatch?: string; ifNoneMatch?: '*' } = {}, + options: { message?: string; packageId?: string; member?: string; ifMatch?: string; ifNoneMatch?: '*'; draftVersion?: string } = {}, ): Promise { if (options.ifMatch && options.ifNoneMatch) { throw new Error( @@ -2079,7 +2088,10 @@ export class MetadataClient { const res = await this.sendWrite(url, { method: 'POST', headers, - body: JSON.stringify(options.message ? { message: options.message } : {}), + body: JSON.stringify({ + ...(options.message ? { message: options.message } : {}), + ...(options.draftVersion !== undefined ? { draftVersion: options.draftVersion } : {}), + }), }); if (!res.ok) throw await parseError(res); const body = await res.json(); From eb9fb12dddee8eeb8f9f08a0d0ca184714896768 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 23:06:42 +0000 Subject: [PATCH 4/9] feat(ui): updateView's draft write and the draft bar's Publish pin the draft they read Claude-Session: https://claude.ai/code/session_012MmDsSpwtcn5gbWrBDA3Jm Co-authored-by: Claude --- .../RuntimeDraftBar.refusal-11583.test.tsx | 2 +- ...untimeDraftBar.resetPackage-12335.test.tsx | 4 +- .../src/views/RuntimeDraftBar.test.tsx | 78 ++++++++++++- .../app-shell/src/views/RuntimeDraftBar.tsx | 22 +++- .../runtime-metadata-persistence.test.ts | 44 ++++++++ .../src/views/runtime-metadata-persistence.ts | 26 ++++- .../viewCacheInvalidation.guard.test.tsx | 2 + ui/packages/data-objectstack/src/index.ts | 33 +++++- ...adata-client.publishPackageBinding.test.ts | 44 ++++++++ .../src/updateView.draft.test.ts | 104 +++++++++++++++++- 10 files changed, 339 insertions(+), 20 deletions(-) diff --git a/ui/packages/app-shell/src/views/RuntimeDraftBar.refusal-11583.test.tsx b/ui/packages/app-shell/src/views/RuntimeDraftBar.refusal-11583.test.tsx index 13711605ffb..5c3fa2d4dc5 100644 --- a/ui/packages/app-shell/src/views/RuntimeDraftBar.refusal-11583.test.tsx +++ b/ui/packages/app-shell/src/views/RuntimeDraftBar.refusal-11583.test.tsx @@ -38,7 +38,7 @@ const refusal = (message: string) => Object.assign(new Error(message), { status: function makeMetadataClient(writes: Record = {}) { return { - get: vi.fn().mockResolvedValue({ type: 'view', name: 'crm_deal.pipeline', item: { label: 'Pipeline' } }), + getDraft: vi.fn().mockResolvedValue({ type: 'view', name: 'crm_deal.pipeline', item: { label: 'Pipeline' } }), publish: vi.fn().mockResolvedValue(undefined), reset: vi.fn().mockResolvedValue(undefined), ...writes, diff --git a/ui/packages/app-shell/src/views/RuntimeDraftBar.resetPackage-12335.test.tsx b/ui/packages/app-shell/src/views/RuntimeDraftBar.resetPackage-12335.test.tsx index 78e785edb5f..f39d25abf61 100644 --- a/ui/packages/app-shell/src/views/RuntimeDraftBar.resetPackage-12335.test.tsx +++ b/ui/packages/app-shell/src/views/RuntimeDraftBar.resetPackage-12335.test.tsx @@ -52,7 +52,9 @@ function realClient(): MetadataClient { ? json(200, { success: true, reset: true }) : json(409, { error: AMBIGUOUS, code: 'RESOURCE_CONFLICT' }); } - // The pending draft that makes the bar render. + // The pending-drafts ledger `getDraft` asks first lists it (objectui#11799)… + if (url.pathname.endsWith('/_drafts')) return json(200, { drafts: [{ type: 'view', name: 'crm_deal.pipeline' }] }); + // …and the pending draft that makes the bar render. return json(200, { type: 'view', name: 'crm_deal.pipeline', item: { label: 'Pipeline' } }); }) as unknown as typeof fetch, }); diff --git a/ui/packages/app-shell/src/views/RuntimeDraftBar.test.tsx b/ui/packages/app-shell/src/views/RuntimeDraftBar.test.tsx index 6adbe4bdd72..30f8a939433 100644 --- a/ui/packages/app-shell/src/views/RuntimeDraftBar.test.tsx +++ b/ui/packages/app-shell/src/views/RuntimeDraftBar.test.tsx @@ -14,7 +14,7 @@ import { RuntimeDraftBar } from './RuntimeDraftBar'; function makeMetadataClient(draftItem: unknown = null) { return { - get: vi.fn().mockResolvedValue(draftItem), + getDraft: vi.fn().mockResolvedValue(draftItem), publish: vi.fn().mockResolvedValue(undefined), reset: vi.fn().mockResolvedValue(undefined), }; @@ -45,7 +45,7 @@ describe('RuntimeDraftBar (ADR-0034)', () => { await waitFor(() => expect(screen.getByTestId('runtime-draft-bar')).toBeTruthy()); expect(screen.getByTestId('runtime-draft-publish')).toBeTruthy(); expect(screen.getByTestId('runtime-draft-discard')).toBeTruthy(); - expect(metadataClient.get).toHaveBeenCalledWith('view', 'my_view', { state: 'draft' }); + expect(metadataClient.getDraft).toHaveBeenCalledWith('view', 'my_view'); expect(onResume).toHaveBeenCalledWith({ columns: ['name'] }); }); @@ -76,7 +76,7 @@ describe('RuntimeDraftBar (ADR-0034)', () => { , ); - await waitFor(() => expect(metadataClient.get).toHaveBeenCalled()); + await waitFor(() => expect(metadataClient.getDraft).toHaveBeenCalled()); expect(container.querySelector('[data-testid="runtime-draft-bar"]')).toBeNull(); }); @@ -120,7 +120,7 @@ describe('RuntimeDraftBar (ADR-0034)', () => { , ); - await waitFor(() => expect(metadataClient.get).toHaveBeenCalled()); + await waitFor(() => expect(metadataClient.getDraft).toHaveBeenCalled()); expect(container.querySelector('[data-testid="runtime-draft-bar"]')).toBeNull(); // Host saved a draft → bump the signal → indicator appears at once. @@ -155,6 +155,74 @@ describe('RuntimeDraftBar (ADR-0034)', () => { ); expect(container.querySelector('[data-testid="runtime-draft-bar"]')).toBeNull(); - expect(metadataClient.get).not.toHaveBeenCalled(); + expect(metadataClient.getDraft).not.toHaveBeenCalled(); + }); +}); + +/** + * objectstack#36350 (ruling 7168616260) — the bar's Publish is pinned to the + * draft the bar showed: the version its draft read's envelope carried, sent as + * `draftVersion`. A draft another writer changed since is refused by the door + * (`409 METADATA_CONFLICT`) instead of being published on that writer's behalf. + */ +describe('RuntimeDraftBar — Publish is pinned to the draft it showed (objectstack#36350)', () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('sends the shown draft\'s version as `draftVersion`', async () => { + const metadataClient = makeMetadataClient({ + type: 'report', + name: 'my_report', + item: { label: 'Pipeline' }, + version: 'hmac-sha256:draft-v1', + }); + + render(); + fireEvent.click(await screen.findByTestId('runtime-draft-publish')); + + await waitFor(() => + expect(metadataClient.publish).toHaveBeenCalledWith('report', 'my_report', { draftVersion: 'hmac-sha256:draft-v1' }), + ); + }); + + it('a moved draft\'s refusal is said and the indicator stays: nothing was published', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}); + const metadataClient = makeMetadataClient({ + type: 'report', + name: 'my_report', + item: { label: 'Pipeline' }, + version: 'hmac-sha256:draft-v1', + }); + metadataClient.publish.mockRejectedValue( + Object.assign(new Error('report/my_report draft changed since the version this publish pinned (draftVersion)'), { + status: 409, + code: 'METADATA_CONFLICT', + }), + ); + + render(); + fireEvent.click(await screen.findByTestId('runtime-draft-publish')); + + await waitFor(() => expect(metadataClient.publish).toHaveBeenCalled()); + expect(screen.getByTestId('runtime-draft-bar')).toBeTruthy(); + }); + + it('after the host\'s own save (savedSignal) the bar has not read the new draft, and Publish goes unpinned', async () => { + const metadataClient = makeMetadataClient({ + type: 'view', + name: 'my_view', + item: { columns: ['name'] }, + version: 'hmac-sha256:draft-v1', + }); + + const { rerender } = render( + , + ); + await screen.findByTestId('runtime-draft-publish'); + rerender(); + fireEvent.click(await screen.findByTestId('runtime-draft-publish')); + + await waitFor(() => expect(metadataClient.publish).toHaveBeenCalledWith('view', 'my_view')); }); }); diff --git a/ui/packages/app-shell/src/views/RuntimeDraftBar.tsx b/ui/packages/app-shell/src/views/RuntimeDraftBar.tsx index ea21a053e5c..b6564cdf21a 100644 --- a/ui/packages/app-shell/src/views/RuntimeDraftBar.tsx +++ b/ui/packages/app-shell/src/views/RuntimeDraftBar.tsx @@ -18,7 +18,7 @@ import { Loader2, Send, Undo2 } from 'lucide-react'; import { publishRuntimeMetadata, discardRuntimeDraft, - readRuntimeDraft, + readRuntimeDraftForPublish, type RuntimeArtifactType, } from './runtime-metadata-persistence.js'; import { useMetadataLocale, t, tFormat } from './metadata-admin/i18n.js'; @@ -98,6 +98,8 @@ export function RuntimeDraftBar({ // Track the `name` we've already resumed so reopening the same item doesn't // clobber in-flight edits with the stored draft on every effect run. const resumedRef = useRef(null); + /** objectstack#36350 — the version of the draft this bar last read and shows. */ + const shownDraftVersionRef = useRef(undefined); const refresh = useCallback(async () => { if (!name || !metadataClient) { @@ -106,11 +108,15 @@ export function RuntimeDraftBar({ } let body: Record | null; try { - body = await readRuntimeDraft>(type, name, { + const shown = await readRuntimeDraftForPublish>(type, name, { metadataClient, }); + body = shown.body; + // objectstack#36350 — the draft this bar shows; its Publish is pinned to it. + shownDraftVersionRef.current = shown.draftVersion; } catch { // A failed draft read must not break the editor — treat as "no draft". + shownDraftVersionRef.current = undefined; setHasDraft(false); return; } @@ -139,14 +145,22 @@ export function RuntimeDraftBar({ useEffect(() => { if (savedSignal === lastSavedSignal.current) return; lastSavedSignal.current = savedSignal; - if (savedSignal) setHasDraft(true); + if (savedSignal) { + // The host's own save moved the draft past the one this bar read, and + // the bar has not read the new one: its Publish goes unpinned, as before. + shownDraftVersionRef.current = undefined; + setHasDraft(true); + } }, [savedSignal]); const handlePublish = useCallback(async () => { if (!name) return; setBusy(true); try { - await publishRuntimeMetadata(type, name, { metadataClient, dataSource, objectName }); + // objectstack#36350 — pinned to the draft this bar showed: a draft + // another writer changed since is refused `409 METADATA_CONFLICT`, said + // by the toast below, and nothing is published. + await publishRuntimeMetadata(type, name, { metadataClient, dataSource, objectName }, shownDraftVersionRef.current); setHasDraft(false); onAfterChange?.(); } catch (err) { diff --git a/ui/packages/app-shell/src/views/runtime-metadata-persistence.test.ts b/ui/packages/app-shell/src/views/runtime-metadata-persistence.test.ts index 633ea60a0a2..789e67aa1d6 100644 --- a/ui/packages/app-shell/src/views/runtime-metadata-persistence.test.ts +++ b/ui/packages/app-shell/src/views/runtime-metadata-persistence.test.ts @@ -382,6 +382,50 @@ describe('saveAndPublishRuntimeMetadata — a confirmed save everyone sees at on }); }); +/** + * objectstack#36350 (ruling 7168616260) — "Save to this view" pins its publish + * to the draft its own draft write returned (`draftVersion`, the receipt's + * version), and the draft bar's Publish to the draft it showed. Another + * writer's draft write landing in between moves the draft; the door refuses + * the publish `409 METADATA_CONFLICT`, nothing is published, and the moved + * draft — no longer this call's own — is never discarded. + */ +describe('the publish is pinned to the draft it means (objectstack#36350)', () => { + const RECEIPT = { success: true, version: 'hmac-sha256:draft-v1' }; + const moved = () => Object.assign(new Error('draft changed'), { status: 409, code: 'METADATA_CONFLICT' }); + + it('Save to this view sends its own draft receipt\'s version as `draftVersion`', async () => { + const metadataClient = makeMetadataClient(); + metadataClient.save.mockResolvedValue(RECEIPT); + await expect(saveAndPublishRuntimeMetadata('view', 'task.all', {}, { metadataClient })).resolves.toBe('published'); + expect(metadataClient.publish).toHaveBeenCalledWith('view', 'task.all', { draftVersion: 'hmac-sha256:draft-v1' }); + }); + + it('a draft moved inside the window is refused: nothing published, the moved draft left pending, `pending-draft`', async () => { + const metadataClient = makeMetadataClient(); + metadataClient.save.mockResolvedValue(RECEIPT); + metadataClient.publish.mockRejectedValue(moved()); + await expect(saveAndPublishRuntimeMetadata('view', 'task.all', {}, { metadataClient })).resolves.toBe('pending-draft'); + // The draft now holds the other writer's change: ⛔ never discarded on their behalf. + expect(metadataClient.reset).not.toHaveBeenCalled(); + }); + + it('CONTROL: a receipt that carries no version publishes unpinned, as before', async () => { + const metadataClient = makeMetadataClient(); + metadataClient.save.mockResolvedValue({ success: true }); + await saveAndPublishRuntimeMetadata('view', 'task.all', {}, { metadataClient }); + expect(metadataClient.publish).toHaveBeenCalledWith('view', 'task.all'); + }); + + it('the draft bar\'s publish passes the version it showed; without one it is unpinned', async () => { + const metadataClient = makeMetadataClient(); + await publishRuntimeMetadata('report', 'pipeline', { metadataClient }, 'hmac-sha256:shown'); + expect(metadataClient.publish).toHaveBeenLastCalledWith('report', 'pipeline', { draftVersion: 'hmac-sha256:shown' }); + await publishRuntimeMetadata('report', 'pipeline', { metadataClient }); + expect(metadataClient.publish).toHaveBeenLastCalledWith('report', 'pipeline'); + }); +}); + /** * objectstack#36372 — a dashboard edited on its own page saves where Studio's * Customize would: the owning package when writable, else the app's diff --git a/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts b/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts index ef95f6ec314..b5c4593cab5 100644 --- a/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts +++ b/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts @@ -507,6 +507,26 @@ export async function readRuntimeDraft>( return unwrapDraftBody(resp) as T | null; } +/** + * objectstack#36350 — the pending draft as the runtime draft bar shows it: its + * bare body (as {@link readRuntimeDraft} answers it) and the `version` the + * strict draft read's envelope carries, which pins the bar's Publish + * ({@link publishRuntimeMetadata}) to this draft. Read through + * `MetadataClient.getDraft`, whose answer keeps the envelope; `draftVersion` + * is absent when no draft is pending or the envelope carries none (a server + * from before the read served one), and the Publish then goes unpinned. + */ +export async function readRuntimeDraftForPublish>( + type: RuntimeArtifactType, + name: string, + ctx: RuntimePersistCtx, +): Promise<{ body: T | null; draftVersion?: string }> { + const answer = await ctx.metadataClient.getDraft(type, name); + const body = unwrapDraftBody(answer) as T | null; + const draftVersion = body ? receiptVersion(answer) : undefined; + return draftVersion ? { body, draftVersion } : { body }; +} + /** * Discard the pending draft of a runtime artifact (Studio's "Discard draft"). * The published overlay is untouched. @@ -541,7 +561,8 @@ export async function publishRuntimeMetadata( // has that draft's version: a draft another writer changed since is refused // `409 METADATA_CONFLICT` and nothing is published. Without one, whichever // draft is pending is published, as before. - await ctx.metadataClient.publish(type, name, draftVersion ? { draftVersion } : {}); + if (draftVersion) await ctx.metadataClient.publish(type, name, { draftVersion }); + else await ctx.metadataClient.publish(type, name); invalidateViewCaches(type, name, ctx); announceDraftLedgerWrite(); } @@ -616,7 +637,8 @@ export async function saveAndPublishRuntimeMetadata( // landing in between (a rename, pin or set-default on the same view) moves // the draft, and the server refuses the publish `409 METADATA_CONFLICT` // rather than publishing that writer's unreviewed change on their behalf. - await ctx.metadataClient.publish(type, name, draftVersion ? { draftVersion } : {}); + if (draftVersion) await ctx.metadataClient.publish(type, name, { draftVersion }); + else await ctx.metadataClient.publish(type, name); } catch (err) { if (isDraftVersionConflict(err)) { // The draft moved: it now holds the other writer's change on top of diff --git a/ui/packages/app-shell/src/views/viewCacheInvalidation.guard.test.tsx b/ui/packages/app-shell/src/views/viewCacheInvalidation.guard.test.tsx index 41cfe219316..5ceec5184fd 100644 --- a/ui/packages/app-shell/src/views/viewCacheInvalidation.guard.test.tsx +++ b/ui/packages/app-shell/src/views/viewCacheInvalidation.guard.test.tsx @@ -129,6 +129,8 @@ function makeAdapter() { function makeMetadataClient(draftItem: unknown = null) { return { get: vi.fn().mockResolvedValue(draftItem), + // The draft bar's read (objectstack#36350: its envelope carries the version Publish pins). + getDraft: vi.fn().mockResolvedValue(draftItem), save: vi.fn().mockResolvedValue(undefined), publish: vi.fn().mockResolvedValue(undefined), reset: vi.fn().mockResolvedValue(undefined), diff --git a/ui/packages/data-objectstack/src/index.ts b/ui/packages/data-objectstack/src/index.ts index c66dcba4ba1..7208d0acd4d 100644 --- a/ui/packages/data-objectstack/src/index.ts +++ b/ui/packages/data-objectstack/src/index.ts @@ -3436,6 +3436,19 @@ export function narrowPersonalizationOverlay(row: T): T { * (ADR-0034 seam); the two live apart because the seam sits above this * adapter, not beside it. */ +/** + * objectstack#36350 — the pin `updateView`'s draft write is sent with, from + * its strict draft read (`MetadataClient.getDraft`'s answer): `null` (no draft + * pending) asserts "no draft" (`If-None-Match: *`); an envelope's `version` + * token pins `If-Match`; an envelope with no token pins nothing, and the write + * goes unpinned as it did before the read served one. + */ +function draftWritePin(answer: unknown): { ifMatch: string } | { ifNoneMatch: '*' } | Record { + if (answer === null || answer === undefined) return { ifNoneMatch: '*' }; + const version = (answer as { version?: unknown }).version; + return typeof version === 'string' && version.length > 0 ? { ifMatch: version } : {}; +} + function unwrapViewDraft(resp: unknown): Record | null { if (!resp || typeof resp !== 'object') return null; const env = resp as Record; @@ -6909,10 +6922,17 @@ export class ObjectStackAdapter implements DataSource { // `MetadataClient.get` answers `null` on 404 (no draft pending) and throws // on anything else, so a transport failure here is NOT read as "published". const metaClient = this.metadataClient(); - const [servedDraft, layers] = await Promise.all([ - metaClient.get('view', viewName, { state: 'draft' }).then(unwrapViewDraft), - metaClient.layered('view', viewName), - ]); + // objectstack#36350 — the draft write below is pinned to the draft this + // read saw: the strict draft read's envelope (`getDraft`) carries its + // `version`. Read BEFORE the layers the body is merged from, so a draft + // write landing between the two leaves the pin older than the body and the + // write is refused, never the other way round (a pin newer than the body + // would let a merge onto the older body through). No draft pending at this + // read pins "no draft" (`If-None-Match: *`); an envelope that carries no + // version (a server from before the read served one) pins nothing. + const draftAnswer = await metaClient.getDraft('view', viewName); + const layers = await metaClient.layered('view', viewName); + const servedDraft = unwrapViewDraft(draftAnswer); const authored = authoredBuffer('view', layers, servedDraft); if (authored.kind === 'unserved') { throw new Error( @@ -6928,7 +6948,10 @@ export class ObjectStackAdapter implements DataSource { throw new Error(`updateView: the pending draft of view "${viewName}" is empty. Nothing was written.`); } const mergedDraft = mergeViewPatch(stored, partial, viewName, objectName); - await metaClient.save('view', viewName, mergedDraft, { mode: 'draft' }); + // A draft that moved since the read (another author's edit, or a + // "Save to this view" in flight) is refused `409 METADATA_CONFLICT` and + // this throws: the edit is not merged over a body it never read. + await metaClient.save('view', viewName, mergedDraft, { mode: 'draft', ...draftWritePin(draftAnswer) }); this.invalidateViewKeys(objectName, viewName); return mergedDraft; } diff --git a/ui/packages/data-objectstack/src/metadata-client.publishPackageBinding.test.ts b/ui/packages/data-objectstack/src/metadata-client.publishPackageBinding.test.ts index ea35fbf7974..fe0b9d59a00 100644 --- a/ui/packages/data-objectstack/src/metadata-client.publishPackageBinding.test.ts +++ b/ui/packages/data-objectstack/src/metadata-client.publishPackageBinding.test.ts @@ -130,3 +130,47 @@ describe('MetadataClient.publish — package binding on the promotion (#5420)', expect(JSON.parse(String(seen[0]?.body))).toEqual({ message: 'ship it' }); }); }); + +/** + * objectstack#36350 (ruling 7168616260) — the promotion's pin on the DRAFT it + * promotes travels in the publish body as `draftVersion`, beside `message` + * (`PublishMetaItemRequestSchema.draftVersion`); `If-Match` keeps pinning the + * active row. Omitted, the body carries no such key and the publish is + * unpinned, as before. + */ +describe('MetadataClient.publish — the draft pin (`draftVersion`, objectstack#36350)', () => { + function recordBodies() { + const sent: { body: unknown; headers: Record }[] = []; + const client = new MetadataClient({ + baseUrl: 'http://localhost:3000', + fetch: vi.fn(async (_url: string, init?: RequestInit) => { + sent.push({ + body: JSON.parse(String(init?.body ?? '{}')), + headers: { ...((init?.headers ?? {}) as Record) }, + }); + return new Response(JSON.stringify({ success: true, version: 'hmac-sha256:next' }), { + status: 200, + headers: { 'content-type': 'application/json' }, + }); + }) as unknown as typeof fetch, + }); + return { sent, client }; + } + + it('sends `draftVersion` in the body beside `message`, and `ifMatch` as If-Match', async () => { + const { sent, client } = recordBodies(); + await client.publish('view', 'task.all', { + message: 'ship it', + draftVersion: 'hmac-sha256:draft-v1', + ifMatch: 'hmac-sha256:active-v1', + }); + expect(sent[0]?.body).toEqual({ message: 'ship it', draftVersion: 'hmac-sha256:draft-v1' }); + expect(sent[0]?.headers['If-Match']).toBe('hmac-sha256:active-v1'); + }); + + it('omitted, the body carries no `draftVersion` key', async () => { + const { sent, client } = recordBodies(); + await client.publish('view', 'task.all'); + expect(sent[0]?.body).toEqual({}); + }); +}); diff --git a/ui/packages/data-objectstack/src/updateView.draft.test.ts b/ui/packages/data-objectstack/src/updateView.draft.test.ts index de60347741a..34a265ad844 100644 --- a/ui/packages/data-objectstack/src/updateView.draft.test.ts +++ b/ui/packages/data-objectstack/src/updateView.draft.test.ts @@ -46,6 +46,8 @@ interface Harness { saveItem: ReturnType; /** Draft-addressed writes: `[url, parsedBody]` per `PUT ...?mode=draft`. */ draftPuts: Array<[string, any]>; + /** objectstack#36350 — the request headers of each draft-addressed write, in order. */ + draftPutHeaders: Array>; /** Every metadata URL the adapter fetched, in order. */ urls: string[]; } @@ -71,8 +73,13 @@ function makeDS(opts: { published: any | Error; packages?: Record; layers?: Record; + /** objectstack#36350 — the `version` the draft read's envelope carries (`undefined`: none). */ + draftVersion?: string; + /** objectstack#36350 — the status the draft-addressed write answers (default 200). */ + draftPutStatus?: number; }): Harness { const draftPuts: Array<[string, any]> = []; + const draftPutHeaders: Array> = []; const urls: string[] = []; const fetchImpl = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { @@ -82,10 +89,19 @@ function makeDS(opts: { status, headers: { 'Content-Type': 'application/json' }, }); + // The pending-drafts ledger `MetadataClient.getDraft` asks first (objectui#11799). + if (/\/meta\/_drafts(\?|$)/.test(url)) { + urls.push(url); + return json({ drafts: opts.draft == null ? [] : [{ type: 'view', name: opts.draft.name }] }); + } if (url.includes('/meta/view/')) { urls.push(url); if ((init?.method ?? 'GET') === 'PUT') { draftPuts.push([url, JSON.parse(String(init?.body ?? '{}'))]); + draftPutHeaders.push({ ...((init?.headers ?? {}) as Record) }); + if (opts.draftPutStatus && opts.draftPutStatus !== 200) { + return json({ code: 'METADATA_CONFLICT', message: 'draft moved', currentVersion: 'hmac-sha256:moved' }, opts.draftPutStatus); + } return json({ success: true, version: 2 }); } if (/\/layers(\?|$)/.test(url)) { @@ -98,7 +114,12 @@ function makeDS(opts: { if (opts.draft == null) return json({ error: 'not found' }, 404); // Draft reads answer the `{type,name,item}` envelope (unlike the // bare-body published read) — the asymmetry `unwrapDraftBody` exists for. - return json({ type: 'view', name: opts.draft.name, item: opts.draft }); + return json({ + type: 'view', + name: opts.draft.name, + item: opts.draft, + ...(opts.draftVersion !== undefined ? { version: opts.draftVersion } : {}), + }); } return json({ error: 'not found' }, 404); } @@ -119,7 +140,7 @@ function makeDS(opts: { }, ...(opts.packages ? { packages: opts.packages } : {}), }; - return { ds, saveItem, draftPuts, urls }; + return { ds, saveItem, draftPuts, draftPutHeaders, urls }; } /** A published read that 404s, decorated the way the SDK client decorates. */ @@ -235,6 +256,13 @@ describe('ObjectStackDataSource.updateView — draft addressing (#4139)', () => // would write the published overlay while a draft may still shadow it. const fetchImpl = vi.fn(async (input: RequestInfo | URL) => { const url = String(input); + // The ledger lists the draft, so the strict draft read is sent (objectui#11799). + if (url.includes('/meta/_drafts')) { + return new Response(JSON.stringify({ drafts: [{ type: 'view', name: DRAFT_VIEW.name }] }), { + status: 200, + headers: { 'Content-Type': 'application/json' }, + }); + } if (url.includes('/meta/view/') && url.includes('state=draft')) { return new Response(JSON.stringify({ error: 'boom' }), { status: 503, @@ -547,3 +575,75 @@ describe('ObjectStackDataSource.updateView — the stored view is the base (obje expect(draftPuts).toHaveLength(0); }); }); + +/** + * objectstack#36350 (ruling 7168616260) — the draft branch writes pinned to the + * draft it read. A draft write by someone else landing between this read and + * this write (another author, or "Save to this view" in flight between its + * draft write and its publish) is refused `409 METADATA_CONFLICT` by the save + * door instead of being merged over: the edit never lands on a body it did not + * read. The read that pins is the strict draft read (`getDraft`, whose envelope + * carries `version`), taken before the layered read the body is merged from. + */ +describe('ObjectStackDataSource.updateView — the draft write is pinned to the draft it read (objectstack#36350)', () => { + it('pins `If-Match` to the draft read\'s version, read before the layers', async () => { + const { ds, draftPuts, draftPutHeaders, urls } = makeDS({ + draft: DRAFT_VIEW, + published: notFound(), + draftVersion: 'hmac-sha256:draft-v1', + }); + + await ds.updateView('crm_activity', DRAFT_VIEW.name, { label: 'Pipeline Board' }); + + expect(draftPuts).toHaveLength(1); + expect(draftPutHeaders[0]['If-Match']).toBe('hmac-sha256:draft-v1'); + expect(draftPutHeaders[0]).not.toHaveProperty('If-None-Match'); + // The version is read first: a write landing between the two reads leaves + // the pin older than the body, so the write is refused rather than merged. + const draftRead = urls.findIndex((u) => u.includes('state=draft')); + const layersRead = urls.findIndex((u) => /\/layers(\?|$)/.test(u)); + expect(draftRead).toBeGreaterThanOrEqual(0); + expect(layersRead).toBeGreaterThan(draftRead); + }); + + it('a draft that appeared after the read saw none is pinned "no draft" (`If-None-Match: *`)', async () => { + const { ds, draftPutHeaders } = makeDS({ + draft: null, + published: notFound(), + // The layered read, sent after, sees a draft the strict read did not. + layers: { code: null, overlay: null, overlayScope: null, effective: null, draft: DRAFT_VIEW }, + }); + + await ds.updateView('crm_activity', DRAFT_VIEW.name, { label: 'Pipeline Board' }); + + expect(draftPutHeaders).toHaveLength(1); + expect(draftPutHeaders[0]['If-None-Match']).toBe('*'); + expect(draftPutHeaders[0]).not.toHaveProperty('If-Match'); + }); + + it('a moved draft is refused 409 and the refusal reaches the caller', async () => { + const { ds, draftPuts } = makeDS({ + draft: DRAFT_VIEW, + published: notFound(), + draftVersion: 'hmac-sha256:draft-v1', + draftPutStatus: 409, + }); + + const refusal = await ds.updateView('crm_activity', DRAFT_VIEW.name, { label: 'Pipeline Board' }).then( + () => null, + (err: unknown) => err, + ); + expect(draftPuts).toHaveLength(1); + expect((refusal as { status?: number } | null)?.status).toBe(409); + }); + + it('CONTROL — a draft read that serves no version pins nothing, as before', async () => { + const { ds, draftPutHeaders } = makeDS({ draft: DRAFT_VIEW, published: notFound() }); + + await ds.updateView('crm_activity', DRAFT_VIEW.name, { label: 'Pipeline Board' }); + + expect(draftPutHeaders).toHaveLength(1); + expect(draftPutHeaders[0]).not.toHaveProperty('If-Match'); + expect(draftPutHeaders[0]).not.toHaveProperty('If-None-Match'); + }); +}); From 9ac751076bd24982320e440fac13e1e0d8d8dafb Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 23:13:54 +0000 Subject: [PATCH 5/9] docs(spec): regenerate the protocol reference for PublishMetaItemRequest.draftVersion Claude-Session: https://claude.ai/code/session_012MmDsSpwtcn5gbWrBDA3Jm Co-authored-by: Claude --- content/docs/references/api/protocol.mdx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/content/docs/references/api/protocol.mdx b/content/docs/references/api/protocol.mdx index fe21995a428..0464643be7c 100644 --- a/content/docs/references/api/protocol.mdx +++ b/content/docs/references/api/protocol.mdx @@ -2660,7 +2660,8 @@ The authoring surface of a metadata write. Closed: `copilot` is an AI assistant' | **message** | `string` | optional | Optional human-readable note recorded with the publish history event. | | **packageId** | `string \| null` | optional | ADR-0048 — the software package the draft being promoted was listed under, when the caller has one to state (`?package=` on the REST door). Named, the publish promotes that package's draft and no other. ABSENT names no package: the publish promotes the draft a draft save that names no package writes — the draft of the one package the item's active rows are bound to, else its package-unbound draft, promoted into that package — and answers `404 NO_DRAFT` when neither exists, as the strict draft read does. For an item never published into a package it is the package-unbound draft, else the one package's draft. It is refused `409 RESOURCE_CONFLICT` when the active rows (or, with none and no package-unbound draft, the drafts) are bound to two or more packages, except a bundled type's member whose active rows a base package and a package declaring it both hold, with no package-unbound row beside them: the read naming no package serves the base's row, and the publish promotes the base's draft into it, as naming the base does (two packages neither of which declares the other are still refused). ⚠️ `null` is NOT the same as absent: the implementation branches on the KEY BEING PRESENT, and `null` pins the lookup to the package-UNBOUND row. Spread it in conditionally; a present-and-`undefined` key coerces to `null` downstream and makes a package-bound draft unfindable — a silent `no_draft`. | | **member** | `string` | optional | Bundle member selector, for a metadata type whose identity is a pair (today only `email_template`, identified by `(name, locale)`): the member this request addresses, spelled as its discriminator value (`zh-CN`). Absent, the canonical member (`en-US` for `email_template`), which is what a bare-name read answers; naming the canonical value is the same request. It is not the response translation locale, which `?locale=` and `Accept-Language` choose. Refused with 400 `VALIDATION_ERROR` on a type that has no members, and for a blank value or one longer than a stored member can be (100 characters). A well-formed member with nothing stored or shipped answers as that door answers an absent item. | -| **parentVersion** | `string \| null` | optional | ADR-0008 optimistic-concurrency pin on the PUBLISHED layer: the version token of the active row the caller loaded and means to replace (on the REST door, the `If-Match` request header; the `/layers` read's `overlayVersion`, the plain read's `version` and a publish receipt's `version` serve it). A token that is not the current active row's at the address the promotion writes is refused 409 `METADATA_CONFLICT`, whose `currentVersion` names the active row's current token, and nothing is promoted: the draft stays pending. ⚠️ `null` is NOT the same as absent: a present `null` asserts "no active row here" (on the REST door, `If-None-Match: *`, which takes `*` alone and never beside `If-Match`), refused 409 when one exists; an ABSENT key is unpinned and promotes over whatever is live, as before. It pins the active row only — which draft is promoted is the address's, as without it. | +| **parentVersion** | `string \| null` | optional | ADR-0008 optimistic-concurrency pin on the PUBLISHED layer: the version token of the active row the caller loaded and means to replace (on the REST door, the `If-Match` request header; the `/layers` read's `overlayVersion`, the plain read's `version` and a publish receipt's `version` serve it). A token that is not the current active row's at the address the promotion writes is refused 409 `METADATA_CONFLICT`, whose `currentVersion` names the active row's current token, and nothing is promoted: the draft stays pending. ⚠️ `null` is NOT the same as absent: a present `null` asserts "no active row here" (on the REST door, `If-None-Match: *`, which takes `*` alone and never beside `If-Match`), refused 409 when one exists; an ABSENT key is unpinned and promotes over whatever is live, as before. It pins the active row only — which draft is promoted is the address's, as without it; the draft's own pin is `draftVersion`. | +| **draftVersion** | `string` | optional | ADR-0008 optimistic-concurrency pin on the DRAFT this publish promotes: the version token of the pending draft row the caller wrote or loaded and means to publish (on the REST door, the `draftVersion` member of the publish body, beside `message`; a draft save's receipt `version` and the draft read's `version` serve it). A token that is not the current draft row's at the address the promotion reads is refused 409 `METADATA_CONFLICT`, whose `currentVersion` names the draft's current token (`null` when no draft is pending), and nothing is promoted: a draft another writer changed after the caller wrote or read it is never published on that writer's behalf. ABSENT is unpinned and promotes whichever draft is pending, as before. It pins the draft only — the active row the promotion replaces is `parentVersion`'s (`If-Match`), and the two may be sent together. | | **userTextLocales** | `string[]` | optional | The locales the user-facing sentences of this write's findings (`advisories[].userMessage`, and `issues[].userMessage` on its 422) are composed in, in ladder order: the locale the request names, then the workspace default. Each is read against the platform locale table, whole and then one subtag shorter at a time; a value that names no table language is passed over, and `en` is the last rung. Stated by the door that holds the request (the REST door and the dispatcher state `[ExecutionContext.locale, ExecutionContext.workspaceLocale]`), never read from a wire body. ABSENT ⇒ the sentences are composed in `en`. It selects a language only: what is judged, refused or saved does not depend on it. | From 8cee422223c72563bb8a2220440e3272d96af509 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 23:14:28 +0000 Subject: [PATCH 6/9] chore(changeset): the publish door's draft pin, per published package Claude-Session: https://claude.ai/code/session_012MmDsSpwtcn5gbWrBDA3Jm Co-authored-by: Claude --- .changeset/36350-publish-draft-pin-client.md | 12 ++++++++++++ .changeset/36350-publish-draft-pin-console.md | 11 +++++++++++ .changeset/36350-publish-draft-pin-protocol.md | 10 ++++++++++ .changeset/36350-publish-draft-pin-rest.md | 10 ++++++++++ .changeset/36350-publish-draft-pin-spec.md | 14 ++++++++++++++ 5 files changed, 57 insertions(+) create mode 100644 .changeset/36350-publish-draft-pin-client.md create mode 100644 .changeset/36350-publish-draft-pin-console.md create mode 100644 .changeset/36350-publish-draft-pin-protocol.md create mode 100644 .changeset/36350-publish-draft-pin-rest.md create mode 100644 .changeset/36350-publish-draft-pin-spec.md diff --git a/.changeset/36350-publish-draft-pin-client.md b/.changeset/36350-publish-draft-pin-client.md new file mode 100644 index 00000000000..4e11be4cd0a --- /dev/null +++ b/.changeset/36350-publish-draft-pin-client.md @@ -0,0 +1,12 @@ +--- +'@object-ui/data-objectstack': patch +--- + +feat(data-objectstack): `MetadataClient.publish` sends `draftVersion`; `updateView` pins its draft write to the draft it read + +Clause-②: yes (widening) +Metadata-protocol: none + +`MetadataClient.publish(type, name, options)` takes an optional `draftVersion` and sends it in the publish body beside `message`, pinning the promotion to that draft (`409 METADATA_CONFLICT` when the draft moved). Omitted, the body carries no such key and the publish is unpinned, as before. + +`ObjectStackAdapter.updateView` (Manage views' Rename, Pin and Set as Default) reads a pending draft through `MetadataClient.getDraft`, whose answer carries the draft's `version`, before the layered read it merges from, and writes the merged draft pinned to it (`If-Match`, or `If-None-Match: *` when the read found no draft). A draft another writer changed in between is refused `409 METADATA_CONFLICT` and `updateView` throws the refusal instead of merging over a body it never read. A server whose draft read carries no `version` gets the unpinned write it got before. diff --git a/.changeset/36350-publish-draft-pin-console.md b/.changeset/36350-publish-draft-pin-console.md new file mode 100644 index 00000000000..ebb0f4a8e82 --- /dev/null +++ b/.changeset/36350-publish-draft-pin-console.md @@ -0,0 +1,11 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/console': patch +--- + +fix(app-shell, console): "Save to this view" and the runtime draft bar's Publish publish only the draft they mean + +Clause-②: yes (widening) +Metadata-protocol: none + +"Save to this view" (and every save that publishes at once, `saveAndPublishRuntimeMetadata`) pins its publish to the draft its own draft write returned. When another admin's rename, pin or set-default lands on the same view between that draft write and the publish, the publish is refused, nothing is published, and the draft, which now holds that other change, stays pending for review instead of being discarded; the save answers as it does over a draft found pending. The runtime draft bar's Publish is pinned to the draft the bar read and shows: a draft changed since is refused with the server's message and stays pending. Against a server that serves no draft version, both publish unpinned, as before. diff --git a/.changeset/36350-publish-draft-pin-protocol.md b/.changeset/36350-publish-draft-pin-protocol.md new file mode 100644 index 00000000000..b412414d58f --- /dev/null +++ b/.changeset/36350-publish-draft-pin-protocol.md @@ -0,0 +1,10 @@ +--- +'@objectstack/metadata-protocol': patch +--- + +feat(metadata-protocol): `publishMetaItem` refuses a draft that moved since the caller's `draftVersion` + +Clause-②: yes (widening) +Metadata-protocol: none + +`publishMetaItem` reads `draftVersion` (`PublishMetaItemRequestSchema.draftVersion`) and judges it against the draft row the promotion reads, before any authoring rule judges that draft: a token that is not that row's, or a pinned draft that is no longer pending, is refused `409 METADATA_CONFLICT` naming the draft's current token as `currentVersion`, with nothing promoted and the optimistic-conflict audit row recorded as for the other publish conflicts. The promotion stays locked to the same row through the write. Absent, any pending draft is promoted, as before; `parentVersion` still pins the active row. diff --git a/.changeset/36350-publish-draft-pin-rest.md b/.changeset/36350-publish-draft-pin-rest.md new file mode 100644 index 00000000000..c3bae8fa165 --- /dev/null +++ b/.changeset/36350-publish-draft-pin-rest.md @@ -0,0 +1,10 @@ +--- +'@objectstack/rest': patch +--- + +feat(rest): `POST /meta/:type/:name/publish` takes `draftVersion` in its body, the pin on the draft it promotes + +Clause-②: yes (widening) +Metadata-protocol: none + +The per-item publish door reads an optional `draftVersion` member from its JSON body, beside `message`, and forwards it to the promotion: a draft that moved since that version (another writer's draft save landing between a caller's draft write and its publish) is refused `409 METADATA_CONFLICT` with the draft's current version as `currentVersion`, and nothing is published. A present `draftVersion` that is not a string is refused `400 VALIDATION_ERROR` instead of being read as absent. `If-Match` / `If-None-Match: *` keep pinning the active row, as before. diff --git a/.changeset/36350-publish-draft-pin-spec.md b/.changeset/36350-publish-draft-pin-spec.md new file mode 100644 index 00000000000..4051de37ffc --- /dev/null +++ b/.changeset/36350-publish-draft-pin-spec.md @@ -0,0 +1,14 @@ +--- +'@objectstack/spec': patch +--- + +feat(spec): `PublishMetaItemRequestSchema` declares `draftVersion`, the per-item publish's pin on the draft it promotes + +Clause-②: yes (widening) +Metadata-protocol: none + +`PublishMetaItemRequestSchema` (the request of `POST /api/v1/meta/:type/:name/publish`) gains one optional member, `draftVersion`: the version token of the pending draft the caller wrote or read and means to publish (a draft save's receipt `version`, or the strict draft read's `version`). On the REST door it is the `draftVersion` member of the publish body, beside `message`. A token that is not the current draft row's is refused `409 METADATA_CONFLICT`, whose `currentVersion` names the draft's current token (`null` when no draft is pending), and nothing is promoted. Absent, the publish promotes whichever draft is pending, as before. + +`parentVersion` (`If-Match` on the REST door) keeps its meaning: it pins the active row the promotion replaces. The two judge different rows and may be sent together. + +Nothing to migrate: a caller that does not send the member is unaffected. From 8eee7080331c7d1a6c47c4dbb1b7369660cb94a2 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 00:51:55 +0000 Subject: [PATCH 7/9] test(app-shell): the report tests wait on the draft bar's getDraft read Claude-Session: https://claude.ai/code/session_012MmDsSpwtcn5gbWrBDA3Jm Co-authored-by: Claude --- .../views/ReportView.authoredEditBuffer-35008.test.tsx | 10 ++++++---- .../views/ReportView.headingStaysServed-36373.test.tsx | 8 +++++--- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/ui/packages/app-shell/src/views/ReportView.authoredEditBuffer-35008.test.tsx b/ui/packages/app-shell/src/views/ReportView.authoredEditBuffer-35008.test.tsx index d542a389dde..27a5ca7ad98 100644 --- a/ui/packages/app-shell/src/views/ReportView.authoredEditBuffer-35008.test.tsx +++ b/ui/packages/app-shell/src/views/ReportView.authoredEditBuffer-35008.test.tsx @@ -154,9 +154,10 @@ function mountReport() { /** A client whose served reads translate and whose layered read is the stored row. */ function makeClient({ draft }: { draft: typeof SOURCE | null }) { return { - // The served draft read (`RuntimeDraftBar`): translated, like every served read. + // The served draft read: translated, like every served read. get: vi.fn(async () => (draft ? served(draft) : null)), - // The served draft read the editor hands `authoredBuffer` (objectstack#35054): the envelope, translated. + // The served draft read the editor hands `authoredBuffer` (objectstack#35054), and the draft bar's + // (`getDraft(type, name)`, objectstack#36350: the envelope keeps the version its Publish pins): translated. getDraft: vi.fn(async () => (draft ? { type: 'report', name: draft.name, item: served(draft) } : null)), layered: vi.fn(async () => ({ code: null, overlay: null, overlayScope: null, effective: SOURCE, draft })), save: vi.fn(async () => ({})), @@ -169,7 +170,8 @@ async function openEditAndSave() { fireEvent.click(await screen.findByTestId('report-edit-button')); await screen.findByTestId('report-config-panel'); // Let the draft bar's read settle, so a resume (if any) has landed first. - await waitFor(() => expect(client.value.get).toHaveBeenCalled()); + // The draft bar's read (`getDraft(type, name)`; the editor's names its package). + await waitFor(() => expect(client.value.getDraft).toHaveBeenCalledWith('report', 'task_overview')); await act(async () => {}); fireEvent.click(screen.getByTestId('stub-report-edit')); await act(async () => { @@ -221,7 +223,7 @@ describe('the report quick edit edits the authored report (objectstack#35008, Re expect(body.blocks.map((b: any) => b.label)).toEqual(['Open Tasks', 'Completed Tasks']); expect(body.description).toBe('Edited description'); // The draft bar still reads the draft, for its indicator and Publish. - expect(client.value.get).toHaveBeenCalledWith('report', 'task_overview', { state: 'draft' }); + expect(client.value.getDraft).toHaveBeenCalledWith('report', 'task_overview'); }); it('a pending draft whose stored copy the layers do not serve opens no editor (objectstack#35054)', async () => { diff --git a/ui/packages/app-shell/src/views/ReportView.headingStaysServed-36373.test.tsx b/ui/packages/app-shell/src/views/ReportView.headingStaysServed-36373.test.tsx index 0601407cb2d..c6e39d21de4 100644 --- a/ui/packages/app-shell/src/views/ReportView.headingStaysServed-36373.test.tsx +++ b/ui/packages/app-shell/src/views/ReportView.headingStaysServed-36373.test.tsx @@ -153,9 +153,10 @@ function mountReport() { /** A client whose served reads translate and whose layered read is the stored row. */ function makeClient({ draft }: { draft: typeof SOURCE | null }) { return { - // The served draft read (`RuntimeDraftBar`): translated, like every served read. + // The served draft read: translated, like every served read. get: vi.fn(async () => (draft ? served(draft) : null)), - // The served draft read the editor hands `authoredBuffer` (objectstack#35054): the envelope, translated. + // The served draft read the editor hands `authoredBuffer` (objectstack#35054), and the draft bar's + // (`getDraft(type, name)`, objectstack#36350: the envelope keeps the version its Publish pins): translated. getDraft: vi.fn(async () => (draft ? { type: 'report', name: draft.name, item: served(draft) } : null)), layered: vi.fn(async () => ({ code: null, overlay: null, overlayScope: null, effective: SOURCE, draft })), save: vi.fn(async () => ({})), @@ -167,7 +168,8 @@ function makeClient({ draft }: { draft: typeof SOURCE | null }) { async function openEditor() { fireEvent.click(await screen.findByTestId('report-edit-button')); await screen.findByTestId('report-config-panel'); - await waitFor(() => expect(client.value.get).toHaveBeenCalled()); + // The draft bar's read (`getDraft(type, name)`; the editor's names its package). + await waitFor(() => expect(client.value.getDraft).toHaveBeenCalledWith('report', 'task_overview')); await act(async () => {}); } From 5b332e94602b797bdaf9d06ec9e8f8118833ab14 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 01:42:12 +0000 Subject: [PATCH 8/9] =?UTF-8?q?fix(spec,metadata-protocol,app-shell):=20co?= =?UTF-8?q?ntract=20review=20on=20the=20draft=20pin=20=E2=80=94=20protocol?= =?UTF-8?q?=20kind,=20bar=20pin=20after=20the=20host's=20save,=20conflict?= =?UTF-8?q?=20text?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Claude-Session: https://claude.ai/code/session_012MmDsSpwtcn5gbWrBDA3Jm Co-authored-by: Claude --- .changeset/36350-publish-draft-pin-client.md | 2 +- .changeset/36350-publish-draft-pin-console.md | 2 +- .../36350-publish-draft-pin-protocol.md | 2 +- .changeset/36350-publish-draft-pin-rest.md | 2 +- .changeset/36350-publish-draft-pin-spec.md | 4 +- .../src/protocol-door-requests.ts | 14 ++++ .../src/protocol-history-and-publish.ts | 13 ++++ .../src/meta-item-publish-version-pin.test.ts | 22 ++++++- packages/spec/src/api/plugin-rest-api.zod.ts | 20 ++++-- packages/spec/src/api/protocol.zod.ts | 21 +++++- .../src/views/RuntimeDraftBar.test.tsx | 66 ++++++++++++++++++- .../app-shell/src/views/RuntimeDraftBar.tsx | 20 ++++-- ...ConfigPanel.pinnedDraftSave-36137.test.tsx | 43 +++++++++++- .../app-shell/src/views/ViewConfigPanel.tsx | 10 ++- .../metadata-admin/DraftConflictDialog.tsx | 17 +++++ .../runtime-metadata-persistence.test.ts | 18 ++++- .../src/views/runtime-metadata-persistence.ts | 24 ++++++- 17 files changed, 272 insertions(+), 28 deletions(-) diff --git a/.changeset/36350-publish-draft-pin-client.md b/.changeset/36350-publish-draft-pin-client.md index 4e11be4cd0a..9ee386a984c 100644 --- a/.changeset/36350-publish-draft-pin-client.md +++ b/.changeset/36350-publish-draft-pin-client.md @@ -5,7 +5,7 @@ feat(data-objectstack): `MetadataClient.publish` sends `draftVersion`; `updateView` pins its draft write to the draft it read Clause-②: yes (widening) -Metadata-protocol: none +Metadata-protocol: added `MetadataClient.publish(type, name, options)` takes an optional `draftVersion` and sends it in the publish body beside `message`, pinning the promotion to that draft (`409 METADATA_CONFLICT` when the draft moved). Omitted, the body carries no such key and the publish is unpinned, as before. diff --git a/.changeset/36350-publish-draft-pin-console.md b/.changeset/36350-publish-draft-pin-console.md index ebb0f4a8e82..74145a6e801 100644 --- a/.changeset/36350-publish-draft-pin-console.md +++ b/.changeset/36350-publish-draft-pin-console.md @@ -6,6 +6,6 @@ fix(app-shell, console): "Save to this view" and the runtime draft bar's Publish publish only the draft they mean Clause-②: yes (widening) -Metadata-protocol: none +Metadata-protocol: added "Save to this view" (and every save that publishes at once, `saveAndPublishRuntimeMetadata`) pins its publish to the draft its own draft write returned. When another admin's rename, pin or set-default lands on the same view between that draft write and the publish, the publish is refused, nothing is published, and the draft, which now holds that other change, stays pending for review instead of being discarded; the save answers as it does over a draft found pending. The runtime draft bar's Publish is pinned to the draft the bar read and shows: a draft changed since is refused with the server's message and stays pending. Against a server that serves no draft version, both publish unpinned, as before. diff --git a/.changeset/36350-publish-draft-pin-protocol.md b/.changeset/36350-publish-draft-pin-protocol.md index b412414d58f..42b55af8ffd 100644 --- a/.changeset/36350-publish-draft-pin-protocol.md +++ b/.changeset/36350-publish-draft-pin-protocol.md @@ -5,6 +5,6 @@ feat(metadata-protocol): `publishMetaItem` refuses a draft that moved since the caller's `draftVersion` Clause-②: yes (widening) -Metadata-protocol: none +Metadata-protocol: added `publishMetaItem` reads `draftVersion` (`PublishMetaItemRequestSchema.draftVersion`) and judges it against the draft row the promotion reads, before any authoring rule judges that draft: a token that is not that row's, or a pinned draft that is no longer pending, is refused `409 METADATA_CONFLICT` naming the draft's current token as `currentVersion`, with nothing promoted and the optimistic-conflict audit row recorded as for the other publish conflicts. The promotion stays locked to the same row through the write. Absent, any pending draft is promoted, as before; `parentVersion` still pins the active row. diff --git a/.changeset/36350-publish-draft-pin-rest.md b/.changeset/36350-publish-draft-pin-rest.md index c3bae8fa165..198cb34f84f 100644 --- a/.changeset/36350-publish-draft-pin-rest.md +++ b/.changeset/36350-publish-draft-pin-rest.md @@ -5,6 +5,6 @@ feat(rest): `POST /meta/:type/:name/publish` takes `draftVersion` in its body, the pin on the draft it promotes Clause-②: yes (widening) -Metadata-protocol: none +Metadata-protocol: added The per-item publish door reads an optional `draftVersion` member from its JSON body, beside `message`, and forwards it to the promotion: a draft that moved since that version (another writer's draft save landing between a caller's draft write and its publish) is refused `409 METADATA_CONFLICT` with the draft's current version as `currentVersion`, and nothing is published. A present `draftVersion` that is not a string is refused `400 VALIDATION_ERROR` instead of being read as absent. `If-Match` / `If-None-Match: *` keep pinning the active row, as before. diff --git a/.changeset/36350-publish-draft-pin-spec.md b/.changeset/36350-publish-draft-pin-spec.md index 4051de37ffc..c9efc5f55ae 100644 --- a/.changeset/36350-publish-draft-pin-spec.md +++ b/.changeset/36350-publish-draft-pin-spec.md @@ -1,11 +1,11 @@ --- -'@objectstack/spec': patch +'@objectstack/spec': minor --- feat(spec): `PublishMetaItemRequestSchema` declares `draftVersion`, the per-item publish's pin on the draft it promotes Clause-②: yes (widening) -Metadata-protocol: none +Metadata-protocol: added `PublishMetaItemRequestSchema` (the request of `POST /api/v1/meta/:type/:name/publish`) gains one optional member, `draftVersion`: the version token of the pending draft the caller wrote or read and means to publish (a draft save's receipt `version`, or the strict draft read's `version`). On the REST door it is the `draftVersion` member of the publish body, beside `message`. A token that is not the current draft row's is refused `409 METADATA_CONFLICT`, whose `currentVersion` names the draft's current token (`null` when no draft is pending), and nothing is promoted. Absent, the publish promotes whichever draft is pending, as before. diff --git a/packages/metadata-protocol/src/protocol-door-requests.ts b/packages/metadata-protocol/src/protocol-door-requests.ts index dbbe11348b5..54faca54e40 100644 --- a/packages/metadata-protocol/src/protocol-door-requests.ts +++ b/packages/metadata-protocol/src/protocol-door-requests.ts @@ -94,6 +94,20 @@ type PublishMetaItemRequest = { member?: string; /** [#32656] The locales the findings' user sentences are composed in (`PublishMetaItemRequestSchema.userTextLocales`). */ userTextLocales?: readonly (string | undefined)[]; + /** + * [#36601] The caller's pin on the active row this promotion replaces + * (`PublishMetaItemRequestSchema.parentVersion`): a token, `null` for "no + * active row here", absent for unpinned. + */ + parentVersion?: string | null; + /** + * [#36350] The caller's pin on the draft this promotion reads + * (`PublishMetaItemRequestSchema.draftVersion`): a token, absent for + * unpinned. Declared here, not only on the promotion's own parameter, so a + * typed in-process caller can state it and an edit that picks members + * instead of spreading the request cannot drop it unseen. + */ + draftVersion?: string; }; /** The request of {@link ObjectStackProtocolImplementation.rollbackMetaItem}. */ diff --git a/packages/metadata-protocol/src/protocol-history-and-publish.ts b/packages/metadata-protocol/src/protocol-history-and-publish.ts index 83b0ed27024..4dfdae076b9 100644 --- a/packages/metadata-protocol/src/protocol-history-and-publish.ts +++ b/packages/metadata-protocol/src/protocol-history-and-publish.ts @@ -967,6 +967,19 @@ export class ProtocolHistoryAndPublishFacet { // active row; the two judge different rows and may be sent together. // Absent, any pending draft is promoted, as before. if (request.draftVersion !== undefined) { + // Off-type from an in-process caller (`null`, a number) is no pin: + // `storedParentForToken` reads `null` as "nothing pinned", which + // would publish unpinned exactly the draft the caller meant to + // guard. The REST door refuses it `400` before it gets here. + if (typeof request.draftVersion !== 'string') { + const err: any = new Error( + `${request.type}/${request.name}: draftVersion must be a string — the version token of the draft ` + + `this publish promotes. Leave it out to publish whichever draft is pending.`, + ); + err.code = 'VALIDATION_ERROR'; + err.status = 400; + throw err; + } try { await host.storedParentForToken( { type: singularType, name: request.name, org: 'env' }, diff --git a/packages/rest/src/meta-item-publish-version-pin.test.ts b/packages/rest/src/meta-item-publish-version-pin.test.ts index 448ccfddd7c..613d869f723 100644 --- a/packages/rest/src/meta-item-publish-version-pin.test.ts +++ b/packages/rest/src/meta-item-publish-version-pin.test.ts @@ -141,7 +141,11 @@ async function boot() { return (rows ?? []).map((r: any) => JSON.parse(String(r.metadata)).label as string); }; - return { protocol, layers, read, readDraft, save, publish, studioSave, stored }; + /** The decision-audit rows of the item, as stored. */ + const audits = async () => + (await engine.find('sys_metadata_audit', { where: { type: 'view', name: 'case_grid' } })) ?? []; + + return { protocol, layers, read, readDraft, save, publish, studioSave, stored, audits }; } const ok = (res: any) => { @@ -328,6 +332,9 @@ describe('[#36350] the publish door\'s draft pin (`draftVersion`)', () => { // Nothing promoted: the live row is untouched and the rename stays a pending draft. expect(await h.stored('active')).toEqual(['live']); expect(await h.stored('draft')).toEqual(['renamed, meant as a draft']); + // The refusal leaves its decision-audit row, as the other publish conflicts do. + const denied = (await h.audits()).filter((a: any) => a.code === 'metadata_conflict'); // adr0112-ok: D6b persisted audit column + expect(denied.map((a: any) => [a.operation, a.outcome])).toEqual([['publish', 'denied']]); }, 60_000); it('acceptance: an UNPINNED updateView draft write inside the window is refused the same way', async () => { @@ -382,6 +389,19 @@ describe('[#36350] the publish door\'s draft pin (`draftVersion`)', () => { expect(await h.stored('draft')).toEqual(['save to this view']); }, 60_000); + it('in process, an off-type `draftVersion` is refused 400 VALIDATION_ERROR by the protocol, never read as unpinned', async () => { + const h = await boot(); + ok(await h.save(view('live'))); + ok(await h.save(view('pending'), { mode: 'draft' })); + const refused: any = await h.protocol + .publishMetaItem({ type: 'view', name: 'case_grid', draftVersion: null } as never) + .then(() => null, (err: unknown) => err); + expect(refused?.code).toBe('VALIDATION_ERROR'); + expect(refused?.status).toBe(400); + expect(await h.stored('active')).toEqual(['live']); + expect(await h.stored('draft')).toEqual(['pending']); + }, 60_000); + for (const [label, draftVersion] of Object.entries({ 'a number': 42, 'null': null, 'an object': { v: 'x' } })) { it(`a \`draftVersion\` that is ${label} is refused 400 VALIDATION_ERROR, never read as unpinned`, async () => { const h = await boot(); diff --git a/packages/spec/src/api/plugin-rest-api.zod.ts b/packages/spec/src/api/plugin-rest-api.zod.ts index a7d10a0a6bc..debf967019c 100644 --- a/packages/spec/src/api/plugin-rest-api.zod.ts +++ b/packages/spec/src/api/plugin-rest-api.zod.ts @@ -951,16 +951,22 @@ export const DEFAULT_METADATA_ROUTES: RestApiRouteRegistration = { 'Promotes the item\'s pending DRAFT overlay to the live `active` row and records an ' + '`op=\'publish\'` history event. The sibling write door of `PUT /:type/:name` — the ' + 'ADR-0033 two-step spelling, where `?mode=draft` stages a body and this makes it live. ' - + '404 `NO_DRAFT` when there is nothing to publish; 409 `METADATA_CONFLICT` when the ' - + 'published row advanced while the draft was held. The route was served for a long time with no ' + + '404 `NO_DRAFT` when there is nothing to publish. 409 `METADATA_CONFLICT` when a pin the ' + + 'caller sent does not hold: the body\'s `draftVersion` (the draft moved, or is no longer ' + + 'pending; judged first, `currentVersion` names the draft\'s token or `null`), or `If-Match` / ' + + '`If-None-Match: *` (the published row advanced; `currentVersion` names the active row\'s ' + + 'token), or the store lost a race. 400 `VALIDATION_ERROR` when `draftVersion` is present and ' + + 'not a string, or the precondition headers are malformed. The route was served for a long time with no ' + 'declaration behind it — this entry is what makes its response contract nameable, the same ' + 'declared-equals-returned rule the save door follows.', tags: ['Metadata'], - // No `requestSchema` (#3899): the body is optional and its only read key - // is `message`, taken only when it is already a string and ignored - // otherwise — the route cannot 400 a malformed body, so declaring a - // schema here would advertise a gate that does not run. Every other - // input (`:type`, `:name`) is path-bound. + // No `requestSchema` (#3899): the body is optional and is not one + // schema. It has two read keys: `message`, taken only when it is a + // string and ignored otherwise, and `draftVersion` + // (`PublishMetaItemRequestSchema.draftVersion`), refused 400 + // `VALIDATION_ERROR` when present and not a string, never read as + // absent. `parentVersion` arrives as the `If-Match` / `If-None-Match` + // headers; `:type` and `:name` are path-bound. responseSchema: 'PublishMetaItemResponseSchema', permissions: ['metadata.write'], cacheable: false, diff --git a/packages/spec/src/api/protocol.zod.ts b/packages/spec/src/api/protocol.zod.ts index 276221171d8..47bef53b44e 100644 --- a/packages/spec/src/api/protocol.zod.ts +++ b/packages/spec/src/api/protocol.zod.ts @@ -1530,6 +1530,15 @@ export const DestructiveChangeIssueSchema = lazySchema(() => z.object({ * state `If-None-Match: *` pins. Both doors of the chain serve it keyed, never * the stored content hash. * + * On the per-item publish door the refusal judges one of two rows, and + * `currentVersion` names the row that refused. A refused `If-Match` / + * `If-None-Match: *` (`PublishMetaItemRequestSchema.parentVersion`) names the + * ACTIVE row's token, pinned back as `If-Match`. A refused draft pin + * (`PublishMetaItemRequestSchema.draftVersion`, judged first) names the + * DRAFT's current token, pinned back as `draftVersion` in the publish body, + * never as `If-Match`; there `null` means no draft is pending any more — + * nothing is left to publish (another writer published or discarded it). + * * Scope: this is the body of the conflicts the four `/meta` item doors answer * through the protocol's one conflict builder, which is how each of them * answers the repository's refusal. Not described here: a per-item @@ -1551,8 +1560,11 @@ export const MetadataConflictErrorSchema = lazySchema(() => z.object({ + 'Send it as `If-Match` to overwrite deliberately (or `If-None-Match: *` ' + 'when it is `null`), or re-read the item to merge first. A `null` for an ' + 'item whose read serves `editable: false` prescribes no pin: that item ' - + 'takes no save. Opaque — echo ' - + 'it verbatim, never parse it.', + + 'takes no save. On the per-item publish door a refused `draftVersion` ' + + 'names the DRAFT\'s current token instead: send it back as `draftVersion` ' + + 'in the publish body (never as `If-Match`, which pins the active row), and ' + + 'there `null` means no draft is pending — nothing is left to publish. ' + + 'Opaque — echo it verbatim, never parse it.', ), })); @@ -1652,7 +1664,10 @@ export const PublishMetaItemRequestSchema = lazySchema(() => z.object({ + 'published on that writer\'s behalf. ABSENT is unpinned and promotes ' + 'whichever draft is pending, as before. It pins the draft only — the active ' + 'row the promotion replaces is `parentVersion`\'s (`If-Match`), and the two ' - + 'may be sent together.', + + 'may be sent together: the draft is judged first, so a request stale on ' + + 'both is refused naming the draft\'s token. The address is resolved before ' + + 'either pin: no draft at the address while another package holds one ' + + 'answers `404 NO_DRAFT`, not this conflict.', ), userTextLocales: userTextLocalesMember(), })); diff --git a/ui/packages/app-shell/src/views/RuntimeDraftBar.test.tsx b/ui/packages/app-shell/src/views/RuntimeDraftBar.test.tsx index 30f8a939433..6d7cc702207 100644 --- a/ui/packages/app-shell/src/views/RuntimeDraftBar.test.tsx +++ b/ui/packages/app-shell/src/views/RuntimeDraftBar.test.tsx @@ -208,7 +208,7 @@ describe('RuntimeDraftBar — Publish is pinned to the draft it showed (objectst expect(screen.getByTestId('runtime-draft-bar')).toBeTruthy(); }); - it('after the host\'s own save (savedSignal) the bar has not read the new draft, and Publish goes unpinned', async () => { + it('after the host\'s own save (savedSignal) the Publish is pinned to that save\'s receipt version, not to the draft read before it', async () => { const metadataClient = makeMetadataClient({ type: 'view', name: 'my_view', @@ -216,6 +216,70 @@ describe('RuntimeDraftBar — Publish is pinned to the draft it showed (objectst version: 'hmac-sha256:draft-v1', }); + const { rerender } = render( + , + ); + await screen.findByTestId('runtime-draft-publish'); + // The view settings saved: its receipt names the draft it wrote. + rerender( + , + ); + fireEvent.click(await screen.findByTestId('runtime-draft-publish')); + + await waitFor(() => + expect(metadataClient.publish).toHaveBeenCalledWith('view', 'my_view', { draftVersion: 'hmac-sha256:saved-v2' }), + ); + // ⛔ No re-read pins it: one draft read, on open. + expect(metadataClient.getDraft).toHaveBeenCalledTimes(1); + }); + + it('save-then-publish window: another writer\'s draft write after the host\'s save is refused at Publish, and the bar stays', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}); + // No draft on open; the host's save writes one (receipt v2); then another + // writer's rename moves it (v3, never shown here). The door refuses the + // Publish pinned to v2. + const metadataClient = makeMetadataClient(null); + metadataClient.publish.mockImplementation(async (_t: string, _n: string, options?: { draftVersion?: string }) => { + if (options?.draftVersion !== 'hmac-sha256:moved-v3') { + throw Object.assign(new Error('view/my_view draft changed since the version this publish pinned (draftVersion)'), { + status: 409, + code: 'METADATA_CONFLICT', + }); + } + return {}; + }); + + const { rerender } = render( + , + ); + await waitFor(() => expect(metadataClient.getDraft).toHaveBeenCalled()); + rerender( + , + ); + fireEvent.click(await screen.findByTestId('runtime-draft-publish')); + + await waitFor(() => + expect(metadataClient.publish).toHaveBeenCalledWith('view', 'my_view', { draftVersion: 'hmac-sha256:saved-v2' }), + ); + // Refused: nothing published, the indicator stays for the author to review. + expect(screen.getByTestId('runtime-draft-bar')).toBeTruthy(); + }); + + it('a host that gives no receipt version leaves the Publish after its save unpinned', async () => { + const metadataClient = makeMetadataClient({ item: { columns: ['name'] }, version: 'hmac-sha256:draft-v1' }); + const { rerender } = render( , ); diff --git a/ui/packages/app-shell/src/views/RuntimeDraftBar.tsx b/ui/packages/app-shell/src/views/RuntimeDraftBar.tsx index b6564cdf21a..da8e79d7806 100644 --- a/ui/packages/app-shell/src/views/RuntimeDraftBar.tsx +++ b/ui/packages/app-shell/src/views/RuntimeDraftBar.tsx @@ -64,6 +64,15 @@ export interface RuntimeDraftBarProps { * dependence on the fire-and-forget write's timing. */ savedSignal?: number; + /** + * objectstack#36350 — the version the host's own save returned (its + * receipt's `version`), given with each {@link savedSignal} bump. The bar's + * Publish after that save is pinned to it (`draftVersion`): the draft the + * bar now shows is the one that save wrote, so a draft another writer + * changed since is refused instead of published on their behalf. Absent (a + * host that does not know it), the Publish after the save goes unpinned. + */ + savedDraftVersion?: string; } /** @@ -90,6 +99,7 @@ export function RuntimeDraftBar({ onResume, onAfterChange, savedSignal, + savedDraftVersion, }: RuntimeDraftBarProps) { const locale = useMetadataLocale(); const refusalTitles = useRefusalTitles(); @@ -146,12 +156,14 @@ export function RuntimeDraftBar({ if (savedSignal === lastSavedSignal.current) return; lastSavedSignal.current = savedSignal; if (savedSignal) { - // The host's own save moved the draft past the one this bar read, and - // the bar has not read the new one: its Publish goes unpinned, as before. - shownDraftVersionRef.current = undefined; + // The host's own save moved the draft past the one this bar read: the + // draft it shows now is that save's, pinned by that save's receipt. ⛔ + // Never a re-read here: after another writer's write it would pin THEIR + // draft, which this bar never showed. + shownDraftVersionRef.current = savedDraftVersion; setHasDraft(true); } - }, [savedSignal]); + }, [savedSignal, savedDraftVersion]); const handlePublish = useCallback(async () => { if (!name) return; diff --git a/ui/packages/app-shell/src/views/ViewConfigPanel.pinnedDraftSave-36137.test.tsx b/ui/packages/app-shell/src/views/ViewConfigPanel.pinnedDraftSave-36137.test.tsx index 8379d13981c..91a4ad8b205 100644 --- a/ui/packages/app-shell/src/views/ViewConfigPanel.pinnedDraftSave-36137.test.tsx +++ b/ui/packages/app-shell/src/views/ViewConfigPanel.pinnedDraftSave-36137.test.tsx @@ -28,7 +28,14 @@ import { describe, it, expect, vi } from 'vitest'; import { render, screen, fireEvent, act, waitFor, cleanup } from '@testing-library/react'; import { MetadataClient } from '@object-ui/data-objectstack'; -vi.mock('./RuntimeDraftBar', () => ({ RuntimeDraftBar: () => null })); +// The draft bar renders nothing here; its props are kept so a pin can read what the panel hands it. +const bar = vi.hoisted(() => ({ props: null as Record | null })); +vi.mock('./RuntimeDraftBar', () => ({ + RuntimeDraftBar: (props: Record) => { + bar.props = props; + return null; + }, +})); // One control: an edit of the view's label, as the real inspector's label field patches it. vi.mock('./metadata-admin/inspectors/ViewVariantInspector', () => ({ @@ -424,3 +431,37 @@ describe('a view create carries the first-write pin (objectstack#36137)', () => expect(door.puts).toEqual([expect.objectContaining({ name: `${OBJECT}.mine`, ifNoneMatch: '*', status: 200 })]); }); }); + +/** + * objectstack#36350 (ruling 7168616260 item 3) — the draft bar's Publish after + * the panel's own save is pinned to the draft that save wrote: the panel hands + * the bar that save's receipt version (`savedDraftVersion`, the `If-Match` its + * guard now holds) with the `savedSignal` bump. Another writer's draft write + * between the save and the Publish then moves the draft away from it, and the + * door refuses the Publish (`RuntimeDraftBar.test.tsx` pins the bar's half). + */ +describe('the draft bar\'s Publish after a view settings save is pinned to that save\'s receipt (objectstack#36350)', () => { + it('each landed save hands the bar its own receipt version', async () => { + const door = viewDoor(); + const { outcomes } = mountPanel(door); + await loadedAndEdited(); + await act(async () => { + fireEvent.click(saveButton()); + }); + await waitFor(() => expect(outcomes).toEqual(['saved'])); + const first = door.draftOf(VIEW_ID)!.version; + await waitFor(() => expect(bar.props?.savedSignal).toBe(1)); + expect(bar.props?.savedDraftVersion).toBe(first); + + fireEvent.click(screen.getByTestId('mock-inspector-label')); + await act(async () => { + fireEvent.click(saveButton()); + }); + await waitFor(() => expect(outcomes).toEqual(['saved', 'saved'])); + const second = door.draftOf(VIEW_ID)!.version; + expect(second).not.toBe(first); + await waitFor(() => expect(bar.props?.savedSignal).toBe(2)); + expect(bar.props?.savedDraftVersion).toBe(second); + cleanup(); + }); +}); diff --git a/ui/packages/app-shell/src/views/ViewConfigPanel.tsx b/ui/packages/app-shell/src/views/ViewConfigPanel.tsx index 60698131564..b5530fb0f8f 100644 --- a/ui/packages/app-shell/src/views/ViewConfigPanel.tsx +++ b/ui/packages/app-shell/src/views/ViewConfigPanel.tsx @@ -212,6 +212,7 @@ export function ViewConfigPanel({ open, onClose, mode = 'edit', activeView, obje save: saveDraftVersioned, recordRead: recordDraftRead, forget: forgetDraftVersion, + heldDraftVersion, dialog: draftConflictDialog, } = useDraftSaveGuard(metadataClient, handleAfterChange); useEffect(() => { @@ -302,6 +303,11 @@ export function ViewConfigPanel({ open, onClose, mode = 'edit', activeView, obje // surfaces the "unpublished changes" indicator immediately (the save // wrote a draft). Never on a refused one (objectui#11583). const [savedSignal, setSavedSignal] = useState(0); + // objectstack#36350 — the version the landed save's receipt returned (the + // guard holds it as that save's `If-Match`): the draft bar's Publish after + // this save is pinned to it, so a draft another writer changed since is + // refused instead of published on their behalf. + const [savedDraftVersion, setSavedDraftVersion] = useState(undefined); // An edit-mode save is in flight: Save is disabled until it settles. const [saving, setSaving] = useState(false); // Mirror the committed draft into a ref so `handlePatch` can compute the @@ -387,9 +393,10 @@ export function ViewConfigPanel({ open, onClose, mode = 'edit', activeView, obje setSaving(false); } if (!landed) return; + setSavedDraftVersion(heldDraftVersion('view', String(flat.id ?? activeView.id))); setSavedSignal((s) => s + 1); if (draftRef.current === savedDraft) setIsDirty(false); - }, [draft, onSave, onCreate, mode, saveDraftVersioned]); + }, [draft, onSave, onCreate, mode, saveDraftVersioned, heldDraftVersion, activeView.id]); // Discard = revert any unsaved edits AND close the panel, in both modes // (objectui#2320). Create mode has no committed view to preview against, so @@ -498,6 +505,7 @@ export function ViewConfigPanel({ open, onClose, mode = 'edit', activeView, obje objectName={objectDef.name} dirty={isDirty} savedSignal={savedSignal} + savedDraftVersion={savedDraftVersion} onAfterChange={handleAfterChange} /> )} diff --git a/ui/packages/app-shell/src/views/metadata-admin/DraftConflictDialog.tsx b/ui/packages/app-shell/src/views/metadata-admin/DraftConflictDialog.tsx index ef1d509493c..224040edb9f 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/DraftConflictDialog.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/DraftConflictDialog.tsx @@ -546,6 +546,14 @@ export class DraftVersionGuard { } } +/** {@link DraftSaveGuard.heldDraftVersion} over a guard: the token of the `If-Match` it holds. */ +export function heldDraftVersionOf(guard: Pick): DraftSaveGuard['heldDraftVersion'] { + return (type, name, packageId) => { + const pin = guard.heldFor(type, name, packageId); + return pin && 'ifMatch' in pin ? pin.ifMatch : undefined; + }; +} + export interface DraftSaveGuard { /** A guarded `client.save` — same arguments, resolves what it ended in. */ save: DraftVersionGuard['save']; @@ -557,6 +565,14 @@ export interface DraftSaveGuard { recordPublished: DraftVersionGuard['recordPublished']; /** The Save's pinned publish (rules 7–8 above). */ publish: DraftVersionGuard['publish']; + /** + * objectstack#36350 — the version of the draft this buffer last wrote or read + * at the item (the `If-Match` it holds: a save's receipt version, or the + * load's draft read), for a publish pinned to that draft (`draftVersion`). + * `undefined` when it holds no token (no draft, or a server that serves no + * version): such a publish goes unpinned. + */ + heldDraftVersion: (type: string, name: string, packageId?: string | null) => string | undefined; /** The conflict dialog; render it once, anywhere in the caller's tree. */ dialog: React.ReactElement; } @@ -613,6 +629,7 @@ export function useDraftSaveGuard(client: Pick, onReload forget: guard.forget, recordPublished: guard.recordPublished, publish: guard.publish, + heldDraftVersion: heldDraftVersionOf(guard), dialog: , }; } diff --git a/ui/packages/app-shell/src/views/runtime-metadata-persistence.test.ts b/ui/packages/app-shell/src/views/runtime-metadata-persistence.test.ts index 789e67aa1d6..b7fea608987 100644 --- a/ui/packages/app-shell/src/views/runtime-metadata-persistence.test.ts +++ b/ui/packages/app-shell/src/views/runtime-metadata-persistence.test.ts @@ -392,7 +392,13 @@ describe('saveAndPublishRuntimeMetadata — a confirmed save everyone sees at on */ describe('the publish is pinned to the draft it means (objectstack#36350)', () => { const RECEIPT = { success: true, version: 'hmac-sha256:draft-v1' }; - const moved = () => Object.assign(new Error('draft changed'), { status: 409, code: 'METADATA_CONFLICT' }); + const refusal = (currentVersion: string | null) => + Object.assign(new Error('draft changed'), { + status: 409, + code: 'METADATA_CONFLICT', + body: { error: 'view/task.all draft changed', code: 'METADATA_CONFLICT', currentVersion }, + }); + const moved = () => refusal('hmac-sha256:moved'); it('Save to this view sends its own draft receipt\'s version as `draftVersion`', async () => { const metadataClient = makeMetadataClient(); @@ -410,6 +416,16 @@ describe('the publish is pinned to the draft it means (objectstack#36350)', () = expect(metadataClient.reset).not.toHaveBeenCalled(); }); + it('a pinned draft no longer pending (`currentVersion: null`) rethrows the refusal: there is no draft to review', async () => { + const metadataClient = makeMetadataClient(); + metadataClient.save.mockResolvedValue(RECEIPT); + const gone = refusal(null); + metadataClient.publish.mockRejectedValue(gone); + await expect(saveAndPublishRuntimeMetadata('view', 'task.all', {}, { metadataClient })).rejects.toBe(gone); + // Nothing of this call's is left to take back: the draft is no longer there. + expect(metadataClient.reset).not.toHaveBeenCalled(); + }); + it('CONTROL: a receipt that carries no version publishes unpinned, as before', async () => { const metadataClient = makeMetadataClient(); metadataClient.save.mockResolvedValue({ success: true }); diff --git a/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts b/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts index b5c4593cab5..5544720aa89 100644 --- a/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts +++ b/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts @@ -39,6 +39,7 @@ */ import { stripReadDecorations } from '@objectstack/spec/kernel'; +import { MetadataConflictErrorSchema } from '@objectstack/spec/api'; import { emitMetadataRefresh } from '../assistant/assistantBus.js'; import { slugify } from './metadata-admin/createDerive.js'; import { @@ -576,6 +577,17 @@ function receiptVersion(receipt: unknown): string | undefined { return typeof version === 'string' && version.length > 0 ? version : undefined; } +/** + * objectstack#36350 — a publish refused `409 METADATA_CONFLICT` whose + * `currentVersion` is `null` (read through the spec's + * `MetadataConflictErrorSchema`): the pinned draft is no longer pending, so + * there is nothing left to publish or to review. + */ +function isNothingPendingConflict(err: unknown): boolean { + const body = MetadataConflictErrorSchema.safeParse((err as { body?: unknown } | null | undefined)?.body); + return body.success && body.data.currentVersion === null; +} + /** What {@link saveAndPublishRuntimeMetadata} did. */ export type SaveAndPublishOutcome = 'published' | 'pending-draft'; @@ -594,7 +606,9 @@ export type SaveAndPublishOutcome = 'published' | 'pending-draft'; * receipt's version, `draftVersion`). When another writer's draft write lands * between the two, the server refuses the publish `409 METADATA_CONFLICT` and * publishes nothing; the moved draft is left pending, never discarded, and - * this resolves `'pending-draft'`. + * this resolves `'pending-draft'`. When the refusal says no draft is pending + * any more (`currentVersion: null`: another writer published or discarded it), + * there is nothing to review, and the refusal is rethrown. * * Any other publish refusal leaves no draft of this call behind: the draft * it wrote is discarded (it was the only one, by the pin) and the refusal is @@ -641,12 +655,16 @@ export async function saveAndPublishRuntimeMetadata( else await ctx.metadataClient.publish(type, name); } catch (err) { if (isDraftVersionConflict(err)) { + invalidateViewCaches(type, name, ctx); + announceDraftLedgerWrite(); + // `currentVersion: null`: no draft is pending any more — another writer + // published or discarded it inside the window. There is no draft to + // review, so the refusal itself is the answer, rethrown as it came. + if (isNothingPendingConflict(err)) throw err; // The draft moved: it now holds the other writer's change on top of // this call's body, so it is no longer this call's own — ⛔ never // discarded here. It stays pending for the draft bar's review, exactly // as a draft found pending before the write does. - invalidateViewCaches(type, name, ctx); - announceDraftLedgerWrite(); return 'pending-draft'; } try { From a0b4863e217f6d10874e82eeae0ea64cf5d75aed Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 01:53:41 +0000 Subject: [PATCH 9/9] docs(spec): regenerate the protocol reference for the draft-pin conflict text Claude-Session: https://claude.ai/code/session_012MmDsSpwtcn5gbWrBDA3Jm Co-authored-by: Claude --- content/docs/references/api/protocol.mdx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/content/docs/references/api/protocol.mdx b/content/docs/references/api/protocol.mdx index 0464643be7c..3d206b515bc 100644 --- a/content/docs/references/api/protocol.mdx +++ b/content/docs/references/api/protocol.mdx @@ -2590,7 +2590,7 @@ The authoring surface of a metadata write. Closed: `copilot` is an AI assistant' | :--- | :--- | :--- | :--- | | **error** | `string` | ✅ | Human-readable refusal sentence, unchanged by `currentVersion`: it names the item and the version the door judged current. For display and logs; branch on `code` and read `currentVersion`, never parse this. | | **code** | `'METADATA_CONFLICT'` | ✅ | ADR-0112 registered code of the optimistic-lock refusal. | -| **currentVersion** | `string \| null` | ✅ | The version token of the head the door judged current — the value the sentence names — or `null` when no row of the target lifecycle exists. Send it as `If-Match` to overwrite deliberately (or `If-None-Match: *` when it is `null`), or re-read the item to merge first. A `null` for an item whose read serves `editable: false` prescribes no pin: that item takes no save. Opaque — echo it verbatim, never parse it. | +| **currentVersion** | `string \| null` | ✅ | The version token of the head the door judged current — the value the sentence names — or `null` when no row of the target lifecycle exists. Send it as `If-Match` to overwrite deliberately (or `If-None-Match: *` when it is `null`), or re-read the item to merge first. A `null` for an item whose read serves `editable: false` prescribes no pin: that item takes no save. On the per-item publish door a refused `draftVersion` names the DRAFT's current token instead: send it back as `draftVersion` in the publish body (never as `If-Match`, which pins the active row), and there `null` means no draft is pending — nothing is left to publish. Opaque — echo it verbatim, never parse it. | --- @@ -2661,7 +2661,7 @@ The authoring surface of a metadata write. Closed: `copilot` is an AI assistant' | **packageId** | `string \| null` | optional | ADR-0048 — the software package the draft being promoted was listed under, when the caller has one to state (`?package=` on the REST door). Named, the publish promotes that package's draft and no other. ABSENT names no package: the publish promotes the draft a draft save that names no package writes — the draft of the one package the item's active rows are bound to, else its package-unbound draft, promoted into that package — and answers `404 NO_DRAFT` when neither exists, as the strict draft read does. For an item never published into a package it is the package-unbound draft, else the one package's draft. It is refused `409 RESOURCE_CONFLICT` when the active rows (or, with none and no package-unbound draft, the drafts) are bound to two or more packages, except a bundled type's member whose active rows a base package and a package declaring it both hold, with no package-unbound row beside them: the read naming no package serves the base's row, and the publish promotes the base's draft into it, as naming the base does (two packages neither of which declares the other are still refused). ⚠️ `null` is NOT the same as absent: the implementation branches on the KEY BEING PRESENT, and `null` pins the lookup to the package-UNBOUND row. Spread it in conditionally; a present-and-`undefined` key coerces to `null` downstream and makes a package-bound draft unfindable — a silent `no_draft`. | | **member** | `string` | optional | Bundle member selector, for a metadata type whose identity is a pair (today only `email_template`, identified by `(name, locale)`): the member this request addresses, spelled as its discriminator value (`zh-CN`). Absent, the canonical member (`en-US` for `email_template`), which is what a bare-name read answers; naming the canonical value is the same request. It is not the response translation locale, which `?locale=` and `Accept-Language` choose. Refused with 400 `VALIDATION_ERROR` on a type that has no members, and for a blank value or one longer than a stored member can be (100 characters). A well-formed member with nothing stored or shipped answers as that door answers an absent item. | | **parentVersion** | `string \| null` | optional | ADR-0008 optimistic-concurrency pin on the PUBLISHED layer: the version token of the active row the caller loaded and means to replace (on the REST door, the `If-Match` request header; the `/layers` read's `overlayVersion`, the plain read's `version` and a publish receipt's `version` serve it). A token that is not the current active row's at the address the promotion writes is refused 409 `METADATA_CONFLICT`, whose `currentVersion` names the active row's current token, and nothing is promoted: the draft stays pending. ⚠️ `null` is NOT the same as absent: a present `null` asserts "no active row here" (on the REST door, `If-None-Match: *`, which takes `*` alone and never beside `If-Match`), refused 409 when one exists; an ABSENT key is unpinned and promotes over whatever is live, as before. It pins the active row only — which draft is promoted is the address's, as without it; the draft's own pin is `draftVersion`. | -| **draftVersion** | `string` | optional | ADR-0008 optimistic-concurrency pin on the DRAFT this publish promotes: the version token of the pending draft row the caller wrote or loaded and means to publish (on the REST door, the `draftVersion` member of the publish body, beside `message`; a draft save's receipt `version` and the draft read's `version` serve it). A token that is not the current draft row's at the address the promotion reads is refused 409 `METADATA_CONFLICT`, whose `currentVersion` names the draft's current token (`null` when no draft is pending), and nothing is promoted: a draft another writer changed after the caller wrote or read it is never published on that writer's behalf. ABSENT is unpinned and promotes whichever draft is pending, as before. It pins the draft only — the active row the promotion replaces is `parentVersion`'s (`If-Match`), and the two may be sent together. | +| **draftVersion** | `string` | optional | ADR-0008 optimistic-concurrency pin on the DRAFT this publish promotes: the version token of the pending draft row the caller wrote or loaded and means to publish (on the REST door, the `draftVersion` member of the publish body, beside `message`; a draft save's receipt `version` and the draft read's `version` serve it). A token that is not the current draft row's at the address the promotion reads is refused 409 `METADATA_CONFLICT`, whose `currentVersion` names the draft's current token (`null` when no draft is pending), and nothing is promoted: a draft another writer changed after the caller wrote or read it is never published on that writer's behalf. ABSENT is unpinned and promotes whichever draft is pending, as before. It pins the draft only — the active row the promotion replaces is `parentVersion`'s (`If-Match`), and the two may be sent together: the draft is judged first, so a request stale on both is refused naming the draft's token. The address is resolved before either pin: no draft at the address while another package holds one answers `404 NO_DRAFT`, not this conflict. | | **userTextLocales** | `string[]` | optional | The locales the user-facing sentences of this write's findings (`advisories[].userMessage`, and `issues[].userMessage` on its 422) are composed in, in ladder order: the locale the request names, then the workspace default. Each is read against the platform locale table, whole and then one subtag shorter at a time; a value that names no table language is passed over, and `en` is the last rung. Stated by the door that holds the request (the REST door and the dispatcher state `[ExecutionContext.locale, ExecutionContext.workspaceLocale]`), never read from a wire body. ABSENT ⇒ the sentences are composed in `en`. It selects a language only: what is judged, refused or saved does not depend on it. |