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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
---
'@objectstack/service-knowledge': minor
'@objectstack/spec': minor
---

feat(knowledge)!: refuse a knowledge_source save that names an adapter the running deployment does not mount

Clause-②: no (narrowing)
Metadata-protocol: narrowed
Skills-docs: none — no page under `skills/**` teaches a knowledge source's `adapter`; `content/docs/ai/knowledge-rag.mdx` and `content/docs/protocol/knowledge.mdx` name the save refusal

<!-- adr-0087: registered knowledge-source-unmounted-adapter-refused-at-save -->

**BREAKING** for an author or agent that saves a `knowledge_source` whose `adapter` names a store the running deployment does not mount (a retired store such as `ragflow`, or a typo): `PUT /api/v1/meta/knowledge_source/:name`, Studio, the MCP `save_metadata_draft` tool and a package duplicate now answer `400 VALIDATION_ERROR` where the save answered success, and nothing is written. The message names the source, the adapter and the mounted adapters. Fix: name one of the mounted adapters as the source's `adapter`, leave `adapter` out so the deployment's store holds it, or mount the named store and save again.

Before, the save was stored, the boot named the source at `error`, and every index and search of it answered `503 SERVICE_UNAVAILABLE`. A source already stored is not touched: it keeps answering `503` until it is saved with a mounted adapter.

Not moved: a source that leaves `adapter` out (it is placed on the deployment's store; several adapters and none the deployment's is still refused as before); a source naming a mounted adapter; the engine's own write, so a package install or a seed; a source registered in code (`KnowledgeServicePlugin({ sources })`, `registerSource`), which registers before its store starts; and `objectstack validate`, which runs with no deployment. For those three the boot's `error` line and the `503` at index and search stay the signal. Migration entry `knowledge-source-unmounted-adapter-refused-at-save` (`@objectstack/spec`) carries it for the upgrade guide.
2 changes: 1 addition & 1 deletion content/docs/ai/knowledge-rag.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ Which store is mounted depends on the platform database:

