Skip to content

Commit f9c6f92

Browse files
feat(knowledge)!: refuse a knowledge_source save that names an adapter the running deployment does not mount (#38060)
repo:objectstack#1 · os-elon-musk · session_016WV4cwPhGV4g9p1BGQaZbP Fixes #37961 Clause-②: no (narrowing) Metadata-protocol: narrowed Skills-docs: follow-up #38158 — `skills/objectstack-ai/SKILL.md` § Knowledge Sources (its `adapter` row, added on `main` by #38053) does not yet name this PR's save refusal of an unmounted adapter; #38158 teaches it there. `content/docs/ai/knowledge-rag.mdx` and `content/docs/protocol/knowledge.mdx` name the refusal here ## 维护者速读 - 用户能看到什么变化:在 Studio、通过接口或用 AI(MCP)保存知识源时,如果写了本部署没装的存储(例如已退役的 ragflow 或拼错),保存会当场被拒,错误里写明知识源、写的存储名和本部署已装的存储;不写存储、或写已装的存储,照常保存。 - 为什么做:知识库检索专题(按调用者权限过滤的知识检索)的收尾一项,替写知识源的作者和 AI 解决“写错存储要到启动日志或检索报错时才发现”。 - 出错会怎样:最坏是某个本该能保存的知识源被拒;改动只在保存这一处,可直接撤回。包安装、代码注册和离线校验不经过这一检查,仍由启动日志和检索报错兜底。 - 要你做什么:无(这是收窄,按惯例走契约审核)。 ## What changes - **The check** (`packages/services/service-knowledge/src/knowledge-service.ts`, `admitAuthoredSource`): a `knowledge_source` item whose `adapter` is a string naming no adapter the running deployment has registered is refused `400 VALIDATION_ERROR`. The message names the source, the adapter and the mounted adapters, as a rule and its remedy: "it names adapter 'ragflow', which this deployment does not mount (mounted: memory), and a source's `adapter` must name a mounted store. Name one of 'memory' as its `adapter`, or leave `adapter` out, and the deployment's store holds it, or mount the 'ragflow' store and save it again." Leaving `adapter` out is offered only where an omitted adapter would be placed (the deployment's store is mounted, or one adapter is). The hunk sits beside the existing unplaced-source check (several adapters, none the deployment's), the other "which store holds it" refusal, and reads the registry at request time, after every store's `start()`: nothing is recorded. - **Not refused:** an omitted `adapter` (legal since the deployment's-store change; it is placed by `adapterIdFor`); a named adapter that is mounted. - **Doors reached:** every caller of `authoredKnowledgeSourceRefusal` (`@objectstack/metadata-core`), unchanged: `PUT /meta/knowledge_source/:name` on both transports, the MCP `save_metadata_draft` tool, and the package duplicate (`refuseDuplicatedKnowledgeSources`), which judges each source it copies for the caller and now refuses a copy whose source names an unmounted adapter, as it already refused an unplaced one. - **Not covered by this door, said in the docs and the changeset:** a package install and any other engine write (`isSystem`, skipped by `authoredKnowledgeSourceRefusal` before the knowledge service is asked); a source registered in code (`registerSource`, `KnowledgeServicePlugin({ sources })`), which registers at `init()` before its store's `start()`, so "not mounted yet" is no verdict there; `objectstack validate`, which runs with no deployment. For those, `reportUnmountedAdapters` at boot (`error`) and the `503 SERVICE_UNAVAILABLE` at index and search stay the signal. - **How the refusals at this door order:** with no knowledge service mounted, the door never reaches `admitAuthoredSource`, so the no-service refusal that #38013 adds (`503`) comes before this one (`400`). Inside `admitAuthoredSource`: no identity (`403`), then the unplaced source (`400`), then this check (`400`), then no data engine (`503`), then the exposure and field gates (`403`/`503`). The code is the existing `VALIDATION_ERROR`, the sibling unplaced refusal's code: no new error code. - **Docs:** `content/docs/ai/knowledge-rag.mdx` (the not-mounted bullet) and `content/docs/protocol/knowledge.mdx` (the "Named" binding rule and guard two, source admission at save). - **ADR-0087:** semantic entry `knowledge-source-unmounted-adapter-refused-at-save` (`packages/spec/src/migrations/entries/semantic/`), registered by the changeset. ## Tests - `packages/services/service-knowledge/src/__tests__/knowledge-source-admission.test.ts`, in the `admitAuthoredSource` describe, through the real `KnowledgeService`: a retired (`ragflow`), mistyped (`memroy`) and empty adapter are each refused `VALIDATION_ERROR`/`400` naming the source, the adapter and `mounted: memory`; the refusal comes before the field gate; the system context is admitted; with none mounted the message says `mounted: none`, with two it names both; CONTROL: a mounted adapter, and an omitted one (deployment's store, two registered), are admitted. One existing fixture (`new KnowledgeService({})` in the fail-closed case) now registers the `memory` adapter its item names, so it still reaches the no-engine `503` it pins. - `packages/qa/dogfood/test/knowledge-source-unmounted-adapter-save.dogfood.test.ts`, a real booted showcase (knowledge service plus `memory`) with the MCP server: `PUT /meta/knowledge_source` refuses `ragflow` and `memroy` `400 VALIDATION_ERROR`, nothing stored (GET `404`, not registered); MCP `save_metadata_draft` with a real OAuth token (`metadata:write actions:execute`) refuses `ragflow` the same way, and no draft is stored; CONTROL: a named `memory` source and an omitted-adapter source save at both doors. <details><summary>Local runs on head 0b2a3bc (all under os-verify-lock)</summary> - Dependency closure `pnpm exec turbo run build --filter='@objectstack/dogfood^...' --concurrency=2`: exit 0 (covers `service-knowledge^...`). - `service-knowledge`: vitest Test Files 18 passed (18), Tests 573 passed (573); `typecheck` (tsc plus `check:test-typecheck`) exit 0. - `metadata-core`: Test Files 29 passed (29), Tests 1111 passed (1111); typecheck exit 0. - Door tests that pin save refusals: runtime `mcp-authoring`, `meta-save-capability-gate`, `packages-knowledge-source-gate`, `meta-type-write-capability-parity`: 4 files, 195 passed; rest `meta-write-door-capability-enumeration`, `meta-type-write-capability`: 2 files, 135 passed. - `spec` `src/migrations`: 5 files, 206 passed. New dogfood file: 4 passed (4). - **Dogfood battery** (`pnpm --filter @objectstack/dogfood test`, no shard, no path): `VERDICT command-exit 0`, held the lock 2405 s; Test Files 491 passed, 3 skipped (494); Tests 4148 passed, 68 skipped (4216). </details> <details><summary>Ablation: the check removed, both layers red; restored, green</summary> Through `scripts/ablation-replace.mjs` (anchor hit, restore trap) on the condition `if (typeof authoredAdapter === 'string' && ...)`, prefixed with an always-false string comparison carrying the marker `ABLATED_UNMOUNTED_CHECK`. - Unit leg (vitest reads `src`; marker count 1 on disk): 2 failed, 43 passed (45). Red: the two refusal cases (`ragflow: expected { admitted: true } to match object { admitted: false, ... }`). Green: the CONTROL. - Door leg: `service-knowledge` rebuilt, `ablation-dist-preflight` found the marker in `dist/` (exit 0); dogfood file 2 failed, 2 passed (4). Red: the PUT leg (`Saved knowledge_source 'ks_retired_store' ... expected 200 to be 400`) and the MCP leg. Green: the booted-store check and the CONTROL. - A first attempt spelled the mutation as a literal comparison, which the DTS build refused (TS2367), so that door leg ran with no `dist/` and is discarded; the unit leg of that attempt is the one above. - Restore: `git diff HEAD` empty, `git status --porcelain` empty, rebuilt, `ablation-dist-preflight --absent` exit 0, unit file 45 passed, dogfood file 4 passed. </details> ## Acceptance notes - The claim's file surface names `knowledge-source-admission.ts` for `admitAuthoredSource`; on 8d34c44 that function lives in `knowledge-service.ts`, beside the other adapter refusals. The admission module (`knowledge-source-admission.ts`, the gates) is untouched, so #38038's gate-2 rewording and #37963 do not meet this hunk; overlap-check reads clean against both. - `metadata-core` `knowledge-source-save-admission.ts` needed no threading: the verdict carries `status`/`code`/`message`, which the doors already pass through. - A source already stored with an unmounted adapter is not touched; it keeps answering `503` until it is saved again. ## Verification Read first: (1) `knowledge-service.ts` the new hunk after the unplaced-source check in `admitAuthoredSource`, and `unmountedAdapterSaveText` (remedy wording); (2) the dogfood file's MCP leg (token, `save_metadata_draft`); (3) the semantic migration entry. Two-minute check: `pnpm --filter @objectstack/service-knowledge exec vitest run --maxWorkers=2 src/__tests__/knowledge-source-admission.test.ts` shows 45 passed, three of them the new unmounted-adapter cases. <details><summary>Gates</summary> - `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack`: 118 families, all run locally on 0b2a3bc, exit codes captured before any pipe. `--ran`: "118 derived famil(ies) accounted for — 115 run, 3 NOT-MEASURED (3 DERIVED from a recorded exit 3)". - NOT MEASURED: `check:skill-examples`, reason: it reads `packages/client-react/dist`, outside the dogfood closure built here (PREREQUISITE NOT MET). - NOT MEASURED: `check:dual-build-cjs-loads`, reason: it needs a whole-tree `dist/` build (PREREQUISITE NOT MET). - NOT MEASURED: `check:type-check-debt`, reason: its re-measure build waited on the shared verify lock while this branch's battery held it, and exited 3. - Local-only: `check:skill-frame-freshness` exit 0; `check:dev-prereqs` exit 1, "38 of 110 workspace packages declare an entry point under dist/ that is not on disk" (only the dogfood closure is built in this worktree; a local reading, not a finding). - `check:adr-0087-registration`: "1 declared-breaking changeset(s), each carrying an ADR-0087 disposition ... registered knowledge-source-unmounted-adapter-refused-at-save (new here)". - `overlap-check` before the PR: "VERDICT clean exit 0" against origin/main 27ee984 and six open PR heads (#38056, #38050, #38038, #38013, #37982, #37963). - CI check-runs: not yet reported at the time of writing; the seat reads them. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent ee2ffca commit f9c6f92

7 files changed

Lines changed: 321 additions & 5 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),
@@ -235,7 +239,8 @@ and the MCP draft door:
235239
as the author: an object of a disabled package, an object the API does not
236240
serve for `search`, a system object without `enable.aiReadable`, or a field
237241
the author may not query refuses the save `403`, naming the object or the
238-
field. The fields judged are the ones the source serves (`content`,
242+
field; an `adapter` naming no mounted store refuses it `400`, naming the
243+
source, the adapter and the mounted ones. The fields judged are the ones the source serves (`content`,
239244
`metadataFields`, the title field) and the ones its `where` reads. A
240245
verdict that cannot be reached, or a knowledge service that is registered
241246
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+
});

