🤯 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
🐛 fix(memory): keep distilled rules honest about where they came from (#20170)
Arvin Xueb3cb4092e7b
diff --git a/apps/server/src/services/expertise/ingestion.test.ts b/apps/server/src/services/expertise/ingestion.test.tsindex 969425ec27d..001a9ee2b1d 100644--- a/apps/server/src/services/expertise/ingestion.test.ts+++ b/apps/server/src/services/expertise/ingestion.test.ts@@ -205,7 +205,7 @@ describe('ExpertiseIngestionService.ingestCompletion', () => {}),expect.objectContaining({tracing: expect.objectContaining({- promptVersion: 'v2',+ promptVersion: 'v3',scenario: 'expertise_topic_ingestion',}),}),@@ -443,6 +443,31 @@ describe('ExpertiseIngestionService.persistDomainRun', () => {expect(lesson?.code).toBe('P-08');});+ it('links a conversation hit to the message it was read from', async () => {+ const fake = createTx([]);+ await persistRun(fake, [observation({ sourceMessageId: 'msg_2' })]);++ expect(fake.inserted.get(expertiseHits)?.[0].sourceMessageId).toBe('msg_2');+ });++ it('marks a new standard the model could not lift above one delivery as a one-off', async () => {+ const fake = createTx([]);+ await persistRun(fake, [observation({ specificity: 'one-off' })]);++ expect(fake.inserted.get(expertiseLessons)?.[0].specificity).toBe('one-off');+ });++ it('lifts the one-off mark once another round attaches to the standard', async () => {+ const fake = createTx([+ { code: 'P-07', id: 'lesson_7', status: 'active', title: 'Separate the runtime plane' },+ ]);+ await persistRun(fake, [observation({ existingLessonCode: 'P-07' })]);++ // Recurring in a second round is exactly what a one-off does not do.+ const lessonUpdate = fake.updates.find((update) => 'hitCount' in update);+ expect(lessonUpdate).toHaveProperty('specificity');+ });+it('collapses observations that restate the same rule inside one run', async () => {const fake = createTx([]);await persistRun(fake, [diff --git a/apps/server/src/services/expertise/ingestion.ts b/apps/server/src/services/expertise/ingestion.tsindex 39de07f3f12..4a2fcba0358 100644--- a/apps/server/src/services/expertise/ingestion.ts+++ b/apps/server/src/services/expertise/ingestion.ts@@ -46,11 +46,21 @@ import type { ConsolidationResult } from './consolidation';import { ExpertiseConsolidationService } from './consolidation';import { resolveExpertiseModelConfig } from './modelConfig';import { isProviderAccountError } from './providerAccountError';+import {+ deliveryStandardsDomainCopy,+ findQuotedMessage,+ refineRejectionFields,+} from './rejectionObservation';const log = debug('lobe-server:expertise-ingestion');const MAX_CONTEXT_MESSAGES = 24;const MAX_CONTEXT_CHARS = 24_000;+/**+ * How far back an observation's excerpt is looked for. Wider than the context window because the+ * self-review path serializes its own context, which can reach older turns than the last 24.+ */+const MAX_QUOTE_LOOKUP_MESSAGES = 200;/*** Frames attached to one round's distillation. A round is a batch, unlike the single-check review* that caps at 3 — but every frame is a full base64 body, so the cap is what keeps a 20-rejection@@ -72,6 +82,8 @@ const AnalysisSchema = z.object({existingLessonCode: z.string().nullable(),layer: z.string().nullable(),outcome: z.enum(['pass', 'violation']),+ // Absent from answers to older prompt versions; reads as "no single message".+ quote: z.string().default(''),reasoning: z.string(),title: z.string(),}),@@ -102,7 +114,10 @@ const RejectionAnalysisSchema = z.object({reasonKind: z.enum(['mechanism', 'taste']),reasoning: z.string(),reasonSource: z.enum(['reviewer', 'inferred']),+ // Older models answer without these; absent reads as "no quote" and "a standard".+ reviewerWords: z.string().default(''),sourceRefs: z.array(z.string()),+ specificity: z.enum(['general', 'one-off']).default('general'),subject: z.string(),title: z.string(),}),@@ -195,6 +210,14 @@ interface PersistableObservation {* N rejections" a real count rather than a count of analysis passes.*/sourceCheckResultIds?: string[];+ /** The conversation message the observation was read from, when its excerpt was found. */+ sourceMessageId?: string;+ /**+ * `one-off` when the model could not lift the rejection above an instruction about that one+ * delivery. Only written on a new lesson; a later round attaching to it clears the mark,+ * because recurring is exactly what a one-off does not do.+ */+ specificity?: 'general' | 'one-off';/** What the standard is really about, once the concrete names are replaced by what they exemplify. */subject?: null | string;title: string;@@ -446,6 +469,13 @@ export class ExpertiseIngestionService {},);const analysis = AnalysisSchema.parse(raw);+ // Read once for every observation; the self-review path hands over its own serialized+ // context, so the topic's messages are looked up here rather than taken from it.+ const quoted = analysis.domains.some((result) =>+ result.observations.some((observation) => observation.quote.trim()),+ )+ ? await this.readTopicMessages(input.topicId, MAX_QUOTE_LOOKUP_MESSAGES)+ : [];let ingested = 0;for (const result of analysis.domains) {@@ -453,7 +483,10 @@ export class ExpertiseIngestionService {if (!domain || !result.matches) continue;await this.persistDomainRun({domain,- observations: result.observations,+ observations: result.observations.map((observation) => ({+ ...observation,+ sourceMessageId: findQuotedMessage(quoted, observation.quote),+ })),run: {actorId: input.agentId,actorType: 'agent',@@ -513,6 +546,15 @@ export class ExpertiseIngestionService {ref: `R${index + 1}`,}));const byRef = new Map(labelled.map((rejection) => [rejection.ref, rejection.id]));+ const saidByRef = new Map(+ labelled.map((rejection) => [+ rejection.ref,+ [+ rejection.detail?.comment ?? '',+ ...(rejection.detail?.annotations ?? []).map((annotation) => annotation.comment ?? ''),+ ].filter((text) => text.trim()),+ ]),+ );const { visuals, withheld } = await this.resolveRejectionFrames(labelled);const frameLabelByEvidence = new Map(visuals.map((visual, index) => [visual.evidenceId, `frame ${index + 1}`]),@@ -541,7 +583,7 @@ export class ExpertiseIngestionService {let bound = await listDomains();if (bound.length === 0) {- await this.createDeliveryStandardsDomain(acceptance.projectId);+ await this.createDeliveryStandardsDomain(acceptance.projectId, rendered);bound = await listDomains();if (bound.length === 0) return { ingested: 0, reason: 'no-domains' } as const;}@@ -595,6 +637,10 @@ export class ExpertiseIngestionService {domain,observations: result.observations.map((observation) => ({...observation,+ ...refineRejectionFields(+ observation,+ observation.sourceRefs.map((ref) => ({ said: saidByRef.get(ref) ?? [] })),+ ),existingLessonCode: observation.existingLessonCode.trim() || null,layer: observation.layer.trim() || null,// A rejection is a violation by construction — never let the model relabel it a pass.@@ -729,7 +775,10 @@ export class ExpertiseIngestionService {* Owned by the user (never by the project — a project mounts standards, it does not own them),* so the same domain can later be mounted by a sibling project without being copied.*/- private createDeliveryStandardsDomain = async (projectId: null | string) => {+ private createDeliveryStandardsDomain = async (+ projectId: null | string,+ rejectionText: string,+ ) => {const [project] = projectId? await this.db.select({ name: projects.name })@@ -737,19 +786,26 @@ export class ExpertiseIngestionService {.where(eq(projects.id, projectId)).limit(1): [];- const scope = project?.name ?? 'my work';return new ExpertiseModel(this.db, this.userId, this.workspaceId).createDomain({- brief: `Delivery standards distilled from rejected acceptance checks on ${scope}.`,+ ...deliveryStandardsDomainCopy(project?.name ?? null, rejectionText),carrier: projectId ? { id: projectId, type: 'project' } : { type: 'user' },- domainFilter: `Strip the screen names, component names and this task's name out of the requirement — does it still hold for any delivery on ${scope}? Only then is it mine.`,- outOfScope:- 'One-off facts about a single screen, and anything that stops being true once the task changes.',- title: `${scope} delivery standards`,});};private readTopicContext = async (topicId: string) => {+ const rows = await this.readTopicMessages(topicId, MAX_CONTEXT_MESSAGES);+ return {+ hadHumanInLoop: rows.some((row) => row.role === 'user'),+ serializedContext: rows+ .reverse()+ .map((row) => `[${row.role}] ${row.content ?? ''}`)+ .join('\n\n'),+ };+ };++ /** A topic's main-thread messages, newest first; empty when the topic is not the caller's. */+ private readTopicMessages = async (topicId: string, limit: number) => {const [topic] = await this.db.select({ id: topics.id }).from(topics)@@ -760,11 +816,11 @@ export class ExpertiseIngestionService {),).limit(1);- if (!topic) return { hadHumanInLoop: false, serializedContext: '' };+ if (!topic) return [];- const rows = await this.db.query.messages.findMany({- columns: { content: true, createdAt: true, role: true },- limit: MAX_CONTEXT_MESSAGES,+ return this.db.query.messages.findMany({+ columns: { content: true, createdAt: true, id: true, role: true },+ limit,orderBy: [desc(messages.createdAt)],where: and(this.workspaceId@@ -777,13 +833,6 @@ export class ExpertiseIngestionService {notShareVisitorMessage(),),});- return {- hadHumanInLoop: rows.some((row) => row.role === 'user'),- serializedContext: rows- .reverse()- .map((row) => `[${row.role}] ${row.content ?? ''}`)- .join('\n\n'),- };};private persistDomainRun = async (input: {@@ -879,6 +928,7 @@ export class ExpertiseIngestionService {outcome: observation.outcome,runId,sourceCheckResultId,+ sourceMessageId: observation.sourceMessageId,})),);return sources.length;@@ -908,6 +958,7 @@ export class ExpertiseIngestionService {// refuse a taste standard, and the body is written in the reviewer's own language.reasonKind: observation.reasonKind,reasonSource: observation.reasonSource,+ specificity: observation.specificity,sections: [{body: observation.subject?.trim()@@ -944,6 +995,10 @@ export class ExpertiseIngestionService {: expertiseLessons.hitRunCount,lastHitAt: new Date(),lastHitRunId: runId,+ // Hit again in another round: whatever it looked like, it was not a one-off.+ ...(firstHitThisRun && {+ specificity: sql`case when ${expertiseLessons.specificity} = 'one-off' then 'general' else ${expertiseLessons.specificity} end`,+ }),}).where(eq(expertiseLessons.id, matchedId));}diff --git a/apps/server/src/services/expertise/rejectionObservation.test.ts b/apps/server/src/services/expertise/rejectionObservation.test.tsnew file mode 100644index 00000000000..819c7ff1e9a--- /dev/null+++ b/apps/server/src/services/expertise/rejectionObservation.test.ts@@ -0,0 +1,99 @@+import { describe, expect, it } from 'vitest';++import {+ deliveryStandardsDomainCopy,+ findQuotedMessage,+ refineRejectionFields,+} from './rejectionObservation';++const fields = (overrides: Partial<Parameters<typeof refineRejectionFields>[0]> = {}) => ({+ limits: '',+ reasoning: '浅色线条与白底亮度差太小,看的人分不清圈的是哪块',+ reviewerWords: '',+ ...overrides,+});++describe('refineRejectionFields', () => {+ it('leads the reason with the reviewer’s own sentence when it is really in what they wrote', () => {+ const refined = refineRejectionFields(fields({ reviewerWords: '这个青色太浅了,我看不见' }), [+ { said: ['这个青色太浅了,我看不见 圈的地方'] },+ ]);++ expect(refined.reasonSource).toBe('reviewer');+ expect(refined.reasoning).toBe(+ '“这个青色太浅了,我看不见”\n\n浅色线条与白底亮度差太小,看的人分不清圈的是哪块',+ );+ });++ it('matches across the whitespace and quote marks a model changes when copying', () => {+ const refined = refineRejectionFields(fields({ reviewerWords: '「按钮 太小了」' }), [+ { said: ['按钮太小了'] },+ ]);++ expect(refined.reasonSource).toBe('reviewer');+ });++ it('treats a quote the reviewer never wrote as an inferred reason, whatever the model claims', () => {+ const refined = refineRejectionFields(fields({ reviewerWords: '颜色对比度不足影响可读性' }), [+ { said: ['这里多了一条线'] },+ ]);++ expect(refined.reasonSource).toBe('inferred');+ expect(refined.reasoning).toBe('浅色线条与白底亮度差太小,看的人分不清圈的是哪块');+ });++ it('only looks in the rejections the observation cites', () => {+ const refined = refineRejectionFields(fields({ reviewerWords: '我看不见' }), []);++ expect(refined.reasonSource).toBe('inferred');+ });++ it('drops the "no boundary given" sentence instead of storing it as a boundary', () => {+ expect(refineRejectionFields(fields({ limits: '边界未由评审者说明' }), []).limits).toBeNull();+ expect(refineRejectionFields(fields({ limits: '边界未由评审者说明。' }), []).limits).toBeNull();+ expect(refineRejectionFields(fields({ limits: ' ' }), []).limits).toBeNull();+ expect(refineRejectionFields(fields({ limits: '图表内部不算' }), []).limits).toBe(+ '图表内部不算',+ );+ });+});++describe('deliveryStandardsDomainCopy', () => {+ it('names the first group in Chinese when the reviewer rejected in Chinese', () => {+ expect(+ deliveryStandardsDomainCopy(null, '[R1] promised: 登录\n said: 按钮太小了'),+ ).toMatchObject({ title: '我的交付规矩' });+ expect(deliveryStandardsDomainCopy('官网', ' said: 对不齐')).toMatchObject({+ title: '官网 交付规矩',+ });+ });++ it('keeps English for a reviewer who wrote in English', () => {+ expect(deliveryStandardsDomainCopy(null, ' said: the button is too small')).toMatchObject({+ title: 'My delivery standards',+ });+ });+});++describe('findQuotedMessage', () => {+ const messages = [+ { content: '好的,我先把按钮改成默认尺寸', id: 'msg_3' },+ { content: '按钮太小了,点不中', id: 'msg_2' },+ { content: null, id: 'msg_1' },+ ];++ it('finds the message an excerpt was copied from, across whitespace and quote marks', () => {+ expect(findQuotedMessage(messages, '「按钮 太小了」')).toBe('msg_2');+ });++ it('prefers the newest message when the same words recur', () => {+ expect(+ findQuotedMessage([{ content: '按钮太小了', id: 'msg_9' }, ...messages], '按钮太小了'),+ ).toBe('msg_9');+ });++ it('links nothing when the excerpt is empty or was never said', () => {+ expect(findQuotedMessage(messages, '')).toBeUndefined();+ expect(findQuotedMessage(messages, '颜色对比度不足')).toBeUndefined();+ });+});diff --git a/apps/server/src/services/expertise/rejectionObservation.ts b/apps/server/src/services/expertise/rejectionObservation.tsnew file mode 100644index 00000000000..fa1e8c91c77--- /dev/null+++ b/apps/server/src/services/expertise/rejectionObservation.ts@@ -0,0 +1,91 @@+/**+ * The "no boundary was given" sentence earlier prompt versions were told to write into `limits`.+ * An empty field says the same thing, and a sentence there reads as a boundary to everything+ * downstream, so it is dropped on the way in. Kept as a set for the other languages a model+ * sometimes answers the instruction in.+ */+const UNSTATED_LIMITS = new Set(['边界未由评审者说明']);++/** Whitespace and quote marks differ freely between what was written and what a model copies. */+const comparable = (text: string) => text.replaceAll(/[\s"'“”‘’「」『』]/g, '').toLowerCase();++export interface RejectionReason {+ /** What the reviewer typed for one rejection: their comment and every note on a circled region. */+ said: string[];+}++export interface RefinedRejectionFields {+ limits: string | null;+ reasoning: string;+ reasonSource: 'inferred' | 'reviewer';+}++/**+ * Settles the fields of a rejection observation the model cannot be trusted to self-report.+ *+ * `reasonSource` is decided by whether the claimed quote is really in what the reviewer wrote on+ * the rejections the observation cites — not by the model's own label, which over-claims. When it+ * is, the reason leads with those words and the model's mechanism follows, so the reader sees+ * their own sentence first.+ */+export const refineRejectionFields = (+ observation: { limits: string; reasoning: string; reviewerWords: string },+ cited: RejectionReason[],+): RefinedRejectionFields => {+ const limits = observation.limits.trim();+ const words = observation.reviewerWords.trim();+ const reasoning = observation.reasoning.trim();++ const quoted =+ comparable(words).length > 0 &&+ cited.some((rejection) =>+ rejection.said.some((text) => comparable(text).includes(comparable(words))),+ );++ return {+ limits: limits && !UNSTATED_LIMITS.has(limits.replace(/[。.]$/, '')) ? limits : null,+ reasoning: quoted ? [`“${words}”`, reasoning].filter(Boolean).join('\n\n') : reasoning,+ reasonSource: quoted ? 'reviewer' : 'inferred',+ };+};++const CJK = /\p{Script=Han}/u;++/**+ * Name, gate and exclusions of the group a reviewer's first rejections open, in the language they+ * rejected in. The group is created before any model sees the round, so its wording is fixed+ * here; an English name on a page where every rule is Chinese reads as someone else's group.+ */+export const deliveryStandardsDomainCopy = (projectName: string | null, rejectionText: string) => {+ if (CJK.test(rejectionText)) {+ const scope = projectName ?? '我的工作';+ return {+ brief: `从「${scope}」被打回的验收检查项里沉淀出的交付规矩。`,+ domainFilter: `去掉页面名、组件名和这次任务的名字之后,这条要求对「${scope}」的任何一次交付是否仍然成立?成立才收进来。`,+ outOfScope: '只关于某一个页面的一次性事实,以及任务一变就不再成立的内容。',+ title: projectName ? `${projectName} 交付规矩` : '我的交付规矩',+ };+ }+ const scope = projectName ?? 'my work';+ return {+ brief: `Delivery standards distilled from rejected acceptance checks on ${scope}.`,+ domainFilter: `Strip the screen names, component names and this task's name out of the requirement — does it still hold for any delivery on ${scope}? Only then is it mine.`,+ outOfScope:+ 'One-off facts about a single screen, and anything that stops being true once the task changes.',+ title: projectName ? `${projectName} delivery standards` : 'My delivery standards',+ };+};++/**+ * The message a verbatim excerpt was copied from, newest first: when the same words recur, the+ * turn under review is the latest one. Undefined when the excerpt is empty or appears nowhere —+ * a hit then keeps only its topic rather than pointing at a message that did not say it.+ */+export const findQuotedMessage = (+ messages: { content: string | null; id: string }[],+ quote: string,+) => {+ const needle = comparable(quote);+ if (!needle) return;+ return messages.find((message) => comparable(message.content ?? '').includes(needle))?.id;+};diff --git a/locales/en-US/memory.json b/locales/en-US/memory.jsonindex 40e8109c579..3bfe54cfc9e 100644--- a/locales/en-US/memory.json+++ b/locales/en-US/memory.json@@ -190,14 +190,18 @@"rules.method.not-compilable": "By judgement","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.generalizedFrom": "Merged from \"{{titles}}\"","rules.origin.lastHit": ", last {{time}}",- "rules.origin.oneOff": "Looks like a one-off; never being checked is normal",+ "rules.origin.learned": "Learned from your work",+ "rules.origin.observed": "Learned from conversations, where it came up {{hits}} times",+ "rules.origin.oneOff": "Looks like a request about that one delivery; it becomes a standing rule once another delivery is sent back for it","rules.origin.overSpecific": "Looks tied to one page; may belong in a broader rule","rules.reason.inferred": "inferred, you never said it","rules.reason.mechanism": "Has a reason","rules.reason.reviewer": "in your words","rules.reason.taste": "Judgement call",+ "rules.reason.unset": "Not decided yet","rules.revisions.bySystem": "by the system","rules.revisions.byTeammate": "by a teammate","rules.revisions.byYou": "by you",@@ -219,15 +223,19 @@"rules.sources.acceptance": "Acceptance","rules.sources.agreed": "you confirmed it learned this right","rules.sources.authoredEmpty": "Written by you; no rejections on record yet.",+ "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.open": "Open",+ "rules.sources.openMessage": "Go to message",+ "rules.sources.openTopic": "Open conversation","rules.sources.rejected": "you said it learned this wrong","rules.sources.retry": "Try again","rules.sources.round": "round {{index}}","rules.sources.title": "Where it came from","rules.subtitle": "{{count}} in use · the agent checks every delivery against them · what you say when sending a round back lands here","rules.tag.authored": "yours",+ "rules.tag.oneOff": "one-off","rules.title": "My rules","tab.activities": "Activities","tab.contexts": "Contexts",diff --git a/locales/zh-CN/memory.json b/locales/zh-CN/memory.jsonindex 8c0342941c0..f4485f50ea1 100644--- a/locales/zh-CN/memory.json+++ b/locales/zh-CN/memory.json@@ -190,14 +190,18 @@"rules.method.not-compilable": "靠判断","rules.origin.authored": "你自己写的","rules.origin.distilled": "你为这事打回过 {{hits}} 次",+ "rules.origin.distilledAndObserved": "你为这事打回过 {{rejections}} 次,对话里另出现过 {{conversations}} 次","rules.origin.generalizedFrom": "由「{{titles}}」合并而来","rules.origin.lastHit": ",最近一次 {{time}}",- "rules.origin.oneOff": "看起来是一次性的情况,没检查过很正常",+ "rules.origin.learned": "从你的工作里学到的",+ "rules.origin.observed": "从对话里学到的,出现过 {{hits}} 次",+ "rules.origin.oneOff": "看起来是针对那一次交付的具体意见,再有一次交付因它被打回,才算通用规矩","rules.origin.overSpecific": "看起来只对某个页面成立,可能该并进更通用的那条","rules.reason.inferred": "推断出来的,你没说过","rules.reason.mechanism": "有依据","rules.reason.reviewer": "你说过的","rules.reason.taste": "凭感觉",+ "rules.reason.unset": "还没判定","rules.revisions.bySystem": "系统改的","rules.revisions.byTeammate": "队友改的","rules.revisions.byYou": "你改的",@@ -219,15 +223,19 @@"rules.sources.acceptance": "验收","rules.sources.agreed": "你确认过这条学对了","rules.sources.authoredEmpty": "你亲手写的,还没有打回记录。",+ "rules.sources.conversation": "对话","rules.sources.empty": "这条规矩背后的打回已经找不回来了。","rules.sources.loadFailed": "来源没加载出来。","rules.sources.open": "打开",+ "rules.sources.openMessage": "定位到消息",+ "rules.sources.openTopic": "打开对话","rules.sources.rejected": "你说这条学错了","rules.sources.retry": "重试","rules.sources.round": "第 {{index}} 轮","rules.sources.title": "它从哪来","rules.subtitle": "{{count}} 条在用 · 交付前 Agent 会逐条对照 · 打回验收时说的话会记到这里","rules.tag.authored": "你写的",+ "rules.tag.oneOff": "一次性","rules.title": "我的规矩","tab.activities": "活动","tab.contexts": "情境",diff --git a/packages/database/src/models/__tests__/expertise.test.ts b/packages/database/src/models/__tests__/expertise.test.tsindex d574644dfab..e617851ad10 100644--- a/packages/database/src/models/__tests__/expertise.test.ts+++ b/packages/database/src/models/__tests__/expertise.test.ts@@ -1,6 +1,6 @@// @vitest-environment nodeimport { eq } from 'drizzle-orm';-import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { getTestDB } from '../../core/getTestDB';import { ExpertiseRuleRepository } from '../../repositories/expertiseRules';@@ -12,6 +12,7 @@ import {expertiseInsights,expertiseLessons,expertiseRuns,+ messages,projects,topics,users,@@ -38,6 +39,65 @@ describe('ExpertiseModel', () => {await serverDB.delete(users);});+ it('points a conversation source at its topic, agent and message', async () => {+ await serverDB.insert(agents).values({ id: 'expertise-source-agent', userId });+ await serverDB.insert(topics).values({+ agentId: 'expertise-source-agent',+ id: 'expertise-source-topic',+ title: '排查生产环境连接池超时',+ userId,+ });+ await serverDB.insert(messages).values({+ content: '先看连接池指标,再动超时配置',+ id: 'expertise-source-message',+ role: 'user',+ topicId: 'expertise-source-topic',+ userId,+ });+ await serverDB.insert(expertiseDomains).values({+ domainFilter: '生产故障排查',+ id: 'expertise-test-domain',+ slug: 'expertise-test-domain',+ title: '生产故障排查',+ userId,+ });+ await serverDB.insert(expertiseRuns).values({+ actorId: 'agent-1',+ actorType: 'agent',+ domainId: 'expertise-test-domain',+ id: runId,+ reflectionKey: 'topic:expertise-source-topic:operation:op-1',+ runIndex: 1,+ subjectId: 'expertise-source-topic',+ subjectType: 'topic',+ userId,+ });+ await serverDB.insert(expertiseLessons).values({+ code: 'P-01',+ domainId: 'expertise-test-domain',+ id: lessonId,+ polarity: 'rule',+ sections: [{ body: '先看连接池指标', key: 'rule' }],+ title: '先看连接池指标',+ });+ await serverDB.insert(expertiseHits).values({+ domainId: 'expertise-test-domain',+ id: hitId,+ lessonId,+ outcome: 'violation',+ runId,+ sourceMessageId: 'expertise-source-message',+ });++ const [source] = await new ExpertiseModel(serverDB, userId).listLessonSources(lessonId);+ expect(source).toMatchObject({+ fromAcceptance: false,+ messageId: 'expertise-source-message',+ topicAgentId: 'expertise-source-agent',+ topicId: 'expertise-source-topic',+ });+ });+it('returns the source topic title for a lesson hit', async () => {await serverDB.insert(topics).values({id: 'expertise-source-topic',@@ -1002,6 +1062,76 @@ describe('ExpertiseModel', () => {expect(groups[0].domain.domainFilter).toBe('交付标准');});+ it('tells rejections apart from conversation sightings, through a move', async () => {+ const { first } = await seedRuleGroup();+ const topicRunId = 'e3f9b0c6-6d0e-4f2e-9b1a-2c4d5e6f7a02';+ await serverDB.insert(expertiseRuns).values([+ {+ actorId: userId,+ actorType: 'user',+ domainId: 'rules-domain',+ id: runId,+ reflectionKey: 'acceptance:acc-1:run:run-1',+ runIndex: 1,+ subjectId: 'x',+ subjectType: 'standalone',+ userId,+ },+ {+ actorId: 'agent-1',+ actorType: 'agent',+ domainId: 'rules-domain',+ id: topicRunId,+ reflectionKey: 'topic:topic-1:operation:op-1',+ runIndex: 2,+ subjectId: 'topic-1',+ subjectType: 'topic',+ userId,+ },+ ]);+ await serverDB.insert(expertiseHits).values(+ [runId, topicRunId, topicRunId].map((run) => ({+ domainId: 'rules-domain',+ example: '证据',+ lessonId: first,+ outcome: 'violation' as const,+ runId: run,+ })),+ );+ const model = new ExpertiseModel(serverDB, userId);++ const moved = await model.moveRule(first, 'rules-domain-2');++ // The hits stayed on the original; the copy reads them through its lineage.+ const groups = await model.listRules();+ expect(groups[1].rules.find(({ id }) => id === moved!.id)).toMatchObject({+ conversationHitCount: 2,+ rejectionHitCount: 1,+ });+ // Each source is labelled by the run it came from, not by whether its check still exists.+ const sources = await model.listLessonSources(moved!.id);+ expect(sources.filter(({ fromAcceptance }) => fromAcceptance)).toHaveLength(1);+ expect(sources.filter(({ fromAcceptance }) => !fromAcceptance)).toHaveLength(2);+ });++ it('refuses to move a rule a merge folded in after it was read', async () => {+ const { first, second } = await seedRuleGroup();+ await seedHitOn(second);+ const model = new ExpertiseModel(serverDB, userId);+ const stale = await model.findLesson(second);+ await new ExpertiseRuleRepository(serverDB, userId).mergeRules(second, first);+ // The move read the rule before the merge committed.+ vi.spyOn(model, 'findLesson').mockResolvedValueOnce(stale);++ expect(await model.moveRule(second, 'rules-domain-2')).toBeNull();+ expect(await model.findLesson(second)).toMatchObject({+ rejectedReason: `merged-into:${first}`,+ status: 'retired',+ });+ const groups = await model.listRules();+ expect(groups[1].rules).toHaveLength(0);+ });+it('keeps the edit history of a rule re-filed with its evidence', async () => {const { first } = await seedRuleGroup();await seedHitOn(first);diff --git a/packages/database/src/models/expertise.ts b/packages/database/src/models/expertise.tsindex fc3ea6f86af..225606da57e 100644--- a/packages/database/src/models/expertise.ts+++ b/packages/database/src/models/expertise.ts@@ -279,6 +279,8 @@ export class ExpertiseModel {.orderBy(asc(expertiseBindings.sortOrder)),]);+ const bySource = await this.countHitsBySource(lessons.map((lesson) => lesson.id));+return bound.map(({ domain }) => ({domain: {domainFilter: domain.domainFilter,@@ -293,6 +295,7 @@ export class ExpertiseModel {// reader uses for `taughtByUser`..map(({ originRunId, ...lesson }) => ({...lesson,+ ...(bySource.get(lesson.id) ?? { conversationHitCount: 0, rejectionHitCount: 0 }),authored: lesson.createdByUserId != null && originRunId == null,})),scopes: bindings@@ -327,42 +330,63 @@ export class ExpertiseModel {listLessonSources = async (lessonId: string, limit = 20) => {const lineage = await this.resolveLineage(lessonId);if (lineage.length === 0) return [];- return this.db- .select({- acceptanceId: verifyRuns.acceptanceId,- checkTitle: verifyCheckResults.checkItemTitle,- createdAt: expertiseHits.createdAt,- example: expertiseHits.example,- id: expertiseHits.id,- reviewerComment: sql<string | null>`${verifyCheckResults.userDecisionDetail} ->> 'comment'`,- roundIndex: verifyRuns.roundIndex,- severity: expertiseHits.severity,- userDecision: expertiseHits.userDecision,- where: expertiseHits.where,- })- .from(expertiseHits)- .innerJoin(expertiseDomains, eq(expertiseDomains.id, expertiseHits.domainId))- .innerJoin(expertiseRuns, eq(expertiseRuns.id, expertiseHits.runId))- .leftJoin(verifyCheckResults, eq(verifyCheckResults.id, expertiseHits.sourceCheckResultId))- .leftJoin(verifyRuns, eq(verifyRuns.id, verifyCheckResults.verifyRunId))- .where(- and(- inArray(expertiseHits.lessonId, lineage),- this.scopeWhere(),- // Access to a shared group is not access to the rounds behind it: a hit distilled from- // a teammate's private round would otherwise show that round's check, the reviewer's- // words and a link to it. Same predicate the consolidation reader applies.- or(- eq(verifyCheckResults.userId, this.userId),- eq(verifyRuns.visibility, 'public'),- // No linked round (never mapped, or the round was deleted): nothing says the viewer- // may see where it came from, so only their own runs' evidence is shown.- and(isNull(verifyCheckResults.id), eq(expertiseRuns.userId, this.userId)),+ return (+ this.db+ .select({+ acceptanceId: verifyRuns.acceptanceId,+ checkTitle: verifyCheckResults.checkItemTitle,+ createdAt: expertiseHits.createdAt,+ example: expertiseHits.example,+ // 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:%'`,+ 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.+ messageId: expertiseHits.sourceMessageId,+ reviewerComment: sql<+ string | null+ >`${verifyCheckResults.userDecisionDetail} ->> 'comment'`,+ roundIndex: verifyRuns.roundIndex,+ severity: expertiseHits.severity,+ topicAgentId: topics.agentId,+ topicId: topics.id,+ userDecision: expertiseHits.userDecision,+ where: expertiseHits.where,+ })+ .from(expertiseHits)+ .innerJoin(expertiseDomains, eq(expertiseDomains.id, expertiseHits.domainId))+ .innerJoin(expertiseRuns, eq(expertiseRuns.id, expertiseHits.runId))+ // Only a topic the viewer can open: a shared group does not grant a teammate's topic.+ .leftJoin(+ topics,+ and(+ eq(expertiseRuns.subjectType, 'topic'),+ eq(topics.id, expertiseRuns.subjectId),+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, topics),),- ),- )- .orderBy(desc(expertiseHits.createdAt))- .limit(limit);+ )+ .leftJoin(verifyCheckResults, eq(verifyCheckResults.id, expertiseHits.sourceCheckResultId))+ .leftJoin(verifyRuns, eq(verifyRuns.id, verifyCheckResults.verifyRunId))+ .where(+ and(+ inArray(expertiseHits.lessonId, lineage),+ this.scopeWhere(),+ // Access to a shared group is not access to the rounds behind it: a hit distilled from+ // a teammate's private round would otherwise show that round's check, the reviewer's+ // words and a link to it. Same predicate the consolidation reader applies.+ or(+ eq(verifyCheckResults.userId, this.userId),+ eq(verifyRuns.visibility, 'public'),+ // No linked round (never mapped, or the round was deleted): nothing says the viewer+ // may see where it came from, so only their own runs' evidence is shown.+ and(isNull(verifyCheckResults.id), eq(expertiseRuns.userId, this.userId)),+ ),+ ),+ )+ .orderBy(desc(expertiseHits.createdAt))+ .limit(limit)+ );};/**@@ -371,33 +395,90 @@ export class ExpertiseModel {* many generations as there are. One level is not enough — merging a rule that was itself a* merge would otherwise keep the counts and lose the evidence.*/- private resolveLineage = async (lessonId: string): Promise<string[]> => {- const readLinks = (ids: string[]) =>- this.db+ private resolveLineage = async (lessonId: string): Promise<string[]> =>+ (await this.resolveLineages([lessonId])).get(lessonId) ?? [];++ /**+ * {@link resolveLineage} for many rules at once: one read per generation instead of one walk+ * per rule, so a whole page of rules costs a handful of queries. A rule outside the caller's+ * scope maps to an empty lineage.+ */+ private resolveLineages = async (lessonIds: string[]) => {+ const parents = new Map<string, string[]>();+ let frontier = [...new Set(lessonIds)];+ // Bounded so a malformed cycle can never spin; real lineages are a handful of steps deep.+ for (let depth = 0; depth <= 16 && frontier.length > 0; depth += 1) {+ const rows = await this.db.select({generalizedFromIds: expertiseLessons.generalizedFromIds,+ id: expertiseLessons.id,salvagedFromId: expertiseLessons.salvagedFromId,}).from(expertiseLessons).innerJoin(expertiseDomains, eq(expertiseDomains.id, expertiseLessons.domainId))- .where(and(inArray(expertiseLessons.id, ids), this.scopeWhere()));-- let frontier = await readLinks([lessonId]);- if (frontier.length === 0) return [];- const seen = new Set<string>([lessonId]);- // Bounded so a malformed cycle can never spin; real lineages are a handful of steps deep.- for (let depth = 0; depth < 16 && frontier.length > 0; depth += 1) {- const next = frontier- .flatMap((lesson) => [- ...(lesson.generalizedFromIds ?? []),- ...(lesson.salvagedFromId ? [lesson.salvagedFromId] : []),- ])- .filter((id) => !seen.has(id));- if (next.length === 0) break;- for (const id of next) seen.add(id);- frontier = await readLinks(next);+ .where(and(inArray(expertiseLessons.id, frontier), this.scopeWhere()));+ for (const row of rows) {+ parents.set(row.id, [+ ...(row.generalizedFromIds ?? []),+ ...(row.salvagedFromId ? [row.salvagedFromId] : []),+ ]);+ }+ frontier = [...new Set(rows.flatMap((row) => parents.get(row.id) ?? []))].filter(+ (id) => !parents.has(id),+ );}- return [...seen];++ return new Map(+ lessonIds.map((root) => {+ if (!parents.has(root)) return [root, []];+ const seen = new Set<string>([root]);+ const stack = [root];+ while (stack.length > 0) {+ for (const parent of parents.get(stack.pop()!) ?? []) {+ if (seen.has(parent)) continue;+ seen.add(parent);+ stack.push(parent);+ }+ }+ return [root, [...seen]];+ }),+ );+ };++ /**+ * How many times each rule's lineage was hit by a rejected acceptance versus observed in a+ * conversation. `hitCount` adds both, and the two mean different things to the reviewer: only+ * the first is "you rejected a delivery for this".+ */+ private countHitsBySource = async (lessonIds: string[]) => {+ const lineages = await this.resolveLineages(lessonIds);+ const all = [...new Set([...lineages.values()].flat())];+ const rows =+ all.length === 0+ ? []+ : await this.db+ .select({+ conversations: sql<number>`count(*) filter (where coalesce(${expertiseRuns.reflectionKey}, '') not like 'acceptance:%')::int`,+ lessonId: expertiseHits.lessonId,+ rejections: sql<number>`count(*) filter (where ${expertiseRuns.reflectionKey} like 'acceptance:%')::int`,+ })+ .from(expertiseHits)+ .innerJoin(expertiseRuns, eq(expertiseRuns.id, expertiseHits.runId))+ .where(inArray(expertiseHits.lessonId, all))+ .groupBy(expertiseHits.lessonId);+ const byLesson = new Map(rows.map((row) => [row.lessonId, row]));++ return new Map(+ lessonIds.map((id) => {+ const lineage = lineages.get(id) ?? [];+ const sum = (key: 'conversations' | 'rejections') =>+ lineage.reduce((total, member) => total + (byLesson.get(member)?.[key] ?? 0), 0);+ return [+ id,+ { conversationHitCount: sum('conversations'), rejectionHitCount: sum('rejections') },+ ];+ }),+ );};/**@@ -907,11 +988,22 @@ export class ExpertiseModel {return { id: lessonId };};- /** The next free `P-nn` code inside one domain; codes are unique per domain, not globally. */+ /**+ * The next free `P-nn` code inside one domain; codes are unique per domain, not globally.+ *+ * Takes the domain row lock first — the same lock distillation holds while it hands out codes —+ * so two writers in one group queue up instead of computing the same number and having the+ * unique index reject one of them. The lock lasts until the caller's transaction commits.+ */private nextLessonCode = async (tx: Pick<LobeChatDatabase, 'select'>,domainId: string,): Promise<string> => {+ await tx+ .select({ id: expertiseDomains.id })+ .from(expertiseDomains)+ .where(eq(expertiseDomains.id, domainId))+ .for('update');const codes = await tx.select({ code: expertiseLessons.code }).from(expertiseLessons)@@ -1070,6 +1162,16 @@ export class ExpertiseModel {if (lesson.domainId === domainId) return { domainId, id: lessonId };return this.db.transaction(async (tx) => {+ // Re-read under a row lock and copy from that: a merge committed since the read above has+ // already folded this rule into another one, and copying it now would leave the same+ // evidence live twice.+ const [current] = await tx+ .select()+ .from(expertiseLessons)+ .where(eq(expertiseLessons.id, lessonId))+ .for('update');+ if (current?.status !== 'active' || current.domainId !== lesson.domainId) return null;+const code = await this.nextLessonCode(tx, domainId);const [last] = await tx.select({ sortOrder: sql<number>`max(${expertiseLessons.sortOrder})` })@@ -1095,7 +1197,7 @@ export class ExpertiseModel {updatedAt: _updatedAt,accessedAt: _accessedAt,...carried- } = lesson;+ } = current;const [copy] = await tx.insert(expertiseLessons).values({ ...carried, code, domainId, salvagedFromId: lessonId, sortOrder })diff --git a/packages/locales/src/default/memory.ts b/packages/locales/src/default/memory.tsindex 6dde9739022..d780e018f4c 100644--- a/packages/locales/src/default/memory.ts+++ b/packages/locales/src/default/memory.ts@@ -212,14 +212,20 @@ export default {'rules.method.not-compilable': 'By judgement','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.generalizedFrom': 'Merged from "{{titles}}"','rules.origin.lastHit': ', last {{time}}',- 'rules.origin.oneOff': 'Looks like a one-off; never being checked is normal',+ 'rules.origin.learned': 'Learned from your work',+ 'rules.origin.observed': 'Learned from conversations, where it came up {{hits}} times',+ 'rules.origin.oneOff':+ 'Looks like a request about that one delivery; it becomes a standing rule once another delivery is sent back for it','rules.origin.overSpecific': 'Looks tied to one page; may belong in a broader rule','rules.reason.inferred': 'inferred, you never said it','rules.reason.mechanism': 'Has a reason','rules.reason.reviewer': 'in your words','rules.reason.taste': 'Judgement call',+ 'rules.reason.unset': 'Not decided yet','rules.revisions.bySystem': 'by the system','rules.revisions.byTeammate': 'by a teammate','rules.revisions.byYou': 'by you',@@ -241,9 +247,12 @@ export default {'rules.sources.acceptance': 'Acceptance','rules.sources.agreed': 'you confirmed it learned this right','rules.sources.authoredEmpty': 'Written by you; no rejections on record yet.',+ '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.open': 'Open',+ 'rules.sources.openMessage': 'Go to message',+ 'rules.sources.openTopic': 'Open conversation','rules.sources.rejected': 'you said it learned this wrong','rules.sources.retry': 'Try again','rules.sources.round': 'round {{index}}',@@ -251,6 +260,7 @@ export default {'rules.subtitle':'{{count}} in use · the agent checks every delivery against them · what you say when sending a round back lands here','rules.tag.authored': 'yours',+ 'rules.tag.oneOff': 'one-off','rules.title': 'My rules','tab.activities': 'Activities','tab.contexts': 'Contexts',diff --git a/packages/prompts/src/chains/expertise.test.ts b/packages/prompts/src/chains/expertise.test.tsindex e84ca07f459..f8e049f763a 100644--- a/packages/prompts/src/chains/expertise.test.ts+++ b/packages/prompts/src/chains/expertise.test.ts@@ -49,6 +49,7 @@ describe('chainExpertiseTopicIngestion', () => {expect(Object.keys(observation.properties)).toContain('existingLessonCode');expect(Object.keys(observation.properties)).not.toContain('existingCode');expect(observation.required).toContain('existingLessonCode');+ expect(observation.required).toContain('quote');});it('keeps filtering policy, input serialization, schema, and version together', () => {@@ -57,7 +58,7 @@ describe('chainExpertiseTopicIngestion', () => {domains: [{ domainFilter: '比喻写作', id: 'domain-1' }],});- expect(EXPERTISE_TOPIC_INGESTION_PROMPT_VERSION).toBe('v2');+ expect(EXPERTISE_TOPIC_INGESTION_PROMPT_VERSION).toBe('v3');expect(EXPERTISE_TOPIC_INGESTION_JSON_SCHEMA.name).toBe('expertise_topic_ingestion');expect(result.messages[0].content).toContain('domainFilter and outOfScope');expect(result.messages[0].content).toContain('matches=false');diff --git a/packages/prompts/src/chains/expertise.ts b/packages/prompts/src/chains/expertise.tsindex 97651f82437..7fffa3112e5 100644--- a/packages/prompts/src/chains/expertise.ts+++ b/packages/prompts/src/chains/expertise.ts@@ -230,7 +230,7 @@ export const chainExpertiseRuleGroupDraft = ({],});-export const EXPERTISE_TOPIC_INGESTION_PROMPT_VERSION = 'v2';+export const EXPERTISE_TOPIC_INGESTION_PROMPT_VERSION = 'v3';export const EXPERTISE_TOPIC_INGESTION_JSON_SCHEMA = {name: 'expertise_topic_ingestion',@@ -251,6 +251,10 @@ export const EXPERTISE_TOPIC_INGESTION_JSON_SCHEMA = {example: { type: 'string' },layer: { type: ['string', 'null'] },outcome: { enum: ['pass', 'violation'], type: 'string' },+ // A verbatim excerpt of the one message the observation rests on. The service+ // looks it up in the topic to link the hit to that message, so the reader can+ // jump from a rule to the turn that taught it; "" when no single message does.+ quote: { type: 'string' },reasoning: { type: 'string' },title: { type: 'string' },},@@ -259,6 +263,7 @@ export const EXPERTISE_TOPIC_INGESTION_JSON_SCHEMA = {'existingLessonCode','layer','outcome',+ 'quote','reasoning','title',],@@ -290,6 +295,8 @@ For a match, turn concrete evidence into observations. Attaching to an existing- Only when no listed lesson carries the judgment, set existingLessonCode to null and propose one reusable lesson. Before doing so, state to yourself what it adds that every listed lesson misses; if you cannot, attach instead. Rewording a listed lesson is not a new lesson.- Do not turn implementation trivia or a one-off fact into a lesson.+For each observation, put in \`quote\` one short excerpt (a sentence or less) copied character for character from the single message the observation rests on — usually the user's correction or the reply that showed the judgment. Do not paraphrase, translate or join text from two messages; answer "" when no single message carries it.+Use only declared layer keys. Keep evidence short and grounded in the supplied conversation, and write human-facing text in the language of the conversation.`;export const chainExpertiseTopicIngestion = (input: {@@ -305,7 +312,7 @@ export const chainExpertiseTopicIngestion = (input: {],});-export const EXPERTISE_REJECTION_INGESTION_PROMPT_VERSION = 'v3';+export const EXPERTISE_REJECTION_INGESTION_PROMPT_VERSION = 'v4';export const EXPERTISE_REJECTION_INGESTION_JSON_SCHEMA = {name: 'expertise_rejection_ingestion',@@ -339,7 +346,14 @@ export const EXPERTISE_REJECTION_INGESTION_JSON_SCHEMA = {// makes a standard transferable — but an explanation it invented must never read// as something the reviewer stated.reasonSource: { enum: ['reviewer', 'inferred'], type: 'string' },+ // The reviewer's own sentence stating the cause, copied verbatim, or "". The+ // service checks it against what they actually wrote, so a claimed quote that is+ // not in the rejection cannot make an inferred reason read as theirs.+ reviewerWords: { type: 'string' },sourceRefs: { items: { type: 'string' }, minItems: 1, type: 'array' },+ // Whether this is a standard at all or an instruction about one delivery. Only+ // decided for a new lesson; attaching to a listed one is itself proof it recurs.+ specificity: { enum: ['general', 'one-off'], type: 'string' },// Naming the abstracted subject is what forces the climb: a model that cannot// say what the concrete thing is an example of has not generalized at all.subject: { type: 'string' },@@ -353,7 +367,9 @@ export const EXPERTISE_REJECTION_INGESTION_JSON_SCHEMA = {'reasonKind','reasonSource','reasoning',+ 'reviewerWords','sourceRefs',+ 'specificity','subject','title',],@@ -407,11 +423,15 @@ For each observation return:For "taste", do not dress the verdict up. State the preference plainly and in a form the next delivery can act on: "the owner does not accept dividers that were not asked for; regions are separated by spacing and container edges alone" is a complete and honest reason. A fabricated mechanism is worse than an admitted preference, because it reads as objective and gets enforced as if it were;- reasonSource — where that reason came from, decided by one test you can actually run: does the reviewer's own text state a consequence or a cause, not just an instruction? "the cyan is too light, I can't see it" states a consequence → "reviewer". "put it in one row, annotations left, actions right" and "there's an extra line here" are instructions with no cause → "inferred", however obvious the cause seems. So is "this is ugly" / "this is wrong" / "this doesn't work". When in doubt answer "inferred": over-claiming the reviewer said something is the one failure this field exists to prevent, and under-claiming costs nothing;+- reviewerWords — when reasonSource is "reviewer", the reviewer's own sentence that states the consequence or cause, copied character for character from what they said or wrote on a circled region. Do not translate, trim into a paraphrase, or merge two remarks. The reader trusts a standard far more when its reason is in their own words, so this is shown first and your mechanism after it. Answer "" when reasonSource is "inferred";- example — how it showed up this time, concretely enough to recognise again;-- limits — the boundary THE REVIEWER drew. Fill it only when they said where the standard stops, or when another rejection in this same round contradicts it. Otherwise answer exactly "边界未由评审者说明" (or the same sentence in their language). An invented exemption is worse than an empty one: it silently narrows a standard the reviewer stated without limit;+- limits — the boundary THE REVIEWER drew. Fill it only when they said where the standard stops, or when another rejection in this same round contradicts it. Otherwise answer "". Never write a sentence saying that no boundary was given — an empty field already says that. An invented exemption is worse than an empty one: it silently narrows a standard the reviewer stated without limit;+- specificity — only matters when you propose a new lesson. Ask: would anyone check this on a delivery that does not contain this very element? If not, answer "one-off". Typical one-offs: a version number, a padding or size on one particular header, the wording of one label, removing one specific button, a fact about this project's release state. They stay one-offs even after you phrase them generally — "keep the top padding of section headers compact" is still that one header. Answer "general" only when the standard would plausibly be broken again on an unrelated screen. A one-off kept and labelled is useful; a one-off dressed as a standard dilutes every real one;- sourceRefs — the reference labels (for example "R2") of every rejection supporting it. Never invent a label that is not listed.-Leave existingLessonCode and layer as an empty string rather than null when they do not apply — never as an object. Use only declared layer keys. Write human-facing text in the language the reviewer used.`;+Leave existingLessonCode and layer as an empty string rather than null when they do not apply — never as an object. Use only declared layer keys.++Write every human-facing field — title, subject, reasoning, example, limits — in the language the reviewer wrote their rejections in, even when the domains, these instructions or the promised checks are in another language. A Chinese reviewer gets Chinese standards.`;export const chainExpertiseRejectionIngestion = (input: {domains: readonly unknown[];@@ -534,7 +554,7 @@ Return \`limits\` as the exemptions you are ADDING. Each entry:- \`text\` — where the standard stops, in the reviewer's language.- \`shippedRefs\` — the labels of the SHIPPED deliveries it was read from (for example ["S2"]). Every entry must name at least one. An entry that names none, or names an instance, is discarded — and so is any label that is not listed.-Do not repeat the limits the standard already carries; they are kept for you, word for word, and nothing you write can remove one. Set \`currentLimitsArePlaceholder\` to true only when the standard's current \`limits\` is ingestion's "边界未由评审者说明" placeholder (in any language) rather than a boundary the reviewer drew — that is the one case where the existing text is dropped, and only if you supply a real exemption to replace it.+Do not repeat the limits the standard already carries; they are kept for you, word for word, and nothing you write can remove one. Set \`currentLimitsArePlaceholder\` to true only when the standard's current \`limits\` is the "边界未由评审者说明" placeholder older ingestion wrote (in any language) rather than a boundary the reviewer drew — that is the one case where the existing text is dropped, and only if you supply a real exemption to replace it.Rules on this, in order:- Only a shipped delivery whose frame you have actually read can justify a new exemption. Never infer one from the instances, from the standard's own wording, or from what a reasonable person "would obviously" exempt — an invented exemption silently narrows a standard the reviewer stated without limit.diff --git a/src/features/MemoryRules/DetailPanel.tsx b/src/features/MemoryRules/DetailPanel.tsxindex 5b2c0df9e24..80e860edc41 100644--- a/src/features/MemoryRules/DetailPanel.tsx+++ b/src/features/MemoryRules/DetailPanel.tsx@@ -19,6 +19,7 @@ import {ClipboardCheckIcon,HistoryIcon,type LucideIcon,+ MessageSquareTextIcon,MoreHorizontalIcon,PencilIcon,ScaleIcon,@@ -27,8 +28,11 @@ import {} from 'lucide-react';import { type ReactNode, useEffect, useState } from 'react';import { useTranslation } from 'react-i18next';+import { useNavigate } from 'react-router';+import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';import RightPanel from '@/features/RightPanel';+import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';import type { RuleGroup, RuleItem, UpdateRuleInput } from '@/services/expertise';import Field from './Field';@@ -37,6 +41,7 @@ import {appendException,mergedIntoId,revisionAuthorKey,+ ruleOrigin,sectionBody,useScopeLabel,} from './labels';@@ -237,6 +242,8 @@ const RuleDocument = ({}: RuleDocumentProps) => {const { t } = useTranslation('memory');const scopeLabel = useScopeLabel();+ const navigate = useNavigate();+ const workspaceSlug = useActiveWorkspaceSlug();const {data: sources,error: sourcesError,@@ -257,6 +264,7 @@ const RuleDocument = ({const all = groups.flatMap((g) => g.rules);const titleOf = (id: string) => all.find((r) => r.id === id)?.title ?? id;const mergedInto = mergedIntoId(rule);+ const origin = ruleOrigin(rule);const save = async (patch: UpdateRuleInput) => {if (busy) return false;@@ -396,14 +404,12 @@ const RuleDocument = ({: undefined}>- <Text weight={500}>{t(`rules.reason.${rule.reasonKind ?? 'taste'}`)}</Text>- <span className={styles.muted}>- {t(- rule.reasonSource === 'inferred'- ? 'rules.reason.inferred'- : 'rules.reason.reviewer',- )}- </span>+ {/* Conversation learning never classifies its reason; saying "taste, you said it"+ for those would claim something nobody stated. */}+ <Text weight={500}>{t(`rules.reason.${rule.reasonKind ?? 'unset'}`)}</Text>+ {rule.reasonSource && (+ <span className={styles.muted}>{t(`rules.reason.${rule.reasonSource}`)}</span>+ )}</Property>{rule.enforcement === 'block' && rule.reasonKind === 'taste' && (<div className={styles.warning}>{t('rules.enforcement.tasteWarning')}</div>@@ -426,12 +432,10 @@ const RuleDocument = ({</Property><Property icon={HistoryIcon} label={t('rules.meta.origin')}><span>- {authored- ? t('rules.origin.authored')- : t('rules.origin.distilled', { hits: rule.hitCount }) +- (rule.lastHitAt- ? t('rules.origin.lastHit', { time: dayjs(rule.lastHitAt).fromNow() })- : '')}+ {t(`rules.origin.${origin.key}`, 'params' in origin ? origin.params : undefined)}+ {!authored && rule.lastHitAt+ ? t('rules.origin.lastHit', { time: dayjs(rule.lastHitAt).fromNow() })+ : ''}</span>{Boolean(rule.generalizedFromIds?.length) && (<span className={styles.muted}>@@ -508,11 +512,35 @@ const RuleDocument = ({<div className={styles.source} key={source.id}><Flexbox horizontal align={'center'} gap={8} justify={'space-between'}><Flexbox horizontal align={'center'} gap={6} style={{ minWidth: 0 }}>- <Tag size={'small'}>{t('rules.sources.acceptance')}</Tag>+ <Tag size={'small'}>+ {t(+ source.fromAcceptance+ ? 'rules.sources.acceptance'+ : 'rules.sources.conversation',+ )}+ </Tag><span style={{ fontSize: 13, fontWeight: 500 }}>{source.checkTitle ?? source.where ?? ''}</span></Flexbox>+ {!source.fromAcceptance && source.topicId && source.topicAgentId && (+ <a+ className={styles.link}+ href={buildWorkspaceAwarePath(+ `/agent/${source.topicAgentId}/${source.topicId}${+ source.messageId ? `?locate=${source.messageId}` : ''+ }`,+ workspaceSlug,+ )}+ onClick={(e) => {+ e.preventDefault();+ navigate(e.currentTarget.getAttribute('href')!);+ }}+ >+ <Icon icon={MessageSquareTextIcon} size={12} />+ {t(source.messageId ? 'rules.sources.openMessage' : 'rules.sources.openTopic')}+ </a>+ )}{source.acceptanceId && (<aclassName={styles.link}diff --git a/src/features/MemoryRules/RuleRow.tsx b/src/features/MemoryRules/RuleRow.tsxindex ebd570f1db6..07195c84101 100644--- a/src/features/MemoryRules/RuleRow.tsx+++ b/src/features/MemoryRules/RuleRow.tsx@@ -66,6 +66,11 @@ const RuleRow = ({<Flexbox horizontal align={'baseline'} gap={6} wrap={'wrap'}><span className={styles.title}>{rule.title}</span>{authored && <Tag size={'small'}>{t('rules.tag.authored')}</Tag>}+ {rule.specificity === 'one-off' && !archived && (+ <Tooltip title={t('rules.origin.oneOff')}>+ <Tag size={'small'}>{t('rules.tag.oneOff')}</Tag>+ </Tooltip>+ )}{archived && (<span className={styles.muted}>{t('rules.archived.at', {diff --git a/src/features/MemoryRules/labels.test.ts b/src/features/MemoryRules/labels.test.tsindex 1a5801cd902..c6660883065 100644--- a/src/features/MemoryRules/labels.test.ts+++ b/src/features/MemoryRules/labels.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest';-import { appendException, findMove, revisionAuthorKey } from './labels';+import { appendException, findMove, revisionAuthorKey, ruleOrigin, sectionBody } from './labels';describe('appendException', () => {it('keeps the exceptions already written and adds the new one below', () => {@@ -55,3 +55,34 @@ describe('revisionAuthorKey', () => {);});});++describe('ruleOrigin', () => {+ const rule = (rejectionHitCount: number, conversationHitCount: number, authored = false) => ({+ authored,+ conversationHitCount,+ rejectionHitCount,+ });++ 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 } });+ });++ it('counts only rejections as "you sent it back"', () => {+ expect(ruleOrigin(rule(4, 0))).toEqual({ key: 'distilled', params: { hits: 4 } });+ expect(ruleOrigin(rule(4, 9))).toEqual({+ key: 'distilledAndObserved',+ params: { conversations: 9, rejections: 4 },+ });+ });++ it('keeps a hand-written rule as the reviewer’s own however it was hit since', () => {+ expect(ruleOrigin(rule(2, 1, true))).toEqual({ key: 'authored' });+ });+});++describe('sectionBody', () => {+ it('reads the "no boundary given" sentence as no boundary', () => {+ const sections = [{ body: '边界未由评审者说明', key: 'limits' as const }];+ expect(sectionBody({ sections }, 'limits')).toBeUndefined();+ });+});diff --git a/src/features/MemoryRules/labels.ts b/src/features/MemoryRules/labels.tsindex c1824a1fe67..75dc2fc98fe 100644--- a/src/features/MemoryRules/labels.ts+++ b/src/features/MemoryRules/labels.ts@@ -4,21 +4,23 @@ import type { RuleItem, RuleRevision, RuleScope } from '@/services/expertise';export type RuleSectionKey = 'rule' | 'why' | 'how' | 'limits';+/**+ * What older distillation wrote into `limits` when the reviewer drew no boundary. It means "none+ * yet", so it reads as an empty section and the first real exception replaces it rather than+ * sitting under it — the same thing consolidation does.+ */+const UNSTATED_LIMITS = new Set(['边界未由评审者说明']);+/** One section's text, or undefined when the rule has nothing under that heading. */-export const sectionBody = (rule: Pick<RuleItem, 'sections'>, key: RuleSectionKey) =>- rule.sections?.find((section) => section.key === key)?.body?.trim() || undefined;+export const sectionBody = (rule: Pick<RuleItem, 'sections'>, key: RuleSectionKey) => {+ const body = rule.sections?.find((section) => section.key === key)?.body?.trim() || undefined;+ return key === 'limits' && body && UNSTATED_LIMITS.has(body) ? undefined : body;+};/*** The "when it does not apply" text after adding one more exception. Exceptions accumulate: the* composer adds a line, it never replaces what the reviewer already narrowed.*/-/**- * What distillation writes into `limits` when the reviewer drew no boundary (see the ingestion- * prompt in `@lobechat/prompts`). It means "none yet", so the first real exception replaces it- * rather than sitting under it — the same thing consolidation does.- */-const UNSTATED_LIMITS = new Set(['边界未由评审者说明']);-export const appendException = (existing: string | undefined, exception: string) => {const next = exception.trim();const trimmed = existing?.trim();@@ -28,6 +30,23 @@ export const appendException = (existing: string | undefined, exception: string)return `${current}\n${next}`;};+/**+ * Which "where it came from" line a rule gets. Rejections and conversation observations are+ * counted apart because only the first is "you sent a delivery back for this"; a rule learned in+ * conversation must not claim the reviewer rejected anything.+ */+export const ruleOrigin = (+ rule: Pick<RuleItem, 'authored' | 'conversationHitCount' | 'rejectionHitCount'>,+) => {+ const { conversationHitCount: conversations, rejectionHitCount: rejections } = rule;+ if (rule.authored) return { key: 'authored' } 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;+ if (conversations > 0) return { key: 'observed', params: { hits: conversations } } as const;+ return { key: 'learned' } as const;+};+/** Where a rule went when it was archived by a merge, or null for a plain archive. */export const mergedIntoId = (rule: Pick<RuleItem, 'rejectedReason'>) =>rule.rejectedReason?.startsWith('merged-into:')diff --git a/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx b/src/routes/(main)/agent/features/Conversation/ConversationArea.tsxindex be126855a4f..5e4fccf9f75 100644--- a/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx+++ b/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx@@ -35,6 +35,7 @@ import { messageMapKey } from '@/store/chat/utils/messageMapKey';import ExposeMainEditor from './ExposeMainEditor';import HeterogeneousChatInput from './HeterogeneousChatInput';+import LocateMessageFromUrl from './LocateMessageFromUrl';import MainChatInput from './MainChatInput';import MessageFromUrl from './MainChatInput/MessageFromUrl';import ThreadHydration from './ThreadHydration';@@ -204,6 +205,7 @@ const Conversation = memo(() => {<ThreadHydration /><ChatMiniMap /><ForwardMessageDispatcher />+ <LocateMessageFromUrl />{/* Held back while the topic is still migrating: the composer above isalready disabled, and letting `?message=` through would send into thenot-yet-migrated history this screen is waiting for. The param staysdiff --git a/src/routes/(main)/agent/features/Conversation/LocateMessageFromUrl.tsx b/src/routes/(main)/agent/features/Conversation/LocateMessageFromUrl.tsxnew file mode 100644index 00000000000..e7e612f0eea--- /dev/null+++ b/src/routes/(main)/agent/features/Conversation/LocateMessageFromUrl.tsx@@ -0,0 +1,61 @@+'use client';++import { useEffect } from 'react';+import { useSearchParams } from 'react-router';++import { useConversationStore } from '@/features/Conversation';+import {+ highlightMessageWhenScrollSettles,+ resolveTopicCommentMessageLocation,+} from '@/features/Portal/TopicComments/messageLocator';+import { useChatStore } from '@/store/chat';+import { displayMessageSelectors } from '@/store/chat/selectors';++const PARAM = 'locate';++/**+ * `?locate=<messageId>` scrolls the opened topic to that message and flashes it — how a rule+ * learned in conversation links back to the turn that taught it. The param is consumed once the+ * messages are in, whether or not the message is among them, so a reload does not jump again.+ */+const LocateMessageFromUrl = () => {+ const [searchParams, setSearchParams] = useSearchParams();+ const messageId = searchParams.get(PARAM);+ const messagesInit = useConversationStore((s) => s.messagesInit);+ const [loaded, index, elementId, scrollToIndex] = useChatStore((s) => {+ const chats = displayMessageSelectors.mainDisplayChats(s);+ const location = resolveTopicCommentMessageLocation(chats, messageId);+ return [+ chats.length > 0,+ location?.index ?? -1,+ location?.elementId,+ s.mainConversationScrollToIndex,+ ] as const;+ });++ useEffect(() => {+ // The conversation store can report ready a beat before the display list fills.+ if (!messageId || !messagesInit || !loaded) return;+ // Found but the list has not mounted its scroller yet: wait for it.+ if (index >= 0 && !scrollToIndex) return;++ if (index >= 0 && elementId && scrollToIndex) {+ requestAnimationFrame(() => {+ scrollToIndex(index, { align: 'center', smooth: false });+ highlightMessageWhenScrollSettles(elementId);+ });+ }+ setSearchParams(+ (prev) => {+ const next = new URLSearchParams(prev);+ next.delete(PARAM);+ return next;+ },+ { replace: true },+ );+ }, [elementId, index, loaded, messageId, messagesInit, scrollToIndex, setSearchParams]);++ return null;+};++export default LocateMessageFromUrl;