- **Sources are metadata**: list them under `knowledgeSources` ([below](#writing-a-source)). A source needs no `adapter`: one left out is held by the store in this table — the deployment's store — so the same source builds on SQLite under `os dev`, on PostgreSQL and on a hosted environment. Name an adapter only to place a source on another store you mounted.
- **Two stores and none the deployment's** (a host that mounts the service and two adapters itself): a source that names no adapter is refused when it is registered or saved — `VALIDATION_ERROR` (400), naming the adapters to choose from.
- **A source naming a store that is not mounted** does not stop the boot: the server logs one error naming the source and the stores that are mounted, and indexing or searching that source answers `SERVICE_UNAVAILABLE` (503) with the same choices; `search_knowledge` lists it in `refused`.
- **A source naming a store that is not mounted** (a retired store such as `ragflow`, or a typo) is refused when it is saved in Studio, over `PUT /meta/knowledge_source` or through MCP: `VALIDATION_ERROR` (400), naming the source, the adapter and the stores that are mounted. A source that leaves `adapter` out is not refused for it. That save check does not reach a package install, a source registered in code or `os validate`; such a source does not stop the boot: the server logs one error naming the source and the stores that are mounted, and indexing or searching that source answers `SERVICE_UNAVAILABLE` (503) with the same choices; `search_knowledge` lists it in `refused`.
- **The embedder** comes from Settings → AI & Embedder ([below](#configuring-the-embedder-from-settings)).
- **Another libSQL store** for the `turso` case: save its URL as `turso_url` (and `turso_auth_token` for a managed `libsql://` database) in Settings → Knowledge, then restart. A `file:` URL saved there must name a file inside that same data directory, and a URL carrying a NUL byte or another control character, written out or percent-encoded (`%00`), is refused, as is a token carrying one (a pasted line break counts); either way the store answers `SERVICE_UNAVAILABLE` saying why, and the boot goes on.
- **Where the file is**: `os start --home` and `OS_HOME` move it with the default database, so on a container put `OS_HOME` on a volume and the index survives a redeploy. A database named by URL (`OS_DATABASE_URL`) does not move it.
Expand Down
11 changes: 8 additions & 3 deletions content/docs/protocol/knowledge.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -166,8 +166,12 @@ A source binds to an **adapter id** (e.g. `'pgvector'`, `'turso'`,
`'memory'`), resolved at run time to the plugin that registered itself under
that name (ADR-0161 K4):

- **Named** — that adapter. One that is not mounted is refused at index and
search, `SERVICE_UNAVAILABLE` (503), naming the adapters that are.
- **Named** — that adapter. One that is not mounted is refused at its save
(the `/meta` and MCP save doors), `VALIDATION_ERROR` (400), naming the
source, the adapter and the adapters that are. A package install, a source
registered in code and `os validate` are not judged there; such a source is
named at boot at `error` and refused at index and search,
`SERVICE_UNAVAILABLE` (503), naming the adapters that are.
- **Omitted** — the deployment's adapter: the store the runtime mounted beside
the service (`pgvector` on PostgreSQL, `turso` otherwise; the runtime passes
`KnowledgeServicePlugin` its `deploymentAdapter` option when it mounts both),
Expand Down Expand Up @@ -231,7 +235,8 @@ and the MCP draft door:
as the author: an object of a disabled package, an object the API does not
serve for `search`, a system object without `enable.aiReadable`, or a field
the author may not query refuses the save `403`, naming the object or the
field. The fields judged are the ones the source serves (`content`,
field; an `adapter` naming no mounted store refuses it `400`, naming the
source, the adapter and the mounted ones. The fields judged are the ones the source serves (`content`,
`metadataFields`, the title field) and the ones its `where` reads. A
verdict that cannot be reached, or a knowledge service that is registered
and cannot be resolved, refuses `503`; nothing is written.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
//
// [ADR-0161 K4] A `knowledge_source` whose `adapter` names a store this
// deployment does not mount is refused at its save, on a REAL booted showcase
// (the knowledge service and its one store, `memory`):
//
// - `PUT /meta/knowledge_source/:name` answers `400 VALIDATION_ERROR`, naming
// the source, the adapter and the mounted stores; nothing is stored;
// - the MCP `save_metadata_draft` tool refuses the same save the same way,
// and no draft is stored.
//
// CONTROLS, at both doors: a source naming the mounted store, and one that
// leaves `adapter` out (the one store holds it), save as before.
//
// Before, both saves answered success, and the source was named only by the
// boot's `error` line and by the `503` its index and search answered.
//
// Not judged at these doors: a package install (the engine's own write), a
// source registered in code and `os validate`.
//
// The verify harness mounts no MCP server, so this file mounts one, as
// `objectstack dev` and `serve` do. The draft door is served only to an OAuth
// agent granted `metadata:write` whose user holds the authoring capability,
// and that agent holds its user's system capabilities only under
// `actions:execute`, so the MCP calls present a REAL access token with both
// scopes (DCR, authorize with the MCP resource, consent, token).
//
// The file is ISOLATED: it writes `/meta`, creates a package and sets
// `OS_OIDC_PROVIDER_ENABLED` for its boot.

import { createHash, randomBytes } from 'node:crypto';
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { MCPServerPlugin } from '@objectstack/mcp';
import { type VerifyStack } from '@objectstack/verify';
import { bootShowcase } from './showcase-boot.js';

const OPERATOR = { email: 'admin@objectos.ai', password: 'admin123' };
const AGENT_SCOPE = 'openid profile email offline_access metadata:write actions:execute';
const REDIRECT_URI = 'http://127.0.0.1:33421/callback';
/** A writable package the drafts are saved into (the showcase's own is read-only). */
const DRAFT_PACKAGE = 'com.dogfood.ksadapter';

/** A source over the showcase's tasks, as the showcase's own `showcase_task_notes`, with the given `adapter`. */
const sourceBody = (name: string, adapter?: string) => ({
name,
label: name,
...(adapter === undefined ? {} : { adapter }),
source: { kind: 'object', object: 'showcase_task', content: ['title', 'notes'], metadataFields: ['status', 'priority'] },
});

async function mintAgentToken(stack: VerifyStack): Promise<string> {
const authSvc: any = await stack.kernel.getServiceAsync('auth');
const resource = authSvc.getMcpResourceUrl();
const reg = await stack.api('/auth/oauth2/register', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
client_name: 'knowledge adapter save probe', redirect_uris: [REDIRECT_URI], grant_types: ['authorization_code', 'refresh_token'],
response_types: ['code'], token_endpoint_auth_method: 'none', application_type: 'native', scope: AGENT_SCOPE,
}),
});
const regBody: any = await reg.json();
expect(reg.status, JSON.stringify(regBody)).toBe(201);
const signin = await stack.api('/auth/sign-in/email', {
method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(OPERATOR),
});
expect(signin.status, await signin.clone().text()).toBe(200);
const cookie = ((signin.headers as any).getSetCookie() as string[]).map((c) => c.split(';')[0]).join('; ');
const verifier = randomBytes(32).toString('base64url');
const challenge = createHash('sha256').update(verifier).digest('base64url');
const qs = new URLSearchParams({
client_id: regBody.client_id, redirect_uri: REDIRECT_URI, response_type: 'code', scope: AGENT_SCOPE, state: 'st',
code_challenge: challenge, code_challenge_method: 'S256', resource,
});
const az = await stack.api(`/auth/oauth2/authorize?${qs}`, { headers: { cookie }, redirect: 'manual' });
const loc = az.headers.get('location') ?? '';
let code = new URL(loc, 'http://localhost:3000').searchParams.get('code');
if (!code) {
const consent = await stack.api('/auth/oauth2/consent', {
method: 'POST',
headers: { 'content-type': 'application/json', cookie, origin: 'http://localhost:3000' },
body: JSON.stringify({ accept: true, oauth_query: loc.slice(loc.indexOf('?')) }),
});
const cb: any = await consent.json().catch(() => null);
code = new URL(cb?.redirect_uri ?? cb?.url).searchParams.get('code');
}
const tok = await stack.api('/auth/oauth2/token', {
method: 'POST',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'authorization_code', code: code!, redirect_uri: REDIRECT_URI, client_id: regBody.client_id, code_verifier: verifier, resource,
}).toString(),
});
const tj: any = await tok.json();
expect(tok.status, JSON.stringify(tj)).toBe(200);
return String(tj.access_token);
}

