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
@@ -1,3 +1,3 @@
---
'@objectstack/metadata-core': minor
'@objectstack/objectql': patch
Expand All @@ -23,4 +23,4 @@

## FROM → TO

- A deployment whose stack does not declare `requires: ['knowledge']`, where authors save knowledge sources → add `requires: ['knowledge']` to the stack, restart, then save the source.
- A deployment whose stack neither declares `requires: ['knowledge']` nor ships a `knowledgeSources` entry, where authors save knowledge sources → add `requires: ['knowledge']` to the stack, restart, then save the source.
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
---
'@objectstack/metadata-core': patch
'@objectstack/runtime': patch
'@objectstack/spec': patch
---

fix(runtime): a knowledge source save refused for a scoped-factory miss says so, and the package duplicate words its remedy for its caller

Clause-②: yes (widening) — `@objectstack/metadata-core` adds `knowledgeServiceNotInScope`, `KnowledgeServiceNotInScope`, `KnowledgeSourceSaveDoor` and the optional `door` input on `authoredKnowledgeSourceRefusal`; `@objectstack/runtime`'s exported `DomainHandlerDeps` adds the optional `classifyServiceOrLoud`, which makes `ClassifiedServiceLookup` reachable
Metadata-protocol: none

- **`@objectstack/metadata-core`.** `authoredKnowledgeSourceRefusal` takes an optional `door` (`'save'`, the default, or `'duplicate'`). With `'duplicate'` each refusal it composes tells the caller to duplicate the package again, and does not say "Nothing was written". A door's knowledge lookup can now answer `knowledgeServiceNotInScope(scopeId)` when a `knowledge` registration serves no instance in the request's environment, a host's scoped factory for example. That save is refused `503 SERVICE_UNAVAILABLE` with its own sentence, which names the environment and does not say the deployment runs no knowledge service or point to the stack's `requires`. The `/meta` save's sentences are unchanged.
- **`@objectstack/runtime`.** The dispatcher's `/meta` save, the MCP `save_metadata_draft` tool and the package duplicate now tell a scoped-factory miss apart from a deployment with no knowledge service, through the new optional `DomainHandlerDeps.classifyServiceOrLoud`. A deps without that member answers both misses as before. The duplicate door's refusal now says once that nothing was copied, and tells the caller to duplicate the package again. The platform's own `KnowledgeServicePlugin` registers a plain instance, so its path is unchanged.
- **`@objectstack/spec`.** The upgrade-guide entry `knowledge-source-save-refused-without-knowledge-service` now names only a deployment whose stack neither declares `requires: ['knowledge']` nor ships a `knowledgeSources` entry. A stack that ships a source already mounts the service.
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
*/

import { describe, it, expect, vi } from 'vitest';
import { authoredKnowledgeSourceRefusal, KNOWLEDGE_SOURCE_ADMISSION_SERVICE } from './knowledge-source-save-admission.js';
import { authoredKnowledgeSourceRefusal, knowledgeServiceNotInScope, KNOWLEDGE_SOURCE_ADMISSION_SERVICE } from './knowledge-source-save-admission.js';

const ITEM = { name: 'faq', label: 'FAQ', adapter: 'memory', source: { kind: 'object', object: 'article', content: ['body'] } };
const AUTHOR = { userId: 'u_author', systemPermissions: ['manage_metadata', 'manage_knowledge_sources'] };
Expand Down Expand Up @@ -89,6 +89,60 @@ describe('authoredKnowledgeSourceRefusal — source admission at save', () => {
expect(thrown?.message).toContain('registry unavailable');
});

