Skip to content

Commit 92adc8f

Browse files
committed
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 <noreply@anthropic.com>
1 parent a252590 commit 92adc8f

4 files changed

Lines changed: 122 additions & 15 deletions

File tree

‎packages/metadata-core/src/knowledge-source-save-admission.test.ts‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -139,8 +139,19 @@ describe('authoredKnowledgeSourceRefusal — source admission at save', () => {
139139
for (const refusal of [none, scoped, unresolved]) {
140140
expect(refusal?.message).not.toMatch(/save the source|Nothing was written/);
141141
}
142-
// A verdict of the knowledge service is its own sentence, passed through as before.
143-
expect(await ask(() => serviceAnswering(REFUSED))).toEqual({ status: 403, code: 'PERMISSION_DENIED', message: REFUSED.message });
142+
// A verdict of the knowledge service is its own sentence, passed through
143+
// as it answers: the service is asked with this door, so it words it.
144+
const service = serviceAnswering(REFUSED);
145+
expect(await ask(() => service)).toEqual({ status: 403, code: 'PERMISSION_DENIED', message: REFUSED.message });
146+
expect(service.admitAuthoredSource).toHaveBeenCalledWith(ITEM, AUTHOR, { door: 'duplicate' });
147+
});
148+
149+
it('a save hands the knowledge service no door: it is asked with the item and the context alone', async () => {
150+
for (const door of [undefined, 'save'] as const) {
151+
const service = serviceAnswering({ admitted: true });
152+
await authoredKnowledgeSourceRefusal({ type: 'knowledge_source', item: ITEM, executionContext: AUTHOR, resolveKnowledgeService: () => service, ...(door ? { door } : {}) });
153+
expect(service.admitAuthoredSource.mock.calls, String(door)).toEqual([[ITEM, AUTHOR]]);
154+
}
144155
});
145156

146157
it('`isSystem: false` is not a bypass', async () => {

‎packages/metadata-core/src/knowledge-source-save-admission.ts‎

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,10 @@
6969
* written). A door that copies sources rather than saves one, the package
7070
* duplicate, asks with `door: 'duplicate'` and gets its caller's remedy
7171
* (duplicate the package again) and no "nothing was written" of its own: that
72-
* door's prefix says once that nothing was copied.
72+
* door's prefix says once that nothing was copied. The door is handed on to
73+
* the knowledge service's own verdict
74+
* ({@link KnowledgeSourceSaveAdmitter.admitAuthoredSource}), which words it
75+
* the same way; a save hands on no door.
7376
*
7477
* ## Fail direction
7578
*
@@ -129,9 +132,18 @@ function isKnowledgeServiceNotInScope(value: unknown): value is KnowledgeService
129132
return typeof value === 'object' && value !== null && (value as Record<symbol, unknown>)[NOT_IN_SCOPE] === true;
130133
}
131134

132-
/** The member of the `knowledge` service the doors ask, reached duck-typed. */
135+
/**
136+
* The member of the `knowledge` service the doors ask, reached duck-typed.
137+
* `options.door` is passed only by a door other than `save` (the package
138+
* duplicate), so the service words its own verdict for that door's caller; a
139+
* save asks with the item and the context alone, as before.
140+
*/
133141
export interface KnowledgeSourceSaveAdmitter {
134-
admitAuthoredSource(item: unknown, context: unknown): Promise<AuthoredKnowledgeSourceVerdict>;
142+
admitAuthoredSource(
143+
item: unknown,
144+
context: unknown,
145+
options?: { door?: KnowledgeSourceSaveDoor },
146+
): Promise<AuthoredKnowledgeSourceVerdict>;
135147
}
136148

