diff --git a/.changeset/34766-mcp-draft-door-write-tools.md b/.changeset/34766-mcp-draft-door-write-tools.md new file mode 100644 index 00000000000..e9c21d079cc --- /dev/null +++ b/.changeset/34766-mcp-draft-door-write-tools.md @@ -0,0 +1,20 @@ +--- +'@objectstack/runtime': patch +'@objectstack/mcp': patch +--- + +feat(runtime,mcp): the open MCP server saves and discards metadata drafts, and every save answers with what publishing the draft would say + +Clause-②: yes (widening) +Metadata-protocol: none + +The open draft door on a self-hosted runtime gains its write half. It is served to the same OAuth clients as the read tools: the token carries `metadata:write` and its user holds `manage_metadata`. + +- `save_metadata_draft({ type, name, item, package, ifMatch? })` saves `item` as a pending draft in `package`, recorded as an MCP save by the token's OAuth client. The reply carries `saved` (type, name, package, state, version), `verdict` and `review`. `verdict` is what publishing the stored draft would say: `publishable`, `refusals` (the issues a publish would refuse the draft on) and `advisories`, each with `rule`, `path`, `message`, `hint` and `severity`. `review` holds the Console routes where a person reviews and publishes the draft in Studio. `ifMatch` is the version the save expects to replace; a stale one is refused as the `/meta` draft save refuses it. +- A save that names no `package` is refused `400 VALIDATION_ERROR`, and nothing is saved. The refusal names the writable packages in that environment. +- `delete_metadata_draft({ type, name, package? })` discards a pending draft. The published version, if any, is left as it is. +- `list_drafts` now gives each draft its `verdict`. A draft the user may not read (for example a dashboard whose `requiredPermissions` they lack) is listed with `verdict: null` and the reason it was withheld. + +A plural type spelling (`dashboards`) is folded to its singular before any gate, verdict or write, as the `/meta` doors fold it. Both writes ask the type-level write admission every `/meta` write asks, so a metadata type the user may not write is refused `403 PERMISSION_DENIED` and nothing is written; a verdict, on a save or a listed draft, is withheld for a type the user may not read. A tenant whose catalog is walled refuses both writes `403 PERMISSION_DENIED`, as the `/meta` write path does; a platform admin is admitted. Nothing on this server publishes: there is no publish tool and no `force`. + +When the authoring tools are listed, the open server's default `initialize` instructions add one paragraph saying that they save drafts only and that a person publishes in Studio. The paragraph is absent when the tools are not served, and a host's own instructions replace the default text as before. diff --git a/.changeset/34766-mcp-draft-door-write.md b/.changeset/34766-mcp-draft-door-write.md new file mode 100644 index 00000000000..6c8b6b023f3 --- /dev/null +++ b/.changeset/34766-mcp-draft-door-write.md @@ -0,0 +1,14 @@ +--- +'@objectstack/metadata-protocol': patch +--- + +feat(metadata-protocol): the draft publish verdict is a public protocol method, and it reads the stored draft itself + +Clause-②: yes (widening) +Metadata-protocol: none + +`ObjectStackProtocolImplementation.draftPublishJudgement` is now public. It answers what publishing a stored draft would say, without publishing it: `refusals`, the issues the publish would refuse the draft on, and `advisories`, the findings a publish that passes still returns. Each issue keeps every member the publish's `422 INVALID_METADATA` carries: `rule`, `path`, `where`, `message`, `hint` (the next step) and `severity`. The draft read's `_diagnostics` folds the same verdict but drops the `hint`. + +A caller that holds no stored row may omit `body`: the method then reads the stored draft at `type`, `name` and `packageId` (`null` for the draft bound to no package), and `member` for a bundled type, and judges the bytes as stored. An address that holds no draft is refused `404 NO_DRAFT`, as the strict draft read refuses it. It runs the same judgement the draft read and the publish gate run; nothing about either changes. + +A caller that judges several drafts in one pass may hand one `packageClosures` map (an empty `Map`) to every call of the pass. The package's other drafts, which a package publish judges each draft against, are then collected once per package instead of once per call. The answers are the same; without the map, each call collects them as before. diff --git a/content/docs/permissions/system-context.mdx b/content/docs/permissions/system-context.mdx index d221ce0be0b..5da5efe131d 100644 --- a/content/docs/permissions/system-context.mdx +++ b/content/docs/permissions/system-context.mdx @@ -210,7 +210,7 @@ One of the largest consumers of the flag; | 54 | Package REST route capability gate bypassed | rest | Get: a marketplace publish over REST (`POST /packages/publish`, the one route the REST registrar mounts since #14503) without `manage_metadata`; the package read cohort (`studio.access` / `setup.access`) is enforced by the dispatcher `/packages` domain's own read gate, where the reads are served | `refusePackageRequest` | | 55 | Package domain capability gates bypassed | runtime | Get: package management and package-inventory reads without the capability | `requireManageMetadata`, `requireReadCapability` | | 56 | Activation write / authoring refusals do not fire | runtime | Get: activation artifacts writable and authorable without the activation-authoring capability | `refuseUngrantedActivationWrite`, `refuseUngrantedActivationAuthoring` | -| 55b | Walled environment-metadata refusal does not fire | metadata-core, rest, runtime | Get: under `isolated` / `group`, a write of the environment's metadata, of any type, at the `/meta` write doors (save, reset, publish, rollback) and `POST /meta/_migrate-stored` on both transports, at every `/packages` write door (create, the manifest `PATCH`, enable, disable, publish, `publish-drafts`, `discard-drafts`, `revert`, `rollback`, `commits/:commitId/revert`, `duplicate`, `adopt-orphans`, delete), at the `/automation` definition writes (create, update, delete, clone), at the permission-set clone door, at the import of a remote table as an object (the REST import route and the MCP `import_object` tool), and at the refresh of a federated datasource's cached catalog. Every other caller below the platform-operator rung is refused `403` there (ADR-0131 D3, D12 items 7–8, D11), because one organization's write would change what every organization resolves. The seeders, the package door and migrations write the environment's metadata this way. Under `single` the refusal is inert for every caller | `walledCatalogWriteVerdict`, `walledCatalogRefusal`, `refuseWalledCatalogPackageWrite`, `refuseWalledFlowDefinitionWrite`, `registerExternalDatasourceRoutes`, `federationService` | +| 55b | Walled environment-metadata refusal does not fire | metadata-core, rest, runtime | Get: under `isolated` / `group`, a write of the environment's metadata, of any type, at the `/meta` write doors (save, reset, publish, rollback) and `POST /meta/_migrate-stored` on both transports, at every `/packages` write door (create, the manifest `PATCH`, enable, disable, publish, `publish-drafts`, `discard-drafts`, `revert`, `rollback`, `commits/:commitId/revert`, `duplicate`, `adopt-orphans`, delete), at the `/automation` definition writes (create, update, delete, clone), at the permission-set clone door, at the import of a remote table as an object (the REST import route and the MCP `import_object` tool), at the open MCP server's draft save and discard (`save_metadata_draft`, `delete_metadata_draft`), and at the refresh of a federated datasource's cached catalog. Every other caller below the platform-operator rung is refused `403` there (ADR-0131 D3, D12 items 7–8, D11), because one organization's write would change what every organization resolves. The seeders, the package door and migrations write the environment's metadata this way. Under `single` the refusal is inert for every caller | `walledCatalogWriteVerdict`, `walledCatalogRefusal`, `refuseWalledCatalogPackageWrite`, `refuseWalledFlowDefinitionWrite`, `registerExternalDatasourceRoutes`, `federationService`, `openWriter` | | 57 | Automation run-state read, flow-authoring write, the paused-run caller gate (screen read and resume), the two operator run-lifecycle writes, and the elevated self-triggered start, the AI-service-account elevated start and the start-record check at every door that starts a flow by name all pass | runtime | Get: run state, flow writes, a paused run's screen and its resume with no grant and without being the run's starter — and cancelling or restoring a suspension without the platform-operator rung. The screen read and the resume ask one predicate, so this is one bypass for both. The lifecycle bypass is the in-process owner's door: plugin-approvals' revise-window recall (ADR-0044) cancels on behalf of a decision it already authorized and recorded. And starting a flow declared `runAs: 'system'` whose type is self-triggered (`autolaunched`, `record_change`, `schedule`) through any door that starts a flow by name — the trigger route, an action of `type: 'flow'` (REST `/actions` and the MCP `run_action` bridge) and a declared endpoint of `type: 'flow'` — which every other caller, the guest principal included, is refused `403 PERMISSION_DENIED` (the maintainer's rulings, letters B and A) — and starting, through the same doors, a flow whose `requiredPermissions` the caller does not hold (ruling record 6377848497, letter A) — and starting, through the same doors, a flow declared `runAs: 'system'` as an AI service account (an agent acting for itself, with no `onBehalfOf`) where the action's `ai.exposed: true` opt-in is not in hand, which that account is refused `403 PERMISSION_DENIED` (ADR-0151 Non-goals, ruling record 6812617393, letter C; a trigger route and a declared endpoint carry no opt-in, so there it is always refused, and the refusal names the action door that admits it). And starting, through the same doors, a flow on a record key the caller's own scope does not deliver, which every other caller is refused with the action door's `404 RECORD_NOT_FOUND` before the run exists (and `400 VALIDATION_FAILED` for a key that is not one id, or for an elevated start that names no object). The three doors ask one check, so this is one bypass for all of them, and it is the in-process caller's, such as a job: inbound HTTP never carries the flag | `mayReadRunState`, `refuseUngrantedFlowWrite`, `isRunStarterOrRunStateReader`, `refuseUngrantedRunLifecycleWrite`, `flowStartRefusal`, `refuseUnreadableFlowStartRecords` | | 57b | Connector credential door's capability and posture gates pass | runtime | Get: listing, setting and clearing the environment's stored connector credentials (`/automation/connectors/credential-refs`) without `manage_metadata`, and under the `group` / `isolated` postures, where the door refuses every other caller `403 PERMISSION_DENIED` naming the posture, the platform operator included, because the store is environment-level. The bypass is the in-process caller's: inbound HTTP never carries the flag. Get nothing more about the value: no answer of this door carries it | `refuseUngrantedConnectorCredentialAccess`, `refuseWalledConnectorCredentialAccess` | | 57c | Connector connection door's capability gate passes | runtime | Get: reading, beginning, completing (the OAuth callback) and revoking an organization's connection of an `oauth2` `authorization_code` connector instance (`/automation/connectors/:name/connection`, `/automation/connectors/oauth/callback`, ADR-0143 D5) without `manage_metadata`. No posture refuses it: a connection belongs to its organization. The bypass is the in-process caller's: inbound HTTP never carries the flag. Get nothing more: no answer of this door carries a token, and the callback's `state` is still bound to the user and organization that began the connect | `refuseUngrantedConnectorConnectionAccess` | @@ -675,6 +675,7 @@ and CI refuses one that differs from what the tree produces. | `packages/runtime/src/domains/automation.ts#refuseWalledConnectorCredentialAccess` | 1 | 57b | | `packages/runtime/src/domains/automation.ts#refuseWalledFlowDefinitionWrite` | 1 | 55b | | `packages/runtime/src/domains/i18n.ts#handleI18nRequest` | 1 | 52 | +| `packages/runtime/src/domains/mcp-authoring.ts#openWriter` | 1 | 55b | | `packages/runtime/src/domains/mcp.ts#federationService` | 1 | 55b | | `packages/runtime/src/domains/mcp.ts#handleMcpRequest` | 1 | 53 | | `packages/runtime/src/domains/mcp.ts#membershipReachRefusal` | 1 | 62b | diff --git a/packages/mcp/src/initialize-selection-rule-34686.test.ts b/packages/mcp/src/initialize-selection-rule-34686.test.ts index 0bb24c3cc10..e05c39d79b7 100644 --- a/packages/mcp/src/initialize-selection-rule-34686.test.ts +++ b/packages/mcp/src/initialize-selection-rule-34686.test.ts @@ -204,6 +204,33 @@ describe('[#34686] initialize instructions — host and configured texts are lef }); }); +describe('[#34766] initialize instructions — the drafts line follows the authoring tools', () => { + const DRAFTS = 'They save drafts only'; + const ONE_TOOL = { getAll: () => [{ name: 'save_metadata_draft', description: 'Save a draft.' }], execute: async () => ({}) as never }; + + it('a metadata:write request whose host registry lists a tool is told authoring lands as drafts a person publishes', async () => { + const runtime = new MCPServerRuntime({ name: 't', version: '1.0.0' }); + const text = await instructionsOf(runtime, makeBridge(), { + grantedScopes: [MCP_OAUTH_SCOPE_DATA_READ, MCP_OAUTH_SCOPE_METADATA_WRITE], + authoring: { registry: ONE_TOOL as never }, + }); + expect(text).toContain(DRAFTS); + // The rest of the open text is still there. + expect(carriesRule(text)).toBe(true); + expect(text).toContain('@objectstack/skills'); + }); + + it('no drafts line where no authoring tool registers: an empty registry, a grant without metadata:write, no injection', async () => { + const runtime = new MCPServerRuntime({ name: 't', version: '1.0.0' }); + const cases: Opts[] = [ + { grantedScopes: [MCP_OAUTH_SCOPE_METADATA_WRITE], authoring: {} }, + { grantedScopes: [MCP_OAUTH_SCOPE_DATA_READ], authoring: { registry: ONE_TOOL as never } }, + {}, + ]; + for (const o of cases) expect(await instructionsOf(runtime, makeBridge(), o), JSON.stringify(o)).not.toContain(DRAFTS); + }); +}); + /** * [#34919] The rule tells the client to follow `list_datasets`' `nextStep` * and cite `query_dataset`'s `sourceLine`, and names the precedence among diff --git a/packages/mcp/src/mcp-server-runtime.authoring-scope.test.ts b/packages/mcp/src/mcp-server-runtime.authoring-scope.test.ts index 703c07261eb..9daca410c1f 100644 --- a/packages/mcp/src/mcp-server-runtime.authoring-scope.test.ts +++ b/packages/mcp/src/mcp-server-runtime.authoring-scope.test.ts @@ -57,6 +57,15 @@ import type { ToolRegistry, } from './types.js'; +/** [#34766] The paragraph the open server's default text adds where authoring tools register. */ +const AUTHORING_DRAFTS_PARAGRAPH_START = 'This connection also lists authoring tools'; + +/** The text with that one paragraph taken out (the paragraphs are joined by a blank line). */ +function withoutDraftsParagraph(text: unknown): unknown { + if (typeof text !== 'string') return text; + return text.split('\n\n').filter((part) => !part.startsWith(AUTHORING_DRAFTS_PARAGRAPH_START)).join('\n\n'); +} + // --------------------------------------------------------------------------- // Fixtures // --------------------------------------------------------------------------- @@ -686,10 +695,12 @@ describe('[#31022] per-request instructions on the authoring injection — answe ).toBe(defaultText); }); - it('a metadata:write request whose injection carries no instructions gets the default', async () => { + it('a metadata:write request whose injection carries no instructions gets the default, plus the drafts line its tools earn', async () => { const defaultText = await instructionsAtInitialize(runtime, { grantedScopes: [MCP_OAUTH_SCOPE_DATA_READ] }); const subject = await instructionsAtInitialize(runtime, { grantedScopes: [MCP_OAUTH_SCOPE_METADATA_WRITE], registry }); - expect(subject).toBe(defaultText); + // [#34766] The one paragraph a request that registers authoring tools adds. + expect(subject).toContain(AUTHORING_DRAFTS_PARAGRAPH_START); + expect(withoutDraftsParagraph(subject)).toBe(defaultText); }); it('a runtime configured with instructions keeps them for every request the injection does not reach', async () => { @@ -810,7 +821,7 @@ describe('[#32766] data-only instructions on the authoring injection — the com await instructionsAtInitialize(runtime, { grantedScopes: [MCP_OAUTH_SCOPE_DATA_READ], registry, dataOnlyInstructions: ' \n ' }), ).toBe(defaultText); expect( - await instructionsAtInitialize(runtime, { grantedScopes: [MCP_OAUTH_SCOPE_METADATA_WRITE], registry, instructions: '' }), + withoutDraftsParagraph(await instructionsAtInitialize(runtime, { grantedScopes: [MCP_OAUTH_SCOPE_METADATA_WRITE], registry, instructions: '' })), ).toBe(defaultText); }); diff --git a/packages/mcp/src/mcp-server-runtime.ts b/packages/mcp/src/mcp-server-runtime.ts index 9296abd6906..c13e800a949 100644 --- a/packages/mcp/src/mcp-server-runtime.ts +++ b/packages/mcp/src/mcp-server-runtime.ts @@ -1837,6 +1837,29 @@ const DATASET_SELECTION_RULE = + 'which reports the first of several_measures, one_measure, candidates_only, no_measure when words differ. Cite ' + 'query_dataset\'s sourceLine as the answer\'s source.'; +/** + * [#34766] What a request that registers host-injected authoring tools is told + * about them, in one sentence true of every such registry: authoring lands as + * drafts that a person reviews and publishes (the authoring section of the + * served skill says the same, `skill-md.ts`). What each tool answers — the + * open draft door's save answers with the publish verdict — is the tool's own + * description. Sent only where the authoring family registers tools + * ({@link authoringToolsServed}). + */ +const AUTHORING_DRAFTS_LINE = + 'This connection also lists authoring tools, which change the app\'s metadata. They save drafts only: nothing ' + + 'they write is published until a person reviews and publishes it in Studio. Read each tool\'s reply before ' + + 'the next step; a refused authoring call means you may not author that here.'; + +/** + * [#34766] Does this request register host-injected authoring tools? The gate + * `registerAuthoringTools` reads (`grantsAuthoringTools`) and a registry that + * lists at least one tool for this caller. + */ +function authoringToolsServed(authoring: McpAuthoringInjection | undefined, grantedScopes: readonly string[] | undefined): boolean { + return authoring !== undefined && grantsAuthoringTools(grantedScopes) && authoring.registry.getAll().length > 0; +} + /** * [#34686] The published skills package an open server points a client to * (#34659 ruling D5 = A), at the version to install: this package's own @@ -1862,13 +1885,19 @@ function skillsInstallLine(version: string | undefined): string | undefined { /** * [#34686] The open server's own `initialize` text for one HTTP request: the * default sentence, the selection rule when this request's grant registers - * both dataset tools, and the skills install line. Read only when neither the + * both dataset tools, [#34766] the drafts line when it registers authoring + * tools, and the skills install line. Read only when neither the * host (`hostInstructions`) nor the runtime's configured `instructions` * answers: both are whole texts their author owns, and the configured one is * the same string for every grant, so nothing is appended to either. */ -function openServerInstructions(datasetRule: boolean): string { - return [DEFAULT_HTTP_INSTRUCTIONS, datasetRule ? DATASET_SELECTION_RULE : undefined, skillsInstallLine(PACKAGE_VERSION)] +function openServerInstructions(datasetRule: boolean, authoringServed = false): string { + return [ + DEFAULT_HTTP_INSTRUCTIONS, + datasetRule ? DATASET_SELECTION_RULE : undefined, + authoringServed ? AUTHORING_DRAFTS_LINE : undefined, + skillsInstallLine(PACKAGE_VERSION), + ] .filter((part): part is string => part !== undefined) .join('\n\n'); } @@ -2821,7 +2850,10 @@ export class MCPServerRuntime { instructions: hostInstructions(opts.authoring, opts.toolOptions?.grantedScopes) ?? this.config.instructions ?? - openServerInstructions(datasetToolsServed(opts.bridge, opts.toolOptions)), + openServerInstructions( + datasetToolsServed(opts.bridge, opts.toolOptions), + authoringToolsServed(opts.authoring, opts.toolOptions?.grantedScopes), + ), }, ); diff --git a/packages/mcp/src/skill-md-surface-guard.test.ts b/packages/mcp/src/skill-md-surface-guard.test.ts index 5de822fc7db..d0333b9acc3 100644 --- a/packages/mcp/src/skill-md-surface-guard.test.ts +++ b/packages/mcp/src/skill-md-surface-guard.test.ts @@ -209,27 +209,28 @@ describe('SKILL.md ↔ native tool surface drift guard', () => { }); /** - * [#34766] The open draft door's read tools, named as the runtime registry - * names them (`OPEN_AUTHORING_READ_TOOL_NAMES` in + * [#34766] The open draft door's five tools, named as the runtime registry + * names them (`OPEN_AUTHORING_READ_TOOL_NAMES` and + * `OPEN_AUTHORING_WRITE_TOOL_NAMES` in * `@objectstack/runtime`, `src/domains/mcp-authoring.ts`; this package cannot * import it). The SDK refuses a second registration under a name already on * the server by throwing, so a collision with any native tool would fail * every `metadata:write` request the open runtime serves. */ -const OPEN_DRAFT_DOOR_READ_TOOLS = ['list_metadata_items', 'get_metadata_item', 'list_drafts']; +const OPEN_DRAFT_DOOR_TOOLS = ['list_metadata_items', 'get_metadata_item', 'list_drafts', 'save_metadata_draft', 'delete_metadata_draft']; -describe('[#34766] the open draft door\'s read tools collide with no native tool', () => { +describe('[#34766] the open draft door\'s tools collide with no native tool', () => { it('registers beside the full native surface under every scope', async () => { const native = await listRegisteredToolNames({ grantedScopes: EVERY_SCOPE }); - for (const name of OPEN_DRAFT_DOOR_READ_TOOLS) expect(native, name).not.toContain(name); + for (const name of OPEN_DRAFT_DOOR_TOOLS) expect(native, name).not.toContain(name); const registry: McpAuthoringToolRegistry = { - getAll: () => OPEN_DRAFT_DOOR_READ_TOOLS.map((name) => ({ name, description: name, parameters: { type: 'object', properties: {} } })), + getAll: () => OPEN_DRAFT_DOOR_TOOLS.map((name) => ({ name, description: name, parameters: { type: 'object', properties: {} } })), async execute(toolCall): Promise { return { type: 'tool-result', toolCallId: toolCall.toolCallId, toolName: toolCall.toolName, output: { type: 'text', value: '' } } as ToolExecutionResult; }, }; const withDoor = await listRegisteredToolNames({ grantedScopes: EVERY_SCOPE, registry }); - expect(withDoor.sort()).toEqual([...native, ...OPEN_DRAFT_DOOR_READ_TOOLS].sort()); + expect(withDoor.sort()).toEqual([...native, ...OPEN_DRAFT_DOOR_TOOLS].sort()); }); }); diff --git a/packages/metadata-protocol/src/protocol-authoring-gate.ts b/packages/metadata-protocol/src/protocol-authoring-gate.ts index 87fc38a29dc..638ced616c4 100644 --- a/packages/metadata-protocol/src/protocol-authoring-gate.ts +++ b/packages/metadata-protocol/src/protocol-authoring-gate.ts @@ -51,6 +51,8 @@ import { permissionSetOwnerBindingRefusal, runtimeHookWithoutBodyRefusal } from import { objectBodyExtensionFieldSuffixRefusal } from './protocol-extension-field-suffix.js'; import { datasourceCredentialsRefSaveRefusal } from './protocol-datasource-credentials-ref.js'; import { storedFlowVerdictBody } from './protocol-flow-save-replay.js'; +import { noPendingDraftError } from './protocol-authoring-refusals.js'; +import { memberOption } from './protocol-bundle-members.js'; import { evaluateRuntimeAuthoringGate } from './runtime-authoring-gate.js'; import { withDisabledExtensionsFolded } from './metadata-diagnostics.js'; import type { PackagedRuleCopyRefusal, RuntimeAuthoringIssue, RuntimeAuthoringVerdict, RuntimePendingDeclarations } from './runtime-authoring-gate.js'; @@ -746,20 +748,57 @@ export async function draftPublishVerdict( * publish checks before Publish is pressed. One run of the same rules; * `userTextLocales` picks the language of the advisories' user sentences and * nothing else. + * + * [#34766] The class method is PUBLIC: it is the publish verdict a door that + * cannot publish answers with (the open MCP draft door's save and its draft + * list), so its caller can tell its author what a publish would refuse before + * a person presses Publish. Each issue keeps every member the publish 422 + * carries (`rule`, `path`, `where`, `message`, `hint`, `severity`); the draft + * read's `_diagnostics` folds them and drops the `hint`, the next step. + * + * Such a door holds no stored row, so `body` may be omitted: the judgement + * then reads the stored draft itself, at the address `packageId` (`null` = the + * package-unbound draft) and `member` name, exactly as the draft read hands + * the row it serves (the bytes as stored, never a served or redacted copy), + * and an address that holds no draft is refused `404 NO_DRAFT`, the strict + * draft read's own refusal ({@link noPendingDraftError}). Never a second + * judgement: the same rules, on the same body, as the draft read's verdict. */ export async function draftPublishJudgement( this: DraftVerdictHost, draft: { - type: string; name: string; body: unknown; packageId: string | null; + /** [#34766] Omitted ⇒ the stored draft at (`type`, `name`, `packageId`, `member`) is read and judged. */ + type: string; name: string; body?: unknown; packageId: string | null; + /** [#34766] The bundle member whose stored draft to read when `body` is omitted; omitted, the canonical member. */ + member?: string; /** * [#34818] The locales the advisories' user sentences are composed in * (`GetMetaItemRequestSchema.userTextLocales`, stated by the draft read * doors). Absent ⇒ `en`. Selects a language, never a verdict. */ userTextLocales?: readonly (string | undefined)[]; + /** + * [#34766] One map per pass, for a caller that judges several drafts in + * one answer (the open MCP door's draft list): a package's closure is + * collected on its first draft and reused for the rest, since it is a + * function of the package alone, never of the draft judged. Absent ⇒ + * collected on this call, as before. + */ + packageClosures?: Map>; }, ): Promise { const singular = PLURAL_TO_SINGULAR[draft.type] ?? draft.type; + // [#34766] No body handed: the stored draft at the address, as stored. + let body = draft.body; + if (body === undefined) { + const repo = this.getOverlayRepo(); + const stored = await repo.get( + { type: singular, name: draft.name, org: 'env' } as Parameters[0], + { state: 'draft', packageId: draft.packageId, ...memberOption(draft.member) }, + ); + if (!stored) throw noPendingDraftError(draft.type, draft.name); + body = stored.body; + } // The closure "Publish all" judges this draft against: its package's other // drafts, collected by the batch door's own collector from the batch door's // own listing. A package-unbound draft has no batch; its publish is the @@ -768,7 +807,13 @@ export async function draftPublishJudgement( if (draft.packageId) { const repo = this.getOverlayRepo(); if (typeof repo.listDrafts === 'function') { - pending = await this.collectBatchPendingDeclarations(await repo.listDrafts({ packageId: draft.packageId })); + const packageId = draft.packageId; + let closure = draft.packageClosures?.get(packageId); + if (!closure) { + closure = repo.listDrafts({ packageId }).then((drafts) => this.collectBatchPendingDeclarations(drafts)); + draft.packageClosures?.set(packageId, closure); + } + pending = await closure; } } // The promotion's restored-credential read: the stored draft holds no @@ -780,11 +825,11 @@ export async function draftPublishJudgement( state: 'active', // [#29557] The body the promotion judges: a flow draft in its // D2-converted spelling, every other draft as stored. - body: storedFlowVerdictBody(singular, draft.body), + body: storedFlowVerdictBody(singular, body), packageId: draft.packageId, ...(pending !== undefined ? { pending } : {}), ...(channel - ? { restoredCredentialPaths: () => channel.heldPaths({ name: draft.name, state: 'draft', item: draft.body }) } + ? { restoredCredentialPaths: () => channel.heldPaths({ name: draft.name, state: 'draft', item: body }) } : {}), ...(draft.userTextLocales !== undefined ? { userTextLocales: draft.userTextLocales } : {}), }); diff --git a/packages/metadata-protocol/src/protocol.draft-publish-verdict.test.ts b/packages/metadata-protocol/src/protocol.draft-publish-verdict.test.ts index 6bc0e28e377..be522f9254e 100644 --- a/packages/metadata-protocol/src/protocol.draft-publish-verdict.test.ts +++ b/packages/metadata-protocol/src/protocol.draft-publish-verdict.test.ts @@ -1383,3 +1383,115 @@ describe('[#34818] a flow draft read carries the advisories its publish would re expect(warnings.filter((w) => w.path === 'nodes.1')).toEqual([]); }); }); + +/** + * [#34766] The draft verdict is PUBLIC: a door that cannot publish (the open + * MCP draft door) answers its draft save and its draft list with it, so its + * caller learns what a publish would refuse before a person presses Publish. + * + * Such a door holds no stored row, so the method reads the stored draft itself + * when no `body` is handed. Pinned: that read judges the bytes as stored, at + * the package named, and answers the per-item publish's own 422 issues WHOLE, + * the `hint` (the next step) included, which the draft read's `_diagnostics` + * drops; an address with no draft is refused as the strict draft read refuses + * it. One judgement: the answer equals the body-handed call's. + */ +describe('[#34766] the public draft publish verdict judges the stored draft', () => { + let warn: ReturnType; + beforeEach(() => { + warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + delete process.env.OS_ALLOW_UNLINTED_METADATA_WRITES; + }); + afterEach(() => { + warn.mockRestore(); + }); + + /** A record-triggered flow whose start node names no trigger: saved as a draft, refused at publish. */ + const unroutable = { + name: 'deal_followup', + label: 'Deal Follow-up', + type: 'record_change', + nodes: [ + { id: 'start', type: 'start', label: 'Start', config: { objectName: 'deal' } }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [{ id: 'e1', source: 'start', target: 'end' }], + }; + + it('with no body, answers the publish 422 issues of the stored draft whole, hint included', async () => { + const { engine } = makeStubEngine(); + const protocol = new ObjectStackProtocolImplementation(engine); + expect(await stageDraft(protocol, 'flow', unroutable)).toMatchObject({ success: true, state: 'draft' }); + + const judgement = await protocol.draftPublishJudgement({ type: 'flow', name: 'deal_followup', packageId: PKG }); + + const finding = judgement.refusals.find((issue) => issue.rule === 'flow-trigger-unroutable'); + expect(finding, JSON.stringify(judgement.refusals)).toBeDefined(); + expect(finding!.path).toBe('flows[0].nodes[0].config.triggerType'); + expect(finding!.severity).toBe('error'); + expect(typeof finding!.hint === 'string' && finding!.hint.length > 0).toBe(true); + + // The publish refuses on exactly these issues, every member included. + const refusal: any = await protocol + .publishMetaItem({ type: 'flow', name: 'deal_followup', packageId: PKG } as any) + .then(() => null, (e: unknown) => e); + expect({ code: refusal?.code, status: refusal?.status }).toEqual({ code: 'INVALID_METADATA', status: 422 }); + expect(judgement.refusals).toEqual(refusal.issues); + }); + + it('judges the stored bytes as the body-handed call judges them: one judgement', async () => { + const { engine, rows } = makeStubEngine(); + const protocol = new ObjectStackProtocolImplementation(engine); + await stageDraft(protocol, 'flow', unroutable); + const stored = JSON.parse([...rows.values()].find((r) => r.name === 'deal_followup' && r.state === 'draft')!.metadata); + + expect(await protocol.draftPublishJudgement({ type: 'flow', name: 'deal_followup', packageId: PKG })) + .toEqual(await protocol.draftPublishJudgement({ type: 'flow', name: 'deal_followup', body: stored, packageId: PKG })); + }); + + it('an address that holds no draft is refused 404 NO_DRAFT, as the strict draft read refuses it', async () => { + const { engine } = makeStubEngine(); + const protocol = new ObjectStackProtocolImplementation(engine); + await stageDraft(protocol, 'flow', unroutable); + + const refusalOf = (draft: { name: string; packageId: string | null }) => protocol + .draftPublishJudgement({ type: 'flow', ...draft }) + .then(() => null, (e: any) => ({ code: e?.code, status: e?.status })); + // Another name, and the package-unbound address of a draft staged into a package. + expect(await refusalOf({ name: 'no_such_flow', packageId: PKG })).toEqual({ code: 'NO_DRAFT', status: 404 }); + expect(await refusalOf({ name: 'deal_followup', packageId: null })).toEqual({ code: 'NO_DRAFT', status: 404 }); + const read: any = await protocol.getMetaItem({ type: 'flow', name: 'no_such_flow', state: 'draft', packageId: PKG } as any) + .then(() => null, (e: any) => ({ code: e?.code, status: e?.status })); + expect(read).toEqual({ code: 'NO_DRAFT', status: 404 }); + }); + + it('one closure map for a pass collects each package\'s closure once and changes no answer; without it, each call collects', async () => { + const { engine } = makeStubEngine(); + const protocol = new ObjectStackProtocolImplementation(engine); + const names = ['deal_followup', 'deal_followup_b', 'deal_followup_c']; + for (const name of names) await stageDraft(protocol, 'flow', { ...unroutable, name }); + const collect = vi.spyOn(protocol as any, 'collectBatchPendingDeclarations'); + + const alone = []; + for (const name of names) alone.push(await protocol.draftPublishJudgement({ type: 'flow', name, packageId: PKG })); + expect(collect).toHaveBeenCalledTimes(3); + + collect.mockClear(); + const packageClosures = new Map(); + const pass = []; + for (const name of names) pass.push(await protocol.draftPublishJudgement({ type: 'flow', name, packageId: PKG, packageClosures })); + expect(collect).toHaveBeenCalledTimes(1); + expect(pass).toEqual(alone); + expect(alone.every((j) => j.refusals.some((issue) => issue.rule === 'flow-trigger-unroutable'))).toBe(true); + }); + + it('a draft the publish passes answers no refusal', async () => { + const { engine } = makeStubEngine(); + const protocol = new ObjectStackProtocolImplementation(engine); + const routed = structuredClone(unroutable); + (routed.nodes[0]!.config as Record).triggerType = 'record-after-create'; + await stageDraft(protocol, 'flow', routed); + + expect((await protocol.draftPublishJudgement({ type: 'flow', name: 'deal_followup', packageId: PKG })).refusals).toEqual([]); + }); +}); diff --git a/packages/metadata-protocol/src/protocol.ts b/packages/metadata-protocol/src/protocol.ts index 08c65f0af79..8b709139b40 100644 --- a/packages/metadata-protocol/src/protocol.ts +++ b/packages/metadata-protocol/src/protocol.ts @@ -1912,10 +1912,11 @@ export class ObjectStackProtocolImplementation implements return draftPublishVerdict.call(this.draftVerdictHost(), draft); } - /** [#34818] The same judgement with the gate's advisories beside its refusal (see `draftPublishJudgement`). */ - private draftPublishJudgement(draft: { - type: string; name: string; body: unknown; packageId: string | null; + /** [#34818, #34766] PUBLIC: this judgement with the gate's advisories; no `body` ⇒ the stored draft (see `draftPublishJudgement`). */ + draftPublishJudgement(draft: { + type: string; name: string; body?: unknown; packageId: string | null; member?: string; userTextLocales?: readonly (string | undefined)[]; + packageClosures?: Map>; }): Promise { return draftPublishJudgement.call(this.draftVerdictHost(), draft); } diff --git a/packages/metadata-protocol/src/registry-question.ts b/packages/metadata-protocol/src/registry-question.ts index c750414bb22..14dccb38283 100644 --- a/packages/metadata-protocol/src/registry-question.ts +++ b/packages/metadata-protocol/src/registry-question.ts @@ -62,7 +62,10 @@ export type RegistryQuestion = 'against-registry' | 'body-only'; * dispatcher (`meta-dispatch`), and a datasource table's import * (`external-import`: each import saves ONE object and relays the save's * refusal to its caller, #32369 — not a batch). Each is stated at exactly one - * call site. + * call site, except `meta-dispatch`, which the open MCP draft door + * (`packages/runtime/src/domains/mcp-authoring.ts`) also states for its + * structured `issues[]` channel; that door saves drafts only, so it asks the + * body-only question ({@link saveRegistryQuestion}). */ export const AGAINST_REGISTRY_SAVE_FACES: ReadonlySet = new Set(['meta-envelope', 'meta-dispatch', 'external-import']); @@ -104,6 +107,7 @@ export interface RegistryQuestionProducer { export const REGISTRY_QUESTION_PRODUCERS: readonly RegistryQuestionProducer[] = [ { file: 'packages/rest/src/meta-item-write-routes.ts', callee: 'saveMetaItem', calls: 1, question: 'by-face', why: '`PUT /meta/:type/:name`, face `meta-envelope`: against the registry when published.' }, { file: 'packages/runtime/src/domains/meta.ts', callee: 'saveMetaItem', calls: 1, question: 'by-face', why: 'the runtime `/meta` dispatcher, face `meta-dispatch`: against the registry when published.' }, + { file: 'packages/runtime/src/domains/mcp-authoring.ts', callee: 'saveMetaItem', calls: 1, question: 'by-face', why: 'the open MCP draft door\'s `save_metadata_draft`, face `meta-dispatch` and always `mode: \'draft\'` (it has no publish tool): body-only; a person publishes in Studio, through a door that asks its own question.' }, { file: 'packages/runtime/src/domains/automation.ts', callee: 'saveMetaItem', calls: 1, question: 'body-only', why: 'a flow clone writes a flow, never an object.' }, { file: 'packages/runtime/src/domains/packages.ts', callee: 'saveMetaItem', calls: 1, question: 'body-only', why: 'a package publish/unpublish flips each of its apps\' visibility: writes an app, never an object.' }, { file: 'packages/runtime/src/domains/permission-set-clone.ts', callee: 'saveMetaItem', calls: 1, question: 'body-only', why: 'a permission-set clone writes a permission set, never an object.' }, diff --git a/packages/runtime/src/domains/mcp-authoring.test.ts b/packages/runtime/src/domains/mcp-authoring.test.ts index a72a1ccd772..6fe0dd3bf42 100644 --- a/packages/runtime/src/domains/mcp-authoring.test.ts +++ b/packages/runtime/src/domains/mcp-authoring.test.ts @@ -1,7 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. /** - * [#34766] The open MCP draft door's admission and its three read tools. + * [#34766] The open MCP draft door's admission, its three read tools, its two + * draft writes, and the publish verdict a save and each listed draft answer with. * * The effective right is the intersection of the token's consent * (`metadata:write`) and the HUMAN's own `manage_metadata` (seat ruling D1 A). @@ -19,7 +20,19 @@ * resolution that throws admits nothing. */ -import { describe, it, expect } from 'vitest'; +import { describe, it, expect, afterEach, vi } 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'; // The `/mcp` domain reaches the dispatcher, which loads this package lazily; // paid here, during collection, never inside a clocked case. import '@objectstack/metadata'; @@ -28,6 +41,7 @@ import { PLATFORM_PROVIDED_TOOL_NAMES, PLATFORM_TOOL_FAMILY_PREFIXES } from '@ob import { handleMcpRequest } from './mcp.js'; import { OPEN_AUTHORING_READ_TOOL_NAMES, + OPEN_AUTHORING_WRITE_TOOL_NAMES, createOpenAuthoringRegistry, resolveOpenAuthoringInjection, type OpenAuthoringInjection, @@ -79,6 +93,16 @@ async function oauthEnvelope(scopes: string[], systemPermissions: string[]) { } const ADMIN = ['manage_metadata', 'manage_users']; + +/** One publish finding, every member the publish 422 carries. */ +const UNROUTABLE_ISSUE = { + rule: 'flow-trigger-unroutable', + path: 'flows[0].nodes[0].config.triggerType', + where: 'flow "lead_intake" › start node', + message: 'declares type: \'record_change\' but its start node has no triggerType at all', + hint: 'Set triggerType to record-{before,after}-{create,update,delete,write}', + severity: 'error' as const, +}; const NOT_AN_AUTHOR = ['manage_users']; /** @@ -124,6 +148,18 @@ function fakeProtocol(store: Record = {}, opts: { listThrows?: st calls.push(['listDrafts', request]); return { drafts: [{ type: 'flow', name: 'lead_intake', label: 'Lead intake', packageId: 'com.acme.crm', updatedAt: null }] } as any; }, + async saveMetaItem(request: any) { + calls.push(['saveMetaItem', request]); + return { success: true, version: 'v8', seq: 1, state: 'draft' } as any; + }, + async deleteMetaItem(request: any) { + calls.push(['deleteMetaItem', request]); + return { success: true } as any; + }, + async draftPublishJudgement(draft: any) { + calls.push(['draftPublishJudgement', draft]); + return { refusals: [UNROUTABLE_ISSUE], advisories: [] }; + }, }; return { protocol, calls }; } @@ -144,10 +180,18 @@ interface Served { */ async function serve( executionContext: unknown, - opts: { systemPermissions?: string[]; qlThrows?: boolean; store?: Record; listThrows?: string } = {}, + opts: { + systemPermissions?: string[]; qlThrows?: boolean; store?: Record; listThrows?: string; + /** A protocol to serve in place of the recording double (the real one, for the end-to-end pin). */ + protocol?: OpenAuthoringProtocol; + /** The `tenancy` service the walled refusal reads its posture from. */ + tenancy?: { posture: string }; + } = {}, ): Promise { const { ql, reads } = userQl(opts.systemPermissions ?? ADMIN); - const { protocol, calls } = fakeProtocol(opts.store, { listThrows: opts.listThrows }); + const fake = fakeProtocol(opts.store, { listThrows: opts.listThrows }); + const protocol = opts.protocol ?? fake.protocol; + const calls = fake.calls; // The holdings the docs audience reads: the permission sets on the caller the // gate is handed, so a set the human does not hold is not held. const security = { resolvePermissionSetNames: async (ctx: any) => (Array.isArray(ctx?.permissions) ? ctx.permissions : []) }; @@ -161,7 +205,7 @@ async function serve( }; const deps = { resolveService: async (_ctx: unknown, name: string) => (name === 'mcp' ? mcp : name === 'protocol' ? protocol : name === 'security' ? security : undefined), - resolveServiceOrLoud: async () => undefined, + resolveServiceOrLoud: async (_ctx: unknown, name: string) => (name === 'tenancy' ? opts.tenancy : undefined), getObjectQL: async () => { if (opts.qlThrows) throw new Error('engine lookup failed'); return ql; @@ -235,14 +279,14 @@ describe('the open draft door is served only where the token consents AND the us expect(served.protocolCalls).toEqual([]); }); - it('a metadata:write token whose user holds manage_metadata lists the three read tools, and a read is served', async () => { + it('a metadata:write token whose user holds manage_metadata lists the five tools, and a read is served', async () => { const ec = await oauthEnvelope(['metadata:write'], ADMIN); // The envelope itself carries no capability: the door read the human's grant. expect(ec.systemPermissions).toEqual([]); const served = await serve(ec); expect(served.grantReads.length).toBeGreaterThan(0); const authoring = served.authoring!; - expect(authoring.registry.getAll().map((t) => t.name)).toEqual([...OPEN_AUTHORING_READ_TOOL_NAMES]); + expect(authoring.registry.getAll().map((t) => t.name)).toEqual([...OPEN_AUTHORING_READ_TOOL_NAMES, ...OPEN_AUTHORING_WRITE_TOOL_NAMES]); expect(authoring.principal).toMatchObject({ userId: 'u1', clientId: 'c1', scopes: ['metadata:write'] }); expect(authoring.environmentId).toBe('env_1'); @@ -382,7 +426,7 @@ describe('the read tools answer from the metadata protocol\'s public reads', () const listed = await call(authoring, 'list_drafts', { package: 'com.acme.crm' }); await call(authoring, 'list_drafts', {}); expect(listed.body.count).toBe(1); - expect(calls).toEqual([['listDrafts', { packageId: 'com.acme.crm' }], ['listDrafts', {}]]); + expect(calls.filter((c: any) => c[0] === 'listDrafts')).toEqual([['listDrafts', { packageId: 'com.acme.crm' }], ['listDrafts', {}]]); }); it('a coded protocol refusal keeps its code; an uncoded throw is a fault answered without its text', async () => { @@ -542,12 +586,348 @@ describe('the read tools withhold what every /meta door withholds from this huma }); }); -describe('the read tools\' names', () => { +describe('the tools\' names', () => { it('collide with no hosted platform tool (seat ruling D3: not list_metadata)', () => { - for (const name of OPEN_AUTHORING_READ_TOOL_NAMES) { + for (const name of [...OPEN_AUTHORING_READ_TOOL_NAMES, ...OPEN_AUTHORING_WRITE_TOOL_NAMES]) { expect(PLATFORM_PROVIDED_TOOL_NAMES.has(name), name).toBe(false); expect(PLATFORM_TOOL_FAMILY_PREFIXES.some((prefix) => name.startsWith(prefix)), name).toBe(false); } expect(PLATFORM_PROVIDED_TOOL_NAMES.has('list_metadata')).toBe(true); }); }); + +// --------------------------------------------------------------------------- +// The draft writes, and the publish verdict each answers with +// --------------------------------------------------------------------------- + +const FLOW_DRAFT = { name: 'lead_intake', label: 'Lead intake', type: 'record_change', nodes: [], edges: [] }; + +/** + * An admitted author's injection through the real domain, over `protocol` (the + * recording double by default). The fixture's user holds `admin_full_access`, + * which a single-posture resolution anchors as the platform operator; `posture` + * replaces that rung, as a walled deployment's resolution would not grant it. + */ +async function authorThroughDomain(opts: Parameters[1] & { posture?: string } = {}) { + const resolved = await oauthEnvelope(['metadata:write'], ADMIN); + const ec = opts.posture ? { ...resolved, posture: opts.posture } : resolved; + const served = await serve(ec, opts); + return { authoring: served.authoring!, served }; +} + +describe('save_metadata_draft saves a draft and answers with its publish verdict', () => { + it('saves through saveMetaItem as an mcp draft by the token\'s client, and the reply carries the verdict whole and the Studio routes', async () => { + const { authoring, served } = await authorThroughDomain(); + const saved = await call(authoring, 'save_metadata_draft', { type: 'flow', name: 'lead_intake', item: FLOW_DRAFT, package: 'com.acme.crm', ifMatch: 'v7' }); + + expect(saved.isError).toBe(false); + const save = served.protocolCalls.find((c: any) => c[0] === 'saveMetaItem') as any[]; + expect(save[1]).toEqual({ + type: 'flow', name: 'lead_intake', item: FLOW_DRAFT, packageId: 'com.acme.crm', + mode: 'draft', surface: 'mcp', client: { id: 'c1' }, writeFace: 'meta-dispatch', + // The languages the real envelope states (`userTextLocalesOf`). + parentVersion: 'v7', actor: 'u1', userTextLocales: ['en-US', 'en-US'], + }); + // The verdict is the protocol's judgement of the STORED draft at the saved address. + expect(served.protocolCalls.find((c: any) => c[0] === 'draftPublishJudgement')).toEqual( + ['draftPublishJudgement', { type: 'flow', name: 'lead_intake', packageId: 'com.acme.crm', userTextLocales: ['en-US', 'en-US'] }], + ); + expect(saved.body).toEqual({ + saved: { type: 'flow', name: 'lead_intake', package: 'com.acme.crm', state: 'draft', version: 'v8' }, + verdict: { publishable: false, refusals: [UNROUTABLE_ISSUE], advisories: [] }, + review: { + changes: '/studio/com.acme.crm/interfaces?changes=review', + item: '/studio/com.acme.crm/metadata/flow/lead_intake?review=1', + note: expect.any(String), + }, + }); + }); + + it('a plural type spelling is folded once: the save, the verdict, the discard and the review route name the canonical singular', async () => { + const { authoring, served } = await authorThroughDomain(); + const saved = await call(authoring, 'save_metadata_draft', { type: 'flows', name: 'lead_intake', item: FLOW_DRAFT, package: 'com.acme.crm' }); + await call(authoring, 'delete_metadata_draft', { type: 'flows', name: 'lead_intake', package: 'com.acme.crm' }); + const typesSent = served.protocolCalls + .filter((c: any) => ['saveMetaItem', 'draftPublishJudgement', 'deleteMetaItem'].includes(c[0])) + .map((c: any) => [c[0], c[1].type]); + expect(typesSent).toEqual([['saveMetaItem', 'flow'], ['draftPublishJudgement', 'flow'], ['deleteMetaItem', 'flow']]); + expect(saved.body.saved.type).toBe('flow'); + expect(saved.body.review.item).toBe('/studio/com.acme.crm/metadata/flow/lead_intake?review=1'); + }); + + it('a type the caller may not write is refused on the save and the discard before anything is written', async () => { + const { authoring, served } = await authorThroughDomain(); + for (const type of ['datasource', 'datasources']) { + const saved = await call(authoring, 'save_metadata_draft', { type, name: 'warehouse', item: { name: 'warehouse' }, package: 'com.acme.crm' }); + expect(saved.body.error, type).toMatchObject({ code: 'PERMISSION_DENIED', status: 403 }); + const discarded = await call(authoring, 'delete_metadata_draft', { type, name: 'warehouse', package: 'com.acme.crm' }); + expect(discarded.body.error, type).toMatchObject({ code: 'PERMISSION_DENIED', status: 403 }); + } + expect(served.protocolCalls.filter((c: any) => ['saveMetaItem', 'deleteMetaItem', 'draftPublishJudgement'].includes(c[0]))).toEqual([]); + + // The control: a human who holds the type's capability writes it. + const holder = [...ADMIN, 'manage_platform_settings']; + const ec = await oauthEnvelope(['metadata:write'], holder); + const allowed = await serve(ec, { systemPermissions: holder }); + expect((await call(allowed.authoring!, 'save_metadata_draft', { type: 'datasource', name: 'warehouse', item: { name: 'warehouse' }, package: 'com.acme.crm' })).isError).toBe(false); + expect((await call(allowed.authoring!, 'delete_metadata_draft', { type: 'datasource', name: 'warehouse', package: 'com.acme.crm' })).isError).toBe(false); + expect(allowed.protocolCalls.filter((c: any) => ['saveMetaItem', 'deleteMetaItem'].includes(c[0])).map((c: any) => [c[0], c[1].type])).toEqual( + [['saveMetaItem', 'datasource'], ['deleteMetaItem', 'datasource']], + ); + }); + + it('a save of a type the caller may not read lands, and its verdict is withheld rather than read', async () => { + const { authoring, served } = await authorThroughDomain(); + const saved = await call(authoring, 'save_metadata_draft', { type: 'external_catalog', name: 'warehouse_catalog', item: { name: 'warehouse_catalog' }, package: 'com.acme.crm' }); + expect(saved.isError).toBe(false); + expect(saved.body.saved).toMatchObject({ type: 'external_catalog', name: 'warehouse_catalog' }); + expect(saved.body.verdict).toBeNull(); + expect(saved.body.verdictWithheld).toMatchObject({ code: 'PERMISSION_DENIED', status: 403 }); + expect(served.protocolCalls.filter((c: any) => c[0] === 'draftPublishJudgement')).toEqual([]); + }); + + it('a save naming no package is refused 400 naming the writable packages, and nothing is written (seat ruling D4)', async () => { + const store = { + package: [ + { manifest: { id: 'com.acme.crm' }, writable: true }, + { manifest: { id: 'com.objectstack.platform' }, writable: false }, + ], + }; + const { authoring, served } = await authorThroughDomain({ store }); + const refused = await call(authoring, 'save_metadata_draft', { type: 'flow', name: 'lead_intake', item: FLOW_DRAFT }); + + expect(refused.isError).toBe(true); + expect(refused.body.error).toMatchObject({ code: 'VALIDATION_ERROR', status: 400 }); + expect(refused.body.error.message).toContain('com.acme.crm'); + expect(refused.body.error.message).not.toContain('com.objectstack.platform'); + expect(served.protocolCalls.filter((c: any) => c[0] === 'saveMetaItem')).toEqual([]); + }); + + it('under a walled tenancy posture the save is refused 403 before anything is written', async () => { + const { authoring, served } = await authorThroughDomain({ tenancy: { posture: 'isolated' }, posture: 'TENANT_ADMIN' }); + const refused = await call(authoring, 'save_metadata_draft', { type: 'flow', name: 'lead_intake', item: FLOW_DRAFT, package: 'com.acme.crm' }); + expect(refused.body.error).toMatchObject({ code: 'PERMISSION_DENIED', status: 403 }); + expect(served.protocolCalls.filter((c: any) => c[0] === 'saveMetaItem')).toEqual([]); + }); + + it('a verdict that cannot be read after the save landed is said beside the saved draft, never as a refused save', async () => { + const { protocol, calls } = fakeProtocol(); + protocol.draftPublishJudgement = async () => { throw Object.assign(new Error('No pending draft exists for flow/lead_intake.'), { code: 'NO_DRAFT', status: 404 }); }; + const { authoring } = await authorThroughDomain({ protocol }); + const saved = await call(authoring, 'save_metadata_draft', { type: 'flow', name: 'lead_intake', item: FLOW_DRAFT, package: 'com.acme.crm' }); + expect(saved.isError).toBe(false); + expect(saved.body.saved).toMatchObject({ type: 'flow', name: 'lead_intake', package: 'com.acme.crm' }); + expect(saved.body.verdict).toBeNull(); + expect(saved.body.verdictError).toMatchObject({ code: 'NO_DRAFT', status: 404 }); + expect(calls.filter((c: any) => c[0] === 'saveMetaItem')).toHaveLength(1); + }); + + it('a registry handed no writer writes nothing', async () => { + const { protocol, calls } = fakeProtocol(); + const registry = createOpenAuthoringRegistry({ admitted: true, userId: 'u1', getProtocol: async () => protocol, readGate: AUTHOR_READ_GATE }); + for (const [toolName, input] of [ + ['save_metadata_draft', { type: 'flow', name: 'lead_intake', item: FLOW_DRAFT, package: 'com.acme.crm' }], + ['delete_metadata_draft', { type: 'flow', name: 'lead_intake' }], + ] as const) { + const result = await registry.execute({ toolCallId: 't', toolName, input }, CONTEXT); + expect(JSON.parse(result.output.value).error, toolName).toMatchObject({ code: 'PERMISSION_DENIED', status: 403 }); + } + expect(calls).toEqual([]); + }); +}); + +describe('delete_metadata_draft discards a pending draft only', () => { + it('deletes the draft state, at the package named, attributed to the human', async () => { + const { authoring, served } = await authorThroughDomain(); + const discarded = await call(authoring, 'delete_metadata_draft', { type: 'flow', name: 'lead_intake', package: 'com.acme.crm' }); + expect(discarded.body).toEqual({ discarded: { type: 'flow', name: 'lead_intake', package: 'com.acme.crm' } }); + expect(served.protocolCalls.filter((c: any) => c[0] === 'deleteMetaItem')).toEqual( + [['deleteMetaItem', { type: 'flow', name: 'lead_intake', state: 'draft', packageId: 'com.acme.crm', actor: 'u1' }]], + ); + }); + + it('under a walled tenancy posture the discard is refused 403 before anything is deleted', async () => { + const { authoring, served } = await authorThroughDomain({ tenancy: { posture: 'isolated' }, posture: 'TENANT_ADMIN' }); + const refused = await call(authoring, 'delete_metadata_draft', { type: 'flow', name: 'lead_intake' }); + expect(refused.body.error).toMatchObject({ code: 'PERMISSION_DENIED', status: 403 }); + expect(served.protocolCalls.filter((c: any) => c[0] === 'deleteMetaItem')).toEqual([]); + }); +}); + +describe('list_drafts answers each draft with its publish verdict, told where the item gate admits the draft read', () => { + it('a draft the human may read carries its verdict; one the item gate refuses them is listed with the verdict withheld', async () => { + const store = { + dashboard: [{ name: 'finance_board', label: 'Finance', requiredPermissions: ['finance.access'], widgets: [] }], + }; + const { protocol, calls } = fakeProtocol(store); + protocol.listDrafts = async () => ({ + drafts: [ + { type: 'flow', name: 'lead_intake', label: 'Lead intake', packageId: 'com.acme.crm', updatedAt: null, updatedBy: null }, + { type: 'dashboard', name: 'finance_board', label: 'Finance', packageId: 'com.acme.crm', updatedAt: null, updatedBy: null }, + { type: 'datasource', name: 'warehouse', label: 'Warehouse', packageId: 'com.acme.crm', updatedAt: null, updatedBy: null }, + ], + } as any); + const { authoring } = await authorThroughDomain({ protocol }); + const listed = await call(authoring, 'list_drafts', {}); + + expect(listed.body.count).toBe(3); + const [flow, dashboard, typeRefused] = listed.body.drafts; + // A type the caller may not read: its body is not read and no verdict is told. + expect(typeRefused).toMatchObject({ type: 'datasource', name: 'warehouse', verdict: null, verdictWithheld: { code: 'PERMISSION_DENIED', status: 403 } }); + expect(calls.some((c: any) => c[1]?.type === 'datasource')).toBe(false); + // The list stays ungated, as /meta/_drafts: both drafts are listed. + expect(flow).toMatchObject({ type: 'flow', name: 'lead_intake', verdict: { publishable: false, refusals: [UNROUTABLE_ISSUE] } }); + expect(dashboard).toMatchObject({ type: 'dashboard', name: 'finance_board', verdict: null, verdictWithheld: { code: 'PERMISSION_DENIED', status: 403 } }); + }); +}); + +// --------------------------------------------------------------------------- +// Done when: the app-crm shape, end to end, on the real metadata protocol +// --------------------------------------------------------------------------- + +/** + * The card's done-when on the `examples/app-crm` shape (its `com.example.crm` + * code package and its `crm_opportunity` object, declared here: this + * package's tests read nothing outside it). A booted code package is + * read-only, so the author saves into a Studio-created base beside it, + * `com.example.crm_studio`, the writable package the D4 refusal would name. The metadata protocol is the real one over a + * real SQL store, the envelope is the real identity door's for an OAuth token + * with `metadata:write` alone, and the door is the real `/mcp` domain: the + * reply's finding is the publish gate's own, not a fixture's. + */ +describe('done when: an OAuth author saves an app-crm flow draft with no routable trigger and gets that finding in the same reply', () => { + let cleanup: Array<() => void> = []; + afterEach(() => { + for (const c of cleanup.reverse()) c(); + cleanup = []; + }); + + async function realProtocol() { + const dir = mkdtempSync(join(tmpdir(), 'os-34766-')); + 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' }, amount: { type: 'currency', label: 'Amount' } }, + } 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: STUDIO_BASE, 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; + } + + const STUDIO_BASE = 'com.example.crm_studio'; + + /** A record-triggered flow on the opportunity whose start node names no trigger. */ + const unroutable = { + name: 'crm_opportunity_followup', + label: 'Opportunity follow-up', + type: 'record_change', + nodes: [ + { id: 'start', type: 'start', label: 'Start', config: { objectName: 'crm_opportunity' } }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [{ id: 'e1', source: 'start', target: 'end' }], + }; + + it('the save answers flow-trigger-unroutable with its rule id, path and hint, and list_drafts lists the draft with the same verdict', async () => { + const protocol = await realProtocol(); + const { authoring } = await authorThroughDomain({ protocol }); + expect(authoring.registry.getAll().map((t) => t.name)).toEqual([...OPEN_AUTHORING_READ_TOOL_NAMES, ...OPEN_AUTHORING_WRITE_TOOL_NAMES]); + + // Seat ruling D4: a save naming no package is refused, naming the packages the + // protocol's own writability verdict admits (the base among them). + const unnamed = await call(authoring, 'save_metadata_draft', { type: 'flow', name: 'crm_opportunity_followup', item: unroutable }); + expect(unnamed.body.error).toMatchObject({ code: 'VALIDATION_ERROR', status: 400 }); + expect(unnamed.body.error.message).toContain(STUDIO_BASE); + expect((await call(authoring, 'list_drafts', {})).body.drafts).toEqual([]); + + const saved = await call(authoring, 'save_metadata_draft', { + type: 'flow', name: 'crm_opportunity_followup', item: unroutable, package: STUDIO_BASE, + }); + expect(saved.isError, JSON.stringify(saved.body)).toBe(false); + expect(saved.body.saved).toMatchObject({ type: 'flow', name: 'crm_opportunity_followup', package: STUDIO_BASE, state: 'draft' }); + const finding = saved.body.verdict.refusals.find((issue: any) => issue.rule === 'flow-trigger-unroutable'); + expect(finding, JSON.stringify(saved.body.verdict)).toBeDefined(); + expect(finding.path).toBe('flows[0].nodes[0].config.triggerType'); + expect(typeof finding.hint === 'string' && finding.hint.length > 0).toBe(true); + expect(saved.body.verdict.publishable).toBe(false); + expect(saved.body.review.changes).toBe(`/studio/${STUDIO_BASE}/interfaces?changes=review`); + + // The Studio Changes source: the package's pending drafts. + const listed = await call(authoring, 'list_drafts', { package: STUDIO_BASE }); + expect(listed.body.drafts.map((d: any) => [d.type, d.name, d.packageId])).toEqual([['flow', 'crm_opportunity_followup', STUDIO_BASE]]); + expect(listed.body.drafts[0].verdict).toEqual(saved.body.verdict); + + // Discarded, it leaves the list; there was no active item to touch. + expect((await call(authoring, 'delete_metadata_draft', { type: 'flow', name: 'crm_opportunity_followup', package: STUDIO_BASE })).isError).toBe(false); + expect((await call(authoring, 'list_drafts', { package: STUDIO_BASE })).body.drafts).toEqual([]); + }); + + it('list_drafts collects a package\'s publish closure once for all its drafts, and each verdict equals the draft judged alone', async () => { + const protocol = await realProtocol(); + const { authoring } = await authorThroughDomain({ protocol }); + const routed = structuredClone(unroutable); + (routed.nodes[0]!.config as Record).triggerType = 'record-after-create'; + const names = ['crm_opportunity_followup', 'crm_opportunity_followup_b', 'crm_opportunity_followup_c']; + for (const [i, name] of names.entries()) { + const item = { ...(i === 1 ? routed : unroutable), name }; + expect((await call(authoring, 'save_metadata_draft', { type: 'flow', name, item, package: STUDIO_BASE })).isError).toBe(false); + } + + const collect = vi.spyOn(protocol as any, 'collectBatchPendingDeclarations'); + const listed = await call(authoring, 'list_drafts', { package: STUDIO_BASE }); + expect(listed.body.count).toBe(3); + // Each strict draft read collects for the verdict it folds into its own + // `_diagnostics`; the door's judgements share one collection per package. + expect(collect).toHaveBeenCalledTimes(names.length + 1); + + // Each draft judged alone, one closure collection per call: the same verdict. + collect.mockClear(); + for (const entry of listed.body.drafts) { + const alone = await protocol.draftPublishJudgement!({ type: 'flow', name: entry.name, packageId: STUDIO_BASE }); + expect(entry.verdict, entry.name).toEqual({ publishable: alone.refusals.length === 0, refusals: alone.refusals, advisories: alone.advisories }); + } + expect(collect).toHaveBeenCalledTimes(3); + const unroutableOf = (d: any) => d.verdict.refusals.some((issue: any) => issue.rule === 'flow-trigger-unroutable'); + expect(listed.body.drafts.map((d: any) => [d.name, unroutableOf(d)]).sort()) + .toEqual([[names[0], true], [names[1], false], [names[2], true]]); + }); + + it('a save the schema refuses answers its structured findings beside the headline, and writes nothing', async () => { + const protocol = await realProtocol(); + const { authoring } = await authorThroughDomain({ protocol }); + const refused = await call(authoring, 'save_metadata_draft', { + type: 'flow', name: 'crm_opportunity_followup', item: { ...unroutable, bogus_key: 1 }, package: STUDIO_BASE, + }); + expect(refused.isError).toBe(true); + expect(refused.body.error).toMatchObject({ code: 'INVALID_METADATA', status: 422 }); + // The message is the face's headline; the finding that names the key is in `issues`. + expect(refused.body.error.message).not.toContain('bogus_key'); + expect(JSON.stringify(refused.body.error.issues)).toContain('bogus_key'); + expect((await call(authoring, 'list_drafts', {})).body.drafts).toEqual([]); + }); + + it('an inherited member\'s name as `type`, which the fold keeps as sent, is refused and writes nothing', async () => { + const protocol = await realProtocol(); + const { authoring } = await authorThroughDomain({ protocol }); + for (const type of ['constructor', 'toString']) { + // Refused, not written. The status is the protocol's answer for such a name, + // not pinned here: its own fold reads a plain object (Acceptance notes). + const saved = await call(authoring, 'save_metadata_draft', { type, name: 'crm_opportunity_followup', item: unroutable, package: STUDIO_BASE }); + expect(saved.isError, `${type}: ${JSON.stringify(saved.body)}`).toBe(true); + expect(saved.body.saved, type).toBeUndefined(); + const discarded = await call(authoring, 'delete_metadata_draft', { type, name: 'crm_opportunity_followup', package: STUDIO_BASE }); + expect(discarded.isError, `${type}: ${JSON.stringify(discarded.body)}`).toBe(true); + } + expect((await call(authoring, 'list_drafts', {})).body.drafts).toEqual([]); + }); +}); diff --git a/packages/runtime/src/domains/mcp-authoring.ts b/packages/runtime/src/domains/mcp-authoring.ts index 31253aca907..4797fb94e88 100644 --- a/packages/runtime/src/domains/mcp-authoring.ts +++ b/packages/runtime/src/domains/mcp-authoring.ts @@ -5,9 +5,10 @@ * `handleHttpRequest` as `authoring` (design `docs/design/mcp-local-first-door.md`, * Design A; rulings D2 A, D3 A and E3 of the local-first door's epic). * - * This first half carries the registry, its admission and the three read - * tools. The draft save and discard tools, and the publish verdict a save - * answers with, join it later; until then nothing here writes. + * Five tools: three reads (`list_metadata_items`, `get_metadata_item`, + * `list_drafts`) and two draft writes (`save_metadata_draft`, + * `delete_metadata_draft`). No tool publishes and none takes a `force` (D2 A): + * a person reviews and publishes the drafts in Studio. * * ## Who is admitted (seat ruling D1 A) * @@ -84,18 +85,46 @@ * - A gate that cannot evaluate (a books or doc read that throws, a security * service that cannot resolve holdings) refuses: the read answers that * fault, never the item (ADR-0049). - * - `list_drafts` runs no item gate, as `/meta/_drafts` runs none for this - * same caller: a draft row carries the item's identity and its own `label`, - * no body for a gate to judge. + * - `list_drafts` runs no item gate on its rows, as `/meta/_drafts` runs none + * for this same caller: a draft row carries the item's identity and its own + * `label`, no body for a gate to judge (each row's verdict is gated, below). * - * The walled refusal (`walledCatalogWriteVerdict`, ADR-0131 D3/D12) gates - * metadata WRITES and no `/meta` read; it joins this door with the save tool. + * ## What the writes do (E3: the save answers with the publish verdict) + * + * - `save_metadata_draft` saves through `saveMetaItem` with `mode: 'draft'`, + * `surface: 'mcp'` and the token's OAuth client as `client`, attributed to + * the human (`actor`). A draft save runs the type's schema parse and no + * authoring rule, so the reply carries what a publish would answer: the + * protocol's public `draftPublishJudgement` on the stored draft, every + * finding whole (rule id, path, message, hint, severity), and the Studio + * routes a person reviews it on. `package` is required (seat ruling D4): + * Studio's Changes review is per package, and a save naming none is + * refused with the writable packages named. A judgement that fails after + * the save landed is said beside the saved identity, never as a refused + * save. + * - `delete_metadata_draft` discards a pending draft through `deleteMetaItem` + * with `state: 'draft'`, never an active item. + * - Both ask the `/meta` type-level write admission (`metaTypeWriteRefusal`, + * the save as `PUT`, the discard as `DELETE`) with the human as the caller, + * then the walled refusal (`walledCatalogWriteVerdict`, ADR-0131 D3/D12), + * before anything is written, as every `/meta` write door does, on the + * posture this transport reads (`readEffectiveTenancyPosture`). The + * authoring admission (D1) alone does not cover a type whose own write + * door requires more. + * - A verdict is a read of the stored draft's body, so the save's verdict + * and each listed draft's verdict are told only where the type-level read + * admission admits the human; elsewhere the reply says it was withheld. + * - `list_drafts` stays ungated as a list (as `/meta/_drafts`), and each + * entry now carries its publish verdict. The verdict is read off the + * draft's body, so it is told only where the `/meta` item gate admits the + * strict draft read for this human; elsewhere the entry says it was + * withheld and why. * * ## The names (seat ruling D3 A) * * The design table's `list_metadata` is already a hosted platform tool * (`PLATFORM_TOOLS_BY_PACKAGE` in `@objectstack/spec/system`), so the two item - * reads are `list_metadata_items` and `get_metadata_item`. None of the three + * reads are `list_metadata_items` and `get_metadata_item`. None of the five * names is an MCP native tool: the SDK refuses a duplicate registration by * throwing, and the request would fail with it. * @@ -107,12 +136,13 @@ * and their names never meet. */ -import { resolveUserAuthzGrants } from '@objectstack/core'; -import { metaWriteCapabilityVerdict } from '@objectstack/metadata-core'; +import { resolveUserAuthzGrants, userTextLocalesOf } from '@objectstack/core'; +import { metaWriteCapabilityVerdict, walledCatalogWriteVerdict } from '@objectstack/metadata-core'; import { createMetaItemReadGate, createMetaListReadGate, metaTypeReadRefusal, + metaTypeWriteRefusal, refuseUnknownMetaListType, STORED_VERSION_DOOR_POLICY, type MetaItemReadGateSources, @@ -120,14 +150,18 @@ import { } from '@objectstack/rest'; import { MCP_OAUTH_SCOPE_METADATA_WRITE } from '@objectstack/spec/ai'; import { canonicalMetaUrlType } from '@objectstack/spec/shared'; -import type { ErrorCode, ListDraftsResponse, MetadataProtocol } from '@objectstack/spec/api'; +import type { ErrorCode, ListDraftsResponse, MetadataProtocol, RuntimeAuthoringIssue } from '@objectstack/spec/api'; import type { AIToolDefinition } from '@objectstack/spec/contracts'; import type { HttpProtocolContext } from '../http-dispatcher.js'; import type { DomainHandlerDeps } from '../domain-handler-registry.js'; +import { readEffectiveTenancyPosture } from './activation-gate.js'; /** The read tools' names, in the order the registry lists them. */ export const OPEN_AUTHORING_READ_TOOL_NAMES = ['list_metadata_items', 'get_metadata_item', 'list_drafts'] as const; +/** The draft write tools' names, listed after the reads. */ +export const OPEN_AUTHORING_WRITE_TOOL_NAMES = ['save_metadata_draft', 'delete_metadata_draft'] as const; + const PERMISSION_DENIED: ErrorCode = 'PERMISSION_DENIED'; /** A malformed argument this door judges itself; a protocol refusal keeps its own code. */ const VALIDATION_ERROR: ErrorCode = 'VALIDATION_ERROR'; @@ -201,8 +235,9 @@ const READ_TOOLS: readonly AIToolDefinition[] = Object.freeze([ name: 'list_drafts', description: 'List the pending metadata drafts in this environment: what was saved as a draft and is not ' - + 'published yet. A person reviews and publishes drafts in Studio. Pass `package` to list one ' - + 'package\'s drafts.', + + 'published yet. A person reviews and publishes drafts in Studio. Each draft carries its publish ' + + 'verdict: `verdict.refusals` lists what a publish would refuse it on (rule id, path, hint), empty ' + + 'when it would publish. Pass `package` to list one package\'s drafts.', parameters: { type: 'object', properties: { @@ -213,11 +248,93 @@ const READ_TOOLS: readonly AIToolDefinition[] = Object.freeze([ }, ]); -/** The protocol reads this door makes, named structurally (a host may fill the slot partially). */ -export type OpenAuthoringProtocol = Partial> & { +/** + * The two draft write tools. `package` is required (seat ruling D4) and is + * judged by the registry rather than by the input schema's `required`, so a + * save naming none is answered with the packages it may name instead of the + * schema validator's bare refusal. + */ +const WRITE_TOOLS: readonly AIToolDefinition[] = Object.freeze([ + { + name: 'save_metadata_draft', + description: + 'Save one metadata item as a DRAFT in a package. Nothing is published: a person reviews and ' + + 'publishes drafts in Studio, and this server has no publish tool. The reply answers what a publish ' + + 'would say about the saved draft: `verdict.refusals` lists every rule the publish would refuse it ' + + 'on, each with its rule id, the path in the item and a `hint` (the next step); fix the item and ' + + 'save again until it is empty. `verdict.advisories` are findings a publish still returns. `review` ' + + 'names the Studio routes where the draft is reviewed. Saving again replaces the pending draft.', + parameters: { + type: 'object', + properties: { + type: TYPE_PARAMETER, + name: { type: 'string', minLength: 1, description: 'The item\'s machine name.' }, + item: { type: 'object', description: 'The item\'s full definition, as `get_metadata_item` reads it.' }, + package: { + type: 'string', + minLength: 1, + description: 'Required: the id of the package the draft is saved into. Studio reviews drafts per package; a save without one is refused with the writable packages named.', + }, + ifMatch: { + type: 'string', + minLength: 1, + description: 'Optional: the `version` a read or a save answered. The save is refused if the draft changed since.', + }, + }, + required: ['type', 'name', 'item'], + additionalProperties: false, + }, + }, + { + name: 'delete_metadata_draft', + description: + 'Discard one pending metadata draft. The published version, if any, is not touched. Pass ' + + '`package` to discard that package\'s draft of the item.', + parameters: { + type: 'object', + properties: { + type: TYPE_PARAMETER, + name: { type: 'string', minLength: 1, description: 'The item\'s machine name.' }, + package: { type: 'string', minLength: 1, description: 'The id of the package whose draft to discard.' }, + }, + required: ['type', 'name'], + additionalProperties: false, + }, + }, +]); + +/** The publish judgement of a stored draft (`ObjectStackProtocolImplementation#draftPublishJudgement`). */ +export interface OpenAuthoringDraftJudgement { + refusals: RuntimeAuthoringIssue[]; + advisories: RuntimeAuthoringIssue[]; +} + +/** The protocol calls this door makes, named structurally (a host may fill the slot partially). */ +export type OpenAuthoringProtocol = Partial> & { listDrafts?(request: { packageId?: string; type?: string }): Promise; + /** The metadata protocol's public draft verdict; with no `body`, it judges the stored draft at the address. */ + draftPublishJudgement?(draft: { + type: string; name: string; packageId: string | null; member?: string; + userTextLocales?: readonly (string | undefined)[]; + /** One map per pass: each package's publish closure is collected once, on its first draft. */ + packageClosures?: Map>; + }): Promise; }; +/** + * What the write tools need beyond the protocol, built per request by + * {@link resolveOpenAuthoringInjection}; a registry handed none refuses every + * write (fail closed). + */ +export interface OpenAuthoringWriter { + /** The OAuth client the token was issued to, stated on the save as its `client`. */ + clientId?: string; + /** The languages the verdict's user sentences are composed in (`userTextLocalesOf`). */ + userTextLocales: string[]; + /** The walled refusal for a write of `type` (`walledCatalogWriteVerdict`). */ + writeVerdict(type: string): Promise<{ allowed: true } | { allowed: false; code: ErrorCode; message: string; status: number }>; +} + /** * The `/meta` read gates' ports for one protocol, with the admitted human as * the caller. Built by {@link resolveOpenAuthoringInjection}; a registry @@ -291,7 +408,7 @@ export async function resolveOpenAuthoringInjection( admitted: reader !== undefined, userId, getProtocol: async () => (await deps.resolveService(context, 'protocol', context.environmentId)) as OpenAuthoringProtocol | undefined, - ...(reader ? { readGate: openReadGateSources(deps, context, reader) } : {}), + ...(reader ? { readGate: openReadGateSources(deps, context, reader), writer: openWriter(deps, context, clientId) } : {}), logger: deps.logger, }), principal: { @@ -353,6 +470,36 @@ async function resolveHumanReader( } } +/** + * The write tools' per-request inputs. The walled refusal is the one every + * `/meta` write door asks (`walledCatalogWriteVerdict`), on the posture this + * transport reads; a posture that cannot be read refuses the write `503`, + * never a permit. The caller's posture rung is the request envelope's, as the + * `/meta` doors and the MCP `import_object` tool read it. + */ +function openWriter(deps: DomainHandlerDeps, context: HttpProtocolContext, clientId: string | undefined): OpenAuthoringWriter { + const ec: any = context.executionContext; + return { + ...(clientId ? { clientId } : {}), + userTextLocales: userTextLocalesOf(ec), + async writeVerdict(type) { + let tenancyPosture: Awaited>; + try { + tenancyPosture = await readEffectiveTenancyPosture(deps, context); + } catch { + return { + allowed: false, + code: SERVICE_UNAVAILABLE, + message: 'This environment\'s tenancy posture could not be read, so no metadata is written. Nothing was saved or discarded; try again.', + status: 503, + }; + } + const walled = walledCatalogWriteVerdict({ type, tenancyPosture, isSystem: ec?.isSystem === true, callerPosture: ec?.posture }); + return walled.allowed ? { allowed: true } : { allowed: false, code: PERMISSION_DENIED, message: walled.message, status: 403 }; + }, + }; +} + /** Where the app gate's nav-servability prune log records what it has already said, for this door. */ const NAV_PRUNE_LOGGED = new Set(); @@ -404,11 +551,13 @@ export function createOpenAuthoringRegistry(opts: { getProtocol: () => Promise; /** The `/meta` read gates' ports; without them every read is refused. */ readGate?: OpenAuthoringReadGateSources; + /** The write tools' inputs; without them every write is refused. */ + writer?: OpenAuthoringWriter; logger?: { warn?: (...args: unknown[]) => void }; }): OpenAuthoringRegistry { - const { admitted, userId, getProtocol, readGate } = opts; + const { admitted, userId, getProtocol, readGate, writer } = opts; return { - getAll: () => (admitted ? [...READ_TOOLS] : []), + getAll: () => (admitted ? [...READ_TOOLS, ...WRITE_TOOLS] : []), async execute(toolCall, context) { const answer = (body: unknown): OpenAuthoringToolResult => ({ type: 'tool-result', @@ -416,8 +565,8 @@ export function createOpenAuthoringRegistry(opts: { toolName: toolCall.toolName, output: { type: 'text', value: JSON.stringify(body, null, 2) }, }); - const refuse = (code: ErrorCode, message: string, status: number): OpenAuthoringToolResult => ({ - ...answer({ error: { code, message, status } }), + const refuse = (code: ErrorCode, message: string, status: number, issues?: unknown[]): OpenAuthoringToolResult => ({ + ...answer({ error: { code, message, status, ...(issues ? { issues } : {}) } }), isError: true, }); @@ -442,6 +591,9 @@ export function createOpenAuthoringRegistry(opts: { if (typeof readGate !== 'function') { return refuse(PERMISSION_DENIED, 'The authoring tools cannot judge what your account may read on this request.', 403); } + /** The `/meta` item gate, as the doors that serve a stored version for authoring run it. */ + const itemGate = (type: string, name: string, stored: unknown) => + createMetaItemReadGate(readGate(protocol ?? {}), type, name, [stored], STORED_VERSION_DOOR_POLICY)(stored); try { switch (toolCall.toolName) { case 'list_metadata_items': { @@ -489,7 +641,7 @@ export function createOpenAuthoringRegistry(opts: { // The `/meta` item gate, as the doors that serve a stored version // for authoring run it. `absent` is the not-found answer itself // (an unpublished app stays unobservable, ADR-0045 §3). - const verdict = await createMetaItemReadGate(readGate(protocol), type, name, [stored], STORED_VERSION_DOOR_POLICY)(stored); + const verdict = await itemGate(type, name, stored); if (verdict.kind === 'refuse') { const { refusal } = verdict; if (refusal.reason === 'absent') return notFound(); @@ -511,9 +663,109 @@ export function createOpenAuthoringRegistry(opts: { if (input.package !== undefined && !pkg) return refuse(VALIDATION_ERROR, '`package` is a package id.', 400); // ADR-0131 D6: no organization, as the `/meta` drafts list; every // draft is saved environment-wide. + if (typeof protocol.draftPublishJudgement !== 'function' || typeof protocol.getMetaItem !== 'function') { + return unavailable(); + } const listed = await protocol.listDrafts(pkg ? { packageId: pkg } : {}); const drafts = Array.isArray(listed?.drafts) ? listed.drafts : []; - return answer({ count: drafts.length, drafts }); + // The list itself runs no item gate, as `/meta/_drafts` runs + // none: a row is the item's identity and its own label. Each + // verdict is read off the draft's BODY, so it is told only where + // the item gate admits the strict draft read for this human. + // Cost per draft: that strict read, which the item gate needs + // (it judges the served body, and the read folds its own verdict + // into `_diagnostics` as every `/meta` draft read does), and the + // judgement, which reads the row as stored (the bytes the publish + // judges; the served copy is not) and answers each finding whole. + // The closure a draft is judged against is its package's alone, + // so one map collects it once per package for the judgements. + const packageClosures = new Map>(); + const judged = []; + for (const draft of drafts) judged.push({ ...draft, ...(await gatedDraftVerdict(protocol, draft, packageClosures)) }); + return answer({ count: judged.length, drafts: judged }); + } + case 'save_metadata_draft': { + if (typeof protocol?.saveMetaItem !== 'function' || typeof protocol.draftPublishJudgement !== 'function') { + return unavailable(); + } + if (!writer) return refuse(PERMISSION_DENIED, 'The authoring tools cannot write on this request.', 403); + // Folded once to the canonical singular, as the protocol folds a + // plural spelling, so the walled verdict, the save, the verdict and + // the review route all name the type the protocol writes. + const type = canonicalTypeOf(input.type); + const name = requiredString(input.name); + if (!type || !name) return refuse(VALIDATION_ERROR, 'Name the item as `type` and `name`.', 400); + const item = input.item; + if (!item || typeof item !== 'object' || Array.isArray(item)) { + return refuse(VALIDATION_ERROR, 'Send the item\'s full definition as `item`, an object.', 400); + } + const pkg = requiredString(input.package); + // Seat ruling D4: Studio's Changes review is per package. + if (!pkg) return refuse(VALIDATION_ERROR, await packageRequiredMessage(protocol), 400); + const ifMatch = input.ifMatch === undefined ? undefined : requiredString(input.ifMatch); + if (input.ifMatch !== undefined && !ifMatch) { + return refuse(VALIDATION_ERROR, '`ifMatch` is the `version` a read or a save answered.', 400); + } + // The `/meta` type-level write admission, before anything is written. + const typeWriteRefused = await typeAdmission('PUT', type); + if (typeWriteRefused) return refuse(typeWriteRefused.code, typeWriteRefused.message, typeWriteRefused.status); + const walled = await writer.writeVerdict(type); + if (!walled.allowed) return refuse(walled.code, walled.message, walled.status); + // Built field by field: `item` is data, never a channel, so no + // `force`, `mode` or `writeFace` rides in through it. + const saved = await protocol.saveMetaItem({ + type, + name, + item, + packageId: pkg, + mode: 'draft', + surface: 'mcp', + ...(writer.clientId ? { client: { id: writer.clientId } } : {}), + // The face of a door with no `force` and a structured issues channel. + writeFace: 'meta-dispatch', + ...(ifMatch ? { parentVersion: ifMatch } : {}), + actor: userId, + userTextLocales: writer.userTextLocales, + }); + const identity = { + type, + name, + package: pkg, + state: (saved as { state?: unknown } | undefined)?.state ?? 'draft', + ...((saved as { version?: unknown } | undefined)?.version !== undefined ? { version: (saved as { version?: unknown }).version } : {}), + }; + const review = reviewRoutes(pkg, type, name); + // The verdict is a read of the stored draft: told only where the + // `/meta` type-level read admission admits this human. + const typeReadRefused = await typeAdmission('read', type); + if (typeReadRefused) { + return answer({ saved: identity, verdict: null, verdictWithheld: typeReadRefused, review }); + } + let judgement: OpenAuthoringDraftJudgement; + try { + judgement = await protocol.draftPublishJudgement({ type, name, packageId: pkg, userTextLocales: writer.userTextLocales }); + } catch (error) { + // The draft is saved; only its verdict is missing, and the + // reply says so rather than reading as a refused save. + return answer({ saved: identity, verdict: null, verdictError: verdictErrorOf(error), review }); + } + return answer({ saved: identity, verdict: verdictOf(judgement), review }); + } + case 'delete_metadata_draft': { + if (typeof protocol?.deleteMetaItem !== 'function') return unavailable(); + if (!writer) return refuse(PERMISSION_DENIED, 'The authoring tools cannot write on this request.', 403); + const type = canonicalTypeOf(input.type); + const name = requiredString(input.name); + if (!type || !name) return refuse(VALIDATION_ERROR, 'Name the draft as `type` and `name`.', 400); + const pkg = input.package === undefined ? undefined : requiredString(input.package); + if (input.package !== undefined && !pkg) return refuse(VALIDATION_ERROR, '`package` is a package id.', 400); + const typeWriteRefused = await typeAdmission('DELETE', type); + if (typeWriteRefused) return refuse(typeWriteRefused.code, typeWriteRefused.message, typeWriteRefused.status); + const walled = await writer.writeVerdict(type); + if (!walled.allowed) return refuse(walled.code, walled.message, walled.status); + // `state: 'draft'`: the pending draft only, never an active item. + await protocol.deleteMetaItem({ type, name, state: 'draft', ...(pkg ? { packageId: pkg } : {}), actor: userId }); + return answer({ discarded: { type, name, package: pkg ?? null } }); } default: return refuse(VALIDATION_ERROR, `'${toolCall.toolName}' is not one of this registry's tools.`, 400); @@ -530,12 +782,89 @@ export function createOpenAuthoringRegistry(opts: { * refuses it, whether or not the named item exists. */ async function typeReadRefusal(type: string): Promise { - const refusal = metaTypeReadRefusal('GET', type, await readGate!(protocol ?? {}).resolveCaller()); + const refusal = await typeAdmission('read', type); return refusal ? refuse(refusal.code, refusal.message, refusal.status) : undefined; } + /** + * The `/meta` type-level admissions, read or write, with the human as + * the caller: `metaTypeReadRefusal` for a read of a typed item (a draft's + * body, the verdict read off it), `metaTypeWriteRefusal` for a draft save + * (`PUT`) or discard (`DELETE`), as the `/meta` entry asks them of the + * same verbs. `undefined` admits. + */ + async function typeAdmission( + kind: 'read' | 'PUT' | 'DELETE', + type: string, + ): Promise<{ code: ErrorCode; message: string; status: number } | undefined> { + const caller = await readGate!(protocol ?? {}).resolveCaller(); + return kind === 'read' ? metaTypeReadRefusal('GET', type, caller) : metaTypeWriteRefusal(kind, type, caller); + } + function unavailable(): OpenAuthoringToolResult { - return refuse(SERVICE_UNAVAILABLE, 'This environment serves no metadata protocol to read from.', 503); + return refuse(SERVICE_UNAVAILABLE, 'This environment serves no metadata protocol this tool can use.', 503); + } + + /** One draft's verdict, told where the item gate admits this human's strict draft read. */ + async function gatedDraftVerdict( + p: OpenAuthoringProtocol, + listed: { type: string; name: string; packageId?: string | null; member?: string }, + packageClosures: Map>, + ): Promise<{ verdict: ReturnType | null; verdictWithheld?: unknown; verdictError?: unknown }> { + // The gate and the judgement read the canonical singular, folded by + // the door's one helper; a row with no type keeps the row's own. + const draft = { ...listed, type: canonicalTypeOf(listed.type) ?? listed.type }; + try { + // A type this human may not read: neither its body nor a verdict read off it. + const typeRefused = await typeAdmission('read', draft.type); + if (typeRefused) return { verdict: null, verdictWithheld: typeRefused }; + // A package-unbound draft is read without a package: the strict + // draft read's own address resolution then names it. + const read = await p.getMetaItem!({ + type: draft.type, + name: draft.name, + state: 'draft', + ...(draft.packageId ? { packageId: draft.packageId } : {}), + ...(draft.member !== undefined ? { member: draft.member } : {}), + } as Parameters>[0]); + if (read?.item === undefined || read.item === null) { + return { verdict: null, verdictWithheld: { code: RESOURCE_NOT_FOUND, message: `No '${draft.type}' draft named '${draft.name}' is readable here.`, status: 404 } }; + } + const gate = await itemGate(draft.type, draft.name, read.item); + if (gate.kind === 'refuse') { + const { refusal } = gate; + return { + verdict: null, + verdictWithheld: refusal.reason === 'absent' + ? { code: RESOURCE_NOT_FOUND, message: `No '${draft.type}' draft named '${draft.name}' is readable here.`, status: 404 } + : { code: refusal.code, message: refusal.message, status: refusal.status }, + }; + } + const judgement = await p.draftPublishJudgement!({ + type: draft.type, + name: draft.name, + packageId: draft.packageId ?? null, + ...(draft.member !== undefined ? { member: draft.member } : {}), + ...(writer ? { userTextLocales: writer.userTextLocales } : {}), + packageClosures, + }); + return { verdict: verdictOf(judgement) }; + } catch (error) { + return { verdict: null, verdictError: verdictErrorOf(error) }; + } + } + + /** A verdict that could not be reached: a coded refusal keeps its code; a fault is named without its text. */ + function verdictErrorOf(error: unknown): { code: string; message: string; status: number } { + const code = (error as { code?: unknown } | null)?.code; + const status = (error as { status?: unknown } | null)?.status; + if (typeof code === 'string' && code.length > 0 && typeof status === 'number' && status < 500) { + return { code, message: error instanceof Error ? error.message : String(error), status }; + } + (opts.logger ?? console).warn?.(`[MCP] ${toolCall.toolName}: the publish verdict could not be read`, { + error: error instanceof Error ? error.message : String(error), + }); + return { code: INTERNAL_ERROR, message: 'The publish verdict could not be read.', status: 500 }; } /** @@ -547,17 +876,81 @@ export function createOpenAuthoringRegistry(opts: { const code = (error as { code?: unknown } | null)?.code; const status = (error as { status?: unknown } | null)?.status; if (typeof code === 'string' && code.length > 0 && typeof status === 'number' && status < 500) { - return refuse(code as ErrorCode, error instanceof Error ? error.message : String(error), status); + // The structured findings travel beside the message: the save + // states the `meta-dispatch` face, whose spec-validation refusal + // trims its message to a headline because the face carries + // `issues[]` (`specValidationFindings`), so they are relayed here. + const issues = (error as { issues?: unknown } | null)?.issues; + return refuse(code as ErrorCode, error instanceof Error ? error.message : String(error), status, Array.isArray(issues) ? issues : undefined); } (opts.logger ?? console).warn?.(`[MCP] ${toolCall.toolName} failed`, { error: error instanceof Error ? error.message : String(error), }); - return refuse(INTERNAL_ERROR, 'Reading the metadata failed.', 500); + return refuse( + INTERNAL_ERROR, + toolCall.toolName === 'save_metadata_draft' ? 'Saving the draft failed.' + : toolCall.toolName === 'delete_metadata_draft' ? 'Discarding the draft failed.' + : 'Reading the metadata failed.', + 500, + ); } }, }; } +/** A judgement as the replies carry it: `publishable` is "no refusal". */ +function verdictOf(judgement: OpenAuthoringDraftJudgement): { + publishable: boolean; + refusals: RuntimeAuthoringIssue[]; + advisories: RuntimeAuthoringIssue[]; +} { + const refusals = Array.isArray(judgement?.refusals) ? judgement.refusals : []; + const advisories = Array.isArray(judgement?.advisories) ? judgement.advisories : []; + return { publishable: refusals.length === 0, refusals, advisories }; +} + +/** + * Where a person reviews the draft, as Console routes: the package's Changes + * drawer (`?changes=review` on its Interfaces pillar, `studioChangesLink.ts`) + * and the item's draft review on Studio's metadata area (`?review=1`). + */ +function reviewRoutes(packageId: string, type: string, name: string): { changes: string; item: string; note: string } { + const pkg = encodeURIComponent(packageId); + return { + changes: `/studio/${pkg}/interfaces?changes=review`, + item: `/studio/${pkg}/metadata/${encodeURIComponent(type)}/${encodeURIComponent(name)}?review=1`, + note: 'Console routes. A person reviews and publishes the draft there; this server cannot publish.', + }; +} + +/** How many writable package ids the missing-package refusal names. */ +const NAMED_PACKAGES_CAP = 20; + +/** + * The refusal of a save naming no package (seat ruling D4), naming the + * packages it may name: the protocol's own writability verdict on each + * installed package (`getMetaItems({ type: 'package' })`'s `writable`). + */ +async function packageRequiredMessage(protocol: OpenAuthoringProtocol): Promise { + const head = 'Name the package to save the draft into as `package`: Studio reviews and publishes drafts per package. Nothing was saved.'; + let writable: string[] | undefined; + try { + const listed = typeof protocol.getMetaItems === 'function' ? await protocol.getMetaItems({ type: 'package' }) : undefined; + if (listed && Array.isArray(listed.items)) { + writable = listed.items + .filter((p: any) => p?.writable === true) + .map((p: any) => p?.manifest?.id ?? p?.id) + .filter((id: unknown): id is string => typeof id === 'string' && id.length > 0); + } + } catch { + writable = undefined; + } + if (writable === undefined) return `${head} The packages could not be listed on this request; list them with list_metadata_items, type "package".`; + if (writable.length === 0) return `${head} No package in this environment is writable: create one in Studio first.`; + const named = writable.slice(0, NAMED_PACKAGES_CAP).join(', '); + return `${head} Writable packages here: ${named}${writable.length > NAMED_PACKAGES_CAP ? `, and ${writable.length - NAMED_PACKAGES_CAP} more` : ''}.`; +} + /** * A `type` argument folded to its canonical singular (`dashboards` → `dashboard`), * or `undefined` when absent: the door's one fold, applied once at its diff --git a/scripts/check-durability-degradation-log-level.mjs b/scripts/check-durability-degradation-log-level.mjs index 0b211c77411..da91f59ffa7 100644 --- a/scripts/check-durability-degradation-log-level.mjs +++ b/scripts/check-durability-degradation-log-level.mjs @@ -636,6 +636,20 @@ const FAILURE_PROPAGATION_SITES = new Map([ + "(#22985); `schema-migration-plugins.test.ts` pins the refusal note and the failed count.", }, ], + [ + 'packages/runtime/src/domains/mcp-authoring.ts::execute', + { + callees: [['refusalFromThrown', 'return']], + why: + "`refusalFromThrown()` is the open draft door's tool-call refusal: it builds the MCP tool result " + + 'with `isError: true` and an ADR-0112 `{ code, message, status }` envelope FROM the caught error, ' + + 'keeping a coded 4xx refusal whole and answering any other throw `500 INTERNAL_ERROR`. The tool ' + + 'switch\'s outer catch returns it on its only path, so the agent that asked for the draft save is ' + + 'told, in the same reply, that the draft did not land. Scoped to this one function because the ' + + 'name is a closure local to it (#34766); `mcp-authoring.test.ts` pins the coded refusal and the ' + + 'uncoded fault answered without its text.', + }, + ], ]); // ─────────────────────────────────────────────────────────────────────────────