Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .changeset/38982-read-version.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
'@objectstack/runtime': patch
---

fix(runtime): `get_metadata_item` without `state` answers the `version` a following save takes

Clause-②: no
Metadata-protocol: none

The MCP authoring door's `get_metadata_item`, read without `state`, serves the pending draft where one exists and the published item otherwise, and answered no `version`. An agent that then saved the item had no token for `save_metadata_draft`'s `ifMatch`: it guessed, and the save was refused (`VALIDATION_ERROR` on `ifMatch`, or `409 METADATA_CONFLICT`) until it read again with `state`.

The answer now carries the `version` of what it served: the pending draft's when it says `draft: true`, the published item's otherwise, the same token a read with that `state` answers. A save pinned to it is written. The tokens are read before the item is served, so a change made while the item is read leaves the token older than what was served, and a save pinned to it is refused naming the current version rather than written over a change the caller never saw. A draft published, discarded or first saved while the item is read leaves the answer with no `version`; read it again. `version: null` means save without `ifMatch`. A read with `state` answers as before, and the protocol's `previewDrafts` read is unchanged.
251 changes: 251 additions & 0 deletions packages/runtime/src/domains/mcp-authoring-38982-read-version.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,251 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* [#38982] `get_metadata_item` without `state` answers the `version` a
* following `save_metadata_draft` takes as `ifMatch`. The protocol's
* `previewDrafts` read, which serves a pending draft in place of the published
* item, answers no `version` (no single lifecycle's token describes it), so an
* agent that read an item that way and then saved it guessed `ifMatch` and was
* refused. The door now answers the token of the lifecycle it served: the
* draft's when the answer says `draft: true`, the published item's otherwise.
*
* Every case runs the real metadata protocol over a SQLite file: each token is
* one a read answered, and each save is the protocol's own judgement of it.
* No token is built by hand.
*/

import { afterEach, describe, expect, it } from 'vitest';
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { ObjectQL } from '@objectstack/objectql';
import { SqlDriver } from '@objectstack/driver-sql';
import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol';
import {
SysMetadataObject,
SysMetadataHistoryObject,
SysMetadataAuditObject,
SysMetadataCommitObject,
} from '@objectstack/metadata-core';
import {
createOpenAuthoringRegistry,
type OpenAuthoringProtocol,
type OpenAuthoringReadGateSources,
type OpenAuthoringWriter,
} from './mcp-authoring.js';

const CONTEXT = { door: 'mcp' as const, principal: { userId: 'u1' }, environmentId: 'env_1' };
const PKG = 'com.example.crm_studio';
const FLOW = 'crm_opportunity_followup';

const AUTHOR_READ_GATE: OpenAuthoringReadGateSources = (protocol) => ({
resolveCaller: async () => ({ userId: 'u1', systemPermissions: ['manage_metadata'], mayWriteItem: true }),
resolveSecurityService: async () => undefined,
listMetaItems: (type) => protocol.getMetaItems?.({ type }),
serviceProbe: () => null,
navPruneLogged: new Set<string>(),
});

const WRITER: OpenAuthoringWriter = {
userTextLocales: ['en-US'],
writeVerdict: async () => ({ allowed: true }),
itemSaveRefusal: async () => undefined,
};

/** An autolaunched flow, labelled so each save differs. */
const flow = (label: string) => ({
name: FLOW,
label,
type: 'autolaunched',
nodes: [
{ id: 'start', type: 'start', label: 'Start' },
{ id: 'end', type: 'end', label: 'End' },
],
edges: [{ id: 'e1', source: 'start', target: 'end' }],
});

let cleanup: Array<() => void> = [];
afterEach(() => {
for (const c of cleanup.reverse()) c();
cleanup = [];
});

async function realProtocol(): Promise<OpenAuthoringProtocol> {
const dir = mkdtempSync(join(tmpdir(), 'os-38982-'));
cleanup.push(() => rmSync(dir, { recursive: true, force: true }));
const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: join(dir, 'data.sqlite') }, useNullAsDefault: true });
const platform = [SysMetadataObject, SysMetadataHistoryObject, SysMetadataAuditObject, SysMetadataCommitObject] as any[];
await driver.initObjects(platform);
const engine = new ObjectQL();
engine.registerDriver(driver as any, true);
await engine.init();
for (const o of platform) engine.registry.registerObject(o, '@objectstack/platform-objects');
engine.registry.registerObject({
name: 'crm_opportunity',
label: 'Opportunity',
sharingModel: 'private',
fields: { name: { type: 'text', label: 'Name' } },
} as any, 'com.example.crm');
engine.registry.installPackage({ id: 'com.example.crm', name: 'CRM', version: '1.0.0', type: 'app', scope: 'project' } as any, 'code' as never);
engine.registry.installPackage({ id: PKG, name: 'CRM Studio', version: '1.0.0', type: 'app' } as any, 'authored');
cleanup.push(() => { void engine.destroy(); });
return new ObjectStackProtocolImplementation(engine as any) as unknown as OpenAuthoringProtocol;
}

