Skip to content

Commit 24d808d

Browse files
fix(service-knowledge): the knowledge-source save door names an absent object or field as such (#38465)
Fixes #38419 Clause-②: no Metadata-protocol: none ## 维护者速读 - 在 Studio 或 MCP 保存知识源的搭建者:以前填错对象名或字段名时,会看到"暂时无法判断、请重试"或"无权访问"的提示,现在会直接看到"该对象/字段不存在",并带上与 `os validate` 相同的规则名。 - 属于知识库检索(把业务数据建成可搜索的知识源)这条线,替搭建者解决"拼错了却被告知去重试或去找管理员"的误导。 - 出错时只影响保存知识源这一个入口的提示文字与状态码;对存在但无权访问的对象和字段,拒绝提示一字未变,可以直接撤回。 - 无。 ## What changes `KnowledgeService.admitAuthoredSource` (the save-time admission every knowledge-source save door asks: `PUT /meta/knowledge_source/:name`, the runtime `/meta` door, the MCP draft save, and the package duplicate) gains a "does not exist" arm ahead of every permission arm (ADR-0161 K4, row 4): - `source.object` names no object the registry defines ⇒ `400 VALIDATION_ERROR`, naming the object and the rule `knowledge-source-object-unknown`. - a `source.content` / `source.contentFields` / `source.metadataFields` member names neither a declared field nor `id` or a system column the registry injects (`resolveInjectedSystemColumns`, the derivation `os validate` uses) ⇒ `400 VALIDATION_ERROR`, naming the object, the field (`field` on the verdict) and the rule `knowledge-source-field-unknown`. Before this PR, with a platform-like security service, the same saves answered `503 SERVICE_UNAVAILABLE` "... could not be judged ... try again" (absent object), `403` "is a system object that does not opt into AI reads" (absent `sys_` object), and `403` "you may not query field ... hidden from you" (absent field). With no security service they were admitted. The arm reads the object's registered definition only. It never reads a permission answer. Every door that asks this verdict admits only a `manage_metadata` holder, and ADR-0106 D4 serves that caller every object definition whole. So the arm tells the author nothing they could not already read. It draws no verdict for an engine with no schema registry, for an object of a disabled package (that gate still answers it), or for an object whose fields cannot be enumerated. A registry that throws keeps the `503`, reported once. No new error code: `VALIDATION_ERROR` is the code this method already answers for an unmounted adapter. The refusal is worded for the door, as the other arms are: the duplicate's caller is told the source cannot be copied, then to duplicate the package again. ## Read first 1. `packages/services/service-knowledge/src/knowledge-service.ts`, `absentSourceReference`: the riskiest hunk is the three early returns (no `getSchema`, disabled package, no field map). Each one keeps a case that exists from being read as absent. 2. `packages/services/service-knowledge/src/knowledge-service.ts`, `admitAuthoredSource`, the new block after the engine check: its position decides which arm wins. 3. `packages/services/service-knowledge/src/__tests__/knowledge-source-save-absent-reference.test.ts`, the `no permission answer changes for an object or a field that exists` block, which holds the full answers taken on the base. ## Two-minute verification `pnpm --filter @objectstack/service-knowledge exec vitest run --maxWorkers=2 src/__tests__/knowledge-source-save-absent-reference.test.ts`. Expect 15 passed. Restore `knowledge-service.ts` from `0c1b2ffe` and the same command shows 7 failed and 8 passed: the absent references answer 503 / 403, and every pin for what exists still passes. ## Tests <details><summary>New file: knowledge-source-save-absent-reference.test.ts (15 cases)</summary> - Absent business object and absent `sys_` object, with and without a security service: `VALIDATION_ERROR` / `400`, `object` set, no `field`, message carries `knowledge-source-object-unknown`, never "could not be judged", "try again", "does not opt into AI reads" or "may not query". The engine's own write (`isSystem`) is admitted. - Absent `content`, `metadataFields` and retired `contentFields` member, for a member and a manager, with and without a security service: `VALIDATION_ERROR` / `400`, `object` + `field`, message carries `knowledge-source-field-unknown`. - An absent field is named before a hidden one in the same source. - CONTROL: `id`, `created_at`, `owner_id` (not declared, injected) are admitted. - `door: duplicate`: same status, code, object and field as the save, worded for the duplicate. - Exists, answer unchanged, full verdict with `toEqual`, sentences taken from the base: hidden field (403), `sys_` object without `enable.aiReadable` (403), security service that answers neither question (503), disabled package with and without a served definition (403), registry that throws (503, logged once), engine with no schema registry (admitted). </details> <details><summary>Red on the base, green on the head</summary> Base `knowledge-service.ts` (`0c1b2ffe`), head test file: ``` Tests 7 failed | 8 passed (15) AssertionError: expected { admitted: false, status: 503, ... } to match object { admitted: false, ... } (absent object) AssertionError: expected { admitted: false, status: 403, ... } to match object { admitted: false, ... } (absent sys_ object) AssertionError: u_member undefined: expected { admitted: false, status: 403, ... } (absent field) os-verify-lock: VERDICT command-exit 1 ``` Head `cf125c96`, after `pnpm turbo run build --filter='@objectstack/service-knowledge...' --concurrency=2` (20/20): ``` pnpm --filter @objectstack/service-knowledge test Test Files 22 passed (22) Tests 741 passed (741) pnpm --filter @objectstack/service-knowledge typecheck check:test-typecheck: OK — 0 file(s) / 0 error(s) os-verify-lock: VERDICT command-exit 0 ``` </details> ## Acceptance notes - The fields a `where` reads are not checked for existence here. `os validate` does not check them either (`validate-knowledge-source.ts` checks `content` and `metadataFields` only), so no rule name exists for them. Measured on `cf125c96`: a `where` naming an absent field answers `403 PERMISSION_DENIED` "which you may not query (it is hidden from you ...)" when a security service is mounted, and is admitted when none is. Reported to the seat to file; not changed here. - The published `objectstack-ai` skill says `os validate` and publish check the two rules. That is still true. It does not mention the save door, and this PR leaves `skills/**` untouched. - Search-time admission (`admitSources`) is untouched by this PR. Only the save-time verdict changes. ## Verification <details><summary>Local derived gates at cf125c9 (dispatch-gates --commands, 71 commands)</summary> Each derived command ran on head `cf125c96` (after merging `origin/main` at `1afd9c13`), exit captured before any pipe: ``` dispatch-gates --ran: 71 derived famil(ies) accounted for, 70 run, 1 NOT-MEASURED (1 DERIVED from a recorded exit 3) NOT MEASURED: node scripts/check-plugin-teardown-shape.mjs --self-test, reason: PREREQUISITE NOT MET, its positive control is pinned to a commit this shallow clone cannot reach (checker health only; CI runs it) pnpm check:dual-build-cjs-loads: 126 published require entry point(s) across 74 package(s) load; 2593 emitted CommonJS file(s) parse ``` The other 69 commands exit 0, among them `check:nul-bytes`, `check:doc-authoring`, `check:issue-citations`, `check:published-files`, `check:type-check-coverage`, `check:type-check-debt`, `check:undeclared-dep-imports`, `check:engine-double-contract`, `check:error-status-conformance`, `check:adr-0087-registration --base origin/main` and `check:empty-changeset --base origin/main`. Every family CI runs beyond these is read from this PR's check-runs, not re-run locally. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_016WV4d13AraSmVmgVtCvkWk)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 4d07ddb commit 24d808d

3 files changed

Lines changed: 371 additions & 1 deletion

File tree

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
---
2+
'@objectstack/service-knowledge': patch
3+
---
4+
5+
fix(service-knowledge): the knowledge-source save door names an absent object or field as such
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
Saving a `knowledge_source` whose `source.object` names no object, or whose `source.content` /
11+
`source.metadataFields` names no field of its object, is now refused `400 VALIDATION_ERROR` with the rule
12+
`os validate` reports: `knowledge-source-object-unknown` or `knowledge-source-field-unknown`. The refusal names
13+
the object, and the field. Before, the same save was answered `503 SERVICE_UNAVAILABLE` ("could not be judged ...
14+
try again") for an absent object, `403` "is a system object that does not opt into AI reads" for an absent `sys_`
15+
object, and `403` "you may not query field ... hidden from you" for an absent field. With no security service, it
16+
was admitted.
17+
18+
The check reads only the object's registered definition. `id` and the system columns the registry injects count
19+
as fields of the object. Every door that asks it admits only a `manage_metadata` holder, and that caller is already
20+
served every object definition whole. So for an object or a field that exists, every refusal stays as it was: a
21+
hidden field, a system object without `enable.aiReadable`, a disabled package, a security service that cannot
22+
answer, and a registry that throws. The fields a `where` reads are not checked for existence, as in `os validate`.
Lines changed: 258 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,258 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [ADR-0161 K4, row 4] The save door's "does not exist" arm: a
5+
* `knowledge_source` whose `source.object` names no object, or whose
6+
* `source.content` / `source.metadataFields` names no field of its object, is
7+
* refused at its save as a permanent reference mistake, by the rule names
8+
* `os validate` reports (`knowledge-source-object-unknown`,
9+
* `knowledge-source-field-unknown`): `400 VALIDATION_ERROR`, never the `503`
10+
* that says "try again" nor a `403` that says "you may not".
11+
*
12+
* The arm is decided from the object's registered definition alone. Every
13+
* door that asks this verdict admits only a `manage_metadata` holder, and that
14+
* caller is served every object definition whole on the metadata plane
15+
* (ADR-0106 D4), so the arm tells the author nothing they could not read.
16+
* Its other half is pinned here byte for byte: for an object or a field that
17+
* EXISTS, every refusal the author was given before is the one given now.
18+
*/
19+
20+
import { describe, it, expect, vi } from 'vitest';
21+
import type { IDataEngine, IKnowledgeAdapter } from '@objectstack/spec/contracts';
22+
import type { ExecutionContext } from '@objectstack/spec/kernel';
23+
import { KnowledgeService, type KnowledgeLogger } from '../knowledge-service.js';
24+
import type { KnowledgeFieldSecurity } from '../knowledge-source-admission.js';
25+
26+
const MEMBER: ExecutionContext = { userId: 'u_member', positions: ['member'], permissions: [], isSystem: false };
27+
const MANAGER: ExecutionContext = { userId: 'u_manager', positions: ['manager'], permissions: [], isSystem: false };
28+
const SYSTEM: ExecutionContext = { positions: [], permissions: [], isSystem: true };
29+
30+
interface ObjectDef {
31+
name: string;
32+
enable?: Record<string, unknown>;
33+
fields: Record<string, Record<string, unknown>>;
34+
}
35+
36+
const TICKET: ObjectDef = {
37+
name: 'ticket',
38+
fields: {
39+
title: { type: 'text' },
40+
body: { type: 'textarea' },
41+
salary_note: { type: 'textarea' },
42+
status: { type: 'select' },
43+
},
44+
};
45+
const SYS_CLOSED: ObjectDef = { name: 'sys_closed_note', fields: { title: { type: 'text' }, body: { type: 'textarea' } } };
46+
47+
const OBJECT_UNKNOWN = 'knowledge-source-object-unknown';
48+
const FIELD_UNKNOWN = 'knowledge-source-field-unknown';
49+
50+
/**
51+
* A security service shaped like the platform's: an object whose definition it
52+
* cannot resolve gets no answer to either field question (`undefined`), and
53+
* members may not query `salary_note`.
54+
*/
55+
function platformLikeSecurity(objects: ObjectDef[]): KnowledgeFieldSecurity {
56+
const fieldsOf = (object: string) => {
57+
const def = objects.find((o) => o.name === object);
58+
return def ? ['id', ...Object.keys(def.fields)] : undefined;
59+
};
60+
return {
61+
getQueryableFields: vi.fn(async (object: string, ctx?: ExecutionContext) => {
62+
const all = fieldsOf(object);
63+
return all && ctx?.userId === 'u_member' ? all.filter((f) => f !== 'salary_note') : all;
64+
}),
65+
getReadableFields: vi.fn(async (object: string) => fieldsOf(object)),
66+
};
67+
}
68+
69+
function setup(options: {
70+
objects?: ObjectDef[];
71+
security?: KnowledgeFieldSecurity | 'none';
72+
disabled?: string[];
73+
schemaThrows?: boolean;
74+
/** An engine that exposes no schema registry at all. */
75+
noSchemaRegistry?: boolean;
76+
logger?: KnowledgeLogger;
77+
}) {
78+
const objects = options.objects ?? [TICKET, SYS_CLOSED];
79+
const byName = new Map(objects.map((o) => [o.name, o]));
80+
const engine = {
81+
find: vi.fn(async () => []),
82+
...(options.noSchemaRegistry
83+
? {}
84+
: {
85+
getSchema: (name: string) => {
86+
if (options.schemaThrows) throw new Error('registry unavailable');
87+
return byName.get(name);
88+
},
89+
}),
90+
registry: { isObjectPackageDisabled: (name: string) => (options.disabled ?? []).includes(name) },
91+
} as unknown as IDataEngine;
92+
const security = options.security === 'none' ? undefined : (options.security ?? platformLikeSecurity(objects));
93+
const svc = new KnowledgeService({
94+
dataEngine: engine,
95+
logger: options.logger,
96+
resolveSecurity: security ? () => security : undefined,
97+
});
98+
const adapter: IKnowledgeAdapter = { id: 'memory', upsert: async () => undefined, delete: async () => undefined, search: async () => [] };
99+
svc.registerAdapter('memory', adapter);
100+
return svc;
101+
}
102+
103+
const item = (object: string, content: string[], extra: Record<string, unknown> = {}) => ({
104+
name: 'authored', label: 'Authored', adapter: 'memory', source: { kind: 'object', object, content, ...extra },
105+
});
106+
107+
type Refusal = { admitted: false; status: number; code: string; message: string; object: string; field?: string };
108+
109+
describe('the save door names an absent object as such, by the rule `os validate` reports', () => {
110+
it.each([
111+
['a business object nothing defines', 'tickt'],
112+
['a `sys_` object nothing defines', 'sys_no_such_note'],
113+
])('%s is refused VALIDATION_ERROR / 400, naming the object and `knowledge-source-object-unknown`', async (_label, object) => {
114+
for (const security of [undefined, 'none'] as const) {
115+
const svc = setup({ security });
116+
const verdict = (await svc.admitAuthoredSource(item(object, ['body']), MANAGER)) as Refusal;
117+
expect(verdict, String(security)).toMatchObject({ admitted: false, code: 'VALIDATION_ERROR', status: 400, object });
118+
expect(verdict.field).toBeUndefined();
119+
expect(verdict.message).toContain(`\`${OBJECT_UNKNOWN}\``);
120+
expect(verdict.message).toContain(`names '${object}'`);
121+
expect(verdict.message.startsWith('The knowledge source "authored" was not saved: ')).toBe(true);
122+
// A permanent mistake: never worded as a transient fault or as a refusal of authority.
123+
expect(verdict.message).not.toMatch(/could not be judged|try again|does not opt into AI reads|may not query/);
124+
}
125+
});
126+
127+
it('the engine itself is admitted: a package install is judged at validate and publish', async () => {
128+
expect(await setup({}).admitAuthoredSource(item('tickt', ['body']), SYSTEM)).toEqual({ admitted: true });
129+
});
130+
});
131+
132+
describe('the save door names an absent field as such, by the rule `os validate` reports', () => {
133+
it.each([
134+
['`content`', item('ticket', ['body', 'bdy']), 'bdy', 'content'],
135+
['`metadataFields`', item('ticket', ['body'], { metadataFields: ['stauts'] }), 'stauts', 'metadataFields'],
136+
['`contentFields` (the retired spelling)', { name: 'authored', label: 'A', adapter: 'memory', source: { kind: 'object', object: 'ticket', contentFields: ['bdy'] } }, 'bdy', 'contentFields'],
137+
])('a %s member is refused VALIDATION_ERROR / 400, naming the object, the field and `knowledge-source-field-unknown`', async (_label, body, field, key) => {
138+
for (const ctx of [MEMBER, MANAGER]) {
139+
for (const security of [undefined, 'none'] as const) {
140+
const verdict = (await setup({ security }).admitAuthoredSource(body, ctx)) as Refusal;
141+
expect(verdict, `${ctx.userId} ${String(security)}`).toMatchObject({
142+
admitted: false, code: 'VALIDATION_ERROR', status: 400, object: 'ticket', field,
143+
});
144+
expect(verdict.message).toContain(`\`${FIELD_UNKNOWN}\``);
145+
expect(verdict.message).toContain(`\`source.${key}\` names field '${field}', which object 'ticket' does not define`);
146+
expect(verdict.message).not.toMatch(/hidden from you|may not query|could not be judged|try again/);
147+
}
148+
}
149+
});
150+
151+
it('an absent field is named before a field the author may not query, wherever each is listed', async () => {
152+
const verdict = (await setup({}).admitAuthoredSource(item('ticket', ['salary_note', 'bdy']), MEMBER)) as Refusal;
153+
expect(verdict).toMatchObject({ admitted: false, code: 'VALIDATION_ERROR', status: 400, field: 'bdy' });
154+
});
155+
156+
it('CONTROL: `id` and the system columns the registry injects are fields of the object, though it does not declare them', async () => {
157+
const svc = setup({ security: 'none' });
158+
expect(await svc.admitAuthoredSource(item('ticket', ['body', 'id'], { metadataFields: ['created_at', 'owner_id'] }), MANAGER))
159+
.toEqual({ admitted: true });
160+
});
161+
162+
it('door: duplicate words both arms for the duplicate\'s caller; the status, code, object and field are the save\'s', async () => {
163+
const svc = setup({});
164+
for (const body of [item('tickt', ['body']), item('ticket', ['bdy'])]) {
165+
const saved = (await svc.admitAuthoredSource(body, MANAGER)) as Refusal;
166+
const duplicated = (await svc.admitAuthoredSource(body, MANAGER, { door: 'duplicate' })) as Refusal;
167+
const { message: _saved, ...savedRest } = saved;
168+
const { message, ...duplicatedRest } = duplicated;
169+
expect(duplicatedRest).toEqual(savedRest);
170+
expect(message).toMatch(/^The knowledge source "authored" cannot be copied: /);
171+
expect(message).toMatch(/, then duplicate the package again\.$/);
172+
expect(message).not.toMatch(/save the source|save it again|was not saved|Nothing was written|nothing was copied|the save /i);
173+
}
174+
});
175+
});
176+
177+
/**
178+
* The arm's other half: what EXISTS keeps the answer it had, byte for byte —
179+
* the sentences below are the ones the door gave before the arm existed.
180+
*/
181+
describe('no permission answer changes for an object or a field that exists', () => {
182+
it('a field that exists but is hidden from the author keeps its PERMISSION_DENIED / 403 sentence', async () => {
183+
const svc = setup({});
184+
expect(await svc.admitAuthoredSource(item('ticket', ['body', 'salary_note']), MEMBER)).toEqual({
185+
admitted: false,
186+
status: 403,
187+
code: 'PERMISSION_DENIED',
188+
object: 'ticket',
189+
field: 'salary_note',
190+
message:
191+
'The knowledge source "authored" was not saved: you may not query field \'salary_note\' of object \'ticket\' (it is hidden ' +
192+
'from you, or served to you masked), and the index would hold its text unmasked. Remove the field from `content` ' +
193+
'and `metadataFields`, or have someone who may query it save the source.',
194+
});
195+
// The same source, by an author who may query the field.
196+
expect(await svc.admitAuthoredSource(item('ticket', ['body', 'salary_note']), MANAGER)).toEqual({ admitted: true });
197+
});
198+
199+
it('a `sys_` object that exists without `enable.aiReadable` keeps its PERMISSION_DENIED / 403 sentence', async () => {
200+
expect(await setup({}).admitAuthoredSource(item('sys_closed_note', ['body']), MANAGER)).toEqual({
201+
admitted: false,
202+
status: 403,
203+
code: 'PERMISSION_DENIED',
204+
object: 'sys_closed_note',
205+
message:
206+
'The knowledge source "authored" was not saved: \'sys_closed_note\' is a system object that does not opt into AI reads ' +
207+
'(`enable.aiReadable: true`), so its records are not indexed for retrieval.',
208+
});
209+
});
210+
211+
it('an object that exists but whose fields the security service cannot answer keeps its SERVICE_UNAVAILABLE / 503 sentence', async () => {
212+
const mute: KnowledgeFieldSecurity = { getQueryableFields: async () => undefined, getReadableFields: async () => undefined };
213+
expect(await setup({ security: mute }).admitAuthoredSource(item('ticket', ['body']), MANAGER)).toEqual({
214+
admitted: false,
215+
status: 503,
216+
code: 'SERVICE_UNAVAILABLE',
217+
object: 'ticket',
218+
message:
219+
'The knowledge source "authored" was not saved: whether you may search object \'ticket\' could not be judged (the security ' +
220+
"service did not answer which fields of 'ticket' you may read), and an author must be allowed to search what their source " +
221+
'indexes. Nothing was written; try again.',
222+
});
223+
});
224+
225+
it('an object of a disabled package keeps its PERMISSION_DENIED / 403 sentence, whether or not its definition is served', async () => {
226+
for (const objects of [[TICKET], []]) {
227+
expect(await setup({ objects, security: 'none', disabled: ['ticket'] }).admitAuthoredSource(item('ticket', ['bdy']), MANAGER))
228+
.toEqual({
229+
admitted: false,
230+
status: 403,
231+
code: 'PERMISSION_DENIED',
232+
object: 'ticket',
233+
message:
234+
'The knowledge source "authored" was not saved: its object \'ticket\' belongs to a disabled package, and a disabled ' +
235+
"package's records are not indexed or searched. Enable the package, or index another object.",
236+
});
237+
}
238+
});
239+
240+
it('a registry that throws keeps its SERVICE_UNAVAILABLE / 503 sentence and is reported once', async () => {
241+
const logger = { warn: vi.fn(), error: vi.fn() };
242+
expect(await setup({ schemaThrows: true, logger }).admitAuthoredSource(item('tickt', ['body']), MANAGER)).toEqual({
243+
admitted: false,
244+
status: 503,
245+
code: 'SERVICE_UNAVAILABLE',
246+
object: 'tickt',
247+
message:
248+
'The knowledge source "authored" was not saved: whether you may search object \'tickt\' could not be judged (registry ' +
249+
'unavailable), and an author must be allowed to search what their source indexes. Nothing was written; try again.',
250+
});
251+
expect(logger.error).toHaveBeenCalledTimes(1);
252+
});
253+
254+
it('an engine with no schema registry draws no "does not exist" verdict: absence of a registry is not absence of the object', async () => {
255+
expect(await setup({ noSchemaRegistry: true, security: 'none' }).admitAuthoredSource(item('tickt', ['bdy']), MANAGER))
256+
.toEqual({ admitted: true });
257+
});
258+
});

0 commit comments

Comments
 (0)