From a2525904ea28b43f03c9285c87d6ca162a89a290 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 10:43:53 +0000 Subject: [PATCH 1/7] test(runtime): pin the duplicate and save doors' wording of the platform knowledge service's verdict Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP Co-authored-by: Claude --- packages/runtime/package.json | 1 + .../packages-knowledge-source-gate.test.ts | 123 ++++++++++++++++++ packages/runtime/vitest.config.ts | 9 ++ pnpm-lock.yaml | 3 + 4 files changed, 136 insertions(+) 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 13358bc9f71..a39936ecdcb 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 }); @@ -415,3 +418,123 @@ 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 }); + kernel.use(host); + 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; the /meta save's sentence is unchanged`, 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/); + expect(stack.protocol.duplicatePackage).not.toHaveBeenCalled(); + + // CONTROL: the same verdict at the /meta save door, byte for byte as before. + 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/pnpm-lock.yaml b/pnpm-lock.yaml index e5b7ea3de1f..40b297155c3 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -2902,6 +2902,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 From 92adc8f6c05f16cf5940a3791b722d26548fbb08 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 10:54:28 +0000 Subject: [PATCH 2/7] fix(service-knowledge): the package duplicate words the knowledge service's own verdict for its caller Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP Co-authored-by: Claude --- .../knowledge-source-save-admission.test.ts | 15 ++++- .../src/knowledge-source-save-admission.ts | 24 ++++++-- .../knowledge-source-admission.test.ts | 37 +++++++++++ .../src/knowledge-service.ts | 61 ++++++++++++++++--- 4 files changed, 122 insertions(+), 15 deletions(-) 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/services/service-knowledge/src/__tests__/knowledge-source-admission.test.ts b/packages/services/service-knowledge/src/__tests__/knowledge-source-admission.test.ts index 8a35659935b..858b7e4e218 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 @@ -1075,6 +1075,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 22f53d295b9..6e9f33f7c50 100644 --- a/packages/services/service-knowledge/src/knowledge-service.ts +++ b/packages/services/service-knowledge/src/knowledge-service.ts @@ -3241,12 +3241,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 } @@ -3267,7 +3277,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) => @@ -3275,9 +3285,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. @@ -3291,7 +3301,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'); @@ -3340,7 +3350,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, ); } @@ -3351,9 +3361,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, ); } @@ -3368,13 +3378,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 ` + @@ -3552,6 +3562,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; From 91dc195ad5e68b1302add0b0f158b5bc4d9b911f Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 11:29:27 +0000 Subject: [PATCH 3/7] test(runtime): await the plugin registrations; the duplicate door asks the service with its door Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP Co-authored-by: Claude --- ...owledge-duplicate-door-service-verdict-wording.md | 12 ++++++++++++ .../domains/packages-knowledge-source-gate.test.ts | 8 ++++---- 2 files changed, 16 insertions(+), 4 deletions(-) create mode 100644 .changeset/38210-knowledge-duplicate-door-service-verdict-wording.md 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/runtime/src/domains/packages-knowledge-source-gate.test.ts b/packages/runtime/src/domains/packages-knowledge-source-gate.test.ts index a39936ecdcb..3ba8732b863 100644 --- a/packages/runtime/src/domains/packages-knowledge-source-gate.test.ts +++ b/packages/runtime/src/domains/packages-knowledge-source-gate.test.ts @@ -252,8 +252,8 @@ 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' }); }); it('every source is asked about: the second one refused refuses the duplicate', async () => { @@ -498,8 +498,8 @@ describe('/packages duplicate and /meta save on a real kernel running KnowledgeS }, } as Plugin; const kernel = new ObjectKernel({ gracefulShutdown: false, skipSystemValidation: true }); - kernel.use(host); - kernel.use(new KnowledgeServicePlugin({ enableEventSync: false })); + 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 () => [] }); From 1f2af2d296ff026f3590c8573222fc141c4dcd06 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 12:12:51 +0000 Subject: [PATCH 4/7] test(runtime): the save-door control is its own case per arm Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP Co-authored-by: Claude --- .../domains/packages-knowledge-source-gate.test.ts | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) 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 3ba8732b863..a57295ec0c0 100644 --- a/packages/runtime/src/domains/packages-knowledge-source-gate.test.ts +++ b/packages/runtime/src/domains/packages-knowledge-source-gate.test.ts @@ -512,7 +512,7 @@ describe('/packages duplicate and /meta save on a real kernel running KnowledgeS } 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; the /meta save's sentence is unchanged`, async () => { + 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]; @@ -525,8 +525,15 @@ describe('/packages duplicate and /meta save on a real kernel running KnowledgeS 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/); expect(stack.protocol.duplicatePackage).not.toHaveBeenCalled(); + } finally { + await stack.kernel.shutdown(); + } + }); - // CONTROL: the same verdict at the /meta save door, byte for byte as before. + 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); @@ -537,4 +544,6 @@ describe('/packages duplicate and /meta save on a real kernel running KnowledgeS } }); } +}); + } }); From 0e4b8b248ca9ebce56e9c1f411835385a0cb762f Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 12:13:58 +0000 Subject: [PATCH 5/7] test(runtime): close the real-kernel describe once Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP Co-authored-by: Claude --- .../runtime/src/domains/packages-knowledge-source-gate.test.ts | 2 -- 1 file changed, 2 deletions(-) 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 a57295ec0c0..8a2e6cb1d32 100644 --- a/packages/runtime/src/domains/packages-knowledge-source-gate.test.ts +++ b/packages/runtime/src/domains/packages-knowledge-source-gate.test.ts @@ -544,6 +544,4 @@ describe('/packages duplicate and /meta save on a real kernel running KnowledgeS } }); } -}); - } }); From 5f857ffe4beb3af3a8fcbd1a48097352acf46746 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 12:44:53 +0000 Subject: [PATCH 6/7] test(runtime): the transient remedy is matched in either case Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP Co-authored-by: Claude --- .../runtime/src/domains/packages-knowledge-source-gate.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 8a2e6cb1d32..0d244119688 100644 --- a/packages/runtime/src/domains/packages-knowledge-source-gate.test.ts +++ b/packages/runtime/src/domains/packages-knowledge-source-gate.test.ts @@ -523,7 +523,7 @@ describe('/packages duplicate and /meta save on a real kernel running KnowledgeS 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/); + 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(); From 221e401b1127827ce46f6e07ef4901627127adc8 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 15:27:09 +0000 Subject: [PATCH 7/7] test(runtime): the unmounted-adapter duplicate case reads the service's duplicate-door sentence Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP --- .../packages-knowledge-source-gate.test.ts | 33 +++++++++++-------- 1 file changed, 20 insertions(+), 13 deletions(-) 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 2f7e4d319e7..f4a287ca8b8 100644 --- a/packages/runtime/src/domains/packages-knowledge-source-gate.test.ts +++ b/packages/runtime/src/domains/packages-knowledge-source-gate.test.ts @@ -239,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 }; } @@ -256,24 +256,31 @@ describe('/packages — duplicate admits each knowledge source it copies for the 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 () => {