function door(protocol: OpenAuthoringProtocol) {
const registry = createOpenAuthoringRegistry({
admitted: true,
userId: 'u1',
getProtocol: async () => protocol,
readGate: AUTHOR_READ_GATE,
writer: WRITER,
logger: { warn: () => {} },
});
return async (toolName: string, input: Record<string, unknown>) => {
const result = await registry.execute({ toolCallId: `t-${toolName}`, toolName, input }, CONTEXT);
return { isError: result.isError === true, body: JSON.parse(result.output.value) };
};
}

/** The item published at `PKG`, with no pending draft. */
async function published(protocol: OpenAuthoringProtocol, label = 'Published') {
await protocol.saveMetaItem!({ type: 'flow', name: FLOW, item: flow(label), packageId: PKG, mode: 'publish', actor: 'u1' } as any);
}

const save = (call: ReturnType<typeof door>, label: string, ifMatch: unknown) =>
call('save_metadata_draft', { type: 'flow', name: FLOW, item: flow(label), package: PKG, ifMatch });

describe('[#38982] get_metadata_item without state answers the version a following save takes', () => {
it('no pending draft: it answers the published item\'s version, the one a state: active read answers, and a save pinned to it is written', async () => {
const protocol = await realProtocol();
await published(protocol);
const call = door(protocol);

const read = await call('get_metadata_item', { type: 'flow', name: FLOW });
expect(read.isError, JSON.stringify(read.body)).toBe(false);
expect(read.body.draft).toBe(false);
expect(typeof read.body.version).toBe('string');
const active = await call('get_metadata_item', { type: 'flow', name: FLOW, state: 'active' });
expect(read.body.version).toBe(active.body.version);
// The answer's key order is unchanged: the version rides ahead of the item.
expect(Object.keys(read.body)).toEqual(['type', 'name', 'draft', 'version', 'item']);

const saved = await save(call, 'First edit', read.body.version);
expect(saved.isError, JSON.stringify(saved.body)).toBe(false);
expect(saved.body.saved).toMatchObject({ state: 'draft', version: expect.any(String) });
});

it('a pending draft: it answers the draft\'s version, the one a state: draft read answers, and a save pinned to it is written', async () => {
const protocol = await realProtocol();
await published(protocol);
const call = door(protocol);
const activeVersion = (await call('get_metadata_item', { type: 'flow', name: FLOW })).body.version;
expect((await save(call, 'First edit', activeVersion)).isError).toBe(false);

const read = await call('get_metadata_item', { type: 'flow', name: FLOW });
expect(read.isError, JSON.stringify(read.body)).toBe(false);
expect(read.body.draft).toBe(true);
expect(read.body.item.label).toBe('First edit');
const pending = await call('get_metadata_item', { type: 'flow', name: FLOW, state: 'draft' });
expect(read.body.version).toBe(pending.body.version);
expect(read.body.version).not.toBe(activeVersion);

// The control: the published item's version is not the token this save
// takes once a draft is pending (the card's 409).
const stale = await save(call, 'Second edit', activeVersion);
expect(stale.isError).toBe(true);
expect(stale.body.error).toMatchObject({ code: 'METADATA_CONFLICT', status: 409 });

const saved = await save(call, 'Second edit', read.body.version);
expect(saved.isError, JSON.stringify(saved.body)).toBe(false);
expect((await call('get_metadata_item', { type: 'flow', name: FLOW, state: 'draft' })).body.item.label).toBe('Second edit');
});

it('an item that was never published: the first draft\'s version, and a save pinned to it is written', async () => {
const protocol = await realProtocol();
const call = door(protocol);
expect((await call('save_metadata_draft', { type: 'flow', name: FLOW, item: flow('Draft only'), package: PKG })).isError).toBe(false);

const read = await call('get_metadata_item', { type: 'flow', name: FLOW });
expect(read.body.draft).toBe(true);
expect(typeof read.body.version).toBe('string');
const saved = await save(call, 'Draft edited', read.body.version);
expect(saved.isError, JSON.stringify(saved.body)).toBe(false);
});
});

