🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(memory): distill rules from materials — pasted text, files, documents and conversations (#20266)
Arvin Xu4cda9fe71dbc
diff --git a/apps/server/src/routers/lambda/expertise.ts b/apps/server/src/routers/lambda/expertise.tsindex c2ca844c4a8..556fdcbe654 100644--- a/apps/server/src/routers/lambda/expertise.ts+++ b/apps/server/src/routers/lambda/expertise.ts@@ -9,6 +9,10 @@ import { ExpertiseModel } from '@/database/models/expertise';import { ExpertiseRuleRepository } from '@/database/repositories/expertiseRules';import { router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';+import {+ DistillRulesInputSchema,+ ExpertiseRuleDistillService,+} from '@/server/services/expertise/distill';import {DomainDraftSchema,EditableDomainDraftSchema,@@ -47,6 +51,11 @@ const expertiseProcedure = wsCompatProcedure.use(serverDatabase).use(async (optsctx.userId,ctx.workspaceId ?? undefined,),+ expertiseRuleDistillService: new ExpertiseRuleDistillService(+ ctx.serverDB,+ ctx.userId,+ ctx.workspaceId ?? undefined,+ ),expertiseRuleDraftService: new ExpertiseRuleDraftService(ctx.serverDB,ctx.userId,@@ -286,6 +295,58 @@ export const expertiseRouter = router({.input(z.object({ brief: z.string().min(1).max(20_000) })).mutation(async ({ ctx, input }) => ctx.expertiseRuleDraftService.draftRuleGroup(input)),+ /**+ * Reads a material the reviewer brought — pasted text, a file, a document or a conversation —+ * and proposes every rule it states. Nothing is written: the reviewer ticks what to keep.+ */+ distillRules: expertiseWriteProcedure+ .input(DistillRulesInputSchema)+ .mutation(async ({ ctx, input }) => ctx.expertiseRuleDistillService.distillRules(input)),++ /** Files the candidates the reviewer kept from one material, each pinned to its passage. */+ commitDistilledRules: expertiseWriteProcedure+ .input(+ z.object({+ items: z+ .array(+ z.discriminatedUnion('kind', [+ z.object({+ domainId: z.string().optional(),+ kind: z.literal('create'),+ newGroup: z+ .object({ gate: z.string().min(1).max(1000), title: z.string().min(1).max(200) })+ .optional(),+ quote: z.string().max(2000),+ rule: z.object({+ // `compiled` is only true once the compiler links a criterion.+ compilability: z.enum(['compilable', 'not-compilable']).optional(),+ enforcement: z.enum(EXPERTISE_ENFORCEMENTS).optional(),+ how: z.string().max(8000).optional(),+ limits: z.string().max(4000).optional(),+ title: z.string().min(1).max(500),+ why: z.string().max(4000).optional(),+ }),+ }),+ z.object({+ intoId: z.string(),+ kind: z.literal('merge'),+ quote: z.string().max(2000),+ }),+ ]),+ )+ .max(50),+ material: z.object({+ subjectId: z.string().nullable(),+ subjectType: z.enum(['document', 'standalone', 'topic']),+ title: z.string().max(500),+ type: z.enum(['document', 'file', 'text', 'topic']),+ }),+ }),+ )+ .mutation(async ({ ctx, input }) =>+ ctx.expertiseRuleRepository.commitDistilled(input.material, input.items),+ ),+/** A rule the reviewer writes down by hand. */createRule: expertiseWriteProcedure.input(diff --git a/apps/server/src/services/expertise/distill.test.ts b/apps/server/src/services/expertise/distill.test.tsnew file mode 100644index 00000000000..1f3d5272be8--- /dev/null+++ b/apps/server/src/services/expertise/distill.test.ts@@ -0,0 +1,267 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { DistillRulesInputSchema, ExpertiseRuleDistillService } from './distill';++const {+ assertContentsNotInRestrictedKnowledgeBase,+ resolveExpertiseModelConfig,+ findDocument,+ findTopic,+ transcript,+ parseFile,+} = vi.hoisted(() => ({+ assertContentsNotInRestrictedKnowledgeBase: vi.fn(),+ findDocument: vi.fn(),+ findTopic: vi.fn(),+ parseFile: vi.fn(),+ resolveExpertiseModelConfig: vi.fn(),+ transcript: vi.fn(),+}));+const generateObject = vi.fn();++vi.mock('@/server/services/aiGeneration', () => ({+ AiGenerationService: class {+ generateObject = generateObject;+ },+}));+vi.mock('./modelConfig', () => ({ resolveExpertiseModelConfig }));+vi.mock('@/database/models/document', () => ({+ DocumentModel: class {+ findById = findDocument;+ },+}));+vi.mock('@/database/models/topic', () => ({+ TopicModel: class {+ findById = findTopic;+ },+}));+vi.mock('@/database/models/message', () => ({+ MessageModel: class {+ queryTopicTranscript = transcript;+ },+}));+vi.mock('@/server/services/knowledgeBaseAccess', () => ({+ assertContentsNotInRestrictedKnowledgeBase,+}));+vi.mock('@/server/services/document', () => ({+ DocumentService: class {+ parseFile = parseFile;+ },+}));++const groups = [{ gate: '换一个仓库还成立吗?', id: 'g-eng', title: '工程规范' }];+const rules = [{ id: 'r-rebase', title: '交付分支必须先 rebase 到 canary' }];++const candidate = (overrides: Record<string, unknown>) => ({+ compilability: 'not-compilable',+ duplicateOf: null,+ enforcement: 'remind',+ groupId: null,+ how: null,+ limits: null,+ newGroup: null,+ quote: '',+ title: 'rule',+ why: null,+ ...overrides,+});++const service = () => new ExpertiseRuleDistillService({} as never, 'user_1');++describe('ExpertiseRuleDistillService', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ resolveExpertiseModelConfig.mockResolvedValue({ model: 'm', provider: 'p' });+ assertContentsNotInRestrictedKnowledgeBase.mockResolvedValue(undefined);+ });++ it('proposes every rule a pasted guideline states, keeping only ids the reviewer has', async () => {+ generateObject.mockResolvedValue({+ rules: [+ candidate({+ duplicateOf: 'r-rebase',+ groupId: 'g-eng',+ newGroup: { gate: 'x', title: 'y' },+ quote: ' 提交前 rebase 到 canary ',+ title: '交付前先 rebase 到 canary',+ }),+ candidate({+ duplicateOf: 'r-invented',+ groupId: 'g-invented',+ newGroup: { gate: '是在约束界面文案吗?', title: '界面文案' },+ title: '按钮文案用动词',+ }),+ ],+ });++ const result = await service().distillRules({+ groups,+ rules,+ source: { text: '# 前端规范\n1. 提交前 rebase 到 canary\n2. 按钮文案用动词', type: 'text' },+ });++ expect(result.material).toEqual({+ subjectId: null,+ subjectType: 'standalone',+ title: '前端规范',+ truncated: false,+ type: 'text',+ });+ expect(result.candidates[0]).toMatchObject({+ duplicateOf: 'r-rebase',+ groupId: 'g-eng',+ // A matched group wins over a proposed one.+ newGroup: null,+ quote: '提交前 rebase 到 canary',+ });+ // Ids the model invented are dropped; its proposed group is kept instead.+ expect(result.candidates[1]).toMatchObject({+ duplicateOf: null,+ groupId: null,+ newGroup: { gate: '是在约束界面文案吗?', title: '界面文案' },+ });+ const [params, options] = generateObject.mock.calls[0];+ expect(params.schema.name).toBe('expertise_rule_distill');+ expect(params.messages[1].content).toContain('r-rebase · 交付分支必须先 rebase 到 canary');+ expect(options.tracing.scenario).toBe('expertise_rule_distill');+ });++ it('reads a conversation as the reviewer and the assistant, and records it as the topic', async () => {+ findTopic.mockResolvedValue({ id: 'tpc_1', title: '首页评审' });+ transcript.mockResolvedValue({+ items: [+ { content: '空状态要给下一步动作', role: 'user' },+ { content: '好的,我来改', role: 'assistant' },+ { content: '{"tool":true}', role: 'tool' },+ ],+ total: 3,+ });+ generateObject.mockResolvedValue({ rules: [] });++ const result = await service().distillRules({+ groups,+ rules,+ source: { id: 'tpc_1', type: 'topic' },+ });++ expect(result.material).toMatchObject({+ subjectId: 'tpc_1',+ subjectType: 'topic',+ title: '首页评审',+ });+ const content = generateObject.mock.calls[0][0].messages[1].content as string;+ expect(content).toContain('Reviewer: 空状态要给下一步动作');+ expect(content).toContain('Assistant: 好的,我来改');+ expect(content).not.toContain('"tool"');+ });++ it('records a file as the document it was parsed into', async () => {+ parseFile.mockResolvedValue({ content: '规范正文', filename: 'guide.pdf', id: 'docs_parsed' });+ generateObject.mockResolvedValue({ rules: [] });++ const result = await service().distillRules({+ groups,+ rules,+ source: { id: 'file_1', type: 'file' },+ });++ expect(parseFile).toHaveBeenCalledWith('file_1');+ expect(result.material).toMatchObject({+ subjectId: 'docs_parsed',+ subjectType: 'document',+ title: 'guide.pdf',+ type: 'file',+ });+ });++ it('says when the tail of a long material was not read', async () => {+ generateObject.mockResolvedValue({ rules: [] });++ const result = await service().distillRules({+ groups,+ rules,+ source: { text: 'x'.repeat(70_000), type: 'text' },+ });++ expect(result.material.truncated).toBe(true);+ });++ it('keeps a large catalog of existing rules to a bounded slice of the prompt', async () => {+ generateObject.mockResolvedValue({ rules: [candidate({ duplicateOf: 'r-1999' })] });+ const many = Array.from({ length: 2000 }, (_, index) => ({+ id: `r-${index}`,+ title: 'x'.repeat(400),+ }));++ const result = await service().distillRules({+ groups,+ rules: many,+ source: { text: '一条规矩', type: 'text' },+ });++ const [params] = generateObject.mock.calls[0];+ expect(params.messages[1].content.length).toBeLessThan(40_000);+ expect(params.messages[1].content).toContain('r-0 · ');+ // A rule the model was never shown cannot be what a candidate restates.+ expect(result.candidates[0].duplicateOf).toBeNull();+ });++ it('refuses an oversized catalog before reading the material', () => {+ const tooMany = Array.from({ length: 201 }, (_, index) => ({+ gate: 'g',+ id: `g-${index}`,+ title: 't',+ }));+ expect(+ DistillRulesInputSchema.safeParse({+ groups: tooMany,+ rules,+ source: { text: 'x', type: 'text' },+ }).success,+ ).toBe(false);+ expect(+ DistillRulesInputSchema.safeParse({+ groups,+ rules: [{ id: 'r', title: 'x'.repeat(501) }],+ source: { text: 'x', type: 'text' },+ }).success,+ ).toBe(false);+ });++ it('refuses a material with no readable text instead of asking the model', async () => {+ findDocument.mockResolvedValue({ content: ' ', id: 'docs_empty', title: '空文稿' });++ await expect(+ service().distillRules({ groups, rules, source: { id: 'docs_empty', type: 'document' } }),+ ).rejects.toThrow('no readable text');+ expect(generateObject).not.toHaveBeenCalled();+ });++ it.each([+ ['document', 'docs_restricted'],+ ['file', 'file_restricted'],+ ] as const)(+ 'refuses a %s in a knowledge base the member has no access to, before reading it',+ async (type, id) => {+ assertContentsNotInRestrictedKnowledgeBase.mockRejectedValue(+ new Error('Only knowledge base managers can view this file'),+ );++ await expect(+ new ExpertiseRuleDistillService({} as never, 'user_1', 'ws_1').distillRules({+ groups,+ rules,+ source: { id, type },+ }),+ ).rejects.toThrow('Only knowledge base managers');+ expect(assertContentsNotInRestrictedKnowledgeBase).toHaveBeenCalledWith(+ { serverDB: {}, userId: 'user_1', workspaceId: 'ws_1' },+ [id],+ );+ expect(findDocument).not.toHaveBeenCalled();+ expect(parseFile).not.toHaveBeenCalled();+ expect(generateObject).not.toHaveBeenCalled();+ },+ );+});diff --git a/apps/server/src/services/expertise/distill.ts b/apps/server/src/services/expertise/distill.tsnew file mode 100644index 00000000000..3a6b19b70a8--- /dev/null+++ b/apps/server/src/services/expertise/distill.ts@@ -0,0 +1,279 @@+import { TRACING_SCENARIOS } from '@lobechat/const';+import {+ chainExpertiseRuleDistill,+ EXPERTISE_RULE_DISTILL_JSON_SCHEMA,+ EXPERTISE_RULE_DISTILL_PROMPT_VERSION,+ sliceHead,+} from '@lobechat/prompts';+import { RequestTrigger } from '@lobechat/types';+import { TRPCError } from '@trpc/server';+import { z } from 'zod';++import { DocumentModel } from '@/database/models/document';+import { MessageModel } from '@/database/models/message';+import { TopicModel } from '@/database/models/topic';+import type { LobeChatDatabase } from '@/database/type';+import { AiGenerationService } from '@/server/services/aiGeneration';+import { DocumentService } from '@/server/services/document';+import { assertContentsNotInRestrictedKnowledgeBase } from '@/server/services/knowledgeBaseAccess';++import { resolveExpertiseModelConfig } from './modelConfig';++/**+ * How much of a material the model reads. A guideline or a long conversation fits; past this the+ * tail is dropped and the result says so, rather than the request failing on the provider.+ */+const MATERIAL_MAX_CHARS = 60_000;+/** One message of a conversation, so a single pasted log cannot crowd out the reviewer's words. */+const MESSAGE_MAX_CHARS = 2000;+/** Messages read from a conversation, oldest first. */+const TOPIC_MAX_MESSAGES = 400;++export const DistillSourceSchema = z.discriminatedUnion('type', [+ z.object({+ text: z.string().min(1).max(200_000),+ title: z.string().max(200).optional(),+ type: z.literal('text'),+ }),+ z.object({ id: z.string().min(1), type: z.literal('document') }),+ z.object({ id: z.string().min(1), type: z.literal('file') }),+ z.object({ id: z.string().min(1), type: z.literal('topic') }),+]);++export type DistillSource = z.infer<typeof DistillSourceSchema>;++/**+ * How much of the prompt the reviewer's existing groups and rules may take, so a large part (or a+ * crafted request) cannot crowd out the material or run up the model bill. Groups go first, then+ * rules in the order sent (the page's order); whatever does not fit is left out of the comparison.+ */+const CATALOG_MAX_CHARS = 30_000;++export const DistillRulesInputSchema = z.object({+ /** The groups of the part the rules will be filed into, so candidates can be sorted there. */+ groups: z+ .array(+ z.object({+ gate: z.string().max(1000),+ id: z.string().max(128),+ title: z.string().max(200),+ }),+ )+ .max(200),+ /** The rules already in that part, so a restatement is flagged instead of filed twice. */+ rules: z.array(z.object({ id: z.string().max(128), title: z.string().max(500) })).max(2000),+ source: DistillSourceSchema,+});++/** The leading items whose rendered lines fit in `budget` characters. */+const fitCatalog = <T>(items: T[], size: (item: T) => number, budget: number) => {+ const kept: T[] = [];+ let used = 0;+ for (const item of items) {+ used += size(item);+ if (used > budget) break;+ kept.push(item);+ }+ return { kept, used };+};++export type DistillRulesInput = z.infer<typeof DistillRulesInputSchema>;++const nullableText = z+ .string()+ .nullable()+ .transform((value) => value?.trim() || null);++const DistillResultSchema = z.object({+ rules: z.array(+ z.object({+ compilability: z+ .enum(['compiled', 'compilable', 'not-compilable'])+ .transform((value) => (value === 'compiled' ? 'compilable' : value)),+ duplicateOf: z.string().nullable(),+ enforcement: z.enum(['block', 'remind']),+ groupId: z.string().nullable(),+ how: nullableText,+ limits: nullableText,+ newGroup: z.object({ gate: z.string().min(1), title: z.string().min(1).max(60) }).nullable(),+ quote: z.string().transform((value) => value.trim()),+ title: z.string().min(1).max(200),+ why: nullableText,+ }),+ ),+});++/** Which material a distillation read, as the commit step needs to record it. */+export interface DistillMaterial {+ /** What the commit records as the run's subject; a file is recorded as its parsed document. */+ subjectId: string | null;+ subjectType: 'document' | 'standalone' | 'topic';+ title: string;+ /** Whether the tail of the material was left unread. */+ truncated: boolean;+ type: DistillSource['type'];+}++/**+ * Reads a material the reviewer brought and proposes every rule it states, for them to tick.+ * Nothing is written here: the candidates come back with the material they were read from, and+ * only the commit step files the ones the reviewer kept.+ */+export class ExpertiseRuleDistillService {+ private db: LobeChatDatabase;+ private userId: string;+ private workspaceId?: string;++ constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {+ this.db = db;+ this.userId = userId;+ this.workspaceId = workspaceId;+ }++ /**+ * A full read of a library item is a content dump, so it honours the same "No access" restriction+ * as the document and file content endpoints: a restricted knowledge base stays retrievable by+ * agents but its text is never handed to a member through distillation.+ */+ private assertReadable = (id: string) =>+ assertContentsNotInRestrictedKnowledgeBase(+ { serverDB: this.db, userId: this.userId, workspaceId: this.workspaceId },+ [id],+ );++ /** The material's text and how its origin is recorded, read within the caller's scope. */+ resolveMaterial = async (+ source: DistillSource,+ ): Promise<{ material: Omit<DistillMaterial, 'truncated'>; text: string }> => {+ switch (source.type) {+ case 'text': {+ const text = source.text.trim();+ // The first line names it, without the Markdown heading marks a pasted guideline starts with.+ const firstLine = (text.split('\n')[0] ?? '').replace(/^#+\s*/, '');+ const title = source.title?.trim() || sliceHead(firstLine, 40);+ return {+ material: { subjectId: null, subjectType: 'standalone', title, type: 'text' },+ text,+ };+ }+ case 'document': {+ await this.assertReadable(source.id);+ const doc = await new DocumentModel(this.db, this.userId, this.workspaceId).findById(+ source.id,+ );+ if (!doc) throw new TRPCError({ code: 'NOT_FOUND', message: 'Document not found' });+ return {+ material: {+ subjectId: doc.id,+ subjectType: 'document',+ title: doc.title || doc.filename || '',+ type: 'document',+ },+ text: doc.content ?? '',+ };+ }+ case 'file': {+ await this.assertReadable(source.id);+ // Parsing is idempotent: a file already read for chat or the library is not read again.+ const doc = await new DocumentService(this.db, this.userId, this.workspaceId).parseFile(+ source.id,+ );+ return {+ material: {+ subjectId: doc.id,+ subjectType: 'document',+ title: doc.filename,+ type: 'file',+ },+ text: doc.content ?? '',+ };+ }+ case 'topic': {+ const topic = await new TopicModel(this.db, this.userId, this.workspaceId).findById(+ source.id,+ );+ if (!topic) throw new TRPCError({ code: 'NOT_FOUND', message: 'Topic not found' });+ const { items } = await new MessageModel(+ this.db,+ this.userId,+ this.workspaceId,+ ).queryTopicTranscript({ limit: TOPIC_MAX_MESSAGES, offset: 0, topicId: source.id });+ const text = items+ .filter((item) => (item.role === 'user' || item.role === 'assistant') && item.content)+ .map(+ (item) =>+ `${item.role === 'user' ? 'Reviewer' : 'Assistant'}: ${sliceHead(item.content!.trim(), MESSAGE_MAX_CHARS)}`,+ )+ .join('\n\n');+ return {+ material: {+ subjectId: topic.id,+ subjectType: 'topic',+ title: topic.title ?? '',+ type: 'topic',+ },+ text,+ };+ }+ }+ };++ distillRules = async (input: DistillRulesInput) => {+ const { material, text } = await this.resolveMaterial(input.source);+ if (!text.trim()) {+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'The material has no readable text' });+ }+ const read = sliceHead(text, MATERIAL_MAX_CHARS);+ const fittedGroups = fitCatalog(+ input.groups,+ (group) => group.id.length + group.title.length + group.gate.length + 10,+ CATALOG_MAX_CHARS,+ );+ const { kept: rules } = fitCatalog(+ input.rules,+ (rule) => rule.id.length + rule.title.length + 6,+ CATALOG_MAX_CHARS - fittedGroups.used,+ );+ const groups = fittedGroups.kept;++ const modelConfig = await resolveExpertiseModelConfig(this.db, this.userId);+ const ai = new AiGenerationService(this.db, this.userId, this.workspaceId);+ const result = DistillResultSchema.parse(+ await ai.generateObject(+ {+ ...chainExpertiseRuleDistill({+ groups,+ material: { kind: material.type, text: read, title: material.title },+ rules,+ }),+ ...modelConfig,+ schema: EXPERTISE_RULE_DISTILL_JSON_SCHEMA,+ },+ {+ metadata: { trigger: RequestTrigger.Expertise },+ tracing: {+ promptVersion: EXPERTISE_RULE_DISTILL_PROMPT_VERSION,+ scenario: TRACING_SCENARIOS.ExpertiseRuleDistill,+ schemaName: EXPERTISE_RULE_DISTILL_JSON_SCHEMA.name,+ },+ },+ ),+ );++ // Ids the model names but the reviewer does not have are slips, not requests.+ const groupIds = new Set(groups.map((group) => group.id));+ const ruleIds = new Set(rules.map((rule) => rule.id));+ return {+ candidates: result.rules.map((rule) => {+ const groupId = rule.groupId && groupIds.has(rule.groupId) ? rule.groupId : null;+ return {+ ...rule,+ duplicateOf: rule.duplicateOf && ruleIds.has(rule.duplicateOf) ? rule.duplicateOf : null,+ groupId,+ newGroup: groupId ? null : rule.newGroup,+ };+ }),+ material: { ...material, truncated: read.length < text.length } satisfies DistillMaterial,+ };+ };+}diff --git a/locales/en-US/memory.json b/locales/en-US/memory.jsonindex 4eee723e612..8aaceac180c 100644--- a/locales/en-US/memory.json+++ b/locales/en-US/memory.json@@ -95,6 +95,7 @@"purge.success": "All memories have been deleted.","purge.title": "Purge All Memories","rules.actions.archive": "Archive",+ "rules.actions.distill": "Distill from material","rules.actions.edit": "Reword","rules.actions.editGate": "Change the gate question…","rules.actions.merge": "Merge into…",@@ -120,7 +121,7 @@"rules.compose.back": "Back","rules.compose.blank": "Write it myself","rules.compose.describeHint": "Before writing, ask: strip the page, component and task names — does it still hold?",- "rules.compose.describePlaceholder": "Say in one sentence what you require, or paste a document. The rule is drafted from it.",+ "rules.compose.describePlaceholder": "Say in one sentence what you require. Have a whole guideline or document? Use \"Distill from material\" instead.","rules.compose.describeTitle": "Write a rule","rules.compose.enforcementBlock": "Block · will hold the delivery (not in effect yet)","rules.compose.enforcementRemind": "Remind · nudges the agent only",@@ -147,6 +148,33 @@"rules.direction.unset": "Not judged yet","rules.direction.unsetArchivedDesc": "Archived before its direction was recorded","rules.direction.unsetDesc": "Being judged — or pick one yourself",+ "rules.distill.description": "Pick a material you already have; every rule it states is listed for you to tick.",+ "rules.distill.duplicate": "Already a rule; tick to record this passage on it",+ "rules.distill.loadFailed": "Could not load the list.",+ "rules.distill.newGroup": "New group: {{title}}",+ "rules.distill.noDocuments": "No documents yet.",+ "rules.distill.noTopics": "No matching conversations.",+ "rules.distill.none": "No rules were found in this material.",+ "rules.distill.pickFile": "Choose from the library",+ "rules.distill.read": "Distill",+ "rules.distill.readFailed": "Could not read rules out of it. Try again.",+ "rules.distill.reading": "Reading it and pulling out the rules…",+ "rules.distill.reviewStep": "Tick the rules to keep; edit any wording",+ "rules.distill.reviewTitle": "{{count}} rules in \"{{title}}\"",+ "rules.distill.save": "Keep {{count}}",+ "rules.distill.saved": "Kept {{count}} rules",+ "rules.distill.searchTopic": "Search conversations",+ "rules.distill.tab.document": "Document",+ "rules.distill.tab.file": "Library file",+ "rules.distill.tab.text": "Paste or upload",+ "rules.distill.tab.topic": "Conversation",+ "rules.distill.textPlaceholder": "Paste a guideline, a spec or review notes…",+ "rules.distill.title": "Distill rules from material",+ "rules.distill.truncated": "The material is long; only its beginning was read.",+ "rules.distill.untitled": "Untitled",+ "rules.distill.upload": "Upload a file",+ "rules.distill.uploadFailed": "Could not upload the file.",+ "rules.distill.uploadHint": "Markdown, PDF, Word, PowerPoint or plain text","rules.enforcement.block": "Block","rules.enforcement.blockDesc": "Will hold the delivery until you let it through. Not in effect yet: for now it only reminds","rules.enforcement.blockHint": "Block: will hold the delivery (not in effect yet, reminds for now). Click to switch to remind",@@ -206,8 +234,11 @@"rules.onboarding.agents.descriptionMany": "{{agents}} agents have learned {{count}} on their own","rules.onboarding.agents.title": "What agents learned","rules.onboarding.backlog": "{{count}} rounds not read yet",- "rules.onboarding.description": "Say one thing you expect from a delivery, or paste a guideline you have; it becomes a checkable rule.",+ "rules.onboarding.description": "Say one thing you expect from a delivery; it becomes a rule that can be checked.","rules.onboarding.descriptionGrow": "Reasons you write when sending an acceptance back grow into rules here too.",+ "rules.onboarding.distill.action": "Distill",+ "rules.onboarding.distill.description": "A guideline, document, file or conversation you already have",+ "rules.onboarding.distill.title": "Distill from material","rules.onboarding.listTitle": "Rules also come from","rules.onboarding.reject.action": "Open","rules.onboarding.reject.description": "Reject a check and say why; it is distilled when the next round lands",@@ -217,6 +248,7 @@"rules.origin.authored": "You wrote it","rules.origin.distilled": "You sent {{hits}} rounds back over this","rules.origin.distilledAndObserved": "You sent {{rejections}} rounds back over this; it also came up {{conversations}} times in conversations",+ "rules.origin.fromMaterial": "Read from material you brought ({{count}})","rules.origin.generalizedFrom": "Merged from \"{{titles}}\"","rules.origin.lastHit": ", last {{time}}","rules.origin.learned": "Learned from your work",@@ -256,7 +288,12 @@"rules.sources.conversation": "Conversation","rules.sources.empty": "The rejections behind this rule are no longer reachable.","rules.sources.loadFailed": "Could not load where this came from.",+ "rules.sources.material.document": "Document",+ "rules.sources.material.file": "File",+ "rules.sources.material.text": "Pasted",+ "rules.sources.material.topic": "Conversation","rules.sources.open": "Open",+ "rules.sources.openMaterial": "Open","rules.sources.openMessage": "Go to message","rules.sources.openTopic": "Open conversation","rules.sources.rejected": "you said it learned this wrong",diff --git a/locales/zh-CN/memory.json b/locales/zh-CN/memory.jsonindex a20c2a3793e..46c00cd4c99 100644--- a/locales/zh-CN/memory.json+++ b/locales/zh-CN/memory.json@@ -95,6 +95,7 @@"purge.success": "所有记忆已被删除。","purge.title": "清除所有记忆","rules.actions.archive": "归档",+ "rules.actions.distill": "从材料提炼","rules.actions.edit": "改措辞","rules.actions.editGate": "改守门题…","rules.actions.merge": "合并到…",@@ -120,7 +121,7 @@"rules.compose.back": "返回","rules.compose.blank": "自己写","rules.compose.describeHint": "写之前先想一下:去掉页面名、组件名、这次的任务名,它还成立吗?",- "rules.compose.describePlaceholder": "一句话说你要求什么,或者把一段文档贴进来,规矩会从这里生成。",+ "rules.compose.describePlaceholder": "一句话说你要求什么,规矩会从这里生成。有整份规范或文档?用「从材料提炼」。","rules.compose.describeTitle": "写一条规矩","rules.compose.enforcementBlock": "拦 · 将拦下交付(尚未生效)","rules.compose.enforcementRemind": "提醒 · 只提醒 Agent",@@ -147,6 +148,33 @@"rules.direction.unset": "还没判定","rules.direction.unsetArchivedDesc": "归档时还没有记录方向","rules.direction.unsetDesc": "正在判定,也可以自己选",+ "rules.distill.description": "选一份现成的材料,它讲到的规矩会逐条列出来,你勾选要留下的。",+ "rules.distill.duplicate": "已有这条规矩,勾选会把这段原文记到它上面",+ "rules.distill.loadFailed": "列表没能加载出来。",+ "rules.distill.newGroup": "新建一组:{{title}}",+ "rules.distill.noDocuments": "还没有文稿。",+ "rules.distill.noTopics": "没有找到对话。",+ "rules.distill.none": "这份材料里没有找到规矩。",+ "rules.distill.pickFile": "从资源库选择",+ "rules.distill.read": "开始提炼",+ "rules.distill.readFailed": "没能从这份材料里提炼出规矩,再试一次。",+ "rules.distill.reading": "正在读材料,逐条提炼规矩…",+ "rules.distill.reviewStep": "勾选要留下的规矩,措辞可以直接改",+ "rules.distill.reviewTitle": "《{{title}}》里有 {{count}} 条规矩",+ "rules.distill.save": "记下 {{count}} 条",+ "rules.distill.saved": "记下了 {{count}} 条",+ "rules.distill.searchTopic": "搜索对话",+ "rules.distill.tab.document": "文稿",+ "rules.distill.tab.file": "资源库文件",+ "rules.distill.tab.text": "粘贴或上传",+ "rules.distill.tab.topic": "对话",+ "rules.distill.textPlaceholder": "粘贴一段规范、需求说明或评审记录…",+ "rules.distill.title": "从材料提炼规矩",+ "rules.distill.truncated": "材料太长,只读了前面一部分。",+ "rules.distill.untitled": "未命名",+ "rules.distill.upload": "上传文件",+ "rules.distill.uploadFailed": "文件没有传上去。",+ "rules.distill.uploadHint": "支持 Markdown、PDF、Word、PPT 和纯文本","rules.enforcement.block": "拦","rules.enforcement.blockDesc": "将拦下交付,直到你放行。尚未生效,目前仍只提醒","rules.enforcement.blockHint": "拦:将拦下交付(尚未生效,目前仍只提醒)。点一下改成提醒",@@ -206,8 +234,11 @@"rules.onboarding.agents.descriptionMany": "{{agents}} 个 Agent 已经自己学到 {{count}} 条","rules.onboarding.agents.title": "Agent 学到的","rules.onboarding.backlog": "{{count}} 轮还没读",- "rules.onboarding.description": "说一句你的交付要求,或贴一段现成规范,整理成可检查的规矩。",+ "rules.onboarding.description": "说一句你对交付的要求,整理成一条可检查的规矩。","rules.onboarding.descriptionGrow": "你打回验收时写下的理由,也会自动长到这里。",+ "rules.onboarding.distill.action": "提炼",+ "rules.onboarding.distill.description": "已有的规范、文稿、文件或对话,一次提炼出多条",+ "rules.onboarding.distill.title": "从材料提炼","rules.onboarding.listTitle": "规矩还会从这些地方来","rules.onboarding.reject.action": "去验收","rules.onboarding.reject.description": "在验收里打回一项并写下理由,下一轮交付后沉淀成规矩",@@ -217,6 +248,7 @@"rules.origin.authored": "你自己写的","rules.origin.distilled": "你为这事打回过 {{hits}} 次","rules.origin.distilledAndObserved": "你为这事打回过 {{rejections}} 次,对话里另出现过 {{conversations}} 次",+ "rules.origin.fromMaterial": "从你给的材料里提炼的({{count}} 处)","rules.origin.generalizedFrom": "由「{{titles}}」合并而来","rules.origin.lastHit": ",最近一次 {{time}}","rules.origin.learned": "从你的工作里学到的",@@ -256,7 +288,12 @@"rules.sources.conversation": "对话","rules.sources.empty": "这条规矩背后的打回已经找不回来了。","rules.sources.loadFailed": "来源没加载出来。",+ "rules.sources.material.document": "文稿",+ "rules.sources.material.file": "文件",+ "rules.sources.material.text": "粘贴的材料",+ "rules.sources.material.topic": "对话","rules.sources.open": "打开",+ "rules.sources.openMaterial": "打开原文","rules.sources.openMessage": "定位到消息","rules.sources.openTopic": "打开对话","rules.sources.rejected": "你说这条学错了",diff --git a/packages/const/src/llmGenerationTracing.ts b/packages/const/src/llmGenerationTracing.tsindex 3102768b7b8..6ae03f48a24 100644--- a/packages/const/src/llmGenerationTracing.ts+++ b/packages/const/src/llmGenerationTracing.ts@@ -15,6 +15,7 @@ export const TRACING_SCENARIOS = {ExpertiseDomainDraft: 'expertise_domain_draft',ExpertiseRejectionIngestion: 'expertise_rejection_ingestion',ExpertiseRuleDirection: 'expertise_rule_direction',+ ExpertiseRuleDistill: 'expertise_rule_distill',ExpertiseRuleDraft: 'expertise_rule_draft',ExpertiseRuleGroupDraft: 'expertise_rule_group_draft',ExpertiseTopicIngestion: 'expertise_topic_ingestion',diff --git a/packages/database/src/models/__tests__/expertise.test.ts b/packages/database/src/models/__tests__/expertise.test.tsindex e7278b532c1..59dab5f56fa 100644--- a/packages/database/src/models/__tests__/expertise.test.ts+++ b/packages/database/src/models/__tests__/expertise.test.ts@@ -6,6 +6,7 @@ import { getTestDB } from '../../core/getTestDB';import { ExpertiseRuleRepository } from '../../repositories/expertiseRules';import {agents,+ documents,expertiseBindings,expertiseDomains,expertiseHits,@@ -888,6 +889,163 @@ describe('ExpertiseModel', () => {expect(rows.every((row) => row.status === 'active')).toBe(true);});+ it('numbers a material run after a concurrent writer holding the same domain', async () => {+ await seedRuleGroup();+ let release!: () => void;+ let reportLocked!: () => void;+ const released = new Promise<void>((resolve) => {+ release = resolve;+ });+ const locked = new Promise<void>((resolve) => {+ reportLocked = resolve;+ });+ // Another writer (ingestion, a second distillation) takes the domain lock and numbers a run.+ const other = serverDB.transaction(async (tx) => {+ await tx+ .select({ id: expertiseDomains.id })+ .from(expertiseDomains)+ .where(eq(expertiseDomains.id, 'rules-domain'))+ .for('update');+ reportLocked();+ await released;+ await new ExpertiseModel(tx as LobeChatDatabase, userId).insertMaterialRun({+ domainId: 'rules-domain',+ reflectionKey: 'material:text:other',+ subjectId: 'other',+ subjectType: 'standalone',+ });+ });+ await locked;++ const distilling = new ExpertiseRuleRepository(serverDB, userId).commitDistilled(+ { subjectId: null, subjectType: 'standalone', title: 'notes', type: 'text' },+ [+ {+ domainId: 'rules-domain',+ kind: 'create',+ quote: 'always rebase',+ rule: { title: 'Rebase before delivering' },+ },+ ],+ );+ await new Promise<void>((resolve) => setTimeout(resolve, 50));+ release();++ const settled = await Promise.allSettled([other, distilling]);+ expect(settled.map(({ status }) => status)).toEqual(['fulfilled', 'fulfilled']);+ const runs = await serverDB+ .select({ runIndex: expertiseRuns.runIndex })+ .from(expertiseRuns)+ .where(eq(expertiseRuns.domainId, 'rules-domain'));+ expect(new Set(runs.map(({ runIndex }) => runIndex)).size).toBe(runs.length);+ });++ it("refuses to number a run or file a rule into another user's domain", async () => {+ await seedRuleGroup();++ const results = await new ExpertiseRuleRepository(serverDB, userId).commitDistilled(+ { subjectId: null, subjectType: 'standalone', title: 'notes', type: 'text' },+ [+ {+ domainId: 'rules-foreign-domain',+ kind: 'create',+ quote: 'always rebase',+ rule: { title: 'Rebase before delivering' },+ },+ ],+ );++ expect(results).toEqual([]);+ const runs = await serverDB+ .select({ id: expertiseRuns.id })+ .from(expertiseRuns)+ .where(eq(expertiseRuns.domainId, 'rules-foreign-domain'));+ expect(runs).toEqual([]);+ expect(+ await new ExpertiseModel(serverDB, userId).insertMaterialRun({+ domainId: 'rules-foreign-domain',+ reflectionKey: 'material:text:x',+ subjectId: 'x',+ subjectType: 'standalone',+ }),+ ).toBeNull();+ });++ it('files rules distilled from a document and records a restatement on the rule it repeats', async () => {+ const { first } = await seedRuleGroup();+ await serverDB.insert(documents).values({+ content: '交付前必须 rebase 到 canary。',+ fileType: 'markdown',+ id: 'distill-doc',+ source: 'document',+ sourceType: 'api',+ title: '工程规范',+ totalCharCount: 20,+ totalLineCount: 1,+ userId,+ });+ const repository = new ExpertiseRuleRepository(serverDB, userId);++ const results = await repository.commitDistilled(+ { subjectId: 'distill-doc', subjectType: 'document', title: '工程规范', type: 'document' },+ [+ {+ domainId: 'rules-domain',+ kind: 'create',+ quote: '交付前必须 rebase 到 canary。',+ rule: { enforcement: 'block', title: '交付前先 rebase 到 canary' },+ },+ { intoId: first, kind: 'merge', quote: '证据只拍成功路径' },+ ],+ );++ expect(results.map(({ kind }) => kind)).toEqual(['create', 'merge']);+ const created = results[0].id;+ const model = new ExpertiseModel(serverDB, userId);+ const rules = (await model.listRules()).flatMap((group) => group.rules);+ // Read from a material: counted apart from rejections and conversations, and not "yours".+ expect(rules.find(({ id }) => id === created)).toMatchObject({+ authored: false,+ conversationHitCount: 0,+ enforcement: 'block',+ materialHitCount: 1,+ rejectionHitCount: 0,+ });+ expect(rules.find(({ id }) => id === first)).toMatchObject({ materialHitCount: 1 });++ const [source] = await model.listLessonSources(created);+ expect(source).toMatchObject({+ documentId: 'distill-doc',+ example: '交付前必须 rebase 到 canary。',+ fromAcceptance: false,+ materialType: 'document',+ where: '工程规范',+ });+ });++ it('keeps quotes read from a material out of how reliably a rule is practised', async () => {+ const { first } = await seedRuleGroup();++ const [created] = await new ExpertiseRuleRepository(serverDB, userId).commitDistilled(+ { subjectId: null, subjectType: 'standalone', title: 'notes', type: 'text' },+ [+ {+ domainId: 'rules-domain',+ kind: 'create',+ quote: 'always rebase',+ rule: { title: 'Rebase before delivering' },+ },+ { intoId: first, kind: 'merge', quote: 'shoot the success path' },+ ],+ );++ const model = new ExpertiseModel(serverDB, userId);+ expect(await model.reliabilitySeries(['rules-domain'])).toEqual([]);+ const lessons = await model.listLessonsWithRecent(['rules-domain']);+ expect(lessons.find(({ id }) => id === created.id)?.recent).toEqual([]);+ expect(lessons.find(({ id }) => id === first)?.recent).toEqual([]);+ });+it('moves an unencumbered rule in place with a fresh code', async () => {const { first } = await seedRuleGroup();const model = new ExpertiseModel(serverDB, userId);diff --git a/packages/database/src/models/expertise.ts b/packages/database/src/models/expertise.tsindex b01c1c231b6..b2ebf0c4303 100644--- a/packages/database/src/models/expertise.ts+++ b/packages/database/src/models/expertise.ts@@ -11,6 +11,7 @@ import { and, asc, desc, eq, inArray, isNotNull, isNull, or, type SQL, sql } froimport {agents,+ documents,expertiseBindings,expertiseDomains,expertiseDomainSnapshots,@@ -71,6 +72,13 @@ const carrierColumns = (: { boundUserId: owner.userId };};+/**+ * Runs that observed practice: a material the reviewer distilled (`reflectionKey` `material:…`)+ * records the passages a rule was read from, which are not outcomes of applying it.+ */+const notMaterialRun = () =>+ sql`coalesce(${expertiseRuns.reflectionKey}, '') not like 'material:%'`;+export class ExpertiseModel {private db: LobeChatDatabase;private userId: string;@@ -186,6 +194,8 @@ export class ExpertiseModel {/*** Per-run pass/violation counts — the reliability series behind the "做对率" chart.* A run without hits produces no row; callers treat missing runs as "nothing to judge".+ * A material the reviewer distilled is not practice: its quotes are evidence the rule exists,+ * not a run that got it right, so they never count as passes.*/reliabilitySeries = async (domainIds: string[]) => {if (domainIds.length === 0) return [];@@ -198,7 +208,7 @@ export class ExpertiseModel {}).from(expertiseHits).innerJoin(expertiseRuns, eq(expertiseRuns.id, expertiseHits.runId))- .where(inArray(expertiseHits.domainId, domainIds))+ .where(and(inArray(expertiseHits.domainId, domainIds), notMaterialRun())).groupBy(expertiseHits.domainId, expertiseRuns.runIndex).orderBy(asc(expertiseHits.domainId), asc(expertiseRuns.runIndex));};@@ -369,7 +379,11 @@ export class ExpertiseModel {// reader uses for `taughtByUser`..map(({ originRunId, ...lesson }) => ({...lesson,- ...(bySource.get(lesson.id) ?? { conversationHitCount: 0, rejectionHitCount: 0 }),+ ...(bySource.get(lesson.id) ?? {+ conversationHitCount: 0,+ materialHitCount: 0,+ rejectionHitCount: 0,+ }),authored: lesson.createdByUserId != null && originRunId == null,})),scopes: (bindingsByDomain.get(domain.id) ?? []).map((binding) => {@@ -409,9 +423,16 @@ export class ExpertiseModel {checkTitle: verifyCheckResults.checkItemTitle,createdAt: expertiseHits.createdAt,example: expertiseHits.example,+ // A material the reviewer brought: the document it was read from (a file is recorded as+ // its parsed document, which keeps the file id), and which kind of material it was.+ documentFileId: documents.fileId,+ documentId: documents.id,// Read from the run, not from the check-result join: a deleted acceptance leaves that// join empty, and the hit was still a rejection.fromAcceptance: sql<boolean>`coalesce(${expertiseRuns.reflectionKey}, '') like 'acceptance:%'`,+ materialType: sql<+ string | null+ >`case when ${expertiseRuns.reflectionKey} like 'material:%' then split_part(${expertiseRuns.reflectionKey}, ':', 2) end`,id: expertiseHits.id,// Where a conversation source can be reopened: the topic, the agent it lives under, and// the message the observation was read from when ingestion could find it.@@ -438,6 +459,15 @@ export class ExpertiseModel {buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, topics),),)+ // Only a document the viewer can open, by the same scope documents are listed with.+ .leftJoin(+ documents,+ and(+ eq(expertiseRuns.subjectType, 'document'),+ eq(documents.id, expertiseRuns.subjectId),+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, documents),+ ),+ ).leftJoin(verifyCheckResults, eq(verifyCheckResults.id, expertiseHits.sourceCheckResultId)).leftJoin(verifyRuns, eq(verifyRuns.id, verifyCheckResults.verifyRunId)).where(@@ -530,8 +560,10 @@ export class ExpertiseModel {? []: await this.db.select({- conversations: sql<number>`count(*) filter (where coalesce(${expertiseRuns.reflectionKey}, '') not like 'acceptance:%')::int`,+ conversations: sql<number>`count(*) filter (where coalesce(${expertiseRuns.reflectionKey}, '') not like 'acceptance:%' and coalesce(${expertiseRuns.reflectionKey}, '') not like 'material:%')::int`,lessonId: expertiseHits.lessonId,+ // Read from a material the reviewer brought: evidence the rule was stated, not seen.+ materials: sql<number>`count(*) filter (where ${expertiseRuns.reflectionKey} like 'material:%')::int`,rejections: sql<number>`count(*) filter (where ${expertiseRuns.reflectionKey} like 'acceptance:%')::int`,}).from(expertiseHits)@@ -543,11 +575,15 @@ export class ExpertiseModel {return new Map(lessonIds.map((id) => {const lineage = lineages.get(id) ?? [];- const sum = (key: 'conversations' | 'rejections') =>+ const sum = (key: 'conversations' | 'materials' | 'rejections') =>lineage.reduce((total, member) => total + (byLesson.get(member)?.[key] ?? 0), 0);return [id,- { conversationHitCount: sum('conversations'), rejectionHitCount: sum('rejections') },+ {+ conversationHitCount: sum('conversations'),+ materialHitCount: sum('materials'),+ rejectionHitCount: sum('rejections'),+ },];}),);@@ -589,6 +625,7 @@ export class ExpertiseModel {* Active lessons for the portrait, each with its most recent hit outcomes (newest last).* Recent outcomes are what the client folds into a reliability tier; the topic title of each* hit lets the row say *where* it last went wrong without another query.+ * Material quotes are left out for the same reason as in {@link reliabilitySeries}.*/listLessonsWithRecent = async (domainIds: string[], recentLimit = 6) => {if (domainIds.length === 0) return [];@@ -625,7 +662,7 @@ export class ExpertiseModel {}).from(expertiseHits).innerJoin(expertiseRuns, eq(expertiseRuns.id, expertiseHits.runId))- .where(inArray(expertiseHits.domainId, domainIds)),+ .where(and(inArray(expertiseHits.domainId, domainIds), notMaterialRun())),);const recentRows = await this.db.with(ranked)@@ -1120,6 +1157,11 @@ export class ExpertiseModel {enforcement?: ExpertiseEnforcement;how?: string;limits?: string;+ /**+ * The run it was read from, when it was distilled from a material rather than typed. It also+ * keeps the row from reading as "you wrote it", which is decided by the absence of an origin.+ */+ originRunId?: string;title: string;why?: string;}) => {@@ -1147,6 +1189,7 @@ export class ExpertiseModel {direction: params.direction ?? null,domainId: params.domainId,enforcement: params.enforcement ?? 'remind',+ originRunId: params.originRunId,polarity: 'rule',reasonKind: 'taste',reasonSource: 'reviewer',@@ -1159,6 +1202,76 @@ export class ExpertiseModel {});};+ /**+ * One reading of a material the reviewer brought, as a run on one domain. `reflectionKey`+ * starts with `material:` so counts and sources can tell it apart from rejections and+ * conversations the system observed on its own. Returns null, writing nothing, when the domain+ * is not one the caller may file into.+ */+ insertMaterialRun = async (params: {+ domainId: string;+ reflectionKey: string;+ subjectId: string;+ subjectType: 'document' | 'standalone' | 'topic';+ }) => {+ // The domain row lock queues this behind any other writer numbering runs in the same domain+ // (another distillation, background ingestion); otherwise both read the same maximum and the+ // unique `(domain_id, run_index)` index aborts one whole save. Held until the caller commits.+ // Read in the caller's scope, so a foreign domain id is neither locked nor numbered.+ const [domain] = await this.db+ .select({ id: expertiseDomains.id })+ .from(expertiseDomains)+ .where(and(eq(expertiseDomains.id, params.domainId), this.scopeWhere()))+ .for('update');+ if (!domain) return null;+ const [prior] = await this.db+ .select({ value: sql<number | null>`max(${expertiseRuns.runIndex})` })+ .from(expertiseRuns)+ .where(eq(expertiseRuns.domainId, params.domainId));+ const [row] = await this.db+ .insert(expertiseRuns)+ .values({+ actorId: this.userId,+ actorType: 'user',+ completedAt: new Date(),+ domainId: params.domainId,+ hadHumanInLoop: true,+ reflectionKey: params.reflectionKey,+ runIndex: (prior?.value ?? 0) + 1,+ subjectId: params.subjectId,+ subjectType: params.subjectType,+ userId: this.userId,+ workspaceId: this.workspaceId,+ })+ .returning({ id: expertiseRuns.id });+ return row.id;+ };++ /**+ * The passage of a material a rule was read from. It is evidence that the material states the+ * rule, not a violation, so it does not add to `hitCount`.+ */+ insertMaterialHit = async (params: {+ domainId: string;+ lessonId: string;+ quote: string;+ runId: string;+ where: string;+ }) => {+ const [row] = await this.db+ .insert(expertiseHits)+ .values({+ domainId: params.domainId,+ example: params.quote || null,+ lessonId: params.lessonId,+ outcome: 'pass',+ runId: params.runId,+ where: params.where,+ })+ .returning({ id: expertiseHits.id });+ return row.id;+ };+/*** The same row `findLesson` returns, read under a row lock for the rest of the caller's* transaction. Anything computed from it — the next revision number, a section patch, mergeddiff --git a/packages/database/src/repositories/expertiseRules/index.ts b/packages/database/src/repositories/expertiseRules/index.tsindex baba20a59ac..e01b3cc87ba 100644--- a/packages/database/src/repositories/expertiseRules/index.ts+++ b/packages/database/src/repositories/expertiseRules/index.ts@@ -10,6 +10,33 @@ import type { LobeChatDatabase } from '../../type';export type RuleSectionPatch = Partial<Record<'rule' | 'why' | 'how' | 'limits', string | null>>;+/** Where a distilled rule was read from, as the distill step resolved it. */+export interface DistilledMaterial {+ subjectId: string | null;+ subjectType: 'document' | 'standalone' | 'topic';+ title: string;+ type: 'document' | 'file' | 'text' | 'topic';+}++/** One candidate the reviewer kept: filed as a new rule, or recorded on a rule that says it. */+export type DistilledItem =+ | {+ domainId?: string;+ kind: 'create';+ /** Opened only when no existing group was chosen. */+ newGroup?: { gate: string; title: string };+ quote: string;+ rule: {+ compilability?: 'compilable' | 'not-compilable';+ enforcement?: ExpertiseEnforcement;+ how?: string;+ limits?: string;+ title: string;+ why?: string;+ };+ }+ | { intoId: string; kind: 'merge'; quote: string };+export interface UpdateRulePatch {compilability?: 'compilable' | 'not-compilable';direction?: ExpertiseRuleDirection;@@ -102,6 +129,80 @@ export class ExpertiseRuleRepository {return { id: lessonId, revision };});+ /**+ * Files what the reviewer kept from one material, in one transaction. Each group touched gets+ * one run for this material (so the sources list can say "read from <material>"), every kept+ * rule gets the passage it was read from, and a candidate that restated an existing rule is+ * recorded on that rule instead of being filed twice. Returns the rules now carrying it.+ */+ commitDistilled = async (material: DistilledMaterial, items: DistilledItem[]) => {+ if (items.length === 0) return [];+ const commitId = crypto.randomUUID();+ const reflectionKey = `material:${material.type}:${commitId}`;+ return this.inTransaction(async (model) => {+ const runs = new Map<string, string | null>();+ // Null for a domain outside the caller's scope: nothing is numbered or filed there.+ const runFor = async (domainId: string) => {+ if (runs.has(domainId)) return runs.get(domainId)!;+ const runId = await model.insertMaterialRun({+ domainId,+ reflectionKey,+ subjectId: material.subjectId ?? commitId,+ subjectType: material.subjectType,+ });+ runs.set(domainId, runId);+ return runId;+ };+ // Several candidates may propose the same new group; open it once.+ const openedGroups = new Map<string, string>();+ const results: { id: string; kind: DistilledItem['kind'] }[] = [];++ for (const item of items) {+ if (item.kind === 'merge') {+ const target = await model.lockLesson(item.intoId);+ if (!target || target.status !== 'active') continue;+ const runId = await runFor(target.domainId);+ if (!runId) continue;+ await model.insertMaterialHit({+ domainId: target.domainId,+ lessonId: target.id,+ quote: item.quote,+ runId,+ where: material.title,+ });+ await model.updateLessonFields(target.id, { exampleCount: target.exampleCount + 1 });+ results.push({ id: target.id, kind: 'merge' });+ continue;+ }++ let domainId = item.domainId;+ if (!domainId && item.newGroup) {+ const key = item.newGroup.title.trim().toLowerCase();+ domainId =+ openedGroups.get(key) ??+ (await model.createRuleGroup({ gate: item.newGroup.gate, title: item.newGroup.title }));+ if (domainId) openedGroups.set(key, domainId);+ }+ if (!domainId) continue;++ const runId = await runFor(domainId);+ if (!runId) continue;+ const created = await model.createRule({ ...item.rule, domainId, originRunId: runId });+ if (!created) continue;+ const hitId = await model.insertMaterialHit({+ domainId,+ lessonId: created.id,+ quote: item.quote,+ runId,+ where: material.title,+ });+ await model.updateLessonFields(created.id, { exampleCount: 1, originHitId: hitId });+ results.push({ id: created.id, kind: 'create' });+ }+ return results;+ });+ };+/*** Folds one rule into another: the counts move to the target, the target gets a `generalize`* revision naming what it absorbed and a lineage pointer to read the source's evidence, and thediff --git a/packages/locales/src/default/memory.ts b/packages/locales/src/default/memory.tsindex f0b64930f7e..316c20cfe3f 100644--- a/packages/locales/src/default/memory.ts+++ b/packages/locales/src/default/memory.ts@@ -105,6 +105,7 @@ export default {'purge.success': 'All memories have been deleted.','purge.title': 'Purge All Memories','rules.actions.archive': 'Archive',+ 'rules.actions.distill': 'Distill from material','rules.actions.edit': 'Reword','rules.actions.editGate': 'Change the gate question…','rules.actions.merge': 'Merge into…',@@ -132,7 +133,7 @@ export default {'rules.compose.describeHint':'Before writing, ask: strip the page, component and task names — does it still hold?','rules.compose.describePlaceholder':- 'Say in one sentence what you require, or paste a document. The rule is drafted from it.',+ 'Say in one sentence what you require. Have a whole guideline or document? Use "Distill from material" instead.','rules.compose.describeTitle': 'Write a rule','rules.compose.enforcementBlock': 'Block · will hold the delivery (not in effect yet)','rules.compose.enforcementRemind': 'Remind · nudges the agent only',@@ -159,6 +160,34 @@ export default {'rules.direction.unset': 'Not judged yet','rules.direction.unsetArchivedDesc': 'Archived before its direction was recorded','rules.direction.unsetDesc': 'Being judged — or pick one yourself',+ 'rules.distill.description':+ 'Pick a material you already have; every rule it states is listed for you to tick.',+ 'rules.distill.duplicate': 'Already a rule; tick to record this passage on it',+ 'rules.distill.loadFailed': 'Could not load the list.',+ 'rules.distill.newGroup': 'New group: {{title}}',+ 'rules.distill.noDocuments': 'No documents yet.',+ 'rules.distill.noTopics': 'No matching conversations.',+ 'rules.distill.none': 'No rules were found in this material.',+ 'rules.distill.pickFile': 'Choose from the library',+ 'rules.distill.read': 'Distill',+ 'rules.distill.readFailed': 'Could not read rules out of it. Try again.',+ 'rules.distill.reading': 'Reading it and pulling out the rules…',+ 'rules.distill.reviewStep': 'Tick the rules to keep; edit any wording',+ 'rules.distill.reviewTitle': '{{count}} rules in "{{title}}"',+ 'rules.distill.save': 'Keep {{count}}',+ 'rules.distill.saved': 'Kept {{count}} rules',+ 'rules.distill.searchTopic': 'Search conversations',+ 'rules.distill.tab.document': 'Document',+ 'rules.distill.tab.file': 'Library file',+ 'rules.distill.tab.text': 'Paste or upload',+ 'rules.distill.tab.topic': 'Conversation',+ 'rules.distill.textPlaceholder': 'Paste a guideline, a spec or review notes…',+ 'rules.distill.title': 'Distill rules from material',+ 'rules.distill.truncated': 'The material is long; only its beginning was read.',+ 'rules.distill.untitled': 'Untitled',+ 'rules.distill.upload': 'Upload a file',+ 'rules.distill.uploadFailed': 'Could not upload the file.',+ 'rules.distill.uploadHint': 'Markdown, PDF, Word, PowerPoint or plain text','rules.enforcement.block': 'Block','rules.enforcement.blockDesc':'Will hold the delivery until you let it through. Not in effect yet: for now it only reminds',@@ -230,9 +259,13 @@ export default {'rules.onboarding.agents.title': 'What agents learned','rules.onboarding.backlog': '{{count}} rounds not read yet','rules.onboarding.description':- 'Say one thing you expect from a delivery, or paste a guideline you have; it becomes a checkable rule.',+ 'Say one thing you expect from a delivery; it becomes a rule that can be checked.','rules.onboarding.descriptionGrow':'Reasons you write when sending an acceptance back grow into rules here too.',+ 'rules.onboarding.distill.action': 'Distill',+ 'rules.onboarding.distill.description':+ 'A guideline, document, file or conversation you already have',+ 'rules.onboarding.distill.title': 'Distill from material','rules.onboarding.listTitle': 'Rules also come from','rules.onboarding.reject.action': 'Open','rules.onboarding.reject.description':@@ -244,6 +277,7 @@ export default {'rules.origin.distilled': 'You sent {{hits}} rounds back over this','rules.origin.distilledAndObserved':'You sent {{rejections}} rounds back over this; it also came up {{conversations}} times in conversations',+ 'rules.origin.fromMaterial': 'Read from material you brought ({{count}})','rules.origin.generalizedFrom': 'Merged from "{{titles}}"','rules.origin.lastHit': ', last {{time}}','rules.origin.learned': 'Learned from your work',@@ -284,7 +318,12 @@ export default {'rules.sources.conversation': 'Conversation','rules.sources.empty': 'The rejections behind this rule are no longer reachable.','rules.sources.loadFailed': 'Could not load where this came from.',+ 'rules.sources.material.document': 'Document',+ 'rules.sources.material.file': 'File',+ 'rules.sources.material.text': 'Pasted',+ 'rules.sources.material.topic': 'Conversation','rules.sources.open': 'Open',+ 'rules.sources.openMaterial': 'Open','rules.sources.openMessage': 'Go to message','rules.sources.openTopic': 'Open conversation','rules.sources.rejected': 'you said it learned this wrong',diff --git a/packages/prompts/src/chains/expertise.ts b/packages/prompts/src/chains/expertise.tsindex 428bb16629f..f2b9e56717b 100644--- a/packages/prompts/src/chains/expertise.ts+++ b/packages/prompts/src/chains/expertise.ts@@ -198,6 +198,111 @@ export const chainExpertiseRuleDraft = ({],});+export const EXPERTISE_RULE_DISTILL_PROMPT_VERSION = 'v1';++/**+ * Every rule a piece of material states — a pasted guideline, an uploaded file, a document, or a+ * conversation — as reviewable candidates. Each carries the editable fields of a lesson row, the+ * passage it was read from, and which existing rule (if any) already says the same thing, so the+ * review step can default duplicates off instead of filing them twice.+ */+export const EXPERTISE_RULE_DISTILL_JSON_SCHEMA = {+ name: 'expertise_rule_distill',+ schema: {+ additionalProperties: false,+ properties: {+ rules: {+ items: {+ additionalProperties: false,+ properties: {+ compilability: { enum: ['compilable', 'not-compilable'], type: 'string' },+ duplicateOf: { type: ['string', 'null'] },+ enforcement: { enum: ['block', 'remind'], type: 'string' },+ groupId: { type: ['string', 'null'] },+ how: { type: ['string', 'null'] },+ limits: { type: ['string', 'null'] },+ newGroup: {+ additionalProperties: false,+ properties: {+ gate: { type: 'string' },+ title: { maxLength: 40, type: 'string' },+ },+ required: ['gate', 'title'],+ type: ['object', 'null'],+ },+ quote: { maxLength: 400, type: 'string' },+ title: { maxLength: 120, type: 'string' },+ why: { type: ['string', 'null'] },+ },+ required: [+ 'compilability',+ 'duplicateOf',+ 'enforcement',+ 'groupId',+ 'how',+ 'limits',+ 'newGroup',+ 'quote',+ 'title',+ 'why',+ ],+ type: 'object',+ },+ maxItems: 20,+ type: 'array',+ },+ },+ required: ['rules'],+ type: 'object',+ },+} as const satisfies ExpertiseGenerateObjectSchema;++const EXPERTISE_RULE_DISTILL_SYSTEM_PROMPT = `You read a piece of material a reviewer brought — a guideline, a spec, a style guide, meeting notes, or a conversation in which they reviewed work — and extract the delivery rules it states, so they can hold every future delivery to them.++Return up to 20 rules, most important first. For each:+- title: the rule as one imperative sentence, general enough to apply to any future delivery (strip page names, component names and the name of this particular task), specific enough that a delivery can be judged against it;+- why: one or two sentences on what goes wrong when it is broken, or null when the material gives no reason and none is obvious;+- how: what counts as breaking it, as a concrete example a checker could look for, or null;+- limits: when it does NOT apply, or null when the material sets no boundary;+- enforcement: "block" only when the material clearly demands deliveries be held until fixed (must, never, required, 必须, 不许, 禁止); otherwise "remind";+- compilability: "compilable" when a program could check it or gather the evidence for it from the delivery (a diff, a file, a count), "not-compilable" when only a person or a model can judge it;+- groupId: the id of the existing group whose gate question this rule passes, or null when none fits;+- newGroup: when groupId is null, a proposed group — a short title and the gate question a rule must pass to be filed there; otherwise null. Propose as few new groups as possible and reuse the same proposal for related rules;+- quote: the shortest passage of the material, copied verbatim, that states this rule;+- duplicateOf: the id of an existing rule that already says the same thing, or null.++Only extract requirements the material actually states or the reviewer clearly demanded; never invent rules, and skip background, history and one-off requests about a single delivery. In a conversation, rules come from what the reviewer asked for or criticised, not from what the assistant proposed. Merge restatements of the same requirement into one rule. Write every human-facing field in the language the material uses.`;++interface ExpertiseRuleDistillChainInput {+ groups: { gate: string; id: string; title: string }[];+ material: { kind: string; text: string; title: string };+ rules: { id: string; title: string }[];+}++export const chainExpertiseRuleDistill = ({+ groups,+ material,+ rules,+}: ExpertiseRuleDistillChainInput): { messages: OpenAIChatMessage[] } => ({+ messages: [+ { content: EXPERTISE_RULE_DISTILL_SYSTEM_PROMPT, role: 'system' },+ {+ content: [+ groups.length > 0+ ? `Existing groups (id · title · gate question):\n${groups+ .map((group) => `- ${group.id} · ${group.title} · ${group.gate}`)+ .join('\n')}`+ : 'There are no groups yet; propose one in newGroup.',+ rules.length > 0+ ? `Existing rules (id · rule):\n${rules.map((rule) => `- ${rule.id} · ${rule.title}`).join('\n')}`+ : 'There are no existing rules yet.',+ `Material (${material.kind}) · ${material.title}:\n${material.text.trim()}`,+ ].join('\n\n'),+ role: 'user',+ },+ ],+});+export const EXPERTISE_RULE_DIRECTION_PROMPT_VERSION = 'v1';/**diff --git a/src/features/MemoryRules/DetailPanel.tsx b/src/features/MemoryRules/DetailPanel.tsxindex e0f6bd2fe04..efbae612560 100644--- a/src/features/MemoryRules/DetailPanel.tsx+++ b/src/features/MemoryRules/DetailPanel.tsx@@ -22,6 +22,7 @@ import {ActivityIcon,BellIcon,ClipboardCheckIcon,+ FileTextIcon,HistoryIcon,type LucideIcon,MessageSquareTextIcon,@@ -544,7 +545,9 @@ const RuleDocument = ({{t(source.fromAcceptance? 'rules.sources.acceptance'- : 'rules.sources.conversation',+ : source.materialType+ ? `rules.sources.material.${source.materialType as 'document' | 'file' | 'text' | 'topic'}`+ : 'rules.sources.conversation',)}</Tag><span style={{ fontSize: 13, fontWeight: 500 }}>@@ -569,6 +572,25 @@ const RuleDocument = ({{t(source.messageId ? 'rules.sources.openMessage' : 'rules.sources.openTopic')}</a>)}+ {/* A document or file it was read from opens where the reviewer keeps it. */}+ {source.documentId && (+ <a+ className={styles.link}+ href={buildWorkspaceAwarePath(+ source.documentFileId+ ? `/resource?file=${source.documentFileId}`+ : `/page/${source.documentId}`,+ workspaceSlug,+ )}+ onClick={(e) => {+ e.preventDefault();+ navigate(e.currentTarget.getAttribute('href')!);+ }}+ >+ <Icon icon={FileTextIcon} size={12} />+ {t('rules.sources.openMaterial')}+ </a>+ )}{source.acceptanceId && (<aclassName={styles.link}diff --git a/src/features/MemoryRules/DistillModal.tsx b/src/features/MemoryRules/DistillModal.tsxnew file mode 100644index 00000000000..426c9461e47--- /dev/null+++ b/src/features/MemoryRules/DistillModal.tsx@@ -0,0 +1,640 @@+'use client';++import type { ExpertiseEnforcement } from '@lobechat/types';+import { Flexbox, Icon } from '@lobehub/ui';+import {+ ActionIcon,+ Button,+ Checkbox,+ createModal,+ DropdownMenu,+ Input,+ Segmented,+ Spin,+ Text,+ TextArea,+ toast,+ useModalContext,+} from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar, cx } from 'antd-style';+import dayjs from 'dayjs';+import {+ ArrowLeftIcon,+ BellIcon,+ ChevronDownIcon,+ FileTextIcon,+ FolderIcon,+ FolderPlusIcon,+ LibraryIcon,+ MessageSquareTextIcon,+ ShieldCheckIcon,+ UploadIcon,+ XIcon,+} from 'lucide-react';+import { useMemo, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';++import GeneratingBorder from '@/components/GeneratingBorder';+import { openLibraryFilePicker } from '@/features/LibraryModal/FilePicker';+import {+ type DistillCandidate,+ type DistillInput,+ type DistillResult,+ expertiseService,+ type RuleGroup,+} from '@/services/expertise';+import { useFileStore } from '@/store/file';+import { shinyTextStyles } from '@/styles';++import { composeStyles } from './GroupModal';+import { useRecentPages, useTopics } from './useDistillSources';++const styles = createStaticStyles(({ css }) => ({+ candidate: css`+ display: flex;+ gap: 10px;+ align-items: flex-start;++ padding-block: 12px;+ padding-inline: 4px;++ & + & {+ border-block-start: 1px solid ${cssVar.colorBorderSecondary};+ }+ `,+ candidateOff: css`+ opacity: 0.55;+ `,+ chip: css`+ cursor: pointer;++ display: inline-flex;+ gap: 6px;+ align-items: center;++ padding-block: 2px;+ padding-inline: 6px;+ border-radius: ${cssVar.borderRadius};++ font-size: 12px;+ color: ${cssVar.colorTextSecondary};++ &:hover {+ background: ${cssVar.colorFillTertiary};+ }+ `,+ duplicate: css`+ font-size: 12px;+ color: ${cssVar.colorWarningText};+ `,+ option: css`+ cursor: pointer;++ display: flex;+ gap: 10px;+ align-items: center;++ padding-block: 8px;+ padding-inline: 10px;+ border-radius: ${cssVar.borderRadius};++ &:hover {+ background: ${cssVar.colorFillTertiary};+ }+ `,+ optionActive: css`+ background: ${cssVar.colorFillSecondary};++ &:hover {+ background: ${cssVar.colorFillSecondary};+ }+ `,+ optionMeta: css`+ flex: none;+ font-size: 12px;+ color: ${cssVar.colorTextTertiary};+ `,+ optionTitle: css`+ overflow: hidden;+ flex: 1;++ min-width: 0;++ text-overflow: ellipsis;+ white-space: nowrap;+ `,+ options: css`+ overflow-y: auto;+ max-height: 280px;+ `,+ quote: css`+ margin-block: 4px 0;+ padding-inline-start: 10px;+ border-inline-start: 2px solid ${cssVar.colorBorder};++ font-size: 12px;+ line-height: 1.6;+ color: ${cssVar.colorTextSecondary};+ `,+ titleInput: css`+ padding-inline: 0;+ font-weight: 500;+ `,+}));++type SourceTab = 'document' | 'file' | 'text' | 'topic';++/** What the reviewer picked, with a name to show while it is being read. */+interface PickedSource {+ name: string;+ source: DistillInput['source'];+}++/** One candidate as the reviewer is shaping it before it is filed. */+interface Draft {+ candidate: DistillCandidate;+ enforcement: ExpertiseEnforcement;+ /** An existing group, or `new` for the model's proposed group. */+ groupId: string | 'new';+ keep: boolean;+ title: string;+}++interface DistillContentProps {+ /** Whether a proposed new group may be opened; a new group always mounts on the reviewer. */+ canOpenGroup: boolean;+ /** The groups of the part on screen; candidates are filed into these. */+ groups: RuleGroup[];+ onDone: (ids: string[]) => void;+}++/**+ * Distilling rules from a material the reviewer already has: pick it (paste or upload, a+ * document, a library file, or a conversation), let the model read it, then tick the candidates+ * worth keeping. A candidate that restates an existing rule starts unticked; ticking it records+ * the passage on that rule instead of filing a second copy.+ */+const DistillContent = ({ canOpenGroup, groups, onDone }: DistillContentProps) => {+ const { t } = useTranslation('memory');+ const { close } = useModalContext();+ const uploadWithProgress = useFileStore((s) => s.uploadWithProgress);+ const fileInput = useRef<HTMLInputElement>(null);++ const [step, setStep] = useState<'pick' | 'reading' | 'review'>('pick');+ const [tab, setTab] = useState<SourceTab>('text');+ const [text, setText] = useState('');+ const [picked, setPicked] = useState<PickedSource>();+ const [uploading, setUploading] = useState(false);+ const [keywords, setKeywords] = useState('');+ const [result, setResult] = useState<DistillResult>();+ const [drafts, setDrafts] = useState<Draft[]>([]);+ const [saving, setSaving] = useState(false);++ const recentPages = useRecentPages(tab === 'document');+ const pages = recentPages.items;+ const topicList = useTopics(tab === 'topic', keywords);+ const topics = topicList.items;+ const rules = useMemo(+ () =>+ groups.flatMap((group) =>+ group.rules+ .filter((rule) => rule.status === 'active')+ .map(({ id, title }) => ({ id, title })),+ ),+ [groups],+ );+ const titleOf = (id: string | null) => rules.find((rule) => rule.id === id)?.title;+ const groupTitle = (id: string, candidate: DistillCandidate) =>+ id === 'new'+ ? t('rules.distill.newGroup', { title: candidate.newGroup?.title ?? '' })+ : (groups.find((group) => group.domain.id === id)?.domain.title ?? '');++ // Pasted text stands on its own; anything else needs a pick in its own tab.+ const source: PickedSource | undefined =+ tab === 'text' && !picked && text.trim()+ ? {+ name: text+ .trim()+ .split('\n')[0]+ .replace(/^#+\s*/, '')+ .slice(0, 40),+ source: { text: text.trim(), type: 'text' },+ }+ : picked;++ const switchTab = (next: SourceTab) => {+ setTab(next);+ setPicked(undefined);+ };++ const upload = async (file: File) => {+ setUploading(true);+ try {+ const uploaded = await uploadWithProgress({ file });+ if (uploaded) setPicked({ name: file.name, source: { id: uploaded.id, type: 'file' } });+ } catch (error) {+ console.error('[MemoryRules] material upload failed:', error);+ toast.error(t('rules.distill.uploadFailed'));+ } finally {+ setUploading(false);+ }+ };++ const read = async () => {+ if (!source) return;+ setStep('reading');+ try {+ const next = await expertiseService.distillRules({+ groups: groups.map(({ domain }) => ({+ gate: domain.domainFilter,+ id: domain.id,+ title: domain.title,+ })),+ rules,+ source: source.source,+ });+ const fallback = groups[0]?.domain.id;+ setResult(next);+ setDrafts(+ next.candidates.map((candidate) => ({+ candidate,+ enforcement: candidate.enforcement,+ groupId:+ candidate.groupId ?? (canOpenGroup && candidate.newGroup ? 'new' : (fallback ?? 'new')),+ keep: !candidate.duplicateOf,+ title: candidate.title,+ })),+ );+ setStep('review');+ } catch (error) {+ console.error('[MemoryRules] distill failed:', error);+ toast.error(t('rules.distill.readFailed'));+ setStep('pick');+ }+ };++ const patch = (index: number, value: Partial<Draft>) =>+ setDrafts((current) => current.map((d, i) => (i === index ? { ...d, ...value } : d)));++ const kept = drafts.filter((draft) => draft.keep && draft.title.trim());++ const save = async () => {+ if (!result || kept.length === 0 || saving) return;+ setSaving(true);+ try {+ const saved = await expertiseService.commitDistilledRules({+ items: kept.map(({ candidate, enforcement, groupId, title }) =>+ candidate.duplicateOf+ ? { intoId: candidate.duplicateOf, kind: 'merge' as const, quote: candidate.quote }+ : {+ domainId: groupId === 'new' ? undefined : groupId,+ kind: 'create' as const,+ newGroup: groupId === 'new' ? (candidate.newGroup ?? undefined) : undefined,+ quote: candidate.quote,+ rule: {+ compilability: candidate.compilability,+ enforcement,+ how: candidate.how ?? undefined,+ limits: candidate.limits ?? undefined,+ title: title.trim(),+ why: candidate.why ?? undefined,+ },+ },+ ),+ material: result.material,+ });+ toast.success(t('rules.distill.saved', { count: saved.length }));+ onDone(saved.filter((item) => item.kind === 'create').map((item) => item.id));+ close();+ } catch (error) {+ console.error('[MemoryRules] distill save failed:', error);+ toast.error(t('rules.saveFailed'));+ } finally {+ setSaving(false);+ }+ };++ const loadFailed = (retry: () => void) => (+ <Flexbox horizontal align={'center'} gap={8}>+ <Text type={'secondary'}>{t('rules.distill.loadFailed')}</Text>+ <Button onClick={retry}>{t('retry', { ns: 'common' })}</Button>+ </Flexbox>+ );++ const optionRow = (key: string, title: string, meta: string | undefined, onPick: () => void) => (+ <div+ key={key}+ className={cx(+ styles.option,+ picked?.source && 'id' in picked.source && picked.source.id === key && styles.optionActive,+ )}+ onClick={onPick}+ >+ <span className={styles.optionTitle}>{title || t('rules.distill.untitled')}</span>+ {meta && <span className={styles.optionMeta}>{meta}</span>}+ </div>+ );++ return (+ <Flexbox>+ <Flexbox className={composeStyles.head} gap={10}>+ {step === 'review' && (+ <Flexbox horizontal align={'center'} gap={8}>+ <ActionIcon+ icon={ArrowLeftIcon}+ size={'small'}+ title={t('rules.compose.back')}+ onClick={() => setStep('pick')}+ />+ <Text fontSize={12} type={'secondary'}>+ {t('rules.distill.reviewStep')}+ </Text>+ </Flexbox>+ )}+ <div className={composeStyles.titleStatic}>+ {step === 'review' && result+ ? t('rules.distill.reviewTitle', {+ count: result.candidates.length,+ title: result.material.title,+ })+ : t('rules.distill.title')}+ </div>+ {step === 'pick' && (+ <>+ <Text type={'secondary'}>{t('rules.distill.description')}</Text>+ <Segmented+ value={tab}+ options={[+ { label: t('rules.distill.tab.text'), value: 'text' },+ { label: t('rules.distill.tab.document'), value: 'document' },+ { label: t('rules.distill.tab.file'), value: 'file' },+ { label: t('rules.distill.tab.topic'), value: 'topic' },+ ]}+ onChange={(value) => switchTab(value as SourceTab)}+ />+ </>+ )}+ <ActionIcon className={composeStyles.close} icon={XIcon} onClick={() => close()} />+ </Flexbox>++ {step === 'pick' && (+ <Flexbox className={composeStyles.body} gap={10}>+ {tab === 'text' &&+ (picked ? (+ <Flexbox horizontal align={'center'} gap={8}>+ <Icon icon={FileTextIcon} size={14} />+ <span>{picked.name}</span>+ <ActionIcon icon={XIcon} size={'small'} onClick={() => setPicked(undefined)} />+ </Flexbox>+ ) : (+ <>+ <TextArea+ autoSize={{ maxRows: 14, minRows: 8 }}+ placeholder={t('rules.distill.textPlaceholder')}+ value={text}+ onChange={(e) => setText(e.target.value)}+ />+ <Flexbox horizontal align={'center'} gap={8}>+ <input+ hidden+ accept={'.md,.markdown,.txt,.pdf,.doc,.docx,.pptx,.csv,.json,.ipynb'}+ ref={fileInput}+ type={'file'}+ onChange={(e) => {+ const file = e.target.files?.[0];+ e.target.value = '';+ if (file) void upload(file);+ }}+ />+ <Button+ icon={<Icon icon={UploadIcon} />}+ loading={uploading}+ size={'small'}+ onClick={() => fileInput.current?.click()}+ >+ {t('rules.distill.upload')}+ </Button>+ <Text fontSize={12} type={'secondary'}>+ {t('rules.distill.uploadHint')}+ </Text>+ </Flexbox>+ </>+ ))}+ {tab === 'document' && (+ <div className={styles.options}>+ {recentPages.error ? (+ loadFailed(recentPages.retry)+ ) : !pages ? (+ <Spin size={'small'} />+ ) : pages.length === 0 ? (+ <Text type={'secondary'}>{t('rules.distill.noDocuments')}</Text>+ ) : (+ pages.map((page) =>+ optionRow(page.id, page.name, dayjs(page.updatedAt).format('YYYY-MM-DD'), () =>+ setPicked({ name: page.name, source: { id: page.id, type: 'document' } }),+ ),+ )+ )}+ </div>+ )}+ {tab === 'file' && (+ <Flexbox horizontal align={'center'} gap={8}>+ <Button+ icon={<Icon icon={LibraryIcon} />}+ onClick={() =>+ openLibraryFilePicker((attachments) => {+ const [first] = attachments;+ if (first)+ setPicked({ name: first.name, source: { id: first.fileId, type: 'file' } });+ })+ }+ >+ {t('rules.distill.pickFile')}+ </Button>+ {picked && (+ <Flexbox horizontal align={'center'} gap={6}>+ <Icon icon={FileTextIcon} size={14} />+ <span>{picked.name}</span>+ </Flexbox>+ )}+ </Flexbox>+ )}+ {tab === 'topic' && (+ <>+ <Input+ placeholder={t('rules.distill.searchTopic')}+ prefix={<Icon icon={MessageSquareTextIcon} size={14} />}+ value={keywords}+ onChange={(e) => setKeywords(e.target.value)}+ />+ <div className={styles.options}>+ {topicList.error ? (+ loadFailed(topicList.retry)+ ) : !topics ? (+ <Spin size={'small'} />+ ) : topics.length === 0 ? (+ <Text type={'secondary'}>{t('rules.distill.noTopics')}</Text>+ ) : (+ topics.map((topic) =>+ optionRow(topic.id, topic.title, topic.agent, () =>+ setPicked({ name: topic.title, source: { id: topic.id, type: 'topic' } }),+ ),+ )+ )}+ </div>+ </>+ )}+ </Flexbox>+ )}++ {step === 'reading' && (+ <Flexbox className={composeStyles.body} gap={10}>+ <GeneratingBorder generating className={composeStyles.inputShell}>+ <Flexbox gap={6} padding={16}>+ <Text weight={500}>{source?.name}</Text>+ <Flexbox horizontal align={'center'} gap={8}>+ <Spin size={'small'} variant={'network'} />+ <span className={shinyTextStyles.shinyText}>{t('rules.distill.reading')}</span>+ </Flexbox>+ </Flexbox>+ </GeneratingBorder>+ </Flexbox>+ )}++ {step === 'review' && result && (+ <Flexbox className={composeStyles.body}>+ {result.material.truncated && (+ <Text fontSize={12} type={'warning'}>+ {t('rules.distill.truncated')}+ </Text>+ )}+ {drafts.length === 0 ? (+ <Text type={'secondary'}>{t('rules.distill.none')}</Text>+ ) : (+ drafts.map((draft, index) => {+ const { candidate } = draft;+ const duplicate = titleOf(candidate.duplicateOf);+ return (+ <div+ className={cx(styles.candidate, !draft.keep && styles.candidateOff)}+ key={index}+ >+ <Checkbox+ checked={draft.keep}+ style={{ marginTop: 6 }}+ onChange={(checked) => patch(index, { keep: Boolean(checked) })}+ />+ <Flexbox flex={1} gap={4} style={{ minWidth: 0 }}>+ {duplicate ? (+ <Text weight={500}>{duplicate}</Text>+ ) : (+ <Input+ className={styles.titleInput}+ value={draft.title}+ variant={'borderless'}+ onChange={(e) => patch(index, { title: e.target.value })}+ />+ )}+ {duplicate && (+ <span className={styles.duplicate}>{t('rules.distill.duplicate')}</span>+ )}+ {candidate.quote && <p className={styles.quote}>{candidate.quote}</p>}+ {!duplicate && (+ <Flexbox horizontal align={'center'} gap={4}>+ <DropdownMenu+ items={[+ ...groups.map((group) => ({+ key: group.domain.id,+ label: group.domain.title,+ onClick: () => patch(index, { groupId: group.domain.id }),+ })),+ ...(canOpenGroup && candidate.newGroup+ ? [+ {+ key: 'new',+ label: t('rules.distill.newGroup', {+ title: candidate.newGroup.title,+ }),+ onClick: () => patch(index, { groupId: 'new' }),+ },+ ]+ : []),+ ]}+ >+ <span className={styles.chip}>+ <Icon+ icon={draft.groupId === 'new' ? FolderPlusIcon : FolderIcon}+ size={12}+ />+ {groupTitle(draft.groupId, candidate)}+ <Icon icon={ChevronDownIcon} size={12} />+ </span>+ </DropdownMenu>+ <span+ className={styles.chip}+ onClick={() =>+ patch(index, {+ enforcement: draft.enforcement === 'block' ? 'remind' : 'block',+ })+ }+ >+ <Icon+ icon={draft.enforcement === 'block' ? ShieldCheckIcon : BellIcon}+ size={12}+ />+ {t(+ draft.enforcement === 'block'+ ? 'rules.enforcement.block'+ : 'rules.enforcement.remind',+ )}+ </span>+ </Flexbox>+ )}+ </Flexbox>+ </div>+ );+ })+ )}+ </Flexbox>+ )}++ <Flexbox+ horizontal+ align={'center'}+ className={composeStyles.footer}+ gap={8}+ justify={'flex-end'}+ >+ {step === 'review' ? (+ <Button+ disabled={kept.length === 0}+ loading={saving}+ type={'primary'}+ onClick={() => void save()}+ >+ {t('rules.distill.save', { count: kept.length })}+ </Button>+ ) : (+ <Button+ disabled={!source || uploading}+ loading={step === 'reading'}+ type={'primary'}+ onClick={() => void read()}+ >+ {t('rules.distill.read')}+ </Button>+ )}+ </Flexbox>+ </Flexbox>+ );+};++export const createDistillModal = (props: DistillContentProps) =>+ createModal({+ content: <DistillContent {...props} />,+ footer: null,+ maskClosable: false,+ styles: { content: { overflow: 'hidden', padding: 0 } },+ title: null,+ width: 'min(88vw, 720px)',+ });diff --git a/src/features/MemoryRules/RulesOnboarding.tsx b/src/features/MemoryRules/RulesOnboarding.tsxindex cf4e8abb422..df5ddeeb7de 100644--- a/src/features/MemoryRules/RulesOnboarding.tsx+++ b/src/features/MemoryRules/RulesOnboarding.tsx@@ -3,7 +3,7 @@import { Icon } from '@lobehub/ui';import { Button } from '@lobehub/ui/base-ui';import { createStaticStyles, cssVar, cx } from 'antd-style';-import { BotIcon, ClipboardCheckIcon, PlusIcon, ScaleIcon } from 'lucide-react';+import { BotIcon, ClipboardCheckIcon, FileSearchIcon, PlusIcon, ScaleIcon } from 'lucide-react';import type { ReactNode } from 'react';import { useTranslation } from 'react-i18next';@@ -171,6 +171,8 @@ interface RulesOnboardingProps {backlogRounds?: number;/** Inside the page under the part switcher, rather than as the whole page. */inline?: boolean;+ /** Read rules out of a material the reviewer already has. */+ onDistill: () => void;onWrite: () => void;}@@ -179,7 +181,13 @@ interface RulesOnboardingProps {* the one thing that can be done right here (write a rule — a sentence or a pasted guideline),* then the other places rules come from, each with the single action that gets there.*/-const RulesOnboarding = ({ agents, backlogRounds, inline, onWrite }: RulesOnboardingProps) => {+const RulesOnboarding = ({+ agents,+ backlogRounds,+ inline,+ onDistill,+ onWrite,+}: RulesOnboardingProps) => {const { t } = useTranslation('memory');const navigate = useWorkspaceAwareNavigate();@@ -205,6 +213,12 @@ const RulesOnboarding = ({ agents, backlogRounds, inline, onWrite }: RulesOnboar<div className={styles.listTitle}>{t('rules.onboarding.listTitle')}</div><div className={styles.list}>+ <Row+ action={<Button onClick={onDistill}>{t('rules.onboarding.distill.action')}</Button>}+ description={t('rules.onboarding.distill.description')}+ icon={FileSearchIcon}+ title={t('rules.onboarding.distill.title')}+ /><Rowdescription={t('rules.onboarding.reject.description')}icon={ClipboardCheckIcon}diff --git a/src/features/MemoryRules/index.tsx b/src/features/MemoryRules/index.tsxindex f226811d2f0..0d7e7c65ae4 100644--- a/src/features/MemoryRules/index.tsx+++ b/src/features/MemoryRules/index.tsx@@ -3,7 +3,7 @@import { Block, Empty, Flexbox, Icon, SortableList } from '@lobehub/ui';import { Button, Text, toast } from '@lobehub/ui/base-ui';import { cx } from 'antd-style';-import { ArrowDownIcon, ArrowUpIcon, FlaskConicalIcon, PencilIcon, PlusIcon } from 'lucide-react';+import { ArrowDownIcon, ArrowUpIcon, FileSearchIcon, FlaskConicalIcon, PencilIcon, PlusIcon } from 'lucide-react';import { useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -18,6 +18,7 @@ import { labPreferSelectors } from '@/store/user/slices/preference/selectors/labimport { createComposeRuleModal } from './ComposeModal';import DetailPanel from './DetailPanel';+import { createDistillModal } from './DistillModal';import { createGroupModal } from './GroupModal';import GroupSection from './GroupSection';import { useRules } from './hooks';@@ -255,6 +256,18 @@ const MemoryRules = () => {setSelectedId(selectedId === id ? undefined : id);};+ // Distilling files into the part on screen, like writing: its groups, and a new group only in+ // the reviewer's own part (a new group always mounts on the reviewer).+ const distill = () =>+ createDistillModal({+ canOpenGroup: part.key === 'mine',+ groups: part.groups,+ onDone: (ids) => {+ if (ids[0]) setSelectedId(ids[0]);+ void refresh();+ },+ });+// Writing files into the part on screen: the header offers its groups, a group's `+` that group.const compose = (defaultGroupId?: string) =>createComposeRuleModal({@@ -377,9 +390,18 @@ const MemoryRules = () => {{/* One primary action. Writing a rule also opens the group when the reviewer hasnone, so a separate "new group" button would be a second way to start. */}{!mineOnboarding && (- <Button icon={<Icon icon={PlusIcon} />} type={'primary'} onClick={() => compose()}>- {t('rules.actions.write')}- </Button>+ <Flexbox horizontal gap={8}>+ <Button icon={<Icon icon={FileSearchIcon} />} onClick={distill}>+ {t('rules.actions.distill')}+ </Button>+ <Button+ icon={<Icon icon={PlusIcon} />}+ type={'primary'}+ onClick={() => compose()}+ >+ {t('rules.actions.write')}+ </Button>+ </Flexbox>)}</Flexbox>@@ -406,7 +428,11 @@ const MemoryRules = () => {isLoading={isLoading}loading={<Loading debugId={'MemoryRules'} />}empty={- <RulesOnboarding backlogRounds={data?.backlogRounds} onWrite={() => compose()} />+ <RulesOnboarding+ backlogRounds={data?.backlogRounds}+ onDistill={distill}+ onWrite={() => compose()}+ />}onRetry={() => void refresh()}>@@ -451,6 +477,7 @@ const MemoryRules = () => {inlineagents={onboardingAgents}backlogRounds={data?.backlogRounds}+ onDistill={distill}onWrite={() => compose()}/>) : (diff --git a/src/features/MemoryRules/labels.test.ts b/src/features/MemoryRules/labels.test.tsindex 2e062813e45..ea8a4c0637f 100644--- a/src/features/MemoryRules/labels.test.ts+++ b/src/features/MemoryRules/labels.test.ts@@ -69,12 +69,27 @@ describe('revisionAuthorKey', () => {});describe('ruleOrigin', () => {- const rule = (rejectionHitCount: number, conversationHitCount: number, authored = false) => ({+ const rule = (+ rejectionHitCount: number,+ conversationHitCount: number,+ authored = false,+ materialHitCount = 0,+ ) => ({authored,conversationHitCount,+ materialHitCount,rejectionHitCount,});+ it('says a rule was read from material until practice confirms it', () => {+ expect(ruleOrigin(rule(0, 0, false, 2))).toEqual({+ key: 'fromMaterial',+ params: { count: 2 },+ });+ // Once it is also rejected for, the rejection is what the reviewer cares about.+ expect(ruleOrigin(rule(1, 0, false, 2))).toEqual({ key: 'distilled', params: { hits: 1 } });+ });+it('does not say the reviewer rejected anything for a rule learned in conversation', () => {expect(ruleOrigin(rule(0, 35))).toEqual({ key: 'observed', params: { hits: 35 } });});diff --git a/src/features/MemoryRules/labels.ts b/src/features/MemoryRules/labels.tsindex fb0f14c66fe..6a6c30b91ce 100644--- a/src/features/MemoryRules/labels.ts+++ b/src/features/MemoryRules/labels.ts@@ -36,10 +36,16 @@ export const appendException = (existing: string | undefined, exception: string)* conversation must not claim the reviewer rejected anything.*/export const ruleOrigin = (- rule: Pick<RuleItem, 'authored' | 'conversationHitCount' | 'rejectionHitCount'>,+ rule: Pick<+ RuleItem,+ 'authored' | 'conversationHitCount' | 'materialHitCount' | 'rejectionHitCount'+ >,) => {const { conversationHitCount: conversations, rejectionHitCount: rejections } = rule;if (rule.authored) return { key: 'authored' } as const;+ // Read out of a material the reviewer brought, and not seen in practice since.+ if (rule.materialHitCount > 0 && rejections === 0 && conversations === 0)+ return { key: 'fromMaterial', params: { count: rule.materialHitCount } } as const;if (rejections > 0 && conversations > 0)return { key: 'distilledAndObserved', params: { conversations, rejections } } as const;if (rejections > 0) return { key: 'distilled', params: { hits: rejections } } as const;diff --git a/src/features/MemoryRules/useDistillSources.test.ts b/src/features/MemoryRules/useDistillSources.test.tsnew file mode 100644index 00000000000..5b72f8bd9f6--- /dev/null+++ b/src/features/MemoryRules/useDistillSources.test.ts@@ -0,0 +1,64 @@+import { act, renderHook, waitFor } from '@testing-library/react';+import { createElement, type ReactNode } from 'react';+import { SWRConfig } from 'swr';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { useRecentPages, useTopics } from './useDistillSources';++const { getRecentPages, getRecentTopics, searchTopics } = vi.hoisted(() => ({+ getRecentPages: vi.fn(),+ getRecentTopics: vi.fn(),+ searchTopics: vi.fn(),+}));+vi.mock('@/services/file', () => ({ fileService: { getRecentPages } }));+vi.mock('@/services/topic', () => ({ topicService: { getRecentTopics, searchTopics } }));+vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({+ useActiveWorkspaceId: () => undefined,+}));++// A fresh cache per test, and no automatic retry, so a failure is observed as it happens.+const wrapper = ({ children }: { children: ReactNode }) =>+ createElement(+ SWRConfig,+ { value: { provider: () => new Map(), shouldRetryOnError: false } },+ children,+ );++describe('useDistillSources', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('reports a failed document read as an error, not as no documents, and retries it', async () => {+ getRecentPages.mockRejectedValueOnce(new Error('network'));+ const { result } = renderHook(() => useRecentPages(true), { wrapper });++ await waitFor(() => expect(result.current.error).toBe(true));+ expect(result.current.items).toBeUndefined();++ getRecentPages.mockResolvedValueOnce([{ id: 'doc-1', name: 'Spec', updatedAt: '2026-10-01' }]);+ await act(async () => {+ result.current.retry();+ });++ await waitFor(() =>+ expect(result.current.items).toEqual([+ { id: 'doc-1', name: 'Spec', updatedAt: '2026-10-01' },+ ]),+ );+ expect(result.current.error).toBe(false);+ });++ it('reports a failed conversation read as an error, not as no conversations', async () => {+ getRecentTopics.mockRejectedValueOnce(new Error('network'));+ const { result } = renderHook(() => useTopics(true, ''), { wrapper });++ await waitFor(() => expect(result.current.error).toBe(true));+ expect(result.current.items).toBeUndefined();+ });++ it('does not read anything while its tab is closed', () => {+ renderHook(() => useRecentPages(false), { wrapper });+ expect(getRecentPages).not.toHaveBeenCalled();+ });+});diff --git a/src/features/MemoryRules/useDistillSources.ts b/src/features/MemoryRules/useDistillSources.tsnew file mode 100644index 00000000000..a634d4f33c7--- /dev/null+++ b/src/features/MemoryRules/useDistillSources.ts@@ -0,0 +1,40 @@+import { useDebounce } from 'ahooks';++import { useClientDataSWR } from '@/libs/swr';+import { fileService } from '@/services/file';+import { topicService } from '@/services/topic';++// A failed read stays distinct from an empty list, with a retry, so a network blip never reads+// as "you have no documents".+export const useRecentPages = (enabled: boolean) => {+ const { data, error, mutate } = useClientDataSWR(+ enabled ? ['memoryRules', 'distill', 'recentPages'] : null,+ async () => {+ const items = await fileService.getRecentPages(30);+ return items.map(({ id, name, updatedAt }) => ({ id, name, updatedAt }));+ },+ { revalidateOnFocus: false },+ );+ return { error: !!error && !data, items: data, retry: () => mutate() };+};++export const useTopics = (enabled: boolean, keywords: string) => {+ const query = useDebounce(keywords.trim(), { wait: 300 });+ const { data, error, mutate } = useClientDataSWR(+ enabled ? ['memoryRules', 'distill', 'topics', query] : null,+ async (): Promise<{ agent?: string; id: string; title: string }[]> => {+ if (query) {+ const items = await topicService.searchTopics(query);+ return items.map(({ id, title }) => ({ id, title: title ?? '' }));+ }+ const items = await topicService.getRecentTopics(30);+ return items.map(({ agent, id, title }) => ({+ agent: agent?.title ?? undefined,+ id,+ title: title ?? '',+ }));+ },+ { keepPreviousData: true, revalidateOnFocus: false },+ );+ return { error: !!error && !data, items: data, retry: () => mutate() };+};diff --git a/src/services/expertise.ts b/src/services/expertise.tsindex 7c8c04ad310..3c14ee7826b 100644--- a/src/services/expertise.ts+++ b/src/services/expertise.ts@@ -26,6 +26,12 @@ export type RuleRevision = Awaited<ReturnType<typeof lambdaClient.expertise.ruleRevisions.query>>[number];export type RuleDraft = Awaited<ReturnType<typeof lambdaClient.expertise.draftRule.mutate>>;+export type DistillResult = Awaited<ReturnType<typeof lambdaClient.expertise.distillRules.mutate>>;+export type DistillCandidate = DistillResult['candidates'][number];+export type DistillInput = Parameters<typeof lambdaClient.expertise.distillRules.mutate>[0];+export type CommitDistilledInput = Parameters<+ typeof lambdaClient.expertise.commitDistilledRules.mutate+>[0];export type RuleGroupDraft = Awaited<ReturnType<typeof lambdaClient.expertise.draftRuleGroup.mutate>>;@@ -52,6 +58,11 @@ class ExpertiseService {draftRuleGroup = async (brief: string) => lambdaClient.expertise.draftRuleGroup.mutate({ brief });+ distillRules = async (input: DistillInput) => lambdaClient.expertise.distillRules.mutate(input);++ commitDistilledRules = async (input: CommitDistilledInput) =>+ lambdaClient.expertise.commitDistilledRules.mutate(input);+createRule = async (input: CreateRuleInput) => lambdaClient.expertise.createRule.mutate(input);updateRule = async (lessonId: string, patch: UpdateRuleInput) =>