Skip to content
Open
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
22 changes: 22 additions & 0 deletions .changeset/38419-knowledge-source-save-absent-reference.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
---
'@objectstack/service-knowledge': patch
---

fix(service-knowledge): the knowledge-source save door names an absent object or field as such

Clause-②: no
Metadata-protocol: none

Saving a `knowledge_source` whose `source.object` names no object, or whose `source.content` /
`source.metadataFields` names no field of its object, is now refused `400 VALIDATION_ERROR` with the rule
`os validate` reports: `knowledge-source-object-unknown` or `knowledge-source-field-unknown`. The refusal names
the object, and the field. Before, the same save was answered `503 SERVICE_UNAVAILABLE` ("could not be judged ...
try again") for an absent object, `403` "is a system object that does not opt into AI reads" for an absent `sys_`
object, and `403` "you may not query field ... hidden from you" for an absent field. With no security service, it
was admitted.

The check reads only the object's registered definition. `id` and the system columns the registry injects count
as fields of the object. Every door that asks it admits only a `manage_metadata` holder, and that caller is already
served every object definition whole. So for an object or a field that exists, every refusal stays as it was: a
hidden field, a system object without `enable.aiReadable`, a disabled package, a security service that cannot
answer, and a registry that throws. The fields a `where` reads are not checked for existence, as in `os validate`.
Original file line number Diff line number Diff line change
@@ -0,0 +1,258 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* [ADR-0161 K4, row 4] The save door's "does not exist" arm: a
* `knowledge_source` whose `source.object` names no object, or whose
* `source.content` / `source.metadataFields` names no field of its object, is
* refused at its save as a permanent reference mistake, by the rule names
* `os validate` reports (`knowledge-source-object-unknown`,
* `knowledge-source-field-unknown`): `400 VALIDATION_ERROR`, never the `503`
* that says "try again" nor a `403` that says "you may not".
*
* The arm is decided from the object's registered definition alone. Every
* door that asks this verdict admits only a `manage_metadata` holder, and that
* caller is served every object definition whole on the metadata plane
* (ADR-0106 D4), so the arm tells the author nothing they could not read.
* Its other half is pinned here byte for byte: for an object or a field that
* EXISTS, every refusal the author was given before is the one given now.
*/

import { describe, it, expect, vi } from 'vitest';
import type { IDataEngine, IKnowledgeAdapter } from '@objectstack/spec/contracts';
import type { ExecutionContext } from '@objectstack/spec/kernel';
import { KnowledgeService, type KnowledgeLogger } from '../knowledge-service.js';
import type { KnowledgeFieldSecurity } from '../knowledge-source-admission.js';

const MEMBER: ExecutionContext = { userId: 'u_member', positions: ['member'], permissions: [], isSystem: false };
const MANAGER: ExecutionContext = { userId: 'u_manager', positions: ['manager'], permissions: [], isSystem: false };
const SYSTEM: ExecutionContext = { positions: [], permissions: [], isSystem: true };

interface ObjectDef {
name: string;
enable?: Record<string, unknown>;
fields: Record<string, Record<string, unknown>>;
}

const TICKET: ObjectDef = {
name: 'ticket',
fields: {
title: { type: 'text' },
body: { type: 'textarea' },
salary_note: { type: 'textarea' },
status: { type: 'select' },
},
};
const SYS_CLOSED: ObjectDef = { name: 'sys_closed_note', fields: { title: { type: 'text' }, body: { type: 'textarea' } } };

const OBJECT_UNKNOWN = 'knowledge-source-object-unknown';
const FIELD_UNKNOWN = 'knowledge-source-field-unknown';

/**
* A security service shaped like the platform's: an object whose definition it
* cannot resolve gets no answer to either field question (`undefined`), and
* members may not query `salary_note`.
*/
function platformLikeSecurity(objects: ObjectDef[]): KnowledgeFieldSecurity {
const fieldsOf = (object: string) => {
const def = objects.find((o) => o.name === object);
return def ? ['id', ...Object.keys(def.fields)] : undefined;
};
return {
getQueryableFields: vi.fn(async (object: string, ctx?: ExecutionContext) => {
const all = fieldsOf(object);
return all && ctx?.userId === 'u_member' ? all.filter((f) => f !== 'salary_note') : all;
}),
getReadableFields: vi.fn(async (object: string) => fieldsOf(object)),
};
}

function setup(options: {
objects?: ObjectDef[];
security?: KnowledgeFieldSecurity | 'none';
disabled?: string[];
schemaThrows?: boolean;
/** An engine that exposes no schema registry at all. */
noSchemaRegistry?: boolean;
logger?: KnowledgeLogger;
}) {
const objects = options.objects ?? [TICKET, SYS_CLOSED];
const byName = new Map(objects.map((o) => [o.name, o]));
const engine = {
find: vi.fn(async () => []),
...(options.noSchemaRegistry
? {}
: {
getSchema: (name: string) => {
if (options.schemaThrows) throw new Error('registry unavailable');
return byName.get(name);
},
}),
registry: { isObjectPackageDisabled: (name: string) => (options.disabled ?? []).includes(name) },
} as unknown as IDataEngine;
const security = options.security === 'none' ? undefined : (options.security ?? platformLikeSecurity(objects));
const svc = new KnowledgeService({
dataEngine: engine,
logger: options.logger,
resolveSecurity: security ? () => security : undefined,
});
const adapter: IKnowledgeAdapter = { id: 'memory', upsert: async () => undefined, delete: async () => undefined, search: async () => [] };
svc.registerAdapter('memory', adapter);
return svc;
}

const item = (object: string, content: string[], extra: Record<string, unknown> = {}) => ({
name: 'authored', label: 'Authored', adapter: 'memory', source: { kind: 'object', object, content, ...extra },
});

type Refusal = { admitted: false; status: number; code: string; message: string; object: string; field?: string };

describe('the save door names an absent object as such, by the rule `os validate` reports', () => {
it.each([
['a business object nothing defines', 'tickt'],
['a `sys_` object nothing defines', 'sys_no_such_note'],
])('%s is refused VALIDATION_ERROR / 400, naming the object and `knowledge-source-object-unknown`', async (_label, object) => {
for (const security of [undefined, 'none'] as const) {
const svc = setup({ security });
const verdict = (await svc.admitAuthoredSource(item(object, ['body']), MANAGER)) as Refusal;
expect(verdict, String(security)).toMatchObject({ admitted: false, code: 'VALIDATION_ERROR', status: 400, object });
expect(verdict.field).toBeUndefined();
expect(verdict.message).toContain(`\`${OBJECT_UNKNOWN}\``);
expect(verdict.message).toContain(`names '${object}'`);
expect(verdict.message.startsWith('The knowledge source "authored" was not saved: ')).toBe(true);
// A permanent mistake: never worded as a transient fault or as a refusal of authority.
expect(verdict.message).not.toMatch(/could not be judged|try again|does not opt into AI reads|may not query/);
}
});

it('the engine itself is admitted: a package install is judged at validate and publish', async () => {
expect(await setup({}).admitAuthoredSource(item('tickt', ['body']), SYSTEM)).toEqual({ admitted: true });
});
});

describe('the save door names an absent field as such, by the rule `os validate` reports', () => {
it.each([
['`content`', item('ticket', ['body', 'bdy']), 'bdy', 'content'],
['`metadataFields`', item('ticket', ['body'], { metadataFields: ['stauts'] }), 'stauts', 'metadataFields'],
['`contentFields` (the retired spelling)', { name: 'authored', label: 'A', adapter: 'memory', source: { kind: 'object', object: 'ticket', contentFields: ['bdy'] } }, 'bdy', 'contentFields'],
])('a %s member is refused VALIDATION_ERROR / 400, naming the object, the field and `knowledge-source-field-unknown`', async (_label, body, field, key) => {
for (const ctx of [MEMBER, MANAGER]) {
for (const security of [undefined, 'none'] as const) {
const verdict = (await setup({ security }).admitAuthoredSource(body, ctx)) as Refusal;
expect(verdict, `${ctx.userId} ${String(security)}`).toMatchObject({
admitted: false, code: 'VALIDATION_ERROR', status: 400, object: 'ticket', field,
});
expect(verdict.message).toContain(`\`${FIELD_UNKNOWN}\``);
expect(verdict.message).toContain(`\`source.${key}\` names field '${field}', which object 'ticket' does not define`);
expect(verdict.message).not.toMatch(/hidden from you|may not query|could not be judged|try again/);
}
}
});

it('an absent field is named before a field the author may not query, wherever each is listed', async () => {
const verdict = (await setup({}).admitAuthoredSource(item('ticket', ['salary_note', 'bdy']), MEMBER)) as Refusal;
expect(verdict).toMatchObject({ admitted: false, code: 'VALIDATION_ERROR', status: 400, field: 'bdy' });
});

it('CONTROL: `id` and the system columns the registry injects are fields of the object, though it does not declare them', async () => {
const svc = setup({ security: 'none' });
expect(await svc.admitAuthoredSource(item('ticket', ['body', 'id'], { metadataFields: ['created_at', 'owner_id'] }), MANAGER))
.toEqual({ admitted: true });
});

it('door: duplicate words both arms for the duplicate\'s caller; the status, code, object and field are the save\'s', async () => {
const svc = setup({});
for (const body of [item('tickt', ['body']), item('ticket', ['bdy'])]) {
const saved = (await svc.admitAuthoredSource(body, MANAGER)) as Refusal;
const duplicated = (await svc.admitAuthoredSource(body, MANAGER, { door: 'duplicate' })) as Refusal;
const { message: _saved, ...savedRest } = saved;
const { message, ...duplicatedRest } = duplicated;
expect(duplicatedRest).toEqual(savedRest);
expect(message).toMatch(/^The knowledge source "authored" cannot be copied: /);
expect(message).toMatch(/, then duplicate the package again\.$/);
expect(message).not.toMatch(/save the source|save it again|was not saved|Nothing was written|nothing was copied|the save /i);
}
});
});

/**
* The arm's other half: what EXISTS keeps the answer it had, byte for byte —
* the sentences below are the ones the door gave before the arm existed.
*/
describe('no permission answer changes for an object or a field that exists', () => {
it('a field that exists but is hidden from the author keeps its PERMISSION_DENIED / 403 sentence', async () => {
const svc = setup({});
expect(await svc.admitAuthoredSource(item('ticket', ['body', 'salary_note']), MEMBER)).toEqual({
admitted: false,
status: 403,
code: 'PERMISSION_DENIED',
object: 'ticket',
field: 'salary_note',
message:
'The knowledge source "authored" was not saved: you may not query field \'salary_note\' of object \'ticket\' (it is hidden ' +
'from you, or served to you masked), and the index would hold its text unmasked. Remove the field from `content` ' +
'and `metadataFields`, or have someone who may query it save the source.',
});
// The same source, by an author who may query the field.
expect(await svc.admitAuthoredSource(item('ticket', ['body', 'salary_note']), MANAGER)).toEqual({ admitted: true });
});

it('a `sys_` object that exists without `enable.aiReadable` keeps its PERMISSION_DENIED / 403 sentence', async () => {
expect(await setup({}).admitAuthoredSource(item('sys_closed_note', ['body']), MANAGER)).toEqual({
admitted: false,
status: 403,
code: 'PERMISSION_DENIED',
object: 'sys_closed_note',
message:
'The knowledge source "authored" was not saved: \'sys_closed_note\' is a system object that does not opt into AI reads ' +
'(`enable.aiReadable: true`), so its records are not indexed for retrieval.',
});
});

it('an object that exists but whose fields the security service cannot answer keeps its SERVICE_UNAVAILABLE / 503 sentence', async () => {
const mute: KnowledgeFieldSecurity = { getQueryableFields: async () => undefined, getReadableFields: async () => undefined };
expect(await setup({ security: mute }).admitAuthoredSource(item('ticket', ['body']), MANAGER)).toEqual({
admitted: false,
status: 503,
code: 'SERVICE_UNAVAILABLE',
object: 'ticket',
message:
'The knowledge source "authored" was not saved: whether you may search object \'ticket\' could not be judged (the security ' +
"service did not answer which fields of 'ticket' you may read), and an author must be allowed to search what their source " +
'indexes. Nothing was written; try again.',
});
});

it('an object of a disabled package keeps its PERMISSION_DENIED / 403 sentence, whether or not its definition is served', async () => {
for (const objects of [[TICKET], []]) {
expect(await setup({ objects, security: 'none', disabled: ['ticket'] }).admitAuthoredSource(item('ticket', ['bdy']), MANAGER))
.toEqual({
admitted: false,
status: 403,
code: 'PERMISSION_DENIED',
object: 'ticket',
message:
'The knowledge source "authored" was not saved: its object \'ticket\' belongs to a disabled package, and a disabled ' +
"package's records are not indexed or searched. Enable the package, or index another object.",
});
}
});

it('a registry that throws keeps its SERVICE_UNAVAILABLE / 503 sentence and is reported once', async () => {
const logger = { warn: vi.fn(), error: vi.fn() };
expect(await setup({ schemaThrows: true, logger }).admitAuthoredSource(item('tickt', ['body']), MANAGER)).toEqual({
admitted: false,
status: 503,
code: 'SERVICE_UNAVAILABLE',
object: 'tickt',
message:
'The knowledge source "authored" was not saved: whether you may search object \'tickt\' could not be judged (registry ' +
'unavailable), and an author must be allowed to search what their source indexes. Nothing was written; try again.',
});
expect(logger.error).toHaveBeenCalledTimes(1);
});

it('an engine with no schema registry draws no "does not exist" verdict: absence of a registry is not absence of the object', async () => {
expect(await setup({ noSchemaRegistry: true, security: 'none' }).admitAuthoredSource(item('tickt', ['bdy']), MANAGER))
.toEqual({ admitted: true });
});
});
Loading
Loading