/**
* A registration that serves no instance in the request's scope (a host's
* scoped factory): the deployment does run a knowledge service, so it is
* not told it runs none, nor sent to the stack's `requires`.
*/
it('a knowledge service registered with no instance in this scope: refused SERVICE_UNAVAILABLE / 503 with its own sentence, not the no-service one', async () => {
const refusal = await authoredKnowledgeSourceRefusal({
type: 'knowledge_source', item: ITEM, executionContext: AUTHOR,
resolveKnowledgeService: async () => knowledgeServiceNotInScope('northwind'),
});
expect(refusal).toMatchObject({ status: 503, code: 'SERVICE_UNAVAILABLE' });
expect(refusal?.message).toMatch(
/^The knowledge source 'faq' was not saved: the knowledge service registered on this deployment serves no instance for environment 'northwind', so nothing would load, index or search it there\./,
);
expect(refusal?.message).not.toContain('runs no knowledge service');
expect(refusal?.message).not.toContain("requires: ['knowledge']");
expect(refusal?.message).toMatch(/save the source again\. Nothing was written\.$/);
// The engine's own write is not asked, scope miss or not.
const resolve = vi.fn(() => knowledgeServiceNotInScope('northwind'));
expect(await authoredKnowledgeSourceRefusal({ type: 'knowledge_source', item: ITEM, executionContext: { isSystem: true }, resolveKnowledgeService: resolve })).toBeUndefined();
expect(resolve).not.toHaveBeenCalled();
});

/**
* The package duplicate copies a package's sources: its caller is told to
* duplicate the package again, and the door's prefix says once that
* nothing was copied, so the sentence carries no "Nothing was written".
*/
it('door: duplicate words each refusal the predicate composes for the duplicate\'s caller', async () => {
const ask = (resolveKnowledgeService: () => unknown, item: unknown = ITEM) =>
authoredKnowledgeSourceRefusal({ type: 'knowledge_source', item, executionContext: AUTHOR, resolveKnowledgeService, door: 'duplicate' });

const none = await ask(() => undefined);
expect(none).toMatchObject({ status: 503, code: 'SERVICE_UNAVAILABLE' });
expect(none?.message).toMatch(/^The knowledge source 'faq' cannot be copied: this deployment runs no knowledge service/);
expect(none?.message).toMatch(/requires: \['knowledge'\].*restart the server, then duplicate the package again: /);

const scoped = await ask(() => knowledgeServiceNotInScope('northwind'));
expect(scoped).toMatchObject({ status: 503, code: 'SERVICE_UNAVAILABLE' });
expect(scoped?.message).toMatch(/^The knowledge source 'faq' cannot be copied: the knowledge service registered on this deployment serves no instance for environment 'northwind'/);
expect(scoped?.message).toMatch(/duplicate the package again\.$/);

const unresolved = await ask(async () => { throw new Error('factory failed'); });
expect(unresolved).toMatchObject({ status: 503, code: 'SERVICE_UNAVAILABLE' });
expect(unresolved?.message).toMatch(/^The knowledge source cannot be copied: /);
expect(unresolved?.message).toMatch(/Duplicate the package again\.$/);

for (const refusal of [none, scoped, unresolved]) {
expect(refusal?.message).not.toMatch(/save the source|Nothing was written/);
}
// A verdict of the knowledge service is its own sentence, passed through as before.
expect(await ask(() => serviceAnswering(REFUSED))).toEqual({ status: 403, code: 'PERMISSION_DENIED', message: REFUSED.message });
});