describe('[ADR-0161 K4] a knowledge_source naming an adapter the deployment does not mount is refused at its save', () => {
let stack: VerifyStack;
let admin = '';
let agent = '';
const priorOidc = process.env.OS_OIDC_PROVIDER_ENABLED;

const put = async (name: string, body: unknown) => {
const res = await stack.apiAs(admin, 'PUT', `/meta/knowledge_source/${name}`, body);
const json: any = await res.json().catch(() => ({}));
return { status: res.status, error: json?.error, json };
};
const saveDraft = async (name: string, item: unknown) => {
const res = await stack.api('/mcp', {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream', Authorization: `Bearer ${agent}` },
body: JSON.stringify({
jsonrpc: '2.0', id: 1, method: 'tools/call',
params: { name: 'save_metadata_draft', arguments: { type: 'knowledge_source', name, item, package: DRAFT_PACKAGE } },
}),
});
expect(res.status, await res.clone().text()).toBe(200);
const rpc: any = await res.json();
expect(rpc.error, JSON.stringify(rpc.error)).toBeUndefined();
const text = String(rpc.result?.content?.[0]?.text ?? '');
let payload: any;
try { payload = JSON.parse(text); } catch { payload = { message: text }; }
return { isError: rpc.result?.isError === true, payload, text };
};
const knowledge = async () => stack.kernel.getServiceAsync<any>('knowledge');

beforeAll(async () => {
process.env.OS_OIDC_PROVIDER_ENABLED = 'true';
stack = await bootShowcase({ extraPlugins: [new MCPServerPlugin()] });
admin = await stack.signIn();
const created = await stack.apiAs(admin, 'POST', '/packages', {
manifest: { id: DRAFT_PACKAGE, name: 'Knowledge adapter drafts', version: '0.1.0', type: 'app', namespace: 'ksadapter' },
});
expect(created.status, await created.clone().text()).toBe(201);
agent = await mintAgentToken(stack);
}, 180_000);

afterAll(async () => {
await stack?.stop();
if (priorOidc === undefined) delete process.env.OS_OIDC_PROVIDER_ENABLED;
else process.env.OS_OIDC_PROVIDER_ENABLED = priorOidc;
});

it('the booted deployment mounts one store, memory', async () => {
expect((await knowledge()).listAdapters()).toEqual(['memory']);
});

it('PUT /meta/knowledge_source refuses a retired or mistyped adapter 400 VALIDATION_ERROR, naming the source, the adapter and the mounted stores; nothing is stored', async () => {
for (const [name, adapter] of [['ks_retired_store', 'ragflow'], ['ks_typo_store', 'memroy']] as const) {
const saved = await put(name, sourceBody(name, adapter));
expect(saved.status, JSON.stringify(saved.json)).toBe(400);
expect(saved.error, JSON.stringify(saved.json)).toMatchObject({ code: 'VALIDATION_ERROR' });
const message = String(saved.error?.message ?? '');
expect(message).toContain(name);
expect(message).toContain(`names adapter '${adapter}', which this deployment does not mount (mounted: memory)`);
expect((await stack.apiAs(admin, 'GET', `/meta/knowledge_source/${name}`)).status, name).toBe(404);
expect((await knowledge()).listSources().map((s: { name: string }) => s.name), name).not.toContain(name);
}
});

it('save_metadata_draft refuses the same save 400 VALIDATION_ERROR, and no draft is stored', async () => {
const refused = await saveDraft('ks_draft_retired_store', sourceBody('ks_draft_retired_store', 'ragflow'));
expect(refused.isError, refused.text).toBe(true);
expect(refused.payload.error, refused.text).toMatchObject({ code: 'VALIDATION_ERROR', status: 400 });
expect(String(refused.payload.error?.message)).toContain("names adapter 'ragflow', which this deployment does not mount (mounted: memory)");
const draft = await stack.apiAs(admin, 'GET', `/meta/knowledge_source/ks_draft_retired_store?state=draft&package=${DRAFT_PACKAGE}`);
expect(draft.status, await draft.clone().text()).toBe(404);
});

it('CONTROL: a source naming the mounted store, and one leaving `adapter` out, save at both doors', async () => {
for (const [name, adapter] of [['ks_named_store', 'memory'], ['ks_omitted_store', undefined]] as const) {
const saved = await put(name, sourceBody(name, adapter));
expect(saved.status, JSON.stringify(saved.json)).toBe(200);
const drafted = await saveDraft(`${name}_draft`, sourceBody(`${name}_draft`, adapter));
expect(drafted.isError, drafted.text).toBe(false);
expect(drafted.payload.saved, drafted.text).toMatchObject({ type: 'knowledge_source', name: `${name}_draft`, package: DRAFT_PACKAGE });
}
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -1000,6 +1000,7 @@ describe('admitAuthoredSource — source admission at save, as the authoring pri
.toMatchObject({ admitted: false, code: 'SERVICE_UNAVAILABLE', status: 503 });

const noEngine = new KnowledgeService({});
noEngine.registerAdapter('memory', makeAdapter());
expect(await noEngine.admitAuthoredSource(item('ticket', ['body']), MANAGER))
.toMatchObject({ admitted: false, code: 'SERVICE_UNAVAILABLE', status: 503 });
});
Expand All @@ -1013,6 +1014,51 @@ describe('admitAuthoredSource — source admission at save, as the authoring pri
}
});

// [ADR-0161 K4] The store a source names must be one this deployment mounts:
// a retired adapter ('ragflow') or a typo is refused at the save, not left to
// the boot's error line and a search's 503.
it('a source naming an adapter the deployment does not mount is refused VALIDATION_ERROR / 400, naming the source, the adapter and the mounted ones', async () => {
const { svc } = setup({ sources: [], security: salaryHiddenFromMembers });
for (const adapter of ['ragflow', 'memroy', '']) {
const verdict = await svc.admitAuthoredSource({ ...item('ticket', ['body']), adapter }, MANAGER);
expect(verdict, adapter).toMatchObject({ admitted: false, code: 'VALIDATION_ERROR', status: 400, object: 'ticket' });
const message = (verdict as { message: string }).message;
expect(message).toContain('knowledge source "authored" was not saved');
expect(message).toContain(`names adapter '${adapter}', which this deployment does not mount (mounted: memory)`);
}
// Refused before the gates are asked: an author the field gate would refuse hears the adapter first.
expect(await svc.admitAuthoredSource({ ...item('ticket', ['body', 'salary_note']), adapter: 'ragflow' }, MEMBER))
.toMatchObject({ admitted: false, code: 'VALIDATION_ERROR', status: 400 });
// The engine's own write (a package install) is not judged at this door.
expect(await svc.admitAuthoredSource({ ...item('ticket', ['body']), adapter: 'ragflow' }, SYSTEM)).toEqual({ admitted: true });
});

it('with no adapter mounted, a named one is refused naming none mounted; with two, both are named', async () => {
const bare = new KnowledgeService({ dataEngine: makeEngine([TICKET]) });
expect(await bare.admitAuthoredSource(item('ticket', ['body']), MANAGER)).toMatchObject({
admitted: false, code: 'VALIDATION_ERROR', status: 400,
message: expect.stringContaining("names adapter 'memory', which this deployment does not mount (mounted: none)"),
});
const { svc } = setup({ sources: [] });
svc.registerAdapter('turso', makeAdapter());
expect(await svc.admitAuthoredSource({ ...item('ticket', ['body']), adapter: 'pgvector' }, MANAGER)).toMatchObject({
admitted: false, code: 'VALIDATION_ERROR', status: 400,
message: expect.stringContaining("(mounted: memory, turso)"),
});
});

it('CONTROL: a source naming a mounted adapter, and one that leaves `adapter` out, are admitted', async () => {
const { svc } = setup({ sources: [] });
svc.registerAdapter('turso', makeAdapter());
expect(await svc.admitAuthoredSource(item('ticket', ['body']), MANAGER)).toEqual({ admitted: true });
expect(await svc.admitAuthoredSource({ ...item('ticket', ['body']), adapter: 'turso' }, MANAGER)).toEqual({ admitted: true });
const placed = new KnowledgeService({ dataEngine: makeEngine([TICKET]), deploymentAdapter: 'turso' });
placed.registerAdapter('turso', makeAdapter());
placed.registerAdapter('memory', makeAdapter());
const { adapter: _omitted, ...omitted } = item('ticket', ['body']);
expect(await placed.admitAuthoredSource(omitted, MANAGER)).toEqual({ admitted: true });
});

it('registers nothing and searches nothing: the verdict is a read', async () => {
const { svc, adapter } = setup({ sources: [], security: salaryHiddenFromMembers });
await svc.admitAuthoredSource(item('ticket', ['body']), MANAGER);
Expand Down
Loading
Loading