🤯 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): my rules — order, group, edit and enforce the distilled delivery rules (Labs alpha) (#19779)
Arvin Xua43f3bff931a
diff --git a/apps/server/src/routers/lambda/expertise.ts b/apps/server/src/routers/lambda/expertise.tsindex dab83049c5c..3929eeed1b8 100644--- a/apps/server/src/routers/lambda/expertise.ts+++ b/apps/server/src/routers/lambda/expertise.ts@@ -1,3 +1,4 @@+import { EXPERTISE_ENFORCEMENTS } from '@lobechat/types';import { z } from 'zod';import {@@ -5,6 +6,7 @@ import {wsCompatProcedure,} from '@/business/server/trpc-middlewares/workspaceAuth';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 {@@ -13,6 +15,7 @@ import {ExpertiseDomainService,} from '@/server/services/expertise/domain';import { ExpertiseIngestionService } from '@/server/services/expertise/ingestion';+import { DraftRuleInputSchema, ExpertiseRuleDraftService } from '@/server/services/expertise/rules';import { ExpertiseHistoryWorkflow } from '@/server/workflows/expertiseHistory';/**@@ -35,6 +38,16 @@ const expertiseProcedure = wsCompatProcedure.use(serverDatabase).use(async (optsctx.userId,ctx.workspaceId ?? undefined,),+ expertiseRuleRepository: new ExpertiseRuleRepository(+ ctx.serverDB,+ ctx.userId,+ ctx.workspaceId ?? undefined,+ ),+ expertiseRuleDraftService: new ExpertiseRuleDraftService(+ ctx.serverDB,+ ctx.userId,+ ctx.workspaceId ?? undefined,+ ),},});});@@ -221,6 +234,139 @@ export const expertiseRouter = router({return { hits, lesson };}),+ /**+ * The reviewer's own rules, grouped, plus how many rejected rounds are still waiting to be+ * read. The backlog travels with the list because an empty page has to say *why* it is empty —+ * distillation only fires when a later round lands, so old rejections never arrive on their own.+ */+ listRules: expertiseProcedure.query(async ({ ctx }) => {+ const [groups, backlogRounds] = await Promise.all([+ ctx.expertiseModel.listRules(),+ ctx.expertiseModel.countUndistilledRejectionRounds(),+ ]);+ return { backlogRounds, groups };+ }),++ /** The rejections one rule was distilled from, linked back to the acceptance round. */+ ruleSources: expertiseProcedure+ .input(z.object({ lessonId: z.string() }))+ .query(async ({ ctx, input }) => ctx.expertiseModel.listLessonSources(input.lessonId)),++ /** The edits one rule has been through, so a reader can see who narrowed it and when. */+ ruleRevisions: expertiseProcedure+ .input(z.object({ lessonId: z.string() }))+ .query(async ({ ctx, input }) => ctx.expertiseModel.listLessonRevisions(input.lessonId)),++ /**+ * Drafts one rule from whatever the reviewer typed or pasted. Nothing is written: the draft+ * comes back for review and only `createRule` persists it.+ */+ // Drafting spends model capacity on something only a member can save, so it is gated the same.+ draftRule: expertiseWriteProcedure+ .input(DraftRuleInputSchema)+ .mutation(async ({ ctx, input }) => ctx.expertiseRuleDraftService.draftRule(input)),++ /** Drafts a group (name + gate question) from a sentence; `createRuleGroup` persists it. */+ draftRuleGroup: expertiseWriteProcedure+ .input(z.object({ brief: z.string().min(1).max(20_000) }))+ .mutation(async ({ ctx, input }) => ctx.expertiseRuleDraftService.draftRuleGroup(input)),++ /** A rule the reviewer writes down by hand. */+ createRule: expertiseWriteProcedure+ .input(+ z.object({+ // `compiled` is only true once the compiler links a criterion; nobody can claim it by hand.+ compilability: z.enum(['compilable', 'not-compilable']).optional(),+ domainId: z.string(),+ 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(),+ }),+ )+ .mutation(async ({ ctx, input }) => ctx.expertiseModel.createRule(input)),++ /** Field-level edits from the rule document; wording edits are versioned. */+ updateRule: expertiseWriteProcedure+ .input(+ z.object({+ // `compiled` is only true once the compiler links a criterion; nobody can claim it by hand.+ compilability: z.enum(['compilable', 'not-compilable']).optional(),+ enforcement: z.enum(EXPERTISE_ENFORCEMENTS).optional(),+ lessonId: z.string(),+ reasonKind: z.enum(['mechanism', 'taste']).optional(),+ sections: z+ .object({+ how: z.string().max(8000).nullable().optional(),+ limits: z.string().max(4000).nullable().optional(),+ rule: z.string().max(4000).nullable().optional(),+ why: z.string().max(4000).nullable().optional(),+ })+ .optional(),+ title: z.string().min(1).max(500).optional(),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ const { lessonId, ...patch } = input;+ return ctx.expertiseRuleRepository.updateRule(lessonId, patch);+ }),++ /** The order the reviewer dragged one group into. */+ /** Moves one rule within its group: before `beforeId`, or to the end when it is null. */+ reorderRule: expertiseWriteProcedure+ .input(+ z.object({ beforeId: z.string().nullable(), domainId: z.string(), lessonId: z.string() }),+ )+ .mutation(async ({ ctx, input }) =>+ ctx.expertiseModel.reorderRule(input.domainId, input.lessonId, input.beforeId),+ ),++ /** Files a rule under another group. */+ moveRule: expertiseWriteProcedure+ .input(z.object({ domainId: z.string(), lessonId: z.string() }))+ .mutation(async ({ ctx, input }) =>+ ctx.expertiseModel.moveRule(input.lessonId, input.domainId),+ ),++ /** Folds one rule into another; the source is archived with a pointer to where it went. */+ mergeRules: expertiseWriteProcedure+ .input(z.object({ fromId: z.string(), intoId: z.string() }))+ .mutation(async ({ ctx, input }) =>+ ctx.expertiseRuleRepository.mergeRules(input.fromId, input.intoId),+ ),++ /** Puts an archived rule back into practice. */+ restoreLesson: expertiseWriteProcedure+ .input(z.object({ lessonId: z.string() }))+ .mutation(async ({ ctx, input }) => ctx.expertiseModel.restoreLesson(input.lessonId)),++ /** A group the reviewer opens by hand; it mounts on them, so every acceptance can add to it. */+ createRuleGroup: expertiseWriteProcedure+ .input(+ z.object({+ gate: z.string().min(1).max(1000),+ outOfScope: z.string().max(1000).optional(),+ title: z.string().min(1).max(200),+ }),+ )+ .mutation(async ({ ctx, input }) => ctx.expertiseModel.createRuleGroup(input)),++ /** Renames a group or rewrites its gate question. */+ updateRuleGroup: expertiseWriteProcedure+ .input(+ z.object({+ domainId: z.string(),+ gate: z.string().min(1).max(1000).optional(),+ outOfScope: z.string().max(1000).nullable().optional(),+ title: z.string().min(1).max(200).optional(),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ const { domainId, ...patch } = input;+ return ctx.expertiseModel.updateRuleGroup(domainId, patch);+ }),+/** Step 1 of creation: interpret the brief into an editable draft. Nothing is persisted. */draftDomain: expertiseWriteProcedure.input(diff --git a/apps/server/src/services/expertise/rules.test.ts b/apps/server/src/services/expertise/rules.test.tsnew file mode 100644index 00000000000..2d1fc3c8d72--- /dev/null+++ b/apps/server/src/services/expertise/rules.test.ts@@ -0,0 +1,130 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { DraftRuleInputSchema, ExpertiseRuleDraftService } from './rules';++const { resolveExpertiseModelConfig } = vi.hoisted(() => ({+ resolveExpertiseModelConfig: vi.fn(),+}));+const generateObject = vi.fn();++vi.mock('@/server/services/aiGeneration', () => ({+ AiGenerationService: class {+ generateObject = generateObject;+ },+}));+vi.mock('./modelConfig', () => ({ resolveExpertiseModelConfig }));++const groups = [+ { gate: '去掉页面名之后还成立吗?', id: 'g-taste', title: '我的交付审美' },+ { gate: '换一个仓库还成立吗?', id: 'g-design', title: '设计体系' },+];++describe('ExpertiseRuleDraftService', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ resolveExpertiseModelConfig.mockResolvedValue({ model: 'm', provider: 'p' });+ });++ it('drafts one rule and keeps a group id only when the reviewer has that group', async () => {+ generateObject.mockResolvedValue({+ compilability: 'compilable',+ enforcement: 'block',+ groupId: 'g-design',+ how: ' 样式里出现 #fff 或 12px ',+ limits: null,+ newGroup: { gate: 'x', title: 'y' },+ title: '颜色、间距、圆角一律取自设计系统变量',+ why: '',+ });++ const draft = await new ExpertiseRuleDraftService({} as never, 'user_1').draftRule({+ brief: '你应该用 cssVar 的吧',+ groups,+ });++ expect(draft).toEqual({+ compilability: 'compilable',+ enforcement: 'block',+ groupId: 'g-design',+ how: '样式里出现 #fff 或 12px',+ limits: null,+ // A matched group wins over a proposed one; both would be confusing.+ newGroup: null,+ title: '颜色、间距、圆角一律取自设计系统变量',+ why: null,+ });+ const [params, options] = generateObject.mock.calls[0];+ expect(params.schema.name).toBe('expertise_rule_draft');+ expect(params.messages[1].content).toContain('g-design · 设计体系 · 换一个仓库还成立吗?');+ expect(options.tracing.scenario).toBe('expertise_rule_draft');+ });++ it('drops a group id the reviewer does not have and keeps the proposed group', async () => {+ generateObject.mockResolvedValue({+ compilability: 'not-compilable',+ enforcement: 'remind',+ groupId: 'g-invented',+ how: null,+ limits: null,+ newGroup: { gate: '这条只对 lobehub 成立吗?', title: 'OSS 工程规范' },+ title: '交付分支必须先 rebase 到 canary',+ why: null,+ });++ const draft = await new ExpertiseRuleDraftService({} as never, 'user_1').draftRule({+ brief: '你先 rebase 一下再截',+ groups,+ });++ expect(draft.groupId).toBeNull();+ expect(draft.newGroup).toEqual({ gate: '这条只对 lobehub 成立吗?', title: 'OSS 工程规范' });+ });++ it('never hands back a draft that claims to be compiled already', async () => {+ generateObject.mockResolvedValue({+ compilability: 'compiled',+ enforcement: 'remind',+ groupId: 'g-design',+ how: null,+ limits: null,+ newGroup: null,+ title: '颜色一律取自设计系统变量',+ why: null,+ });++ const draft = await new ExpertiseRuleDraftService({} as never, 'user_1').draftRule({+ brief: '你应该用 cssVar 的吧',+ groups,+ });++ // Only the compiler can make a rule `compiled`, by linking a criterion.+ expect(draft.compilability).toBe('compilable');+ });++ it('drafts a group as a name and a gate question', async () => {+ generateObject.mockResolvedValue({+ gate: '这条只对 lobehub 这个仓库成立,还是对任何仓库都成立?',+ outOfScope: null,+ title: 'OSS 工程规范',+ });++ const draft = await new ExpertiseRuleDraftService({} as never, 'user_1').draftRuleGroup({+ brief: '开源仓库的工程要求',+ });++ expect(draft.title).toBe('OSS 工程规范');+ expect(generateObject.mock.calls[0][1].tracing.scenario).toBe('expertise_rule_group_draft');+ });++ it('accepts a scope with more groups than a page used to fit', () => {+ const many = Array.from({ length: 120 }, (_, i) => ({+ gate: `守门题 ${i}`,+ id: `g-${i}`,+ title: `分组 ${i}`,+ }));+ expect(DraftRuleInputSchema.safeParse({ brief: '颜色取自变量', groups: many }).success).toBe(+ true,+ );+ });+});diff --git a/apps/server/src/services/expertise/rules.ts b/apps/server/src/services/expertise/rules.tsnew file mode 100644index 00000000000..a8f7a65eea8--- /dev/null+++ b/apps/server/src/services/expertise/rules.ts@@ -0,0 +1,123 @@+import { TRACING_SCENARIOS } from '@lobechat/const';+import {+ chainExpertiseRuleDraft,+ chainExpertiseRuleGroupDraft,+ EXPERTISE_RULE_DRAFT_JSON_SCHEMA,+ EXPERTISE_RULE_DRAFT_PROMPT_VERSION,+ EXPERTISE_RULE_GROUP_DRAFT_JSON_SCHEMA,+ EXPERTISE_RULE_GROUP_DRAFT_PROMPT_VERSION,+} from '@lobechat/prompts';+import { RequestTrigger } from '@lobechat/types';+import { z } from 'zod';++import type { LobeChatDatabase } from '@/database/type';+import { AiGenerationService } from '@/server/services/aiGeneration';++import { resolveExpertiseModelConfig } from './modelConfig';++const nullableText = z+ .string()+ .nullable()+ .transform((value) => value?.trim() || null);++export const RuleDraftSchema = z.object({+ // A draft can at most be checkable by a program; `compiled` means a criterion is linked, which+ // only the compiler does. Older prompt versions may still say `compiled`.+ compilability: z+ .enum(['compiled', 'compilable', 'not-compilable'])+ .transform((value) => (value === 'compiled' ? 'compilable' : value)),+ 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(),+ title: z.string().min(1).max(200),+ why: nullableText,+});++export const RuleGroupDraftSchema = z.object({+ gate: z.string().min(1),+ outOfScope: nullableText,+ title: z.string().min(1).max(60),+});++export type RuleDraft = z.infer<typeof RuleDraftSchema>;+export type RuleGroupDraft = z.infer<typeof RuleGroupDraftSchema>;++/**+ * What the compose box sends: the sentence plus every group the page shows, so the model can+ * file the draft into one of them. The group list is not capped — group creation has no limit+ * and the page lists them all, so a cap here would turn every draft in a long-lived scope into a+ * failure.+ */+export const DraftRuleInputSchema = z.object({+ brief: z.string().min(1).max(20_000),+ groups: z.array(z.object({ gate: z.string(), id: z.string(), title: z.string() })),+});++export type DraftRuleInput = z.infer<typeof DraftRuleInputSchema>;++/**+ * Turns what the reviewer typed or pasted into an editable draft, and nothing else: no row is+ * written until they have seen every field and pressed save. A draft that names a group the+ * reviewer does not have is a model slip, not a request, so it is dropped to "no group".+ */+export class ExpertiseRuleDraftService {+ 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;+ }++ draftRule = async (input: DraftRuleInput): Promise<RuleDraft> => {+ const modelConfig = await resolveExpertiseModelConfig(this.db, this.userId);+ const ai = new AiGenerationService(this.db, this.userId, this.workspaceId);+ const draft = RuleDraftSchema.parse(+ await ai.generateObject(+ {+ ...chainExpertiseRuleDraft(input),+ ...modelConfig,+ schema: EXPERTISE_RULE_DRAFT_JSON_SCHEMA,+ },+ {+ metadata: { trigger: RequestTrigger.Expertise },+ tracing: {+ promptVersion: EXPERTISE_RULE_DRAFT_PROMPT_VERSION,+ scenario: TRACING_SCENARIOS.ExpertiseRuleDraft,+ schemaName: EXPERTISE_RULE_DRAFT_JSON_SCHEMA.name,+ },+ },+ ),+ );++ const known = new Set(input.groups.map((group) => group.id));+ const groupId = draft.groupId && known.has(draft.groupId) ? draft.groupId : null;+ return { ...draft, groupId, newGroup: groupId ? null : draft.newGroup };+ };++ draftRuleGroup = async (input: { brief: string }): Promise<RuleGroupDraft> => {+ const modelConfig = await resolveExpertiseModelConfig(this.db, this.userId);+ const ai = new AiGenerationService(this.db, this.userId, this.workspaceId);+ return RuleGroupDraftSchema.parse(+ await ai.generateObject(+ {+ ...chainExpertiseRuleGroupDraft(input),+ ...modelConfig,+ schema: EXPERTISE_RULE_GROUP_DRAFT_JSON_SCHEMA,+ },+ {+ metadata: { trigger: RequestTrigger.Expertise },+ tracing: {+ promptVersion: EXPERTISE_RULE_GROUP_DRAFT_PROMPT_VERSION,+ scenario: TRACING_SCENARIOS.ExpertiseRuleGroupDraft,+ schemaName: EXPERTISE_RULE_GROUP_DRAFT_JSON_SCHEMA.name,+ },+ },+ ),+ );+ };+}diff --git a/locales/en-US/electron.json b/locales/en-US/electron.jsonindex c594707eb8b..776880b6f39 100644--- a/locales/en-US/electron.json+++ b/locales/en-US/electron.json@@ -34,6 +34,7 @@"navigation.memoryContexts": "Memory - Contexts","navigation.memoryIdentities": "Memory - Identities","navigation.memoryPreferences": "Memory - Preferences",+ "navigation.memoryRules": "Memory - Rules","navigation.newChat": "New Chat","navigation.noPages": "No pages yet","navigation.onboarding": "Onboarding",diff --git a/locales/en-US/labs.json b/locales/en-US/labs.jsonindex 605039e22b8..6e1cdd2dc6f 100644--- a/locales/en-US/labs.json+++ b/locales/en-US/labs.json@@ -30,6 +30,8 @@"features.inputMarkdown.title": "Input Markdown Rendering","features.integrations.desc": "Show the Integrations settings page: connect the GitHub App so merged pull requests accept deliveries and failing checks or reviews reach the agent that opened them. Hidden by default.","features.integrations.title": "Integrations",+ "features.memoryRules.desc": "Adds \"My rules\" under Memory: the delivery rules distilled from the acceptance rounds you sent back, with ordering, grouping and block / remind controls.",+ "features.memoryRules.title": "My rules","features.messageTextSelectionActions.desc": "Show a quick action when selecting text in chat messages so the selected text can be added to the next conversation context.","features.messageTextSelectionActions.title": "Message Text Selection Actions","features.oauthApps.desc": "Show OAuth app management in personal and workspace settings. This feature is hidden by default.",diff --git a/locales/en-US/memory.json b/locales/en-US/memory.jsonindex 132be475bbb..40e8109c579 100644--- a/locales/en-US/memory.json+++ b/locales/en-US/memory.json@@ -89,11 +89,152 @@"purge.error": "Failed to purge memories. Please try again.","purge.success": "All memories have been deleted.","purge.title": "Purge All Memories",+ "rules.actions.archive": "Archive",+ "rules.actions.edit": "Reword",+ "rules.actions.editGate": "Change the gate question…",+ "rules.actions.merge": "Merge into…",+ "rules.actions.move": "Move to…",+ "rules.actions.newGroup": "New group…",+ "rules.actions.renameGroup": "Rename",+ "rules.actions.restore": "Put back to work",+ "rules.actions.write": "Write one",+ "rules.actions.writeHere": "Write one in this group",+ "rules.archived.at": "Archived {{time}}",+ "rules.archived.byYou": "archived by you",+ "rules.archived.group": "Archived ({{count}})",+ "rules.archived.mergedInto": "merged into \"{{title}}\"",+ "rules.backlog": "{{count}} rejected rounds have not been read yet",+ "rules.columns.code": "No.",+ "rules.columns.enforcement": "Effect",+ "rules.columns.method": "Check",+ "rules.columns.rule": "Rule",+ "rules.columns.runs": "Checked",+ "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.describeTitle": "Write a rule",+ "rules.compose.enforcementBlock": "Block · will hold the delivery (not in effect yet)",+ "rules.compose.enforcementRemind": "Remind · nudges the agent only",+ "rules.compose.generateFailed": "Could not draft it. Fill it in yourself.",+ "rules.compose.generating": "Drafting the rule…",+ "rules.compose.generatingFields": "Working out why, an example and the limits…",+ "rules.compose.generatingGroup": "Picking a group…",+ "rules.compose.generatingTitle": "Putting it in one sentence…",+ "rules.compose.how": "What counts as breaking it (optional)",+ "rules.compose.limits": "When it does not apply (optional)",+ "rules.compose.needGroup": "Pick a group before saving.",+ "rules.compose.newGroupProposed": "New group: {{title}}",+ "rules.compose.next": "Draft it",+ "rules.compose.noGroup": "Choose a group",+ "rules.compose.reviewStep": "Check the draft, change anything, then save",+ "rules.compose.scope": "applies to {{scopes}}",+ "rules.compose.submit": "Save",+ "rules.compose.titlePlaceholder": "The rule in one sentence",+ "rules.compose.why": "Why it matters (optional)",+ "rules.empty.description": "Rules grow out of the checks you send back — the reason you wrote, and the spot you circled.",+ "rules.empty.title": "No rules yet",+ "rules.empty.write": "Or write one first",+ "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",+ "rules.enforcement.remind": "Remind",+ "rules.enforcement.remindDesc": "Nudges the agent only; never holds a delivery",+ "rules.enforcement.remindHint": "Remind: nudges the agent only. Click to switch to block",+ "rules.enforcement.tasteWarning": "This one rests on your judgement with nothing hard to check against, so blocking on it may misfire.",+ "rules.exception.placeholder": "Say in one sentence where it does not apply, e.g. \"spacing inside charts does not count\".",+ "rules.exception.submit": "Add exception",+ "rules.field.cancel": "Cancel",+ "rules.field.check": "How it is checked",+ "rules.field.checkPending": "No check code yet. It appears here once the compiler turns this rule into a check item.",+ "rules.field.edit": "Edit",+ "rules.field.how": "For example",+ "rules.field.howEmpty": "No examples yet.",+ "rules.field.limits": "When it does not apply",+ "rules.field.limitsEmpty": "No boundary given by the reviewer.",+ "rules.field.save": "Save",+ "rules.field.why": "Why",+ "rules.field.whyEmpty": "No reason written yet.",+ "rules.group.back": "Back",+ "rules.group.blank": "Fill it in myself",+ "rules.group.describePlaceholder": "Say what this group is for, e.g. \"engineering rules for open-source repos\".",+ "rules.group.empty": "Nothing in this group yet.",+ "rules.group.gate": "Gate question: {{gate}}",+ "rules.group.gateLabel": "Gate question — the one to ask before a rule goes in",+ "rules.group.gatePlaceholder": "e.g. Strip the page and task names; does this still hold for any delivery?",+ "rules.group.generateFailed": "Could not draft it. Fill it in yourself.",+ "rules.group.generating": "Drafting the group…",+ "rules.group.nameLabel": "Group name",+ "rules.group.newTitle": "New group",+ "rules.group.next": "Draft it",+ "rules.group.outOfScopeLabel": "What does not belong here (optional)",+ "rules.group.outOfScopePlaceholder": "e.g. general delivery taste that has nothing to do with the repository",+ "rules.group.renameTitle": "Rename group",+ "rules.group.reviewStep": "Check the name and the gate question, then create",+ "rules.group.scope": "· applies to {{scopes}}",+ "rules.group.submitCreate": "Create",+ "rules.group.submitRename": "Save",+ "rules.labOff.description": "Turn it on under Settings → Labs to see the delivery rules distilled from the rounds you sent back.",+ "rules.labOff.open": "Open Labs",+ "rules.labOff.title": "My rules is still in the lab",+ "rules.merge.banner": "Click the rule to merge into — \"{{title}}\" will be archived and its sources and counts move over.",+ "rules.merge.cancel": "Cancel",+ "rules.meta.enforcement": "Effect",+ "rules.meta.method": "Check",+ "rules.meta.origin": "Origin",+ "rules.meta.reason": "Basis",+ "rules.meta.runs": "Checked",+ "rules.meta.scope": "Applies to",+ "rules.method.compilable": "Program-assisted",+ "rules.method.compiled": "By program",+ "rules.method.not-compilable": "By judgement",+ "rules.origin.authored": "You wrote it",+ "rules.origin.distilled": "You sent {{hits}} rounds back over this",+ "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.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.revisions.bySystem": "by the system",+ "rules.revisions.byTeammate": "by a teammate",+ "rules.revisions.byYou": "by you",+ "rules.revisions.generalize": "Merged in \"{{title}}\"",+ "rules.revisions.prevTitle": "Was \"{{title}}\"",+ "rules.revisions.title": "Edits",+ "rules.runs.count": "{{count}}×",+ "rules.runs.detail": "Checked {{runs}} times, caught {{hits}}",+ "rules.runs.none": "Not checked yet",+ "rules.runs.overruled": "you overruled it {{count}} times",+ "rules.saveFailed": "Could not save that change. The page now shows what is actually saved.",+ "rules.scope.agent": "agent {{title}}",+ "rules.scope.project": "project {{title}}",+ "rules.scope.user": "all your runs",+ "rules.scope.workspace": "the whole workspace",+ "rules.severity.high": "severe",+ "rules.severity.low": "minor",+ "rules.severity.mid": "moderate",+ "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.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.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.title": "My rules","tab.activities": "Activities","tab.contexts": "Contexts","tab.home": "Home","tab.identities": "Identities","tab.preferences": "Preferences",+ "tab.rules": "Rules","tab.search": "Search","viewMode.masonry": "Masonry","viewMode.timeline": "Timeline"diff --git a/locales/zh-CN/electron.json b/locales/zh-CN/electron.jsonindex 126eaf1317c..57d2e17c2ff 100644--- a/locales/zh-CN/electron.json+++ b/locales/zh-CN/electron.json@@ -34,6 +34,7 @@"navigation.memoryContexts": "记忆 - 上下文","navigation.memoryIdentities": "记忆 - 身份","navigation.memoryPreferences": "记忆 - 偏好",+ "navigation.memoryRules": "记忆 - 规矩","navigation.newChat": "新建对话","navigation.noPages": "暂无页面","navigation.onboarding": "引导",diff --git a/locales/zh-CN/labs.json b/locales/zh-CN/labs.jsonindex d52c0610a97..f7a0d6a8eca 100644--- a/locales/zh-CN/labs.json+++ b/locales/zh-CN/labs.json@@ -30,6 +30,8 @@"features.inputMarkdown.title": "输入框 Markdown 渲染","features.integrations.desc": "显示「集成」设置页:连接 GitHub App 后,合并 PR 自动验收通过,CI 失败或评审意见会送到开这个 PR 的智能体。默认隐藏。","features.integrations.title": "集成",+ "features.memoryRules.desc": "在「记忆」下增加「我的规矩」:从你打回的验收轮次里沉淀出来的交付规矩,可以排序、分组,并设置拦下或提醒。",+ "features.memoryRules.title": "我的规矩","features.messageTextSelectionActions.desc": "在聊天消息中选中文本时显示快捷操作,可将选中的文本加入下一次对话上下文。","features.messageTextSelectionActions.title": "消息文本选择操作","features.oauthApps.desc": "在个人和工作区设置中显示 OAuth 应用管理入口。此功能默认隐藏。",diff --git a/locales/zh-CN/memory.json b/locales/zh-CN/memory.jsonindex 6f9fd535180..8c0342941c0 100644--- a/locales/zh-CN/memory.json+++ b/locales/zh-CN/memory.json@@ -89,11 +89,152 @@"purge.error": "清除记忆失败。请重试。","purge.success": "所有记忆已被删除。","purge.title": "清除所有记忆",+ "rules.actions.archive": "归档",+ "rules.actions.edit": "改措辞",+ "rules.actions.editGate": "改守门题…",+ "rules.actions.merge": "合并到…",+ "rules.actions.move": "移到…",+ "rules.actions.newGroup": "新建一组…",+ "rules.actions.renameGroup": "重命名",+ "rules.actions.restore": "重新启用",+ "rules.actions.write": "写一条",+ "rules.actions.writeHere": "往这组写一条",+ "rules.archived.at": "{{time}} 归档",+ "rules.archived.byYou": "你归档的",+ "rules.archived.group": "已归档({{count}})",+ "rules.archived.mergedInto": "并入了「{{title}}」",+ "rules.backlog": "还有 {{count}} 轮打回没被读过",+ "rules.columns.code": "编号",+ "rules.columns.enforcement": "效力",+ "rules.columns.method": "验法",+ "rules.columns.rule": "规矩",+ "rules.columns.runs": "检查过",+ "rules.compose.back": "返回",+ "rules.compose.blank": "自己写",+ "rules.compose.describeHint": "写之前先想一下:去掉页面名、组件名、这次的任务名,它还成立吗?",+ "rules.compose.describePlaceholder": "一句话说你要求什么,或者把一段文档贴进来,规矩会从这里生成。",+ "rules.compose.describeTitle": "写一条规矩",+ "rules.compose.enforcementBlock": "拦 · 将拦下交付(尚未生效)",+ "rules.compose.enforcementRemind": "提醒 · 只提醒 Agent",+ "rules.compose.generateFailed": "没能生成,请自己填。",+ "rules.compose.generating": "正在生成规矩…",+ "rules.compose.generatingFields": "在补为什么、例子和边界…",+ "rules.compose.generatingGroup": "在挑一个合适的组…",+ "rules.compose.generatingTitle": "在把要求压成一句话…",+ "rules.compose.how": "什么算违反(可不填)",+ "rules.compose.limits": "什么时候不适用(可不填)",+ "rules.compose.needGroup": "先选一个组再记下。",+ "rules.compose.newGroupProposed": "新建一组:{{title}}",+ "rules.compose.next": "生成",+ "rules.compose.noGroup": "选一个组",+ "rules.compose.reviewStep": "看看生成的内容,改到满意再记下",+ "rules.compose.scope": "生效于 {{scopes}}",+ "rules.compose.submit": "记下",+ "rules.compose.titlePlaceholder": "一句话说清这条规矩",+ "rules.compose.why": "为什么这样要求(可不填)",+ "rules.empty.description": "规矩是从你打回的检查项里长出来的——你写下的理由,和你圈出的那一处。",+ "rules.empty.title": "还没有规矩",+ "rules.empty.write": "也可以先写一条",+ "rules.enforcement.block": "拦",+ "rules.enforcement.blockDesc": "将拦下交付,直到你放行。尚未生效,目前仍只提醒",+ "rules.enforcement.blockHint": "拦:将拦下交付(尚未生效,目前仍只提醒)。点一下改成提醒",+ "rules.enforcement.remind": "提醒",+ "rules.enforcement.remindDesc": "只提醒 Agent,不挡交付",+ "rules.enforcement.remindHint": "提醒:只提醒 Agent,不挡交付。点一下改成拦",+ "rules.enforcement.tasteWarning": "这条靠的是你的判断,没有硬指标,拦的时候可能会误判。",+ "rules.exception.placeholder": "说一句它在哪儿不适用,例如「图表内部的间距不算」。",+ "rules.exception.submit": "补一条例外",+ "rules.field.cancel": "取消",+ "rules.field.check": "怎么验",+ "rules.field.checkPending": "还没有检验代码。编译器把这条规矩变成检查项之后会出现在这里。",+ "rules.field.edit": "改",+ "rules.field.how": "比如",+ "rules.field.howEmpty": "还没有例子。",+ "rules.field.limits": "什么时候不适用",+ "rules.field.limitsEmpty": "边界未由评审者说明",+ "rules.field.save": "保存",+ "rules.field.why": "为什么",+ "rules.field.whyEmpty": "还没写为什么。",+ "rules.group.back": "返回",+ "rules.group.blank": "自己填",+ "rules.group.describePlaceholder": "说说这组是管什么的,比如「开源仓库的工程要求」。",+ "rules.group.empty": "这组还是空的。",+ "rules.group.gate": "守门题:{{gate}}",+ "rules.group.gateLabel": "守门题——一条规矩进这组之前先过的那道题",+ "rules.group.gatePlaceholder": "例如:去掉页面名和任务名之后,这条对任何一次交付还成立吗?",+ "rules.group.generateFailed": "没能生成,请自己填。",+ "rules.group.generating": "正在生成…",+ "rules.group.nameLabel": "组名",+ "rules.group.newTitle": "新建一组",+ "rules.group.next": "生成",+ "rules.group.outOfScopeLabel": "不属于这组的(可不填)",+ "rules.group.outOfScopePlaceholder": "例如:和仓库无关的通用交付审美不放这里",+ "rules.group.renameTitle": "重命名",+ "rules.group.reviewStep": "看看组名和守门题,改到满意再建组",+ "rules.group.scope": "· 生效于 {{scopes}}",+ "rules.group.submitCreate": "建组",+ "rules.group.submitRename": "保存",+ "rules.labOff.description": "到「设置 → 实验室」里打开它,就能看到从你打回的那些轮里沉淀出来的交付规矩。",+ "rules.labOff.open": "打开实验室",+ "rules.labOff.title": "「我的规矩」还在实验室里",+ "rules.merge.banner": "点一条要并进去的规矩——「{{title}}」会归档,它的来源和次数记到目标上。",+ "rules.merge.cancel": "取消",+ "rules.meta.enforcement": "效力",+ "rules.meta.method": "验法",+ "rules.meta.origin": "来历",+ "rules.meta.reason": "依据",+ "rules.meta.runs": "检查",+ "rules.meta.scope": "生效于",+ "rules.method.compilable": "可程序验",+ "rules.method.compiled": "程序验",+ "rules.method.not-compilable": "靠判断",+ "rules.origin.authored": "你自己写的",+ "rules.origin.distilled": "你为这事打回过 {{hits}} 次",+ "rules.origin.generalizedFrom": "由「{{titles}}」合并而来",+ "rules.origin.lastHit": ",最近一次 {{time}}",+ "rules.origin.oneOff": "看起来是一次性的情况,没检查过很正常",+ "rules.origin.overSpecific": "看起来只对某个页面成立,可能该并进更通用的那条",+ "rules.reason.inferred": "推断出来的,你没说过",+ "rules.reason.mechanism": "有依据",+ "rules.reason.reviewer": "你说过的",+ "rules.reason.taste": "凭感觉",+ "rules.revisions.bySystem": "系统改的",+ "rules.revisions.byTeammate": "队友改的",+ "rules.revisions.byYou": "你改的",+ "rules.revisions.generalize": "并入了「{{title}}」",+ "rules.revisions.prevTitle": "原来叫「{{title}}」",+ "rules.revisions.title": "改过的地方",+ "rules.runs.count": "{{count}} 次",+ "rules.runs.detail": "检查过 {{runs}} 次,拦下 {{hits}} 次",+ "rules.runs.none": "还没检查过",+ "rules.runs.overruled": "你说误判了 {{count}} 次",+ "rules.saveFailed": "这次修改没存上,页面已恢复成实际保存的内容。",+ "rules.scope.agent": "智能体 {{title}}",+ "rules.scope.project": "项目 {{title}}",+ "rules.scope.user": "你的所有运行",+ "rules.scope.workspace": "整个工作区",+ "rules.severity.high": "严重",+ "rules.severity.low": "轻微",+ "rules.severity.mid": "一般",+ "rules.sources.acceptance": "验收",+ "rules.sources.agreed": "你确认过这条学对了",+ "rules.sources.authoredEmpty": "你亲手写的,还没有打回记录。",+ "rules.sources.empty": "这条规矩背后的打回已经找不回来了。",+ "rules.sources.loadFailed": "来源没加载出来。",+ "rules.sources.open": "打开",+ "rules.sources.rejected": "你说这条学错了",+ "rules.sources.retry": "重试",+ "rules.sources.round": "第 {{index}} 轮",+ "rules.sources.title": "它从哪来",+ "rules.subtitle": "{{count}} 条在用 · 交付前 Agent 会逐条对照 · 打回验收时说的话会记到这里",+ "rules.tag.authored": "你写的",+ "rules.title": "我的规矩","tab.activities": "活动","tab.contexts": "情境","tab.home": "首页","tab.identities": "身份","tab.preferences": "偏好",+ "tab.rules": "规矩","tab.search": "搜索","viewMode.masonry": "瀑布流","viewMode.timeline": "时间线"diff --git a/packages/const/src/llmGenerationTracing.ts b/packages/const/src/llmGenerationTracing.tsindex 65c8a846e20..6aa0360a0c1 100644--- a/packages/const/src/llmGenerationTracing.ts+++ b/packages/const/src/llmGenerationTracing.ts@@ -14,6 +14,8 @@ export const TRACING_SCENARIOS = {ExpertiseConsolidation: 'expertise_consolidation',ExpertiseDomainDraft: 'expertise_domain_draft',ExpertiseRejectionIngestion: 'expertise_rejection_ingestion',+ ExpertiseRuleDraft: 'expertise_rule_draft',+ ExpertiseRuleGroupDraft: 'expertise_rule_group_draft',ExpertiseTopicIngestion: 'expertise_topic_ingestion',FollowUp: 'follow_up',GoalCriteriaGen: 'goal_criteria_gen',diff --git a/packages/database/src/models/__tests__/expertise.test.ts b/packages/database/src/models/__tests__/expertise.test.tsindex df72b79bcc2..d574644dfab 100644--- a/packages/database/src/models/__tests__/expertise.test.ts+++ b/packages/database/src/models/__tests__/expertise.test.ts@@ -3,6 +3,7 @@ import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../core/getTestDB';+import { ExpertiseRuleRepository } from '../../repositories/expertiseRules';import {agents,expertiseBindings,@@ -11,8 +12,11 @@ import {expertiseInsights,expertiseLessons,expertiseRuns,+ projects,topics,users,+ verifyCheckResults,+ verifyRuns,workspaces,} from '../../schemas';import type { LobeChatDatabase } from '../../type';@@ -308,4 +312,833 @@ describe('ExpertiseModel', () => {expect(insights.map(({ id }) => id)).toEqual([workspaceOneInsightId]);expect(foreignInsight.status).toBe('active');});+ const seedRuleGroup = async () => {+ const otherUserId = 'expertise-rules-other-user';+ await serverDB.insert(users).values({ id: otherUserId });+ await serverDB.insert(expertiseDomains).values([+ {+ anchorChosenAt: new Date(),+ domainFilter: '交付标准',+ id: 'rules-domain',+ slug: 'rules-domain',+ title: '我的交付审美',+ userId,+ },+ {+ anchorChosenAt: new Date(),+ domainFilter: '设计体系',+ id: 'rules-domain-2',+ slug: 'rules-domain-2',+ title: 'LobeHub 设计体系',+ userId,+ },+ {+ anchorChosenAt: new Date(),+ domainFilter: '别人的标准',+ id: 'rules-foreign-domain',+ slug: 'rules-foreign-domain',+ title: 'Foreign rules',+ userId: otherUserId,+ },+ ]);+ await serverDB.insert(expertiseBindings).values([+ { boundUserId: userId, domainId: 'rules-domain', sortOrder: 0 },+ { boundUserId: userId, domainId: 'rules-domain-2', sortOrder: 1 },+ { boundUserId: otherUserId, domainId: 'rules-foreign-domain' },+ ]);+ await serverDB.insert(expertiseLessons).values([+ {+ code: 'P-01',+ domainId: 'rules-domain',+ exampleCount: 1,+ hitCount: 2,+ hitRunCount: 5,+ id: '0d3e1a5c-6f52-4c2e-8f2a-9f2d3f26b101',+ polarity: 'rule',+ sections: [{ body: '颜色取自设计系统变量', key: 'rule' }],+ sortOrder: 1,+ title: '颜色取自设计系统变量',+ },+ {+ code: 'P-02',+ domainId: 'rules-domain',+ exampleCount: 3,+ hitCount: 7,+ hitRunCount: 9,+ id: '0d3e1a5c-6f52-4c2e-8f2a-9f2d3f26b102',+ polarity: 'rule',+ sections: [{ body: '证据要拍成功路径', key: 'rule' }],+ sortOrder: 0,+ title: '证据要拍成功路径',+ },+ {+ code: 'P-01',+ domainId: 'rules-foreign-domain',+ id: '0d3e1a5c-6f52-4c2e-8f2a-9f2d3f26b103',+ polarity: 'rule',+ sections: [{ body: 'Foreign rule', key: 'rule' }],+ title: 'Foreign rule',+ },+ ]);+ return {+ first: '0d3e1a5c-6f52-4c2e-8f2a-9f2d3f26b102',+ second: '0d3e1a5c-6f52-4c2e-8f2a-9f2d3f26b101',+ };+ };++ it("lists the rules in the owner's own groups, in the owner's order", async () => {+ await seedRuleGroup();++ const groups = await new ExpertiseModel(serverDB, userId).listRules();++ expect(groups.map((g) => g.domain.title)).toEqual(['我的交付审美', 'LobeHub 设计体系']);+ // The reviewer's own order, not hit count: they said the order matters.+ expect(groups[0].rules.map(({ code }) => code)).toEqual(['P-02', 'P-01']);+ expect(groups[0].rules[0].enforcement).toBe('remind');+ expect(groups[0].scopes).toEqual([{ id: userId, kind: 'user', title: null }]);+ });++ it('reads rules from before the columns existed as unplaced reminders', async () => {+ const { first, second } = await seedRuleGroup();+ await serverDB.insert(expertiseLessons).values({+ code: 'P-03',+ domainId: 'rules-domain',+ enforcement: null,+ id: '0d3e1a5c-6f52-4c2e-8f2a-9f2d3f26b104',+ polarity: 'rule',+ sections: [{ body: '旧规矩', key: 'rule' }],+ sortOrder: null,+ title: '旧规矩',+ });++ const [group] = await new ExpertiseModel(serverDB, userId).listRules();++ // Null sorts after every placed rule rather than jumping to the top.+ expect(group.rules.map(({ id }) => id)).toEqual([+ first,+ second,+ '0d3e1a5c-6f52-4c2e-8f2a-9f2d3f26b104',+ ]);+ expect(group.rules[2].enforcement).toBe('remind');+ });++ it('lists groups distilled from a project, but not agent self-learning domains', async () => {+ await seedRuleGroup();+ await serverDB.insert(agents).values({ id: 'rules-agent', userId });+ await serverDB.insert(projects).values({+ coordinatorAgentId: 'rules-agent',+ id: 'rules-project',+ identifier: 'LOBE',+ name: 'lobehub',+ userId,+ });+ await serverDB.insert(expertiseDomains).values([+ {+ anchorChosenAt: new Date(),+ domainFilter: '项目里的打回',+ id: 'project-domain',+ slug: 'project-domain',+ title: 'lobehub 的规矩',+ userId,+ },+ {+ anchorChosenAt: new Date(),+ domainFilter: '智能体专长',+ id: 'agent-domain',+ slug: 'agent-domain',+ title: '智能体专长',+ userId,+ },+ ]);+ await serverDB.insert(expertiseBindings).values([+ { domainId: 'project-domain', projectId: 'rules-project' },+ { agentId: 'rules-agent', domainId: 'agent-domain' },+ ]);++ const groups = await new ExpertiseModel(serverDB, userId).listRules();++ expect(groups.map((g) => g.domain.title)).toContain('lobehub 的规矩');+ expect(groups.map((g) => g.domain.title)).not.toContain('智能体专长');+ expect(groups.find((g) => g.domain.id === 'project-domain')?.scopes).toEqual([+ { id: 'rules-project', kind: 'project', title: 'lobehub' },+ ]);+ });++ it('files a hand-written rule at the top of its group with the next code', async () => {+ await seedRuleGroup();+ const model = new ExpertiseModel(serverDB, userId);++ const created = await model.createRule({+ domainId: 'rules-domain',+ enforcement: 'block',+ limits: ' ',+ title: '次要操作收进「…」',+ why: '主行只留一个操作',+ });++ expect(created?.code).toBe('P-03');+ const [group] = await model.listRules();+ expect(group.rules.map(({ code }) => code)).toEqual(['P-03', 'P-02', 'P-01']);+ expect(group.rules[0]).toMatchObject({+ createdByUserId: userId,+ enforcement: 'block',+ reasonKind: 'taste',+ reasonSource: 'reviewer',+ sections: [+ { body: '次要操作收进「…」', key: 'rule' },+ { body: '主行只留一个操作', key: 'why' },+ ],+ });+ // A foreign group is not a place the caller can write into.+ expect(await model.createRule({ domainId: 'rules-foreign-domain', title: 'x' })).toBeNull();+ });++ it('versions a rewording but not a switch flip', async () => {+ const { first } = await seedRuleGroup();+ const model = new ExpertiseModel(serverDB, userId);++ await new ExpertiseRuleRepository(serverDB, userId).updateRule(first, {+ enforcement: 'block',+ reasonKind: 'mechanism',+ });+ let lesson = await model.findLesson(first);+ expect(lesson).toMatchObject({+ currentRevision: 1,+ enforcement: 'block',+ reasonKind: 'mechanism',+ });++ await new ExpertiseRuleRepository(serverDB, userId).updateRule(first, {+ sections: { limits: '被验的就是报错态本身时除外' },+ title: '证据要拍成功路径本身',+ });+ lesson = await model.findLesson(first);+ expect(lesson?.title).toBe('证据要拍成功路径本身');+ expect(lesson?.currentRevision).toBe(2);+ expect(lesson?.sections).toEqual([+ { body: '证据要拍成功路径本身', key: 'rule' },+ { body: '被验的就是报错态本身时除外', key: 'limits' },+ ]);+ const revisions = await model.listLessonRevisions(first);+ expect(revisions).toHaveLength(1);+ expect(revisions[0]).toMatchObject({ changedBy: 'user', kind: 'user-feedback', revision: 2 });+ });++ it('numbers revisions from the row, and a switch flip never writes one back', async () => {+ const { first } = await seedRuleGroup();+ const rules = new ExpertiseRuleRepository(serverDB, userId);+ const model = new ExpertiseModel(serverDB, userId);+ await rules.updateRule(first, { title: '第二版' });+ await rules.updateRule(first, { title: '第三版' });++ await rules.updateRule(first, { enforcement: 'block' });+ expect((await model.findLesson(first))?.currentRevision).toBe(3);++ await expect(rules.updateRule(first, { title: '第四版' })).resolves.toMatchObject({+ revision: 4,+ });+ });++ it('keeps both of two concurrent edits to different sections', async () => {+ const { first } = await seedRuleGroup();+ const rules = new ExpertiseRuleRepository(serverDB, userId);++ // Two members save different sections of the same rule at the same moment.+ const results = await Promise.all([+ rules.updateRule(first, { sections: { why: '截图要能复现' } }),+ rules.updateRule(first, { sections: { limits: '报错态本身除外' } }),+ ]);++ expect(results.map((r) => r?.revision).sort()).toEqual([2, 3]);+ const lesson = await new ExpertiseModel(serverDB, userId).findLesson(first);+ expect(lesson?.currentRevision).toBe(3);+ expect(lesson?.sections).toEqual(+ expect.arrayContaining([+ { body: '截图要能复现', key: 'why' },+ { body: '报错态本身除外', key: 'limits' },+ ]),+ );+ });++ it("tells a member which edits to a shared rule were a teammate's", async () => {+ const teammate = 'expertise-rules-editor-teammate';+ const workspaceId = 'rules-editor-workspace';+ await serverDB.insert(users).values({ id: teammate });+ await serverDB+ .insert(workspaces)+ .values({ id: workspaceId, name: 'Team', primaryOwnerId: userId, slug: 'rules-editor-team' });+ await serverDB.insert(expertiseDomains).values({+ anchorChosenAt: new Date(),+ domainFilter: '团队规矩',+ id: 'edited-domain',+ slug: 'edited-domain',+ title: '团队规矩',+ userId,+ visibility: 'public',+ workspaceId,+ });+ const lesson = '0d3e1a5c-6f52-4c2e-8f2a-9f2d3f26b107';+ await serverDB.insert(expertiseLessons).values({+ code: 'P-01',+ domainId: 'edited-domain',+ id: lesson,+ polarity: 'rule',+ sections: [{ body: '共享规矩', key: 'rule' }],+ title: '共享规矩',+ });++ await new ExpertiseRuleRepository(serverDB, teammate, workspaceId).updateRule(lesson, {+ title: '队友改过的规矩',+ });++ const [mine] = await new ExpertiseModel(serverDB, userId, workspaceId).listLessonRevisions(+ lesson,+ );+ const [theirs] = await new ExpertiseModel(serverDB, teammate, workspaceId).listLessonRevisions(+ lesson,+ );+ expect(mine.byViewer).toBe(false);+ expect(mine).not.toHaveProperty('changedByUserId');+ expect(theirs.byViewer).toBe(true);+ });++ it("does not name a teammate's private agent among a shared group's mounts", async () => {+ const teammate = 'expertise-rules-mount-teammate';+ const workspaceId = 'rules-mount-workspace';+ await serverDB.insert(users).values({ id: teammate });+ await serverDB+ .insert(workspaces)+ .values({ id: workspaceId, name: 'Team', primaryOwnerId: userId, slug: 'rules-mount-team' });+ await serverDB.insert(agents).values([+ {+ id: 'teammate-private-agent',+ title: '队友的私有助手',+ userId: teammate,+ visibility: 'private',+ workspaceId,+ },+ {+ id: 'teammate-public-agent',+ title: '团队助手',+ userId: teammate,+ visibility: 'public',+ workspaceId,+ },+ ]);+ await serverDB.insert(expertiseDomains).values({+ anchorChosenAt: new Date(),+ domainFilter: '团队规矩',+ id: 'mounted-domain',+ slug: 'mounted-domain',+ title: '团队规矩',+ userId,+ workspaceId,+ });+ await serverDB.insert(expertiseBindings).values([+ { boundWorkspaceId: workspaceId, domainId: 'mounted-domain', sortOrder: 0 },+ { agentId: 'teammate-private-agent', domainId: 'mounted-domain', sortOrder: 1 },+ { agentId: 'teammate-public-agent', domainId: 'mounted-domain', sortOrder: 2 },+ ]);++ const [group] = await new ExpertiseModel(serverDB, userId, workspaceId).listRules();++ expect(group.scopes).toEqual([+ { id: workspaceId, kind: 'workspace', title: null },+ { id: 'teammate-public-agent', kind: 'agent', title: '团队助手' },+ ]);+ });++ it("moves one rule within its group from the server's own order", async () => {+ const { first, second } = await seedRuleGroup();+ const model = new ExpertiseModel(serverDB, userId);++ // Seeded order is [second, first]; move `first` to the top.+ await model.reorderRule('rules-domain', first, second);+ expect((await model.listRules())[0].rules.map(({ id }) => id)).toEqual([first, second]);++ // And back to the end.+ await model.reorderRule('rules-domain', first, null);+ expect((await model.listRules())[0].rules.map(({ id }) => id)).toEqual([second, first]);++ // A rule from another group cannot be pulled in through this group.+ expect(+ await model.reorderRule('rules-domain', '0d3e1a5c-6f52-4c2e-8f2a-9f2d3f26b103', null),+ ).toBeNull();+ const [foreign] = await serverDB+ .select({ domainId: expertiseLessons.domainId, sortOrder: expertiseLessons.sortOrder })+ .from(expertiseLessons)+ .where(eq(expertiseLessons.id, '0d3e1a5c-6f52-4c2e-8f2a-9f2d3f26b103'));+ expect(foreign).toEqual({ domainId: 'rules-foreign-domain', sortOrder: 0 });+ });++ it("keeps a hand-written rule marked as the reviewer's after it starts being hit", async () => {+ await seedRuleGroup();+ const model = new ExpertiseModel(serverDB, userId);+ const created = await model.createRule({ domainId: 'rules-domain', title: '主行只留一个操作' });+ await serverDB+ .update(expertiseLessons)+ .set({ hitCount: 3, hitRunCount: 2 })+ .where(eq(expertiseLessons.id, created!.id));++ const [group] = await model.listRules();+ expect(group.rules.find((r) => r.id === created!.id)?.authored).toBe(true);+ // Distilled rules (no author) are never marked as the reviewer's own.+ expect(group.rules.filter((r) => r.id !== created!.id).every((r) => !r.authored)).toBe(true);+ });++ const seedHitOn = async (lessonId: string) => {+ await serverDB.insert(expertiseRuns).values({+ actorId: 'agent-1',+ actorType: 'agent',+ domainId: 'rules-domain',+ id: runId,+ runIndex: 1,+ subjectId: 'x',+ subjectType: 'standalone',+ userId,+ });+ await serverDB.insert(expertiseHits).values({+ domainId: 'rules-domain',+ example: '你应该用 cssVar 的吧',+ id: hitId,+ lessonId,+ outcome: 'violation',+ runId,+ });+ };++ it('moves an unencumbered rule in place with a fresh code', async () => {+ const { first } = await seedRuleGroup();+ const model = new ExpertiseModel(serverDB, userId);++ expect(await model.moveRule(first, 'rules-domain-2')).toEqual({+ domainId: 'rules-domain-2',+ id: first,+ });++ const groups = await model.listRules();+ expect(groups[0].rules.map(({ id }) => id)).not.toContain(first);+ expect(groups[1].rules.map(({ code, id }) => ({ code, id }))).toEqual([+ { code: 'P-01', id: first },+ ]);+ });++ it('re-files a rule with evidence as a copy that still reads its sources', async () => {+ const { first } = await seedRuleGroup();+ await seedHitOn(first);+ const model = new ExpertiseModel(serverDB, userId);++ const moved = await model.moveRule(first, 'rules-domain-2');+ expect(moved?.id).not.toBe(first);++ const groups = await model.listRules();+ // The original is hidden, not archived: it moved, it did not stop applying.+ expect(groups.flatMap((g) => g.rules.map(({ id }) => id))).not.toContain(first);+ expect(groups[1].rules[0]).toMatchObject({+ code: 'P-01',+ hitCount: 7,+ id: moved!.id,+ title: '证据要拍成功路径',+ });+ expect((await model.listLessonSources(moved!.id)).map(({ example }) => example)).toEqual([+ '你应该用 cssVar 的吧',+ ]);+ expect(await model.findLesson(first)).toMatchObject({+ rejectedReason: `moved-to:${moved!.id}`,+ status: 'rejected',+ });+ });++ it('refuses to fold into, or restore, a rule a merge already accounted for', async () => {+ const { first, second } = await seedRuleGroup();+ const model = new ExpertiseModel(serverDB, userId);+ await new ExpertiseRuleRepository(serverDB, userId).mergeRules(second, first);++ // The source now lives inside the target; restoring it would count its history twice.+ expect(await model.restoreLesson(second)).toBeNull();+ expect(await model.findLesson(second)).toMatchObject({ status: 'retired' });++ // An archived rule is not a merge target: nothing would be left in force.+ const third = '0d3e1a5c-6f52-4c2e-8f2a-9f2d3f26b105';+ await serverDB.insert(expertiseLessons).values({+ code: 'P-03',+ domainId: 'rules-domain',+ id: third,+ polarity: 'rule',+ sections: [{ body: '第三条', key: 'rule' }],+ title: '第三条',+ });+ expect(+ await new ExpertiseRuleRepository(serverDB, userId).mergeRules(third, second),+ ).toBeNull();+ expect(await model.findLesson(third)).toMatchObject({ status: 'active' });+ expect(await model.findLesson(first)).toMatchObject({ hitCount: 9 });+ });++ it('counts a run both rules were proven in once after a merge', async () => {+ const { first, second } = await seedRuleGroup();+ await serverDB.insert(expertiseRuns).values([+ {+ actorId: 'agent-1',+ actorType: 'agent',+ domainId: 'rules-domain',+ id: runId,+ runIndex: 1,+ subjectId: 'x',+ subjectType: 'standalone',+ userId,+ },+ {+ actorId: 'agent-1',+ actorType: 'agent',+ domainId: 'rules-domain',+ id: 'd3f9b0c6-6d0e-4f2e-9b1a-2c4d5e6f7a01',+ runIndex: 2,+ subjectId: 'y',+ subjectType: 'standalone',+ userId,+ },+ ]);+ // Both rules were hit in the same run, and `first` once more in another one.+ await serverDB.insert(expertiseHits).values([+ { domainId: 'rules-domain', lessonId: first, outcome: 'violation', runId },+ { domainId: 'rules-domain', lessonId: second, outcome: 'violation', runId },+ {+ domainId: 'rules-domain',+ lessonId: first,+ outcome: 'violation',+ runId: 'd3f9b0c6-6d0e-4f2e-9b1a-2c4d5e6f7a01',+ },+ ]);+ const model = new ExpertiseModel(serverDB, userId);++ await new ExpertiseRuleRepository(serverDB, userId).mergeRules(second, first);++ expect((await model.findLesson(first))?.hitRunCount).toBe(2);+ });++ it('keeps the exclusion a group was opened with', async () => {+ const model = new ExpertiseModel(serverDB, userId);+ const id = await model.createRuleGroup({+ gate: '只对本仓库成立吗?',+ outOfScope: '和仓库无关的交付审美',+ title: 'OSS 工程规范',+ });++ const [group] = await model.listRules();+ expect(group.domain).toMatchObject({ id, outOfScope: '和仓库无关的交付审美' });++ await model.updateRuleGroup(id, { outOfScope: null });+ const [cleared] = await model.listRules();+ expect(cleared.domain.outOfScope).toBeNull();+ });++ it('keeps the evidence of a rule merged twice over', async () => {+ const { first, second } = await seedRuleGroup();+ await seedHitOn(second);+ const third = '0d3e1a5c-6f52-4c2e-8f2a-9f2d3f26b105';+ await serverDB.insert(expertiseLessons).values({+ code: 'P-03',+ domainId: 'rules-domain',+ id: third,+ polarity: 'rule',+ sections: [{ body: '第三条', key: 'rule' }],+ title: '第三条',+ });+ const model = new ExpertiseModel(serverDB, userId);++ await new ExpertiseRuleRepository(serverDB, userId).mergeRules(second, first);+ await new ExpertiseRuleRepository(serverDB, userId).mergeRules(first, third);++ // The hit sits on the grandparent of `third`; one level of lineage would lose it.+ expect((await model.listLessonSources(third)).map(({ example }) => example)).toEqual([+ '你应该用 cssVar 的吧',+ ]);+ });++ it("does not show a teammate's private round behind a shared rule", async () => {+ const teammate = 'expertise-rules-teammate';+ const workspaceId = 'rules-workspace';+ await serverDB.insert(users).values({ id: teammate });+ await serverDB+ .insert(workspaces)+ .values({ id: workspaceId, name: 'Team', primaryOwnerId: userId, slug: 'rules-team' });+ await serverDB.insert(expertiseDomains).values({+ anchorChosenAt: new Date(),+ domainFilter: '团队规矩',+ id: 'shared-domain',+ slug: 'shared-domain',+ title: '团队规矩',+ userId,+ workspaceId,+ });+ const lesson = '0d3e1a5c-6f52-4c2e-8f2a-9f2d3f26b106';+ await serverDB.insert(expertiseLessons).values({+ code: 'P-01',+ domainId: 'shared-domain',+ id: lesson,+ polarity: 'rule',+ sections: [{ body: '共享规矩', key: 'rule' }],+ title: '共享规矩',+ });+ await serverDB.insert(expertiseRuns).values({+ actorId: 'agent-1',+ actorType: 'agent',+ domainId: 'shared-domain',+ id: runId,+ runIndex: 1,+ subjectId: 'x',+ subjectType: 'standalone',+ userId,+ workspaceId,+ });+ const privateRun = 'b3f9b0c6-6d0e-4f2e-9b1a-2c4d5e6f7a01';+ const publicRun = 'b3f9b0c6-6d0e-4f2e-9b1a-2c4d5e6f7a02';+ await serverDB.insert(verifyRuns).values([+ { id: privateRun, userId: teammate, visibility: 'private', workspaceId },+ { id: publicRun, userId: teammate, visibility: 'public', workspaceId },+ ]);+ const [privateCheck, publicCheck] = await serverDB+ .insert(verifyCheckResults)+ .values([+ {+ checkItemId: 'chk-private',+ checkItemTitle: '私有轮次的检查项',+ userDecision: 'rejected',+ userId: teammate,+ verifierType: 'llm',+ verifyRunId: privateRun,+ workspaceId,+ },+ {+ checkItemId: 'chk-public',+ checkItemTitle: '公开轮次的检查项',+ userDecision: 'rejected',+ userId: teammate,+ verifierType: 'llm',+ verifyRunId: publicRun,+ workspaceId,+ },+ ])+ .returning({ id: verifyCheckResults.id });+ await serverDB.insert(expertiseHits).values([+ {+ domainId: 'shared-domain',+ lessonId: lesson,+ outcome: 'violation',+ runId,+ sourceCheckResultId: privateCheck.id,+ },+ {+ domainId: 'shared-domain',+ lessonId: lesson,+ outcome: 'violation',+ runId,+ sourceCheckResultId: publicCheck.id,+ },+ ]);++ // Hits whose round is not linked: one from the teammate's run, one from the viewer's own.+ const teammateRun = 'b3f9b0c6-6d0e-4f2e-9b1a-2c4d5e6f7a09';+ await serverDB.insert(expertiseRuns).values({+ actorId: 'agent-2',+ actorType: 'agent',+ domainId: 'shared-domain',+ id: teammateRun,+ runIndex: 2,+ subjectId: 'z',+ subjectType: 'standalone',+ userId: teammate,+ workspaceId,+ });+ await serverDB.insert(expertiseHits).values([+ {+ domainId: 'shared-domain',+ example: '队友私下的原话',+ lessonId: lesson,+ outcome: 'violation',+ runId: teammateRun,+ },+ {+ domainId: 'shared-domain',+ example: '我自己的原话',+ lessonId: lesson,+ outcome: 'violation',+ runId,+ },+ ]);++ const sources = await new ExpertiseModel(serverDB, userId, workspaceId).listLessonSources(+ lesson,+ );++ expect(sources.map(({ checkTitle }) => checkTitle)).toContain('公开轮次的检查项');+ expect(sources.map(({ checkTitle }) => checkTitle)).not.toContain('私有轮次的检查项');+ expect(sources.map(({ example }) => example)).toContain('我自己的原话');+ expect(sources.map(({ example }) => example)).not.toContain('队友私下的原话');+ });++ it('reuses a group the reviewer already has instead of opening a second one', async () => {+ await seedRuleGroup();+ const model = new ExpertiseModel(serverDB, userId);++ const reused = await model.createRuleGroup({ gate: '别的守门题', title: ' 我的交付审美 ' });+ expect(reused).toBe('rules-domain');++ const opened = await model.createRuleGroup({+ gate: '这条只对本仓库成立吗?',+ title: 'OSS 工程规范',+ });+ expect(opened).not.toBe('rules-domain');++ const groups = await model.listRules();+ // The newly opened group lands after the ones already there, not at the top.+ expect(groups.map((g) => g.domain.title)).toEqual([+ '我的交付审美',+ 'LobeHub 设计体系',+ 'OSS 工程规范',+ ]);+ // The reused group keeps its own gate question; the caller does not get to overwrite it.+ expect(groups[0].domain.domainFilter).toBe('交付标准');+ });++ it('keeps the edit history of a rule re-filed with its evidence', async () => {+ const { first } = await seedRuleGroup();+ await seedHitOn(first);+ const model = new ExpertiseModel(serverDB, userId);+ await new ExpertiseRuleRepository(serverDB, userId).updateRule(first, {+ title: '证据要拍成功路径本身',+ });++ const moved = await model.moveRule(first, 'rules-domain-2');++ expect(moved?.id).not.toBe(first);+ expect((await model.listLessonRevisions(moved!.id)).map(({ prevTitle }) => prevTitle)).toEqual([+ '证据要拍成功路径',+ ]);+ });++ it('folds one rule into another and archives the source with a pointer back', async () => {+ const { first, second } = await seedRuleGroup();+ const model = new ExpertiseModel(serverDB, userId);++ await seedHitOn(second);+ await new ExpertiseRuleRepository(serverDB, userId).mergeRules(second, first);++ const target = await model.findLesson(first);+ expect(target).toMatchObject({+ currentRevision: 2,+ exampleCount: 4,+ generalizedFromIds: [second],+ hitCount: 9,+ // Recounted from the hits, not summed: the seeded counters were placeholders.+ hitRunCount: 1,+ });+ const source = await model.findLesson(second);+ expect(source).toMatchObject({ rejectedReason: `merged-into:${first}`, status: 'retired' });+ expect(source?.retiredAt).not.toBeNull();+ const revisions = await model.listLessonRevisions(first);+ expect(revisions[0]).toMatchObject({ feedback: '颜色取自设计系统变量', kind: 'generalize' });+ // The target reads the source's evidence through its lineage; the hit itself did not move.+ expect((await model.listLessonSources(first)).map(({ example }) => example)).toEqual([+ '你应该用 cssVar 的吧',+ ]);+ // Both still come back: the archive is part of the list.+ const [group] = await model.listRules();+ expect(group.rules.map(({ status }) => status)).toEqual(['active', 'retired']);+ });++ it('counts only the rejected rounds no distillation run has read', async () => {+ await serverDB.insert(expertiseDomains).values({+ anchorChosenAt: new Date(),+ domainFilter: '交付标准',+ id: 'backlog-domain',+ slug: 'backlog-domain',+ title: '我的交付标准',+ userId,+ });+ const readRunId = 'a3f9b0c6-6d0e-4f2e-9b1a-2c4d5e6f7a01';+ const unreadRunId = 'a3f9b0c6-6d0e-4f2e-9b1a-2c4d5e6f7a02';+ const acceptedRunId = 'a3f9b0c6-6d0e-4f2e-9b1a-2c4d5e6f7a03';+ await serverDB.insert(verifyRuns).values([+ { id: readRunId, userId },+ { id: unreadRunId, userId },+ { id: acceptedRunId, userId },+ ]);+ await serverDB.insert(verifyCheckResults).values([+ {+ checkItemId: 'chk-read',+ userDecision: 'rejected',+ userId,+ verifierType: 'llm',+ verifyRunId: readRunId,+ },+ {+ checkItemId: 'chk-unread',+ userDecision: 'rejected',+ userId,+ verifierType: 'llm',+ verifyRunId: unreadRunId,+ },+ {+ checkItemId: 'chk-accepted',+ userDecision: 'accepted',+ userId,+ verifierType: 'llm',+ verifyRunId: acceptedRunId,+ },+ ]);+ await serverDB.insert(expertiseRuns).values({+ actorId: userId,+ actorType: 'user',+ domainId: 'backlog-domain',+ id: 'a3f9b0c6-6d0e-4f2e-9b1a-2c4d5e6f7a04',+ reflectionKey: `acceptance:some-acceptance:run:${readRunId}`,+ runIndex: 1,+ subjectId: 'some-topic',+ subjectType: 'topic',+ userId,+ });++ await expect(+ new ExpertiseModel(serverDB, userId).countUndistilledRejectionRounds(),+ ).resolves.toBe(1);+ });++ it('counts the backlog of the scope being viewed only', async () => {+ const workspaceId = 'backlog-workspace';+ await serverDB+ .insert(workspaces)+ .values({ id: workspaceId, name: 'Team', primaryOwnerId: userId, slug: 'backlog-team' });+ const personalRun = 'c3f9b0c6-6d0e-4f2e-9b1a-2c4d5e6f7a01';+ const workspaceRun = 'c3f9b0c6-6d0e-4f2e-9b1a-2c4d5e6f7a02';+ await serverDB.insert(verifyRuns).values([+ { id: personalRun, userId },+ { id: workspaceRun, userId, workspaceId },+ ]);+ await serverDB.insert(verifyCheckResults).values([+ {+ checkItemId: 'chk-personal',+ userDecision: 'rejected',+ userId,+ verifierType: 'llm',+ verifyRunId: personalRun,+ },+ {+ checkItemId: 'chk-workspace',+ userDecision: 'rejected',+ userId,+ verifierType: 'llm',+ verifyRunId: workspaceRun,+ workspaceId,+ },+ ]);++ await expect(+ new ExpertiseModel(serverDB, userId).countUndistilledRejectionRounds(),+ ).resolves.toBe(1);+ await expect(+ new ExpertiseModel(serverDB, userId, workspaceId).countUndistilledRejectionRounds(),+ ).resolves.toBe(1);+ });});diff --git a/packages/database/src/models/expertise.ts b/packages/database/src/models/expertise.tsindex 40c93035f61..fc3ea6f86af 100644--- a/packages/database/src/models/expertise.ts+++ b/packages/database/src/models/expertise.ts@@ -1,10 +1,11 @@import type {ExpertiseAnchorCandidate,ExpertiseCanonEntry,+ ExpertiseEnforcement,ExpertiseLayerDefinition,ExpertiseLessonSection,} from '@lobechat/types';-import { and, asc, desc, eq, inArray, isNotNull, isNull, or, sql } from 'drizzle-orm';+import { and, asc, desc, eq, inArray, isNotNull, isNull, or, type SQL, sql } from 'drizzle-orm';import {agents,@@ -16,7 +17,10 @@ import {expertiseLessonRevisions,expertiseLessons,expertiseRuns,+ projects,topics,+ verifyCheckResults,+ verifyRuns,} from '../schemas';import type { LobeChatDatabase } from '../type';import { idGenerator } from '../utils/idGenerator';@@ -100,7 +104,7 @@ export class ExpertiseModel {/** The caller's always-on domains only — the scope an acceptance without a project falls back to. */listDomainsForOwner = async () => this.listDomainsBoundTo();- private listDomainsBoundTo = async (carrierWhere?: ReturnType<typeof eq>) => {+ private listDomainsBoundTo = async (carrierWhere?: SQL) => {const ownerWhere = this.workspaceId? eq(expertiseBindings.boundWorkspaceId, this.workspaceId): eq(expertiseBindings.boundUserId, this.userId);@@ -125,7 +129,9 @@ export class ExpertiseModel {carrierWhere ? or(carrierWhere, ownerWhere) : ownerWhere,),)- .orderBy(asc(expertiseBindings.sortOrder));+ // Every binding starts at sortOrder 0, so without a tiebreak the order of a reviewer's+ // groups is whatever the planner returns and a newly opened group can jump to the top.+ .orderBy(asc(expertiseBindings.sortOrder), asc(expertiseDomains.createdAt));// One domain may be bound at multiple levels; retain the first binding by sort order.const seen = new Set<string>();@@ -182,6 +188,250 @@ export class ExpertiseModel {.orderBy(asc(expertiseHits.domainId), asc(expertiseRuns.runIndex));};+ /**+ * The reviewer's rules — every always-on domain as a group, with the rules filed in it and+ * where the group takes effect.+ *+ * Reads the same binding arm the distillation writes through, so what this returns is exactly+ * what an acceptance without a project would add to. Rules come back in the reviewer's own+ * order (`sortOrder`, then creation) because they told us the order matters; the page does not+ * re-rank them by hit count.+ */+ listRules = async () => {+ // The reviewer's own groups plus the ones distilled from a project's acceptances, which are+ // bound to that project only. Agent-bound domains are self-learning, not rules, and stay out.+ const bound = await this.listDomainsBoundTo(isNotNull(expertiseBindings.projectId));+ const domainIds = bound.map(({ domain }) => domain.id);+ if (domainIds.length === 0) return [];++ const [lessons, bindings] = await Promise.all([+ this.db+ .select({+ code: expertiseLessons.code,+ compilability: expertiseLessons.compilability,+ createdAt: expertiseLessons.createdAt,+ createdByUserId: expertiseLessons.createdByUserId,+ domainId: expertiseLessons.domainId,+ originRunId: expertiseLessons.originRunId,+ // Rows that predate the column hold null; they have only ever been reminders.+ enforcement: sql<ExpertiseEnforcement>`coalesce(${expertiseLessons.enforcement}, 'remind')`,+ exampleCount: expertiseLessons.exampleCount,+ falsePositiveCount: expertiseLessons.falsePositiveCount,+ generalizedFromIds: expertiseLessons.generalizedFromIds,+ hitCount: expertiseLessons.hitCount,+ hitRunCount: expertiseLessons.hitRunCount,+ id: expertiseLessons.id,+ lastHitAt: expertiseLessons.lastHitAt,+ reasonKind: expertiseLessons.reasonKind,+ reasonSource: expertiseLessons.reasonSource,+ rejectedReason: expertiseLessons.rejectedReason,+ retiredAt: expertiseLessons.retiredAt,+ sections: expertiseLessons.sections,+ sortOrder: expertiseLessons.sortOrder,+ specificity: expertiseLessons.specificity,+ status: expertiseLessons.status,+ tags: expertiseLessons.tags,+ title: expertiseLessons.title,+ })+ .from(expertiseLessons)+ .where(+ and(+ inArray(expertiseLessons.domainId, domainIds),+ // Retired ones are kept and returned: the page files them under an archive the reader+ // can reopen, because "I already told it to stop using this" is itself worth seeing.+ inArray(expertiseLessons.status, ['active', 'retired']),+ ),+ )+ // Unplaced rows (null, from before the column existed) come after the ones the+ // reviewer ordered, oldest first, until a drag writes them an explicit position.+ .orderBy(+ sql`${expertiseLessons.sortOrder} asc nulls last`,+ asc(expertiseLessons.createdAt),+ ),+ this.db+ .select({+ agentId: expertiseBindings.agentId,+ agentTitle: agents.title,+ boundUserId: expertiseBindings.boundUserId,+ boundWorkspaceId: expertiseBindings.boundWorkspaceId,+ domainId: expertiseBindings.domainId,+ projectId: expertiseBindings.projectId,+ projectName: projects.name,+ })+ .from(expertiseBindings)+ .leftJoin(projects, eq(projects.id, expertiseBindings.projectId))+ // A shared group can also be mounted on a teammate's private agent; the viewer may see+ // the group without being allowed to see that agent, its id or its name.+ .leftJoin(+ agents,+ and(+ eq(agents.id, expertiseBindings.agentId),+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, agents),+ ),+ )+ .where(+ and(+ inArray(expertiseBindings.domainId, domainIds),+ eq(expertiseBindings.enabled, true),+ or(isNull(expertiseBindings.agentId), isNotNull(agents.id)),+ ),+ )+ .orderBy(asc(expertiseBindings.sortOrder)),+ ]);++ return bound.map(({ domain }) => ({+ domain: {+ domainFilter: domain.domainFilter,+ id: domain.id,+ outOfScope: domain.outOfScope,+ title: domain.title,+ },+ rules: lessons+ .filter((lesson) => lesson.domainId === domain.id)+ // Written by the reviewer rather than distilled from a run. Hit counts grow as a rule is+ // applied, so provenance is read from where the row came from — same test the lesson+ // reader uses for `taughtByUser`.+ .map(({ originRunId, ...lesson }) => ({+ ...lesson,+ authored: lesson.createdByUserId != null && originRunId == null,+ })),+ scopes: bindings+ .filter((binding) => binding.domainId === domain.id)+ .map((binding) => {+ if (binding.projectId) {+ return { id: binding.projectId, kind: 'project' as const, title: binding.projectName };+ }+ if (binding.agentId) {+ return { id: binding.agentId, kind: 'agent' as const, title: binding.agentTitle };+ }+ return binding.boundWorkspaceId+ ? { id: binding.boundWorkspaceId, kind: 'workspace' as const, title: null }+ : { id: binding.boundUserId!, kind: 'user' as const, title: null };+ }),+ }));+ };++ /**+ * The rejections one rule was distilled from, resolved back to the acceptance they were+ * written in so the reader can reopen the round and see the frame they circled.+ *+ * Evidence never changes hands: a hit stays on the lesson and the run that produced it, because+ * both are pinned to their domain by composite keys. So a rule that absorbed others+ * (`generalizedFromIds`) or was re-filed into another group (`salvagedFromId`) reads its sources+ * through that lineage instead of owning them.+ *+ * `sourceCheckResultId` is nullable by design — a deleted acceptance leaves the rule standing+ * and only breaks the trail — so the joins are left joins and the caller renders an unlinked+ * row rather than dropping the evidence.+ */+ 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)),+ ),+ ),+ )+ .orderBy(desc(expertiseHits.createdAt))+ .limit(limit);+ };++ /**+ * Every lesson whose evidence this one now speaks for: itself, what it absorbed through merges+ * (`generalizedFromIds`) and what it was re-filed from (`salvagedFromId`), followed through as+ * 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+ .select({+ generalizedFromIds: expertiseLessons.generalizedFromIds,+ 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);+ }+ return [...seen];+ };++ /**+ * Rejected rounds no standard has been distilled from yet.+ *+ * Distillation only fires forward — a round is read when the NEXT one lands — so every round+ * rejected before the feature existed stays untouched unless something asks for it. This is+ * that backlog, and it is the only honest number to put on an empty standards page.+ */+ countUndistilledRejectionRounds = async () => {+ const [row] = await this.db+ .select({+ rounds: sql<number>`count(distinct ${verifyCheckResults.verifyRunId})::int`,+ })+ .from(verifyCheckResults)+ .where(+ and(+ eq(verifyCheckResults.userId, this.userId),+ // The page is either the personal view or one workspace's; count only that scope.+ this.workspaceId+ ? eq(verifyCheckResults.workspaceId, this.workspaceId)+ : isNull(verifyCheckResults.workspaceId),+ eq(verifyCheckResults.userDecision, 'rejected'),+ isNotNull(verifyCheckResults.verifyRunId),+ sql`not exists (+ select 1 from ${expertiseRuns}+ where ${expertiseRuns.reflectionKey} like '%:run:' || ${verifyCheckResults.verifyRunId}::text+ )`,+ ),+ );++ return row?.rounds ?? 0;+ };+/*** 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@@ -496,11 +746,26 @@ export class ExpertiseModel {userId: this.userId,workspaceId: this.workspaceId,});+ const carrier = carrierColumns(params.carrier, {+ userId: this.userId,+ workspaceId: this.workspaceId,+ });+ // A new mount goes after the ones already there. Leaving every binding at 0 makes the+ // reviewer's group order depend on the query plan.+ const [carrierColumn, carrierValue] = Object.entries(carrier)[0] as [+ keyof typeof expertiseBindings.$inferInsert,+ string,+ ];+ const [last] = await tx+ .select({ sortOrder: sql<number>`max(${expertiseBindings.sortOrder})` })+ .from(expertiseBindings)+ .where(eq(expertiseBindings[carrierColumn as 'boundUserId'], carrierValue));await tx.insert(expertiseBindings).values({addedByUserId: this.userId,domainId: id,+ sortOrder: (last?.sortOrder ?? -1) + 1,workspaceId: this.workspaceId,- ...carrierColumns(params.carrier, { userId: this.userId, workspaceId: this.workspaceId }),+ ...carrier,});});return id;@@ -580,6 +845,317 @@ export class ExpertiseModel {return { id: lessonId, revision };};+ /**+ * The edits a standard has been through, newest first.+ *+ * `feedback` is the reviewer's own sentence and `changedBy` says whether the edit came from them+ * or from the system generalizing, which is the distinction that makes the history readable.+ */+ listLessonRevisions = async (lessonId: string, limit = 10) => {+ // A rule re-filed into another group is a copy; its earlier edits stay on the row it was+ // copied from. Follow `salvagedFromId` back so the history reads as one rule's. Merged-in+ // rules are not followed: their edits were to a different sentence.+ const chain = [lessonId];+ for (let depth = 0; depth < 16; depth += 1) {+ const [row] = await this.db+ .select({ salvagedFromId: expertiseLessons.salvagedFromId })+ .from(expertiseLessons)+ .innerJoin(expertiseDomains, eq(expertiseDomains.id, expertiseLessons.domainId))+ .where(and(eq(expertiseLessons.id, chain.at(-1)!), this.scopeWhere()))+ .limit(1);+ const previous = row?.salvagedFromId;+ if (!previous || chain.includes(previous)) break;+ chain.push(previous);+ }+ const rows = await this.db+ .select({+ changedBy: expertiseLessonRevisions.changedBy,+ changedByUserId: expertiseLessonRevisions.changedByUserId,+ createdAt: expertiseLessonRevisions.createdAt,+ feedback: expertiseLessonRevisions.feedback,+ id: expertiseLessonRevisions.id,+ kind: expertiseLessonRevisions.kind,+ prevTitle: expertiseLessonRevisions.prevTitle,+ revision: expertiseLessonRevisions.revision,+ })+ .from(expertiseLessonRevisions)+ .innerJoin(expertiseLessons, eq(expertiseLessons.id, expertiseLessonRevisions.lessonId))+ .innerJoin(expertiseDomains, eq(expertiseDomains.id, expertiseLessons.domainId))+ .where(and(inArray(expertiseLessonRevisions.lessonId, chain), this.scopeWhere()))+ .orderBy(desc(expertiseLessonRevisions.revision), desc(expertiseLessonRevisions.createdAt))+ .limit(limit);+ // In a shared group any member can edit; the reader is told whether an edit was theirs, and+ // the other member's id does not leave the server.+ return rows.map(({ changedByUserId, ...row }) => ({+ ...row,+ byViewer: changedByUserId === this.userId,+ }));+ };++ /** Brings a retired standard back into practice. */+ restoreLesson = async (lessonId: string) => {+ const lesson = await this.findLesson(lessonId);+ if (!lesson) return null;+ // A rule archived by a merge already lives on inside its target: its counts were added there+ // and its evidence is read through the target's lineage. Bringing it back would count the+ // same history twice, so it stays archived.+ if (lesson.rejectedReason?.startsWith('merged-into:')) return null;+ await this.db+ .update(expertiseLessons)+ .set({ retiredAt: null, status: 'active', updatedAt: new Date() })+ .where(eq(expertiseLessons.id, lessonId));+ return { id: lessonId };+ };++ /** The next free `P-nn` code inside one domain; codes are unique per domain, not globally. */+ private nextLessonCode = async (+ tx: Pick<LobeChatDatabase, 'select'>,+ domainId: string,+ ): Promise<string> => {+ const codes = await tx+ .select({ code: expertiseLessons.code })+ .from(expertiseLessons)+ .where(eq(expertiseLessons.domainId, domainId));+ const next =+ Math.max(0, ...codes.map(({ code }) => Number(/^P-(\d+)$/.exec(code)?.[1] ?? 0))) + 1;+ return `P-${String(next).padStart(2, '0')}`;+ };++ /**+ * A rule the reviewer writes down themselves, filed at the top of its group so they see it+ * where they just put it. Hand-written rules start as `taste` from the reviewer: nothing has+ * been distilled, so there is no mechanism to claim yet.+ */+ createRule = async (params: {+ compilability?: 'compilable' | 'not-compilable';+ domainId: string;+ enforcement?: ExpertiseEnforcement;+ how?: string;+ limits?: string;+ title: string;+ why?: string;+ }) => {+ const domain = await this.findDomain(params.domainId);+ if (!domain) return null;+ const title = params.title.trim();+ const sections: ExpertiseLessonSection[] = [{ body: title, key: 'rule' }];+ for (const key of ['why', 'how', 'limits'] as const) {+ const body = params[key]?.trim();+ if (body) sections.push({ body, key });+ }++ return this.db.transaction(async (tx) => {+ const code = await this.nextLessonCode(tx, params.domainId);+ const [first] = await tx+ .select({ sortOrder: sql<number>`min(${expertiseLessons.sortOrder})` })+ .from(expertiseLessons)+ .where(eq(expertiseLessons.domainId, params.domainId));+ const [row] = await tx+ .insert(expertiseLessons)+ .values({+ code,+ compilability: params.compilability ?? 'not-compilable',+ createdByUserId: this.userId,+ domainId: params.domainId,+ enforcement: params.enforcement ?? 'remind',+ polarity: 'rule',+ reasonKind: 'taste',+ reasonSource: 'reviewer',+ sections,+ sortOrder: (first?.sortOrder ?? 1) - 1,+ title,+ })+ .returning({ code: expertiseLessons.code, id: expertiseLessons.id });+ return row;+ });+ };++ /**+ * 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, merged+ * counts — stays valid until commit, so a concurrent edit waits instead of being overwritten.+ */+ lockLesson = async (lessonId: string) => {+ const [row] = await this.db+ .select({ lesson: expertiseLessons })+ .from(expertiseLessons)+ .innerJoin(expertiseDomains, eq(expertiseDomains.id, expertiseLessons.domainId))+ .where(and(eq(expertiseLessons.id, lessonId), this.scopeWhere()))+ .for('update', { of: expertiseLessons })+ .limit(1);+ return row?.lesson;+ };++ /** Appends one entry to a lesson's edit history. */+ insertLessonRevision = async (values: typeof expertiseLessonRevisions.$inferInsert) => {+ await this.db.insert(expertiseLessonRevisions).values(values);+ };++ /** Writes fields of one lesson row; `updatedAt` is always refreshed. */+ updateLessonFields = async (+ lessonId: string,+ fields: Partial<typeof expertiseLessons.$inferInsert>,+ ) => {+ await this.db+ .update(expertiseLessons)+ .set({ ...fields, updatedAt: new Date() })+ .where(eq(expertiseLessons.id, lessonId));+ };++ /**+ * Distinct runs a lesson has been proven in across its whole lineage. Runs are "distinct+ * situations", so two merged rules hit in the same delivery count it once.+ */+ countLineageRuns = async (lessonId: string) => {+ const lineage = await this.resolveLineage(lessonId);+ if (lineage.length === 0) return 0;+ const [row] = await this.db+ .select({ runs: sql<number>`count(distinct ${expertiseHits.runId})::int` })+ .from(expertiseHits)+ .where(inArray(expertiseHits.lessonId, lineage));+ return row?.runs ?? 0;+ };++ /**+ * Applies one drag inside a group. Only that group's active rules are renumbered; a rule from+ * elsewhere is refused rather than pulled across, because moving between groups changes the+ * code and goes through `moveRule`.+ */+ reorderRule = async (domainId: string, lessonId: string, beforeId: string | null) => {+ const domain = await this.findDomain(domainId);+ if (!domain) return null;+ return this.db.transaction(async (tx) => {+ // The server's own order, not a list sent by the client: a stale or partial client view+ // cannot scramble the group, and the request stays one id no matter how large it grows.+ const rows = await tx+ .select({ id: expertiseLessons.id, sortOrder: expertiseLessons.sortOrder })+ .from(expertiseLessons)+ .where(and(eq(expertiseLessons.domainId, domainId), eq(expertiseLessons.status, 'active')))+ .orderBy(+ sql`${expertiseLessons.sortOrder} asc nulls last`,+ asc(expertiseLessons.createdAt),+ );+ if (!rows.some((row) => row.id === lessonId)) return null;++ const order = rows.map((row) => row.id).filter((id) => id !== lessonId);+ const at = beforeId ? order.indexOf(beforeId) : -1;+ order.splice(at === -1 ? order.length : at, 0, lessonId);++ const current = new Map(rows.map((row) => [row.id, row.sortOrder]));+ for (const [index, id] of order.entries()) {+ if (current.get(id) === index) continue;+ await tx+ .update(expertiseLessons)+ .set({ sortOrder: index, updatedAt: new Date() })+ .where(eq(expertiseLessons.id, id));+ }+ return { domainId, order };+ });+ };++ /**+ * Files a rule under another of the reviewer's groups, at the end, with a fresh code there.+ *+ * A rule with no evidence simply changes domain. One with evidence cannot: its hits are pinned+ * to the run and domain that produced them, so the rule is re-created in the target group with+ * `salvagedFromId` pointing at the original, and the original is hidden (`rejected`, not+ * archived — it did not stop applying, it moved). The caller gets the id that is now live.+ */+ moveRule = async (lessonId: string, domainId: string) => {+ const [lesson, domain] = await Promise.all([+ this.findLesson(lessonId),+ this.findDomain(domainId),+ ]);+ if (!lesson || !domain) return null;+ if (lesson.domainId === domainId) return { domainId, id: lessonId };++ return this.db.transaction(async (tx) => {+ const code = await this.nextLessonCode(tx, domainId);+ const [last] = await tx+ .select({ sortOrder: sql<number>`max(${expertiseLessons.sortOrder})` })+ .from(expertiseLessons)+ .where(eq(expertiseLessons.domainId, domainId));+ const sortOrder = (last?.sortOrder ?? -1) + 1;+ const [{ hits }] = await tx+ .select({ hits: sql<number>`count(*)::int` })+ .from(expertiseHits)+ .where(eq(expertiseHits.lessonId, lessonId));++ if (hits === 0) {+ await tx+ .update(expertiseLessons)+ .set({ code, domainId, sortOrder, updatedAt: new Date() })+ .where(eq(expertiseLessons.id, lessonId));+ return { domainId, id: lessonId };+ }++ const {+ createdAt: _createdAt,+ id: _id,+ updatedAt: _updatedAt,+ accessedAt: _accessedAt,+ ...carried+ } = lesson;+ const [copy] = await tx+ .insert(expertiseLessons)+ .values({ ...carried, code, domainId, salvagedFromId: lessonId, sortOrder })+ .returning({ id: expertiseLessons.id });+ await tx+ .update(expertiseLessons)+ .set({ rejectedReason: `moved-to:${copy.id}`, status: 'rejected', updatedAt: new Date() })+ .where(eq(expertiseLessons.id, lessonId));+ return { domainId, id: copy.id };+ });+ };++ /**+ * A group the reviewer opens by hand. It is a plain always-on domain: the gate question is the+ * domain filter, and it mounts on the reviewer themselves so every acceptance without a project+ * can add to it.+ *+ * A name the reviewer already uses returns that group instead of opening a second one. The+ * drafting model proposes a group name without seeing which ones already exist in every case,+ * and two groups with the same name on one page are indistinguishable to the reader.+ */+ createRuleGroup = async (params: { gate: string; outOfScope?: string; title: string }) => {+ const title = params.title.trim();+ const existing = await this.listDomainsForOwner();+ const match = existing.find(+ ({ domain }) => domain.title.trim().toLowerCase() === title.toLowerCase(),+ );+ if (match) return match.domain.id;++ return this.createDomain({+ brief: title,+ carrier: { type: 'user' },+ domainFilter: params.gate,+ outOfScope: params.outOfScope,+ title,+ });+ };++ /** Renames a group; the gate question can be changed the same way. */+ updateRuleGroup = async (+ domainId: string,+ patch: { gate?: string; outOfScope?: string | null; title?: string },+ ) => {+ const domain = await this.findDomain(domainId);+ if (!domain) return null;+ const title = patch.title?.trim();+ const gate = patch.gate?.trim();+ await this.db+ .update(expertiseDomains)+ .set({+ ...(title && { title }),+ ...(gate && { domainFilter: gate }),+ // Empty clears the exclusion; undefined leaves it alone.+ ...(patch.outOfScope !== undefined && { outOfScope: patch.outOfScope?.trim() || null }),+ updatedAt: new Date(),+ })+ .where(eq(expertiseDomains.id, domainId));+ return { id: domainId };+ };+/** Retires a lesson so it stops being practiced; the record and its evidence are kept. */retireLesson = async (lessonId: string) => {const lesson = await this.findLesson(lessonId);diff --git a/packages/database/src/repositories/expertiseRules/index.ts b/packages/database/src/repositories/expertiseRules/index.tsnew file mode 100644index 00000000000..dcfb3beb520--- /dev/null+++ b/packages/database/src/repositories/expertiseRules/index.ts@@ -0,0 +1,154 @@+import type {+ ExpertiseEnforcement,+ ExpertiseLessonSection,+ ExpertiseReasonKind,+} from '@lobechat/types';++import { ExpertiseModel } from '../../models/expertise';+import type { LobeChatDatabase } from '../../type';++export type RuleSectionPatch = Partial<Record<'rule' | 'why' | 'how' | 'limits', string | null>>;++export interface UpdateRulePatch {+ compilability?: 'compilable' | 'not-compilable';+ enforcement?: ExpertiseEnforcement;+ reasonKind?: ExpertiseReasonKind;+ sections?: RuleSectionPatch;+ title?: string;+}++/**+ * Cross-table write flows for the reviewer's rules. A versioned edit and a merge each write the+ * lesson row and its edit history together, so they run as one transaction here and compose the+ * single-table pieces on {@link ExpertiseModel}. Reads and single-table writes stay on the model.+ */+export class ExpertiseRuleRepository {+ constructor(+ private readonly db: LobeChatDatabase,+ private readonly userId: string,+ private readonly workspaceId?: string,+ ) {}++ private inTransaction = <T>(run: (model: ExpertiseModel) => Promise<T>) =>+ this.db.transaction((tx) =>+ run(new ExpertiseModel(tx as LobeChatDatabase, this.userId, this.workspaceId)),+ );++ /**+ * Field-level edits from the rule document. Wording and body edits are versioned like a+ * conversational correction — same table, same `user-feedback` kind — so the history reads as+ * one list whether the reviewer typed a sentence or rewrote a paragraph. Switches (enforcement,+ * compilability, reason kind) are not versioned: they are settings, not judgments.+ */+ updateRule = async (lessonId: string, patch: UpdateRulePatch) =>+ this.inTransaction(async (model) => {+ // The patch is applied to the row as it is now, not as this request first read it: two+ // members saving different sections at once must both keep their edit.+ const lesson = await model.lockLesson(lessonId);+ if (!lesson) return null;++ const title = patch.title?.trim();+ const titleChanged = Boolean(title) && title !== lesson.title;++ let sections = lesson.sections;+ let sectionsChanged = false;+ if (patch.sections) {+ sections = lesson.sections.filter((section) => !(section.key in patch.sections!));+ for (const [key, body] of Object.entries(patch.sections)) {+ const text = body?.trim();+ if (text) sections.push({ body: text, key: key as ExpertiseLessonSection['key'] });+ }+ sectionsChanged = true;+ }+ // The rule sentence and the title are the same words seen from two places.+ if (titleChanged && !patch.sections?.rule) {+ sections = [+ { body: title!, key: 'rule' as const },+ ...sections.filter((section) => section.key !== 'rule'),+ ];+ sectionsChanged = true;+ }++ const versioned = titleChanged || sectionsChanged;+ const revision = versioned ? lesson.currentRevision + 1 : lesson.currentRevision;+ if (versioned) {+ await model.insertLessonRevision({+ changedBy: 'user',+ changedByUserId: this.userId,+ feedback: titleChanged+ ? title!+ : (Object.values(patch.sections ?? {})+ .find(Boolean)+ ?.trim() ?? null),+ kind: 'user-feedback',+ lessonId,+ prevTitle: titleChanged ? lesson.title : null,+ revision,+ sections,+ });+ }+ await model.updateLessonFields(lessonId, {+ ...(patch.compilability && { compilability: patch.compilability }),+ ...(patch.enforcement && { enforcement: patch.enforcement }),+ ...(patch.reasonKind && { reasonKind: patch.reasonKind }),+ ...(titleChanged && { title }),+ ...(sectionsChanged && { sections }),+ // A switch flip is not a revision and never writes the number back.+ ...(versioned && { currentRevision: revision }),+ });+ return { id: lessonId, revision };+ });++ /**+ * 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 the+ * source is retired with a pointer back. Nothing is deleted — the archived source still opens+ * and still says where it went.+ */+ mergeRules = async (fromId: string, intoId: string) => {+ if (fromId === intoId) return null;+ return this.inTransaction(async (model) => {+ // Both rows are read under a lock, in a fixed order so two merges of the same pair cannot+ // deadlock, and the counts are summed from what they hold now.+ const locked = new Map<string, Awaited<ReturnType<ExpertiseModel['lockLesson']>>>();+ for (const id of [fromId, intoId].sort()) locked.set(id, await model.lockLesson(id));+ const from = locked.get(fromId);+ const into = locked.get(intoId);+ if (!from || !into) return null;+ // Folding into an archived rule would leave neither rule in force.+ if (from.status !== 'active' || into.status !== 'active') return null;++ const revision = into.currentRevision + 1;+ // The evidence stays where it is; `generalizedFromIds` is how the target reads it.+ await model.insertLessonRevision({+ changedBy: 'user',+ changedByUserId: this.userId,+ feedback: from.title,+ kind: 'generalize',+ lessonId: intoId,+ prevTitle: null,+ revision,+ sections: into.sections,+ });+ await model.updateLessonFields(intoId, {+ currentRevision: revision,+ exampleCount: into.exampleCount + from.exampleCount,+ falsePositiveCount: into.falsePositiveCount + from.falsePositiveCount,+ generalizedFromIds: [...(into.generalizedFromIds ?? []), fromId],+ hitCount: into.hitCount + from.hitCount,+ lastHitAt:+ from.lastHitAt && (!into.lastHitAt || from.lastHitAt > into.lastHitAt)+ ? from.lastHitAt+ : into.lastHitAt,+ });+ // Recount over the merged lineage instead of adding the two counters.+ await model.updateLessonFields(intoId, { hitRunCount: await model.countLineageRuns(intoId) });+ await model.updateLessonFields(fromId, {+ rejectedReason: `merged-into:${intoId}`,+ retiredAt: new Date(),+ status: 'retired',+ });+ return { fromId, intoId, revision };+ });+ };+}diff --git a/packages/locales/src/default/electron.ts b/packages/locales/src/default/electron.tsindex 151600d7b06..5eb6c8a4d36 100644--- a/packages/locales/src/default/electron.ts+++ b/packages/locales/src/default/electron.ts@@ -21,6 +21,7 @@ export default {'navigation.memoryIdentities': 'Memory - Identities','navigation.document': 'Document','navigation.memoryPreferences': 'Memory - Preferences',+ 'navigation.memoryRules': 'Memory - Rules','navigation.newChat': 'New Chat','navigation.noPages': 'No pages yet','navigation.onboarding': 'Onboarding',diff --git a/packages/locales/src/default/labs.ts b/packages/locales/src/default/labs.tsindex a7ddf3b6b3f..1c879910f1b 100644--- a/packages/locales/src/default/labs.ts+++ b/packages/locales/src/default/labs.ts@@ -45,6 +45,9 @@ export default {'Show the Integrations settings page: connect the GitHub App so merged pull requests accept deliveries and failing checks or reviews reach the agent that opened them. Hidden by default.','features.integrations.title': 'Integrations','features.inputMarkdown.title': 'Input Markdown Rendering',+ 'features.memoryRules.desc':+ 'Adds "My rules" under Memory: the delivery rules distilled from the acceptance rounds you sent back, with ordering, grouping and block / remind controls.',+ 'features.memoryRules.title': 'My rules','features.messageTextSelectionActions.desc':'Show a quick action when selecting text in chat messages so the selected text can be added to the next conversation context.','features.messageTextSelectionActions.title': 'Message Text Selection Actions',diff --git a/packages/locales/src/default/memory.ts b/packages/locales/src/default/memory.tsindex 7d3d38caa59..6dde9739022 100644--- a/packages/locales/src/default/memory.ts+++ b/packages/locales/src/default/memory.ts@@ -98,11 +98,166 @@ export default {'purge.error': 'Failed to purge memories. Please try again.','purge.success': 'All memories have been deleted.','purge.title': 'Purge All Memories',+ 'rules.actions.archive': 'Archive',+ 'rules.actions.edit': 'Reword',+ 'rules.actions.editGate': 'Change the gate question…',+ 'rules.actions.merge': 'Merge into…',+ 'rules.actions.move': 'Move to…',+ 'rules.actions.newGroup': 'New group…',+ 'rules.actions.renameGroup': 'Rename',+ 'rules.actions.restore': 'Put back to work',+ 'rules.actions.write': 'Write one',+ 'rules.actions.writeHere': 'Write one in this group',+ 'rules.archived.at': 'Archived {{time}}',+ 'rules.archived.byYou': 'archived by you',+ 'rules.archived.group': 'Archived ({{count}})',+ 'rules.archived.mergedInto': 'merged into "{{title}}"',+ 'rules.backlog': '{{count}} rejected rounds have not been read yet',+ 'rules.columns.code': 'No.',+ 'rules.columns.enforcement': 'Effect',+ 'rules.columns.method': 'Check',+ 'rules.columns.rule': 'Rule',+ 'rules.columns.runs': 'Checked',+ '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.describeTitle': 'Write a rule',+ 'rules.compose.enforcementBlock': 'Block · will hold the delivery (not in effect yet)',+ 'rules.compose.enforcementRemind': 'Remind · nudges the agent only',+ 'rules.compose.generateFailed': 'Could not draft it. Fill it in yourself.',+ 'rules.compose.generating': 'Drafting the rule…',+ 'rules.compose.generatingFields': 'Working out why, an example and the limits…',+ 'rules.compose.generatingGroup': 'Picking a group…',+ 'rules.compose.generatingTitle': 'Putting it in one sentence…',+ 'rules.compose.how': 'What counts as breaking it (optional)',+ 'rules.compose.limits': 'When it does not apply (optional)',+ 'rules.compose.needGroup': 'Pick a group before saving.',+ 'rules.compose.newGroupProposed': 'New group: {{title}}',+ 'rules.compose.next': 'Draft it',+ 'rules.compose.noGroup': 'Choose a group',+ 'rules.compose.reviewStep': 'Check the draft, change anything, then save',+ 'rules.compose.scope': 'applies to {{scopes}}',+ 'rules.compose.submit': 'Save',+ 'rules.compose.titlePlaceholder': 'The rule in one sentence',+ 'rules.compose.why': 'Why it matters (optional)',+ 'rules.empty.description':+ 'Rules grow out of the checks you send back — the reason you wrote, and the spot you circled.',+ 'rules.empty.title': 'No rules yet',+ 'rules.empty.write': 'Or write one first',+ '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',+ 'rules.enforcement.remind': 'Remind',+ 'rules.enforcement.remindDesc': 'Nudges the agent only; never holds a delivery',+ 'rules.enforcement.remindHint': 'Remind: nudges the agent only. Click to switch to block',+ 'rules.enforcement.tasteWarning':+ 'This one rests on your judgement with nothing hard to check against, so blocking on it may misfire.',+ 'rules.exception.placeholder':+ 'Say in one sentence where it does not apply, e.g. "spacing inside charts does not count".',+ 'rules.exception.submit': 'Add exception',+ 'rules.field.cancel': 'Cancel',+ 'rules.field.check': 'How it is checked',+ 'rules.field.checkPending':+ 'No check code yet. It appears here once the compiler turns this rule into a check item.',+ 'rules.field.edit': 'Edit',+ 'rules.field.how': 'For example',+ 'rules.field.howEmpty': 'No examples yet.',+ 'rules.field.limits': 'When it does not apply',+ 'rules.field.limitsEmpty': 'No boundary given by the reviewer.',+ 'rules.field.save': 'Save',+ 'rules.field.why': 'Why',+ 'rules.field.whyEmpty': 'No reason written yet.',+ 'rules.group.back': 'Back',+ 'rules.group.blank': 'Fill it in myself',+ 'rules.group.describePlaceholder':+ 'Say what this group is for, e.g. "engineering rules for open-source repos".',+ 'rules.group.empty': 'Nothing in this group yet.',+ 'rules.group.gate': 'Gate question: {{gate}}',+ 'rules.group.gateLabel': 'Gate question — the one to ask before a rule goes in',+ 'rules.group.gatePlaceholder':+ 'e.g. Strip the page and task names; does this still hold for any delivery?',+ 'rules.group.generateFailed': 'Could not draft it. Fill it in yourself.',+ 'rules.group.generating': 'Drafting the group…',+ 'rules.group.nameLabel': 'Group name',+ 'rules.group.newTitle': 'New group',+ 'rules.group.next': 'Draft it',+ 'rules.group.outOfScopeLabel': 'What does not belong here (optional)',+ 'rules.group.outOfScopePlaceholder':+ 'e.g. general delivery taste that has nothing to do with the repository',+ 'rules.group.renameTitle': 'Rename group',+ 'rules.group.reviewStep': 'Check the name and the gate question, then create',+ 'rules.group.scope': '· applies to {{scopes}}',+ 'rules.group.submitCreate': 'Create',+ 'rules.group.submitRename': 'Save',+ 'rules.labOff.description':+ 'Turn it on under Settings → Labs to see the delivery rules distilled from the rounds you sent back.',+ 'rules.labOff.open': 'Open Labs',+ 'rules.labOff.title': 'My rules is still in the lab',+ 'rules.merge.banner':+ 'Click the rule to merge into — "{{title}}" will be archived and its sources and counts move over.',+ 'rules.merge.cancel': 'Cancel',+ 'rules.meta.enforcement': 'Effect',+ 'rules.meta.method': 'Check',+ 'rules.meta.origin': 'Origin',+ 'rules.meta.reason': 'Basis',+ 'rules.meta.runs': 'Checked',+ 'rules.meta.scope': 'Applies to',+ 'rules.method.compilable': 'Program-assisted',+ 'rules.method.compiled': 'By program',+ 'rules.method.not-compilable': 'By judgement',+ 'rules.origin.authored': 'You wrote it',+ 'rules.origin.distilled': 'You sent {{hits}} rounds back over this',+ '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.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.revisions.bySystem': 'by the system',+ 'rules.revisions.byTeammate': 'by a teammate',+ 'rules.revisions.byYou': 'by you',+ 'rules.revisions.generalize': 'Merged in "{{title}}"',+ 'rules.revisions.prevTitle': 'Was "{{title}}"',+ 'rules.revisions.title': 'Edits',+ 'rules.runs.count': '{{count}}×',+ 'rules.runs.detail': 'Checked {{runs}} times, caught {{hits}}',+ 'rules.runs.none': 'Not checked yet',+ 'rules.runs.overruled': 'you overruled it {{count}} times',+ 'rules.saveFailed': 'Could not save that change. The page now shows what is actually saved.',+ 'rules.scope.agent': 'agent {{title}}',+ 'rules.scope.project': 'project {{title}}',+ 'rules.scope.user': 'all your runs',+ 'rules.scope.workspace': 'the whole workspace',+ 'rules.severity.high': 'severe',+ 'rules.severity.low': 'minor',+ 'rules.severity.mid': 'moderate',+ '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.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.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.title': 'My rules','tab.activities': 'Activities','tab.contexts': 'Contexts','tab.home': 'Home','tab.identities': 'Identities','tab.preferences': 'Preferences',+ 'tab.rules': 'Rules','tab.search': 'Search','viewMode.masonry': 'Masonry','viewMode.timeline': 'Timeline',diff --git a/packages/prompts/src/chains/expertise.ts b/packages/prompts/src/chains/expertise.tsindex 8014ecd2d69..97651f82437 100644--- a/packages/prompts/src/chains/expertise.ts+++ b/packages/prompts/src/chains/expertise.ts@@ -113,6 +113,123 @@ export const chainExpertiseDomainDraft = ({],});+export const EXPERTISE_RULE_DRAFT_PROMPT_VERSION = 'v2';++/**+ * One rule drafted from whatever the reviewer typed or pasted: a sentence, a paragraph, or a+ * whole document. The schema mirrors the editable fields of a lesson row so the review step can+ * show every field and let the reviewer change any of them before it is written.+ */+export const EXPERTISE_RULE_DRAFT_JSON_SCHEMA = {+ name: 'expertise_rule_draft',+ schema: {+ additionalProperties: false,+ properties: {+ compilability: { enum: ['compilable', 'not-compilable'], type: 'string' },+ 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'],+ },+ title: { maxLength: 120, type: 'string' },+ why: { type: ['string', 'null'] },+ },+ required: [+ 'compilability',+ 'enforcement',+ 'groupId',+ 'how',+ 'limits',+ 'newGroup',+ 'title',+ 'why',+ ],+ type: 'object',+ },+} as const satisfies ExpertiseGenerateObjectSchema;++const EXPERTISE_RULE_DRAFT_SYSTEM_PROMPT = `You turn what a reviewer wrote — one sentence, a paragraph, or a pasted document — into ONE delivery rule they will hold every future delivery to.++Return:+- title: the rule as one imperative sentence in the reviewer's own voice, 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 reviewer gave 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 reviewer set no boundary;+- enforcement: "block" only when the reviewer clearly wants deliveries held until fixed (words like must, never, reject, block, 必须, 不许, 打回); 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.++If the input is a long document, extract the single most important rule it states; do not summarise the document. Never invent requirements the reviewer did not express. Write every human-facing field in the language the reviewer used.`;++interface ExpertiseRuleDraftChainInput {+ brief: string;+ groups: { gate: string; id: string; title: string }[];+}++export const chainExpertiseRuleDraft = ({+ brief,+ groups,+}: ExpertiseRuleDraftChainInput): { messages: OpenAIChatMessage[] } => ({+ messages: [+ { content: EXPERTISE_RULE_DRAFT_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.',+ `What the reviewer wrote:\n${brief.trim()}`,+ ].join('\n\n'),+ role: 'user',+ },+ ],+});++export const EXPERTISE_RULE_GROUP_DRAFT_PROMPT_VERSION = 'v1';++/** A group is a name and the gate question a rule must pass to be filed under it. */+export const EXPERTISE_RULE_GROUP_DRAFT_JSON_SCHEMA = {+ name: 'expertise_rule_group_draft',+ schema: {+ additionalProperties: false,+ properties: {+ gate: { type: 'string' },+ outOfScope: { type: ['string', 'null'] },+ title: { maxLength: 40, type: 'string' },+ },+ required: ['gate', 'outOfScope', 'title'],+ type: 'object',+ },+} as const satisfies ExpertiseGenerateObjectSchema;++const EXPERTISE_RULE_GROUP_DRAFT_SYSTEM_PROMPT = `A reviewer is opening a group to file their delivery rules under. From what they wrote, return:+- title: a short name for the group, 2 to 6 words, in the reviewer's language;+- gate: the one question to ask of a rule before filing it here, phrased so a yes means it belongs (for example: "Strip the page and task names — does this still hold for any delivery?");+- outOfScope: one sentence on what does not belong here, or null.++Keep the reviewer's intent; do not widen the group beyond what they described.`;++export const chainExpertiseRuleGroupDraft = ({+ brief,+}: {+ brief: string;+}): { messages: OpenAIChatMessage[] } => ({+ messages: [+ { content: EXPERTISE_RULE_GROUP_DRAFT_SYSTEM_PROMPT, role: 'system' },+ { content: brief.trim(), role: 'user' },+ ],+});+export const EXPERTISE_TOPIC_INGESTION_PROMPT_VERSION = 'v2';export const EXPERTISE_TOPIC_INGESTION_JSON_SCHEMA = {diff --git a/packages/types/src/user/preference.ts b/packages/types/src/user/preference.tsindex 21d2331ab6e..8f8baa60a06 100644--- a/packages/types/src/user/preference.ts+++ b/packages/types/src/user/preference.ts@@ -206,6 +206,11 @@ export const UserLabSchema = z.object({* enable the project workspace experiment*/enableProjects: z.boolean().optional(),+ /**+ * show the "my rules" page under memory: the delivery rules distilled from rejected+ * acceptance rounds, with ordering, grouping and enforcement controls+ */+ enableMemoryRules: z.boolean().optional(),/*** show the per-agent self-learning (expertise) page and its sidebar entry*/diff --git a/src/features/MemoryRules/ComposeModal.tsx b/src/features/MemoryRules/ComposeModal.tsxnew file mode 100644index 00000000000..f24bbab8093--- /dev/null+++ b/src/features/MemoryRules/ComposeModal.tsx@@ -0,0 +1,424 @@+'use client';++import type { ExpertiseEnforcement } from '@lobechat/types';+import { Flexbox, Icon, TextArea } from '@lobehub/ui';+import {+ ActionIcon,+ Button,+ createModal,+ DropdownMenu,+ Spin,+ Text,+ toast,+ Tooltip,+ useModalContext,+} from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar } from 'antd-style';+import {+ ArrowLeftIcon,+ BellIcon,+ ChevronDownIcon,+ ClipboardCheckIcon,+ FolderIcon,+ FolderPlusIcon,+ PencilLineIcon,+ ShieldCheckIcon,+ XIcon,+} from 'lucide-react';+import { useEffect, useState } from 'react';+import { useTranslation } from 'react-i18next';++import GeneratingBorder from '@/components/GeneratingBorder';+import { expertiseService, type RuleDraft, type RuleGroup } from '@/services/expertise';+import { shinyTextStyles } from '@/styles';++import { composeStyles, type CreatedGroup, createGroupModal } from './GroupModal';+import { useScopeLabel } from './labels';++const styles = createStaticStyles(({ css }) => ({+ chip: css`+ cursor: pointer;++ display: inline-flex;+ gap: 6px;+ align-items: center;++ padding-block: 4px;+ padding-inline: 8px;+ border-radius: ${cssVar.borderRadius};++ font-size: 12.5px;+ color: ${cssVar.colorTextSecondary};++ &:hover {+ background: ${cssVar.colorFillTertiary};+ }+ `,+ field: css`+ font-size: 13px;+ `,+}));++/** What the reviewer can claim; `compiled` is only set by the compiler. */+type Compilability = 'compilable' | 'not-compilable';++interface GroupChoice {+ gate: string;+ id: string;+ scopes: RuleGroup['scopes'];+ title: string;+}++interface ComposeContentProps {+ defaultGroupId?: string;+ groups: RuleGroup[];+ onCreated: (id: string) => void;+}++/**+ * Writing a rule works like creating a goal: say it in a sentence or paste a document, let the+ * model draft the rule and its fields, then correct anything before it is saved. "Write it+ * myself" skips the draft and lands on the same review form.+ */+const ComposeContent = ({+ defaultGroupId,+ groups: initialGroups,+ onCreated,+}: ComposeContentProps) => {+ const { t } = useTranslation('memory');+ const { close } = useModalContext();+ const scopeLabel = useScopeLabel();+ const [step, setStep] = useState<'describe' | 'preparing' | 'review'>('describe');+ const [brief, setBrief] = useState('');+ const [groups, setGroups] = useState<GroupChoice[]>(() =>+ initialGroups.map((group) => ({+ gate: group.domain.domainFilter,+ id: group.domain.id,+ scopes: group.scopes,+ title: group.domain.title,+ })),+ );+ const [groupId, setGroupId] = useState<string | undefined>(defaultGroupId ?? groups[0]?.id);+ const [newGroup, setNewGroup] = useState<RuleDraft['newGroup']>(null);+ const [title, setTitle] = useState('');+ const [why, setWhy] = useState('');+ const [how, setHow] = useState('');+ const [limits, setLimits] = useState('');+ const [enforcement, setEnforcement] = useState<ExpertiseEnforcement>('remind');+ const [compilability, setCompilability] = useState<Compilability>('not-compilable');+ const [busy, setBusy] = useState(false);+ const [tick, setTick] = useState(0);++ const group = groups.find((g) => g.id === groupId);+ const generating = [+ t('rules.compose.generating'),+ t('rules.compose.generatingTitle'),+ t('rules.compose.generatingFields'),+ t('rules.compose.generatingGroup'),+ ];++ useEffect(() => {+ if (step !== 'preparing') return;+ const timer = window.setInterval(() => setTick((n) => n + 1), 2400);+ return () => window.clearInterval(timer);+ }, [step]);++ const draft = async () => {+ const text = brief.trim();+ if (!text) return;+ setStep('preparing');+ try {+ const drafted = await expertiseService.draftRule({+ brief: text,+ groups: groups.map(({ gate, id, title: groupTitle }) => ({ gate, id, title: groupTitle })),+ });+ setTitle(drafted.title);+ setWhy(drafted.why ?? '');+ setHow(drafted.how ?? '');+ setLimits(drafted.limits ?? '');+ setEnforcement(drafted.enforcement);+ setCompilability(drafted.compilability);+ if (drafted.groupId) {+ setGroupId(drafted.groupId);+ setNewGroup(null);+ } else if (drafted.newGroup) {+ setGroupId(undefined);+ setNewGroup(drafted.newGroup);+ }+ } catch (error) {+ console.error('[MemoryRules] rule draft failed:', error);+ setTitle(text.split('\n')[0].slice(0, 120));+ toast.warning(t('rules.compose.generateFailed'));+ }+ setStep('review');+ };++ const addGroup = () =>+ createGroupModal({+ onDone: (created?: CreatedGroup) => {+ if (!created) return;+ setGroups((current) => [...current, { ...created, scopes: [] }]);+ setGroupId(created.id);+ setNewGroup(null);+ },+ });++ const submit = async () => {+ if (!title.trim() || busy) return;+ if (!groupId && !newGroup) {+ toast.warning(t('rules.compose.needGroup'));+ return;+ }+ setBusy(true);+ try {+ const domainId =+ groupId ??+ (await expertiseService.createRuleGroup({ gate: newGroup!.gate, title: newGroup!.title }));+ if (!domainId) return;+ const created = await expertiseService.createRule({+ compilability,+ domainId,+ enforcement,+ how: how.trim() || undefined,+ limits: limits.trim() || undefined,+ title: title.trim(),+ why: why.trim() || undefined,+ });+ if (created) onCreated(created.id);+ close();+ } catch (error) {+ console.error('[MemoryRules] rule save failed:', error);+ toast.error(t('rules.saveFailed'));+ } finally {+ setBusy(false);+ }+ };++ const groupLabel = group+ ? group.title+ : newGroup+ ? t('rules.compose.newGroupProposed', { title: newGroup.title })+ : t('rules.compose.noGroup');++ return (+ <Flexbox+ onKeyDown={(e) => {+ if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {+ e.preventDefault();+ void (step === 'describe' ? draft() : submit());+ }+ }}+ >+ <Flexbox className={composeStyles.head} gap={6}>+ {step === 'review' && (+ <Flexbox horizontal align={'center'} gap={8}>+ <ActionIcon+ icon={ArrowLeftIcon}+ size={'small'}+ title={t('rules.compose.back')}+ onClick={() => setStep('describe')}+ />+ <Text fontSize={12} type={'secondary'}>+ {t('rules.compose.reviewStep')}+ </Text>+ </Flexbox>+ )}+ {step === 'review' ? (+ <input+ autoFocus+ className={composeStyles.title}+ placeholder={t('rules.compose.titlePlaceholder')}+ value={title}+ onChange={(e) => setTitle(e.target.value)}+ />+ ) : (+ <div className={composeStyles.titleStatic}>{t('rules.compose.describeTitle')}</div>+ )}+ {step !== 'review' && (+ <>+ <GeneratingBorder+ className={composeStyles.inputShell}+ generating={step === 'preparing'}+ >+ <textarea+ autoFocus+ className={composeStyles.describe}+ disabled={step === 'preparing'}+ placeholder={t('rules.compose.describePlaceholder')}+ style={{ minHeight: 190 }}+ value={brief}+ onChange={(e) => setBrief(e.target.value)}+ />+ </GeneratingBorder>+ {step === 'preparing' ? (+ <Flexbox horizontal align={'center'} className={composeStyles.status} gap={8}>+ <Spin size={'small'} variant={'network'} />+ <span className={shinyTextStyles.shinyText}>+ {generating[tick % generating.length]}+ </span>+ </Flexbox>+ ) : (+ <Text type={'secondary'}>{t('rules.compose.describeHint')}</Text>+ )}+ </>+ )}+ <ActionIcon className={composeStyles.close} icon={XIcon} onClick={() => close()} />+ </Flexbox>++ {step === 'review' && (+ <Flexbox className={composeStyles.body} gap={14}>+ <Flexbox gap={4}>+ <span className={composeStyles.label}>{t('rules.compose.why')}</span>+ <TextArea+ autoSize={{ maxRows: 6, minRows: 1 }}+ className={styles.field}+ value={why}+ onChange={(e) => setWhy(e.target.value)}+ />+ </Flexbox>+ <Flexbox gap={4}>+ <span className={composeStyles.label}>{t('rules.compose.how')}</span>+ <TextArea+ autoSize={{ maxRows: 6, minRows: 1 }}+ className={styles.field}+ value={how}+ onChange={(e) => setHow(e.target.value)}+ />+ </Flexbox>+ <Flexbox gap={4}>+ <span className={composeStyles.label}>{t('rules.compose.limits')}</span>+ <TextArea+ autoSize={{ maxRows: 6, minRows: 1 }}+ className={styles.field}+ value={limits}+ onChange={(e) => setLimits(e.target.value)}+ />+ </Flexbox>+ </Flexbox>+ )}++ <Flexbox+ horizontal+ align={'center'}+ className={composeStyles.footer}+ gap={8}+ justify={'space-between'}+ >+ <Flexbox horizontal align={'center'} gap={2} wrap={'wrap'}>+ {step === 'review' && (+ <>+ <DropdownMenu+ items={[+ ...groups.map((g) => ({+ key: g.id,+ label: g.title,+ onClick: () => {+ setGroupId(g.id);+ setNewGroup(null);+ },+ })),+ ...(newGroup+ ? [+ {+ key: 'proposed',+ label: t('rules.compose.newGroupProposed', { title: newGroup.title }),+ onClick: () => setGroupId(undefined),+ },+ ]+ : []),+ { type: 'divider' as const },+ {+ icon: <Icon icon={FolderPlusIcon} />,+ key: 'new',+ label: t('rules.actions.newGroup'),+ onClick: addGroup,+ },+ ]}+ >+ <span className={styles.chip}>+ <Icon icon={newGroup && !group ? FolderPlusIcon : FolderIcon} size={13} />+ {groupLabel}+ <Icon icon={ChevronDownIcon} size={12} />+ </span>+ </DropdownMenu>+ <DropdownMenu+ items={[+ {+ key: 'remind',+ label: t('rules.compose.enforcementRemind'),+ onClick: () => setEnforcement('remind'),+ },+ {+ key: 'block',+ label: t('rules.compose.enforcementBlock'),+ onClick: () => setEnforcement('block'),+ },+ ]}+ >+ <span className={styles.chip}>+ <Icon icon={enforcement === 'block' ? ShieldCheckIcon : BellIcon} size={13} />+ {t(+ enforcement === 'block'+ ? 'rules.enforcement.block'+ : 'rules.enforcement.remind',+ )}+ <Icon icon={ChevronDownIcon} size={12} />+ </span>+ </DropdownMenu>+ <DropdownMenu+ items={(['compilable', 'not-compilable'] as const).map((value) => ({+ key: value,+ label: t(`rules.method.${value}`),+ onClick: () => setCompilability(value),+ }))}+ >+ <span className={styles.chip}>+ <Icon icon={ClipboardCheckIcon} size={13} />+ {t(`rules.method.${compilability}`)}+ <Icon icon={ChevronDownIcon} size={12} />+ </span>+ </DropdownMenu>+ {group && group.scopes.length > 0 && (+ <Tooltip title={t('rules.group.gate', { gate: group.gate })}>+ <span className={styles.chip} style={{ cursor: 'default' }}>+ {t('rules.compose.scope', { scopes: scopeLabel(group.scopes) })}+ </span>+ </Tooltip>+ )}+ </>+ )}+ </Flexbox>+ <Flexbox horizontal align={'center'} gap={4}>+ {step === 'describe' && (+ <Button+ icon={<Icon icon={PencilLineIcon} />}+ style={{ color: cssVar.colorTextTertiary }}+ type={'text'}+ onClick={() => setStep('review')}+ >+ {t('rules.compose.blank')}+ </Button>+ )}+ <Button+ disabled={step === 'describe' ? !brief.trim() : !title.trim()}+ loading={busy || step === 'preparing'}+ type={'primary'}+ onClick={() => void (step === 'describe' ? draft() : submit())}+ >+ {step === 'describe' ? t('rules.compose.next') : t('rules.compose.submit')}+ </Button>+ </Flexbox>+ </Flexbox>+ </Flexbox>+ );+};++export const createComposeRuleModal = (props: ComposeContentProps) =>+ createModal({+ content: <ComposeContent {...props} />,+ footer: null,+ maskClosable: false,+ styles: { content: { overflow: 'hidden', padding: 0 } },+ title: null,+ width: 'min(88vw, 720px)',+ });diff --git a/src/features/MemoryRules/DetailPanel.tsx b/src/features/MemoryRules/DetailPanel.tsxnew file mode 100644index 00000000000..5b2c0df9e24--- /dev/null+++ b/src/features/MemoryRules/DetailPanel.tsx@@ -0,0 +1,627 @@+'use client';++import type { ExpertiseEnforcement, ExpertiseReasonKind } from '@lobechat/types';+import { Block, Flexbox, Icon, TextArea } from '@lobehub/ui';+import {+ ActionIcon,+ Button,+ type DropdownItem,+ DropdownMenu,+ SkeletonText,+ Tag,+ Text,+} from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar, cx } from 'antd-style';+import dayjs from 'dayjs';+import {+ ActivityIcon,+ BellIcon,+ ClipboardCheckIcon,+ HistoryIcon,+ type LucideIcon,+ MoreHorizontalIcon,+ PencilIcon,+ ScaleIcon,+ ShieldCheckIcon,+ TargetIcon,+} from 'lucide-react';+import { type ReactNode, useEffect, useState } from 'react';+import { useTranslation } from 'react-i18next';++import RightPanel from '@/features/RightPanel';+import type { RuleGroup, RuleItem, UpdateRuleInput } from '@/services/expertise';++import Field from './Field';+import { useRuleRevisions, useRuleSources } from './hooks';+import {+ appendException,+ mergedIntoId,+ revisionAuthorKey,+ sectionBody,+ useScopeLabel,+} from './labels';++const styles = createStaticStyles(({ css }) => ({+ body: css`+ overflow-y: auto;+ flex: 1;+ padding-block: 4px 24px;+ padding-inline: 28px;+ `,+ foot: css`+ flex: none;+ padding-block: 12px;+ padding-inline: 28px;+ border-block-start: 1px solid ${cssVar.colorBorderSecondary};+ `,+ head: css`+ flex: none;+ padding-block: 24px 0;+ padding-inline: 28px;+ `,+ heading: css`+ display: flex;+ align-items: center;+ justify-content: space-between;++ margin-block: 22px 6px;++ font-size: 12px;+ font-weight: 600;+ color: ${cssVar.colorTextTertiary};+ letter-spacing: 0.02em;+ `,+ kicker: css`+ font-family: ${cssVar.fontFamilyCode};+ font-size: 12px;+ color: ${cssVar.colorTextSecondary};+ `,+ link: css`+ cursor: pointer;++ display: inline-flex;+ gap: 4px;+ align-items: center;++ font-size: 12px;+ color: ${cssVar.colorTextSecondary};+ text-decoration: none;++ &:hover {+ color: ${cssVar.colorText};+ }+ `,+ muted: css`+ font-size: 12px;+ line-height: 1.6;+ color: ${cssVar.colorTextSecondary};+ `,+ properties: css`+ display: flex;+ flex-direction: column;+ gap: 2px;++ margin-block-start: 16px;+ padding-block-end: 16px;+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};+ `,+ property: css`+ width: 100%;+ min-height: 30px;+ padding-block: 5px;+ padding-inline: 8px 10px;+ border-radius: ${cssVar.borderRadius};++ font-size: 13px;+ `,+ propertyLabel: css`+ flex: none;+ width: 44px;+ font-size: 12px;+ color: ${cssVar.colorTextTertiary};+ `,+ propertyStatic: css`+ background: transparent;+ `,+ quote: css`+ margin-block: 6px 0;+ padding-block: 6px;+ padding-inline: 12px 0;+ border-inline-start: 2px solid ${cssVar.colorBorder};++ font-size: 13px;+ line-height: 1.6;+ color: ${cssVar.colorTextSecondary};+ `,+ source: css`+ padding-block: 10px;+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};++ &:last-child {+ border-block-end: none;+ }+ `,+ title: css`+ font-size: 20px;+ font-weight: 600;+ line-height: 1.35;+ text-wrap: pretty;+ `,+ titleInput: css`+ box-sizing: border-box;+ width: 100%;+ padding: 0;+ border: none;++ font-family: inherit;+ font-size: 20px;+ font-weight: 600;+ line-height: 1.35;+ color: inherit;++ background: transparent;+ outline: none;+ `,+ warning: css`+ padding-block: 6px;+ padding-inline: 8px;+ border-radius: ${cssVar.borderRadius};++ font-size: 12px;+ line-height: 1.6;+ color: ${cssVar.colorWarningText};++ background: ${cssVar.colorWarningBg};+ `,+}));++interface PropertyProps {+ children: ReactNode;+ icon: LucideIcon;+ label: string;+ menu?: DropdownItem[];+}++/**+ * One property line, in the shape the task detail uses: a label, an icon, the current value, and+ * a menu behind the click when it can be changed. Read-only lines drop the fill so the eye finds+ * the switches first.+ */+const Property = ({ children, icon, label, menu }: PropertyProps) => {+ const row = (+ <Block+ horizontal+ align={'center'}+ className={cx(styles.property, !menu && styles.propertyStatic)}+ clickable={Boolean(menu)}+ gap={8}+ variant={menu ? 'filled' : 'borderless'}+ >+ <span className={styles.propertyLabel}>{label}</span>+ <Icon color={cssVar.colorTextSecondary} icon={icon} size={14} />+ <Flexbox flex={1} style={{ minWidth: 0 }}>+ {children}+ </Flexbox>+ </Block>+ );+ return menu ? <DropdownMenu items={menu}>{row}</DropdownMenu> : row;+};++interface RuleDocumentProps {+ code: string;+ group?: RuleGroup;+ groups: RuleGroup[];+ menu: DropdownItem[];+ onTitleEditing: (editing: boolean) => void;+ /** Resolves to whether the change was saved. */+ onUpdate: (patch: UpdateRuleInput) => Promise<boolean>;+ rule: RuleItem;+ titleEditing: boolean;+}++/**+ * The rule as a document: the sentence itself as the title (editable in place), its settings as+ * property lines, then the sections a lesson row carries, the evidence it grew from, and the+ * edits it has been through. The exception composer is docked at the foot so a long source list+ * never pushes it out of a short window.+ */+const RuleDocument = ({+ code,+ group,+ groups,+ menu,+ onTitleEditing,+ onUpdate,+ rule,+ titleEditing,+}: RuleDocumentProps) => {+ const { t } = useTranslation('memory');+ const scopeLabel = useScopeLabel();+ const {+ data: sources,+ error: sourcesError,+ isLoading: sourcesLoading,+ mutate: retrySources,+ } = useRuleSources(rule.id);+ const { data: revisions, mutate: mutateRevisions } = useRuleRevisions(rule.id);+ const [exception, setException] = useState('');+ const [titleDraft, setTitleDraft] = useState(rule.title);+ const [busy, setBusy] = useState(false);++ useEffect(() => {+ setTitleDraft(rule.title);+ }, [rule.id, rule.title, titleEditing]);++ const archived = rule.status === 'retired';+ const authored = rule.authored;+ const all = groups.flatMap((g) => g.rules);+ const titleOf = (id: string) => all.find((r) => r.id === id)?.title ?? id;+ const mergedInto = mergedIntoId(rule);++ const save = async (patch: UpdateRuleInput) => {+ if (busy) return false;+ setBusy(true);+ try {+ const saved = await onUpdate(patch);+ if (saved) await mutateRevisions();+ return saved;+ } finally {+ setBusy(false);+ }+ };++ const commitTitle = async () => {+ const next = titleDraft.trim();+ if (!next || next === rule.title) return onTitleEditing(false);+ // Leave edit mode only once the rename is saved; on failure the draft stays to retry.+ if (await save({ title: next })) onTitleEditing(false);+ };++ const addException = () => {+ const text = exception.trim();+ if (!text) return;+ // Keep what they typed if the save did not land.+ void save({ sections: { limits: appendException(sectionBody(rule, 'limits'), text) } }).then(+ (saved) => saved && setException(''),+ );+ };++ const choose = <T extends string>(+ values: readonly T[],+ label: (value: T) => string,+ onPick: (value: T) => void,+ ): DropdownItem[] =>+ values.map((value) => ({ key: value, label: label(value), onClick: () => onPick(value) }));+ const editable = !archived && !busy;++ return (+ <Flexbox height={'100%'} width={'100%'}>+ <div className={styles.head}>+ <Flexbox horizontal align={'flex-start'} gap={8}>+ <div style={{ flex: 1, minWidth: 0 }}>+ <div className={styles.kicker}>+ {code} · {group?.domain.title}+ {rule.tags?.length ? ` · ${rule.tags.join(' / ')}` : ''}+ </div>+ {titleEditing ? (+ <input+ autoFocus+ className={styles.titleInput}+ value={titleDraft}+ onBlur={() => void commitTitle()}+ onChange={(e) => setTitleDraft(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === 'Enter') void commitTitle();+ if (e.key === 'Escape') onTitleEditing(false);+ }}+ />+ ) : (+ <div className={styles.title}>{rule.title}</div>+ )}+ </div>+ {!archived && !titleEditing && (+ <ActionIcon+ icon={PencilIcon}+ size={'small'}+ title={t('rules.actions.edit')}+ onClick={() => onTitleEditing(true)}+ />+ )}+ <DropdownMenu items={menu}>+ <ActionIcon disabled={busy} icon={MoreHorizontalIcon} size={'small'} />+ </DropdownMenu>+ </Flexbox>++ <div className={styles.properties}>+ <Property+ icon={rule.enforcement === 'block' ? ShieldCheckIcon : BellIcon}+ label={t('rules.meta.enforcement')}+ menu={+ editable+ ? choose(+ ['block', 'remind'] as const,+ (value) =>+ t(+ value === 'block'+ ? 'rules.compose.enforcementBlock'+ : 'rules.compose.enforcementRemind',+ ),+ (enforcement: ExpertiseEnforcement) => void save({ enforcement }),+ )+ : undefined+ }+ >+ <Text weight={500}>+ {t(+ rule.enforcement === 'block'+ ? 'rules.enforcement.block'+ : 'rules.enforcement.remind',+ )}+ </Text>+ <span className={styles.muted}>+ {t(+ rule.enforcement === 'block'+ ? 'rules.enforcement.blockDesc'+ : 'rules.enforcement.remindDesc',+ )}+ </span>+ </Property>+ <Property+ icon={ClipboardCheckIcon}+ label={t('rules.meta.method')}+ menu={+ // `compiled` is set by the compiler once a criterion is linked; the reviewer can only+ // say whether a program could check it.+ editable && rule.compilability !== 'compiled'+ ? choose(+ ['compilable', 'not-compilable'] as const,+ (value) => t(`rules.method.${value}`),+ (compilability) => void save({ compilability }),+ )+ : undefined+ }+ >+ <Text weight={500}>{t(`rules.method.${rule.compilability}`)}</Text>+ </Property>+ <Property+ icon={ScaleIcon}+ label={t('rules.meta.reason')}+ menu={+ editable+ ? choose(+ ['mechanism', 'taste'] as const,+ (value) => t(`rules.reason.${value}`),+ (reasonKind: ExpertiseReasonKind) => void save({ reasonKind }),+ )+ : 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>+ </Property>+ {rule.enforcement === 'block' && rule.reasonKind === 'taste' && (+ <div className={styles.warning}>{t('rules.enforcement.tasteWarning')}</div>+ )}+ <Property icon={TargetIcon} label={t('rules.meta.scope')}>+ <span>{group ? scopeLabel(group.scopes) : ''}</span>+ </Property>+ <Property icon={ActivityIcon} label={t('rules.meta.runs')}>+ <span>+ {rule.hitRunCount+ ? t('rules.runs.detail', { hits: rule.hitCount, runs: rule.hitRunCount })+ : t('rules.runs.none')}+ {rule.falsePositiveCount > 0 && (+ <span className={styles.muted}>+ {' · '}+ {t('rules.runs.overruled', { count: rule.falsePositiveCount })}+ </span>+ )}+ </span>+ </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() })+ : '')}+ </span>+ {Boolean(rule.generalizedFromIds?.length) && (+ <span className={styles.muted}>+ {t('rules.origin.generalizedFrom', {+ titles: rule.generalizedFromIds!.map(titleOf).join('」「'),+ })}+ </span>+ )}+ {rule.specificity === 'over-specific' && (+ <span className={styles.muted}>{t('rules.origin.overSpecific')}</span>+ )}+ {rule.specificity === 'one-off' && (+ <span className={styles.muted}>{t('rules.origin.oneOff')}</span>+ )}+ {archived && (+ <span className={styles.muted}>+ {t('rules.archived.at', {+ time: dayjs(rule.retiredAt ?? undefined).format('YYYY-MM-DD'),+ })}+ {' · '}+ {mergedInto+ ? t('rules.archived.mergedInto', { title: titleOf(mergedInto) })+ : t('rules.archived.byYou')}+ </span>+ )}+ </Property>+ </div>+ </div>++ <div className={styles.body}>+ <Field+ editable={!archived}+ label={t('rules.field.why')}+ placeholder={t('rules.field.whyEmpty')}+ value={sectionBody(rule, 'why')}+ onSave={(why) => save({ sections: { why: why || null } })}+ />+ <Field+ editable={!archived}+ label={t('rules.field.how')}+ placeholder={t('rules.field.howEmpty')}+ value={sectionBody(rule, 'how')}+ onSave={(how) => save({ sections: { how: how || null } })}+ />+ <Field+ editable={!archived}+ label={t('rules.field.limits')}+ placeholder={t('rules.field.limitsEmpty')}+ value={sectionBody(rule, 'limits')}+ onSave={(next) => save({ sections: { limits: next || null } })}+ />+ <Field+ muted+ label={`${t('rules.field.check')} · ${t(`rules.method.${rule.compilability}`)}`}+ placeholder={t('rules.field.checkPending')}+ />++ <div className={styles.heading}>+ <span>{t('rules.sources.title')}</span>+ </div>+ {/* "No sources" is only said once the list has actually come back empty; loading and a+ failed request each say what they are, so nothing reads as lost evidence. */}+ {sourcesLoading && !sources ? (+ <SkeletonText rows={2} />+ ) : sourcesError && !sources ? (+ <Flexbox horizontal align={'center'} gap={8}>+ <span className={styles.muted}>{t('rules.sources.loadFailed')}</span>+ <Button size={'small'} type={'link'} onClick={() => void retrySources()}>+ {t('rules.sources.retry')}+ </Button>+ </Flexbox>+ ) : sources?.length ? (+ sources.map((source) => (+ <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>+ <span style={{ fontSize: 13, fontWeight: 500 }}>+ {source.checkTitle ?? source.where ?? ''}+ </span>+ </Flexbox>+ {source.acceptanceId && (+ <a+ className={styles.link}+ href={`/acceptance/${source.acceptanceId}`}+ rel={'noreferrer'}+ target={'_blank'}+ >+ <Icon icon={ClipboardCheckIcon} size={12} />+ {t('rules.sources.open')}+ </a>+ )}+ </Flexbox>+ {(source.reviewerComment || source.example) && (+ <p className={styles.quote}>{source.reviewerComment || source.example}</p>+ )}+ <div className={styles.muted}>+ {dayjs(source.createdAt).format('YYYY-MM-DD')}+ {source.roundIndex+ ? ` · ${t('rules.sources.round', { index: source.roundIndex })}`+ : ''}+ {source.severity ? ` · ${t(`rules.severity.${source.severity}`)}` : ''}+ {source.userDecision === 'agree' ? ` · ${t('rules.sources.agreed')}` : ''}+ {source.userDecision === 'reject' ? ` · ${t('rules.sources.rejected')}` : ''}+ </div>+ </div>+ ))+ ) : (+ <p className={styles.muted}>+ {t(authored ? 'rules.sources.authoredEmpty' : 'rules.sources.empty')}+ </p>+ )}++ {Boolean(revisions?.length) && (+ <>+ <div className={styles.heading}>+ <span>{t('rules.revisions.title')}</span>+ </div>+ {revisions!.map((revision) => (+ <div key={revision.id} style={{ marginBottom: 10 }}>+ <Text fontSize={13}>+ {revision.kind === 'generalize'+ ? t('rules.revisions.generalize', { title: revision.feedback ?? '' })+ : revision.feedback}+ </Text>+ {revision.prevTitle && (+ <div className={styles.muted}>+ {t('rules.revisions.prevTitle', { title: revision.prevTitle })}+ </div>+ )}+ <div className={styles.muted}>+ {t(revisionAuthorKey(revision))}+ {' · '}+ {dayjs(revision.createdAt).format('YYYY-MM-DD')}+ </div>+ </div>+ ))}+ </>+ )}+ </div>++ {!archived && (+ <Flexbox horizontal align={'flex-end'} className={styles.foot} gap={8}>+ <TextArea+ autoSize={{ maxRows: 4, minRows: 1 }}+ disabled={busy}+ placeholder={t('rules.exception.placeholder')}+ style={{ flex: 1 }}+ value={exception}+ onChange={(e) => setException(e.target.value)}+ onKeyDown={(e) => {+ if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') addException();+ }}+ />+ <Button+ disabled={!exception.trim()}+ loading={busy}+ type={'primary'}+ onClick={addException}+ >+ {t('rules.exception.submit')}+ </Button>+ </Flexbox>+ )}+ </Flexbox>+ );+};++interface DetailPanelProps extends Omit<RuleDocumentProps, 'rule' | 'code'> {+ code?: string;+ onClose: () => void;+ rule?: RuleItem;+}++/**+ * The same draggable right panel the sibling memory surfaces use. Its visibility follows the+ * selection: until a rule is picked there is nothing to show, and an empty column is not worth+ * the width.+ */+const DetailPanel = ({ code, onClose, rule, ...rest }: DetailPanelProps) => (+ <RightPanel+ defaultWidth={440}+ expand={Boolean(rule)}+ maxWidth={760}+ minWidth={380}+ onExpandChange={(next) => !next && onClose()}+ >+ {/* Keyed by rule: every draft in the document belongs to one rule and must not carry over. */}+ {rule ? <RuleDocument code={code ?? ''} key={rule.id} rule={rule} {...rest} /> : null}+ </RightPanel>+);++export default DetailPanel;diff --git a/src/features/MemoryRules/EnforcementToggle.tsx b/src/features/MemoryRules/EnforcementToggle.tsxnew file mode 100644index 00000000000..5a438c1c2cf--- /dev/null+++ b/src/features/MemoryRules/EnforcementToggle.tsx@@ -0,0 +1,41 @@+'use client';++import type { ExpertiseEnforcement } from '@lobechat/types';+import { Icon } from '@lobehub/ui';+import { Tooltip } from '@lobehub/ui/base-ui';+import { cx } from 'antd-style';+import { BellIcon, ShieldCheckIcon } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { styles } from './styles';++interface EnforcementToggleProps {+ disabled?: boolean;+ onChange: (next: ExpertiseEnforcement) => void;+ value: ExpertiseEnforcement;+}++/**+ * The effect column is itself the switch: one click flips block ⇄ remind. It stops the click+ * from reaching the row, so flipping a rule does not also open it.+ */+const EnforcementToggle = ({ disabled, onChange, value }: EnforcementToggleProps) => {+ const { t } = useTranslation('memory');+ const isBlock = value === 'block';+ return (+ <Tooltip title={t(isBlock ? 'rules.enforcement.blockHint' : 'rules.enforcement.remindHint')}>+ <span+ className={cx(styles.modeBtn, isBlock ? styles.modeBlock : styles.modeRemind)}+ onClick={(e) => {+ e.stopPropagation();+ if (!disabled) onChange(isBlock ? 'remind' : 'block');+ }}+ >+ <Icon icon={isBlock ? ShieldCheckIcon : BellIcon} size={13} />+ {t(isBlock ? 'rules.enforcement.block' : 'rules.enforcement.remind')}+ </span>+ </Tooltip>+ );+};++export default EnforcementToggle;diff --git a/src/features/MemoryRules/Field.tsx b/src/features/MemoryRules/Field.tsxnew file mode 100644index 00000000000..14c2cc37dd6--- /dev/null+++ b/src/features/MemoryRules/Field.tsx@@ -0,0 +1,121 @@+'use client';++import { Flexbox, Icon, TextArea } from '@lobehub/ui';+import { Button } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar } from 'antd-style';+import { PencilIcon } from 'lucide-react';+import { useState } from 'react';+import { useTranslation } from 'react-i18next';++const styles = createStaticStyles(({ css }) => ({+ body: css`+ margin: 0;+ font-size: 13.5px;+ line-height: 1.75;+ white-space: pre-wrap;+ `,+ edit: css`+ cursor: pointer;++ display: inline-flex;+ gap: 4px;+ align-items: center;++ font-size: 12px;+ color: ${cssVar.colorTextSecondary};++ &:hover {+ color: ${cssVar.colorText};+ }+ `,+ head: css`+ display: flex;+ align-items: center;+ justify-content: space-between;++ margin-block: 22px 6px;++ font-size: 12px;+ font-weight: 600;+ color: ${cssVar.colorTextTertiary};+ letter-spacing: 0.02em;+ `,+ muted: css`+ color: ${cssVar.colorTextTertiary};+ `,+}));++interface FieldProps {+ editable?: boolean;+ label: string;+ /** Rendered dimmed: a placeholder, or a value that is really the absence of one. */+ muted?: boolean;+ /** Resolves to whether the save landed; the editor stays open with the draft when it did not. */+ onSave?: (value: string) => Promise<boolean>;+ placeholder?: string;+ value?: string;+}++/**+ * One heading of the rule document. Each maps to a column or a section of the lesson row, so+ * editing one never rewrites the others; the structure the distillation produced stays intact.+ */+const Field = ({ editable, label, muted, onSave, placeholder, value }: FieldProps) => {+ const { t } = useTranslation('memory');+ const [editing, setEditing] = useState(false);+ const [draft, setDraft] = useState('');++ return (+ <div>+ <div className={styles.head}>+ <span>{label}</span>+ {editable && !editing && (+ <span+ className={styles.edit}+ onClick={() => {+ setDraft(value ?? '');+ setEditing(true);+ }}+ >+ <Icon icon={PencilIcon} size={12} />+ {t('rules.field.edit')}+ </span>+ )}+ </div>+ {editing ? (+ <Flexbox gap={8}>+ <TextArea+ autoFocus+ autoSize={{ maxRows: 20, minRows: 3 }}+ value={draft}+ onChange={(e) => setDraft(e.target.value)}+ />+ <Flexbox horizontal gap={6} justify={'flex-end'}>+ <Button size={'small'} onClick={() => setEditing(false)}>+ {t('rules.field.cancel')}+ </Button>+ <Button+ size={'small'}+ type={'primary'}+ onClick={async () => {+ if (!onSave) return setEditing(false);+ if (await onSave(draft.trim())) setEditing(false);+ }}+ >+ {t('rules.field.save')}+ </Button>+ </Flexbox>+ </Flexbox>+ ) : (+ <p+ className={styles.body}+ style={muted || !value ? { color: cssVar.colorTextTertiary } : undefined}+ >+ {value || placeholder}+ </p>+ )}+ </div>+ );+};++export default Field;diff --git a/src/features/MemoryRules/GroupModal.tsx b/src/features/MemoryRules/GroupModal.tsxnew file mode 100644index 00000000000..3c6819efc14--- /dev/null+++ b/src/features/MemoryRules/GroupModal.tsx@@ -0,0 +1,293 @@+'use client';++import { Flexbox, Icon, TextArea } from '@lobehub/ui';+import {+ ActionIcon,+ Button,+ createModal,+ Input,+ Spin,+ Text,+ toast,+ useModalContext,+} from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar } from 'antd-style';+import { ArrowLeftIcon, PencilLineIcon, XIcon } from 'lucide-react';+import { useState } from 'react';+import { useTranslation } from 'react-i18next';++import GeneratingBorder from '@/components/GeneratingBorder';+import { expertiseService, type RuleGroup } from '@/services/expertise';+import { shinyTextStyles } from '@/styles';++export const composeStyles = createStaticStyles(({ css }) => ({+ body: css`+ overflow-y: auto;+ max-height: min(70vh, 640px);+ padding-block: 4px 20px;+ padding-inline: 20px;+ `,+ close: css`+ position: absolute;+ inset-block-start: 14px;+ inset-inline-end: 14px;+ `,+ describe: css`+ resize: none;++ width: 100%;+ min-height: 150px;+ padding-block: 14px;+ padding-inline: 16px;+ border: none;++ font: inherit;+ font-size: 14px;+ line-height: 1.7;+ color: inherit;++ background: transparent;+ outline: none;+ `,+ footer: css`+ padding-block: 10px;+ padding-inline: 20px;+ border-block-start: 1px solid ${cssVar.colorBorderSecondary};+ `,+ head: css`+ position: relative;+ padding-block: 16px 8px;+ padding-inline: 20px;+ `,+ inputShell: css`+ overflow: hidden;+ background: ${cssVar.colorBgElevated};+ `,+ label: css`+ font-size: 12px;+ color: ${cssVar.colorTextSecondary};+ `,+ status: css`+ min-height: 32px;+ padding-block: 4px;+ color: ${cssVar.colorTextSecondary};+ `,+ title: css`+ box-sizing: border-box;+ width: 100%;+ padding-block: 4px 8px;+ padding-inline-end: 40px;+ border: none;++ font-family: inherit;+ font-size: 20px;+ font-weight: 600;+ line-height: 1.4;+ color: inherit;++ background: transparent;+ outline: none;+ `,+ titleStatic: css`+ padding-block: 4px 8px;+ padding-inline-end: 40px;++ font-size: 20px;+ font-weight: 600;+ line-height: 1.4;+ color: ${cssVar.colorText};+ `,+}));++export interface CreatedGroup {+ gate: string;+ id: string;+ title: string;+}++interface GroupContentProps {+ /** Present when renaming; absent when opening a new group. */+ group?: RuleGroup;+ onDone: (created?: CreatedGroup) => void;+}++/**+ * Opening a group works like opening a goal: say what it is for, let the model draft the name and+ * the gate question, then correct either before it exists. Renaming skips the draft and lands on+ * the same review form.+ */+const GroupContent = ({ group, onDone }: GroupContentProps) => {+ const { t } = useTranslation('memory');+ const { close } = useModalContext();+ const [step, setStep] = useState<'describe' | 'preparing' | 'review'>(+ group ? 'review' : 'describe',+ );+ const [brief, setBrief] = useState('');+ const [title, setTitle] = useState(group?.domain.title ?? '');+ const [gate, setGate] = useState(group?.domain.domainFilter ?? '');+ // Ingestion reads this literally when deciding which rejections belong, so it is kept.+ const [outOfScope, setOutOfScope] = useState(group?.domain.outOfScope ?? '');+ const [busy, setBusy] = useState(false);+ const ready = Boolean(title.trim() && gate.trim());++ const draft = async () => {+ const text = brief.trim();+ if (!text) return;+ setStep('preparing');+ try {+ const drafted = await expertiseService.draftRuleGroup(text);+ setTitle(drafted.title);+ setGate(drafted.gate);+ setOutOfScope(drafted.outOfScope ?? '');+ } catch (error) {+ console.error('[MemoryRules] group draft failed:', error);+ setTitle(text.slice(0, 40));+ toast.warning(t('rules.group.generateFailed'));+ }+ setStep('review');+ };++ const submit = async () => {+ if (!ready || busy) return;+ setBusy(true);+ try {+ if (group) {+ await expertiseService.updateRuleGroup(group.domain.id, {+ gate: gate.trim(),+ outOfScope: outOfScope.trim() || null,+ title: title.trim(),+ });+ onDone();+ } else {+ const id = await expertiseService.createRuleGroup({+ gate: gate.trim(),+ outOfScope: outOfScope.trim() || undefined,+ title: title.trim(),+ });+ onDone(id ? { gate: gate.trim(), id, title: title.trim() } : undefined);+ }+ close();+ } catch (error) {+ console.error('[MemoryRules] group save failed:', error);+ toast.error(t('rules.saveFailed'));+ } finally {+ setBusy(false);+ }+ };++ return (+ <Flexbox+ onKeyDown={(e) => {+ if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {+ e.preventDefault();+ void (step === 'describe' ? draft() : submit());+ }+ }}+ >+ <Flexbox className={composeStyles.head} gap={6}>+ {step === 'review' && !group && (+ <Flexbox horizontal align={'center'} gap={8}>+ <ActionIcon+ icon={ArrowLeftIcon}+ size={'small'}+ title={t('rules.group.back')}+ onClick={() => setStep('describe')}+ />+ <Text fontSize={12} type={'secondary'}>+ {t('rules.group.reviewStep')}+ </Text>+ </Flexbox>+ )}+ <div className={composeStyles.titleStatic}>+ {t(group ? 'rules.group.renameTitle' : 'rules.group.newTitle')}+ </div>+ {step !== 'review' && (+ <>+ <GeneratingBorder+ className={composeStyles.inputShell}+ generating={step === 'preparing'}+ >+ <textarea+ autoFocus+ className={composeStyles.describe}+ disabled={step === 'preparing'}+ placeholder={t('rules.group.describePlaceholder')}+ value={brief}+ onChange={(e) => setBrief(e.target.value)}+ />+ </GeneratingBorder>+ {step === 'preparing' && (+ <Flexbox horizontal align={'center'} className={composeStyles.status} gap={8}>+ <Spin size={'small'} variant={'network'} />+ <span className={shinyTextStyles.shinyText}>{t('rules.group.generating')}</span>+ </Flexbox>+ )}+ </>+ )}+ <ActionIcon className={composeStyles.close} icon={XIcon} onClick={() => close()} />+ </Flexbox>++ {step === 'review' && (+ <Flexbox className={composeStyles.body} gap={16}>+ <Flexbox gap={6}>+ <span className={composeStyles.label}>{t('rules.group.nameLabel')}</span>+ <Input autoFocus value={title} onChange={(e) => setTitle(e.target.value)} />+ </Flexbox>+ <Flexbox gap={6}>+ <span className={composeStyles.label}>{t('rules.group.gateLabel')}</span>+ <TextArea+ autoSize={{ maxRows: 6, minRows: 2 }}+ placeholder={t('rules.group.gatePlaceholder')}+ value={gate}+ onChange={(e) => setGate(e.target.value)}+ />+ </Flexbox>+ <Flexbox gap={6}>+ <span className={composeStyles.label}>{t('rules.group.outOfScopeLabel')}</span>+ <TextArea+ autoSize={{ maxRows: 4, minRows: 1 }}+ placeholder={t('rules.group.outOfScopePlaceholder')}+ value={outOfScope}+ onChange={(e) => setOutOfScope(e.target.value)}+ />+ </Flexbox>+ </Flexbox>+ )}++ <Flexbox horizontal align={'center'} className={composeStyles.footer} justify={'flex-end'}>+ <Flexbox horizontal align={'center'} gap={4}>+ {step === 'describe' && (+ <Button+ icon={<Icon icon={PencilLineIcon} />}+ style={{ color: cssVar.colorTextTertiary }}+ type={'text'}+ onClick={() => setStep('review')}+ >+ {t('rules.group.blank')}+ </Button>+ )}+ <Button+ disabled={step === 'describe' ? !brief.trim() : !ready}+ loading={busy || step === 'preparing'}+ type={'primary'}+ onClick={() => void (step === 'describe' ? draft() : submit())}+ >+ {step === 'describe'+ ? t('rules.group.next')+ : t(group ? 'rules.group.submitRename' : 'rules.group.submitCreate')}+ </Button>+ </Flexbox>+ </Flexbox>+ </Flexbox>+ );+};++export const createGroupModal = (props: GroupContentProps) =>+ createModal({+ content: <GroupContent {...props} />,+ footer: null,+ maskClosable: false,+ styles: { content: { overflow: 'hidden', padding: 0 } },+ title: null,+ width: 'min(88vw, 560px)',+ });diff --git a/src/features/MemoryRules/GroupSection.tsx b/src/features/MemoryRules/GroupSection.tsxnew file mode 100644index 00000000000..b89e0e1bad4--- /dev/null+++ b/src/features/MemoryRules/GroupSection.tsx@@ -0,0 +1,60 @@+'use client';++import { Flexbox, Icon } from '@lobehub/ui';+import { ActionIcon, type DropdownItem, DropdownMenu, Tooltip } from '@lobehub/ui/base-ui';+import { cx } from 'antd-style';+import { ChevronRightIcon, MoreHorizontalIcon, PlusIcon } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import type { RuleGroup } from '@/services/expertise';++import { useScopeLabel } from './labels';+import { styles } from './styles';++interface GroupSectionProps {+ collapsed: boolean;+ count: number;+ group: RuleGroup;+ menu: DropdownItem[];+ onToggle: () => void;+ onWrite: () => void;+}++/**+ * A Linear-style group row: one line, a hairline running to the edge of the sheet, and two+ * bordered controls that only appear on hover, sitting in the same column as each row's `…`.+ */+const GroupSection = ({ collapsed, count, group, menu, onToggle, onWrite }: GroupSectionProps) => {+ const { t } = useTranslation('memory');+ const scopeLabel = useScopeLabel();++ return (+ <div className={cx(styles.section, collapsed && styles.sectionCollapsed)} onClick={onToggle}>+ <span className={cx(styles.chevron, !collapsed && styles.chevronOpen)}>+ <Icon icon={ChevronRightIcon} size={14} />+ </span>+ <span className={styles.sectionTitle}>{group.domain.title}</span>+ <span className={styles.sectionCount}>{count}</span>+ <span className={styles.sectionScope}>+ {t('rules.group.scope', { scopes: scopeLabel(group.scopes) })}+ </span>+ {!collapsed && <span data-line className={styles.sectionLine} />}+ <span+ data-hover+ className={cx(styles.hover, styles.sectionActions)}+ onClick={(e) => e.stopPropagation()}+ >+ <Flexbox horizontal gap={2}>+ <Tooltip title={t('rules.actions.writeHere')}>+ <ActionIcon icon={PlusIcon} size={'small'} variant={'outlined'} onClick={onWrite} />+ </Tooltip>+ <DropdownMenu items={menu}>+ <ActionIcon icon={MoreHorizontalIcon} size={'small'} variant={'outlined'} />+ </DropdownMenu>+ </Flexbox>+ </span>+ </div>+ );+};++export default GroupSection;diff --git a/src/features/MemoryRules/RuleRow.tsx b/src/features/MemoryRules/RuleRow.tsxnew file mode 100644index 00000000000..ebd570f1db6--- /dev/null+++ b/src/features/MemoryRules/RuleRow.tsx@@ -0,0 +1,103 @@+'use client';++import type { ExpertiseEnforcement } from '@lobechat/types';+import { Flexbox, SortableList } from '@lobehub/ui';+import { ActionIcon, type DropdownItem, DropdownMenu, Tag, Tooltip } from '@lobehub/ui/base-ui';+import { cx } from 'antd-style';+import dayjs from 'dayjs';+import { MoreHorizontalIcon } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import type { RuleItem } from '@/services/expertise';++import EnforcementToggle from './EnforcementToggle';+import { styles } from './styles';++interface RuleRowProps {+ active: boolean;+ /** Where an archived rule went, when it was folded into another one. */+ archivedInto?: string | null;+ code: string;+ menu: DropdownItem[];+ onEnforcement: (next: ExpertiseEnforcement) => void;+ onSelect: () => void;+ rule: RuleItem;+}++/**+ * One line of the sheet. Everything that acts on the row — the drag handle, the effect switch,+ * the `…` menu — stops its click so the row itself only ever opens the document. Rewording+ * happens in the document, not here: a text box inside a table row reads as a glitch.+ */+const RuleRow = ({+ active,+ archivedInto,+ code,+ menu,+ onEnforcement,+ onSelect,+ rule,+}: RuleRowProps) => {+ const { t } = useTranslation('memory');+ const archived = rule.status === 'retired';+ const authored = rule.authored;++ const archivedWhy = archivedInto+ ? t('rules.archived.mergedInto', { title: archivedInto })+ : t('rules.archived.byYou');++ return (+ <SortableList.Item id={rule.id} style={{ padding: 0, width: '100%' }} variant={'borderless'}>+ <div+ className={cx(+ styles.grid,+ styles.row,+ styles.rowHover,+ active && styles.rowActive,+ archived && styles.rowArchived,+ )}+ onClick={onSelect}+ >+ <span data-hover className={styles.hover} onClick={(e) => e.stopPropagation()}>+ {!archived && <SortableList.DragHandle size={'small'} />}+ </span>+ <span className={styles.cellId}>{code}</span>+ <div style={{ minWidth: 0 }}>+ <Flexbox horizontal align={'baseline'} gap={6} wrap={'wrap'}>+ <span className={styles.title}>{rule.title}</span>+ {authored && <Tag size={'small'}>{t('rules.tag.authored')}</Tag>}+ {archived && (+ <span className={styles.muted}>+ {t('rules.archived.at', {+ time: dayjs(rule.retiredAt ?? undefined).format('YYYY-MM-DD'),+ })}+ {' · '}+ {archivedWhy}+ </span>+ )}+ </Flexbox>+ </div>+ <EnforcementToggle disabled={archived} value={rule.enforcement} onChange={onEnforcement} />+ <span className={styles.muted}>{t(`rules.method.${rule.compilability}`)}</span>+ <Tooltip+ title={+ rule.hitRunCount+ ? t('rules.runs.detail', { hits: rule.hitCount, runs: rule.hitRunCount })+ : t('rules.runs.none')+ }+ >+ <span className={styles.muted}>+ {rule.hitRunCount ? t('rules.runs.count', { count: rule.hitRunCount }) : '—'}+ </span>+ </Tooltip>+ <span data-hover className={styles.hover} onClick={(e) => e.stopPropagation()}>+ <DropdownMenu items={menu}>+ <ActionIcon icon={MoreHorizontalIcon} size={'small'} />+ </DropdownMenu>+ </span>+ </div>+ </SortableList.Item>+ );+};++export default RuleRow;diff --git a/src/features/MemoryRules/hooks.ts b/src/features/MemoryRules/hooks.tsnew file mode 100644index 00000000000..3bd9de4e872--- /dev/null+++ b/src/features/MemoryRules/hooks.ts@@ -0,0 +1,17 @@+import { useClientDataSWR } from '@/libs/swr';+import { swrKeys } from '@/libs/swr/keys';+import { expertiseService } from '@/services/expertise';++/** The reviewer's own rules by group, plus the backlog of rejected rounds nothing has read yet. */+export const useRules = () =>+ useClientDataSWR(swrKeys.expertise.rules(), () => expertiseService.listRules());++export const useRuleSources = (lessonId?: string) =>+ useClientDataSWR(lessonId ? swrKeys.expertise.ruleSources(lessonId) : null, () =>+ expertiseService.ruleSources(lessonId!),+ );++export const useRuleRevisions = (lessonId?: string) =>+ useClientDataSWR(lessonId ? swrKeys.expertise.ruleRevisions(lessonId) : null, () =>+ expertiseService.ruleRevisions(lessonId!),+ );diff --git a/src/features/MemoryRules/index.tsx b/src/features/MemoryRules/index.tsxnew file mode 100644index 00000000000..dc2720b3e1c--- /dev/null+++ b/src/features/MemoryRules/index.tsx@@ -0,0 +1,391 @@+'use client';++import { Block, Empty, Flexbox, Icon, SortableList } from '@lobehub/ui';+import { Button, Text, toast } from '@lobehub/ui/base-ui';+import { cx } from 'antd-style';+import { FlaskConicalIcon, PencilIcon, PlusIcon, ScaleIcon } from 'lucide-react';+import { useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import AsyncBoundary from '@/components/AsyncBoundary';+import Loading from '@/components/Loading/BrandTextLoading';+import NavHeader from '@/features/NavHeader';+import WideScreenContainer from '@/features/WideScreenContainer';+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import { expertiseService, type RuleItem, type UpdateRuleInput } from '@/services/expertise';+import { useUserStore } from '@/store/user';+import { labPreferSelectors } from '@/store/user/slices/preference/selectors/labPrefer';++import { createComposeRuleModal } from './ComposeModal';+import DetailPanel from './DetailPanel';+import { createGroupModal } from './GroupModal';+import GroupSection from './GroupSection';+import { useRules } from './hooks';+import { findMove, mergedIntoId } from './labels';+import { buildRuleMenu } from './ruleMenu';+import RuleRow from './RuleRow';+import { styles } from './styles';++const LabOff = () => {+ const { t } = useTranslation('memory');+ const navigate = useWorkspaceAwareNavigate();+ return (+ <Flexbox align={'center'} flex={1} justify={'center'}>+ <Empty+ description={t('rules.labOff.description')}+ icon={FlaskConicalIcon}+ title={t('rules.labOff.title')}+ >+ <Button size={'small'} onClick={() => navigate('/settings/labs')}>+ {t('rules.labOff.open')}+ </Button>+ </Empty>+ </Flexbox>+ );+};++/**+ * The reviewer's rules as one sheet: groups as full-width section rows, rules as draggable lines+ * under them, the archive at the foot, and the selected rule opened as a document on the right.+ *+ * Every write goes through the service and then re-reads the list; only the drag reorder and the+ * effect switch are applied optimistically, because both would visibly snap back otherwise.+ */+const MemoryRules = () => {+ const { t } = useTranslation('memory');+ const enabled = useUserStore(labPreferSelectors.enableMemoryRules);+ const { data, error, isLoading, mutate } = useRules();+ const [selectedId, setSelectedId] = useState<string>();+ const [titleEditing, setTitleEditing] = useState(false);+ const [mergeFrom, setMergeFrom] = useState<string>();+ const [collapsed, setCollapsed] = useState<Record<string, boolean>>({});++ const groups = useMemo(() => data?.groups ?? [], [data]);+ const all = useMemo(() => groups.flatMap((group) => group.rules), [groups]);+ const live = useMemo(() => all.filter((rule) => rule.status === 'active'), [all]);+ const archived = useMemo(() => all.filter((rule) => rule.status === 'retired'), [all]);+ const selected = all.find((rule) => rule.id === selectedId);+ const isEmpty = !isLoading && !error && all.length === 0;++ // Display numbers follow the sheet order, not the per-group `P-nn` codes, which restart in+ // every group and would repeat down the page.+ const codes = useMemo(() => {+ const map = new Map<string, string>();+ let n = 0;+ for (const rule of [...live, ...archived]) map.set(rule.id, `R${String(++n).padStart(2, '0')}`);+ return map;+ }, [live, archived]);++ const refresh = () => mutate();++ const patchLocal = (id: string, patch: Partial<RuleItem>) =>+ mutate(+ (current) =>+ current && {+ ...current,+ groups: current.groups.map((group) => ({+ ...group,+ rules: group.rules.map((rule) => (rule.id === id ? { ...rule, ...patch } : rule)),+ })),+ },+ { revalidate: false },+ );++ // Optimistic writes must not outlive a failed request: re-read the server's truth and say so.+ const recover = async (error: unknown) => {+ console.error('[MemoryRules] write failed:', error);+ toast.error(t('rules.saveFailed'));+ await refresh();+ };++ /** Resolves to whether the change was saved, so callers keep unsaved input on failure. */+ const updateRule = async (id: string, patch: UpdateRuleInput) => {+ try {+ if (patch.enforcement) await patchLocal(id, { enforcement: patch.enforcement });+ await expertiseService.updateRule(id, patch);+ await refresh();+ return true;+ } catch (error) {+ await recover(error);+ return false;+ }+ };++ const reorder = async (domainId: string, items: RuleItem[]) => {+ const previous = (groups.find((group) => group.domain.id === domainId)?.rules ?? [])+ .filter((rule) => rule.status === 'active')+ .map((rule) => rule.id);+ const move = findMove(+ previous,+ items.map((rule) => rule.id),+ );+ if (!move) return;+ await mutate(+ (current) =>+ current && {+ ...current,+ groups: current.groups.map((group) =>+ group.domain.id === domainId+ ? { ...group, rules: [...items, ...group.rules.filter((r) => r.status !== 'active')] }+ : group,+ ),+ },+ { revalidate: false },+ );+ try {+ await expertiseService.reorderRule(domainId, move.id, move.beforeId);+ await refresh();+ } catch (error) {+ await recover(error);+ }+ };++ /** Every list mutation: re-read after it, and on failure say so and show what is saved. */+ const run = async (action: () => Promise<unknown>) => {+ try {+ await action();+ await refresh();+ } catch (error) {+ await recover(error);+ }+ };++ const handlers = {+ archive: (id: string) => void run(() => expertiseService.archiveRule(id)),+ // Rewording opens the document with the title already in edit mode.+ edit: (id: string) => {+ setSelectedId(id);+ setTitleEditing(true);+ },+ merge: (id: string) => setMergeFrom(id),+ move: (id: string, domainId: string) =>+ void run(async () => {+ const moved = await expertiseService.moveRule(id, domainId);+ if (moved && selectedId === id) setSelectedId(moved.id);+ }),+ restore: (id: string) => void run(() => expertiseService.restoreRule(id)),+ };++ const select = (id: string) => {+ setTitleEditing(false);+ if (mergeFrom && mergeFrom !== id) {+ // Only a rule still in force can absorb another; archived rows are not targets.+ if (all.find((rule) => rule.id === id)?.status !== 'active') return;+ const target = id;+ const source = mergeFrom;+ // Leave merge mode whatever the outcome, so a failure does not strand the page in it.+ setMergeFrom(undefined);+ void run(async () => {+ await expertiseService.mergeRules(source, target);+ setSelectedId(target);+ });+ return;+ }+ setSelectedId(selectedId === id ? undefined : id);+ };++ const compose = (defaultGroupId?: string) =>+ createComposeRuleModal({+ defaultGroupId,+ groups,+ onCreated: (id) => {+ setSelectedId(id);+ void refresh();+ },+ });++ const openGroupModal = (group?: (typeof groups)[number]) =>+ createGroupModal({ group, onDone: () => void refresh() });++ const renderRow = (rule: RuleItem) => (+ <RuleRow+ active={rule.id === selectedId}+ code={codes.get(rule.id) ?? ''}+ menu={buildRuleMenu(t, rule, groups, handlers)}+ rule={rule}+ archivedInto={(() => {+ const into = mergedIntoId(rule);+ return into ? (all.find((r) => r.id === into)?.title ?? into) : null;+ })()}+ onEnforcement={(enforcement) => void updateRule(rule.id, { enforcement })}+ onSelect={() => select(rule.id)}+ />+ );++ if (!enabled) {+ return (+ <Flexbox height={'100%'} width={'100%'}>+ <NavHeader />+ <LabOff />+ </Flexbox>+ );+ }++ return (+ <Flexbox height={'100%'} width={'100%'}>+ <NavHeader />+ <Flexbox horizontal flex={1} height={'100%'} width={'100%'}>+ <Flexbox className={styles.body}>+ <WideScreenContainer gap={18} paddingBlock={'24px 96px'}>+ <Flexbox+ horizontal+ align={'flex-start'}+ gap={16}+ justify={'space-between'}+ paddingInline={8}+ >+ <Flexbox gap={4}>+ <Text fontSize={26} weight={700}>+ {t('rules.title')}+ </Text>+ <Text type={'secondary'}>{t('rules.subtitle', { count: live.length })}</Text>+ </Flexbox>+ {/* One primary action. Writing a rule also opens the group when the reviewer has+ none, so a separate "new group" button would be a second way to start. */}+ <Button icon={<Icon icon={PlusIcon} />} type={'primary'} onClick={() => compose()}>+ {t('rules.actions.write')}+ </Button>+ </Flexbox>++ {mergeFrom && (+ <Block gap={4} padding={12} variant={'filled'}>+ <Text fontSize={13}>+ {t('rules.merge.banner', {+ title: all.find((rule) => rule.id === mergeFrom)?.title ?? '',+ })}+ </Text>+ <Flexbox horizontal>+ <Button size={'small'} onClick={() => setMergeFrom(undefined)}>+ {t('rules.merge.cancel')}+ </Button>+ </Flexbox>+ </Block>+ )}++ <AsyncBoundary+ data={data}+ error={error}+ errorVariant={'page'}+ isEmpty={isEmpty}+ isLoading={isLoading}+ loading={<Loading debugId={'MemoryRules'} />}+ empty={+ <Empty+ icon={ScaleIcon}+ title={t('rules.empty.title')}+ description={+ <Flexbox align={'center'} gap={8}>+ <span>{t('rules.empty.description')}</span>+ {Boolean(data?.backlogRounds) && (+ <Text fontSize={13} type={'secondary'}>+ {t('rules.backlog', { count: data!.backlogRounds })}+ </Text>+ )}+ <Button onClick={() => compose()}>{t('rules.empty.write')}</Button>+ </Flexbox>+ }+ />+ }+ onRetry={() => void refresh()}+ >+ <div>+ <div className={cx(styles.grid, styles.thead)}>+ <span />+ <span>{t('rules.columns.code')}</span>+ <span>{t('rules.columns.rule')}</span>+ <span>{t('rules.columns.enforcement')}</span>+ <span>{t('rules.columns.method')}</span>+ <span>{t('rules.columns.runs')}</span>+ <span />+ </div>+ {groups.map((group) => {+ const items = group.rules.filter((rule) => rule.status === 'active');+ const isCollapsed = Boolean(collapsed[group.domain.id]);+ return (+ <div key={group.domain.id}>+ <GroupSection+ collapsed={isCollapsed}+ count={items.length}+ group={group}+ menu={[+ {+ disabled: true,+ key: 'gate',+ label: (+ <span+ className={styles.muted}+ style={{ display: 'block', maxWidth: 280 }}+ >+ {t('rules.group.gate', { gate: group.domain.domainFilter })}+ </span>+ ),+ },+ { type: 'divider' },+ {+ icon: <Icon icon={PencilIcon} />,+ key: 'rename',+ label: t('rules.actions.renameGroup'),+ onClick: () => openGroupModal(group),+ },+ ]}+ onWrite={() => compose(group.domain.id)}+ onToggle={() =>+ setCollapsed((c) => ({ ...c, [group.domain.id]: !c[group.domain.id] }))+ }+ />+ {isCollapsed ? null : items.length === 0 ? (+ <div className={styles.muted} style={{ padding: '10px 8px' }}>+ {t('rules.group.empty')}+ </div>+ ) : (+ <SortableList+ gap={0}+ items={items}+ renderItem={renderRow}+ onChange={(next) => void reorder(group.domain.id, next)}+ />+ )}+ </div>+ );+ })}+ {archived.length > 0 && (+ <>+ <div className={styles.divider}>+ {t('rules.archived.group', { count: archived.length })}+ </div>+ <SortableList+ gap={0}+ items={archived}+ renderItem={renderRow}+ onChange={() => {}}+ />+ </>+ )}+ </div>+ </AsyncBoundary>+ </WideScreenContainer>+ </Flexbox>+ {all.length > 0 && (+ <DetailPanel+ code={selected ? codes.get(selected.id) : undefined}+ group={groups.find((group) => group.domain.id === selected?.domainId)}+ groups={groups}+ menu={selected ? buildRuleMenu(t, selected, groups, handlers) : []}+ rule={selected}+ titleEditing={titleEditing}+ onTitleEditing={setTitleEditing}+ onClose={() => {+ setSelectedId(undefined);+ setTitleEditing(false);+ }}+ onUpdate={(patch) =>+ selected ? updateRule(selected.id, patch) : Promise.resolve(false)+ }+ />+ )}+ </Flexbox>+ </Flexbox>+ );+};++export default MemoryRules;diff --git a/src/features/MemoryRules/labels.test.ts b/src/features/MemoryRules/labels.test.tsnew file mode 100644index 00000000000..1a5801cd902--- /dev/null+++ b/src/features/MemoryRules/labels.test.ts@@ -0,0 +1,57 @@+import { describe, expect, it } from 'vitest';++import { appendException, findMove, revisionAuthorKey } from './labels';++describe('appendException', () => {+ it('keeps the exceptions already written and adds the new one below', () => {+ expect(appendException('图表内部的间距不算', '打印样式不算')).toBe(+ '图表内部的间距不算\n打印样式不算',+ );+ });++ it('starts the list when there is nothing yet', () => {+ expect(appendException(undefined, ' 图表内部的间距不算 ')).toBe('图表内部的间距不算');+ });++ it('replaces the "no boundary given" placeholder instead of keeping it above', () => {+ expect(appendException('边界未由评审者说明', '图表内部的间距不算')).toBe('图表内部的间距不算');+ });++ it('does not add the same exception twice', () => {+ expect(appendException('图表内部的间距不算\n打印样式不算', '打印样式不算')).toBe(+ '图表内部的间距不算\n打印样式不算',+ );+ });+});++describe('findMove', () => {+ it('describes a drag upward as "now before" its new neighbour', () => {+ expect(findMove(['a', 'b', 'c', 'd'], ['c', 'a', 'b', 'd'])).toEqual({+ beforeId: 'a',+ id: 'c',+ });+ });++ it('describes a drag to the end with no neighbour after it', () => {+ expect(findMove(['a', 'b', 'c'], ['b', 'c', 'a'])).toEqual({ beforeId: null, id: 'a' });+ });++ it('reports nothing when the order did not change', () => {+ expect(findMove(['a', 'b'], ['a', 'b'])).toBeNull();+ });+});++describe('revisionAuthorKey', () => {+ it("credits the reader only with their own edits, not a teammate's", () => {+ expect(revisionAuthorKey({ byViewer: true, changedBy: 'user' })).toBe('rules.revisions.byYou');+ expect(revisionAuthorKey({ byViewer: false, changedBy: 'user' })).toBe(+ 'rules.revisions.byTeammate',+ );+ });++ it('attributes a generalization to the system', () => {+ expect(revisionAuthorKey({ byViewer: false, changedBy: 'system' })).toBe(+ 'rules.revisions.bySystem',+ );+ });+});diff --git a/src/features/MemoryRules/labels.ts b/src/features/MemoryRules/labels.tsnew file mode 100644index 00000000000..c1824a1fe67--- /dev/null+++ b/src/features/MemoryRules/labels.ts@@ -0,0 +1,97 @@+import { useTranslation } from 'react-i18next';++import type { RuleItem, RuleRevision, RuleScope } from '@/services/expertise';++export type RuleSectionKey = 'rule' | 'why' | 'how' | 'limits';++/** 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;++/**+ * 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();+ const current = trimmed && !UNSTATED_LIMITS.has(trimmed) ? trimmed : undefined;+ if (!current) return next;+ if (!next || current.split('\n').some((line) => line.trim() === next)) return current;+ return `${current}\n${next}`;+};++/** 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:')+ ? rule.rejectedReason.slice('merged-into:'.length)+ : null;++/**+ * Who made one edit. In a shared group any member can edit, so a human edit is "yours" only when+ * the reader made it.+ */+export const revisionAuthorKey = (revision: Pick<RuleRevision, 'byViewer' | 'changedBy'>) => {+ if (revision.changedBy !== 'user') return 'rules.revisions.bySystem' as const;+ return revision.byViewer+ ? ('rules.revisions.byYou' as const)+ : ('rules.revisions.byTeammate' as const);+};++/**+ * The sentence that says where a group takes effect, in the reader's language and with the+ * reader's list punctuation. Scopes with a deleted carrier still count; they just have no name.+ */+export const useScopeLabel = () => {+ const { i18n, t } = useTranslation('memory');+ const format = new Intl.ListFormat(i18n.language, { style: 'narrow', type: 'unit' });+ return (scopes: RuleScope[]) =>+ format.format(+ scopes.map((scope) => {+ switch (scope.kind) {+ case 'project': {+ return t('rules.scope.project', { title: scope.title ?? scope.id });+ }+ case 'agent': {+ return t('rules.scope.agent', { title: scope.title ?? scope.id });+ }+ case 'workspace': {+ return t('rules.scope.workspace');+ }+ default: {+ return t('rules.scope.user');+ }+ }+ }),+ );+};++/**+ * The single move a drag made, as "this rule now sits before that one" (or at the end). A drag+ * moves one row, so the rest of the order is implied and the request stays one id long.+ */+export const findMove = (+ previous: string[],+ next: string[],+): { beforeId: string | null; id: string } | null => {+ if (previous.length !== next.length || previous.every((id, index) => id === next[index])) {+ return null;+ }+ // The moved row is the one whose neighbours changed; try each candidate against the result.+ for (const id of next) {+ const rest = previous.filter((other) => other !== id);+ const at = next.indexOf(id);+ const rebuilt = [...rest.slice(0, at), id, ...rest.slice(at)];+ if (rebuilt.every((other, index) => other === next[index])) {+ return { beforeId: next[at + 1] ?? null, id };+ }+ }+ return null;+};diff --git a/src/features/MemoryRules/ruleMenu.tsx b/src/features/MemoryRules/ruleMenu.tsxnew file mode 100644index 00000000000..53042f0f09e--- /dev/null+++ b/src/features/MemoryRules/ruleMenu.tsx@@ -0,0 +1,94 @@+import { Icon } from '@lobehub/ui';+import type { DropdownItem } from '@lobehub/ui/base-ui';+import type { TFunction } from 'i18next';+import {+ ArchiveIcon,+ ArchiveRestoreIcon,+ ArrowRightLeftIcon,+ MergeIcon,+ PencilIcon,+} from 'lucide-react';++import type { RuleGroup, RuleItem } from '@/services/expertise';++import { mergedIntoId } from './labels';++export interface RuleHandlers {+ archive: (id: string) => void;+ edit: (id: string) => void;+ merge: (id: string) => void;+ move: (id: string, domainId: string) => void;+ restore: (id: string) => void;+}++/**+ * The same `…` menu on a row and on the document header. Moving lists every other group as a+ * submenu; merging and archiving are one click because both are reversible from the archive.+ */+export const buildRuleMenu = (+ t: TFunction<'memory'>,+ rule: RuleItem,+ groups: RuleGroup[],+ h: RuleHandlers,+): DropdownItem[] => {+ const archived = rule.status === 'retired';+ const mergedInto = mergedIntoId(rule);+ const others = groups.filter((group) => group.domain.id !== rule.domainId);+ return [+ ...(archived+ ? []+ : [+ {+ icon: <Icon icon={PencilIcon} />,+ key: 'edit',+ label: t('rules.actions.edit'),+ onClick: () => h.edit(rule.id),+ },+ ...(others.length > 0+ ? [+ {+ children: others.map((group) => ({+ key: `move-${group.domain.id}`,+ label: group.domain.title,+ onClick: () => h.move(rule.id, group.domain.id),+ })),+ icon: <Icon icon={ArrowRightLeftIcon} />,+ key: 'move',+ label: t('rules.actions.move'),+ },+ ]+ : []),+ {+ icon: <Icon icon={MergeIcon} />,+ key: 'merge',+ label: t('rules.actions.merge'),+ onClick: () => h.merge(rule.id),+ },+ { type: 'divider' as const },+ ]),+ archived+ ? // A rule merged into another lives on in that one; restoring it would count it twice,+ // so the menu says where it went instead of offering to bring it back.+ mergedInto+ ? {+ disabled: true,+ key: 'merged',+ label: t('rules.archived.mergedInto', {+ title: groups.flatMap((g) => g.rules).find((r) => r.id === mergedInto)?.title ?? '',+ }),+ }+ : {+ icon: <Icon icon={ArchiveRestoreIcon} />,+ key: 'restore',+ label: t('rules.actions.restore'),+ onClick: () => h.restore(rule.id),+ }+ : {+ danger: true,+ icon: <Icon icon={ArchiveIcon} />,+ key: 'archive',+ label: t('rules.actions.archive'),+ onClick: () => h.archive(rule.id),+ },+ ];+};diff --git a/src/features/MemoryRules/styles.ts b/src/features/MemoryRules/styles.tsnew file mode 100644index 00000000000..1f7d498da66--- /dev/null+++ b/src/features/MemoryRules/styles.ts@@ -0,0 +1,177 @@+import { createStaticStyles, cssVar } from 'antd-style';++/**+ * One sheet, Linear-style: a sticky header row, one hairline per row, group rows that run the+ * full width, and hover-only controls. The grid is shared by the header row and every rule row+ * so the columns line up without a table element.+ */+export const styles = createStaticStyles(({ css }) => ({+ body: css`+ overflow-y: auto;+ display: flex;+ flex: 1;+ `,+ cellId: css`+ padding-block-start: 2px;+ font-family: ${cssVar.fontFamilyCode};+ font-size: 12px;+ color: ${cssVar.colorTextSecondary};+ `,+ chevron: css`+ display: inline-flex;+ color: ${cssVar.colorTextTertiary};+ transition: transform 0.15s;+ `,+ chevronOpen: css`+ transform: rotate(90deg);+ `,+ divider: css`+ padding-block: 22px 6px;+ padding-inline: 8px;+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};++ font-size: 12px;+ color: ${cssVar.colorTextTertiary};+ `,+ grid: css`+ display: grid;+ grid-template-columns: 22px 40px minmax(220px, 2fr) 56px 64px 64px 28px;+ column-gap: 8px;+ align-items: start;+ `,+ hover: css`+ opacity: 0;+ transition: opacity 0.15s;+ `,+ modeBlock: css`+ color: ${cssVar.colorPrimary};+ `,+ modeBtn: css`+ cursor: pointer;+ user-select: none;++ display: inline-flex;+ gap: 4px;+ align-items: center;++ padding-block: 1px;+ padding-inline: 6px;+ border-radius: ${cssVar.borderRadiusSM};++ font-size: 12px;++ &:hover {+ background: ${cssVar.colorFillSecondary};+ }+ `,+ modeRemind: css`+ color: ${cssVar.colorTextTertiary};+ `,+ muted: css`+ font-size: 12px;+ line-height: 1.6;+ color: ${cssVar.colorTextSecondary};+ `,+ row: css`+ cursor: pointer;++ width: 100%;+ padding-block: 10px;+ padding-inline: 8px;+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};++ font-size: 13px;++ &:hover {+ background: ${cssVar.colorFillQuaternary};+ }+ `,+ rowActive: css`+ background: ${cssVar.colorFillTertiary};++ &:hover {+ background: ${cssVar.colorFillTertiary};+ }+ `,+ rowArchived: css`+ color: ${cssVar.colorTextTertiary};+ `,+ rowHover: css`+ &:hover [data-hover] {+ opacity: 1;+ }+ `,+ section: css`+ cursor: pointer;+ user-select: none;++ position: relative;++ display: flex;+ gap: 8px;+ align-items: center;++ height: 34px;+ margin-block-start: 10px;+ padding-inline: 8px;+ border-radius: ${cssVar.borderRadius};++ &:hover {+ background: ${cssVar.colorFillQuaternary};+ }++ &:hover [data-hover] {+ opacity: 1;+ }++ &:hover [data-line] {+ margin-inline-end: 64px;+ }+ `,+ sectionActions: css`+ position: absolute;+ inset-block-start: 50%;+ inset-inline-end: 8px;+ transform: translateY(-50%);+ `,+ sectionCollapsed: css`+ background: ${cssVar.colorFillQuaternary};+ `,+ sectionCount: css`+ font-size: 12px;+ font-weight: 400;+ color: ${cssVar.colorTextTertiary};+ `,+ sectionLine: css`+ flex: 1;+ height: 1px;+ margin-inline: 4px -8px;+ background: ${cssVar.colorBorderSecondary};+ `,+ sectionScope: css`+ font-size: 12px;+ color: ${cssVar.colorTextTertiary};+ `,+ sectionTitle: css`+ font-size: 13px;+ font-weight: 600;+ `,+ thead: css`+ position: sticky;+ z-index: 1;+ inset-block-start: 0;++ padding-block: 6px 8px;+ padding-inline: 8px;+ border-block-end: 1px solid ${cssVar.colorBorder};++ font-size: 12px;+ color: ${cssVar.colorTextTertiary};++ background: ${cssVar.colorBgContainer};+ `,+ title: css`+ font-weight: 500;+ text-wrap: pretty;+ `,+}));diff --git a/src/features/Settings/labs/features.ts b/src/features/Settings/labs/features.tsindex 436457ea93a..4982fe452c9 100644--- a/src/features/Settings/labs/features.ts+++ b/src/features/Settings/labs/features.ts@@ -23,6 +23,7 @@ type LabFeatureI18nKey =| 'imessage'| 'inputMarkdown'| 'integrations'+ | 'memoryRules'| 'messageTextSelectionActions'| 'oauthApps'| 'projects'@@ -66,6 +67,12 @@ export const LAB_FEATURES: LabFeatureItem[] = [searchKeywords: ['text selection', 'quote'],stage: 'alpha',},+ {+ flag: 'enableMemoryRules',+ i18nKey: 'memoryRules',+ searchKeywords: ['rules', 'memory rules', 'delivery rules', 'verifier'],+ stage: 'alpha',+ },{flag: 'enableSelfLearning',i18nKey: 'selfLearning',diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex 42524197ce7..d192982a66f 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -1133,6 +1133,15 @@ export const expertiseKeys = {]),lesson: def('expertise:lesson', (lessonId: string) => ['expertise:lesson', lessonId]),overview: def('expertise:overview', (agentId: string) => ['expertise:overview', agentId]),+ ruleRevisions: def('expertise:ruleRevisions', (lessonId: string) => [+ 'expertise:ruleRevisions',+ lessonId,+ ]),+ ruleSources: def('expertise:ruleSources', (lessonId: string) => [+ 'expertise:ruleSources',+ lessonId,+ ]),+ rules: def('expertise:rules', () => ['expertise:rules']),};export const verifyKeys = {diff --git a/src/routes/(main)/memory/_layout/Sidebar/Header/Nav.tsx b/src/routes/(main)/memory/_layout/Sidebar/Header/Nav.tsxindex 1d8908a0884..691dec4be7f 100644--- a/src/routes/(main)/memory/_layout/Sidebar/Header/Nav.tsx+++ b/src/routes/(main)/memory/_layout/Sidebar/Header/Nav.tsx@@ -6,6 +6,7 @@ import {BubblesIcon,CalendarClockIcon,HeartPulseIcon,+ ScaleIcon,SearchIcon,SignatureIcon,} from 'lucide-react';@@ -18,6 +19,8 @@ import NavItem from '@/features/NavPanel/components/NavItem';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { useActiveLocation } from '@/hooks/useActiveLocation';import { useGlobalStore } from '@/store/global';+import { useUserStore } from '@/store/user';+import { labPreferSelectors } from '@/store/user/slices/preference/selectors/labPrefer';import { isModifierClick } from '@/utils/navigation';interface Item {@@ -34,6 +37,7 @@ enum MemoryTabKey {Home = 'home',Identities = 'identities',Preferences = 'preferences',+ Rules = 'rules',}const useActiveTabKey = () => {@@ -47,11 +51,13 @@ const Nav = memo(() => {const navigate = useWorkspaceAwareNavigate();const { t } = useTranslation('memory');const toggleCommandMenu = useGlobalStore((s) => s.toggleCommandMenu);+ const enableRules = useUserStore(labPreferSelectors.enableMemoryRules);/**- * Groups separated by space rather than rules: what the whole section is (home), who the- * person is (identity, preferences), and what is going on around them (contexts, activities).- * Search sits above all of them because it is an action, not a destination.+ * Four groups, separated by space rather than rules: what the whole section is (home), what it+ * requires of a delivery (rules), who the person is (identity, preferences), and what is+ * going on around them (contexts, activities). Search sits above all of them because it is an+ * action, not a destination.*/const groups: Item[][] = useMemo(() => [@@ -73,6 +79,20 @@ const Nav = memo(() => {url: '/memory',},],+ // Rules are still an alpha lab: the group disappears with the flag rather than sitting+ // there disabled, so the sidebar of everyone else reads exactly as before.+ ...(enableRules+ ? [+ [+ {+ icon: ScaleIcon,+ key: MemoryTabKey.Rules,+ title: t('tab.rules'),+ url: '/memory/rules',+ },+ ],+ ]+ : []),[{icon: SignatureIcon,@@ -102,7 +122,7 @@ const Nav = memo(() => {},],],- [t, toggleCommandMenu],+ [t, toggleCommandMenu, enableRules],);return (diff --git a/src/routes/(main)/memory/rules/index.tsx b/src/routes/(main)/memory/rules/index.tsxnew file mode 100644index 00000000000..d85b8890d72--- /dev/null+++ b/src/routes/(main)/memory/rules/index.tsx@@ -0,0 +1 @@+export { default } from '@/features/MemoryRules';diff --git a/src/services/expertise.ts b/src/services/expertise.tsindex 47a0768104d..70918de3ba1 100644--- a/src/services/expertise.ts+++ b/src/services/expertise.ts@@ -15,9 +15,71 @@ export type ExpertiseDomainDraft = Awaited<ReturnType<typeof lambdaClient.expertise.draftDomain.mutate>>;+export type RulesOverview = Awaited<ReturnType<typeof lambdaClient.expertise.listRules.query>>;+export type RuleGroup = RulesOverview['groups'][number];+export type RuleItem = RuleGroup['rules'][number];+export type RuleScope = RuleGroup['scopes'][number];+export type RuleSource = Awaited<+ ReturnType<typeof lambdaClient.expertise.ruleSources.query>+>[number];+export type RuleRevision = Awaited<+ ReturnType<typeof lambdaClient.expertise.ruleRevisions.query>+>[number];+export type RuleDraft = Awaited<ReturnType<typeof lambdaClient.expertise.draftRule.mutate>>;+export type RuleGroupDraft = Awaited<+ ReturnType<typeof lambdaClient.expertise.draftRuleGroup.mutate>+>;+export type CreateRuleInput = Parameters<typeof lambdaClient.expertise.createRule.mutate>[0];+export type UpdateRuleInput = Omit<+ Parameters<typeof lambdaClient.expertise.updateRule.mutate>[0],+ 'lessonId'+>;+class ExpertiseService {listByAgent = async (agentId: string) => lambdaClient.expertise.listByAgent.query({ agentId });+ listRules = async () => lambdaClient.expertise.listRules.query();++ ruleSources = async (lessonId: string) => lambdaClient.expertise.ruleSources.query({ lessonId });++ ruleRevisions = async (lessonId: string) =>+ lambdaClient.expertise.ruleRevisions.query({ lessonId });++ draftRule = async (input: {+ brief: string;+ groups: { gate: string; id: string; title: string }[];+ }) => lambdaClient.expertise.draftRule.mutate(input);++ draftRuleGroup = async (brief: string) => lambdaClient.expertise.draftRuleGroup.mutate({ brief });++ createRule = async (input: CreateRuleInput) => lambdaClient.expertise.createRule.mutate(input);++ updateRule = async (lessonId: string, patch: UpdateRuleInput) =>+ lambdaClient.expertise.updateRule.mutate({ lessonId, ...patch });++ reorderRule = async (domainId: string, lessonId: string, beforeId: string | null) =>+ lambdaClient.expertise.reorderRule.mutate({ beforeId, domainId, lessonId });++ moveRule = async (lessonId: string, domainId: string) =>+ lambdaClient.expertise.moveRule.mutate({ domainId, lessonId });++ mergeRules = async (fromId: string, intoId: string) =>+ lambdaClient.expertise.mergeRules.mutate({ fromId, intoId });++ archiveRule = async (lessonId: string) =>+ lambdaClient.expertise.retireLesson.mutate({ lessonId });++ restoreRule = async (lessonId: string) =>+ lambdaClient.expertise.restoreLesson.mutate({ lessonId });++ createRuleGroup = async (input: { gate: string; outOfScope?: string; title: string }) =>+ lambdaClient.expertise.createRuleGroup.mutate(input);++ updateRuleGroup = async (+ domainId: string,+ patch: { gate?: string; outOfScope?: string | null; title?: string },+ ) => lambdaClient.expertise.updateRuleGroup.mutate({ domainId, ...patch });+getDomain = async (domainId: string) => lambdaClient.expertise.getDomain.query({ domainId });getLesson = async (lessonId: string) => lambdaClient.expertise.getLesson.query({ lessonId });diff --git a/src/spa/router/desktopRouter.shared.tsx b/src/spa/router/desktopRouter.shared.tsxindex 02977957cef..57f9b9f0f6e 100644--- a/src/spa/router/desktopRouter.shared.tsx+++ b/src/spa/router/desktopRouter.shared.tsx@@ -12,6 +12,7 @@ import {LayoutPanelTopIcon,LibraryBigIcon,Mic2,+ Scale,Settings,ShapesIcon,SquarePlay,@@ -780,6 +781,17 @@ export const sharedMainAreaChildren: RouteObject[] = [},path: 'preferences',},+ {+ element: dynamicElement(+ () => import('@/routes/(main)/memory/rules'),+ 'Desktop > Memory > Rules',+ ),+ handle: {+ // Same icon the memory sidebar uses, so a desktop tab and the nav item agree.+ meta: routeMeta({ icon: Scale, titleKey: 'navigation.memoryRules' }),+ },+ path: 'rules',+ },{element: dynamicElement(() => import('@/routes/(main)/memory/activities'),diff --git a/src/store/user/slices/preference/selectors/labPrefer.ts b/src/store/user/slices/preference/selectors/labPrefer.tsindex e6cac9f6c60..c266ab95df8 100644--- a/src/store/user/slices/preference/selectors/labPrefer.ts+++ b/src/store/user/slices/preference/selectors/labPrefer.ts@@ -21,6 +21,7 @@ export const labPreferSelectors = {enableIntegrations: (s: UserState): boolean => s.preference.lab?.enableIntegrations ?? false,enableInputMarkdown: (s: UserState): boolean =>s.preference.lab?.enableInputMarkdown ?? DEFAULT_PREFERENCE.lab?.enableInputMarkdown ?? true,+ enableMemoryRules: (s: UserState): boolean => s.preference.lab?.enableMemoryRules ?? false,enableMessageTextSelectionActions: (s: UserState): boolean =>s.preference.lab?.enableMessageTextSelectionActions ??DEFAULT_PREFERENCE.lab?.enableMessageTextSelectionActions ??