it('`isSystem: false` is not a bypass', async () => {
const service = serviceAnswering(REFUSED);
const refusal = await authoredKnowledgeSourceRefusal({ type: 'knowledge_source', item: ITEM, executionContext: { ...AUTHOR, isSystem: false }, resolveKnowledgeService: () => service });
Expand Down
122 changes: 107 additions & 15 deletions packages/metadata-core/src/knowledge-source-save-admission.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,26 @@
* service answers at index and search for a store that is not mounted.
* Nothing was written.
*
* ## A knowledge service registered, with no instance in this scope
*
* A host can register `knowledge` per environment, as a scoped factory that
* answers no instance for some of them. The deployment does run a knowledge
* service then, so the sentence above would be false, and its remedy (the
* stack's `requires`) is not the fix: the host's registration decides. A door
* whose lookup tells that miss apart answers it as
* {@link knowledgeServiceNotInScope}, and the save is refused with its own
* sentence ({@link noKnowledgeServiceInScopeRefusal}), the same status and
* code. The platform's `KnowledgeServicePlugin` registers a plain instance,
* so its own service never reaches this.
*
* ## The door's wording
*
* The sentences name the save's remedy (save the source again, nothing was
* written). A door that copies sources rather than saves one, the package
* duplicate, asks with `door: 'duplicate'` and gets its caller's remedy
* (duplicate the package again) and no "nothing was written" of its own: that
* door's prefix says once that nothing was copied.
*
* ## Fail direction
*
* Access-narrowing, so it fails closed: a knowledge service that cannot be
Expand Down Expand Up @@ -78,18 +98,61 @@ export type AuthoredKnowledgeSourceVerdict =
| { admitted: true }
| ({ admitted: false } & AuthoredKnowledgeSourceRefusal);

/**
* Which door asks, for the remedy its caller is told: `save` (the default) for
* a door that saves one item, `duplicate` for the package duplicate, which
* copies a package's sources.
*/
export type KnowledgeSourceSaveDoor = 'save' | 'duplicate';

/** Brand of {@link knowledgeServiceNotInScope}, shared across copies of this module. */
const NOT_IN_SCOPE = Symbol.for('@objectstack/metadata-core/knowledge-service-not-in-scope');

/**
* What a door's `resolveKnowledgeService` answers when a `knowledge`
* registration exists and the lookup made in the request's scope produced no
* instance (a host's scoped factory that serves no service for that
* environment). Built by {@link knowledgeServiceNotInScope}.
*/
export interface KnowledgeServiceNotInScope {
readonly [NOT_IN_SCOPE]: true;
/** The scope the lookup was made in: the request's environment. */
readonly scopeId: string;
}

/** The answer a door's lookup gives for a scope-relative miss of the `knowledge` service. */
export function knowledgeServiceNotInScope(scopeId: string): KnowledgeServiceNotInScope {
return Object.freeze({ [NOT_IN_SCOPE]: true as const, scopeId });
}

function isKnowledgeServiceNotInScope(value: unknown): value is KnowledgeServiceNotInScope {
return typeof value === 'object' && value !== null && (value as Record<symbol, unknown>)[NOT_IN_SCOPE] === true;
}

/** The member of the `knowledge` service the doors ask, reached duck-typed. */
export interface KnowledgeSourceSaveAdmitter {
admitAuthoredSource(item: unknown, context: unknown): Promise<AuthoredKnowledgeSourceVerdict>;
}

function unavailable(why: string): AuthoredKnowledgeSourceRefusal {
/** The remedy and the no-op each door's caller is told. */
const DOOR_WORDING: Readonly<Record<KnowledgeSourceSaveDoor, { notDone: string; retry: string; nothingDone: string }>> = {
save: { notDone: 'was not saved', retry: 'save the source again', nothingDone: ' Nothing was written.' },
duplicate: { notDone: 'cannot be copied', retry: 'duplicate the package again', nothingDone: '' },
};

function sourceSubject(item: unknown): string {
const name = (item as { name?: unknown } | null | undefined)?.name;
return typeof name === 'string' && name !== '' ? `The knowledge source '${name}'` : 'The knowledge source';
}

function unavailable(why: string, door: KnowledgeSourceSaveDoor): AuthoredKnowledgeSourceRefusal {
const wording = DOOR_WORDING[door];
return {
status: 503,
code: 'SERVICE_UNAVAILABLE',
message:
`The knowledge source was not saved: whether its author may search what it would index could not be ` +
`judged (${why}). Nothing was written; try again.`,
`The knowledge source ${wording.notDone}: whether its author may search what it would index could not be ` +
`judged (${why}).` + (door === 'save' ? ' Nothing was written; try again.' : ' Duplicate the package again.'),
};
}

Expand All @@ -100,18 +163,41 @@ function unavailable(why: string): AuthoredKnowledgeSourceRefusal {
* while the process runs, so the remedy is ordered: the token, a restart, then
* the save.
*/
function noKnowledgeServiceRefusal(item: unknown): AuthoredKnowledgeSourceRefusal {
const name = (item as { name?: unknown } | null | undefined)?.name;
const source = typeof name === 'string' && name !== '' ? `The knowledge source '${name}'` : 'The knowledge source';
function noKnowledgeServiceRefusal(item: unknown, door: KnowledgeSourceSaveDoor): AuthoredKnowledgeSourceRefusal {
const wording = DOOR_WORDING[door];
return {
status: 503,
code: 'SERVICE_UNAVAILABLE',
message:
`${sourceSubject(item)} ${wording.notDone}: this deployment runs no knowledge service, so nothing would ` +
"load, index or search it. Add requires: ['knowledge'] to the stack (or, on a host that composes its own " +
'kernel, KnowledgeServicePlugin from @objectstack/service-knowledge and a knowledge store), restart the ' +
`server, then ${wording.retry}: the service is mounted when the server starts, never while it runs.` +
wording.nothingDone,
};
}

/**
* The refusal of an author's `knowledge_source` save where a `knowledge`
* registration exists and answers no instance for the request's environment
* (a host's scoped factory). The deployment does run a knowledge service, so
* the stack's `requires` is not the remedy: the host's registration decides
* which environments it serves.
*/
function noKnowledgeServiceInScopeRefusal(
item: unknown,
scopeId: string,
door: KnowledgeSourceSaveDoor,
): AuthoredKnowledgeSourceRefusal {
const wording = DOOR_WORDING[door];
return {
status: 503,
code: 'SERVICE_UNAVAILABLE',
message:
`${source} was not saved: this deployment runs no knowledge service, so nothing would load, index or ` +
"search it. Add requires: ['knowledge'] to the stack (or, on a host that composes its own kernel, " +
'KnowledgeServicePlugin from @objectstack/service-knowledge and a knowledge store), restart the server, ' +
'then save the source again: the service is mounted when the server starts, never while it runs. ' +
'Nothing was written.',
`${sourceSubject(item)} ${wording.notDone}: the knowledge service registered on this deployment serves ` +
`no instance for environment '${scopeId}', so nothing would load, index or search it there. The host's ` +
`knowledge service registration decides which environments it serves; once it serves '${scopeId}', ` +
`${wording.retry}.` + wording.nothingDone,
};
}

Expand All @@ -121,7 +207,9 @@ function noKnowledgeServiceRefusal(item: unknown): AuthoredKnowledgeSourceRefusa
*
* `resolveKnowledgeService` answers the request environment's `knowledge`
* service, `undefined` when none is registered (an author's save is then
* refused), and throws when one is registered and cannot be resolved.
* refused), {@link knowledgeServiceNotInScope} when one is registered and
* serves no instance in the request's scope (refused, with its own sentence),
* and throws when one is registered and cannot be resolved.
*/
export async function authoredKnowledgeSourceRefusal(input: {
/** The metadata type saved, in any URL spelling the protocol accepts. */
Expand All @@ -131,23 +219,27 @@ export async function authoredKnowledgeSourceRefusal(input: {
/** The author's execution context. */
executionContext: unknown;
resolveKnowledgeService: () => Promise<unknown> | unknown;
/** The door that asks, for its caller's remedy; `save` when absent. */
door?: KnowledgeSourceSaveDoor;
}): Promise<AuthoredKnowledgeSourceRefusal | undefined> {
if (canonicalMetaUrlType(input.type) !== KNOWLEDGE_SOURCE_TYPE) return undefined;
if ((input.executionContext as { isSystem?: unknown } | null | undefined)?.isSystem === true) return undefined;
const door: KnowledgeSourceSaveDoor = input.door ?? 'save';
let service: unknown;
try {
service = await input.resolveKnowledgeService();
} catch (err) {
return unavailable(`the knowledge service could not be resolved: ${err instanceof Error ? err.message : String(err)}`);
return unavailable(`the knowledge service could not be resolved: ${err instanceof Error ? err.message : String(err)}`, door);
}
if (service === undefined || service === null) return noKnowledgeServiceRefusal(input.item);
if (service === undefined || service === null) return noKnowledgeServiceRefusal(input.item, door);
if (isKnowledgeServiceNotInScope(service)) return noKnowledgeServiceInScopeRefusal(input.item, service.scopeId, door);
const admit = (service as Partial<KnowledgeSourceSaveAdmitter>).admitAuthoredSource;
if (typeof admit !== 'function') return undefined;
let verdict: AuthoredKnowledgeSourceVerdict;
try {
verdict = await admit.call(service, input.item, input.executionContext);
} catch (err) {
return unavailable(err instanceof Error ? err.message : String(err));
return unavailable(err instanceof Error ? err.message : String(err), door);
}
if (!verdict || verdict.admitted === true) return undefined;
return { status: verdict.status, code: verdict.code, message: verdict.message };
Expand Down
Loading
Loading