diff --git a/.changeset/38210-knowledge-duplicate-door-service-verdict-wording.md b/.changeset/38210-knowledge-duplicate-door-service-verdict-wording.md new file mode 100644 index 00000000000..bdb275c9906 --- /dev/null +++ b/.changeset/38210-knowledge-duplicate-door-service-verdict-wording.md @@ -0,0 +1,12 @@ +--- +'@objectstack/service-knowledge': patch +'@objectstack/metadata-core': patch +--- + +fix(service-knowledge): a package duplicate that the knowledge service itself refuses is told the source cannot be copied and to duplicate the package again + +Clause-②: yes (widening) — `@objectstack/service-knowledge`'s `KnowledgeService.admitAuthoredSource` takes an optional third input `options: { door?: 'save' | 'duplicate' }`; `@objectstack/metadata-core`'s `KnowledgeSourceSaveAdmitter.admitAuthoredSource` declares the same optional `options` input +Metadata-protocol: none + +- **`@objectstack/service-knowledge`.** `admitAuthoredSource(item, ctx, { door: 'duplicate' })` words every verdict for the package duplicate's caller: the source "cannot be copied", a verdict that could not be judged ends "Duplicate the package again.", and a field the caller may not query is fixed by removing it and duplicating the package again, or by someone who may query it duplicating the package. It never says "save the source" or "Nothing was written". The status, code, object and field are the same as at a save. With no `door`, or `door: 'save'`, every sentence is byte-identical to before. +- **`@objectstack/metadata-core`.** `authoredKnowledgeSourceRefusal({ door: 'duplicate' })` hands the door on to the knowledge service's `admitAuthoredSource`, so the package duplicate's refusal says once, in its prefix, that nothing was copied. A save hands on no door: the service is asked with the item and the context alone, as before. diff --git a/packages/metadata-core/src/knowledge-source-save-admission.test.ts b/packages/metadata-core/src/knowledge-source-save-admission.test.ts index 496e30fa6e0..b809d3c2605 100644 --- a/packages/metadata-core/src/knowledge-source-save-admission.test.ts +++ b/packages/metadata-core/src/knowledge-source-save-admission.test.ts @@ -139,8 +139,19 @@ describe('authoredKnowledgeSourceRefusal — source admission at save', () => { 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 }); + // A verdict of the knowledge service is its own sentence, passed through + // as it answers: the service is asked with this door, so it words it. + const service = serviceAnswering(REFUSED); + expect(await ask(() => service)).toEqual({ status: 403, code: 'PERMISSION_DENIED', message: REFUSED.message }); + expect(service.admitAuthoredSource).toHaveBeenCalledWith(ITEM, AUTHOR, { door: 'duplicate' }); + }); + + it('a save hands the knowledge service no door: it is asked with the item and the context alone', async () => { + for (const door of [undefined, 'save'] as const) { + const service = serviceAnswering({ admitted: true }); + await authoredKnowledgeSourceRefusal({ type: 'knowledge_source', item: ITEM, executionContext: AUTHOR, resolveKnowledgeService: () => service, ...(door ? { door } : {}) }); + expect(service.admitAuthoredSource.mock.calls, String(door)).toEqual([[ITEM, AUTHOR]]); + } }); it('`isSystem: false` is not a bypass', async () => { diff --git a/packages/metadata-core/src/knowledge-source-save-admission.ts b/packages/metadata-core/src/knowledge-source-save-admission.ts index ccd41d5f8cd..3f33d1411f5 100644 --- a/packages/metadata-core/src/knowledge-source-save-admission.ts +++ b/packages/metadata-core/src/knowledge-source-save-admission.ts @@ -69,7 +69,10 @@ * 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. + * door's prefix says once that nothing was copied. The door is handed on to + * the knowledge service's own verdict + * ({@link KnowledgeSourceSaveAdmitter.admitAuthoredSource}), which words it + * the same way; a save hands on no door. * * ## Fail direction * @@ -129,9 +132,18 @@ function isKnowledgeServiceNotInScope(value: unknown): value is KnowledgeService return typeof value === 'object' && value !== null && (value as Record)[NOT_IN_SCOPE] === true; } -/** The member of the `knowledge` service the doors ask, reached duck-typed. */ +/** + * The member of the `knowledge` service the doors ask, reached duck-typed. + * `options.door` is passed only by a door other than `save` (the package + * duplicate), so the service words its own verdict for that door's caller; a + * save asks with the item and the context alone, as before. + */ export interface KnowledgeSourceSaveAdmitter { - admitAuthoredSource(item: unknown, context: unknown): Promise; + admitAuthoredSource( + item: unknown, + context: unknown, + options?: { door?: KnowledgeSourceSaveDoor }, + ): Promise; } /** The remedy and the no-op each door's caller is told. */ @@ -237,7 +249,11 @@ export async function authoredKnowledgeSourceRefusal(input: { if (typeof admit !== 'function') return undefined; let verdict: AuthoredKnowledgeSourceVerdict; try { - verdict = await admit.call(service, input.item, input.executionContext); + // The service words its verdict for the door: a duplicate is asked with + // its door, a save as before. + verdict = await (door === 'save' + ? admit.call(service, input.item, input.executionContext) + : admit.call(service, input.item, input.executionContext, { door })); } catch (err) { return unavailable(err instanceof Error ? err.message : String(err), door); } diff --git a/packages/runtime/package.json b/packages/runtime/package.json index cb0f26f010c..5ee1c436df3 100644 --- a/packages/runtime/package.json +++ b/packages/runtime/package.json @@ -81,6 +81,7 @@ "@objectstack/service-analytics": "workspace:*", "@objectstack/service-datasource": "workspace:*", "@objectstack/service-job": "workspace:*", + "@objectstack/service-knowledge": "workspace:*", "@objectstack/service-messaging": "workspace:*", "@objectstack/service-package": "workspace:*", "@objectstack/service-record-context": "workspace:*", diff --git a/packages/runtime/src/domains/packages-knowledge-source-gate.test.ts b/packages/runtime/src/domains/packages-knowledge-source-gate.test.ts index 6738a59c175..f4a287ca8b8 100644 --- a/packages/runtime/src/domains/packages-knowledge-source-gate.test.ts +++ b/packages/runtime/src/domains/packages-knowledge-source-gate.test.ts @@ -26,6 +26,9 @@ import '@objectstack/metadata'; import { describe, it, expect, vi } from 'vitest'; import { ObjectKernel, ServiceLifecycle } from '@objectstack/core'; +import type { Plugin, PluginContext } from '@objectstack/core'; +// The platform's knowledge service, for the doors' wording of its own verdict. +import { KnowledgeServicePlugin, type KnowledgeService } from '@objectstack/service-knowledge'; import { HttpDispatcher } from '../http-dispatcher.js'; const ctx = (executionContext: any): any => ({ request: {}, environmentId: 'platform', executionContext }); @@ -236,8 +239,8 @@ describe('/packages — duplicate admits each knowledge source it copies for the message: "The knowledge source \"faq\" was not saved: you may not query field 'salary' of object 'article'.", }; /** A stack whose kernel also serves a knowledge service answering `admit`. */ - function withKnowledge(holding: Holding, admit: (item: unknown, ctx: unknown) => unknown) { - const admitAuthoredSource = vi.fn(async (item: unknown, c: unknown) => admit(item, c)); + function withKnowledge(holding: Holding, admit: (item: unknown, ctx: unknown, options?: { door?: unknown }) => unknown) { + const admitAuthoredSource = vi.fn(async (item: unknown, c: unknown, options?: { door?: unknown }) => admit(item, c, options)); return { ...make(holding, { admitAuthoredSource }), admitAuthoredSource }; } @@ -249,28 +252,35 @@ describe('/packages — duplicate admits each knowledge source it copies for the expect(r.response?.body?.error?.message).toContain('nothing was copied'); expect(r.response?.body?.error?.message).toContain(REFUSAL.message); expect(s.protocol.duplicatePackage).not.toHaveBeenCalled(); - // Judged as the caller, on the item the package holds. - expect(s.admitAuthoredSource).toHaveBeenCalledWith(SOURCE_ITEM, caller.executionContext); + // Judged as the caller, on the item the package holds, and asked for this door's wording. + expect(s.admitAuthoredSource).toHaveBeenCalledWith(SOURCE_ITEM, caller.executionContext, { door: 'duplicate' }); }); - // The save refusal of a source whose `adapter` the deployment does not - // mount is a `400`, where the gates' own are `403`: the door answers the - // predicate's status and sentence, never one of its own. - it('a source naming an adapter the deployment does not mount refuses the duplicate 400 VALIDATION_ERROR with the save\'s sentence, and nothing is copied', async () => { - const UNMOUNTED = { + // The refusal of a source whose `adapter` the deployment does not mount is + // a `400`, where the gates' own are `403`: the door answers the service's + // status and its sentence for this door, worded for the duplicate's caller + // (the service is asked with `door: 'duplicate'`), never one of its own. + it('a source naming an adapter the deployment does not mount refuses the duplicate 400 VALIDATION_ERROR with the service\'s duplicate-door sentence, and nothing is copied', async () => { + const verdictFor = (door: unknown) => ({ admitted: false, status: 400, code: 'VALIDATION_ERROR', - message: "The knowledge source \"faq\" was not saved: it names adapter 'ragflow', which this deployment does not mount (mounted: memory).", - }; + message: door === 'duplicate' + ? "The knowledge source \"faq\" cannot be copied: it names adapter 'ragflow', which this deployment does not mount (mounted: memory), and a source's `adapter` must name a mounted store. Mount the 'ragflow' store and duplicate the package again." + : "The knowledge source \"faq\" was not saved: it names adapter 'ragflow', which this deployment does not mount (mounted: memory), and a source's `adapter` must name a mounted store. Mount the 'ragflow' store and save it again.", + }); const held = { ...SOURCE_ITEM, adapter: 'ragflow' }; - const s = withKnowledge({ items: [held] }, () => UNMOUNTED); + const s = withKnowledge({ items: [held] }, (_item: unknown, _ctx: unknown, options?: { door?: unknown }) => verdictFor(options?.door)); const caller = authed(BOTH); const r = await call(s, DUPLICATE, caller); expect(r.response?.status).toBe(400); expect(r.response?.body?.error?.code).toBe('VALIDATION_ERROR'); - expect(r.response?.body?.error?.message).toContain('nothing was copied'); - expect(r.response?.body?.error?.message).toContain(UNMOUNTED.message); + const message: string = r.response?.body?.error?.message; + expect(message).toContain(verdictFor('duplicate').message); + expect(message).toContain('cannot be copied'); + expect(message).toMatch(/duplicate the package again/i); + expect(message).not.toMatch(/save the source|save it again|Nothing was written|was not saved/); + expect(message.match(/nothing was copied/gi)).toHaveLength(1); expect(s.protocol.duplicatePackage).not.toHaveBeenCalled(); - expect(s.admitAuthoredSource).toHaveBeenCalledWith(held, caller.executionContext); + expect(s.admitAuthoredSource).toHaveBeenCalledWith(held, caller.executionContext, { door: 'duplicate' }); }); it('every source is asked about: the second one refused refuses the duplicate', async () => { @@ -435,3 +445,130 @@ describe('/packages — what the gate leaves alone', () => { expect(s.registry.installPackage).toHaveBeenCalled(); }); }); + +/** + * The verdict the platform's own knowledge service answers, through both doors + * that ask it: the package duplicate and the `/meta` save. A real kernel runs + * `KnowledgeServicePlugin` over host doubles (the engine, the security + * service, the metadata protocol), so the sentence each door returns is the + * one `admitAuthoredSource` composes for that door, not a double's. + * + * The duplicate's caller copies a package: never told to save a source, and + * told once, by the door's prefix, that nothing was copied. The `/meta` + * save's sentences are the control, pinned byte for byte. + */ +describe('/packages duplicate and /meta save on a real kernel running KnowledgeServicePlugin: each door words the service\'s own verdict', () => { + const ARTICLE = { + name: 'article', + fields: { id: { type: 'text' }, title: { type: 'text' }, body: { type: 'textarea' }, salary: { type: 'textarea' } }, + }; + const FIELDS = Object.keys(ARTICLE.fields); + type Arm = 'transient' | 'content' | 'where' | 'title'; + const sourceFor = (arm: Arm) => ({ + name: 'faq', label: 'FAQ', adapter: 'memory', + source: { + kind: 'object', object: 'article', content: arm === 'content' ? ['body', 'salary'] : ['body'], + ...(arm === 'where' ? { where: { salary: { $ne: null } } } : {}), + }, + }); + /** What the save door answers today, byte for byte. */ + const SAVE_VERDICT: Record = { + transient: { + status: 503, code: 'SERVICE_UNAVAILABLE', + message: 'The knowledge source "faq" was not saved: whether you may search object \'article\' could not be judged ' + + '(registry unavailable), and an author must be allowed to search what their source indexes. Nothing was written; try again.', + }, + content: { + status: 403, code: 'PERMISSION_DENIED', + message: 'The knowledge source "faq" was not saved: you may not query field \'salary\' of object \'article\' (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.', + }, + where: { + status: 403, code: 'PERMISSION_DENIED', + message: 'The knowledge source "faq" was not saved: its `where` reads field \'salary\' of object \'article\', which you may ' + + 'not query (it is hidden from you, or served to you masked), and the source would select its records by that ' + + 'field. Remove the field from `where`, or have someone who may query it save the source.', + }, + title: { + status: 403, code: 'PERMISSION_DENIED', + message: 'The knowledge source "faq" was not saved: you may not query field \'title\' of object \'article\' (it is hidden ' + + 'from you, or served to you masked), and the index would hold its text unmasked. The source does not list it: ' + + "it is the object's display field, which every document carries as its title. Have someone who may query it save the source.", + }, + }; + + async function bootPlatformKnowledge(arm: Arm) { + const s = make({ items: [sourceFor(arm)] }); + const saveMetaItem = vi.fn(async ({ name }: any) => ({ success: true, name })); + Object.assign(s.protocol, { saveMetaItem }); + // The engine the knowledge service reads schemas through; the package registry rides on it. + Object.assign(s.kernelServices.objectql, { + getSchema: (name: string) => { + if (arm === 'transient') throw new Error('registry unavailable'); + return name === 'article' ? ARTICLE : undefined; + }, + find: vi.fn(async () => []), + }); + const hidden = arm === 'title' ? 'title' : arm === 'transient' ? undefined : 'salary'; + const security = { + getQueryableFields: vi.fn(async () => FIELDS.filter((f) => f !== hidden)), + getReadableFields: vi.fn(async () => FIELDS), + }; + const doubles: Record = { ...s.kernelServices, security }; + const host: Plugin = { + name: 'test.duplicate-door.host', + version: '1.0.0', + type: 'standard', + async init(ctx: PluginContext) { + for (const [name, service] of Object.entries(doubles)) ctx.registerService(name, service); + }, + } as Plugin; + const kernel = new ObjectKernel({ gracefulShutdown: false, skipSystemValidation: true }); + await kernel.use(host); + await kernel.use(new KnowledgeServicePlugin({ enableEventSync: false })); + await kernel.bootstrap(); + const knowledge = kernel.getService('knowledge'); + knowledge.registerAdapter('memory', { id: 'memory', upsert: async () => undefined, delete: async () => undefined, search: async () => [] }); + const dispatcher = new HttpDispatcher(kernel as any); + return { + ...s, kernel, saveMetaItem, + duplicate: (caller: any) => dispatcher.handlePackages('/pkg-a/duplicate', 'POST', { targetPackageId: 'pkg-b' }, {}, caller), + save: (caller: any) => dispatcher.handleMetadata('/knowledge_source/faq', caller, 'PUT', JSON.parse(JSON.stringify(sourceFor(arm)))), + }; + } + + for (const arm of ['transient', 'content', 'where', 'title'] as const) { + it(`${arm}: the duplicate is told nothing was copied once and to duplicate the package, never to save, and nothing is copied`, async () => { + const stack = await bootPlatformKnowledge(arm); + try { + const expected = SAVE_VERDICT[arm]; + const r = await stack.duplicate(authed(BOTH)); + expect(r.response?.status).toBe(expected.status); + expect(r.response?.body?.error?.code).toBe(expected.code); + const message: string = r.response?.body?.error?.message; + expect(message.startsWith('Duplicating package "pkg-a" is refused, and nothing was copied. The knowledge source "faq" cannot be copied: '), message).toBe(true); + expect(message).not.toMatch(/save the source|save it again|Nothing was written|was not saved|the save /); + expect(message.match(/nothing was copied/gi)).toHaveLength(1); + expect(message).toMatch(arm === 'title' ? /Have someone who may query it duplicate the package\.$/ : /duplicate the package again/i); + expect(stack.protocol.duplicatePackage).not.toHaveBeenCalled(); + } finally { + await stack.kernel.shutdown(); + } + }); + + it(`${arm}: CONTROL — the same verdict at the /meta save door is byte for byte what it was, and nothing is saved`, async () => { + const stack = await bootPlatformKnowledge(arm); + try { + const expected = SAVE_VERDICT[arm]; + const saved = await stack.save(authed(BOTH)); + expect(saved.response?.status).toBe(expected.status); + expect(saved.response?.body?.error?.code).toBe(expected.code); + expect(saved.response?.body?.error?.message).toBe(expected.message); + expect(stack.saveMetaItem).not.toHaveBeenCalled(); + } finally { + await stack.kernel.shutdown(); + } + }); + } +}); diff --git a/packages/runtime/vitest.config.ts b/packages/runtime/vitest.config.ts index 069428c48ca..d268cd2009d 100644 --- a/packages/runtime/vitest.config.ts +++ b/packages/runtime/vitest.config.ts @@ -216,6 +216,15 @@ export default defineConfig({ // the #4567 regression (croner rejecting the expression envelope) is // reproduced by the actual scheduler rather than by a double. { find: '@objectstack/service-job', replacement: path.resolve(__dirname, '../services/service-job/src/index.ts') }, + // Dev-only: packages-knowledge-source-gate.test.ts drives the package + // duplicate and the `/meta` save over the REAL `KnowledgeServicePlugin` + // (ADR-0161 K4, guard two), so the verdict each door words is the + // service's in the checkout, never a built copy of it. Anchored: the pin + // imports only the root entry. + { + find: /^@objectstack\/service-knowledge$/, + replacement: path.resolve(__dirname, '../services/service-knowledge/src/index.ts'), + }, // Dev-only: src/security/request-execution-context.conformance.test.ts // drives the REAL settings door (`SettingsServicePlugin`'s context // resolver) as one row of ruling record 6227928430's conformance test, so diff --git a/packages/services/service-knowledge/src/__tests__/knowledge-source-admission.test.ts b/packages/services/service-knowledge/src/__tests__/knowledge-source-admission.test.ts index 0be78f9b711..c34ee998d93 100644 --- a/packages/services/service-knowledge/src/__tests__/knowledge-source-admission.test.ts +++ b/packages/services/service-knowledge/src/__tests__/knowledge-source-admission.test.ts @@ -1122,6 +1122,43 @@ describe('admitAuthoredSource — source admission at save, as the authoring pri expect(await placed.admitAuthoredSource(omitted, MANAGER)).toEqual({ admitted: true }); }); + /** + * The package duplicate asks with `door: 'duplicate'`: its caller copies a + * package, so every arm says the source cannot be copied, none says to save + * the source or that nothing was written (the door's prefix says once that + * nothing was copied), and the status, code, object and field are the save's. + */ + it('door: duplicate words every arm for the duplicate\'s caller; the status and code are the save\'s', async () => { + const hideTitle = makeSecurity(() => ['id', 'body', 'salary_note', 'status']); + const arms: Array<[string, () => Promise, (door: { door: 'save' | 'duplicate' }) => Promise, RegExp | undefined]> = []; + const at = (label: string, svc: KnowledgeService, body: unknown, ctx: ExecutionContext | undefined, remedy?: RegExp) => + arms.push([label, () => svc.admitAuthoredSource(body, ctx), (door) => svc.admitAuthoredSource(body, ctx, door), remedy]); + const members = setup({ sources: [], security: salaryHiddenFromMembers }).svc; + at('content field', members, item('ticket', ['body', 'salary_note']), MEMBER, /`metadataFields`, then duplicate the package again, or have someone who may query it duplicate the package\.$/); + at('where field', members, item('ticket', ['body'], { where: { salary_note: 'x' } }), MEMBER, /`where`, then duplicate the package again, or have someone who may query it duplicate the package\.$/); + at('display field', setup({ sources: [], security: hideTitle }).svc, item('ticket', ['body']), MEMBER, /Have someone who may query it duplicate the package\.$/); + at('gate throws', setup({ sources: [], schemaThrows: true, logger: { warn: vi.fn(), error: vi.fn() } }).svc, item('ticket', ['body']), MANAGER, /indexes\. Duplicate the package again\.$/); + const mute: KnowledgeFieldSecurity = { getQueryableFields: async () => undefined, getReadableFields: async () => undefined }; + at('security answers neither', setup({ sources: [], security: mute }).svc, item('ticket', ['body']), MANAGER, /Duplicate the package again\.$/); + at('no identity', members, item('ticket', ['body']), undefined, /: the duplicate carries no identity/); + at('unmounted adapter', members, { ...item('ticket', ['body']), adapter: 'ragflow' }, MANAGER, /mount the 'ragflow' store and duplicate the package again\.$/); + at('disabled package', setup({ sources: [], objects: [TICKET], disabled: ['ticket'] }).svc, item('ticket', ['body']), MANAGER, undefined); + + for (const [label, asSaved, asDuplicated, remedy] of arms) { + const saved = (await asSaved()) as { admitted: false; message: string }; + const duplicated = (await asDuplicated({ door: 'duplicate' })) as { admitted: false; message: string }; + expect(saved.admitted, label).toBe(false); + const { message: _s, ...savedRest } = saved; + const { message, ...duplicatedRest } = duplicated; + expect(duplicatedRest, label).toEqual(savedRest); + expect(message, label).toMatch(/^The knowledge source( "authored")? cannot be copied: /); + expect(message, label).not.toMatch(/save the source|save it again|was not saved|Nothing was written|nothing was copied|the save /i); + if (remedy) expect(message, label).toMatch(remedy); + // The save's own sentence is what it was: asked with no door, or with `save`. + expect(await asDuplicated({ door: 'save' }), label).toEqual(saved); + } + }); + it('registers nothing and searches nothing: the verdict is a read', async () => { const { svc, adapter } = setup({ sources: [], security: salaryHiddenFromMembers }); await svc.admitAuthoredSource(item('ticket', ['body']), MANAGER); diff --git a/packages/services/service-knowledge/src/knowledge-service.ts b/packages/services/service-knowledge/src/knowledge-service.ts index 4b91b46c6bc..fc75b128ab2 100644 --- a/packages/services/service-knowledge/src/knowledge-service.ts +++ b/packages/services/service-knowledge/src/knowledge-service.ts @@ -3732,12 +3732,22 @@ export class KnowledgeService implements IKnowledgeService { * gate that throws, or a security service that answers neither field * question, the save is refused `503 SERVICE_UNAVAILABLE`. The system * context is admitted, as it bypasses the gates at search. + * + * `options.door` words the sentences for the door that asks (the gates and + * the status and code are the same at both): `save`, the default, for a + * door that saves one item; `duplicate` for the package duplicate, which + * copies a package's sources. Its caller is told the source cannot be + * copied and to duplicate the package again, never to save the source, and + * no "nothing was written": that door's own prefix says once that nothing + * was copied. */ async admitAuthoredSource( item: unknown, ctx: ExecutionContext | undefined, + options?: { door?: 'save' | 'duplicate' }, ): Promise<{ admitted: true } | { admitted: false; status: number; code: string; message: string; object: string; field?: string }> { if (ctx?.isSystem) return { admitted: true }; + const wording = AUTHORED_SOURCE_DOOR_WORDING[options?.door === 'duplicate' ? 'duplicate' : 'save']; const body = (item as { name?: unknown; source?: unknown } | null | undefined) ?? {}; const declared = body.source as | { object?: unknown; content?: unknown; contentFields?: unknown; metadataFields?: unknown; where?: unknown } @@ -3758,7 +3768,7 @@ export class KnowledgeService implements IKnowledgeService { ? { where: where as Record } : {}), }; - const named = `The knowledge source${describeName(body)} was not saved`; + const named = `The knowledge source${describeName(body)} ${wording.notDone}`; const refuse = (status: number, code: string, message: string, field?: string) => ({ admitted: false as const, status, code, message, object, ...(field === undefined ? {} : { field }) }); const unavailable = (why: string) => @@ -3766,9 +3776,9 @@ export class KnowledgeService implements IKnowledgeService { 503, 'SERVICE_UNAVAILABLE', `${named}: whether you may search object '${object}' could not be judged (${why}), and an author must be ` + - 'allowed to search what their source indexes. Nothing was written; try again.', + `allowed to search what their source indexes.${wording.tryAgain}`, ); - if (!ctx) return refuse(403, 'PERMISSION_DENIED', `${named}: the save carries no identity, and a missing identity is not a grant of authority.`); + if (!ctx) return refuse(403, 'PERMISSION_DENIED', `${named}: ${wording.act} carries no identity, and a missing identity is not a grant of authority.`); // [ADR-0161 K4 ◆] A source that names no adapter where this deployment // cannot place one is refused at its save as at its registration, so the // author hears it: several adapters registered, none the deployment's. @@ -3782,7 +3792,7 @@ export class KnowledgeService implements IKnowledgeService { // the boot log or a search's 503. A save is served after every store's // `start()`, so the adapters registered now are the deployment's. if (typeof authoredAdapter === 'string' && !registeredAdapters.includes(authoredAdapter)) { - return refuse(400, 'VALIDATION_ERROR', `${named}: ${this.unmountedAdapterSaveText(authoredAdapter, registeredAdapters)}`); + return refuse(400, 'VALIDATION_ERROR', `${named}: ${this.unmountedAdapterSaveText(authoredAdapter, registeredAdapters, wording.again)}`); } const engine = this.options.dataEngine; if (!engine) return unavailable('the knowledge service has no data engine'); @@ -3831,7 +3841,7 @@ export class KnowledgeService implements IKnowledgeService { 'PERMISSION_DENIED', `${named}: its \`where\` reads field '${field}' of object '${object}', which you may not query (it is ` + 'hidden from you, or served to you masked), and the source would select its records by that field. ' + - 'Remove the field from `where`, or have someone who may query it save the source.', + `Remove the field from \`where\`${wording.thenAgain}, or have someone who may query it ${wording.byWhoMay}.`, field, ); } @@ -3842,9 +3852,9 @@ export class KnowledgeService implements IKnowledgeService { `${named}: you may not query field '${field}' of object '${object}' (it is hidden from you, or served ` + 'to you masked), and the index would hold its text unmasked. ' + (listedByAuthor - ? 'Remove the field from `content` and `metadataFields`, or have someone who may query it save the source.' + ? `Remove the field from \`content\` and \`metadataFields\`${wording.thenAgain}, or have someone who may query it ${wording.byWhoMay}.` : "The source does not list it: it is the object's display field, which every document carries as its " + - 'title. Have someone who may query it save the source.'), + `title. Have someone who may query it ${wording.byWhoMay}.`), field, ); } @@ -3859,13 +3869,13 @@ export class KnowledgeService implements IKnowledgeService { * can take. Leaving `adapter` out is offered only where an omitted adapter * would be placed ({@link adapterIdFor}). */ - private unmountedAdapterSaveText(adapter: string, mounted: readonly string[]): string { + private unmountedAdapterSaveText(adapter: string, mounted: readonly string[], again: string): string { const deployment = this.options.deploymentAdapter; const placeable = (deployment !== undefined && mounted.includes(deployment)) || mounted.length === 1; const remedies = [ ...(mounted.length === 0 ? [] : [`name one of ${mounted.map((id) => `'${id}'`).join(', ')} as its \`adapter\``]), ...(placeable ? ["leave `adapter` out, and the deployment's store holds it"] : []), - `mount the '${adapter}' store and save it again`, + `mount the '${adapter}' store and ${again}`, ]; return ( `it names adapter '${adapter}', which this deployment does not mount ` + @@ -4043,6 +4053,39 @@ function describeEntry(entry: KnowledgeSourceEntry): KnowledgeSourceDescription } /** ` 'NAME'` for a refusal about an input that carries a usable name (or its retired `id`), else nothing. */ +/** + * The door that asks {@link KnowledgeService.admitAuthoredSource}: `save` for + * a door that saves one item, `duplicate` for the package duplicate. + */ +type AuthoredSourceDoor = 'save' | 'duplicate'; + +/** + * What each door's caller is told: the source not done, the act that carries + * the identity, the retry after a verdict that could not be judged, the redo + * after a fix, and the act someone who may query the field performs. The + * `save` row is the save door's wording, unchanged. + */ +const AUTHORED_SOURCE_DOOR_WORDING: Readonly< + Record +> = { + save: { + notDone: 'was not saved', + act: 'the save', + tryAgain: ' Nothing was written; try again.', + again: 'save it again', + thenAgain: '', + byWhoMay: 'save the source', + }, + duplicate: { + notDone: 'cannot be copied', + act: 'the duplicate', + tryAgain: ' Duplicate the package again.', + again: 'duplicate the package again', + thenAgain: ', then duplicate the package again', + byWhoMay: 'duplicate the package', + }, +}; + function describeName(input: unknown): string { const { name, id } = (input ?? {}) as { name?: unknown; id?: unknown }; const shown = typeof name === 'string' && name !== '' ? name : typeof id === 'string' && id !== '' ? id : undefined; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index aed1517ce04..b269576de98 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -2905,6 +2905,9 @@ importers: '@objectstack/service-job': specifier: workspace:* version: link:../services/service-job + '@objectstack/service-knowledge': + specifier: workspace:* + version: link:../services/service-knowledge '@objectstack/service-messaging': specifier: workspace:* version: link:../services/service-messaging