diff --git a/.changeset/37983-knowledge-source-save-needs-the-service.md b/.changeset/37983-knowledge-source-save-needs-the-service.md new file mode 100644 index 00000000000..fd8e1b9c13c --- /dev/null +++ b/.changeset/37983-knowledge-source-save-needs-the-service.md @@ -0,0 +1,24 @@ +--- +'@objectstack/metadata-core': minor +'@objectstack/objectql': patch +'@objectstack/spec': patch +--- + +feat(metadata-core)!: a knowledge source is saved only on a deployment that mounts the knowledge service + +Clause-②: no (narrowing) +Metadata-protocol: narrowed + + + +**BREAKING** for an author who saves a `knowledge_source` on a deployment that registers no knowledge service: the save was accepted before and is refused now. Nothing there loads, indexes or searches the source, and the service is mounted when the server starts, never while it runs, so the accepted item was kept and never served; only a boot log line said so, which a Studio, REST or MCP author does not see. + +- **`@objectstack/metadata-core`.** `authoredKnowledgeSourceRefusal` answers a refusal, `503 SERVICE_UNAVAILABLE`, when no knowledge service is registered and the writer is not the engine. The message names the item, the reason and the fix: add `requires: ['knowledge']` to the stack (or, on a host that composes its own kernel, `KnowledgeServicePlugin` and a knowledge store), restart, then save the source. Every door that asks it refuses the save with that answer and writes nothing: `PUT /meta/:type/:name` on both transports, the MCP `save_metadata_draft` tool, and a package duplicate that would copy a source. +- **`@objectstack/objectql`.** The boot line for `knowledge_source` items held with no knowledge service names the same fix: `requires: ['knowledge']` and a restart (or `KnowledgeServicePlugin` and a knowledge store on a host that composes its own kernel), where it named the plugin and an adapter. +- **`@objectstack/spec`.** The upgrade guide carries the `knowledge-source-save-refused-without-knowledge-service` entry. + +Unchanged: the engine's own writes (a package install, a seed, a migration) are not refused; a registered knowledge service that is not the platform's (one with no `admitAuthoredSource`) answers for its own sources and the save goes on; stored items are not rewritten or refused at boot. + +## 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. diff --git a/content/docs/ai/knowledge-rag.mdx b/content/docs/ai/knowledge-rag.mdx index 79205a676c9..8aee1df3352 100644 --- a/content/docs/ai/knowledge-rag.mdx +++ b/content/docs/ai/knowledge-rag.mdx @@ -40,6 +40,7 @@ Which store is mounted depends on the platform database: - **More than one replica** on MySQL, MongoDB or a remote libSQL database: each replica keeps its own local `knowledge.db` and indexes only the record writes that replica itself handles, so replicas answer from indexes that differ. Give them one store: save a shared `libsql://` URL in `turso_url`, or run on PostgreSQL, where the vectors live in the one database. - **An install without the libSQL client**: `@objectstack/knowledge-turso` is an optional dependency of the CLI, because its client is a native module. Where it could not be installed the server warns at boot that the store was not mounted, and sources naming `turso` answer `SERVICE_UNAVAILABLE`. - **Without a source or the token** nothing is mounted: no knowledge service, no store and no Knowledge settings page. `knowledge-memory` is never mounted for you. +- **A source is saved only on a deployment that mounts the knowledge service.** On one without it, saving a source in Studio, the metadata API or MCP is refused `SERVICE_UNAVAILABLE` (503) and nothing is written: nothing there would load, index or search it, and the service is mounted when the server starts, never while it runs. A source saved at run time is not one the app ships, so it does not mount the service either. The refusal names the fix: add `requires: ['knowledge']`, restart, then save the source. A package install, a seed or a migration is not refused; the boot names each source it holds with no service to load it, and the same fix. - **Mounting it yourself** still works: an app whose `plugins` already hold `KnowledgeServicePlugin` keeps its own, and the runtime adds neither a second service nor a store. ## Writing a source @@ -77,7 +78,7 @@ and keeps the index in step with the records. There is no registration call to write. - **`content` lists its fields by name.** What is listed is what leaves the row store: the text of those fields is sent to the embedder and kept in the index. `'*'` is refused, and a field added to the object later is not indexed until you add it here. -- **A source can also be created or changed at run time**, in Studio or through MCP, with no restart where the knowledge service is mounted (above): a new source is loaded and built, a changed one is reloaded (and rebuilt when what it indexes changed), and a removed one has its index dropped. +- **A source can also be created or changed at run time**, in Studio or through MCP, with no restart where the knowledge service is mounted (above; where it is not, the save is refused, naming the fix): a new source is loaded and built, a changed one is reloaded (and rebuilt when what it indexes changed), and a removed one has its index dropped. - **Authoring one needs `manage_knowledge_sources`** beside `manage_metadata` — platform administrators hold it by default — and the author must themselves be allowed to search the object and query every listed field and every field `where` reads, or the save is refused naming what they may not read. A write to a package that holds a source (publish its drafts, roll it back, duplicate, disable or delete it) needs the same capability. - **Two packages may each ship a source of the same name.** `search_knowledge` lists a package's source as `NAMESPACE-NAME` and takes that spelling in `sourceIds`. - **Registering in code still works**: `new KnowledgeServicePlugin({ sources: [TaskNotes] })` or `knowledge.registerSource(TaskNotes)` takes the same shape. A source registered in code and an item saved under the same name are one name: the second to arrive is refused. diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index a4b04b385e7..0173c10775a 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -198,11 +198,15 @@ starts and follows the type from then on, with no restart: the adapter's `dropSource` (§3.4). Over an adapter without that member the index is kept, and the service says so once in its log, naming the source. -A deployment that holds a `knowledge_source` item but mounts no knowledge -service says so once at boot, naming the items: nothing loads, indexes or -searches them until `KnowledgeServicePlugin` and an adapter are mounted. Such -an item is one the stack does not ship — saved at run time or installed in a -package after the boot — since a shipped one mounts the service. +A source is saved only on a deployment that mounts the knowledge service +(see [Who may author one](#who-may-author-one)). A deployment that holds a +`knowledge_source` item but mounts no knowledge service says so once at boot, +naming the items: nothing loads, indexes or searches them until the service is +mounted, by `requires: ['knowledge']` in the stack and a restart (or, on a host +that composes its own kernel, `KnowledgeServicePlugin` and a store). Such an +item is one the stack does not ship, since a shipped one mounts the service: +one a package install, a seed or a migration wrote after the boot, or one +saved before saves were refused there. #### Who may author one @@ -236,6 +240,17 @@ and the MCP draft door: verdict that cannot be reached, or a knowledge service that is registered and cannot be resolved, refuses `503`; nothing is written. +**A deployment with no knowledge service saves no source.** Nothing there +would load, index or search it, and the service is mounted when the server +starts, never while it runs; a source saved at run time is not one the stack +ships, so it does not mount the service either. So on such a deployment every +door above refuses an author's save `503 SERVICE_UNAVAILABLE`, and a duplicate +that would copy a source is refused the same way; nothing is written. The +refusal names the fix: add `requires: ['knowledge']` to the stack, restart, +then save the source. The engine's own writes (a package install, a seed, a +migration) are not refused, and a knowledge service a host mounts itself +answers for its own sources. + #### One name, one source A source is identified by the package that ships it and its `name` 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 a3b7c3eeb8d..6bac06d156f 100644 --- a/packages/metadata-core/src/knowledge-source-save-admission.test.ts +++ b/packages/metadata-core/src/knowledge-source-save-admission.test.ts @@ -4,8 +4,9 @@ * [ADR-0161 K4, guard two] `authoredKnowledgeSourceRefusal` — what every save * door asks before a `knowledge_source` is written: the knowledge service's * verdict for the AUTHOR. Pinned here: which saves are judged, that the - * service is asked with the item and the author's context, and that the gate - * fails closed. + * service is asked with the item and the author's context, that a deployment + * with no knowledge service refuses an author's save, and that the gate fails + * closed. */ import { describe, it, expect, vi } from 'vitest'; @@ -44,8 +45,29 @@ describe('authoredKnowledgeSourceRefusal — source admission at save', () => { expect(resolve).not.toHaveBeenCalled(); }); - it('no knowledge service, or one without the member, judges nothing: nothing loads the item there', async () => { - for (const service of [undefined, null, {}, { search: async () => [] }]) { + it('no knowledge service registered: an author\'s save is refused SERVICE_UNAVAILABLE / 503, naming the reason and the remedy', async () => { + for (const service of [undefined, null]) { + for (const type of ['knowledge_source', 'knowledge_sources']) { + const refusal = await authoredKnowledgeSourceRefusal({ type, item: ITEM, executionContext: AUTHOR, resolveKnowledgeService: async () => service }); + expect(refusal, `${type} / ${String(service)}`).toMatchObject({ status: 503, code: 'SERVICE_UNAVAILABLE' }); + // The reason, the item, and the remedy in its order: the token, a restart, then the save. + expect(refusal?.message).toMatch(/^The knowledge source 'faq' was not saved: this deployment runs no knowledge service/); + expect(refusal?.message).toMatch(/requires: \['knowledge'\].*restart the server.*then save the source again/); + } + } + // An item with no name is still refused, without a name to quote. + const unnamed = await authoredKnowledgeSourceRefusal({ type: 'knowledge_source', item: {}, executionContext: AUTHOR, resolveKnowledgeService: () => undefined }); + expect(unnamed?.message).toMatch(/^The knowledge source was not saved: /); + }); + + it('no knowledge service registered: the engine\'s own write is not refused (a package install, a seed, a migration)', async () => { + const resolve = vi.fn(() => undefined); + expect(await authoredKnowledgeSourceRefusal({ type: 'knowledge_source', item: ITEM, executionContext: { isSystem: true }, resolveKnowledgeService: resolve })).toBeUndefined(); + expect(resolve).not.toHaveBeenCalled(); + }); + + it('a registered knowledge service without the member (not the platform\'s) judges nothing: the save goes on', async () => { + for (const service of [{}, { search: async () => [] }]) { expect(await authoredKnowledgeSourceRefusal({ type: 'knowledge_source', item: ITEM, executionContext: AUTHOR, resolveKnowledgeService: () => service })).toBeUndefined(); } }); diff --git a/packages/metadata-core/src/knowledge-source-save-admission.ts b/packages/metadata-core/src/knowledge-source-save-admission.ts index 59987a6c545..cd26e8f520d 100644 --- a/packages/metadata-core/src/knowledge-source-save-admission.ts +++ b/packages/metadata-core/src/knowledge-source-save-admission.ts @@ -29,9 +29,26 @@ * * - **Any other type**, and **the engine's own write** (`isSystem`: a package * install, a seed, a migration): the gates that need no principal at - * `os validate` and publish are their own card (topic #37000, row 4). - * - **A deployment with no knowledge service**, or one whose service is not - * the platform's: nothing loads the item there, so nothing is indexed. + * `os validate` and publish are their own card (topic #37000, row 4). A + * system write is never refused here, a deployment with no knowledge + * service included: the boot names such an item and its remedy + * (`knowledge-source-unserved.ts` in `@objectstack/objectql`). + * - **A registered knowledge service that is not the platform's** (one with + * no `admitAuthoredSource`, a host-mounted one for example): it answers for + * its own sources, and the save goes on. + * + * ## A deployment with no knowledge service + * + * Refused, not judged (ADR-0078 §1: a declaration that never takes effect is + * an error). Nothing loads, indexes or searches a `knowledge_source` there, + * and nothing mounts the service while the process runs: it is composed at + * boot, from `requires: ['knowledge']` in the stack. So an author's save there + * would be kept and never served, and the Studio, REST or MCP author would + * never see the boot line that says so. The refusal tells them at the save, + * with the remedy: declare the token, restart, then save + * ({@link noKnowledgeServiceRefusal}). `503 SERVICE_UNAVAILABLE`: the save + * needs a service this deployment does not run, the code the knowledge + * service itself answers for a store that is not mounted. Nothing was written. * * ## Fail direction * @@ -75,13 +92,35 @@ function unavailable(why: string): AuthoredKnowledgeSourceRefusal { }; } +/** + * The refusal of an author's `knowledge_source` save on a deployment that + * registers no knowledge service: what is wrong, and what makes the save take + * effect. The service is mounted at boot from the stack's `requires`, never + * 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'; + 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.', + }; +} + /** * The refusal of a `knowledge_source` save, or `undefined` when the save may * go on (the module doc says what is and is not judged). * * `resolveKnowledgeService` answers the request environment's `knowledge` - * service, `undefined` when none is registered, and throws when one is - * registered and cannot be resolved. + * service, `undefined` when none is registered (an author's save is then + * refused), 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. */ @@ -100,7 +139,8 @@ export async function authoredKnowledgeSourceRefusal(input: { } catch (err) { return unavailable(`the knowledge service could not be resolved: ${err instanceof Error ? err.message : String(err)}`); } - const admit = (service as Partial | null | undefined)?.admitAuthoredSource; + if (service === undefined || service === null) return noKnowledgeServiceRefusal(input.item); + const admit = (service as Partial).admitAuthoredSource; if (typeof admit !== 'function') return undefined; let verdict: AuthoredKnowledgeSourceVerdict; try { diff --git a/packages/objectql/src/knowledge-source-unserved.test.ts b/packages/objectql/src/knowledge-source-unserved.test.ts index fc722ca8890..d7ea3d2a8ed 100644 --- a/packages/objectql/src/knowledge-source-unserved.test.ts +++ b/packages/objectql/src/knowledge-source-unserved.test.ts @@ -20,6 +20,8 @@ describe('describeUnservedKnowledgeSources — items with no knowledge service ( expect(line).toContain('it is loaded, indexed or searched'); expect(line).toContain('@objectstack/service-knowledge'); expect(line).toContain('or remove the item.'); + // The remedy an author's save on such a deployment is refused with: the token, then a restart. + expect(line).toContain("Declare requires: ['knowledge'] in the stack and restart"); }); it(`names at most ${UNSERVED_KNOWLEDGE_SOURCES_NAMED} items, counts the rest, and says a name two packages hold once`, () => { diff --git a/packages/objectql/src/knowledge-source-unserved.ts b/packages/objectql/src/knowledge-source-unserved.ts index 073c6142ba0..aa50e2ec542 100644 --- a/packages/objectql/src/knowledge-source-unserved.ts +++ b/packages/objectql/src/knowledge-source-unserved.ts @@ -16,6 +16,16 @@ * A statement at `warn`, never a boot refusal: a package may ship a source to * a deployment that chose not to run retrieval, and its objects, pages and * flows must keep serving there. + * + * The remedy it names is the one an author's save is refused with on such a + * deployment (`authoredKnowledgeSourceRefusal`, `@objectstack/metadata-core`): + * `requires: ['knowledge']` in the stack, then a restart, since the service is + * composed at boot and never while the process runs. The items this line + * finds are ones the stack does not ship, since a `knowledgeSources` entry + * mounts the service by itself: they arrived by the engine's own write, + * which is never refused (a package + * installed after the boot, a seed, a migration), or were saved before the + * save refused them. */ import { KNOWLEDGE_SERVICE } from '@objectstack/spec/contracts'; @@ -40,12 +50,21 @@ export function describeUnservedKnowledgeSources(names: readonly string[], servi return ( `[ObjectQLPlugin] this deployment holds ${count} knowledge_source ${count === 1 ? 'item' : 'items'} ` + `(${shown}${rest > 0 ? `, and ${rest} more` : ''}), but no '${KNOWLEDGE_SERVICE}' service is registered, so ` + - `${count === 1 ? 'it is' : 'none is'} loaded, indexed or searched. Add KnowledgeServicePlugin ` + - '(@objectstack/service-knowledge) and a knowledge adapter to the composition, or remove the ' + + `${count === 1 ? 'it is' : 'none is'} loaded, indexed or searched. ${UNSERVED_REMEDY} or remove the ` + `${count === 1 ? 'item' : 'items'}.` ); } +/** + * What mounts the service for an item on a deployment that runs none: the + * token (or the plugin, for a host that composes its own kernel), then a + * restart. The same remedy an author's save there is refused with. + */ +const UNSERVED_REMEDY = + "Declare requires: ['knowledge'] in the stack and restart — the service and the deployment's store are mounted " + + 'at boot, never while the process runs — or, on a host that composes its own kernel, add KnowledgeServicePlugin ' + + '(@objectstack/service-knowledge) and a knowledge store;'; + /** What {@link announceUnservedKnowledgeSources} reads of its host. */ export interface UnservedKnowledgeSourcesHost { /** Resolve a kernel service by name; throws or answers nothing when none is registered. */ diff --git a/packages/rest/src/meta-item-write-routes.ts b/packages/rest/src/meta-item-write-routes.ts index c49b6546223..087813a0835 100644 --- a/packages/rest/src/meta-item-write-routes.ts +++ b/packages/rest/src/meta-item-write-routes.ts @@ -255,9 +255,12 @@ export function registerMetaItemWriteRoutes(this: MetaItemWriteRouteHost, scope: // themselves search what it would index — the knowledge // service's search-time gates, asked for the author before // anything is written (`authoredKnowledgeSourceRefusal`). - // Every other type passes untouched. `403` keeps this door's - // `FORBIDDEN` spelling; a verdict that cannot be reached is - // the gate's own `503`. + // On a deployment with no knowledge service the author's save + // is refused `503 SERVICE_UNAVAILABLE`, naming the remedy: + // nothing would load it, and the author never sees the boot + // line. Every other type passes untouched. `403` keeps this + // door's `FORBIDDEN` spelling; a verdict that cannot be + // reached is the gate's own `503`. { const refused = await authoredKnowledgeSourceRefusal({ type: req.params.type, diff --git a/packages/rest/src/meta-type-write-capability.test.ts b/packages/rest/src/meta-type-write-capability.test.ts index 5d3bdc92099..41b482f8d0c 100644 --- a/packages/rest/src/meta-type-write-capability.test.ts +++ b/packages/rest/src/meta-type-write-capability.test.ts @@ -472,6 +472,14 @@ describe('[ADR-0161 K4] a knowledge_source is written through /meta only beside it('a holder of both saves, publishes, rolls back and resets — each reaching the store', async () => { const { rest, store, protocol } = boot(BOTH); + // [ADR-0161 K4] The deployment mounts a knowledge service that admits every source: on one with + // none, an author's `knowledge_source` save is refused (ruled D), and this suite is about something else. + (rest as any).kernelServiceProvider = async (name: string) => { + if (name === 'knowledge') return { admitAuthoredSource: async () => ({ admitted: true }) }; + throw Object.assign(new Error(`Service '${name}' not found`), { + __objectstackServiceNotRegistered: true, code: 'SERVICE_NOT_REGISTERED', serviceName: name, + }); + }; const saved = await drive(rest, 'PUT', `${META}/:type/:name`, 'knowledge_source', 'faq', {}, FAQ); expect(saved.statusCode).toBe(200); expect(store.knowledge_source.faq).toEqual(FAQ); diff --git a/packages/rest/src/meta-write-door-capability-enumeration.test.ts b/packages/rest/src/meta-write-door-capability-enumeration.test.ts index 024abfea01b..44b536cc06e 100644 --- a/packages/rest/src/meta-write-door-capability-enumeration.test.ts +++ b/packages/rest/src/meta-write-door-capability-enumeration.test.ts @@ -706,14 +706,49 @@ describe('ADR-0161 K4 — the save door asks the knowledge service to admit the expect(stack.calls.saveMetaItem).toBe(0); }); - it('CONTROL: an admitted source is saved; with no knowledge service the save goes on', async () => { + /** + * Ruled D: on a deployment that registers no knowledge service, nothing + * loads, indexes or searches a source, and nothing mounts the service while + * the server runs. So an author's save is refused at the door, naming the + * reason and the remedy, instead of being kept and never served. + */ + it('no knowledge service registered: an author\'s save is refused 503 SERVICE_UNAVAILABLE with the remedy, and nothing is saved', async () => { + // The kernel registry's branded "never registered" miss (`isServiceNotRegisteredError`), + // and a server built with no kernel provider at all. The engine's own write is held at the + // predicate (`knowledge-source-save-admission.test.ts`): inbound HTTP never carries `isSystem`. + const unregistered = boot(AUTHOR); + (unregistered.rest as any).kernelServiceProvider = async (name: string) => { + throw Object.assign(new Error(`Service '${name}' not found`), { + __objectstackServiceNotRegistered: true, code: 'SERVICE_NOT_REGISTERED', serviceName: name, + }); + }; + for (const stack of [unregistered, boot(AUTHOR)]) { + const out = await stack.knock(asSource(SAVE)); + expect(out.status).toBe(503); + expect(out.body).toMatchObject({ + error: { + code: 'SERVICE_UNAVAILABLE', + message: expect.stringMatching(/^The knowledge source 'faq' was not saved: this deployment runs no knowledge service/), + }, + }); + expect(out.body).toMatchObject({ + error: { message: expect.stringMatching(/requires: \['knowledge'\].*restart the server.*then save the source again/) }, + }); + expect(stack.calls.saveMetaItem).toBe(0); + } + }); + + it('CONTROL: an admitted source is saved; a registered knowledge service that is not the platform\'s (no admitAuthoredSource) lets the save go on', async () => { const admitted = bootWith(AUTHOR, () => ({ admitted: true })); expect((await admitted.knock(asSource(SAVE))).status).not.toBe(403); expect(admitted.calls.saveMetaItem).toBe(1); - const none = boot(AUTHOR); - expect((await none.knock(asSource(SAVE))).status).not.toBe(403); - expect(none.calls.saveMetaItem).toBe(1); + const hostMounted = boot(AUTHOR); + (hostMounted.rest as any).kernelServiceProvider = async (name: string) => (name === 'knowledge' ? { search: async () => [] } : undefined); + const out = await hostMounted.knock(asSource(SAVE)); + expect(out.status).not.toBe(403); + expect(out.status).not.toBe(503); + expect(hostMounted.calls.saveMetaItem).toBe(1); }); it('the gate is behind the capability gates, and is not asked for another type', async () => { diff --git a/packages/rest/src/rest-server-meta-org-scope-url-spelling.test.ts b/packages/rest/src/rest-server-meta-org-scope-url-spelling.test.ts index 2edbb2f51ed..b4b6fdf9901 100644 --- a/packages/rest/src/rest-server-meta-org-scope-url-spelling.test.ts +++ b/packages/rest/src/rest-server-meta-org-scope-url-spelling.test.ts @@ -117,6 +117,14 @@ function boot(execCtx: any) { { api: { requireAuth: false } } as any, ); (rest as any).resolveExecCtx = async () => execCtx; + // [ADR-0161 K4] The deployment mounts a knowledge service that admits every source: on one with + // none, an author's `knowledge_source` save is refused (ruled D), and this suite is about something else. + (rest as any).kernelServiceProvider = async (name: string) => { + if (name === 'knowledge') return { admitAuthoredSource: async () => ({ admitted: true }) }; + throw Object.assign(new Error(`Service '${name}' not found`), { + __objectstackServiceNotRegistered: true, code: 'SERVICE_NOT_REGISTERED', serviceName: name, + }); + }; rest.registerRoutes(); const drive = async ( diff --git a/packages/rest/src/rest-server-meta-write-org-scope.test.ts b/packages/rest/src/rest-server-meta-write-org-scope.test.ts index 5e4375419a4..79379f5e875 100644 --- a/packages/rest/src/rest-server-meta-write-org-scope.test.ts +++ b/packages/rest/src/rest-server-meta-write-org-scope.test.ts @@ -87,6 +87,14 @@ function boot(execCtx: any) { { api: { requireAuth: false } } as any, ); (rest as any).resolveExecCtx = async () => execCtx; + // [ADR-0161 K4] The deployment mounts a knowledge service that admits every source: on one with + // none, an author's `knowledge_source` save is refused (ruled D), and this suite is about something else. + (rest as any).kernelServiceProvider = async (name: string) => { + if (name === 'knowledge') return { admitAuthoredSource: async () => ({ admitted: true }) }; + throw Object.assign(new Error(`Service '${name}' not found`), { + __objectstackServiceNotRegistered: true, code: 'SERVICE_NOT_REGISTERED', serviceName: name, + }); + }; rest.registerRoutes(); const drive = async ( diff --git a/packages/rest/src/rest-server.ts b/packages/rest/src/rest-server.ts index 95b77910ae0..5cd1517d870 100644 --- a/packages/rest/src/rest-server.ts +++ b/packages/rest/src/rest-server.ts @@ -6214,14 +6214,15 @@ export class RestServer { * [ADR-0161 K4, guard two] The request environment's `knowledge` service, * for the save door's source admission (`authoredKnowledgeSourceRefusal`): * `undefined` when none is registered (nothing loads a knowledge source - * there), a throw when one is registered and cannot be resolved (the door - * then refuses `503`, never proceeds). `unknown`, deliberately: the door - * reads the one member it asks structurally. + * there, so an author's save is refused `503`, naming the remedy), a + * throw when one is registered and cannot be resolved (the door then + * refuses `503`, never proceeds). `unknown`, deliberately: the door reads + * the one member it asks structurally. * * A server built with no `kernelServiceProvider` answers `undefined`, * quietly: `RestApiPlugin` always passes one, and a hand-built server * without it reaches no kernel service at all (its security and audit - * lookups read the same way), so there is no knowledge service to ask. + * lookups read the same way), so no knowledge service serves it either. */ private async resolveKnowledgeService( environmentId?: string, diff --git a/packages/runtime/src/domains/mcp-authoring.test.ts b/packages/runtime/src/domains/mcp-authoring.test.ts index 0e566776fb7..12b723e9cf8 100644 --- a/packages/runtime/src/domains/mcp-authoring.test.ts +++ b/packages/runtime/src/domains/mcp-authoring.test.ts @@ -998,7 +998,11 @@ describe('[ADR-0161 K4] a knowledge_source draft needs the human to hold manage_ }); it('CONTROL: a human holding both saves and discards; the same human still saves another type', async () => { - const { authoring, served } = await authorThroughDomain({ systemPermissions: ['manage_metadata', 'manage_knowledge_sources'] }); + // A deployment that mounts a knowledge service admitting the source (on one with none, ruled D refuses the save). + const { authoring, served } = await authorThroughDomain({ + systemPermissions: ['manage_metadata', 'manage_knowledge_sources'], + knowledge: { admitAuthoredSource: async () => ({ admitted: true }) }, + }); expect((await save(authoring)).isError).toBe(false); expect((await discard(authoring)).body).toEqual({ discarded: { type: 'knowledge_source', name: 'faq', package: 'com.acme.crm' } }); expect(served.protocolCalls.filter((c: any) => c[0] === 'saveMetaItem').map((c: any) => c[1].type)).toEqual(['knowledge_source']); @@ -1063,7 +1067,25 @@ describe('[ADR-0161 K4] save_metadata_draft asks the knowledge service to admit expect(served.protocolCalls.filter((c: any) => c[0] === 'saveMetaItem')).toEqual([]); }); - it('CONTROL: an admitted source is saved; another type is never asked about; no knowledge service judges nothing', async () => { + /** + * Ruled D: on a deployment that registers no knowledge service, nothing + * loads, indexes or searches a source, and nothing mounts the service while + * the server runs. So the human's draft save is refused, naming the reason + * and the remedy, instead of being kept and never served. + */ + it('no knowledge service registered: the draft save is refused 503 SERVICE_UNAVAILABLE with the remedy, and nothing is written', async () => { + const none = await authorThroughDomain({ systemPermissions: BOTH }); + const refused = await save(none.authoring); + expect(refused.isError).toBe(true); + expect(refused.body.error).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 }); + expect(refused.body.error.message).toMatch(/^The knowledge source 'faq' was not saved: this deployment runs no knowledge service/); + expect(refused.body.error.message).toMatch(/requires: \['knowledge'\].*restart the server.*then save the source again/); + expect(none.served.protocolCalls.filter((c: any) => c[0] === 'saveMetaItem')).toEqual([]); + // Another type saves as before on the same deployment. + expect((await call(none.authoring, 'save_metadata_draft', { type: 'flow', name: 'lead_intake', item: FLOW_DRAFT, package: 'com.acme.crm' })).isError).toBe(false); + }); + + it('CONTROL: an admitted source is saved; another type is never asked about; a registered knowledge service that is not the platform\'s judges nothing', async () => { const admitAuthoredSource = vi.fn(async () => ({ admitted: true })); const { authoring, served } = await authorThroughDomain({ systemPermissions: BOTH, knowledge: { admitAuthoredSource } }); expect((await save(authoring)).isError).toBe(false); @@ -1071,8 +1093,8 @@ describe('[ADR-0161 K4] save_metadata_draft asks the knowledge service to admit expect(admitAuthoredSource).toHaveBeenCalledTimes(1); expect(served.protocolCalls.filter((c: any) => c[0] === 'saveMetaItem').map((c: any) => c[1].type)).toEqual(['knowledge_source', 'flow']); - const none = await authorThroughDomain({ systemPermissions: BOTH }); - expect((await save(none.authoring)).isError).toBe(false); + const hostMounted = await authorThroughDomain({ systemPermissions: BOTH, knowledge: { search: async () => [] } }); + expect((await save(hostMounted.authoring)).isError).toBe(false); }); }); diff --git a/packages/runtime/src/domains/mcp-authoring.ts b/packages/runtime/src/domains/mcp-authoring.ts index 5517fc51955..86a11f3ba89 100644 --- a/packages/runtime/src/domains/mcp-authoring.ts +++ b/packages/runtime/src/domains/mcp-authoring.ts @@ -438,7 +438,8 @@ export interface OpenAuthoringWriter { * [ADR-0161 K4, guard two] The refusal of a `knowledge_source` save whose * author may not themselves search what it would index * (`authoredKnowledgeSourceRefusal`, judged for the admitted human), or - * `undefined` when the save may go on. Every other type answers `undefined`. + * on a deployment with no knowledge service, or `undefined` when the save + * may go on. Every other type answers `undefined`. */ itemSaveRefusal(type: string, item: unknown): Promise<{ code: ErrorCode; message: string; status: number } | undefined>; } @@ -674,8 +675,9 @@ function openWriter( // The human the door admitted: their grants, never the envelope's. executionContext: reader, // The classified lookup (`resolveServiceOrLoud`): an absent - // service answers `undefined`, a registered one that cannot be - // resolved rejects and the predicate answers `503`. + // 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), }); if (!refused) return undefined; 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 4ea3b20710e..57474a2e150 100644 --- a/packages/runtime/src/domains/meta-save-capability-gate.test.ts +++ b/packages/runtime/src/domains/meta-save-capability-gate.test.ts @@ -343,21 +343,37 @@ describe('ADR-0161 K4 — dispatcher PUT asks the knowledge service to admit the expect(stack.saveMetaItem).not.toHaveBeenCalled(); }); - it('CONTROL: on the same kernel with no knowledge service registered, the save goes on', async () => { + /** + * Ruled D: on a deployment that registers no knowledge service, nothing + * loads, indexes or searches a source, and nothing mounts the service while + * the server runs. So an author's save is refused at the door, naming the + * reason and the remedy, instead of being kept and never served. + */ + it('on the same kernel with no knowledge service registered, an author\'s save is refused 503 SERVICE_UNAVAILABLE with the remedy, and nothing is saved', async () => { const stack = bootOnKernel('never-registered'); const res = await stack.dispatcher.handleMetadata('/knowledge_source/faq', ctx(AUTHOR), 'PUT', copy(SOURCE)); - expect(res.response?.status).toBe(200); - expect(stack.saveMetaItem).toHaveBeenCalledTimes(1); + 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: this deployment runs no knowledge service/); + expect(res.response?.body?.error?.message).toMatch(/requires: \['knowledge'\].*restart the server.*then save the source again/); + expect(stack.saveMetaItem).not.toHaveBeenCalled(); + + // The double whose registry answers nothing for the name: the same refusal. + const none = bootWith(); + expect((await put(none, AUTHOR)).response?.status).toBe(503); + expect(none.saveMetaItem).not.toHaveBeenCalled(); }); - it('CONTROL: an admitted source is saved; with no knowledge service the save goes on', async () => { + it('CONTROL: an admitted source is saved; a registered knowledge service that is not the platform\'s (no admitAuthoredSource) lets the save go on', async () => { const admitted = bootWith(() => ({ admitted: true })); expect((await put(admitted, AUTHOR)).response?.status).toBe(200); expect(admitted.saveMetaItem).toHaveBeenCalledTimes(1); - const none = bootWith(); - expect((await put(none, AUTHOR)).response?.status).toBe(200); - expect(none.saveMetaItem).toHaveBeenCalledTimes(1); + const saveMetaItem = vi.fn(async ({ name }: any) => ({ success: true, name })); + const services: Record = { protocol: { saveMetaItem }, knowledge: { search: async () => [] } }; + const hostMounted = new HttpDispatcher({ context: { getService: (n: string) => services[n] ?? null } } as any); + expect((await hostMounted.handleMetadata('/knowledge_source/faq', ctx(AUTHOR), 'PUT', copy(SOURCE))).response?.status).toBe(200); + expect(saveMetaItem).toHaveBeenCalledTimes(1); }); it('the gate is behind the capability gates, and is not asked for another type', async () => { diff --git a/packages/runtime/src/domains/meta-type-write-capability-parity.test.ts b/packages/runtime/src/domains/meta-type-write-capability-parity.test.ts index af357a1e6a0..fd4b36c1193 100644 --- a/packages/runtime/src/domains/meta-type-write-capability-parity.test.ts +++ b/packages/runtime/src/domains/meta-type-write-capability-parity.test.ts @@ -65,6 +65,9 @@ function storeAndProtocol() { return { store, protocol, calls }; } +/** [ADR-0161 K4] Both transports run on a deployment that mounts a knowledge service admitting every source. */ +const KNOWLEDGE_ADMITS = { admitAuthoredSource: async () => ({ admitted: true }) }; + const security = { resolvePermissionSetNames: async () => [], getMetadataReadableFields: async () => [] }; interface Answer { status: number; code?: string } @@ -72,7 +75,9 @@ interface Answer { status: number; code?: string } function bootDispatcher(callerName: CallerName) { const { store, protocol, calls } = storeAndProtocol(); const list = vi.fn(async (type: string) => Object.values(store[singular(type)] ?? {}).map(clone)); - const services: Record = { protocol, security, metadata: { getPublished: async () => undefined, list } }; + // [ADR-0161 K4] The deployment mounts a knowledge service that admits every source: on one with + // none, an author's `knowledge_source` save is refused (ruled D), and this suite is about something else. + const services: Record = { protocol, security, metadata: { getPublished: async () => undefined, list }, knowledge: KNOWLEDGE_ADMITS }; const get = (n: string) => services[n] ?? null; const kernel: any = { context: { getService: get }, getService: get, getServiceAsync: async (n: string) => get(n) }; const dispatcher = new HttpDispatcher(kernel); @@ -106,6 +111,12 @@ function bootRest(callerName: CallerName) { const { store, protocol, calls } = storeAndProtocol(); const rest: any = new RestServer(createMockServer() as any, protocol as any, {} as any); rest.resolveExecCtx = async () => clone(CALLERS[callerName]); + rest.kernelServiceProvider = async (name: string) => { + if (name === 'knowledge') return KNOWLEDGE_ADMITS; + throw Object.assign(new Error(`Service '${name}' not found`), { + __objectstackServiceNotRegistered: true, code: 'SERVICE_NOT_REGISTERED', serviceName: name, + }); + }; rest.registerRoutes(); /** `path` is the dispatcher's spelling (`/meta/:type/:name`), mapped onto the REST item route. */ const send = async (method: string, path: string, body?: unknown): Promise => { diff --git a/packages/runtime/src/domains/meta.ts b/packages/runtime/src/domains/meta.ts index ee83e1bfcdd..905863dda3e 100644 --- a/packages/runtime/src/domains/meta.ts +++ b/packages/runtime/src/domains/meta.ts @@ -1984,8 +1984,10 @@ export async function handleMetadataRequest(deps: DomainHandlerDeps, path: strin // search what it would index — the knowledge service's search-time // gates, asked for the author before anything is written // (`authoredKnowledgeSourceRefusal`, the predicate `RestServer`'s - // `PUT` and the MCP draft save ask). Every other type passes - // untouched. + // `PUT` and the MCP draft save ask). On a deployment with no + // knowledge service the author's save is refused `503 + // SERVICE_UNAVAILABLE`, naming the remedy. Every other type + // passes untouched. { const refused = await authoredKnowledgeSourceRefusal({ type, @@ -1993,7 +1995,7 @@ export async function handleMetadataRequest(deps: DomainHandlerDeps, path: strin executionContext: _context.executionContext, // The classified lookup, not the `resolveService` probe: // a name nothing registered answers `undefined` (no - // knowledge service, nothing to ask), and a service that + // knowledge service: the save is refused), and a service that // is registered and cannot be resolved rejects, which the // predicate answers `503`. resolveKnowledgeService: () => 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 9baf9fcae0e..43d526b371c 100644 --- a/packages/runtime/src/domains/packages-knowledge-source-gate.test.ts +++ b/packages/runtime/src/domains/packages-knowledge-source-gate.test.ts @@ -148,7 +148,9 @@ describe('/packages — a package that holds a knowledge source is written by a }); it(`${door.name}: a holder of both capabilities goes on, and the capability gate reads no draft listing for it`, async () => { - const s = make({ items: [SOURCE_ITEM], drafts: [SOURCE_DRAFT] }); + // A host that mounts a knowledge service admitting each source: the duplicate copies them as the caller, + // and on a host with none a duplicate that copies one is refused (ruled D, pinned below). + const s = make({ items: [SOURCE_ITEM], drafts: [SOURCE_DRAFT] }, { admitAuthoredSource: async () => ({ admitted: true }) }); const r = await call(s, door, authed(BOTH, door.tenantId)); expect(r.response?.status).not.toBe(403); expect(door.target(s)).toHaveBeenCalled(); @@ -270,7 +272,7 @@ describe('/packages — duplicate admits each knowledge source it copies for the expect(unread.protocol.duplicatePackage).not.toHaveBeenCalled(); }); - it('CONTROL: admitted sources are copied; a package with none, and a host with no knowledge service, copy as before', async () => { + it('CONTROL: admitted sources are copied; a package with none copies as before', async () => { const admitted = withKnowledge({ items: [SOURCE_ITEM] }, () => ({ admitted: true })); expect((await call(admitted, DUPLICATE, authed(BOTH))).response?.status).not.toBe(403); expect(admitted.protocol.duplicatePackage).toHaveBeenCalled(); @@ -279,10 +281,31 @@ describe('/packages — duplicate admits each knowledge source it copies for the expect((await call(none, DUPLICATE, authed(METADATA_ONLY))).response?.status).not.toBe(403); expect(none.admitAuthoredSource).not.toHaveBeenCalled(); expect(none.protocol.duplicatePackage).toHaveBeenCalled(); + }); + /** + * The duplicate saves each source again, for the caller, through the + * predicate the `/meta` save asks: on a deployment with no knowledge + * service the copy of a source would be kept and never served, so the + * duplicate is refused as the save is, naming the remedy. + */ + it('a host with no knowledge service refuses a duplicate that copies a source 503, naming the remedy, and nothing is copied', async () => { const noService = make({ items: [SOURCE_ITEM] }); - expect((await call(noService, DUPLICATE, authed(BOTH))).response?.status).not.toBe(403); - expect(noService.protocol.duplicatePackage).toHaveBeenCalled(); + 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']"); + expect(noService.protocol.duplicatePackage).not.toHaveBeenCalled(); + + // A package with no source, and the engine's own call, copy as before. + const none = make({ items: [] }); + expect((await call(none, DUPLICATE, authed(BOTH))).response?.status).not.toBe(503); + expect(none.protocol.duplicatePackage).toHaveBeenCalled(); + const engine = make({ items: [SOURCE_ITEM] }); + expect((await call(engine, DUPLICATE, system())).response?.status).not.toBe(503); + expect(engine.protocol.duplicatePackage).toHaveBeenCalled(); }); it('the engine\'s own call is not asked', async () => { diff --git a/packages/runtime/src/meta-write-org-scope.test.ts b/packages/runtime/src/meta-write-org-scope.test.ts index 4b901cc6cad..27a9d11594f 100644 --- a/packages/runtime/src/meta-write-org-scope.test.ts +++ b/packages/runtime/src/meta-write-org-scope.test.ts @@ -256,6 +256,9 @@ function makeDispatcher( const services: Record = { protocol, objectql: { registry: engine.registry }, + // [ADR-0161 K4] The deployment mounts a knowledge service that admits every source: on one with + // none, an author's `knowledge_source` save is refused (ruled D), and this suite is about something else. + knowledge: { admitAuthoredSource: async () => ({ admitted: true }) }, ...(metadataService ? { metadata: metadataService } : {}), auth: { api: { 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 new file mode 100644 index 00000000000..0a55d219544 --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/19.knowledge-source-save-refused-without-knowledge-service.ts @@ -0,0 +1,32 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// The upgrade-guide entry of the save refusal for a `knowledge_source` on a +// deployment that registers no knowledge service (ADR-0161 K4, ADR-0078 §1). +// Notice only: the schema is unchanged, no key is removed and no D2 conversion +// exists, because the fix is the deployment's composition, never the item. +export const entry: SemanticMigration = { + id: 'knowledge-source-save-refused-without-knowledge-service', + 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`', + 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, ' + + 'then save the source', + reason: + 'On a deployment with no knowledge service nothing loads, indexes or searches a knowledge source, and nothing ' + + 'mounts the service while the server runs: it is composed at boot. Such a save used to be accepted and was ' + + 'never served, and only a boot log line said so, which a Studio, REST or MCP author does not see. It is now ' + + 'refused at the save, 503 SERVICE_UNAVAILABLE, naming the reason and the fix; nothing is written. The ' + + '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.', +};