‎packages/services/service-knowledge/src/__tests__/knowledge-source-admission.test.ts‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1016,6 +1016,7 @@ describe('admitAuthoredSource — source admission at save, as the authoring pri
10161016
.toMatchObject({ admitted: false, code: 'SERVICE_UNAVAILABLE', status: 503 });
10171017

10181018
const noEngine = new KnowledgeService({});
1019+
noEngine.registerAdapter('memory', makeAdapter());
10191020
expect(await noEngine.admitAuthoredSource(item('ticket', ['body']), MANAGER))
10201021
.toMatchObject({ admitted: false, code: 'SERVICE_UNAVAILABLE', status: 503 });
10211022
});
@@ -1029,6 +1030,51 @@ describe('admitAuthoredSource — source admission at save, as the authoring pri
10291030
}
10301031
});
10311032

1033+
// [ADR-0161 K4] The store a source names must be one this deployment mounts:
1034+
// a retired adapter ('ragflow') or a typo is refused at the save, not left to
1035+
// the boot's error line and a search's 503.
1036+
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 () => {
1037+
const { svc } = setup({ sources: [], security: salaryHiddenFromMembers });
1038+
for (const adapter of ['ragflow', 'memroy', '']) {
1039+
const verdict = await svc.admitAuthoredSource({ ...item('ticket', ['body']), adapter }, MANAGER);
1040+
expect(verdict, adapter).toMatchObject({ admitted: false, code: 'VALIDATION_ERROR', status: 400, object: 'ticket' });
1041+
const message = (verdict as { message: string }).message;
1042+
expect(message).toContain('knowledge source "authored" was not saved');
1043+
expect(message).toContain(`names adapter '${adapter}', which this deployment does not mount (mounted: memory)`);
1044+
}
1045+
// Refused before the gates are asked: an author the field gate would refuse hears the adapter first.
1046+
expect(await svc.admitAuthoredSource({ ...item('ticket', ['body', 'salary_note']), adapter: 'ragflow' }, MEMBER))
1047+
.toMatchObject({ admitted: false, code: 'VALIDATION_ERROR', status: 400 });
1048+
// The engine's own write (a package install) is not judged at this door.
1049+
expect(await svc.admitAuthoredSource({ ...item('ticket', ['body']), adapter: 'ragflow' }, SYSTEM)).toEqual({ admitted: true });
1050+
});
1051+
1052+
it('with no adapter mounted, a named one is refused naming none mounted; with two, both are named', async () => {
1053+
const bare = new KnowledgeService({ dataEngine: makeEngine([TICKET]) });
1054+
expect(await bare.admitAuthoredSource(item('ticket', ['body']), MANAGER)).toMatchObject({
1055+
admitted: false, code: 'VALIDATION_ERROR', status: 400,
1056+
message: expect.stringContaining("names adapter 'memory', which this deployment does not mount (mounted: none)"),
1057+
});
1058+
const { svc } = setup({ sources: [] });
1059+
svc.registerAdapter('turso', makeAdapter());
1060+
expect(await svc.admitAuthoredSource({ ...item('ticket', ['body']), adapter: 'pgvector' }, MANAGER)).toMatchObject({
1061+
admitted: false, code: 'VALIDATION_ERROR', status: 400,
1062+
message: expect.stringContaining("(mounted: memory, turso)"),
1063+
});
1064+
});
1065+
1066+
it('CONTROL: a source naming a mounted adapter, and one that leaves `adapter` out, are admitted', async () => {
1067+
const { svc } = setup({ sources: [] });
1068+
svc.registerAdapter('turso', makeAdapter());
1069+
expect(await svc.admitAuthoredSource(item('ticket', ['body']), MANAGER)).toEqual({ admitted: true });
1070+
expect(await svc.admitAuthoredSource({ ...item('ticket', ['body']), adapter: 'turso' }, MANAGER)).toEqual({ admitted: true });
1071+
const placed = new KnowledgeService({ dataEngine: makeEngine([TICKET]), deploymentAdapter: 'turso' });
1072+
placed.registerAdapter('turso', makeAdapter());
1073+
placed.registerAdapter('memory', makeAdapter());
1074+
const { adapter: _omitted, ...omitted } = item('ticket', ['body']);
1075+
expect(await placed.admitAuthoredSource(omitted, MANAGER)).toEqual({ admitted: true });
1076+
});
1077+
10321078
it('registers nothing and searches nothing: the verdict is a read', async () => {
10331079
const { svc, adapter } = setup({ sources: [], security: salaryHiddenFromMembers });
10341080
await svc.admitAuthoredSource(item('ticket', ['body']), MANAGER);

0 commit comments

Comments
 (0)