describe('[#38982] a change while the item is read never answers a token newer than what was served', () => {
/**
* The real protocol, with `change` run once on the served read
* (`previewDrafts`), before it reads: a writer that lands between the
* door's token reads and the served read.
*/
function racing(protocol: OpenAuthoringProtocol, change: () => Promise<unknown>): OpenAuthoringProtocol {
let fired = false;
return new Proxy(protocol, {
get(target, key, receiver) {
const value = Reflect.get(target, key, receiver);
if (key !== 'getMetaItem' || typeof value !== 'function') return typeof value === 'function' ? value.bind(target) : value;
return async (request: { previewDrafts?: boolean }) => {
if (request.previewDrafts && !fired) {
fired = true;
await change();
}
return value.call(target, request);
};
},
});
}

it('the draft saved again in between: the token answered is the older draft\'s, and a save pinned to it is refused, never written over the newer draft', async () => {
const protocol = await realProtocol();
await published(protocol);
const direct = door(protocol);
const activeVersion = (await direct('get_metadata_item', { type: 'flow', name: FLOW })).body.version;
expect((await save(direct, 'First edit', activeVersion)).isError).toBe(false);
const firstDraftVersion = (await direct('get_metadata_item', { type: 'flow', name: FLOW, state: 'draft' })).body.version;

const call = door(racing(protocol, async () => {
expect((await save(direct, 'Someone else', firstDraftVersion)).isError).toBe(false);
}));
const read = await call('get_metadata_item', { type: 'flow', name: FLOW });
expect(read.body.draft).toBe(true);
expect(read.body.item.label).toBe('Someone else');
expect(read.body.version).toBe(firstDraftVersion);

const refused = await save(direct, 'Mine', read.body.version);
expect(refused.body.error).toMatchObject({ code: 'METADATA_CONFLICT', status: 409 });
expect((await direct('get_metadata_item', { type: 'flow', name: FLOW, state: 'draft' })).body.item.label).toBe('Someone else');
});

it('the draft discarded in between: the published item is served with no version, since the token read was the draft\'s', async () => {
const protocol = await realProtocol();
await published(protocol);
const direct = door(protocol);
const activeVersion = (await direct('get_metadata_item', { type: 'flow', name: FLOW })).body.version;
expect((await save(direct, 'First edit', activeVersion)).isError).toBe(false);

const call = door(racing(protocol, async () => {
expect((await direct('delete_metadata_draft', { type: 'flow', name: FLOW, package: PKG })).isError).toBe(false);
}));
const read = await call('get_metadata_item', { type: 'flow', name: FLOW });
expect(read.isError, JSON.stringify(read.body)).toBe(false);
expect(read.body.draft).toBe(false);
expect('version' in read.body).toBe(false);
});

it('a first draft saved in between: the draft is served with no version, since the token read was the published item\'s', async () => {
const protocol = await realProtocol();
await published(protocol);
const direct = door(protocol);
const activeVersion = (await direct('get_metadata_item', { type: 'flow', name: FLOW, state: 'active' })).body.version;

const call = door(racing(protocol, async () => {
expect((await save(direct, 'Someone else', activeVersion)).isError).toBe(false);
}));
const read = await call('get_metadata_item', { type: 'flow', name: FLOW });
expect(read.isError, JSON.stringify(read.body)).toBe(false);
expect(read.body.draft).toBe(true);
expect('version' in read.body).toBe(false);
});
});
3 changes: 3 additions & 0 deletions packages/runtime/src/domains/mcp-authoring.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -462,6 +462,9 @@ describe('the read tools answer from the metadata protocol\'s public reads', ()
await call(authoring, 'get_metadata_item', { type: 'flow', name: 'lead_intake', state: 'draft' });
await call(authoring, 'get_metadata_item', { type: 'flow', name: 'lead_intake', state: 'active' });
expect(calls).toEqual([
// [#38982] The read without `state` reads the pending draft's token first,
// then the item it serves.
['getMetaItem', { type: 'flow', name: 'lead_intake', state: 'draft' }],
['getMetaItem', { type: 'flow', name: 'lead_intake', previewDrafts: true }],
['getMetaItem', { type: 'flow', name: 'lead_intake', state: 'draft' }],
['getMetaItem', { type: 'flow', name: 'lead_intake' }],
Expand Down
43 changes: 40 additions & 3 deletions packages/runtime/src/domains/mcp-authoring.ts
Original file line number Diff line number Diff line change
Expand Up @@ -331,8 +331,10 @@ const READ_TOOLS: readonly AIToolDefinition[] = Object.freeze([
'Read one metadata item\'s full definition. Without `state`, a pending draft is read in place of '
+ 'the published version and the answer says `draft: true`. `state: "draft"` reads the pending '
+ 'draft only and is refused when there is none; `state: "active"` reads the published version. '
+ 'A read with `state` answers that version\'s `version`, the token `save_metadata_draft` takes as '
+ '`ifMatch`; a read without `state` answers none. '
+ 'The answer\'s `version` is the token `save_metadata_draft` takes as `ifMatch`, the one of the '
+ 'version it read: without `state`, the pending draft\'s when it says `draft: true` and the published '
+ 'version\'s otherwise. It carries none when the item changed while it was read: read it again. '
+ '`version: null` means save without `ifMatch`. '
+ 'A flow\'s answer also carries `runtimeState.enabled`: `false` means the flow is switched off and '
+ 'does not run, whatever its `status` reads.',
parameters: {
Expand Down Expand Up @@ -883,6 +885,36 @@ export function createOpenAuthoringRegistry(opts: {
if (!type || !name) return refuse(VALIDATION_ERROR, 'Name the item as `type` and `name`.', 400);
const typeRefused = await typeReadRefusal(type);
if (typeRefused) return typeRefused;
// [#38982] A read without `state` serves the pending draft
// where one exists and the published item otherwise, through
// the protocol's `previewDrafts` read, which answers no
// `version`: no one lifecycle's token describes it. So the
// token of each lifecycle is read here, by the strict read a
// `state` read makes, and the answer below carries the one of
// the lifecycle the served item came from. The tokens are read
// BEFORE the served item, never after: a change in between
// leaves the token older than what was served, and a save
// pinned to it is refused naming the current version. Read
// after, a newer token would pin a save to content the caller
// never saw. A draft that is published, discarded or first
// saved in between leaves no token of the served lifecycle,
// and the answer then carries none.
let servedTokens: { draft?: unknown; active?: unknown } | undefined;
if (state === undefined) {
let pending: { item?: unknown; version?: unknown } | undefined;
try {
pending = await protocol.getMetaItem({ type, name, state: 'draft' });
} catch (error) {
// No pending draft: the strict draft read's 404.
if ((error as { code?: unknown } | null)?.code !== 'NO_DRAFT') throw error;
}
if (pending?.item !== undefined && pending.item !== null) {
servedTokens = pending.version !== undefined ? { draft: pending.version } : {};
} else {
const published = await protocol.getMetaItem({ type, name });
servedTokens = published?.version !== undefined ? { active: published.version } : {};
}
}
const read = await protocol.getMetaItem({
type,
name,
Expand All @@ -902,6 +934,11 @@ export function createOpenAuthoringRegistry(opts: {
}
const item = verdict.document;
const draft = state === 'draft' || (item as { _draft?: unknown })._draft === true;
// A `state` read's own token; a read without `state`, the
// token read above of the lifecycle served, if one was.
const version = servedTokens === undefined
? read.version
: draft ? servedTokens.draft : servedTokens.active;
// [#36856] A flow's switch is not in its definition: an admin
// who switched it off left `status: 'active'` on the item. The
// engine's reading rides beside the item, ahead of it, so a
Expand All @@ -914,7 +951,7 @@ export function createOpenAuthoringRegistry(opts: {
type: read.type ?? type,
name: read.name ?? name,
draft,
...(read.version !== undefined ? { version: read.version } : {}),
...(version !== undefined ? { version } : {}),
...(runtimeState ? { [FLOW_RUNTIME_STATE_KEY]: runtimeState } : {}),
item,
});
Expand Down
Loading