137149
/** The remedy and the no-op each door's caller is told. */
@@ -237,7 +249,11 @@ export async function authoredKnowledgeSourceRefusal(input: {
237249
if (typeof admit !== 'function') return undefined;
238250
let verdict: AuthoredKnowledgeSourceVerdict;
239251
try {
240-
verdict = await admit.call(service, input.item, input.executionContext);
252+
// The service words its verdict for the door: a duplicate is asked with
253+
// its door, a save as before.
254+
verdict = await (door === 'save'
255+
? admit.call(service, input.item, input.executionContext)
256+
: admit.call(service, input.item, input.executionContext, { door }));
241257
} catch (err) {
242258
return unavailable(err instanceof Error ? err.message : String(err), door);
243259
}

‎packages/services/service-knowledge/src/__tests__/knowledge-source-admission.test.ts‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1075,6 +1075,43 @@ describe('admitAuthoredSource — source admission at save, as the authoring pri
10751075
expect(await placed.admitAuthoredSource(omitted, MANAGER)).toEqual({ admitted: true });
10761076
});
10771077

1078+
/**
1079+
* The package duplicate asks with `door: 'duplicate'`: its caller copies a
1080+
* package, so every arm says the source cannot be copied, none says to save
1081+
* the source or that nothing was written (the door's prefix says once that
1082+
* nothing was copied), and the status, code, object and field are the save's.
1083+
*/
1084+
it('door: duplicate words every arm for the duplicate\'s caller; the status and code are the save\'s', async () => {
1085+
const hideTitle = makeSecurity(() => ['id', 'body', 'salary_note', 'status']);
1086+
const arms: Array<[string, () => Promise<unknown>, (door: { door: 'save' | 'duplicate' }) => Promise<unknown>, RegExp | undefined]> = [];
1087+
const at = (label: string, svc: KnowledgeService, body: unknown, ctx: ExecutionContext | undefined, remedy?: RegExp) =>
1088+
arms.push([label, () => svc.admitAuthoredSource(body, ctx), (door) => svc.admitAuthoredSource(body, ctx, door), remedy]);
1089+
const members = setup({ sources: [], security: salaryHiddenFromMembers }).svc;
1090+
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\.$/);
1091+
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\.$/);
1092+
at('display field', setup({ sources: [], security: hideTitle }).svc, item('ticket', ['body']), MEMBER, /Have someone who may query it duplicate the package\.$/);
1093+
at('gate throws', setup({ sources: [], schemaThrows: true, logger: { warn: vi.fn(), error: vi.fn() } }).svc, item('ticket', ['body']), MANAGER, /indexes\. Duplicate the package again\.$/);
1094+
const mute: KnowledgeFieldSecurity = { getQueryableFields: async () => undefined, getReadableFields: async () => undefined };
1095+
at('security answers neither', setup({ sources: [], security: mute }).svc, item('ticket', ['body']), MANAGER, /Duplicate the package again\.$/);
1096+
at('no identity', members, item('ticket', ['body']), undefined, /: the duplicate carries no identity/);
1097+
at('unmounted adapter', members, { ...item('ticket', ['body']), adapter: 'ragflow' }, MANAGER, /mount the 'ragflow' store and duplicate the package again\.$/);
1098+
at('disabled package', setup({ sources: [], objects: [TICKET], disabled: ['ticket'] }).svc, item('ticket', ['body']), MANAGER, undefined);
1099+
1100+
for (const [label, asSaved, asDuplicated, remedy] of arms) {
1101+
const saved = (await asSaved()) as { admitted: false; message: string };
1102+
const duplicated = (await asDuplicated({ door: 'duplicate' })) as { admitted: false; message: string };
1103+
expect(saved.admitted, label).toBe(false);
1104+
const { message: _s, ...savedRest } = saved;
1105+
const { message, ...duplicatedRest } = duplicated;
1106+
expect(duplicatedRest, label).toEqual(savedRest);
1107+
expect(message, label).toMatch(/^The knowledge source( "authored")? cannot be copied: /);
1108+
expect(message, label).not.toMatch(/save the source|save it again|was not saved|Nothing was written|nothing was copied|the save /i);
1109+
if (remedy) expect(message, label).toMatch(remedy);
1110+
// The save's own sentence is what it was: asked with no door, or with `save`.
1111+
expect(await asDuplicated({ door: 'save' }), label).toEqual(saved);
1112+
}
1113+
});
1114+
10781115
it('registers nothing and searches nothing: the verdict is a read', async () => {
10791116
const { svc, adapter } = setup({ sources: [], security: salaryHiddenFromMembers });
10801117
await svc.admitAuthoredSource(item('ticket', ['body']), MANAGER);

‎packages/services/service-knowledge/src/knowledge-service.ts‎

Lines changed: 52 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3241,12 +3241,22 @@ export class KnowledgeService implements IKnowledgeService {
32413241
* gate that throws, or a security service that answers neither field
32423242
* question, the save is refused `503 SERVICE_UNAVAILABLE`. The system
32433243
* context is admitted, as it bypasses the gates at search.
3244+
*
3245+
* `options.door` words the sentences for the door that asks (the gates and
3246+
* the status and code are the same at both): `save`, the default, for a
3247+
* door that saves one item; `duplicate` for the package duplicate, which
3248+
* copies a package's sources. Its caller is told the source cannot be
3249+
* copied and to duplicate the package again, never to save the source, and
3250+
* no "nothing was written": that door's own prefix says once that nothing
3251+
* was copied.
32443252
*/
32453253
async admitAuthoredSource(
32463254
item: unknown,
32473255
ctx: ExecutionContext | undefined,
3256+
options?: { door?: 'save' | 'duplicate' },
32483257
): Promise<{ admitted: true } | { admitted: false; status: number; code: string; message: string; object: string; field?: string }> {
32493258
if (ctx?.isSystem) return { admitted: true };
3259+
const wording = AUTHORED_SOURCE_DOOR_WORDING[options?.door === 'duplicate' ? 'duplicate' : 'save'];
32503260
const body = (item as { name?: unknown; source?: unknown } | null | undefined) ?? {};
32513261
const declared = body.source as
32523262
| { object?: unknown; content?: unknown; contentFields?: unknown; metadataFields?: unknown; where?: unknown }
@@ -3267,17 +3277,17 @@ export class KnowledgeService implements IKnowledgeService {
32673277
? { where: where as Record<string, unknown> }
32683278
: {}),
32693279
};
3270-
const named = `The knowledge source${describeName(body)} was not saved`;
3280+
const named = `The knowledge source${describeName(body)} ${wording.notDone}`;
32713281
const refuse = (status: number, code: string, message: string, field?: string) =>
32723282
({ admitted: false as const, status, code, message, object, ...(field === undefined ? {} : { field }) });
32733283
const unavailable = (why: string) =>
32743284
refuse(
32753285
503,
32763286
'SERVICE_UNAVAILABLE',
32773287
`${named}: whether you may search object '${object}' could not be judged (${why}), and an author must be ` +
3278-
'allowed to search what their source indexes. Nothing was written; try again.',
3288+
`allowed to search what their source indexes.${wording.tryAgain}`,
32793289
);
3280-
if (!ctx) return refuse(403, 'PERMISSION_DENIED', `${named}: the save carries no identity, and a missing identity is not a grant of authority.`);
3290+
if (!ctx) return refuse(403, 'PERMISSION_DENIED', `${named}: ${wording.act} carries no identity, and a missing identity is not a grant of authority.`);
32813291
// [ADR-0161 K4 ◆] A source that names no adapter where this deployment
32823292
// cannot place one is refused at its save as at its registration, so the
32833293
// author hears it: several adapters registered, none the deployment's.
@@ -3291,7 +3301,7 @@ export class KnowledgeService implements IKnowledgeService {
32913301
// the boot log or a search's 503. A save is served after every store's
32923302
// `start()`, so the adapters registered now are the deployment's.
32933303
if (typeof authoredAdapter === 'string' && !registeredAdapters.includes(authoredAdapter)) {
3294-
return refuse(400, 'VALIDATION_ERROR', `${named}: ${this.unmountedAdapterSaveText(authoredAdapter, registeredAdapters)}`);
3304+
return refuse(400, 'VALIDATION_ERROR', `${named}: ${this.unmountedAdapterSaveText(authoredAdapter, registeredAdapters, wording.again)}`);
32953305
}
32963306
const engine = this.options.dataEngine;
32973307
if (!engine) return unavailable('the knowledge service has no data engine');
@@ -3340,7 +3350,7 @@ export class KnowledgeService implements IKnowledgeService {
33403350
'PERMISSION_DENIED',
33413351
`${named}: its \`where\` reads field '${field}' of object '${object}', which you may not query (it is ` +
33423352
'hidden from you, or served to you masked), and the source would select its records by that field. ' +
3343-
'Remove the field from `where`, or have someone who may query it save the source.',
3353+
`Remove the field from \`where\`${wording.thenAgain}, or have someone who may query it ${wording.byWhoMay}.`,
33443354
field,
33453355
);
33463356
}
@@ -3351,9 +3361,9 @@ export class KnowledgeService implements IKnowledgeService {
33513361
`${named}: you may not query field '${field}' of object '${object}' (it is hidden from you, or served ` +
33523362
'to you masked), and the index would hold its text unmasked. ' +
33533363
(listedByAuthor
3354-
? 'Remove the field from `content` and `metadataFields`, or have someone who may query it save the source.'
3364+
? `Remove the field from \`content\` and \`metadataFields\`${wording.thenAgain}, or have someone who may query it ${wording.byWhoMay}.`
33553365
: "The source does not list it: it is the object's display field, which every document carries as its " +
3356-
'title. Have someone who may query it save the source.'),
3366+
`title. Have someone who may query it ${wording.byWhoMay}.`),
33573367
field,
33583368
);
33593369
}
@@ -3368,13 +3378,13 @@ export class KnowledgeService implements IKnowledgeService {
33683378
* can take. Leaving `adapter` out is offered only where an omitted adapter
33693379
* would be placed ({@link adapterIdFor}).
33703380
*/
3371-
private unmountedAdapterSaveText(adapter: string, mounted: readonly string[]): string {
3381+
private unmountedAdapterSaveText(adapter: string, mounted: readonly string[], again: string): string {
33723382
const deployment = this.options.deploymentAdapter;
33733383
const placeable = (deployment !== undefined && mounted.includes(deployment)) || mounted.length === 1;
33743384
const remedies = [
33753385
...(mounted.length === 0 ? [] : [`name one of ${mounted.map((id) => `'${id}'`).join(', ')} as its \`adapter\``]),
33763386
...(placeable ? ["leave `adapter` out, and the deployment's store holds it"] : []),
3377-
`mount the '${adapter}' store and save it again`,
3387+
`mount the '${adapter}' store and ${again}`,
33783388
];
33793389
return (
33803390
`it names adapter '${adapter}', which this deployment does not mount ` +
@@ -3552,6 +3562,39 @@ function describeEntry(entry: KnowledgeSourceEntry): KnowledgeSourceDescription
35523562
}
35533563

35543564
/** ` 'NAME'` for a refusal about an input that carries a usable name (or its retired `id`), else nothing. */
3565+
/**
3566+
* The door that asks {@link KnowledgeService.admitAuthoredSource}: `save` for
3567+
* a door that saves one item, `duplicate` for the package duplicate.
3568+
*/
3569+
type AuthoredSourceDoor = 'save' | 'duplicate';
3570+
3571+
/**
3572+
* What each door's caller is told: the source not done, the act that carries
3573+
* the identity, the retry after a verdict that could not be judged, the redo
3574+
* after a fix, and the act someone who may query the field performs. The
3575+
* `save` row is the save door's wording, unchanged.
3576+
*/
3577+
const AUTHORED_SOURCE_DOOR_WORDING: Readonly<
3578+
Record<AuthoredSourceDoor, { notDone: string; act: string; tryAgain: string; again: string; thenAgain: string; byWhoMay: string }>
3579+
> = {
3580+
save: {
3581+
notDone: 'was not saved',
3582+
act: 'the save',
3583+
tryAgain: ' Nothing was written; try again.',
3584+
again: 'save it again',
3585+
thenAgain: '',
3586+
byWhoMay: 'save the source',
3587+
},
3588+
duplicate: {
3589+
notDone: 'cannot be copied',
3590+
act: 'the duplicate',
3591+
tryAgain: ' Duplicate the package again.',
3592+
again: 'duplicate the package again',
3593+
thenAgain: ', then duplicate the package again',
3594+
byWhoMay: 'duplicate the package',
3595+
},
3596+
};
3597+
35553598
function describeName(input: unknown): string {
35563599
const { name, id } = (input ?? {}) as { name?: unknown; id?: unknown };
35573600
const shown = typeof name === 'string' && name !== '' ? name : typeof id === 'string' && id !== '' ? id : undefined;

0 commit comments

Comments
 (0)