diff --git a/.changeset/37983-knowledge-source-save-needs-the-service.md b/.changeset/37983-knowledge-source-save-needs-the-service.md index 4e3330d2b5c..03f252a8d2d 100644 --- a/.changeset/37983-knowledge-source-save-needs-the-service.md +++ b/.changeset/37983-knowledge-source-save-needs-the-service.md @@ -23,4 +23,4 @@ Unchanged: the engine's own writes (a package install, a seed, a migration) are ## FROM → TO -- A deployment whose stack does not declare `requires: ['knowledge']`, where authors save knowledge sources → add `requires: ['knowledge']` to the stack, restart, then save the source. +- A deployment whose stack neither declares `requires: ['knowledge']` nor ships a `knowledgeSources` entry, where authors save knowledge sources → add `requires: ['knowledge']` to the stack, restart, then save the source. diff --git a/.changeset/38058-knowledge-save-refusal-scope-miss-and-duplicate-wording.md b/.changeset/38058-knowledge-save-refusal-scope-miss-and-duplicate-wording.md new file mode 100644 index 00000000000..738b31de13c --- /dev/null +++ b/.changeset/38058-knowledge-save-refusal-scope-miss-and-duplicate-wording.md @@ -0,0 +1,14 @@ +--- +'@objectstack/metadata-core': patch +'@objectstack/runtime': patch +'@objectstack/spec': patch +--- + +fix(runtime): a knowledge source save refused for a scoped-factory miss says so, and the package duplicate words its remedy for its caller + +Clause-②: yes (widening) — `@objectstack/metadata-core` adds `knowledgeServiceNotInScope`, `KnowledgeServiceNotInScope`, `KnowledgeSourceSaveDoor` and the optional `door` input on `authoredKnowledgeSourceRefusal`; `@objectstack/runtime`'s exported `DomainHandlerDeps` adds the optional `classifyServiceOrLoud`, which makes `ClassifiedServiceLookup` reachable +Metadata-protocol: none + +- **`@objectstack/metadata-core`.** `authoredKnowledgeSourceRefusal` takes an optional `door` (`'save'`, the default, or `'duplicate'`). With `'duplicate'` each refusal it composes tells the caller to duplicate the package again, and does not say "Nothing was written". A door's knowledge lookup can now answer `knowledgeServiceNotInScope(scopeId)` when a `knowledge` registration serves no instance in the request's environment, a host's scoped factory for example. That save is refused `503 SERVICE_UNAVAILABLE` with its own sentence, which names the environment and does not say the deployment runs no knowledge service or point to the stack's `requires`. The `/meta` save's sentences are unchanged. +- **`@objectstack/runtime`.** The dispatcher's `/meta` save, the MCP `save_metadata_draft` tool and the package duplicate now tell a scoped-factory miss apart from a deployment with no knowledge service, through the new optional `DomainHandlerDeps.classifyServiceOrLoud`. A deps without that member answers both misses as before. The duplicate door's refusal now says once that nothing was copied, and tells the caller to duplicate the package again. The platform's own `KnowledgeServicePlugin` registers a plain instance, so its path is unchanged. +- **`@objectstack/spec`.** The upgrade-guide entry `knowledge-source-save-refused-without-knowledge-service` now names only a deployment whose stack neither declares `requires: ['knowledge']` nor ships a `knowledgeSources` entry. A stack that ships a source already mounts the service. diff --git a/packages/metadata-core/src/knowledge-source-save-admission.test.ts b/packages/metadata-core/src/knowledge-source-save-admission.test.ts index 6bac06d156f..496e30fa6e0 100644 --- a/packages/metadata-core/src/knowledge-source-save-admission.test.ts +++ b/packages/metadata-core/src/knowledge-source-save-admission.test.ts @@ -10,7 +10,7 @@ */ import { describe, it, expect, vi } from 'vitest'; -import { authoredKnowledgeSourceRefusal, KNOWLEDGE_SOURCE_ADMISSION_SERVICE } from './knowledge-source-save-admission.js'; +import { authoredKnowledgeSourceRefusal, knowledgeServiceNotInScope, KNOWLEDGE_SOURCE_ADMISSION_SERVICE } from './knowledge-source-save-admission.js'; const ITEM = { name: 'faq', label: 'FAQ', adapter: 'memory', source: { kind: 'object', object: 'article', content: ['body'] } }; const AUTHOR = { userId: 'u_author', systemPermissions: ['manage_metadata', 'manage_knowledge_sources'] }; @@ -89,6 +89,60 @@ describe('authoredKnowledgeSourceRefusal — source admission at save', () => { expect(thrown?.message).toContain('registry unavailable'); }); + /** + * A registration that serves no instance in the request's scope (a host's + * scoped factory): the deployment does run a knowledge service, so it is + * not told it runs none, nor sent to the stack's `requires`. + */ + it('a knowledge service registered with no instance in this scope: refused SERVICE_UNAVAILABLE / 503 with its own sentence, not the no-service one', async () => { + const refusal = await authoredKnowledgeSourceRefusal({ + type: 'knowledge_source', item: ITEM, executionContext: AUTHOR, + resolveKnowledgeService: async () => knowledgeServiceNotInScope('northwind'), + }); + expect(refusal).toMatchObject({ status: 503, code: 'SERVICE_UNAVAILABLE' }); + expect(refusal?.message).toMatch( + /^The knowledge source 'faq' was not saved: the knowledge service registered on this deployment serves no instance for environment 'northwind', so nothing would load, index or search it there\./, + ); + expect(refusal?.message).not.toContain('runs no knowledge service'); + expect(refusal?.message).not.toContain("requires: ['knowledge']"); + expect(refusal?.message).toMatch(/save the source again\. Nothing was written\.$/); + // The engine's own write is not asked, scope miss or not. + const resolve = vi.fn(() => knowledgeServiceNotInScope('northwind')); + expect(await authoredKnowledgeSourceRefusal({ type: 'knowledge_source', item: ITEM, executionContext: { isSystem: true }, resolveKnowledgeService: resolve })).toBeUndefined(); + expect(resolve).not.toHaveBeenCalled(); + }); + + /** + * The package duplicate copies a package's sources: its caller is told to + * duplicate the package again, and the door's prefix says once that + * nothing was copied, so the sentence carries no "Nothing was written". + */ + it('door: duplicate words each refusal the predicate composes for the duplicate\'s caller', async () => { + const ask = (resolveKnowledgeService: () => unknown, item: unknown = ITEM) => + authoredKnowledgeSourceRefusal({ type: 'knowledge_source', item, executionContext: AUTHOR, resolveKnowledgeService, door: 'duplicate' }); + + const none = await ask(() => undefined); + expect(none).toMatchObject({ status: 503, code: 'SERVICE_UNAVAILABLE' }); + expect(none?.message).toMatch(/^The knowledge source 'faq' cannot be copied: this deployment runs no knowledge service/); + expect(none?.message).toMatch(/requires: \['knowledge'\].*restart the server, then duplicate the package again: /); + + const scoped = await ask(() => knowledgeServiceNotInScope('northwind')); + expect(scoped).toMatchObject({ status: 503, code: 'SERVICE_UNAVAILABLE' }); + expect(scoped?.message).toMatch(/^The knowledge source 'faq' cannot be copied: the knowledge service registered on this deployment serves no instance for environment 'northwind'/); + expect(scoped?.message).toMatch(/duplicate the package again\.$/); + + const unresolved = await ask(async () => { throw new Error('factory failed'); }); + expect(unresolved).toMatchObject({ status: 503, code: 'SERVICE_UNAVAILABLE' }); + expect(unresolved?.message).toMatch(/^The knowledge source cannot be copied: /); + expect(unresolved?.message).toMatch(/Duplicate the package again\.$/); + + for (const refusal of [none, scoped, unresolved]) { + expect(refusal?.message).not.toMatch(/save the source|Nothing was written/); + } + // A verdict of the knowledge service is its own sentence, passed through as before. + expect(await ask(() => serviceAnswering(REFUSED))).toEqual({ status: 403, code: 'PERMISSION_DENIED', message: REFUSED.message }); + }); + it('`isSystem: false` is not a bypass', async () => { const service = serviceAnswering(REFUSED); const refusal = await authoredKnowledgeSourceRefusal({ type: 'knowledge_source', item: ITEM, executionContext: { ...AUTHOR, isSystem: false }, resolveKnowledgeService: () => service }); diff --git a/packages/metadata-core/src/knowledge-source-save-admission.ts b/packages/metadata-core/src/knowledge-source-save-admission.ts index c66f0980118..ccd41d5f8cd 100644 --- a/packages/metadata-core/src/knowledge-source-save-admission.ts +++ b/packages/metadata-core/src/knowledge-source-save-admission.ts @@ -51,6 +51,26 @@ * service answers at index and search for a store that is not mounted. * Nothing was written. * + * ## A knowledge service registered, with no instance in this scope + * + * A host can register `knowledge` per environment, as a scoped factory that + * answers no instance for some of them. The deployment does run a knowledge + * service then, so the sentence above would be false, and its remedy (the + * stack's `requires`) is not the fix: the host's registration decides. A door + * whose lookup tells that miss apart answers it as + * {@link knowledgeServiceNotInScope}, and the save is refused with its own + * sentence ({@link noKnowledgeServiceInScopeRefusal}), the same status and + * code. The platform's `KnowledgeServicePlugin` registers a plain instance, + * so its own service never reaches this. + * + * ## The door's wording + * + * The sentences name the save's remedy (save the source again, nothing was + * written). A door that copies sources rather than saves one, the package + * duplicate, asks with `door: 'duplicate'` and gets its caller's remedy + * (duplicate the package again) and no "nothing was written" of its own: that + * door's prefix says once that nothing was copied. + * * ## Fail direction * * Access-narrowing, so it fails closed: a knowledge service that cannot be @@ -78,18 +98,61 @@ export type AuthoredKnowledgeSourceVerdict = | { admitted: true } | ({ admitted: false } & AuthoredKnowledgeSourceRefusal); +/** + * Which door asks, for the remedy its caller is told: `save` (the default) for + * a door that saves one item, `duplicate` for the package duplicate, which + * copies a package's sources. + */ +export type KnowledgeSourceSaveDoor = 'save' | 'duplicate'; + +/** Brand of {@link knowledgeServiceNotInScope}, shared across copies of this module. */ +const NOT_IN_SCOPE = Symbol.for('@objectstack/metadata-core/knowledge-service-not-in-scope'); + +/** + * What a door's `resolveKnowledgeService` answers when a `knowledge` + * registration exists and the lookup made in the request's scope produced no + * instance (a host's scoped factory that serves no service for that + * environment). Built by {@link knowledgeServiceNotInScope}. + */ +export interface KnowledgeServiceNotInScope { + readonly [NOT_IN_SCOPE]: true; + /** The scope the lookup was made in: the request's environment. */ + readonly scopeId: string; +} + +/** The answer a door's lookup gives for a scope-relative miss of the `knowledge` service. */ +export function knowledgeServiceNotInScope(scopeId: string): KnowledgeServiceNotInScope { + return Object.freeze({ [NOT_IN_SCOPE]: true as const, scopeId }); +} + +function isKnowledgeServiceNotInScope(value: unknown): value is KnowledgeServiceNotInScope { + return typeof value === 'object' && value !== null && (value as Record)[NOT_IN_SCOPE] === true; +} + /** The member of the `knowledge` service the doors ask, reached duck-typed. */ export interface KnowledgeSourceSaveAdmitter { admitAuthoredSource(item: unknown, context: unknown): Promise; } -function unavailable(why: string): AuthoredKnowledgeSourceRefusal { +/** The remedy and the no-op each door's caller is told. */ +const DOOR_WORDING: Readonly> = { + save: { notDone: 'was not saved', retry: 'save the source again', nothingDone: ' Nothing was written.' }, + duplicate: { notDone: 'cannot be copied', retry: 'duplicate the package again', nothingDone: '' }, +}; + +function sourceSubject(item: unknown): string { + const name = (item as { name?: unknown } | null | undefined)?.name; + return typeof name === 'string' && name !== '' ? `The knowledge source '${name}'` : 'The knowledge source'; +} + +function unavailable(why: string, door: KnowledgeSourceSaveDoor): AuthoredKnowledgeSourceRefusal { + const wording = DOOR_WORDING[door]; return { status: 503, code: 'SERVICE_UNAVAILABLE', message: - `The knowledge source was not saved: whether its author may search what it would index could not be ` + - `judged (${why}). Nothing was written; try again.`, + `The knowledge source ${wording.notDone}: whether its author may search what it would index could not be ` + + `judged (${why}).` + (door === 'save' ? ' Nothing was written; try again.' : ' Duplicate the package again.'), }; } @@ -100,18 +163,41 @@ function unavailable(why: string): AuthoredKnowledgeSourceRefusal { * while the process runs, so the remedy is ordered: the token, a restart, then * the save. */ -function noKnowledgeServiceRefusal(item: unknown): AuthoredKnowledgeSourceRefusal { - const name = (item as { name?: unknown } | null | undefined)?.name; - const source = typeof name === 'string' && name !== '' ? `The knowledge source '${name}'` : 'The knowledge source'; +function noKnowledgeServiceRefusal(item: unknown, door: KnowledgeSourceSaveDoor): AuthoredKnowledgeSourceRefusal { + const wording = DOOR_WORDING[door]; + return { + status: 503, + code: 'SERVICE_UNAVAILABLE', + message: + `${sourceSubject(item)} ${wording.notDone}: this deployment runs no knowledge service, so nothing would ` + + "load, index or search it. Add requires: ['knowledge'] to the stack (or, on a host that composes its own " + + 'kernel, KnowledgeServicePlugin from @objectstack/service-knowledge and a knowledge store), restart the ' + + `server, then ${wording.retry}: the service is mounted when the server starts, never while it runs.` + + wording.nothingDone, + }; +} + +/** + * The refusal of an author's `knowledge_source` save where a `knowledge` + * registration exists and answers no instance for the request's environment + * (a host's scoped factory). The deployment does run a knowledge service, so + * the stack's `requires` is not the remedy: the host's registration decides + * which environments it serves. + */ +function noKnowledgeServiceInScopeRefusal( + item: unknown, + scopeId: string, + door: KnowledgeSourceSaveDoor, +): AuthoredKnowledgeSourceRefusal { + const wording = DOOR_WORDING[door]; return { status: 503, code: 'SERVICE_UNAVAILABLE', message: - `${source} was not saved: this deployment runs no knowledge service, so nothing would load, index or ` + - "search it. Add requires: ['knowledge'] to the stack (or, on a host that composes its own kernel, " + - 'KnowledgeServicePlugin from @objectstack/service-knowledge and a knowledge store), restart the server, ' + - 'then save the source again: the service is mounted when the server starts, never while it runs. ' + - 'Nothing was written.', + `${sourceSubject(item)} ${wording.notDone}: the knowledge service registered on this deployment serves ` + + `no instance for environment '${scopeId}', so nothing would load, index or search it there. The host's ` + + `knowledge service registration decides which environments it serves; once it serves '${scopeId}', ` + + `${wording.retry}.` + wording.nothingDone, }; } @@ -121,7 +207,9 @@ function noKnowledgeServiceRefusal(item: unknown): AuthoredKnowledgeSourceRefusa * * `resolveKnowledgeService` answers the request environment's `knowledge` * service, `undefined` when none is registered (an author's save is then - * refused), and throws when one is registered and cannot be resolved. + * refused), {@link knowledgeServiceNotInScope} when one is registered and + * serves no instance in the request's scope (refused, with its own sentence), + * and throws when one is registered and cannot be resolved. */ export async function authoredKnowledgeSourceRefusal(input: { /** The metadata type saved, in any URL spelling the protocol accepts. */ @@ -131,23 +219,27 @@ export async function authoredKnowledgeSourceRefusal(input: { /** The author's execution context. */ executionContext: unknown; resolveKnowledgeService: () => Promise | unknown; + /** The door that asks, for its caller's remedy; `save` when absent. */ + door?: KnowledgeSourceSaveDoor; }): Promise { if (canonicalMetaUrlType(input.type) !== KNOWLEDGE_SOURCE_TYPE) return undefined; if ((input.executionContext as { isSystem?: unknown } | null | undefined)?.isSystem === true) return undefined; + const door: KnowledgeSourceSaveDoor = input.door ?? 'save'; let service: unknown; try { service = await input.resolveKnowledgeService(); } catch (err) { - return unavailable(`the knowledge service could not be resolved: ${err instanceof Error ? err.message : String(err)}`); + return unavailable(`the knowledge service could not be resolved: ${err instanceof Error ? err.message : String(err)}`, door); } - if (service === undefined || service === null) return noKnowledgeServiceRefusal(input.item); + if (service === undefined || service === null) return noKnowledgeServiceRefusal(input.item, door); + if (isKnowledgeServiceNotInScope(service)) return noKnowledgeServiceInScopeRefusal(input.item, service.scopeId, door); const admit = (service as Partial).admitAuthoredSource; if (typeof admit !== 'function') return undefined; let verdict: AuthoredKnowledgeSourceVerdict; try { verdict = await admit.call(service, input.item, input.executionContext); } catch (err) { - return unavailable(err instanceof Error ? err.message : String(err)); + return unavailable(err instanceof Error ? err.message : String(err), door); } if (!verdict || verdict.admitted === true) return undefined; return { status: verdict.status, code: verdict.code, message: verdict.message }; diff --git a/packages/runtime/src/domain-handler-registry.ts b/packages/runtime/src/domain-handler-registry.ts index 14f2d90261d..c9f47815445 100644 --- a/packages/runtime/src/domain-handler-registry.ts +++ b/packages/runtime/src/domain-handler-registry.ts @@ -128,6 +128,27 @@ export interface DomainRoute { handler: DomainHandler; } +/** + * [#16402] What {@link DomainHandlerDeps.classifyServiceOrLoud} answers: the + * classified service lookup's three non-fault outcomes. + * + * - `resolved`: an instance. + * - `never-registered`: every registry in the chain answered the branded + * "nothing was ever registered under this name", or the probe tail found + * nothing. The supported no-service composition. + * - `no-instance-in-scope`: a registry did know the name, and the read made + * in this scope produced no instance. + * + * A caller that named no scope and asked for a `SCOPED` registration is not + * here: that stays the unbranded rejection `packages/core` raises, so + * `Scope ID required for scoped service 'NAME'` keeps reaching the one caller + * it is true about. + */ +export type ClassifiedServiceLookup = + | { readonly outcome: 'resolved'; readonly value: any } + | { readonly outcome: 'never-registered' } + | { readonly outcome: 'no-instance-in-scope'; readonly scopeId: string }; + /** * The dispatcher facilities an extracted domain body is allowed to use — the * WHOLE dependency contract, made explicit. Growing this interface is a @@ -199,8 +220,10 @@ export interface DomainHandlerDeps { * service the same way it reads a deployment with none. ⚠️ It is a * DIFFERENT fact from the one above with the same licence, and the * lookup tells the two apart internally (`HttpDispatcher.classifyService`) - * — it is collapsed HERE because no door needs to act on the difference, - * ⛔ not because they are the same state; + * — it is collapsed HERE because both misses license the same answer at + * the doors that read this member, ⛔ not because they are the same + * state. A door whose ANSWER differs between them asks + * {@link classifyServiceOrLoud} instead; * - every other rejection (a factory that threw, a scoped registration * resolved without a scope id, a circular service dependency) → * re-raised, for the gate to answer as an OUTAGE rather than as an @@ -245,6 +268,23 @@ export interface DomainHandlerDeps { * nothing verifies. */ resolveServiceOrLoud(context: HttpProtocolContext, name: string, environmentId?: string): Promise; + /** + * {@link resolveServiceOrLoud} with its two quiet misses told apart, for a + * door that tells its caller something different for each: today the + * `knowledge_source` save doors (ADR-0161 K4), where "this deployment runs + * no knowledge service" is false for a host whose scoped `knowledge` + * factory serves no instance for the request's environment. The same + * chain, the same scope travel, and the same loud rejections; only the + * answer is classified ({@link ClassifiedServiceLookup}). It claims no + * more than the registry did: `no-instance-in-scope` never asserts that the + * registration is `SCOPED`. + * + * Optional, so an implementation of this exported interface written + * before it existed (a host's own deps, a test double) still compiles; a + * door reading a deps without it falls back to {@link resolveServiceOrLoud} + * and answers both misses as `never-registered`, the answer it gave before. + */ + classifyServiceOrLoud?(context: HttpProtocolContext, name: string, environmentId?: string): Promise; /** * Unscoped service lookup on the current kernel, typed by the slot. * diff --git a/packages/runtime/src/domains/mcp-authoring.ts b/packages/runtime/src/domains/mcp-authoring.ts index 86a11f3ba89..3d9009bbfad 100644 --- a/packages/runtime/src/domains/mcp-authoring.ts +++ b/packages/runtime/src/domains/mcp-authoring.ts @@ -160,11 +160,11 @@ import { createRequire } from 'node:module'; import { resolveUserAuthzGrants, userTextLocalesOf } from '@objectstack/core'; import { - KNOWLEDGE_SOURCE_ADMISSION_SERVICE, authoredKnowledgeSourceRefusal, metaWriteCapabilityVerdict, walledCatalogWriteVerdict, } from '@objectstack/metadata-core'; +import { resolveKnowledgeServiceForSave } from '../knowledge-service-lookup.js'; import { createMetaItemReadGate, createMetaListReadGate, @@ -435,11 +435,12 @@ export interface OpenAuthoringWriter { /** The walled refusal for a write of `type` (`walledCatalogWriteVerdict`). */ writeVerdict(type: string): Promise<{ allowed: true } | { allowed: false; code: ErrorCode; message: string; status: number }>; /** - * [ADR-0161 K4, guard two] The refusal of a `knowledge_source` save whose - * author may not themselves search what it would index + * [ADR-0161 K4, guard two] The refusal of a `knowledge_source` save * (`authoredKnowledgeSourceRefusal`, judged for the admitted human), or - * on a deployment with no knowledge service, or `undefined` when the save - * may go on. Every other type answers `undefined`. + * `undefined` when the save may go on. A save is refused when its author + * may not themselves search what it would index, and when no knowledge + * service serves the request's environment. Every other type answers + * `undefined`. */ itemSaveRefusal(type: string, item: unknown): Promise<{ code: ErrorCode; message: string; status: number } | undefined>; } @@ -674,11 +675,12 @@ function openWriter( item, // The human the door admitted: their grants, never the envelope's. executionContext: reader, - // The classified lookup (`resolveServiceOrLoud`): an absent - // service answers `undefined` and the predicate refuses the - // save `503`, naming the remedy; a registered one that cannot - // be resolved rejects and the predicate answers `503`. - resolveKnowledgeService: () => deps.resolveServiceOrLoud(context, KNOWLEDGE_SOURCE_ADMISSION_SERVICE, context.environmentId), + // The classified lookup (`resolveKnowledgeServiceForSave`): an + // absent service, and a registration with no instance in this + // scope, are each refused `503` with their own sentence; a + // registered one that cannot be resolved rejects and the + // predicate answers `503`. + resolveKnowledgeService: () => resolveKnowledgeServiceForSave(deps, context), }); if (!refused) return undefined; return { diff --git a/packages/runtime/src/domains/meta-save-capability-gate.test.ts b/packages/runtime/src/domains/meta-save-capability-gate.test.ts index 57474a2e150..04cdc07fc63 100644 --- a/packages/runtime/src/domains/meta-save-capability-gate.test.ts +++ b/packages/runtime/src/domains/meta-save-capability-gate.test.ts @@ -40,7 +40,7 @@ */ import { describe, it, expect, vi } from 'vitest'; -import { ObjectKernel } from '@objectstack/core'; +import { ObjectKernel, ServiceLifecycle } from '@objectstack/core'; import { HttpDispatcher } from '../http-dispatcher.js'; // Paid at collection, not inside a case's clock (check:test-source-alias). @@ -376,6 +376,57 @@ describe('ADR-0161 K4 — dispatcher PUT asks the knowledge service to admit the expect(saveMetaItem).toHaveBeenCalledTimes(1); }); + /** + * A host that registers `knowledge` per environment, as a scoped factory + * serving no instance for this request's environment: the deployment does + * run a knowledge service, so the author is not told it runs none, nor + * sent to the stack's `requires`. The platform's `KnowledgeServicePlugin` + * registers a plain instance, so the platform's own path is the control. + */ + describe('a knowledge service registered with no instance in the request\'s environment', () => { + function bootScoped(served: string) { + const saveMetaItem = vi.fn(async ({ name }: any) => ({ success: true, name })); + const admitAuthoredSource = vi.fn(async () => ({ admitted: true })); + const kernel = new ObjectKernel({ gracefulShutdown: false, skipSystemValidation: true }); + kernel.registerService('protocol', { saveMetaItem }); + kernel.registerServiceFactory( + 'knowledge', + (_ctx: unknown, scopeId?: string) => (scopeId === served ? { admitAuthoredSource } : undefined), + ServiceLifecycle.SCOPED, + ); + return { dispatcher: new HttpDispatcher(kernel as any), saveMetaItem, admitAuthoredSource }; + } + + it('is refused 503 SERVICE_UNAVAILABLE with its own sentence naming the environment, and nothing is saved', async () => { + const stack = bootScoped('northwind'); + const res = await stack.dispatcher.handleMetadata('/knowledge_source/faq', ctx(AUTHOR), 'PUT', copy(SOURCE)); + expect(res.response?.status).toBe(503); + expect(res.response?.body?.error?.code).toBe('SERVICE_UNAVAILABLE'); + expect(res.response?.body?.error?.message).toMatch( + /^The knowledge source 'faq' was not saved: the knowledge service registered on this deployment serves no instance for environment 'platform'/, + ); + expect(res.response?.body?.error?.message).not.toContain('runs no knowledge service'); + expect(stack.saveMetaItem).not.toHaveBeenCalled(); + }); + + it('CONTROL: the same factory serving this environment admits the save; the platform\'s plain instance is unchanged', async () => { + const served = bootScoped('platform'); + expect((await served.dispatcher.handleMetadata('/knowledge_source/faq', ctx(AUTHOR), 'PUT', copy(SOURCE))).response?.status).toBe(200); + expect(served.admitAuthoredSource).toHaveBeenCalledTimes(1); + expect(served.saveMetaItem).toHaveBeenCalledTimes(1); + + const saveMetaItem = vi.fn(async ({ name }: any) => ({ success: true, name })); + const admitAuthoredSource = vi.fn(async () => ({ admitted: true })); + const kernel = new ObjectKernel({ gracefulShutdown: false, skipSystemValidation: true }); + kernel.registerService('protocol', { saveMetaItem }); + kernel.registerService('knowledge', { admitAuthoredSource }); + const plain = new HttpDispatcher(kernel as any); + expect((await plain.handleMetadata('/knowledge_source/faq', ctx(AUTHOR), 'PUT', copy(SOURCE))).response?.status).toBe(200); + expect(admitAuthoredSource).toHaveBeenCalledTimes(1); + expect(saveMetaItem).toHaveBeenCalledTimes(1); + }); + }); + it('the gate is behind the capability gates, and is not asked for another type', async () => { // `manage_metadata` without `manage_knowledge_sources`, and the reverse. for (const systemPermissions of [['manage_metadata'], ['manage_knowledge_sources']]) { diff --git a/packages/runtime/src/domains/meta.ts b/packages/runtime/src/domains/meta.ts index 905863dda3e..1aecaba2fb2 100644 --- a/packages/runtime/src/domains/meta.ts +++ b/packages/runtime/src/domains/meta.ts @@ -33,13 +33,13 @@ import { // `manage_metadata` (or `isSystem`), the one predicate the REST doors run // too. No `/meta` branch here carries an organization into a metadata // write or read: the per-organization overlay axis is retired. - KNOWLEDGE_SOURCE_ADMISSION_SERVICE, authoredKnowledgeSourceRefusal, metaWriteCapabilityVerdict, // [ADR-0131 D3 · D12 items 7–8] …and, under a wall, the platform operator // alone: the walled refusal every environment-metadata write door asks. walledCatalogWriteVerdict, } from '@objectstack/metadata-core'; +import { resolveKnowledgeServiceForSave } from '../knowledge-service-lookup.js'; // [#15238] The DECLARED protocol contracts this domain's request literals are // compiled against. Imported, never restated: a second hand-written // `getMetaItem(…)` signature here would silently drift from the one the spec @@ -1994,12 +1994,11 @@ export async function handleMetadataRequest(deps: DomainHandlerDeps, path: strin item, executionContext: _context.executionContext, // The classified lookup, not the `resolveService` probe: - // a name nothing registered answers `undefined` (no - // knowledge service: the save is refused), and a service that - // is registered and cannot be resolved rejects, which the - // predicate answers `503`. - resolveKnowledgeService: () => - deps.resolveServiceOrLoud(_context, KNOWLEDGE_SOURCE_ADMISSION_SERVICE, _context.environmentId), + // a name nothing registered answers the no-service refusal, + // a registration with no instance in this scope its own, + // and a service that is registered and cannot be resolved + // rejects, which the predicate answers `503`. + resolveKnowledgeService: () => resolveKnowledgeServiceForSave(deps, _context), }); if (refused) { return { handled: true, response: deps.error(refused.message, refused.status) }; diff --git a/packages/runtime/src/domains/packages-knowledge-source-gate.test.ts b/packages/runtime/src/domains/packages-knowledge-source-gate.test.ts index 43d526b371c..13358bc9f71 100644 --- a/packages/runtime/src/domains/packages-knowledge-source-gate.test.ts +++ b/packages/runtime/src/domains/packages-knowledge-source-gate.test.ts @@ -25,6 +25,7 @@ // Pays `@objectstack/metadata`'s first load at collection, never inside a clocked case. import '@objectstack/metadata'; import { describe, it, expect, vi } from 'vitest'; +import { ObjectKernel, ServiceLifecycle } from '@objectstack/core'; import { HttpDispatcher } from '../http-dispatcher.js'; const ctx = (executionContext: any): any => ({ request: {}, environmentId: 'platform', executionContext }); @@ -97,7 +98,7 @@ function make(holding: Holding = {}, knowledge?: unknown) { : null, }, }; - return { dispatcher: new HttpDispatcher(kernel), protocol, metadata, registry }; + return { dispatcher: new HttpDispatcher(kernel), protocol, metadata, registry, kernelServices: { objectql, protocol, metadata } }; } type Stack = ReturnType; @@ -294,9 +295,14 @@ describe('/packages — duplicate admits each knowledge source it copies for the const r = await call(noService, DUPLICATE, authed(BOTH)); expect(r.response?.status).toBe(503); expect(r.response?.body?.error?.code).toBe('SERVICE_UNAVAILABLE'); - expect(r.response?.body?.error?.message).toContain('nothing was copied'); - expect(r.response?.body?.error?.message).toContain('this deployment runs no knowledge service'); - expect(r.response?.body?.error?.message).toContain("requires: ['knowledge']"); + const message: string = r.response?.body?.error?.message; + expect(message).toMatch( + /^Duplicating package "pkg-a" is refused, and nothing was copied\. The knowledge source 'faq' cannot be copied: this deployment runs no knowledge service/, + ); + expect(message).toMatch(/requires: \['knowledge'\].*restart the server, then duplicate the package again: /); + // The caller duplicates a package: never told to save a source, and told once that nothing was copied. + expect(message).not.toMatch(/save the source|Nothing was written/); + expect(message.match(/nothing was copied/gi)).toHaveLength(1); expect(noService.protocol.duplicatePackage).not.toHaveBeenCalled(); // A package with no source, and the engine's own call, copy as before. @@ -308,6 +314,42 @@ describe('/packages — duplicate admits each knowledge source it copies for the expect(engine.protocol.duplicatePackage).toHaveBeenCalled(); }); + /** + * A host that registers `knowledge` per environment and serves no instance + * for this request's: the deployment runs a knowledge service, so the + * caller is told what is true and the stack's `requires` is not named. + */ + it('a knowledge service registered with no instance in the request\'s environment refuses 503 with its own sentence; the plain instance is the control', async () => { + const scoped = make({ items: [SOURCE_ITEM] }); + const kernel = new ObjectKernel({ gracefulShutdown: false, skipSystemValidation: true }); + for (const name of ['objectql', 'protocol', 'metadata'] as const) { + kernel.registerService(name, scoped.kernelServices[name]); + } + kernel.registerServiceFactory('knowledge', () => undefined, ServiceLifecycle.SCOPED); + const r = await new HttpDispatcher(kernel as any).handlePackages('/pkg-a/duplicate', 'POST', { targetPackageId: 'pkg-b' }, {}, authed(BOTH)); + expect(r.response?.status).toBe(503); + expect(r.response?.body?.error?.code).toBe('SERVICE_UNAVAILABLE'); + const message: string = r.response?.body?.error?.message; + expect(message).toMatch( + /^Duplicating package "pkg-a" is refused, and nothing was copied\. The knowledge source 'faq' cannot be copied: the knowledge service registered on this deployment serves no instance for environment 'platform'/, + ); + expect(message).not.toMatch(/runs no knowledge service|requires: \['knowledge'\]|save the source|Nothing was written/); + expect(scoped.protocol.duplicatePackage).not.toHaveBeenCalled(); + + // CONTROL: a plain instance, as the platform's plugin registers it, is asked and admits. + const plain = make({ items: [SOURCE_ITEM] }); + const plainKernel = new ObjectKernel({ gracefulShutdown: false, skipSystemValidation: true }); + for (const name of ['objectql', 'protocol', 'metadata'] as const) { + plainKernel.registerService(name, plain.kernelServices[name]); + } + const admitAuthoredSource = vi.fn(async () => ({ admitted: true })); + plainKernel.registerService('knowledge', { admitAuthoredSource }); + const ok = await new HttpDispatcher(plainKernel as any).handlePackages('/pkg-a/duplicate', 'POST', { targetPackageId: 'pkg-b' }, {}, authed(BOTH)); + expect(ok.response?.status).not.toBe(503); + expect(admitAuthoredSource).toHaveBeenCalledTimes(1); + expect(plain.protocol.duplicatePackage).toHaveBeenCalled(); + }); + it('the engine\'s own call is not asked', async () => { const s = withKnowledge({ items: [SOURCE_ITEM] }, () => REFUSAL); expect((await call(s, DUPLICATE, system())).response?.status).not.toBe(403); diff --git a/packages/runtime/src/domains/packages.ts b/packages/runtime/src/domains/packages.ts index 47ee716f3bf..6cb72a92e16 100644 --- a/packages/runtime/src/domains/packages.ts +++ b/packages/runtime/src/domains/packages.ts @@ -49,7 +49,8 @@ import type { GetPackageCustomizationsResponse } from '@objectstack/spec/api'; import { walledCatalogWriteVerdict } from '@objectstack/metadata-core'; // [ADR-0161 K4, guard two] Source admission, asked for each knowledge source a // duplicate would copy (`refuseDuplicatedKnowledgeSources`). -import { KNOWLEDGE_SOURCE_ADMISSION_SERVICE, authoredKnowledgeSourceRefusal } from '@objectstack/metadata-core'; +import { authoredKnowledgeSourceRefusal } from '@objectstack/metadata-core'; +import { resolveKnowledgeServiceForSave } from '../knowledge-service-lookup.js'; import { isMissingTableError } from '@objectstack/types'; import { readEffectiveTenancyPosture } from './activation-gate.js'; // [#21727] ADR-0087 D1's protocol handshake and the brand predicate for its @@ -612,7 +613,9 @@ async function knowledgeSourceInPackageReach( * before anything is copied, by the predicate the `/meta` save asks * (`authoredKnowledgeSourceRefusal`): the caller must themselves be allowed to * search what the source indexes. The first source refused refuses the whole - * duplicate with the predicate's own status and sentence; nothing was copied. + * duplicate with the predicate's own status and sentence, worded for this + * door (`door: 'duplicate'`: duplicate the package again); nothing was copied, + * which the prefix says once. * * Asked of every caller but the engine's own call, a holder of * `manage_knowledge_sources` included: the capability says who may author a @@ -655,8 +658,10 @@ async function refuseDuplicatedKnowledgeSources( type: KNOWLEDGE_SOURCE_PACKAGE_TYPE, item, executionContext: ec, - resolveKnowledgeService: () => - deps.resolveServiceOrLoud(context, KNOWLEDGE_SOURCE_ADMISSION_SERVICE, context.environmentId), + resolveKnowledgeService: () => resolveKnowledgeServiceForSave(deps, context), + // This door's caller is told to duplicate the package again; the + // prefix below says once that nothing was copied. + door: 'duplicate', }); if (refused) { return { diff --git a/packages/runtime/src/http-dispatcher.ts b/packages/runtime/src/http-dispatcher.ts index 2a8676d8d84..26622ce79b3 100644 --- a/packages/runtime/src/http-dispatcher.ts +++ b/packages/runtime/src/http-dispatcher.ts @@ -35,7 +35,7 @@ import { apiErrorResponse } from './error-envelope.js'; import { resolveRuntimeVersion } from './runtime-version.js'; import { readSeedReadiness, type SeedReadiness } from './seed-readiness.js'; import type { ExecutionContext } from '@objectstack/spec/kernel'; -import { DomainHandlerRegistry, type DomainRoute, type DomainHandlerDeps } from './domain-handler-registry.js'; +import { DomainHandlerRegistry, type DomainRoute, type DomainHandlerDeps, type ClassifiedServiceLookup } from './domain-handler-registry.js'; // `import * as actionExec from './action-execution.js'` was dropped in #4936: // the dispatcher's own `callData` delegate was its last consumer here, and the // delegate died with the `handleApiEndpoint` branch. The domain modules import @@ -424,26 +424,6 @@ function withSeedReading( return { ...body, seed }; } -/** - * [#16402] What {@link HttpDispatcher.classifyService} answers — the classified - * service lookup's three non-fault outcomes. - * - * ⛔ Module-local and deliberately NOT exported, for the same reason - * `PrimaryDatasourceReading` above is not: it is an internal reading, and - * `DomainHandlerDeps.resolveServiceOrLoud` — which IS part of an exported type — - * keeps answering the service or `undefined`, unchanged. Nothing published - * gains a member. - * - * A caller that named no scope and asked for a `SCOPED` registration is NOT - * here: that stays the unbranded rejection `packages/core` raises, so - * `Scope ID required for scoped service ''` keeps reaching the one caller - * it is true about. - */ -type ClassifiedServiceLookup = - | { readonly outcome: 'resolved'; readonly value: any } - | { readonly outcome: 'never-registered' } - | { readonly outcome: 'no-instance-in-scope'; readonly scopeId: string }; - /** * [#32887] The environment a host's {@link KernelResolver} placed each request * in, kept beside the request and readable only through @@ -596,6 +576,11 @@ export class HttpDispatcher { // it does not reroute a name for every domain (#15900 option C). resolveServiceOrLoud: (context: HttpProtocolContext, name: string, environmentId?: string) => this.resolveServiceOrLoud(this.requestKernel(context), name, environmentId), + // The same lookup with its two quiet misses told apart, for a door + // whose answer differs between them (the `knowledge_source` save + // doors). Opted into per call site, as the member above is. + classifyServiceOrLoud: (context: HttpProtocolContext, name: string, environmentId?: string) => + this.classifyService(this.requestKernel(context), name, environmentId), getService: (context: HttpProtocolContext, name: string) => this.getService(this.requestKernel(context), name as Parameters[1]), getObjectQL: (context, environmentId) => @@ -2874,10 +2859,13 @@ export class HttpDispatcher { * back. Reading that value as a fault would be this lookup overruling the * registry. * - * ⛔ The distinction stays HERE rather than on - * {@link DomainHandlerDeps.resolveServiceOrLoud}: that member is part of an - * EXPORTED type, and no door needs to act on the difference — both misses - * license the same answer. A caller that needs the fact asks this method. + * ⛔ The distinction stays off + * {@link DomainHandlerDeps.resolveServiceOrLoud}: at the doors that read + * that member both misses license the same answer. A door whose answer + * differs between them (the `knowledge_source` save doors: "this + * deployment runs no knowledge service" is false for a scope-relative + * miss) asks this method, through the optional + * {@link DomainHandlerDeps.classifyServiceOrLoud}. */ private async classifyService( kernel: any, diff --git a/packages/runtime/src/knowledge-service-lookup.ts b/packages/runtime/src/knowledge-service-lookup.ts new file mode 100644 index 00000000000..a4b7c661767 --- /dev/null +++ b/packages/runtime/src/knowledge-service-lookup.ts @@ -0,0 +1,44 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0161 K4, guard two] The request environment's `knowledge` service, as + * the dispatcher's `knowledge_source` save doors hand it to + * `authoredKnowledgeSourceRefusal` (`@objectstack/metadata-core`): the `/meta` + * save, the MCP draft save and the package duplicate. + * + * The classified lookup, never the `resolveService` probe, and its two quiet + * misses told apart: + * + * - an instance → the service, which the predicate asks; + * - nothing registered under the name → `undefined`: the deployment runs no + * knowledge service, and the predicate's refusal says so and names the + * stack's `requires` as the remedy; + * - a registration that serves no instance in the request's scope (a host's + * scoped `knowledge` factory) → `knowledgeServiceNotInScope`: the + * deployment does run one, so the predicate answers its own sentence and + * does not send the author to the stack. The platform's + * `KnowledgeServicePlugin` registers a plain instance, so its own service + * never reaches this. + * + * A registered service that cannot be resolved rejects, and the predicate + * answers that `503`. A deps with no `classifyServiceOrLoud` (a host's own, + * a test double) is read through `resolveServiceOrLoud` as before: both misses + * are then the no-service answer. + */ + +import { KNOWLEDGE_SOURCE_ADMISSION_SERVICE, knowledgeServiceNotInScope } from '@objectstack/metadata-core'; +import type { DomainHandlerDeps } from './domain-handler-registry.js'; +import type { HttpProtocolContext } from './http-dispatcher.js'; + +export async function resolveKnowledgeServiceForSave( + deps: DomainHandlerDeps, + context: HttpProtocolContext, +): Promise { + if (typeof deps.classifyServiceOrLoud !== 'function') { + return deps.resolveServiceOrLoud(context, KNOWLEDGE_SOURCE_ADMISSION_SERVICE, context.environmentId); + } + const answer = await deps.classifyServiceOrLoud(context, KNOWLEDGE_SOURCE_ADMISSION_SERVICE, context.environmentId); + if (answer.outcome === 'resolved') return answer.value; + if (answer.outcome === 'no-instance-in-scope') return knowledgeServiceNotInScope(answer.scopeId); + return undefined; +} diff --git a/packages/spec/src/migrations/entries/semantic/19.knowledge-source-save-refused-without-knowledge-service.ts b/packages/spec/src/migrations/entries/semantic/19.knowledge-source-save-refused-without-knowledge-service.ts index 0a55d219544..b8101cd4f42 100644 --- a/packages/spec/src/migrations/entries/semantic/19.knowledge-source-save-refused-without-knowledge-service.ts +++ b/packages/spec/src/migrations/entries/semantic/19.knowledge-source-save-refused-without-knowledge-service.ts @@ -11,8 +11,8 @@ export const entry: SemanticMigration = { surface: 'A `knowledge_source` saved by an author (Studio and REST `PUT /meta/knowledge_source/:name`, the runtime ' + 'dispatcher\'s `/meta` save, the MCP `save_metadata_draft` tool, and a package duplicate that copies one) on a ' - + 'deployment whose stack does not declare `requires: [\'knowledge\']` and whose host mounts no ' - + '`KnowledgeServicePlugin`', + + 'deployment whose stack neither declares `requires: [\'knowledge\']` nor ships a `knowledgeSources` entry, and ' + + 'whose host mounts no `KnowledgeServicePlugin`', replacement: 'Add `requires: [\'knowledge\']` to the stack (or, on a host that composes its own kernel, ' + '`KnowledgeServicePlugin` from `@objectstack/service-knowledge` and a knowledge store), restart the server, ' @@ -25,8 +25,9 @@ export const entry: SemanticMigration = { + 'engine\'s own writes (a package install, a seed, a migration) are not refused, a knowledge service a host ' + 'registers itself answers for its own sources as before, and stored items are not rewritten or refused at boot.', acceptanceCriteria: - 'On a deployment that should serve knowledge sources, the stack declares requires: [\'knowledge\'] (or the host ' - + 'mounts KnowledgeServicePlugin), and the boot logs no line naming knowledge_source items with no knowledge ' - + 'service registered; a source saved there is accepted as before. On a deployment that should not, no author ' - + 'saves a knowledge_source, and one a package brings is reported once at boot with the same fix.', + 'On a deployment that should serve knowledge sources, the stack declares requires: [\'knowledge\'] or ships a ' + + 'knowledgeSources entry (either mounts the service; or the host mounts KnowledgeServicePlugin), and the boot ' + + 'logs no line naming knowledge_source items with no knowledge service registered; a source saved there is ' + + 'accepted as before. On a deployment that should not, no author saves a knowledge_source, and one a package ' + + 'brings is reported once at boot with the same fix.', };