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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions .changeset/37983-knowledge-source-save-needs-the-service.md
Original file line number Diff line number Diff line change
@@ -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

<!-- adr-0087: registered knowledge-source-save-refused-without-knowledge-service -->

**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.
3 changes: 2 additions & 1 deletion content/docs/ai/knowledge-rag.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down
25 changes: 20 additions & 5 deletions content/docs/protocol/knowledge.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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`
Expand Down
30 changes: 26 additions & 4 deletions packages/metadata-core/src/knowledge-source-save-admission.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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();
}
});
Expand Down
52 changes: 46 additions & 6 deletions packages/metadata-core/src/knowledge-source-save-admission.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
*
Expand Down Expand Up @@ -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. */
Expand All @@ -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<KnowledgeSourceSaveAdmitter> | null | undefined)?.admitAuthoredSource;
if (service === undefined || service === null) return noKnowledgeServiceRefusal(input.item);
const admit = (service as Partial<KnowledgeSourceSaveAdmitter>).admitAuthoredSource;
if (typeof admit !== 'function') return undefined;
let verdict: AuthoredKnowledgeSourceVerdict;
try {
Expand Down
2 changes: 2 additions & 0 deletions packages/objectql/src/knowledge-source-unserved.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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`, () => {
Expand Down
23 changes: 21 additions & 2 deletions packages/objectql/src/knowledge-source-unserved.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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. */
Expand Down
9 changes: 6 additions & 3 deletions packages/rest/src/meta-item-write-routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Loading
Loading