Skip to content

Commit 0b2a3bc

Browse files
committed
test(dogfood), docs, changeset: the unmounted-adapter save refusal at both doors, its docs and migration entry
Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP
1 parent 993cd89 commit 0b2a3bc

5 files changed

Lines changed: 239 additions & 4 deletions

File tree

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
---
2+
'@objectstack/service-knowledge': minor
3+
'@objectstack/spec': minor
4+
---
5+
6+
feat(knowledge)!: refuse a knowledge_source save that names an adapter the running deployment does not mount
7+
8+
Clause-②: no (narrowing)
9+
Metadata-protocol: narrowed
10+
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
11+
12+
<!-- adr-0087: registered knowledge-source-unmounted-adapter-refused-at-save -->
13+
14+
**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.
15+
16+
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.
17+
18+
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.

‎content/docs/ai/knowledge-rag.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ Which store is mounted depends on the platform database:
3232

3333
- **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.
3434
- **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.
35-
- **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`.
35+
- **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`.
3636
- **The embedder** comes from Settings → AI & Embedder ([below](#configuring-the-embedder-from-settings)).
3737
- **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.
3838
- **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.

‎content/docs/protocol/knowledge.mdx‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -166,8 +166,12 @@ A source binds to an **adapter id** (e.g. `'pgvector'`, `'turso'`,
166166
`'memory'`), resolved at run time to the plugin that registered itself under
167167
that name (ADR-0161 K4):
168168

169-
- **Named** — that adapter. One that is not mounted is refused at index and
170-
search, `SERVICE_UNAVAILABLE` (503), naming the adapters that are.
169+
- **Named** — that adapter. One that is not mounted is refused at its save
170+
(the `/meta` and MCP save doors), `VALIDATION_ERROR` (400), naming the
171+
source, the adapter and the adapters that are. A package install, a source
172+
registered in code and `os validate` are not judged there; such a source is
173+
named at boot at `error` and refused at index and search,
174+
`SERVICE_UNAVAILABLE` (503), naming the adapters that are.
171175
- **Omitted** — the deployment's adapter: the store the runtime mounted beside
172176
the service (`pgvector` on PostgreSQL, `turso` otherwise; the runtime passes
173177
`KnowledgeServicePlugin` its `deploymentAdapter` option when it mounts both),
@@ -231,7 +235,8 @@ and the MCP draft door:
231235
as the author: an object of a disabled package, an object the API does not
232236
serve for `search`, a system object without `enable.aiReadable`, or a field
233237
the author may not query refuses the save `403`, naming the object or the
234-
field. The fields judged are the ones the source serves (`content`,
238+
field; an `adapter` naming no mounted store refuses it `400`, naming the
239+
source, the adapter and the mounted ones. The fields judged are the ones the source serves (`content`,
235240
`metadataFields`, the title field) and the ones its `where` reads. A
236241
verdict that cannot be reached, or a knowledge service that is registered
237242
and cannot be resolved, refuses `503`; nothing is written.
Lines changed: 181 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,181 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
//
3+
// [ADR-0161 K4] A `knowledge_source` whose `adapter` names a store this
4+
// deployment does not mount is refused at its save, on a REAL booted showcase
5+
// (the knowledge service and its one store, `memory`):
6+
//
7+
// - `PUT /meta/knowledge_source/:name` answers `400 VALIDATION_ERROR`, naming
8+
// the source, the adapter and the mounted stores; nothing is stored;
9+
// - the MCP `save_metadata_draft` tool refuses the same save the same way,
10+
// and no draft is stored.
11+
//
12+
// CONTROLS, at both doors: a source naming the mounted store, and one that
13+
// leaves `adapter` out (the one store holds it), save as before.
14+
//
15+
// Before, both saves answered success, and the source was named only by the
16+
// boot's `error` line and by the `503` its index and search answered.
17+
//
18+
// Not judged at these doors: a package install (the engine's own write), a
19+
// source registered in code and `os validate`.
20+
//
21+
// The verify harness mounts no MCP server, so this file mounts one, as
22+
// `objectstack dev` and `serve` do. The draft door is served only to an OAuth
23+
// agent granted `metadata:write` whose user holds the authoring capability,
24+
// and that agent holds its user's system capabilities only under
25+
// `actions:execute`, so the MCP calls present a REAL access token with both
26+
// scopes (DCR, authorize with the MCP resource, consent, token).
27+
//
28+
// The file is ISOLATED: it writes `/meta`, creates a package and sets
29+
// `OS_OIDC_PROVIDER_ENABLED` for its boot.
30+
31+
import { createHash, randomBytes } from 'node:crypto';
32+
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
33+
import { MCPServerPlugin } from '@objectstack/mcp';
34+
import { type VerifyStack } from '@objectstack/verify';
35+
import { bootShowcase } from './showcase-boot.js';
36+
37+
const OPERATOR = { email: 'admin@objectos.ai', password: 'admin123' };
38+
const AGENT_SCOPE = 'openid profile email offline_access metadata:write actions:execute';
39+
const REDIRECT_URI = 'http://127.0.0.1:33421/callback';
40+
/** A writable package the drafts are saved into (the showcase's own is read-only). */
41+
const DRAFT_PACKAGE = 'com.dogfood.ksadapter';
42+
43+
/** A source over the showcase's tasks, as the showcase's own `showcase_task_notes`, with the given `adapter`. */
44+
const sourceBody = (name: string, adapter?: string) => ({
45+
name,
46+
label: name,
47+
...(adapter === undefined ? {} : { adapter }),
48+
source: { kind: 'object', object: 'showcase_task', content: ['title', 'notes'], metadataFields: ['status', 'priority'] },
49+
});
50+
51+
async function mintAgentToken(stack: VerifyStack): Promise<string> {
52+
const authSvc: any = await stack.kernel.getServiceAsync('auth');
53+
const resource = authSvc.getMcpResourceUrl();
54+
const reg = await stack.api('/auth/oauth2/register', {
55+
method: 'POST',
56+
headers: { 'content-type': 'application/json' },
57+
body: JSON.stringify({
58+
client_name: 'knowledge adapter save probe', redirect_uris: [REDIRECT_URI], grant_types: ['authorization_code', 'refresh_token'],
59+
response_types: ['code'], token_endpoint_auth_method: 'none', application_type: 'native', scope: AGENT_SCOPE,
60+
}),
61+
});
62+
const regBody: any = await reg.json();
63+
expect(reg.status, JSON.stringify(regBody)).toBe(201);
64+
const signin = await stack.api('/auth/sign-in/email', {
65+
method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(OPERATOR),
66+
});
67+
expect(signin.status, await signin.clone().text()).toBe(200);
68+
const cookie = ((signin.headers as any).getSetCookie() as string[]).map((c) => c.split(';')[0]).join('; ');
69+
const verifier = randomBytes(32).toString('base64url');
70+
const challenge = createHash('sha256').update(verifier).digest('base64url');
71+
const qs = new URLSearchParams({
72+
client_id: regBody.client_id, redirect_uri: REDIRECT_URI, response_type: 'code', scope: AGENT_SCOPE, state: 'st',
73+
code_challenge: challenge, code_challenge_method: 'S256', resource,
74+
});
75+
const az = await stack.api(`/auth/oauth2/authorize?${qs}`, { headers: { cookie }, redirect: 'manual' });
76+
const loc = az.headers.get('location') ?? '';
77+
let code = new URL(loc, 'http://localhost:3000').searchParams.get('code');
78+
if (!code) {
79+
const consent = await stack.api('/auth/oauth2/consent', {
80+
method: 'POST',
81+
headers: { 'content-type': 'application/json', cookie, origin: 'http://localhost:3000' },
82+
body: JSON.stringify({ accept: true, oauth_query: loc.slice(loc.indexOf('?')) }),
83+
});
84+
const cb: any = await consent.json().catch(() => null);
85+
code = new URL(cb?.redirect_uri ?? cb?.url).searchParams.get('code');
86+
}
87+
const tok = await stack.api('/auth/oauth2/token', {
88+
method: 'POST',
89+
headers: { 'content-type': 'application/x-www-form-urlencoded' },
90+
body: new URLSearchParams({
91+
grant_type: 'authorization_code', code: code!, redirect_uri: REDIRECT_URI, client_id: regBody.client_id, code_verifier: verifier, resource,
92+
}).toString(),
93+
});
94+
const tj: any = await tok.json();
95+
expect(tok.status, JSON.stringify(tj)).toBe(200);
96+
return String(tj.access_token);
97+
}
98+
99+
describe('[ADR-0161 K4] a knowledge_source naming an adapter the deployment does not mount is refused at its save', () => {
100+
let stack: VerifyStack;
101+
let admin = '';
102+
let agent = '';
103+
const priorOidc = process.env.OS_OIDC_PROVIDER_ENABLED;
104+
105+
const put = async (name: string, body: unknown) => {
106+
const res = await stack.apiAs(admin, 'PUT', `/meta/knowledge_source/${name}`, body);
107+
const json: any = await res.json().catch(() => ({}));
108+
return { status: res.status, error: json?.error, json };
109+
};
110+
const saveDraft = async (name: string, item: unknown) => {
111+
const res = await stack.api('/mcp', {
112+
method: 'POST',
113+
headers: { 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream', Authorization: `Bearer ${agent}` },
114+
body: JSON.stringify({
115+
jsonrpc: '2.0', id: 1, method: 'tools/call',
116+
params: { name: 'save_metadata_draft', arguments: { type: 'knowledge_source', name, item, package: DRAFT_PACKAGE } },
117+
}),
118+
});
119+
expect(res.status, await res.clone().text()).toBe(200);
120+
const rpc: any = await res.json();
121+
expect(rpc.error, JSON.stringify(rpc.error)).toBeUndefined();
122+
const text = String(rpc.result?.content?.[0]?.text ?? '');
123+
let payload: any;
124+
try { payload = JSON.parse(text); } catch { payload = { message: text }; }
125+
return { isError: rpc.result?.isError === true, payload, text };
126+
};
127+
const knowledge = async () => stack.kernel.getServiceAsync<any>('knowledge');
128+
129+
beforeAll(async () => {
130+
process.env.OS_OIDC_PROVIDER_ENABLED = 'true';
131+
stack = await bootShowcase({ extraPlugins: [new MCPServerPlugin()] });
132+
admin = await stack.signIn();
133+
const created = await stack.apiAs(admin, 'POST', '/packages', {
134+
manifest: { id: DRAFT_PACKAGE, name: 'Knowledge adapter drafts', version: '0.1.0', type: 'app', namespace: 'ksadapter' },
135+
});
136+
expect(created.status, await created.clone().text()).toBe(201);
137+
agent = await mintAgentToken(stack);
138+
}, 180_000);
139+
140+
afterAll(async () => {
141+
await stack?.stop();
142+
if (priorOidc === undefined) delete process.env.OS_OIDC_PROVIDER_ENABLED;
143+
else process.env.OS_OIDC_PROVIDER_ENABLED = priorOidc;
144+
});
145+
146+
it('the booted deployment mounts one store, memory', async () => {
147+
expect((await knowledge()).listAdapters()).toEqual(['memory']);
148+
});
149+
150+
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 () => {
151+
for (const [name, adapter] of [['ks_retired_store', 'ragflow'], ['ks_typo_store', 'memroy']] as const) {
152+
const saved = await put(name, sourceBody(name, adapter));
153+
expect(saved.status, JSON.stringify(saved.json)).toBe(400);
154+
expect(saved.error, JSON.stringify(saved.json)).toMatchObject({ code: 'VALIDATION_ERROR' });
155+
const message = String(saved.error?.message ?? '');
156+
expect(message).toContain(name);
157+
expect(message).toContain(`names adapter '${adapter}', which this deployment does not mount (mounted: memory)`);
158+
expect((await stack.apiAs(admin, 'GET', `/meta/knowledge_source/${name}`)).status, name).toBe(404);
159+
expect((await knowledge()).listSources().map((s: { name: string }) => s.name), name).not.toContain(name);
160+
}
161+
});
162+
163+
it('save_metadata_draft refuses the same save 400 VALIDATION_ERROR, and no draft is stored', async () => {
164+
const refused = await saveDraft('ks_draft_retired_store', sourceBody('ks_draft_retired_store', 'ragflow'));
165+
expect(refused.isError, refused.text).toBe(true);
166+
expect(refused.payload.error, refused.text).toMatchObject({ code: 'VALIDATION_ERROR', status: 400 });
167+
expect(String(refused.payload.error?.message)).toContain("names adapter 'ragflow', which this deployment does not mount (mounted: memory)");
168+
const draft = await stack.apiAs(admin, 'GET', `/meta/knowledge_source/ks_draft_retired_store?state=draft&package=${DRAFT_PACKAGE}`);
169+
expect(draft.status, await draft.clone().text()).toBe(404);
170+
});
171+
172+
it('CONTROL: a source naming the mounted store, and one leaving `adapter` out, save at both doors', async () => {
173+
for (const [name, adapter] of [['ks_named_store', 'memory'], ['ks_omitted_store', undefined]] as const) {
174+
const saved = await put(name, sourceBody(name, adapter));
175+
expect(saved.status, JSON.stringify(saved.json)).toBe(200);
176+
const drafted = await saveDraft(`${name}_draft`, sourceBody(`${name}_draft`, adapter));
177+
expect(drafted.isError, drafted.text).toBe(false);
178+
expect(drafted.payload.saved, drafted.text).toMatchObject({ type: 'knowledge_source', name: `${name}_draft`, package: DRAFT_PACKAGE });
179+
}
180+
});
181+
});
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
import type { SemanticMigration } from '../../types.js';
4+
5+
// ADR-0161 K4 — a knowledge source's `adapter` names the store that holds its
6+
// index, resolved at run time to an adapter the deployment mounts. Saved at
7+
// run time (the `/meta` save door, Studio, the MCP draft save, a package
8+
// duplicate), a source naming no mounted adapter is now refused at the save,
9+
// where it used to be stored and then named only by the boot's error line and
10+
// by the 503 its index and search answered. Semantic-only: which store the
11+
// author meant is theirs to say, so no D2 conversion rewrites the value.
12+
export const entry: SemanticMigration = {
13+
id: 'knowledge-source-unmounted-adapter-refused-at-save',
14+
surface:
15+
'knowledge_source.adapter on a source saved at run time (`PUT /meta/knowledge_source/:name`, Studio, '
16+
+ 'the MCP `save_metadata_draft` tool, a package duplicate), when it names an adapter id the running '
17+
+ 'deployment does not mount: a retired store such as `ragflow`, or a mistyped id',
18+
replacement:
19+
'An adapter id the deployment mounts (the refusal lists them), or no `adapter` at all, so the '
20+
+ 'deployment\'s store holds the source; or mount the named store before saving the source.',
21+
reason:
22+
'Such a source was stored, and then every index and search of it answered SERVICE_UNAVAILABLE (503) and '
23+
+ 'the boot logged it at error. The save now refuses it, VALIDATION_ERROR (400), naming the source, the '
24+
+ 'adapter and the mounted adapters, and nothing is written. A source already stored is not touched: it '
25+
+ 'keeps answering 503 until it is saved again with a mounted adapter. A package install, a source '
26+
+ 'registered in code and objectstack validate are not judged by this check. No D2 conversion exists: '
27+
+ 'only the author knows which store the source belongs in.',
28+
acceptanceCriteria:
29+
'The boot logs no error naming a knowledge source whose adapter is not mounted, and saving each of the '
30+
+ 'application\'s knowledge sources in Studio answers success.',
31+
};

0 commit comments

Comments
 (0)